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 PetscDefined(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: /*@
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: /*@
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: /*@
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: /*@
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;
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 (PetscInt 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];
1097: PetscCall(DMPlexPointLocalRead(dmCell, cells[0], cellgeom, &cg));
1098: PetscCall(DMPlexPointLocalRead(dm, cells[0], x, &cx));
1099: PetscCall(DMPlexPointLocalRead(dmGrad, cells[0], grad, &cgrad));
1100: PetscCall(DMPlexPointLocalFieldRef(dm, cells[1], field, x, &xG));
1101: DMPlex_WaxpyD_Internal(dim, -1, cg->centroid, fg->centroid, dx);
1102: for (PetscInt d = 0; d < pdim; ++d) fx[d] = cx[d] + DMPlex_DotD_Internal(dim, &cgrad[d * dim], dx);
1103: PetscCall((*func)(time, fg->centroid, fg->normal, fx, xG, ctx));
1104: } else {
1105: PetscScalar *xI;
1106: PetscScalar *xG;
1108: PetscCall(DMPlexPointLocalRead(dm, cells[0], x, &xI));
1109: PetscCall(DMPlexPointLocalFieldRef(dm, cells[1], field, x, &xG));
1110: ierru = (*func)(time, fg->centroid, fg->normal, xI, xG, ctx);
1111: if (ierru) {
1112: PetscCall(ISRestoreIndices(faceIS, &faces));
1113: PetscCall(ISDestroy(&faceIS));
1114: goto cleanup;
1115: }
1116: }
1117: }
1118: PetscCall(ISRestoreIndices(faceIS, &faces));
1119: PetscCall(ISDestroy(&faceIS));
1120: }
1121: cleanup:
1122: PetscCall(VecRestoreArray(locX, &x));
1123: if (Grad) {
1124: PetscCall(DMRestoreWorkArray(dm, pdim, MPIU_SCALAR, &fx));
1125: PetscCall(VecRestoreArrayRead(Grad, &grad));
1126: }
1127: if (cellGeometry) PetscCall(VecRestoreArrayRead(cellGeometry, &cellgeom));
1128: PetscCall(VecRestoreArrayRead(faceGeometry, &facegeom));
1129: PetscCall(ierru);
1130: PetscFunctionReturn(PETSC_SUCCESS);
1131: }
1133: static PetscErrorCode zero(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, PetscCtx ctx)
1134: {
1135: for (PetscInt c = 0; c < Nc; ++c) u[c] = 0.0;
1136: return PETSC_SUCCESS;
1137: }
1139: PetscErrorCode DMPlexInsertBoundaryValues_Plex(DM dm, PetscBool insertEssential, Vec locX, PetscReal time, Vec faceGeomFVM, Vec cellGeomFVM, Vec gradFVM)
1140: {
1141: PetscObject isZero;
1142: PetscDS prob;
1143: PetscInt numBd;
1145: PetscFunctionBegin;
1146: PetscCall(DMGetDS(dm, &prob));
1147: PetscCall(PetscDSGetNumBoundary(prob, &numBd));
1148: PetscCall(PetscObjectQuery((PetscObject)locX, "__Vec_bc_zero__", &isZero));
1149: PetscCall(PetscDSUpdateBoundaryLabels(prob, dm));
1150: for (PetscInt b = 0; b < numBd; ++b) {
1151: PetscWeakForm wf;
1152: DMBoundaryConditionType type;
1153: const char *name;
1154: DMLabel label;
1155: PetscInt field, Nc;
1156: const PetscInt *comps;
1157: PetscObject obj;
1158: PetscClassId id;
1159: PetscVoidFn *bvfunc;
1160: PetscInt numids;
1161: const PetscInt *ids;
1162: void *ctx;
1164: PetscCall(PetscDSGetBoundary(prob, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
1165: if (insertEssential != (type & DM_BC_ESSENTIAL)) continue;
1166: PetscCall(DMGetField(dm, field, NULL, &obj));
1167: PetscCall(PetscObjectGetClassId(obj, &id));
1168: if (id == PETSCFE_CLASSID) {
1169: switch (type) {
1170: /* for FEM, there is no insertion to be done for non-essential boundary conditions */
1171: case DM_BC_ESSENTIAL: {
1172: PetscSimplePointFn *func = (PetscSimplePointFn *)bvfunc;
1174: if (isZero) func = zero;
1175: PetscCall(DMPlexLabelAddCells(dm, label));
1176: PetscCall(DMPlexInsertBoundaryValuesEssential(dm, time, field, Nc, comps, label, numids, ids, func, ctx, locX));
1177: PetscCall(DMPlexLabelClearCells(dm, label));
1178: } break;
1179: case DM_BC_ESSENTIAL_FIELD: {
1180: PetscPointFn *func = (PetscPointFn *)bvfunc;
1182: PetscCall(DMPlexLabelAddCells(dm, label));
1183: PetscCall(DMPlexInsertBoundaryValuesEssentialField(dm, time, locX, field, Nc, comps, label, numids, ids, func, ctx, locX));
1184: PetscCall(DMPlexLabelClearCells(dm, label));
1185: } break;
1186: default:
1187: break;
1188: }
1189: } else if (id == PETSCFV_CLASSID) {
1190: {
1191: PetscErrorCode (*func)(PetscReal, const PetscReal *, const PetscReal *, const PetscScalar *, PetscScalar *, void *) = (PetscErrorCode (*)(PetscReal, const PetscReal *, const PetscReal *, const PetscScalar *, PetscScalar *, void *))bvfunc;
1193: if (!faceGeomFVM) continue;
1194: PetscCall(DMPlexInsertBoundaryValuesRiemann(dm, time, faceGeomFVM, cellGeomFVM, gradFVM, field, Nc, comps, label, numids, ids, func, ctx, locX));
1195: }
1196: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1197: }
1198: PetscFunctionReturn(PETSC_SUCCESS);
1199: }
1201: PetscErrorCode DMPlexInsertTimeDerivativeBoundaryValues_Plex(DM dm, PetscBool insertEssential, Vec locX, PetscReal time, Vec faceGeomFVM, Vec cellGeomFVM, Vec gradFVM)
1202: {
1203: PetscObject isZero;
1204: PetscDS prob;
1205: PetscInt numBd;
1207: PetscFunctionBegin;
1208: if (!locX) PetscFunctionReturn(PETSC_SUCCESS);
1209: PetscCall(DMGetDS(dm, &prob));
1210: PetscCall(PetscDSGetNumBoundary(prob, &numBd));
1211: PetscCall(PetscObjectQuery((PetscObject)locX, "__Vec_bc_zero__", &isZero));
1212: for (PetscInt b = 0; b < numBd; ++b) {
1213: PetscWeakForm wf;
1214: DMBoundaryConditionType type;
1215: const char *name;
1216: DMLabel label;
1217: PetscInt field, Nc;
1218: const PetscInt *comps;
1219: PetscObject obj;
1220: PetscClassId id;
1221: PetscInt numids;
1222: const PetscInt *ids;
1223: PetscVoidFn *bvfunc;
1224: void *ctx;
1226: PetscCall(PetscDSGetBoundary(prob, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, NULL, &bvfunc, &ctx));
1227: if (insertEssential != (type & DM_BC_ESSENTIAL)) continue;
1228: PetscCall(DMGetField(dm, field, NULL, &obj));
1229: PetscCall(PetscObjectGetClassId(obj, &id));
1230: if (id == PETSCFE_CLASSID) {
1231: switch (type) {
1232: /* for FEM, there is no insertion to be done for non-essential boundary conditions */
1233: case DM_BC_ESSENTIAL: {
1234: PetscSimplePointFn *func_t = (PetscSimplePointFn *)bvfunc;
1236: if (isZero) func_t = zero;
1237: PetscCall(DMPlexLabelAddCells(dm, label));
1238: PetscCall(DMPlexInsertBoundaryValuesEssential(dm, time, field, Nc, comps, label, numids, ids, func_t, ctx, locX));
1239: PetscCall(DMPlexLabelClearCells(dm, label));
1240: } break;
1241: case DM_BC_ESSENTIAL_FIELD: {
1242: PetscPointFn *func_t = (PetscPointFn *)bvfunc;
1244: PetscCall(DMPlexLabelAddCells(dm, label));
1245: PetscCall(DMPlexInsertBoundaryValuesEssentialField(dm, time, locX, field, Nc, comps, label, numids, ids, func_t, ctx, locX));
1246: PetscCall(DMPlexLabelClearCells(dm, label));
1247: } break;
1248: default:
1249: break;
1250: }
1251: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1252: }
1253: PetscFunctionReturn(PETSC_SUCCESS);
1254: }
1256: PetscErrorCode DMPlexInsertBounds_Plex(DM dm, PetscBool lower, PetscReal time, Vec locB)
1257: {
1258: PetscDS ds;
1259: PetscInt numBd;
1261: PetscFunctionBegin;
1262: PetscCall(DMGetDS(dm, &ds));
1263: PetscCall(PetscDSGetNumBoundary(ds, &numBd));
1264: PetscCall(PetscDSUpdateBoundaryLabels(ds, dm));
1265: for (PetscInt b = 0; b < numBd; ++b) {
1266: PetscWeakForm wf;
1267: DMBoundaryConditionType type;
1268: const char *name;
1269: DMLabel label;
1270: PetscInt numids;
1271: const PetscInt *ids;
1272: PetscInt field, Nc;
1273: const PetscInt *comps;
1274: PetscVoidFn *bvfunc;
1275: void *ctx;
1277: PetscCall(PetscDSGetBoundary(ds, b, &wf, &type, &name, &label, &numids, &ids, &field, &Nc, &comps, &bvfunc, NULL, &ctx));
1278: if (lower && type != DM_BC_LOWER_BOUND) continue;
1279: if (!lower && type != DM_BC_UPPER_BOUND) continue;
1280: PetscCall(DMPlexLabelAddCells(dm, label));
1281: {
1282: PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal x[], PetscInt, PetscScalar *u, PetscCtx ctx);
1283: void **ctxs;
1284: PetscInt Nf;
1286: PetscCall(DMGetNumFields(dm, &Nf));
1287: PetscCall(PetscCalloc2(Nf, &funcs, Nf, &ctxs));
1288: funcs[field] = (PetscSimplePointFn *)bvfunc;
1289: ctxs[field] = ctx;
1290: PetscCall(DMProjectFunctionLabelLocal(dm, time, label, numids, ids, Nc, comps, funcs, ctxs, INSERT_ALL_VALUES, locB));
1291: PetscCall(PetscFree2(funcs, ctxs));
1292: }
1293: PetscCall(DMPlexLabelClearCells(dm, label));
1294: }
1295: PetscFunctionReturn(PETSC_SUCCESS);
1296: }
1298: /*@
1299: DMPlexInsertBoundaryValues - Puts coefficients which represent boundary values into the local solution vector
1301: Not Collective
1303: Input Parameters:
1304: + dm - The `DM`
1305: . insertEssential - Should I insert essential (e.g. Dirichlet) or inessential (e.g. Neumann) boundary conditions
1306: . time - The time
1307: . faceGeomFVM - Face geometry data for FV discretizations
1308: . cellGeomFVM - Cell geometry data for FV discretizations
1309: - gradFVM - Gradient reconstruction data for FV discretizations
1311: Output Parameter:
1312: . locX - Solution updated with boundary values
1314: Level: intermediate
1316: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectFunctionLabelLocal()`, `DMAddBoundary()`
1317: @*/
1318: PetscErrorCode DMPlexInsertBoundaryValues(DM dm, PetscBool insertEssential, Vec locX, PetscReal time, Vec faceGeomFVM, Vec cellGeomFVM, Vec gradFVM)
1319: {
1320: PetscFunctionBegin;
1326: PetscTryMethod(dm, "DMPlexInsertBoundaryValues_C", (DM, PetscBool, Vec, PetscReal, Vec, Vec, Vec), (dm, insertEssential, locX, time, faceGeomFVM, cellGeomFVM, gradFVM));
1327: PetscFunctionReturn(PETSC_SUCCESS);
1328: }
1330: /*@
1331: DMPlexInsertTimeDerivativeBoundaryValues - Puts coefficients which represent boundary values of the time derivative into the local solution vector
1333: Input Parameters:
1334: + dm - The `DM`
1335: . insertEssential - Should I insert essential (e.g. Dirichlet) or inessential (e.g. Neumann) boundary conditions
1336: . time - The time
1337: . faceGeomFVM - Face geometry data for FV discretizations
1338: . cellGeomFVM - Cell geometry data for FV discretizations
1339: - gradFVM - Gradient reconstruction data for FV discretizations
1341: Output Parameter:
1342: . locX_t - Solution updated with boundary values
1344: Level: developer
1346: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectFunctionLabelLocal()`
1347: @*/
1348: PetscErrorCode DMPlexInsertTimeDerivativeBoundaryValues(DM dm, PetscBool insertEssential, Vec locX_t, PetscReal time, Vec faceGeomFVM, Vec cellGeomFVM, Vec gradFVM)
1349: {
1350: PetscFunctionBegin;
1356: PetscTryMethod(dm, "DMPlexInsertTimeDerivativeBoundaryValues_C", (DM, PetscBool, Vec, PetscReal, Vec, Vec, Vec), (dm, insertEssential, locX_t, time, faceGeomFVM, cellGeomFVM, gradFVM));
1357: PetscFunctionReturn(PETSC_SUCCESS);
1358: }
1360: /*@
1361: DMPlexInsertBounds - Puts coefficients which represent solution bounds into the local bounds vector
1363: Not Collective
1365: Input Parameters:
1366: + dm - The `DM`
1367: . lower - If `PETSC_TRUE` use `DM_BC_LOWER_BOUND` conditions, otherwise use `DM_BC_UPPER_BOUND`
1368: - time - The time
1370: Output Parameter:
1371: . locB - Bounds vector updated with new bounds
1373: Level: intermediate
1375: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectFunctionLabelLocal()`, `PetscDSAddBoundary()`
1376: @*/
1377: PetscErrorCode DMPlexInsertBounds(DM dm, PetscBool lower, PetscReal time, Vec locB)
1378: {
1379: PetscFunctionBegin;
1382: PetscTryMethod(dm, "DMPlexInsertBounds_C", (DM, PetscBool, PetscReal, Vec), (dm, lower, time, locB));
1383: PetscFunctionReturn(PETSC_SUCCESS);
1384: }
1386: /*@
1387: DMPlexInsertBoundaryValuesFVM - Reconstruct cell gradients and insert non-essential (e.g. outflow) boundary values
1388: into a local finite-volume solution vector.
1390: Collective
1392: Input Parameters:
1393: + dm - the `DMPLEX`
1394: . fv - the `PetscFV` discretization
1395: . locX - the local solution vector; updated with non-essential boundary values
1396: - time - the current time
1398: Output Parameter:
1399: . locGradient - if non-`NULL`, the local vector holding the reconstructed cell gradients
1401: Level: developer
1403: Note:
1404: The caller receives ownership of `*locGradient` via `DMGetLocalVector()` and must return it with
1405: `DMRestoreLocalVector()`.
1407: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `PetscFV`, `DMPlexInsertBoundaryValues()`, `DMPlexReconstructGradientsFVM()`
1408: @*/
1409: PetscErrorCode DMPlexInsertBoundaryValuesFVM(DM dm, PetscFV fv, Vec locX, PetscReal time, Vec *locGradient)
1410: {
1411: DM dmGrad;
1412: Vec cellGeometryFVM, faceGeometryFVM, locGrad = NULL;
1414: PetscFunctionBegin;
1418: if (locGradient) {
1419: PetscAssertPointer(locGradient, 5);
1420: *locGradient = NULL;
1421: }
1422: PetscCall(DMPlexGetGeometryFVM(dm, &faceGeometryFVM, &cellGeometryFVM, NULL));
1423: /* Reconstruct and limit cell gradients */
1424: PetscCall(DMPlexGetGradientDM(dm, fv, &dmGrad));
1425: if (dmGrad) {
1426: Vec grad;
1427: PetscInt fStart, fEnd;
1429: PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
1430: PetscCall(DMGetGlobalVector(dmGrad, &grad));
1431: PetscCall(DMPlexReconstructGradients_Internal(dm, fv, fStart, fEnd, faceGeometryFVM, cellGeometryFVM, locX, grad));
1432: /* Communicate gradient values */
1433: PetscCall(DMGetLocalVector(dmGrad, &locGrad));
1434: PetscCall(DMGlobalToLocalBegin(dmGrad, grad, INSERT_VALUES, locGrad));
1435: PetscCall(DMGlobalToLocalEnd(dmGrad, grad, INSERT_VALUES, locGrad));
1436: PetscCall(DMRestoreGlobalVector(dmGrad, &grad));
1437: }
1438: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_FALSE, locX, time, faceGeometryFVM, cellGeometryFVM, locGrad));
1439: if (locGradient) *locGradient = locGrad;
1440: else if (locGrad) PetscCall(DMRestoreLocalVector(dmGrad, &locGrad));
1441: PetscFunctionReturn(PETSC_SUCCESS);
1442: }
1444: PetscErrorCode DMComputeL2Diff_Plex(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
1445: {
1446: Vec localX;
1448: PetscFunctionBegin;
1449: PetscCall(DMGetLocalVector(dm, &localX));
1450: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_TRUE, localX, time, NULL, NULL, NULL));
1451: PetscCall(DMGlobalToLocalBegin(dm, X, INSERT_VALUES, localX));
1452: PetscCall(DMGlobalToLocalEnd(dm, X, INSERT_VALUES, localX));
1453: PetscCall(DMPlexComputeL2DiffLocal(dm, time, funcs, ctxs, localX, diff));
1454: PetscCall(DMRestoreLocalVector(dm, &localX));
1455: PetscFunctionReturn(PETSC_SUCCESS);
1456: }
1458: /*@
1459: DMPlexComputeL2DiffLocal - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.
1461: Collective
1463: Input Parameters:
1464: + dm - The `DM`
1465: . time - The time
1466: . funcs - The functions to evaluate for each field component
1467: . ctxs - Optional array of contexts to pass to each function, or `NULL`.
1468: - localX - The coefficient vector u_h, a local vector
1470: Output Parameter:
1471: . diff - The diff ||u - u_h||_2
1473: Level: developer
1475: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectFunction()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
1476: @*/
1477: PetscErrorCode DMPlexComputeL2DiffLocal(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec localX, PetscReal *diff)
1478: {
1479: const PetscInt debug = ((DM_Plex *)dm->data)->printL2;
1480: DM tdm;
1481: Vec tv;
1482: PetscSection section;
1483: PetscQuadrature quad;
1484: PetscFEGeom fegeom;
1485: PetscScalar *funcVal, *interpolant;
1486: PetscReal *coords, *gcoords;
1487: const PetscReal *quadWeights;
1488: PetscInt dim, coordDim, numFields, numComponents = 0, qNc, Nq, cellHeight, cStart, cEnd, c, field, fieldOffset;
1489: PetscBool transform;
1491: PetscFunctionBegin;
1492: *diff = 0.0;
1493: PetscCall(DMGetDimension(dm, &dim));
1494: PetscCall(DMGetCoordinateDim(dm, &coordDim));
1495: fegeom.dimEmbed = coordDim;
1496: PetscCall(DMGetLocalSection(dm, §ion));
1497: PetscCall(PetscSectionGetNumFields(section, &numFields));
1498: PetscCall(DMGetBasisTransformDM_Internal(dm, &tdm));
1499: PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
1500: PetscCall(DMHasBasisTransform(dm, &transform));
1501: PetscCheck(numFields, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of fields is zero!");
1502: for (field = 0; field < numFields; ++field) {
1503: PetscObject obj;
1504: PetscClassId id;
1505: PetscInt Nc;
1507: PetscCall(DMGetField(dm, field, NULL, &obj));
1508: PetscCall(PetscObjectGetClassId(obj, &id));
1509: if (id == PETSCFE_CLASSID) {
1510: PetscFE fe = (PetscFE)obj;
1512: PetscCall(PetscFEGetQuadrature(fe, &quad));
1513: PetscCall(PetscFEGetNumComponents(fe, &Nc));
1514: } else if (id == PETSCFV_CLASSID) {
1515: PetscFV fv = (PetscFV)obj;
1517: PetscCall(PetscFVGetQuadrature(fv, &quad));
1518: PetscCall(PetscFVGetNumComponents(fv, &Nc));
1519: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1520: numComponents += Nc;
1521: }
1522: PetscCall(PetscQuadratureGetData(quad, NULL, &qNc, &Nq, NULL, &quadWeights));
1523: PetscCheck(!(qNc != 1) || !(qNc != numComponents), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Quadrature components %" PetscInt_FMT " != %" PetscInt_FMT " field components", qNc, numComponents);
1524: PetscCall(PetscMalloc6(numComponents, &funcVal, numComponents, &interpolant, coordDim * (Nq + 1), &coords, Nq, &fegeom.detJ, coordDim * coordDim * Nq, &fegeom.J, coordDim * coordDim * Nq, &fegeom.invJ));
1525: PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
1526: PetscCall(DMPlexGetSimplexOrBoxCells(dm, cellHeight, &cStart, &cEnd));
1527: for (c = cStart; c < cEnd; ++c) {
1528: PetscScalar *x = NULL;
1529: PetscReal elemDiff = 0.0;
1530: PetscInt qc = 0;
1532: PetscCall(DMPlexComputeCellGeometryFEM(dm, c, quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
1533: PetscCall(DMPlexVecGetOrientedClosure(dm, NULL, PETSC_FALSE, localX, c, 0, NULL, &x));
1535: for (field = 0, fieldOffset = 0; field < numFields; ++field) {
1536: PetscObject obj;
1537: PetscClassId id;
1538: void *const ctx = ctxs ? ctxs[field] : NULL;
1539: PetscInt Nb, Nc, q, fc;
1541: PetscCall(DMGetField(dm, field, NULL, &obj));
1542: PetscCall(PetscObjectGetClassId(obj, &id));
1543: if (id == PETSCFE_CLASSID) {
1544: PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
1545: PetscCall(PetscFEGetDimension((PetscFE)obj, &Nb));
1546: } else if (id == PETSCFV_CLASSID) {
1547: PetscCall(PetscFVGetNumComponents((PetscFV)obj, &Nc));
1548: Nb = 1;
1549: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1550: if (debug) {
1551: char title[1024];
1552: PetscCall(PetscSNPrintf(title, 1023, "Solution for Field %" PetscInt_FMT, field));
1553: PetscCall(DMPrintCellVector(c, title, Nb, &x[fieldOffset]));
1554: }
1555: for (q = 0; q < Nq; ++q) {
1556: PetscFEGeom qgeom;
1557: PetscErrorCode ierr;
1559: qgeom.dimEmbed = fegeom.dimEmbed;
1560: qgeom.J = &fegeom.J[q * coordDim * coordDim];
1561: qgeom.invJ = &fegeom.invJ[q * coordDim * coordDim];
1562: qgeom.detJ = &fegeom.detJ[q];
1563: 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);
1564: if (transform) {
1565: gcoords = &coords[coordDim * Nq];
1566: PetscCall(DMPlexBasisTransformApplyReal_Internal(dm, &coords[coordDim * q], PETSC_TRUE, coordDim, &coords[coordDim * q], gcoords, dm->transformCtx));
1567: } else {
1568: gcoords = &coords[coordDim * q];
1569: }
1570: PetscCall(PetscArrayzero(funcVal, Nc));
1571: ierr = (*funcs[field])(coordDim, time, gcoords, Nc, funcVal, ctx);
1572: if (ierr) {
1573: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, c, NULL, &x));
1574: PetscCall(DMRestoreLocalVector(dm, &localX));
1575: PetscCall(PetscFree6(funcVal, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
1576: }
1577: if (transform) PetscCall(DMPlexBasisTransformApply_Internal(dm, &coords[coordDim * q], PETSC_FALSE, Nc, funcVal, funcVal, dm->transformCtx));
1578: if (id == PETSCFE_CLASSID) PetscCall(PetscFEInterpolate_Static((PetscFE)obj, &x[fieldOffset], &qgeom, q, interpolant));
1579: else if (id == PETSCFV_CLASSID) PetscCall(PetscFVInterpolate_Static((PetscFV)obj, &x[fieldOffset], q, interpolant));
1580: else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1581: for (fc = 0; fc < Nc; ++fc) {
1582: const PetscReal wt = quadWeights[q * qNc + (qNc == 1 ? 0 : qc + fc)];
1583: if (debug)
1584: 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),
1585: (double)(PetscSqr(PetscRealPart(interpolant[fc] - funcVal[fc])) * wt * fegeom.detJ[q]), (double)PetscRealPart(interpolant[fc]), (double)PetscRealPart(funcVal[fc])));
1586: elemDiff += PetscSqr(PetscRealPart(interpolant[fc] - funcVal[fc])) * wt * fegeom.detJ[q];
1587: }
1588: }
1589: fieldOffset += Nb;
1590: qc += Nc;
1591: }
1592: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, c, NULL, &x));
1593: if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, " elem %" PetscInt_FMT " diff %g\n", c, (double)elemDiff));
1594: *diff += elemDiff;
1595: }
1596: PetscCall(PetscFree6(funcVal, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
1597: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, diff, 1, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)dm)));
1598: *diff = PetscSqrtReal(*diff);
1599: PetscFunctionReturn(PETSC_SUCCESS);
1600: }
1602: 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)
1603: {
1604: const PetscInt debug = ((DM_Plex *)dm->data)->printL2;
1605: DM tdm;
1606: PetscSection section;
1607: PetscQuadrature quad;
1608: Vec localX, tv;
1609: PetscScalar *funcVal, *interpolant;
1610: const PetscReal *quadWeights;
1611: PetscFEGeom fegeom;
1612: PetscReal *coords, *gcoords;
1613: PetscInt dim, coordDim, qNc = 0, Nq = 0, numFields, numComponents = 0, cStart, cEnd, c, field, fieldOffset;
1614: PetscBool transform;
1616: PetscFunctionBegin;
1617: *diff = 0.0;
1618: PetscCall(DMGetDimension(dm, &dim));
1619: PetscCall(DMGetCoordinateDim(dm, &coordDim));
1620: fegeom.dimEmbed = coordDim;
1621: PetscCall(DMGetLocalSection(dm, §ion));
1622: PetscCall(PetscSectionGetNumFields(section, &numFields));
1623: PetscCall(DMGetLocalVector(dm, &localX));
1624: PetscCall(DMGlobalToLocalBegin(dm, X, INSERT_VALUES, localX));
1625: PetscCall(DMGlobalToLocalEnd(dm, X, INSERT_VALUES, localX));
1626: PetscCall(DMGetBasisTransformDM_Internal(dm, &tdm));
1627: PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
1628: PetscCall(DMHasBasisTransform(dm, &transform));
1629: for (field = 0; field < numFields; ++field) {
1630: PetscFE fe;
1631: PetscInt Nc;
1633: PetscCall(DMGetField(dm, field, NULL, (PetscObject *)&fe));
1634: PetscCall(PetscFEGetQuadrature(fe, &quad));
1635: PetscCall(PetscFEGetNumComponents(fe, &Nc));
1636: numComponents += Nc;
1637: }
1638: PetscCall(PetscQuadratureGetData(quad, NULL, &qNc, &Nq, NULL, &quadWeights));
1639: PetscCheck(!(qNc != 1) || !(qNc != numComponents), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Quadrature components %" PetscInt_FMT " != %" PetscInt_FMT " field components", qNc, numComponents);
1640: /* PetscCall(DMProjectFunctionLocal(dm, fe, funcs, INSERT_BC_VALUES, localX)); */
1641: PetscCall(PetscMalloc6(numComponents, &funcVal, coordDim * (Nq + 1), &coords, coordDim * coordDim * Nq, &fegeom.J, coordDim * coordDim * Nq, &fegeom.invJ, numComponents * coordDim, &interpolant, Nq, &fegeom.detJ));
1642: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
1643: for (c = cStart; c < cEnd; ++c) {
1644: PetscScalar *x = NULL;
1645: PetscReal elemDiff = 0.0;
1646: PetscInt qc = 0;
1648: PetscCall(DMPlexComputeCellGeometryFEM(dm, c, quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
1649: PetscCall(DMPlexVecGetOrientedClosure(dm, NULL, PETSC_FALSE, localX, c, 0, NULL, &x));
1651: for (field = 0, fieldOffset = 0; field < numFields; ++field) {
1652: PetscFE fe;
1653: void *const ctx = ctxs ? ctxs[field] : NULL;
1654: PetscInt Nb, Nc, q, fc;
1656: PetscCall(DMGetField(dm, field, NULL, (PetscObject *)&fe));
1657: PetscCall(PetscFEGetDimension(fe, &Nb));
1658: PetscCall(PetscFEGetNumComponents(fe, &Nc));
1659: if (debug) {
1660: char title[1024];
1661: PetscCall(PetscSNPrintf(title, 1023, "Solution for Field %" PetscInt_FMT, field));
1662: PetscCall(DMPrintCellVector(c, title, Nb, &x[fieldOffset]));
1663: }
1664: for (q = 0; q < Nq; ++q) {
1665: PetscFEGeom qgeom;
1666: PetscErrorCode ierr;
1668: qgeom.dimEmbed = fegeom.dimEmbed;
1669: qgeom.J = &fegeom.J[q * coordDim * coordDim];
1670: qgeom.invJ = &fegeom.invJ[q * coordDim * coordDim];
1671: qgeom.detJ = &fegeom.detJ[q];
1672: 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);
1673: if (transform) {
1674: gcoords = &coords[coordDim * Nq];
1675: PetscCall(DMPlexBasisTransformApplyReal_Internal(dm, &coords[coordDim * q], PETSC_TRUE, coordDim, &coords[coordDim * q], gcoords, dm->transformCtx));
1676: } else {
1677: gcoords = &coords[coordDim * q];
1678: }
1679: PetscCall(PetscArrayzero(funcVal, Nc));
1680: ierr = (*funcs[field])(coordDim, time, gcoords, n, Nc, funcVal, ctx);
1681: if (ierr) {
1682: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, c, NULL, &x));
1683: PetscCall(DMRestoreLocalVector(dm, &localX));
1684: PetscCall(PetscFree6(funcVal, coords, fegeom.J, fegeom.invJ, interpolant, fegeom.detJ));
1685: }
1686: if (transform) PetscCall(DMPlexBasisTransformApply_Internal(dm, &coords[coordDim * q], PETSC_FALSE, Nc, funcVal, funcVal, dm->transformCtx));
1687: PetscCall(PetscFEInterpolateGradient_Static(fe, 1, &x[fieldOffset], &qgeom, q, interpolant));
1688: /* Overwrite with the dot product if the normal is given */
1689: if (n) {
1690: for (fc = 0; fc < Nc; ++fc) {
1691: PetscScalar sum = 0.0;
1692: for (PetscInt d = 0; d < dim; ++d) sum += interpolant[fc * dim + d] * n[d];
1693: interpolant[fc] = sum;
1694: }
1695: }
1696: for (fc = 0; fc < Nc; ++fc) {
1697: const PetscReal wt = quadWeights[q * qNc + (qNc == 1 ? 0 : qc + fc)];
1698: 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])));
1699: elemDiff += PetscSqr(PetscRealPart(interpolant[fc] - funcVal[fc])) * wt * fegeom.detJ[q];
1700: }
1701: }
1702: fieldOffset += Nb;
1703: qc += Nc;
1704: }
1705: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, c, NULL, &x));
1706: if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, " elem %" PetscInt_FMT " diff %g\n", c, (double)elemDiff));
1707: *diff += elemDiff;
1708: }
1709: PetscCall(PetscFree6(funcVal, coords, fegeom.J, fegeom.invJ, interpolant, fegeom.detJ));
1710: PetscCall(DMRestoreLocalVector(dm, &localX));
1711: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, diff, 1, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)dm)));
1712: *diff = PetscSqrtReal(*diff);
1713: PetscFunctionReturn(PETSC_SUCCESS);
1714: }
1716: PetscErrorCode DMComputeL2FieldDiff_Plex(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
1717: {
1718: const PetscInt debug = ((DM_Plex *)dm->data)->printL2;
1719: DM tdm;
1720: DMLabel depthLabel;
1721: PetscSection section;
1722: Vec localX, tv;
1723: PetscInt dim, depth, dE, Nf, f, Nds, s;
1724: PetscBool transform;
1726: PetscFunctionBegin;
1727: PetscCall(DMGetDimension(dm, &dim));
1728: PetscCall(DMGetCoordinateDim(dm, &dE));
1729: PetscCall(DMGetLocalSection(dm, §ion));
1730: PetscCall(DMGetLocalVector(dm, &localX));
1731: PetscCall(DMGetBasisTransformDM_Internal(dm, &tdm));
1732: PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
1733: PetscCall(DMHasBasisTransform(dm, &transform));
1734: PetscCall(DMGetNumFields(dm, &Nf));
1735: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
1736: PetscCall(DMLabelGetNumValues(depthLabel, &depth));
1738: PetscCall(VecSet(localX, 0.0));
1739: PetscCall(DMGlobalToLocalBegin(dm, X, INSERT_VALUES, localX));
1740: PetscCall(DMGlobalToLocalEnd(dm, X, INSERT_VALUES, localX));
1741: PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, INSERT_BC_VALUES, localX));
1742: PetscCall(DMGetNumDS(dm, &Nds));
1743: PetscCall(PetscArrayzero(diff, Nf));
1744: for (s = 0; s < Nds; ++s) {
1745: PetscDS ds;
1746: DMLabel label;
1747: IS fieldIS, pointIS;
1748: const PetscInt *fields, *points = NULL;
1749: PetscQuadrature quad;
1750: const PetscReal *quadPoints, *quadWeights;
1751: PetscFEGeom fegeom;
1752: PetscReal *coords, *gcoords;
1753: PetscScalar *funcVal, *interpolant;
1754: PetscBool isCohesive;
1755: PetscInt qNc, Nq, totNc, cStart = 0, cEnd, c, dsNf;
1757: PetscCall(DMGetRegionNumDS(dm, s, &label, &fieldIS, &ds, NULL));
1758: PetscCall(ISGetIndices(fieldIS, &fields));
1759: PetscCall(PetscDSIsCohesive(ds, &isCohesive));
1760: PetscCall(PetscDSGetNumFields(ds, &dsNf));
1761: PetscCall(PetscDSGetTotalComponents(ds, &totNc));
1762: PetscCall(PetscDSGetQuadrature(ds, &quad));
1763: PetscCall(PetscQuadratureGetData(quad, NULL, &qNc, &Nq, &quadPoints, &quadWeights));
1764: PetscCheck(!(qNc != 1) || !(qNc != totNc), PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Quadrature components %" PetscInt_FMT " != %" PetscInt_FMT " field components", qNc, totNc);
1765: PetscCall(PetscCalloc6(totNc, &funcVal, totNc, &interpolant, dE * (Nq + 1), &coords, Nq, &fegeom.detJ, dE * dE * Nq, &fegeom.J, dE * dE * Nq, &fegeom.invJ));
1766: if (!label) {
1767: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
1768: } else {
1769: PetscCall(DMLabelGetStratumIS(label, 1, &pointIS));
1770: PetscCall(ISGetLocalSize(pointIS, &cEnd));
1771: PetscCall(ISGetIndices(pointIS, &points));
1772: }
1773: for (c = cStart; c < cEnd; ++c) {
1774: const PetscInt cell = points ? points[c] : c;
1775: PetscScalar *x = NULL;
1776: const PetscInt *cone;
1777: PetscInt qc = 0, fOff = 0, dep;
1779: PetscCall(DMLabelGetValue(depthLabel, cell, &dep));
1780: if (dep != depth - 1) continue;
1781: if (isCohesive) {
1782: PetscCall(DMPlexGetCone(dm, cell, &cone));
1783: PetscCall(DMPlexComputeCellGeometryFEM(dm, cone[0], quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
1784: } else {
1785: PetscCall(DMPlexComputeCellGeometryFEM(dm, cell, quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
1786: }
1787: PetscCall(DMPlexVecGetOrientedClosure(dm, NULL, PETSC_FALSE, localX, cell, 0, NULL, &x));
1788: for (f = 0; f < dsNf; ++f) {
1789: PetscObject obj;
1790: PetscClassId id;
1791: void *const ctx = ctxs ? ctxs[fields[f]] : NULL;
1792: PetscInt Nb, Nc, q, fc;
1793: PetscReal elemDiff = 0.0;
1794: PetscBool cohesive;
1796: PetscCall(PetscDSGetCohesive(ds, f, &cohesive));
1797: PetscCall(PetscDSGetDiscretization(ds, f, &obj));
1798: PetscCall(PetscObjectGetClassId(obj, &id));
1799: if (id == PETSCFE_CLASSID) {
1800: PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
1801: PetscCall(PetscFEGetDimension((PetscFE)obj, &Nb));
1802: } else if (id == PETSCFV_CLASSID) {
1803: PetscCall(PetscFVGetNumComponents((PetscFV)obj, &Nc));
1804: Nb = 1;
1805: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, fields[f]);
1806: if (isCohesive && !cohesive) {
1807: fOff += Nb * 2;
1808: qc += Nc;
1809: continue;
1810: }
1811: if (debug) {
1812: char title[1024];
1813: PetscCall(PetscSNPrintf(title, 1023, "Solution for Field %" PetscInt_FMT, fields[f]));
1814: PetscCall(DMPrintCellVector(cell, title, Nb, &x[fOff]));
1815: }
1816: for (q = 0; q < Nq; ++q) {
1817: PetscFEGeom qgeom;
1818: PetscErrorCode ierr;
1820: qgeom.dimEmbed = fegeom.dimEmbed;
1821: qgeom.J = &fegeom.J[q * dE * dE];
1822: qgeom.invJ = &fegeom.invJ[q * dE * dE];
1823: qgeom.detJ = &fegeom.detJ[q];
1824: 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);
1825: if (transform) {
1826: gcoords = &coords[dE * Nq];
1827: PetscCall(DMPlexBasisTransformApplyReal_Internal(dm, &coords[dE * q], PETSC_TRUE, dE, &coords[dE * q], gcoords, dm->transformCtx));
1828: } else {
1829: gcoords = &coords[dE * q];
1830: }
1831: for (fc = 0; fc < Nc; ++fc) funcVal[fc] = 0.;
1832: ierr = (*funcs[fields[f]])(dE, time, gcoords, Nc, funcVal, ctx);
1833: if (ierr) {
1834: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, cell, NULL, &x));
1835: PetscCall(DMRestoreLocalVector(dm, &localX));
1836: PetscCall(PetscFree6(funcVal, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
1837: }
1838: if (transform) PetscCall(DMPlexBasisTransformApply_Internal(dm, &coords[dE * q], PETSC_FALSE, Nc, funcVal, funcVal, dm->transformCtx));
1839: /* Call once for each face, except for lagrange field */
1840: if (id == PETSCFE_CLASSID) PetscCall(PetscFEInterpolate_Static((PetscFE)obj, &x[fOff], &qgeom, q, interpolant));
1841: else if (id == PETSCFV_CLASSID) PetscCall(PetscFVInterpolate_Static((PetscFV)obj, &x[fOff], q, interpolant));
1842: else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, fields[f]);
1843: for (fc = 0; fc < Nc; ++fc) {
1844: const PetscReal wt = quadWeights[q * qNc + (qNc == 1 ? 0 : qc + fc)];
1845: if (debug)
1846: 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),
1847: (double)(PetscSqr(PetscRealPart(interpolant[fc] - funcVal[fc])) * wt * fegeom.detJ[q])));
1848: elemDiff += PetscSqr(PetscRealPart(interpolant[fc] - funcVal[fc])) * wt * fegeom.detJ[q];
1849: }
1850: }
1851: fOff += Nb;
1852: qc += Nc;
1853: diff[fields[f]] += elemDiff;
1854: if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, " cell %" PetscInt_FMT " field %" PetscInt_FMT " cum diff %g\n", cell, fields[f], (double)diff[fields[f]]));
1855: }
1856: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, cell, NULL, &x));
1857: }
1858: if (label) {
1859: PetscCall(ISRestoreIndices(pointIS, &points));
1860: PetscCall(ISDestroy(&pointIS));
1861: }
1862: PetscCall(ISRestoreIndices(fieldIS, &fields));
1863: PetscCall(PetscFree6(funcVal, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
1864: }
1865: PetscCall(DMRestoreLocalVector(dm, &localX));
1866: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, diff, Nf, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)dm)));
1867: for (f = 0; f < Nf; ++f) diff[f] = PetscSqrtReal(diff[f]);
1868: PetscFunctionReturn(PETSC_SUCCESS);
1869: }
1871: /*@
1872: 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.
1874: Collective
1876: Input Parameters:
1877: + dm - The `DM`
1878: . time - The time
1879: . funcs - The functions to evaluate for each field component: `NULL` means that component does not contribute to error calculation
1880: . ctxs - Optional array of contexts to pass to each function, or `NULL`.
1881: - X - The coefficient vector u_h
1883: Output Parameter:
1884: . D - A `Vec` which holds the difference ||u - u_h||_2 for each cell
1886: Level: developer
1888: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
1889: @*/
1890: PetscErrorCode DMPlexComputeL2DiffVec(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, Vec D)
1891: {
1892: PetscSection section;
1893: PetscQuadrature quad;
1894: Vec localX;
1895: PetscFEGeom fegeom;
1896: PetscScalar *funcVal, *interpolant;
1897: PetscReal *coords;
1898: const PetscReal *quadPoints, *quadWeights;
1899: PetscInt dim, coordDim, numFields, numComponents = 0, qNc, Nq, cStart, cEnd, c, field, fieldOffset;
1901: PetscFunctionBegin;
1902: PetscCall(VecSet(D, 0.0));
1903: PetscCall(DMGetDimension(dm, &dim));
1904: PetscCall(DMGetCoordinateDim(dm, &coordDim));
1905: PetscCall(DMGetLocalSection(dm, §ion));
1906: PetscCall(PetscSectionGetNumFields(section, &numFields));
1907: PetscCall(DMGetLocalVector(dm, &localX));
1908: PetscCall(DMProjectFunctionLocal(dm, time, funcs, ctxs, INSERT_BC_VALUES, localX));
1909: PetscCall(DMGlobalToLocalBegin(dm, X, INSERT_VALUES, localX));
1910: PetscCall(DMGlobalToLocalEnd(dm, X, INSERT_VALUES, localX));
1911: for (field = 0; field < numFields; ++field) {
1912: PetscObject obj;
1913: PetscClassId id;
1914: PetscInt Nc;
1916: PetscCall(DMGetField(dm, field, NULL, &obj));
1917: PetscCall(PetscObjectGetClassId(obj, &id));
1918: if (id == PETSCFE_CLASSID) {
1919: PetscFE fe = (PetscFE)obj;
1921: PetscCall(PetscFEGetQuadrature(fe, &quad));
1922: PetscCall(PetscFEGetNumComponents(fe, &Nc));
1923: } else if (id == PETSCFV_CLASSID) {
1924: PetscFV fv = (PetscFV)obj;
1926: PetscCall(PetscFVGetQuadrature(fv, &quad));
1927: PetscCall(PetscFVGetNumComponents(fv, &Nc));
1928: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1929: numComponents += Nc;
1930: }
1931: PetscCall(PetscQuadratureGetData(quad, NULL, &qNc, &Nq, &quadPoints, &quadWeights));
1932: PetscCheck(!(qNc != 1) || !(qNc != numComponents), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Quadrature components %" PetscInt_FMT " != %" PetscInt_FMT " field components", qNc, numComponents);
1933: PetscCall(PetscMalloc6(numComponents, &funcVal, numComponents, &interpolant, coordDim * Nq, &coords, Nq, &fegeom.detJ, coordDim * coordDim * Nq, &fegeom.J, coordDim * coordDim * Nq, &fegeom.invJ));
1934: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
1935: for (c = cStart; c < cEnd; ++c) {
1936: PetscScalar *x = NULL;
1937: PetscScalar elemDiff = 0.0;
1938: PetscInt qc = 0;
1940: PetscCall(DMPlexComputeCellGeometryFEM(dm, c, quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
1941: PetscCall(DMPlexVecGetOrientedClosure(dm, NULL, PETSC_FALSE, localX, c, 0, NULL, &x));
1943: for (field = 0, fieldOffset = 0; field < numFields; ++field) {
1944: PetscObject obj;
1945: PetscClassId id;
1946: void *const ctx = ctxs ? ctxs[field] : NULL;
1947: PetscInt Nb, Nc, q, fc;
1949: PetscCall(DMGetField(dm, field, NULL, &obj));
1950: PetscCall(PetscObjectGetClassId(obj, &id));
1951: if (id == PETSCFE_CLASSID) {
1952: PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
1953: PetscCall(PetscFEGetDimension((PetscFE)obj, &Nb));
1954: } else if (id == PETSCFV_CLASSID) {
1955: PetscCall(PetscFVGetNumComponents((PetscFV)obj, &Nc));
1956: Nb = 1;
1957: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1958: if (funcs[field]) {
1959: for (q = 0; q < Nq; ++q) {
1960: PetscFEGeom qgeom;
1962: qgeom.dimEmbed = fegeom.dimEmbed;
1963: qgeom.J = &fegeom.J[q * coordDim * coordDim];
1964: qgeom.invJ = &fegeom.invJ[q * coordDim * coordDim];
1965: qgeom.detJ = &fegeom.detJ[q];
1966: 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);
1967: PetscCall((*funcs[field])(coordDim, time, &coords[q * coordDim], Nc, funcVal, ctx));
1968: #if defined(needs_fix_with_return_code_argument)
1969: if (ierr) {
1970: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, c, NULL, &x));
1971: PetscCall(PetscFree6(funcVal, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
1972: PetscCall(DMRestoreLocalVector(dm, &localX));
1973: }
1974: #endif
1975: if (id == PETSCFE_CLASSID) PetscCall(PetscFEInterpolate_Static((PetscFE)obj, &x[fieldOffset], &qgeom, q, interpolant));
1976: else if (id == PETSCFV_CLASSID) PetscCall(PetscFVInterpolate_Static((PetscFV)obj, &x[fieldOffset], q, interpolant));
1977: else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
1978: for (fc = 0; fc < Nc; ++fc) {
1979: const PetscReal wt = quadWeights[q * qNc + (qNc == 1 ? 0 : qc + fc)];
1980: elemDiff += PetscSqr(PetscRealPart(interpolant[fc] - funcVal[fc])) * wt * fegeom.detJ[q];
1981: }
1982: }
1983: }
1984: fieldOffset += Nb;
1985: qc += Nc;
1986: }
1987: PetscCall(DMPlexVecRestoreClosure(dm, NULL, localX, c, NULL, &x));
1988: PetscCall(VecSetValue(D, c - cStart, elemDiff, INSERT_VALUES));
1989: }
1990: PetscCall(PetscFree6(funcVal, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
1991: PetscCall(DMRestoreLocalVector(dm, &localX));
1992: PetscCall(VecSqrtAbs(D));
1993: PetscFunctionReturn(PETSC_SUCCESS);
1994: }
1996: /*@
1997: DMPlexComputeL2FluxDiffVecLocal - This function computes the integral of the difference between the gradient of field `f`in `u` and field `mf` in `mu`
1999: Collective
2001: Input Parameters:
2002: + lu - The local `Vec` containing the primal solution
2003: . f - The field number for the potential
2004: . lmu - The local `Vec` containing the mixed solution
2005: - mf - The field number for the flux
2007: Output Parameter:
2008: . eFlux - A global `Vec` which holds $||\nabla u_f - \mu_{mf}||$
2010: Level: advanced
2012: Notes:
2013: We assume that the `DM` for each solution has the same topology, geometry, and quadrature.
2015: This is usually used to get an error estimate for the primal solution, using the flux from a mixed solution.
2017: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeL2FluxDiffVec()`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
2018: @*/
2019: PetscErrorCode DMPlexComputeL2FluxDiffVecLocal(Vec lu, PetscInt f, Vec lmu, PetscInt mf, Vec eFlux)
2020: {
2021: DM dm, mdm, edm;
2022: PetscFE fe, mfe;
2023: PetscFEGeom fegeom;
2024: PetscQuadrature quad;
2025: const PetscReal *quadWeights;
2026: PetscReal *coords;
2027: PetscScalar *interpolant, *minterpolant, *earray;
2028: PetscInt cdim, mcdim, cStart, cEnd, Nc, mNc, qNc, Nq;
2029: MPI_Comm comm;
2031: PetscFunctionBegin;
2032: PetscCall(VecGetDM(lu, &dm));
2033: PetscCall(VecGetDM(lmu, &mdm));
2034: PetscCall(VecGetDM(eFlux, &edm));
2035: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
2036: PetscCall(VecSet(eFlux, 0.0));
2038: // Check if the both problems are on the same mesh
2039: PetscCall(DMGetCoordinateDim(dm, &cdim));
2040: PetscCall(DMGetCoordinateDim(mdm, &mcdim));
2041: PetscCheck(cdim == mcdim, comm, PETSC_ERR_ARG_SIZ, "primal coordinate Dim %" PetscInt_FMT " != %" PetscInt_FMT " mixed coordinate Dim", cdim, mcdim);
2042: fegeom.dimEmbed = cdim;
2044: PetscCall(DMGetField(dm, f, NULL, (PetscObject *)&fe));
2045: PetscCall(DMGetField(mdm, mf, NULL, (PetscObject *)&mfe));
2046: PetscCall(PetscFEGetNumComponents(fe, &Nc));
2047: PetscCall(PetscFEGetNumComponents(mfe, &mNc));
2048: PetscCall(PetscFEGetQuadrature(fe, &quad));
2049: PetscCall(PetscQuadratureGetData(quad, NULL, &qNc, &Nq, NULL, &quadWeights));
2050: PetscCheck(qNc == 1 || qNc == mNc, comm, PETSC_ERR_ARG_SIZ, "Quadrature components %" PetscInt_FMT " != %" PetscInt_FMT " field components", qNc, mNc);
2052: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
2053: PetscCall(VecGetArrayWrite(eFlux, &earray));
2054: 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));
2055: for (PetscInt c = cStart; c < cEnd; ++c) {
2056: PetscScalar *x = NULL;
2057: PetscScalar *mx = NULL;
2058: PetscScalar *eval = NULL;
2059: PetscReal fluxElemDiff = 0.0;
2061: PetscCall(DMPlexComputeCellGeometryFEM(dm, c, quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
2062: PetscCall(DMPlexVecGetClosure(dm, NULL, lu, c, NULL, &x));
2063: PetscCall(DMPlexVecGetClosure(mdm, NULL, lmu, c, NULL, &mx));
2065: for (PetscInt q = 0; q < Nq; ++q) {
2066: PetscFEGeom qgeom;
2068: qgeom.dimEmbed = fegeom.dimEmbed;
2069: qgeom.J = &fegeom.J[q * cdim * cdim];
2070: qgeom.invJ = &fegeom.invJ[q * cdim * cdim];
2071: qgeom.detJ = &fegeom.detJ[q];
2073: 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);
2075: PetscCall(PetscFEInterpolate_Static(mfe, &mx[0], &qgeom, q, minterpolant));
2076: PetscCall(PetscFEInterpolateGradient_Static(fe, 1, &x[0], &qgeom, q, interpolant));
2078: /* Now take the elementwise difference and store that in a vector. */
2079: for (PetscInt fc = 0; fc < mNc; ++fc) {
2080: const PetscReal wt = quadWeights[q * qNc + (qNc == 1 ? 0 : fc)];
2081: fluxElemDiff += PetscSqr(PetscRealPart(interpolant[fc] - minterpolant[fc])) * wt * fegeom.detJ[q];
2082: }
2083: }
2084: PetscCall(DMPlexVecRestoreClosure(dm, NULL, lu, c, NULL, &x));
2085: PetscCall(DMPlexVecRestoreClosure(mdm, NULL, lmu, c, NULL, &mx));
2086: PetscCall(DMPlexPointGlobalRef(edm, c, earray, (void *)&eval));
2087: if (eval) eval[0] = fluxElemDiff;
2088: }
2089: PetscCall(PetscFree6(interpolant, minterpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
2090: PetscCall(VecRestoreArrayWrite(eFlux, &earray));
2092: PetscCall(VecAssemblyBegin(eFlux));
2093: PetscCall(VecAssemblyEnd(eFlux));
2094: PetscCall(VecSqrtAbs(eFlux));
2095: PetscFunctionReturn(PETSC_SUCCESS);
2096: }
2098: /*@
2099: DMPlexComputeL2FluxDiffVec - This function computes the integral of the difference between the gradient of field `f`in `u` and field `mf` in `mu`
2101: Collective
2103: Input Parameters:
2104: + u - The global `Vec` containing the primal solution
2105: . f - The field number for the potential
2106: . mu - The global `Vec` containing the mixed solution
2107: - mf - The field number for the flux
2109: Output Parameter:
2110: . eFlux - A global `Vec` which holds $||\nabla u_f - \mu_{mf}||$
2112: Level: advanced
2114: Notes:
2115: We assume that the `DM` for each solution has the same topology, geometry, and quadrature.
2117: This is usually used to get an error estimate for the primal solution, using the flux from a mixed solution.
2119: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeL2FluxDiffVecLocal()`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
2120: @*/
2121: PetscErrorCode DMPlexComputeL2FluxDiffVec(Vec u, PetscInt f, Vec mu, PetscInt mf, Vec eFlux)
2122: {
2123: DM dm, mdm;
2124: Vec lu, lmu;
2126: PetscFunctionBegin;
2127: PetscCall(VecGetDM(u, &dm));
2128: PetscCall(DMGetLocalVector(dm, &lu));
2129: PetscCall(DMGlobalToLocal(dm, u, INSERT_VALUES, lu));
2130: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_TRUE, lu, 0.0, NULL, NULL, NULL));
2132: PetscCall(VecGetDM(mu, &mdm));
2133: PetscCall(DMGetLocalVector(mdm, &lmu));
2134: PetscCall(DMGlobalToLocal(mdm, mu, INSERT_VALUES, lmu));
2135: PetscCall(DMPlexInsertBoundaryValues(mdm, PETSC_TRUE, lmu, 0.0, NULL, NULL, NULL));
2137: PetscCall(DMPlexComputeL2FluxDiffVecLocal(lu, f, lmu, mf, eFlux));
2139: PetscCall(DMRestoreLocalVector(dm, &lu));
2140: PetscCall(DMRestoreLocalVector(mdm, &lmu));
2141: PetscFunctionReturn(PETSC_SUCCESS);
2142: }
2144: /*@
2145: DMPlexComputeClementInterpolant - This function computes the L2 projection of the cellwise values of a function u onto P1
2147: Collective
2149: Input Parameters:
2150: + dm - The `DM`
2151: - locX - The coefficient vector u_h
2153: Output Parameter:
2154: . locC - A `Vec` which holds the Clement interpolant of the function
2156: Level: developer
2158: Note:
2159: $ 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
2161: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
2162: @*/
2163: PetscErrorCode DMPlexComputeClementInterpolant(DM dm, Vec locX, Vec locC)
2164: {
2165: PetscInt debug = ((DM_Plex *)dm->data)->printFEM;
2166: DM dmc;
2167: PetscQuadrature quad;
2168: PetscScalar *interpolant, *valsum;
2169: PetscFEGeom fegeom;
2170: PetscReal *coords;
2171: const PetscReal *quadPoints, *quadWeights;
2172: PetscInt dim, cdim, Nf, f, Nc = 0, Nq, qNc, cStart, cEnd, vStart, vEnd, v;
2174: PetscFunctionBegin;
2175: PetscCall(PetscCitationsRegister(ClementCitation, &Clementcite));
2176: PetscCall(VecGetDM(locC, &dmc));
2177: PetscCall(VecSet(locC, 0.0));
2178: PetscCall(DMGetDimension(dm, &dim));
2179: PetscCall(DMGetCoordinateDim(dm, &cdim));
2180: fegeom.dimEmbed = cdim;
2181: PetscCall(DMGetNumFields(dm, &Nf));
2182: PetscCheck(Nf > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of fields is zero!");
2183: for (f = 0; f < Nf; ++f) {
2184: PetscObject obj;
2185: PetscClassId id;
2186: PetscInt fNc;
2188: PetscCall(DMGetField(dm, f, NULL, &obj));
2189: PetscCall(PetscObjectGetClassId(obj, &id));
2190: if (id == PETSCFE_CLASSID) {
2191: PetscFE fe = (PetscFE)obj;
2193: PetscCall(PetscFEGetQuadrature(fe, &quad));
2194: PetscCall(PetscFEGetNumComponents(fe, &fNc));
2195: } else if (id == PETSCFV_CLASSID) {
2196: PetscFV fv = (PetscFV)obj;
2198: PetscCall(PetscFVGetQuadrature(fv, &quad));
2199: PetscCall(PetscFVGetNumComponents(fv, &fNc));
2200: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, f);
2201: Nc += fNc;
2202: }
2203: PetscCall(PetscQuadratureGetData(quad, NULL, &qNc, &Nq, &quadPoints, &quadWeights));
2204: PetscCheck(qNc == 1, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Quadrature components %" PetscInt_FMT " > 1", qNc);
2205: PetscCall(PetscMalloc6(Nc * 2, &valsum, Nc, &interpolant, cdim * Nq, &coords, Nq, &fegeom.detJ, cdim * cdim * Nq, &fegeom.J, cdim * cdim * Nq, &fegeom.invJ));
2206: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
2207: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
2208: for (v = vStart; v < vEnd; ++v) {
2209: PetscScalar volsum = 0.0;
2210: PetscInt *star = NULL;
2211: PetscInt starSize, st, fc;
2213: PetscCall(PetscArrayzero(valsum, Nc));
2214: PetscCall(DMPlexGetTransitiveClosure(dm, v, PETSC_FALSE, &starSize, &star));
2215: for (st = 0; st < starSize * 2; st += 2) {
2216: const PetscInt cell = star[st];
2217: PetscScalar *val = &valsum[Nc];
2218: PetscScalar *x = NULL;
2219: PetscReal vol = 0.0;
2220: PetscInt foff = 0;
2222: if (cell < cStart || cell >= cEnd) continue;
2223: PetscCall(DMPlexComputeCellGeometryFEM(dm, cell, quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
2224: PetscCall(DMPlexVecGetClosure(dm, NULL, locX, cell, NULL, &x));
2225: for (f = 0; f < Nf; ++f) {
2226: PetscObject obj;
2227: PetscClassId id;
2228: PetscInt Nb, fNc, q;
2230: PetscCall(PetscArrayzero(val, Nc));
2231: PetscCall(DMGetField(dm, f, NULL, &obj));
2232: PetscCall(PetscObjectGetClassId(obj, &id));
2233: if (id == PETSCFE_CLASSID) {
2234: PetscCall(PetscFEGetNumComponents((PetscFE)obj, &fNc));
2235: PetscCall(PetscFEGetDimension((PetscFE)obj, &Nb));
2236: } else if (id == PETSCFV_CLASSID) {
2237: PetscCall(PetscFVGetNumComponents((PetscFV)obj, &fNc));
2238: Nb = 1;
2239: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, f);
2240: for (q = 0; q < Nq; ++q) {
2241: const PetscReal wt = quadWeights[q] * fegeom.detJ[q];
2242: PetscFEGeom qgeom;
2244: qgeom.dimEmbed = fegeom.dimEmbed;
2245: qgeom.J = &fegeom.J[q * cdim * cdim];
2246: qgeom.invJ = &fegeom.invJ[q * cdim * cdim];
2247: qgeom.detJ = &fegeom.detJ[q];
2248: 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);
2249: PetscCheck(id == PETSCFE_CLASSID, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, f);
2250: PetscCall(PetscFEInterpolate_Static((PetscFE)obj, &x[foff], &qgeom, q, interpolant));
2251: for (fc = 0; fc < fNc; ++fc) val[foff + fc] += interpolant[fc] * wt;
2252: vol += wt;
2253: }
2254: foff += Nb;
2255: }
2256: PetscCall(DMPlexVecRestoreClosure(dm, NULL, locX, cell, NULL, &x));
2257: for (fc = 0; fc < Nc; ++fc) valsum[fc] += val[fc];
2258: volsum += vol;
2259: if (debug) {
2260: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Vertex %" PetscInt_FMT " Cell %" PetscInt_FMT " value: [", v, cell));
2261: for (fc = 0; fc < Nc; ++fc) {
2262: if (fc) PetscCall(PetscPrintf(PETSC_COMM_SELF, ", "));
2263: PetscCall(PetscPrintf(PETSC_COMM_SELF, "%g", (double)PetscRealPart(val[fc])));
2264: }
2265: PetscCall(PetscPrintf(PETSC_COMM_SELF, "]\n"));
2266: }
2267: }
2268: for (fc = 0; fc < Nc; ++fc) valsum[fc] /= volsum;
2269: PetscCall(DMPlexRestoreTransitiveClosure(dm, v, PETSC_FALSE, &starSize, &star));
2270: PetscCall(DMPlexVecSetClosure(dmc, NULL, locC, v, valsum, INSERT_VALUES));
2271: }
2272: PetscCall(PetscFree6(valsum, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
2273: PetscFunctionReturn(PETSC_SUCCESS);
2274: }
2276: /*@
2277: DMPlexComputeGradientClementInterpolant - This function computes the L2 projection of the cellwise gradient of a function u onto P1
2279: Collective
2281: Input Parameters:
2282: + dm - The `DM`
2283: - locX - The coefficient vector u_h
2285: Output Parameter:
2286: . locC - A `Vec` which holds the Clement interpolant of the gradient
2288: Level: developer
2290: Note:
2291: $\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
2293: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMProjectFunction()`, `DMComputeL2Diff()`, `DMComputeL2FieldDiff()`, `DMComputeL2GradientDiff()`
2294: @*/
2295: PetscErrorCode DMPlexComputeGradientClementInterpolant(DM dm, Vec locX, Vec locC)
2296: {
2297: DM_Plex *mesh = (DM_Plex *)dm->data;
2298: PetscInt debug = mesh->printFEM;
2299: DM dmC;
2300: PetscQuadrature quad;
2301: PetscScalar *interpolant, *gradsum;
2302: PetscFEGeom fegeom;
2303: PetscReal *coords;
2304: const PetscReal *quadPoints, *quadWeights;
2305: PetscInt dim, coordDim, numFields, numComponents = 0, qNc, Nq, cStart, cEnd, vStart, vEnd, v, field, fieldOffset;
2307: PetscFunctionBegin;
2308: PetscCall(PetscCitationsRegister(ClementCitation, &Clementcite));
2309: PetscCall(VecGetDM(locC, &dmC));
2310: PetscCall(VecSet(locC, 0.0));
2311: PetscCall(DMGetDimension(dm, &dim));
2312: PetscCall(DMGetCoordinateDim(dm, &coordDim));
2313: fegeom.dimEmbed = coordDim;
2314: PetscCall(DMGetNumFields(dm, &numFields));
2315: PetscCheck(numFields, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of fields is zero!");
2316: for (field = 0; field < numFields; ++field) {
2317: PetscObject obj;
2318: PetscClassId id;
2319: PetscInt Nc;
2321: PetscCall(DMGetField(dm, field, NULL, &obj));
2322: PetscCall(PetscObjectGetClassId(obj, &id));
2323: if (id == PETSCFE_CLASSID) {
2324: PetscFE fe = (PetscFE)obj;
2326: PetscCall(PetscFEGetQuadrature(fe, &quad));
2327: PetscCall(PetscFEGetNumComponents(fe, &Nc));
2328: } else if (id == PETSCFV_CLASSID) {
2329: PetscFV fv = (PetscFV)obj;
2331: PetscCall(PetscFVGetQuadrature(fv, &quad));
2332: PetscCall(PetscFVGetNumComponents(fv, &Nc));
2333: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
2334: numComponents += Nc;
2335: }
2336: PetscCall(PetscQuadratureGetData(quad, NULL, &qNc, &Nq, &quadPoints, &quadWeights));
2337: PetscCheck((qNc == 1) || (qNc == numComponents), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Quadrature components %" PetscInt_FMT " != %" PetscInt_FMT " field components", qNc, numComponents);
2338: 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));
2339: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
2340: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
2341: for (v = vStart; v < vEnd; ++v) {
2342: PetscScalar volsum = 0.0;
2343: PetscInt *star = NULL;
2344: PetscInt starSize, st, d, fc;
2346: PetscCall(PetscArrayzero(gradsum, coordDim * numComponents));
2347: PetscCall(DMPlexGetTransitiveClosure(dm, v, PETSC_FALSE, &starSize, &star));
2348: for (st = 0; st < starSize * 2; st += 2) {
2349: const PetscInt cell = star[st];
2350: PetscInt qc = 0;
2351: PetscScalar *grad = &gradsum[coordDim * numComponents];
2352: PetscScalar *x = NULL;
2353: PetscReal vol = 0.0;
2355: if (cell < cStart || cell >= cEnd) continue;
2356: PetscCall(DMPlexComputeCellGeometryFEM(dm, cell, quad, coords, fegeom.J, fegeom.invJ, fegeom.detJ));
2357: PetscCall(DMPlexVecGetClosure(dm, NULL, locX, cell, NULL, &x));
2358: for (field = 0, fieldOffset = 0; field < numFields; ++field) {
2359: PetscObject obj;
2360: PetscClassId id;
2361: PetscInt Nb, Nc, q;
2363: PetscCall(PetscArrayzero(grad, coordDim * numComponents));
2364: PetscCall(DMGetField(dm, field, NULL, &obj));
2365: PetscCall(PetscObjectGetClassId(obj, &id));
2366: if (id == PETSCFE_CLASSID) {
2367: PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
2368: PetscCall(PetscFEGetDimension((PetscFE)obj, &Nb));
2369: } else if (id == PETSCFV_CLASSID) {
2370: PetscCall(PetscFVGetNumComponents((PetscFV)obj, &Nc));
2371: Nb = 1;
2372: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
2373: for (q = 0; q < Nq; ++q) {
2374: PetscFEGeom qgeom;
2376: qgeom.dimEmbed = fegeom.dimEmbed;
2377: qgeom.J = &fegeom.J[q * coordDim * coordDim];
2378: qgeom.invJ = &fegeom.invJ[q * coordDim * coordDim];
2379: qgeom.detJ = &fegeom.detJ[q];
2380: 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);
2381: PetscCheck(id == PETSCFE_CLASSID, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
2382: PetscCall(PetscFEInterpolateGradient_Static((PetscFE)obj, 1, &x[fieldOffset], &qgeom, q, interpolant));
2383: for (fc = 0; fc < Nc; ++fc) {
2384: const PetscReal wt = quadWeights[q * qNc + (qNc == 1 ? 0 : qc + fc)];
2386: for (d = 0; d < coordDim; ++d) grad[fc * coordDim + d] += interpolant[fc * dim + d] * wt * fegeom.detJ[q];
2387: }
2388: vol += quadWeights[q * qNc] * fegeom.detJ[q];
2389: }
2390: fieldOffset += Nb;
2391: if (qNc > 1) qc += Nc;
2392: }
2393: PetscCall(DMPlexVecRestoreClosure(dm, NULL, locX, cell, NULL, &x));
2394: for (fc = 0; fc < numComponents; ++fc) {
2395: for (d = 0; d < coordDim; ++d) gradsum[fc * coordDim + d] += grad[fc * coordDim + d];
2396: }
2397: volsum += vol;
2398: if (debug) {
2399: PetscCall(PetscPrintf(PETSC_COMM_SELF, "Vertex %" PetscInt_FMT " Cell %" PetscInt_FMT " gradient: [", v, cell));
2400: for (fc = 0; fc < numComponents; ++fc) {
2401: for (d = 0; d < coordDim; ++d) {
2402: if (fc || d > 0) PetscCall(PetscPrintf(PETSC_COMM_SELF, ", "));
2403: PetscCall(PetscPrintf(PETSC_COMM_SELF, "%g", (double)PetscRealPart(grad[fc * coordDim + d])));
2404: }
2405: }
2406: PetscCall(PetscPrintf(PETSC_COMM_SELF, "]\n"));
2407: }
2408: }
2409: for (fc = 0; fc < numComponents; ++fc) {
2410: for (d = 0; d < coordDim; ++d) gradsum[fc * coordDim + d] /= volsum;
2411: }
2412: PetscCall(DMPlexRestoreTransitiveClosure(dm, v, PETSC_FALSE, &starSize, &star));
2413: PetscCall(DMPlexVecSetClosure(dmC, NULL, locC, v, gradsum, INSERT_VALUES));
2414: }
2415: PetscCall(PetscFree6(gradsum, interpolant, coords, fegeom.detJ, fegeom.J, fegeom.invJ));
2416: PetscFunctionReturn(PETSC_SUCCESS);
2417: }
2419: PetscErrorCode DMPlexComputeIntegral_Internal(DM dm, Vec locX, PetscInt cStart, PetscInt cEnd, PetscScalar *cintegral, PetscCtx ctx)
2420: {
2421: DM dmAux = NULL, plexA = NULL;
2422: PetscDS prob, probAux = NULL;
2423: PetscSection section, sectionAux;
2424: Vec locA;
2425: PetscInt dim, numCells = cEnd - cStart, c, f;
2426: PetscBool useFVM = PETSC_FALSE;
2427: /* DS */
2428: PetscInt Nf, totDim, *uOff, *uOff_x, numConstants;
2429: PetscInt NfAux, totDimAux, *aOff;
2430: PetscScalar *u, *a = NULL;
2431: const PetscScalar *constants;
2432: /* Geometry */
2433: PetscFEGeom *cgeomFEM;
2434: DM dmGrad;
2435: PetscQuadrature affineQuad = NULL;
2436: Vec cellGeometryFVM = NULL, faceGeometryFVM = NULL, locGrad = NULL;
2437: PetscFVCellGeom *cgeomFVM;
2438: const PetscScalar *lgrad;
2439: PetscInt maxDegree;
2440: DMField coordField;
2441: IS cellIS;
2443: PetscFunctionBegin;
2444: PetscCall(DMGetDS(dm, &prob));
2445: PetscCall(DMGetDimension(dm, &dim));
2446: PetscCall(DMGetLocalSection(dm, §ion));
2447: PetscCall(DMGetNumFields(dm, &Nf));
2448: /* Determine which discretizations we have */
2449: for (f = 0; f < Nf; ++f) {
2450: PetscObject obj;
2451: PetscClassId id;
2453: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
2454: PetscCall(PetscObjectGetClassId(obj, &id));
2455: if (id == PETSCFV_CLASSID) useFVM = PETSC_TRUE;
2456: }
2457: /* Read DS information */
2458: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
2459: PetscCall(PetscDSGetComponentOffsets(prob, &uOff));
2460: PetscCall(PetscDSGetComponentDerivativeOffsets(prob, &uOff_x));
2461: PetscCall(ISCreateStride(PETSC_COMM_SELF, numCells, cStart, 1, &cellIS));
2462: PetscCall(PetscDSGetConstants(prob, &numConstants, &constants));
2463: /* Read Auxiliary DS information */
2464: PetscCall(DMGetAuxiliaryVec(dm, NULL, 0, 0, &locA));
2465: if (locA) {
2466: PetscCall(VecGetDM(locA, &dmAux));
2467: PetscCall(DMConvert(dmAux, DMPLEX, &plexA));
2468: PetscCall(DMGetDS(dmAux, &probAux));
2469: PetscCall(PetscDSGetNumFields(probAux, &NfAux));
2470: PetscCall(DMGetLocalSection(dmAux, §ionAux));
2471: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
2472: PetscCall(PetscDSGetComponentOffsets(probAux, &aOff));
2473: }
2474: /* Allocate data arrays */
2475: PetscCall(PetscCalloc1(numCells * totDim, &u));
2476: if (dmAux) PetscCall(PetscMalloc1(numCells * totDimAux, &a));
2477: /* Read out geometry */
2478: PetscCall(DMGetCoordinateField(dm, &coordField));
2479: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
2480: if (maxDegree <= 1) {
2481: PetscCall(DMFieldCreateDefaultQuadrature(coordField, cellIS, &affineQuad));
2482: if (affineQuad) PetscCall(DMFieldCreateFEGeom(coordField, cellIS, affineQuad, PETSC_FEGEOM_BASIC, &cgeomFEM));
2483: }
2484: if (useFVM) {
2485: PetscFV fv = NULL;
2486: Vec grad;
2487: PetscInt fStart, fEnd;
2488: PetscBool compGrad;
2490: for (f = 0; f < Nf; ++f) {
2491: PetscObject obj;
2492: PetscClassId id;
2494: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
2495: PetscCall(PetscObjectGetClassId(obj, &id));
2496: if (id == PETSCFV_CLASSID) {
2497: fv = (PetscFV)obj;
2498: break;
2499: }
2500: }
2501: PetscCall(PetscFVGetComputeGradients(fv, &compGrad));
2502: PetscCall(PetscFVSetComputeGradients(fv, PETSC_TRUE));
2503: PetscCall(DMPlexComputeGeometryFVM(dm, &cellGeometryFVM, &faceGeometryFVM));
2504: PetscCall(DMPlexComputeGradientFVM(dm, fv, faceGeometryFVM, cellGeometryFVM, &dmGrad));
2505: PetscCall(PetscFVSetComputeGradients(fv, compGrad));
2506: PetscCall(VecGetArrayRead(cellGeometryFVM, (const PetscScalar **)&cgeomFVM));
2507: /* Reconstruct and limit cell gradients */
2508: PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
2509: PetscCall(DMGetGlobalVector(dmGrad, &grad));
2510: PetscCall(DMPlexReconstructGradients_Internal(dm, fv, fStart, fEnd, faceGeometryFVM, cellGeometryFVM, locX, grad));
2511: /* Communicate gradient values */
2512: PetscCall(DMGetLocalVector(dmGrad, &locGrad));
2513: PetscCall(DMGlobalToLocalBegin(dmGrad, grad, INSERT_VALUES, locGrad));
2514: PetscCall(DMGlobalToLocalEnd(dmGrad, grad, INSERT_VALUES, locGrad));
2515: PetscCall(DMRestoreGlobalVector(dmGrad, &grad));
2516: /* Handle non-essential (e.g. outflow) boundary values */
2517: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_FALSE, locX, 0.0, faceGeometryFVM, cellGeometryFVM, locGrad));
2518: PetscCall(VecGetArrayRead(locGrad, &lgrad));
2519: }
2520: /* Read out data from inputs */
2521: for (c = cStart; c < cEnd; ++c) {
2522: PetscScalar *x = NULL;
2524: PetscCall(DMPlexVecGetClosure(dm, section, locX, c, NULL, &x));
2525: for (PetscInt i = 0; i < totDim; ++i) u[c * totDim + i] = x[i];
2526: PetscCall(DMPlexVecRestoreClosure(dm, section, locX, c, NULL, &x));
2527: if (dmAux) {
2528: PetscCall(DMPlexVecGetClosure(plexA, sectionAux, locA, c, NULL, &x));
2529: for (PetscInt i = 0; i < totDimAux; ++i) a[c * totDimAux + i] = x[i];
2530: PetscCall(DMPlexVecRestoreClosure(plexA, sectionAux, locA, c, NULL, &x));
2531: }
2532: }
2533: /* Do integration for each field */
2534: for (f = 0; f < Nf; ++f) {
2535: PetscObject obj;
2536: PetscClassId id;
2537: PetscInt numChunks, numBatches, batchSize, numBlocks, blockSize, Ne, Nr, offset;
2539: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
2540: PetscCall(PetscObjectGetClassId(obj, &id));
2541: if (id == PETSCFE_CLASSID) {
2542: PetscFE fe = (PetscFE)obj;
2543: PetscQuadrature q;
2544: PetscFEGeom *chunkGeom = NULL;
2545: PetscInt Nq, Nb;
2547: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
2548: PetscCall(PetscFEGetQuadrature(fe, &q));
2549: PetscCall(PetscQuadratureGetData(q, NULL, NULL, &Nq, NULL, NULL));
2550: PetscCall(PetscFEGetDimension(fe, &Nb));
2551: blockSize = Nb * Nq;
2552: batchSize = numBlocks * blockSize;
2553: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
2554: numChunks = numCells / (numBatches * batchSize);
2555: Ne = numChunks * numBatches * batchSize;
2556: Nr = numCells % (numBatches * batchSize);
2557: offset = numCells - Nr;
2558: if (!affineQuad) PetscCall(DMFieldCreateFEGeom(coordField, cellIS, q, PETSC_FEGEOM_BASIC, &cgeomFEM));
2559: PetscCall(PetscFEGeomGetChunk(cgeomFEM, 0, offset, &chunkGeom));
2560: PetscCall(PetscFEIntegrate(prob, f, Ne, chunkGeom, u, probAux, a, cintegral));
2561: PetscCall(PetscFEGeomGetChunk(cgeomFEM, offset, numCells, &chunkGeom));
2562: PetscCall(PetscFEIntegrate(prob, f, Nr, chunkGeom, &u[offset * totDim], probAux, PetscSafePointerPlusOffset(a, offset * totDimAux), &cintegral[offset * Nf]));
2563: PetscCall(PetscFEGeomRestoreChunk(cgeomFEM, offset, numCells, &chunkGeom));
2564: if (!affineQuad) PetscCall(PetscFEGeomDestroy(&cgeomFEM));
2565: } else if (id == PETSCFV_CLASSID) {
2566: PetscInt foff;
2567: PetscPointFn *obj_func;
2569: PetscCall(PetscDSGetObjective(prob, f, &obj_func));
2570: PetscCall(PetscDSGetFieldOffset(prob, f, &foff));
2571: if (obj_func) {
2572: for (c = 0; c < numCells; ++c) {
2573: PetscScalar *u_x;
2574: PetscScalar lint = 0.;
2576: PetscCall(DMPlexPointLocalRead(dmGrad, c, lgrad, &u_x));
2577: 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);
2578: cintegral[c * Nf + f] += PetscRealPart(lint) * cgeomFVM[c].volume;
2579: }
2580: }
2581: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, f);
2582: }
2583: /* Cleanup data arrays */
2584: if (useFVM) {
2585: PetscCall(VecRestoreArrayRead(locGrad, &lgrad));
2586: PetscCall(VecRestoreArrayRead(cellGeometryFVM, (const PetscScalar **)&cgeomFVM));
2587: PetscCall(DMRestoreLocalVector(dmGrad, &locGrad));
2588: PetscCall(VecDestroy(&faceGeometryFVM));
2589: PetscCall(VecDestroy(&cellGeometryFVM));
2590: PetscCall(DMDestroy(&dmGrad));
2591: }
2592: if (dmAux) PetscCall(PetscFree(a));
2593: PetscCall(DMDestroy(&plexA));
2594: PetscCall(PetscFree(u));
2595: /* Cleanup */
2596: if (affineQuad) PetscCall(PetscFEGeomDestroy(&cgeomFEM));
2597: PetscCall(PetscQuadratureDestroy(&affineQuad));
2598: PetscCall(ISDestroy(&cellIS));
2599: PetscFunctionReturn(PETSC_SUCCESS);
2600: }
2602: /*@
2603: DMPlexComputeIntegralFEM - Form the integral over the domain from the global input X using pointwise functions specified by the user
2605: Input Parameters:
2606: + dm - The mesh
2607: . X - Global input vector
2608: - ctx - The application context
2610: Output Parameter:
2611: . integral - Integral for each field
2613: Level: developer
2615: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSNESComputeResidualFEM()`
2616: @*/
2617: PetscErrorCode DMPlexComputeIntegralFEM(DM dm, Vec X, PetscScalar *integral, PetscCtx ctx)
2618: {
2619: PetscInt printFEM;
2620: PetscScalar *cintegral;
2621: PetscInt Nf, f, cellHeight, cStart, cEnd, cell;
2622: Vec locX;
2624: PetscFunctionBegin;
2627: PetscAssertPointer(integral, 3);
2628: PetscCall(PetscLogEventBegin(DMPLEX_IntegralFEM, dm, 0, 0, 0));
2629: PetscCall(DMPlexConvertPlex(dm, &dm, PETSC_TRUE));
2630: PetscCall(DMGetNumFields(dm, &Nf));
2631: PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
2632: PetscCall(DMPlexGetSimplexOrBoxCells(dm, cellHeight, &cStart, &cEnd));
2633: /* TODO Introduce a loop over large chunks (right now this is a single chunk) */
2634: PetscCall(PetscArrayzero(integral, Nf));
2635: PetscCall(PetscCalloc1((cEnd - cStart) * Nf, &cintegral));
2636: /* Get local solution with boundary values */
2637: PetscCall(DMGetLocalVector(dm, &locX));
2638: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_TRUE, locX, 0.0, NULL, NULL, NULL));
2639: PetscCall(DMGlobalToLocalBegin(dm, X, INSERT_VALUES, locX));
2640: PetscCall(DMGlobalToLocalEnd(dm, X, INSERT_VALUES, locX));
2641: PetscCall(DMPlexComputeIntegral_Internal(dm, locX, cStart, cEnd, cintegral, ctx));
2642: PetscCall(DMRestoreLocalVector(dm, &locX));
2643: printFEM = ((DM_Plex *)dm->data)->printFEM;
2644: /* Sum up values */
2645: for (cell = cStart; cell < cEnd; ++cell) {
2646: const PetscInt c = cell - cStart;
2648: if (printFEM > 1) PetscCall(DMPrintCellVector(cell, "Cell Integral", Nf, &cintegral[c * Nf]));
2649: for (f = 0; f < Nf; ++f) integral[f] += cintegral[c * Nf + f];
2650: }
2651: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, integral, Nf, MPIU_SCALAR, MPIU_SUM, PetscObjectComm((PetscObject)dm)));
2652: if (printFEM) {
2653: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), "Integral:"));
2654: for (f = 0; f < Nf; ++f) PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), " %g", (double)PetscRealPart(integral[f])));
2655: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), "\n"));
2656: }
2657: PetscCall(PetscFree(cintegral));
2658: PetscCall(PetscLogEventEnd(DMPLEX_IntegralFEM, dm, 0, 0, 0));
2659: PetscCall(DMDestroy(&dm));
2660: PetscFunctionReturn(PETSC_SUCCESS);
2661: }
2663: /*@
2664: DMPlexComputeCellwiseIntegralFEM - Form the vector of cellwise integrals F from the global input X using pointwise functions specified by the user
2666: Input Parameters:
2667: + dm - The mesh
2668: . X - Global input vector
2669: - ctx - The application context
2671: Output Parameter:
2672: . F - Cellwise integrals for each field
2674: Level: developer
2676: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSNESComputeResidualFEM()`
2677: @*/
2678: PetscErrorCode DMPlexComputeCellwiseIntegralFEM(DM dm, Vec X, Vec F, PetscCtx ctx)
2679: {
2680: PetscInt printFEM;
2681: DM dmF;
2682: PetscSection sectionF = NULL;
2683: PetscScalar *cintegral, *af;
2684: PetscInt Nf, f, cellHeight, cStart, cEnd, cell, n;
2685: Vec locX;
2687: PetscFunctionBegin;
2691: PetscCall(PetscLogEventBegin(DMPLEX_IntegralFEM, dm, 0, 0, 0));
2692: PetscCall(DMPlexConvertPlex(dm, &dm, PETSC_TRUE));
2693: PetscCall(DMGetNumFields(dm, &Nf));
2694: PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
2695: PetscCall(DMPlexGetSimplexOrBoxCells(dm, cellHeight, &cStart, &cEnd));
2696: /* TODO Introduce a loop over large chunks (right now this is a single chunk) */
2697: PetscCall(PetscCalloc1((cEnd - cStart) * Nf, &cintegral));
2698: /* Get local solution with boundary values */
2699: PetscCall(DMGetLocalVector(dm, &locX));
2700: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_TRUE, locX, 0.0, NULL, NULL, NULL));
2701: PetscCall(DMGlobalToLocalBegin(dm, X, INSERT_VALUES, locX));
2702: PetscCall(DMGlobalToLocalEnd(dm, X, INSERT_VALUES, locX));
2703: PetscCall(DMPlexComputeIntegral_Internal(dm, locX, cStart, cEnd, cintegral, ctx));
2704: PetscCall(DMRestoreLocalVector(dm, &locX));
2705: /* Put values in F */
2706: PetscCall(VecGetArray(F, &af));
2707: PetscCall(VecGetDM(F, &dmF));
2708: if (dmF) PetscCall(DMGetLocalSection(dmF, §ionF));
2709: PetscCall(VecGetLocalSize(F, &n));
2710: PetscCheck(n >= (cEnd - cStart) * Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Vector size %" PetscInt_FMT " < %" PetscInt_FMT, n, (cEnd - cStart) * Nf);
2711: printFEM = ((DM_Plex *)dm->data)->printFEM;
2712: for (cell = cStart; cell < cEnd; ++cell) {
2713: const PetscInt c = cell - cStart;
2714: PetscInt dof = Nf, off = c * Nf;
2716: if (printFEM > 1) PetscCall(DMPrintCellVector(cell, "Cell Integral", Nf, &cintegral[c * Nf]));
2717: if (sectionF) {
2718: PetscCall(PetscSectionGetDof(sectionF, cell, &dof));
2719: PetscCall(PetscSectionGetOffset(sectionF, cell, &off));
2720: }
2721: PetscCheck(dof == Nf, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "The number of cell dofs %" PetscInt_FMT " != %" PetscInt_FMT, dof, Nf);
2722: for (f = 0; f < Nf; ++f) af[off + f] = cintegral[c * Nf + f];
2723: }
2724: PetscCall(VecRestoreArray(F, &af));
2725: PetscCall(PetscFree(cintegral));
2726: PetscCall(PetscLogEventEnd(DMPLEX_IntegralFEM, dm, 0, 0, 0));
2727: PetscCall(DMDestroy(&dm));
2728: PetscFunctionReturn(PETSC_SUCCESS);
2729: }
2731: 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)
2732: {
2733: DM plex = NULL, plexA = NULL;
2734: DMEnclosureType encAux;
2735: PetscDS prob, probAux = NULL;
2736: PetscSection section, sectionAux = NULL;
2737: Vec locA = NULL;
2738: DMField coordField;
2739: PetscInt Nf, totDim, *uOff, *uOff_x;
2740: PetscInt NfAux = 0, totDimAux = 0, *aOff = NULL;
2741: PetscScalar *u, *a = NULL;
2742: const PetscScalar *constants;
2743: PetscInt numConstants, f;
2745: PetscFunctionBegin;
2746: PetscCall(DMGetCoordinateField(dm, &coordField));
2747: PetscCall(DMConvert(dm, DMPLEX, &plex));
2748: PetscCall(DMGetDS(dm, &prob));
2749: PetscCall(DMGetLocalSection(dm, §ion));
2750: PetscCall(PetscSectionGetNumFields(section, &Nf));
2751: /* Determine which discretizations we have */
2752: for (f = 0; f < Nf; ++f) {
2753: PetscObject obj;
2754: PetscClassId id;
2756: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
2757: PetscCall(PetscObjectGetClassId(obj, &id));
2758: PetscCheck(id != PETSCFV_CLASSID, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Not supported for FVM (field %" PetscInt_FMT ")", f);
2759: }
2760: /* Read DS information */
2761: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
2762: PetscCall(PetscDSGetComponentOffsets(prob, &uOff));
2763: PetscCall(PetscDSGetComponentDerivativeOffsets(prob, &uOff_x));
2764: PetscCall(PetscDSGetConstants(prob, &numConstants, &constants));
2765: /* Read Auxiliary DS information */
2766: PetscCall(DMGetAuxiliaryVec(dm, NULL, 0, 0, &locA));
2767: if (locA) {
2768: DM dmAux;
2770: PetscCall(VecGetDM(locA, &dmAux));
2771: PetscCall(DMGetEnclosureRelation(dmAux, dm, &encAux));
2772: PetscCall(DMConvert(dmAux, DMPLEX, &plexA));
2773: PetscCall(DMGetDS(dmAux, &probAux));
2774: PetscCall(PetscDSGetNumFields(probAux, &NfAux));
2775: PetscCall(DMGetLocalSection(dmAux, §ionAux));
2776: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
2777: PetscCall(PetscDSGetComponentOffsets(probAux, &aOff));
2778: }
2779: /* Integrate over points */
2780: {
2781: PetscFEGeom *fgeom, *chunkGeom = NULL;
2782: PetscInt maxDegree;
2783: PetscQuadrature qGeom = NULL;
2784: const PetscInt *points;
2785: PetscInt numFaces, face, Nq, field;
2786: PetscInt numChunks, chunkSize, chunk, Nr, offset;
2788: PetscCall(ISGetLocalSize(pointIS, &numFaces));
2789: PetscCall(ISGetIndices(pointIS, &points));
2790: PetscCall(PetscCalloc2(numFaces * totDim, &u, (locA ? (size_t)numFaces * totDimAux : 0), &a));
2791: PetscCall(DMFieldGetDegree(coordField, pointIS, NULL, &maxDegree));
2792: for (face = 0; face < numFaces; ++face) {
2793: const PetscInt point = points[face], *support;
2794: PetscScalar *x = NULL;
2796: PetscCall(DMPlexGetSupport(dm, point, &support));
2797: PetscCall(DMPlexVecGetClosure(plex, section, locX, support[0], NULL, &x));
2798: for (PetscInt i = 0; i < totDim; ++i) u[face * totDim + i] = x[i];
2799: PetscCall(DMPlexVecRestoreClosure(plex, section, locX, support[0], NULL, &x));
2800: if (locA) {
2801: PetscInt subp;
2802: PetscCall(DMGetEnclosurePoint(plexA, dm, encAux, support[0], &subp));
2803: PetscCall(DMPlexVecGetClosure(plexA, sectionAux, locA, subp, NULL, &x));
2804: for (PetscInt i = 0; i < totDimAux; ++i) a[f * totDimAux + i] = x[i];
2805: PetscCall(DMPlexVecRestoreClosure(plexA, sectionAux, locA, subp, NULL, &x));
2806: }
2807: }
2808: for (field = 0; field < Nf; ++field) {
2809: PetscFE fe;
2811: PetscCall(PetscDSGetDiscretization(prob, field, (PetscObject *)&fe));
2812: if (maxDegree <= 1) PetscCall(DMFieldCreateDefaultQuadrature(coordField, pointIS, &qGeom));
2813: if (!qGeom) {
2814: PetscCall(PetscFEGetFaceQuadrature(fe, &qGeom));
2815: PetscCall(PetscObjectReference((PetscObject)qGeom));
2816: }
2817: PetscCall(PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL));
2818: PetscCall(DMPlexGetFEGeom(coordField, pointIS, qGeom, PETSC_FEGEOM_BOUNDARY, &fgeom));
2819: /* Get blocking */
2820: {
2821: PetscQuadrature q;
2822: PetscInt numBatches, batchSize, numBlocks, blockSize;
2823: PetscInt Nq, Nb;
2825: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
2826: PetscCall(PetscFEGetQuadrature(fe, &q));
2827: PetscCall(PetscQuadratureGetData(q, NULL, NULL, &Nq, NULL, NULL));
2828: PetscCall(PetscFEGetDimension(fe, &Nb));
2829: blockSize = Nb * Nq;
2830: batchSize = numBlocks * blockSize;
2831: chunkSize = numBatches * batchSize;
2832: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
2833: numChunks = numFaces / chunkSize;
2834: Nr = numFaces % chunkSize;
2835: offset = numFaces - Nr;
2836: }
2837: /* Do integration for each field */
2838: for (chunk = 0; chunk < numChunks; ++chunk) {
2839: PetscCall(PetscFEGeomGetChunk(fgeom, chunk * chunkSize, (chunk + 1) * chunkSize, &chunkGeom));
2840: PetscCall(PetscFEIntegrateBd(prob, field, funcs[field], chunkSize, chunkGeom, &u[chunk * chunkSize * totDim], probAux, PetscSafePointerPlusOffset(a, chunk * chunkSize * totDimAux), &fintegral[chunk * chunkSize * Nf]));
2841: PetscCall(PetscFEGeomRestoreChunk(fgeom, 0, offset, &chunkGeom));
2842: }
2843: PetscCall(PetscFEGeomGetChunk(fgeom, offset, numFaces, &chunkGeom));
2844: PetscCall(PetscFEIntegrateBd(prob, field, funcs[field], Nr, chunkGeom, &u[offset * totDim], probAux, PetscSafePointerPlusOffset(a, offset * totDimAux), &fintegral[offset * Nf]));
2845: PetscCall(PetscFEGeomRestoreChunk(fgeom, offset, numFaces, &chunkGeom));
2846: /* Cleanup data arrays */
2847: PetscCall(DMPlexRestoreFEGeom(coordField, pointIS, qGeom, PETSC_FEGEOM_BOUNDARY, &fgeom));
2848: PetscCall(PetscQuadratureDestroy(&qGeom));
2849: }
2850: PetscCall(PetscFree2(u, a));
2851: PetscCall(ISRestoreIndices(pointIS, &points));
2852: }
2853: PetscCall(DMDestroy(&plex));
2854: PetscCall(DMDestroy(&plexA));
2855: PetscFunctionReturn(PETSC_SUCCESS);
2856: }
2858: /*@
2859: DMPlexComputeBdIntegral - Form the integral over the specified boundary from the global input X using pointwise functions specified by the user
2861: Input Parameters:
2862: + dm - The mesh
2863: . X - Global input vector
2864: . label - The boundary `DMLabel`
2865: . numVals - The number of label values to use, or `PETSC_DETERMINE` for all values
2866: . vals - The label values to use, or NULL for all values
2867: . funcs - The functions to integrate along the boundary for each field
2868: - ctx - The application context
2870: Output Parameter:
2871: . integral - Integral for each field
2873: Level: developer
2875: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeIntegralFEM()`, `DMPlexComputeBdResidualFEM()`
2876: @*/
2877: 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)
2878: {
2879: Vec locX;
2880: PetscSection section;
2881: DMLabel depthLabel;
2882: IS facetIS;
2883: PetscInt dim, Nf, f, v;
2885: PetscFunctionBegin;
2889: if (vals) PetscAssertPointer(vals, 5);
2890: PetscAssertPointer(integral, 7);
2891: PetscCall(PetscLogEventBegin(DMPLEX_IntegralFEM, dm, 0, 0, 0));
2892: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
2893: PetscCall(DMGetDimension(dm, &dim));
2894: PetscCall(DMLabelGetStratumIS(depthLabel, dim - 1, &facetIS));
2895: /* Filter out ghost facets (SF leaves) so that each boundary facet is only
2896: counted on one rank. Without this, shared facets at partition boundaries
2897: are integrated on multiple ranks, causing double-counting after MPI sum. */
2898: if (facetIS) {
2899: PetscSF sf;
2900: PetscInt nleaves;
2901: const PetscInt *leaves;
2903: PetscCall(DMGetPointSF(dm, &sf));
2904: PetscCall(PetscSFGetGraph(sf, NULL, &nleaves, &leaves, NULL));
2905: if (nleaves > 0 && leaves) {
2906: IS leafIS, ownedFacetIS;
2908: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, nleaves, leaves, PETSC_USE_POINTER, &leafIS));
2909: PetscCall(ISDifference(facetIS, leafIS, &ownedFacetIS));
2910: PetscCall(ISDestroy(&leafIS));
2911: PetscCall(ISDestroy(&facetIS));
2912: facetIS = ownedFacetIS;
2913: }
2914: }
2915: PetscCall(DMGetLocalSection(dm, §ion));
2916: PetscCall(PetscSectionGetNumFields(section, &Nf));
2917: /* Get local solution with boundary values */
2918: PetscCall(DMGetLocalVector(dm, &locX));
2919: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_TRUE, locX, 0.0, NULL, NULL, NULL));
2920: PetscCall(DMGlobalToLocalBegin(dm, X, INSERT_VALUES, locX));
2921: PetscCall(DMGlobalToLocalEnd(dm, X, INSERT_VALUES, locX));
2922: /* Loop over label values */
2923: PetscCall(PetscArrayzero(integral, Nf));
2924: for (v = 0; v < numVals; ++v) {
2925: IS pointIS;
2926: PetscInt numFaces;
2927: PetscScalar *fintegral;
2929: PetscCall(DMLabelGetStratumIS(label, vals[v], &pointIS));
2930: if (!pointIS) continue; /* No points with that id on this process */
2931: {
2932: IS isectIS;
2934: /* TODO: Special cases of ISIntersect where it is quick to check a priori if one is a superset of the other */
2935: PetscCall(ISIntersect_Caching_Internal(facetIS, pointIS, &isectIS));
2936: PetscCall(ISDestroy(&pointIS));
2937: pointIS = isectIS;
2938: }
2939: PetscCall(ISGetLocalSize(pointIS, &numFaces));
2940: PetscCall(PetscCalloc1(numFaces * Nf, &fintegral));
2941: PetscCall(DMPlexComputeBdIntegral_Internal(dm, locX, pointIS, funcs, fintegral, ctx));
2942: /* Sum point contributions into integral */
2943: for (f = 0; f < Nf; ++f)
2944: for (PetscInt face = 0; face < numFaces; ++face) integral[f] += fintegral[face * Nf + f];
2945: PetscCall(PetscFree(fintegral));
2946: PetscCall(ISDestroy(&pointIS));
2947: }
2948: PetscCall(DMRestoreLocalVector(dm, &locX));
2949: PetscCall(ISDestroy(&facetIS));
2950: PetscCall(PetscLogEventEnd(DMPLEX_IntegralFEM, dm, 0, 0, 0));
2951: PetscFunctionReturn(PETSC_SUCCESS);
2952: }
2954: /*@
2955: DMPlexComputeInterpolatorNested - Form the local portion of the interpolation matrix from the coarse `DM` to a uniformly refined `DM`.
2957: Input Parameters:
2958: + dmc - The coarse mesh
2959: . dmf - The fine mesh
2960: . isRefined - Flag indicating regular refinement, rather than the same topology
2961: - ctx - The application context
2963: Output Parameter:
2964: . In - The interpolation matrix
2966: Level: developer
2968: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeInterpolatorGeneral()`
2969: @*/
2970: PetscErrorCode DMPlexComputeInterpolatorNested(DM dmc, DM dmf, PetscBool isRefined, Mat In, PetscCtx ctx)
2971: {
2972: DM_Plex *mesh = (DM_Plex *)dmc->data;
2973: const char *name = "Interpolator";
2974: PetscFE *feRef;
2975: PetscFV *fvRef;
2976: PetscSection fsection, fglobalSection;
2977: PetscSection csection, cglobalSection;
2978: PetscScalar *elemMat;
2979: PetscInt dim, Nf, f, fieldI, fieldJ, offsetI, offsetJ, cStart, cEnd, c;
2980: PetscInt cTotDim = 0, rTotDim = 0;
2982: PetscFunctionBegin;
2983: PetscCall(PetscLogEventBegin(DMPLEX_InterpolatorFEM, dmc, dmf, 0, 0));
2984: PetscCall(DMGetDimension(dmf, &dim));
2985: PetscCall(DMGetLocalSection(dmf, &fsection));
2986: PetscCall(DMGetGlobalSection(dmf, &fglobalSection));
2987: PetscCall(DMGetLocalSection(dmc, &csection));
2988: PetscCall(DMGetGlobalSection(dmc, &cglobalSection));
2989: PetscCall(PetscSectionGetNumFields(fsection, &Nf));
2990: PetscCall(DMPlexGetSimplexOrBoxCells(dmc, 0, &cStart, &cEnd));
2991: PetscCall(PetscCalloc2(Nf, &feRef, Nf, &fvRef));
2992: for (f = 0; f < Nf; ++f) {
2993: PetscObject obj, objc;
2994: PetscClassId id, idc;
2995: PetscInt rNb = 0, Nc = 0, cNb = 0;
2997: PetscCall(DMGetField(dmf, f, NULL, &obj));
2998: PetscCall(PetscObjectGetClassId(obj, &id));
2999: if (id == PETSCFE_CLASSID) {
3000: PetscFE fe = (PetscFE)obj;
3002: if (isRefined) PetscCall(PetscFERefine(fe, &feRef[f]));
3003: else {
3004: PetscCall(PetscObjectReference((PetscObject)fe));
3005: feRef[f] = fe;
3006: }
3007: PetscCall(PetscFEGetDimension(feRef[f], &rNb));
3008: PetscCall(PetscFEGetNumComponents(fe, &Nc));
3009: } else if (id == PETSCFV_CLASSID) {
3010: PetscFV fv = (PetscFV)obj;
3011: PetscDualSpace Q;
3013: if (isRefined) PetscCall(PetscFVRefine(fv, &fvRef[f]));
3014: else {
3015: PetscCall(PetscObjectReference((PetscObject)fv));
3016: fvRef[f] = fv;
3017: }
3018: PetscCall(PetscFVGetDualSpace(fvRef[f], &Q));
3019: PetscCall(PetscDualSpaceGetDimension(Q, &rNb));
3020: PetscCall(PetscFVGetDualSpace(fv, &Q));
3021: PetscCall(PetscFVGetNumComponents(fv, &Nc));
3022: }
3023: PetscCall(DMGetField(dmc, f, NULL, &objc));
3024: PetscCall(PetscObjectGetClassId(objc, &idc));
3025: if (idc == PETSCFE_CLASSID) {
3026: PetscFE fe = (PetscFE)objc;
3028: PetscCall(PetscFEGetDimension(fe, &cNb));
3029: } else if (id == PETSCFV_CLASSID) {
3030: PetscFV fv = (PetscFV)obj;
3031: PetscDualSpace Q;
3033: PetscCall(PetscFVGetDualSpace(fv, &Q));
3034: PetscCall(PetscDualSpaceGetDimension(Q, &cNb));
3035: }
3036: rTotDim += rNb;
3037: cTotDim += cNb;
3038: }
3039: PetscCall(PetscMalloc1(rTotDim * cTotDim, &elemMat));
3040: PetscCall(PetscArrayzero(elemMat, rTotDim * cTotDim));
3041: for (fieldI = 0, offsetI = 0; fieldI < Nf; ++fieldI) {
3042: PetscDualSpace Qref;
3043: PetscQuadrature f;
3044: const PetscReal *qpoints, *qweights;
3045: PetscReal *points;
3046: PetscInt npoints = 0, Nc, Np, fpdim, i, k, p, d;
3048: /* Compose points from all dual basis functionals */
3049: if (feRef[fieldI]) {
3050: PetscCall(PetscFEGetDualSpace(feRef[fieldI], &Qref));
3051: PetscCall(PetscFEGetNumComponents(feRef[fieldI], &Nc));
3052: } else {
3053: PetscCall(PetscFVGetDualSpace(fvRef[fieldI], &Qref));
3054: PetscCall(PetscFVGetNumComponents(fvRef[fieldI], &Nc));
3055: }
3056: PetscCall(PetscDualSpaceGetDimension(Qref, &fpdim));
3057: for (i = 0; i < fpdim; ++i) {
3058: PetscCall(PetscDualSpaceGetFunctional(Qref, i, &f));
3059: PetscCall(PetscQuadratureGetData(f, NULL, NULL, &Np, NULL, NULL));
3060: npoints += Np;
3061: }
3062: PetscCall(PetscMalloc1(npoints * dim, &points));
3063: for (i = 0, k = 0; i < fpdim; ++i) {
3064: PetscCall(PetscDualSpaceGetFunctional(Qref, i, &f));
3065: PetscCall(PetscQuadratureGetData(f, NULL, NULL, &Np, &qpoints, NULL));
3066: for (p = 0; p < Np; ++p, ++k)
3067: for (d = 0; d < dim; ++d) points[k * dim + d] = qpoints[p * dim + d];
3068: }
3070: for (fieldJ = 0, offsetJ = 0; fieldJ < Nf; ++fieldJ) {
3071: PetscObject obj;
3072: PetscClassId id;
3073: PetscInt NcJ = 0, cpdim = 0, j, qNc;
3075: PetscCall(DMGetField(dmc, fieldJ, NULL, &obj));
3076: PetscCall(PetscObjectGetClassId(obj, &id));
3077: if (id == PETSCFE_CLASSID) {
3078: PetscFE fe = (PetscFE)obj;
3079: PetscTabulation T = NULL;
3081: /* Evaluate basis at points */
3082: PetscCall(PetscFEGetNumComponents(fe, &NcJ));
3083: PetscCall(PetscFEGetDimension(fe, &cpdim));
3084: /* For now, fields only interpolate themselves */
3085: if (fieldI == fieldJ) {
3086: 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);
3087: PetscCall(PetscFECreateTabulation(fe, 1, npoints, points, 0, &T));
3088: for (i = 0, k = 0; i < fpdim; ++i) {
3089: PetscCall(PetscDualSpaceGetFunctional(Qref, i, &f));
3090: PetscCall(PetscQuadratureGetData(f, NULL, &qNc, &Np, NULL, &qweights));
3091: 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);
3092: for (p = 0; p < Np; ++p, ++k) {
3093: for (j = 0; j < cpdim; ++j) {
3094: /*
3095: cTotDim: Total columns in element interpolation matrix, sum of number of dual basis functionals in each field
3096: offsetI, offsetJ: Offsets into the larger element interpolation matrix for different fields
3097: fpdim, i, cpdim, j: Dofs for fine and coarse grids, correspond to dual space basis functionals
3098: qNC, Nc, Ncj, c: Number of components in this field
3099: Np, p: Number of quad points in the fine grid functional i
3100: k: i*Np + p, overall point number for the interpolation
3101: */
3102: 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];
3103: }
3104: }
3105: }
3106: PetscCall(PetscTabulationDestroy(&T));
3107: }
3108: } else if (id == PETSCFV_CLASSID) {
3109: PetscFV fv = (PetscFV)obj;
3111: /* Evaluate constant function at points */
3112: PetscCall(PetscFVGetNumComponents(fv, &NcJ));
3113: cpdim = 1;
3114: /* For now, fields only interpolate themselves */
3115: if (fieldI == fieldJ) {
3116: 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);
3117: for (i = 0, k = 0; i < fpdim; ++i) {
3118: PetscCall(PetscDualSpaceGetFunctional(Qref, i, &f));
3119: PetscCall(PetscQuadratureGetData(f, NULL, &qNc, &Np, NULL, &qweights));
3120: 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);
3121: for (p = 0; p < Np; ++p, ++k) {
3122: for (j = 0; j < cpdim; ++j) {
3123: for (c = 0; c < Nc; ++c) elemMat[(offsetI + i) * cTotDim + offsetJ + j] += 1.0 * qweights[p * qNc + c];
3124: }
3125: }
3126: }
3127: }
3128: }
3129: offsetJ += cpdim;
3130: }
3131: offsetI += fpdim;
3132: PetscCall(PetscFree(points));
3133: }
3134: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(0, name, rTotDim, cTotDim, elemMat));
3135: /* Preallocate matrix */
3136: {
3137: Mat preallocator;
3138: PetscScalar *vals;
3139: PetscInt *cellCIndices, *cellFIndices;
3140: PetscInt locRows, locCols, cell;
3142: PetscCall(MatGetLocalSize(In, &locRows, &locCols));
3143: PetscCall(MatCreate(PetscObjectComm((PetscObject)In), &preallocator));
3144: PetscCall(MatSetType(preallocator, MATPREALLOCATOR));
3145: PetscCall(MatSetSizes(preallocator, locRows, locCols, PETSC_DETERMINE, PETSC_DETERMINE));
3146: PetscCall(MatSetUp(preallocator));
3147: PetscCall(PetscCalloc3(rTotDim * cTotDim, &vals, cTotDim, &cellCIndices, rTotDim, &cellFIndices));
3148: if (locRows || locCols) {
3149: for (cell = cStart; cell < cEnd; ++cell) {
3150: if (isRefined) {
3151: PetscCall(DMPlexMatGetClosureIndicesRefined(dmf, fsection, fglobalSection, dmc, csection, cglobalSection, cell, cellCIndices, cellFIndices));
3152: PetscCall(MatSetValues(preallocator, rTotDim, cellFIndices, cTotDim, cellCIndices, vals, INSERT_VALUES));
3153: } else {
3154: PetscCall(DMPlexMatSetClosureGeneral(dmf, fsection, fglobalSection, PETSC_FALSE, dmc, csection, cglobalSection, PETSC_FALSE, preallocator, cell, vals, INSERT_VALUES));
3155: }
3156: }
3157: }
3158: PetscCall(PetscFree3(vals, cellCIndices, cellFIndices));
3159: PetscCall(MatAssemblyBegin(preallocator, MAT_FINAL_ASSEMBLY));
3160: PetscCall(MatAssemblyEnd(preallocator, MAT_FINAL_ASSEMBLY));
3161: PetscCall(MatPreallocatorPreallocate(preallocator, PETSC_TRUE, In));
3162: PetscCall(MatDestroy(&preallocator));
3163: }
3164: /* Fill matrix */
3165: PetscCall(MatZeroEntries(In));
3166: for (c = cStart; c < cEnd; ++c) {
3167: if (isRefined) {
3168: PetscCall(DMPlexMatSetClosureRefined(dmf, fsection, fglobalSection, dmc, csection, cglobalSection, In, c, elemMat, INSERT_VALUES));
3169: } else {
3170: PetscCall(DMPlexMatSetClosureGeneral(dmf, fsection, fglobalSection, PETSC_FALSE, dmc, csection, cglobalSection, PETSC_FALSE, In, c, elemMat, INSERT_VALUES));
3171: }
3172: }
3173: for (f = 0; f < Nf; ++f) PetscCall(PetscFEDestroy(&feRef[f]));
3174: PetscCall(PetscFree2(feRef, fvRef));
3175: PetscCall(PetscFree(elemMat));
3176: PetscCall(MatAssemblyBegin(In, MAT_FINAL_ASSEMBLY));
3177: PetscCall(MatAssemblyEnd(In, MAT_FINAL_ASSEMBLY));
3178: if (mesh->printFEM > 1) {
3179: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)In), "%s:\n", name));
3180: PetscCall(MatFilter(In, 1.0e-10, PETSC_FALSE, PETSC_FALSE));
3181: PetscCall(MatView(In, NULL));
3182: }
3183: PetscCall(PetscLogEventEnd(DMPLEX_InterpolatorFEM, dmc, dmf, 0, 0));
3184: PetscFunctionReturn(PETSC_SUCCESS);
3185: }
3187: /*@
3188: DMPlexComputeMassMatrixNested - Form the local portion of the mass matrix from a coarse `DM` to a nested fine `DM`.
3190: Collective
3192: Input Parameters:
3193: + dmc - the coarse mesh
3194: . dmf - the fine mesh
3195: - ctx - the application context
3197: Output Parameter:
3198: . mass - the mass matrix
3200: Level: developer
3202: Note:
3203: This routine is not implemented and currently raises `PETSC_ERR_SUP`.
3205: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeMassMatrixGeneral()`, `DMPlexComputeInterpolatorNested()`
3206: @*/
3207: PetscErrorCode DMPlexComputeMassMatrixNested(DM dmc, DM dmf, Mat mass, PetscCtx ctx)
3208: {
3209: SETERRQ(PetscObjectComm((PetscObject)dmc), PETSC_ERR_SUP, "Laziness");
3210: }
3212: /*@
3213: DMPlexComputeInterpolatorGeneral - Form the local portion of the interpolation matrix from the coarse `DM` to a non-nested fine `DM`.
3215: Input Parameters:
3216: + dmf - The fine mesh
3217: . dmc - The coarse mesh
3218: - ctx - The application context
3220: Output Parameter:
3221: . In - The interpolation matrix
3223: Level: developer
3225: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeInterpolatorNested()`
3226: @*/
3227: PetscErrorCode DMPlexComputeInterpolatorGeneral(DM dmc, DM dmf, Mat In, PetscCtx ctx)
3228: {
3229: DM_Plex *mesh = (DM_Plex *)dmf->data;
3230: const char *name = "Interpolator";
3231: PetscDS prob;
3232: Mat interp;
3233: PetscSection fsection, globalFSection;
3234: PetscSection csection, globalCSection;
3235: PetscInt locRows, locCols;
3236: PetscReal *x, *v0, *J, *invJ, detJ;
3237: PetscReal *v0c, *Jc, *invJc, detJc;
3238: PetscScalar *elemMat;
3239: PetscInt dim, Nf, field, totDim, cStart, cEnd, cell, ccell, s;
3241: PetscFunctionBegin;
3242: PetscCall(PetscLogEventBegin(DMPLEX_InterpolatorFEM, dmc, dmf, 0, 0));
3243: PetscCall(DMGetCoordinateDim(dmc, &dim));
3244: PetscCall(DMGetDS(dmc, &prob));
3245: PetscCall(PetscDSGetWorkspace(prob, &x, NULL, NULL, NULL, NULL));
3246: PetscCall(PetscDSGetNumFields(prob, &Nf));
3247: PetscCall(PetscMalloc3(dim, &v0, dim * dim, &J, dim * dim, &invJ));
3248: PetscCall(PetscMalloc3(dim, &v0c, dim * dim, &Jc, dim * dim, &invJc));
3249: PetscCall(DMGetLocalSection(dmf, &fsection));
3250: PetscCall(DMGetGlobalSection(dmf, &globalFSection));
3251: PetscCall(DMGetLocalSection(dmc, &csection));
3252: PetscCall(DMGetGlobalSection(dmc, &globalCSection));
3253: PetscCall(DMPlexGetSimplexOrBoxCells(dmf, 0, &cStart, &cEnd));
3254: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
3255: PetscCall(PetscMalloc1(totDim, &elemMat));
3257: PetscCall(MatGetLocalSize(In, &locRows, &locCols));
3258: PetscCall(MatCreate(PetscObjectComm((PetscObject)In), &interp));
3259: PetscCall(MatSetType(interp, MATPREALLOCATOR));
3260: PetscCall(MatSetSizes(interp, locRows, locCols, PETSC_DETERMINE, PETSC_DETERMINE));
3261: PetscCall(MatSetUp(interp));
3262: for (s = 0; s < 2; ++s) {
3263: for (field = 0; field < Nf; ++field) {
3264: PetscObject obj;
3265: PetscClassId id;
3266: PetscDualSpace Q = NULL;
3267: PetscTabulation T = NULL;
3268: PetscQuadrature f;
3269: const PetscReal *qpoints, *qweights;
3270: PetscInt Nc, qNc, Np, fpdim, off, i, d;
3272: PetscCall(PetscDSGetFieldOffset(prob, field, &off));
3273: PetscCall(PetscDSGetDiscretization(prob, field, &obj));
3274: PetscCall(PetscObjectGetClassId(obj, &id));
3275: if (id == PETSCFE_CLASSID) {
3276: PetscFE fe = (PetscFE)obj;
3278: PetscCall(PetscFEGetDualSpace(fe, &Q));
3279: PetscCall(PetscFEGetNumComponents(fe, &Nc));
3280: if (s) PetscCall(PetscFECreateTabulation(fe, 1, 1, x, 0, &T));
3281: } else if (id == PETSCFV_CLASSID) {
3282: PetscFV fv = (PetscFV)obj;
3284: PetscCall(PetscFVGetDualSpace(fv, &Q));
3285: Nc = 1;
3286: } else SETERRQ(PetscObjectComm((PetscObject)dmc), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, field);
3287: PetscCall(PetscDualSpaceGetDimension(Q, &fpdim));
3288: /* For each fine grid cell */
3289: for (cell = cStart; cell < cEnd; ++cell) {
3290: PetscInt *findices, *cindices;
3291: PetscInt numFIndices, numCIndices;
3293: PetscCall(DMPlexGetClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
3294: PetscCall(DMPlexComputeCellGeometryFEM(dmf, cell, NULL, v0, J, invJ, &detJ));
3295: PetscCheck(numFIndices == totDim, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of fine indices %" PetscInt_FMT " != %" PetscInt_FMT " dual basis vecs", numFIndices, totDim);
3296: for (i = 0; i < fpdim; ++i) {
3297: Vec pointVec;
3298: PetscScalar *pV;
3299: PetscSF coarseCellSF = NULL;
3300: const PetscSFNode *coarseCells;
3301: PetscInt numCoarseCells, cpdim, row = findices[i + off], q, c, j;
3303: /* Get points from the dual basis functional quadrature */
3304: PetscCall(PetscDualSpaceGetFunctional(Q, i, &f));
3305: PetscCall(PetscQuadratureGetData(f, NULL, &qNc, &Np, &qpoints, &qweights));
3306: 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);
3307: PetscCall(VecCreateSeq(PETSC_COMM_SELF, Np * dim, &pointVec));
3308: PetscCall(VecSetBlockSize(pointVec, dim));
3309: PetscCall(VecGetArray(pointVec, &pV));
3310: for (q = 0; q < Np; ++q) {
3311: const PetscReal xi0[3] = {-1., -1., -1.};
3313: /* Transform point to real space */
3314: CoordinatesRefToReal(dim, dim, xi0, v0, J, &qpoints[q * dim], x);
3315: for (d = 0; d < dim; ++d) pV[q * dim + d] = x[d];
3316: }
3317: PetscCall(VecRestoreArray(pointVec, &pV));
3318: /* Get set of coarse cells that overlap points (would like to group points by coarse cell) */
3319: /* OPT: Read this out from preallocation information */
3320: PetscCall(DMLocatePoints(dmc, pointVec, DM_POINTLOCATION_NEAREST, &coarseCellSF));
3321: /* Update preallocation info */
3322: PetscCall(PetscSFGetGraph(coarseCellSF, NULL, &numCoarseCells, NULL, &coarseCells));
3323: PetscCheck(numCoarseCells == Np, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Not all closure points located");
3324: PetscCall(VecGetArray(pointVec, &pV));
3325: for (ccell = 0; ccell < numCoarseCells; ++ccell) {
3326: PetscReal pVReal[3];
3327: const PetscReal xi0[3] = {-1., -1., -1.};
3329: PetscCall(DMPlexGetClosureIndices(dmc, csection, globalCSection, coarseCells[ccell].index, PETSC_FALSE, &numCIndices, &cindices, NULL, NULL));
3330: if (id == PETSCFE_CLASSID) PetscCall(PetscFEGetDimension((PetscFE)obj, &cpdim));
3331: else cpdim = 1;
3333: if (s) {
3334: /* Transform points from real space to coarse reference space */
3335: PetscCall(DMPlexComputeCellGeometryFEM(dmc, coarseCells[ccell].index, NULL, v0c, Jc, invJc, &detJc));
3336: for (d = 0; d < dim; ++d) pVReal[d] = PetscRealPart(pV[ccell * dim + d]);
3337: CoordinatesRealToRef(dim, dim, xi0, v0c, invJc, pVReal, x);
3339: if (id == PETSCFE_CLASSID) {
3340: /* Evaluate coarse basis on contained point */
3341: PetscCall(PetscFEComputeTabulation((PetscFE)obj, 1, x, 0, T));
3342: PetscCall(PetscArrayzero(elemMat, cpdim));
3343: /* Get elemMat entries by multiplying by weight */
3344: for (j = 0; j < cpdim; ++j) {
3345: for (c = 0; c < Nc; ++c) elemMat[j] += T->T[0][j * Nc + c] * qweights[ccell * qNc + c];
3346: }
3347: } else {
3348: for (j = 0; j < cpdim; ++j) {
3349: for (c = 0; c < Nc; ++c) elemMat[j] += 1.0 * qweights[ccell * qNc + c];
3350: }
3351: }
3352: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, 1, numCIndices, elemMat));
3353: }
3354: /* Update interpolator */
3355: PetscCheck(numCIndices == totDim, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of element matrix columns %" PetscInt_FMT " != %" PetscInt_FMT, numCIndices, totDim);
3356: PetscCall(MatSetValues(interp, 1, &row, cpdim, &cindices[off], elemMat, INSERT_VALUES));
3357: PetscCall(DMPlexRestoreClosureIndices(dmc, csection, globalCSection, coarseCells[ccell].index, PETSC_FALSE, &numCIndices, &cindices, NULL, NULL));
3358: }
3359: PetscCall(VecRestoreArray(pointVec, &pV));
3360: PetscCall(PetscSFDestroy(&coarseCellSF));
3361: PetscCall(VecDestroy(&pointVec));
3362: }
3363: PetscCall(DMPlexRestoreClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
3364: }
3365: if (s && id == PETSCFE_CLASSID) PetscCall(PetscTabulationDestroy(&T));
3366: }
3367: if (!s) {
3368: PetscCall(MatAssemblyBegin(interp, MAT_FINAL_ASSEMBLY));
3369: PetscCall(MatAssemblyEnd(interp, MAT_FINAL_ASSEMBLY));
3370: PetscCall(MatPreallocatorPreallocate(interp, PETSC_TRUE, In));
3371: PetscCall(MatDestroy(&interp));
3372: interp = In;
3373: }
3374: }
3375: PetscCall(PetscFree3(v0, J, invJ));
3376: PetscCall(PetscFree3(v0c, Jc, invJc));
3377: PetscCall(PetscFree(elemMat));
3378: PetscCall(MatAssemblyBegin(In, MAT_FINAL_ASSEMBLY));
3379: PetscCall(MatAssemblyEnd(In, MAT_FINAL_ASSEMBLY));
3380: PetscCall(PetscLogEventEnd(DMPLEX_InterpolatorFEM, dmc, dmf, 0, 0));
3381: PetscFunctionReturn(PETSC_SUCCESS);
3382: }
3384: /*@
3385: DMPlexComputeMassMatrixGeneral - Form the local portion of the mass matrix from the coarse `DM` to a non-nested fine `DM`.
3387: Input Parameters:
3388: + dmf - The fine mesh
3389: . dmc - The coarse mesh
3390: - ctx - The application context
3392: Output Parameter:
3393: . mass - The mass matrix
3395: Level: developer
3397: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeMassMatrixNested()`, `DMPlexComputeInterpolatorNested()`, `DMPlexComputeInterpolatorGeneral()`
3398: @*/
3399: PetscErrorCode DMPlexComputeMassMatrixGeneral(DM dmc, DM dmf, Mat mass, PetscCtx ctx)
3400: {
3401: DM_Plex *mesh = (DM_Plex *)dmf->data;
3402: const char *name = "Mass Matrix";
3403: PetscDS prob;
3404: PetscSection fsection, csection, globalFSection, globalCSection;
3405: PetscHSetIJ ht;
3406: PetscLayout rLayout;
3407: PetscInt *dnz, *onz;
3408: PetscInt locRows, rStart, rEnd;
3409: PetscReal *x, *v0, *J, *invJ, detJ;
3410: PetscReal *v0c, *Jc, *invJc, detJc;
3411: PetscScalar *elemMat;
3412: PetscInt dim, Nf, field, totDim, cStart, cEnd, cell, ccell;
3414: PetscFunctionBegin;
3415: PetscCall(DMGetCoordinateDim(dmc, &dim));
3416: PetscCall(DMGetDS(dmc, &prob));
3417: PetscCall(PetscDSGetWorkspace(prob, &x, NULL, NULL, NULL, NULL));
3418: PetscCall(PetscDSGetNumFields(prob, &Nf));
3419: PetscCall(PetscMalloc3(dim, &v0, dim * dim, &J, dim * dim, &invJ));
3420: PetscCall(PetscMalloc3(dim, &v0c, dim * dim, &Jc, dim * dim, &invJc));
3421: PetscCall(DMGetLocalSection(dmf, &fsection));
3422: PetscCall(DMGetGlobalSection(dmf, &globalFSection));
3423: PetscCall(DMGetLocalSection(dmc, &csection));
3424: PetscCall(DMGetGlobalSection(dmc, &globalCSection));
3425: PetscCall(DMPlexGetHeightStratum(dmf, 0, &cStart, &cEnd));
3426: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
3427: PetscCall(PetscMalloc1(totDim, &elemMat));
3429: PetscCall(MatGetLocalSize(mass, &locRows, NULL));
3430: PetscCall(PetscLayoutCreate(PetscObjectComm((PetscObject)mass), &rLayout));
3431: PetscCall(PetscLayoutSetLocalSize(rLayout, locRows));
3432: PetscCall(PetscLayoutSetBlockSize(rLayout, 1));
3433: PetscCall(PetscLayoutSetUp(rLayout));
3434: PetscCall(PetscLayoutGetRange(rLayout, &rStart, &rEnd));
3435: PetscCall(PetscLayoutDestroy(&rLayout));
3436: PetscCall(PetscCalloc2(locRows, &dnz, locRows, &onz));
3437: PetscCall(PetscHSetIJCreate(&ht));
3438: for (field = 0; field < Nf; ++field) {
3439: PetscObject obj;
3440: PetscClassId id;
3441: PetscQuadrature quad;
3442: const PetscReal *qpoints;
3443: PetscInt Nq, Nc, i, d;
3445: PetscCall(PetscDSGetDiscretization(prob, field, &obj));
3446: PetscCall(PetscObjectGetClassId(obj, &id));
3447: if (id == PETSCFE_CLASSID) PetscCall(PetscFEGetQuadrature((PetscFE)obj, &quad));
3448: else PetscCall(PetscFVGetQuadrature((PetscFV)obj, &quad));
3449: PetscCall(PetscQuadratureGetData(quad, NULL, &Nc, &Nq, &qpoints, NULL));
3450: /* For each fine grid cell */
3451: for (cell = cStart; cell < cEnd; ++cell) {
3452: Vec pointVec;
3453: PetscScalar *pV;
3454: PetscSF coarseCellSF = NULL;
3455: const PetscSFNode *coarseCells;
3456: PetscInt numCoarseCells, q, c;
3457: PetscInt *findices, *cindices;
3458: PetscInt numFIndices, numCIndices;
3460: PetscCall(DMPlexGetClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
3461: PetscCall(DMPlexComputeCellGeometryFEM(dmf, cell, NULL, v0, J, invJ, &detJ));
3462: /* Get points from the quadrature */
3463: PetscCall(VecCreateSeq(PETSC_COMM_SELF, Nq * dim, &pointVec));
3464: PetscCall(VecSetBlockSize(pointVec, dim));
3465: PetscCall(VecGetArray(pointVec, &pV));
3466: for (q = 0; q < Nq; ++q) {
3467: const PetscReal xi0[3] = {-1., -1., -1.};
3469: /* Transform point to real space */
3470: CoordinatesRefToReal(dim, dim, xi0, v0, J, &qpoints[q * dim], x);
3471: for (d = 0; d < dim; ++d) pV[q * dim + d] = x[d];
3472: }
3473: PetscCall(VecRestoreArray(pointVec, &pV));
3474: /* Get set of coarse cells that overlap points (would like to group points by coarse cell) */
3475: PetscCall(DMLocatePoints(dmc, pointVec, DM_POINTLOCATION_NEAREST, &coarseCellSF));
3476: PetscCall(PetscSFViewFromOptions(coarseCellSF, NULL, "-interp_sf_view"));
3477: /* Update preallocation info */
3478: PetscCall(PetscSFGetGraph(coarseCellSF, NULL, &numCoarseCells, NULL, &coarseCells));
3479: PetscCheck(numCoarseCells == Nq, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Not all closure points located");
3480: {
3481: PetscHashIJKey key;
3482: PetscBool missing;
3484: for (i = 0; i < numFIndices; ++i) {
3485: key.i = findices[i];
3486: if (key.i >= 0) {
3487: /* Get indices for coarse elements */
3488: for (ccell = 0; ccell < numCoarseCells; ++ccell) {
3489: PetscCall(DMPlexGetClosureIndices(dmc, csection, globalCSection, coarseCells[ccell].index, PETSC_FALSE, &numCIndices, &cindices, NULL, NULL));
3490: for (c = 0; c < numCIndices; ++c) {
3491: key.j = cindices[c];
3492: if (key.j < 0) continue;
3493: PetscCall(PetscHSetIJQueryAdd(ht, key, &missing));
3494: if (missing) {
3495: if (key.j >= rStart && key.j < rEnd) ++dnz[key.i - rStart];
3496: else ++onz[key.i - rStart];
3497: }
3498: }
3499: PetscCall(DMPlexRestoreClosureIndices(dmc, csection, globalCSection, coarseCells[ccell].index, PETSC_FALSE, &numCIndices, &cindices, NULL, NULL));
3500: }
3501: }
3502: }
3503: }
3504: PetscCall(PetscSFDestroy(&coarseCellSF));
3505: PetscCall(VecDestroy(&pointVec));
3506: PetscCall(DMPlexRestoreClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
3507: }
3508: }
3509: PetscCall(PetscHSetIJDestroy(&ht));
3510: PetscCall(MatXAIJSetPreallocation(mass, 1, dnz, onz, NULL, NULL));
3511: PetscCall(MatSetOption(mass, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE));
3512: PetscCall(PetscFree2(dnz, onz));
3513: for (field = 0; field < Nf; ++field) {
3514: PetscObject obj;
3515: PetscClassId id;
3516: PetscTabulation T, Tfine;
3517: PetscQuadrature quad;
3518: const PetscReal *qpoints, *qweights;
3519: PetscInt Nq, Nc, i, d;
3521: PetscCall(PetscDSGetDiscretization(prob, field, &obj));
3522: PetscCall(PetscObjectGetClassId(obj, &id));
3523: if (id == PETSCFE_CLASSID) {
3524: PetscCall(PetscFEGetQuadrature((PetscFE)obj, &quad));
3525: PetscCall(PetscFEGetCellTabulation((PetscFE)obj, 1, &Tfine));
3526: PetscCall(PetscFECreateTabulation((PetscFE)obj, 1, 1, x, 0, &T));
3527: } else {
3528: PetscCall(PetscFVGetQuadrature((PetscFV)obj, &quad));
3529: }
3530: PetscCall(PetscQuadratureGetData(quad, NULL, &Nc, &Nq, &qpoints, &qweights));
3531: /* For each fine grid cell */
3532: for (cell = cStart; cell < cEnd; ++cell) {
3533: Vec pointVec;
3534: PetscScalar *pV;
3535: PetscSF coarseCellSF = NULL;
3536: const PetscSFNode *coarseCells;
3537: PetscInt numCoarseCells, cpdim, q, c, j;
3538: PetscInt *findices, *cindices;
3539: PetscInt numFIndices, numCIndices;
3541: PetscCall(DMPlexGetClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
3542: PetscCall(DMPlexComputeCellGeometryFEM(dmf, cell, NULL, v0, J, invJ, &detJ));
3543: /* Get points from the quadrature */
3544: PetscCall(VecCreateSeq(PETSC_COMM_SELF, Nq * dim, &pointVec));
3545: PetscCall(VecSetBlockSize(pointVec, dim));
3546: PetscCall(VecGetArray(pointVec, &pV));
3547: for (q = 0; q < Nq; ++q) {
3548: const PetscReal xi0[3] = {-1., -1., -1.};
3550: /* Transform point to real space */
3551: CoordinatesRefToReal(dim, dim, xi0, v0, J, &qpoints[q * dim], x);
3552: for (d = 0; d < dim; ++d) pV[q * dim + d] = x[d];
3553: }
3554: PetscCall(VecRestoreArray(pointVec, &pV));
3555: /* Get set of coarse cells that overlap points (would like to group points by coarse cell) */
3556: PetscCall(DMLocatePoints(dmc, pointVec, DM_POINTLOCATION_NEAREST, &coarseCellSF));
3557: /* Update matrix */
3558: PetscCall(PetscSFGetGraph(coarseCellSF, NULL, &numCoarseCells, NULL, &coarseCells));
3559: PetscCheck(numCoarseCells == Nq, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Not all closure points located");
3560: PetscCall(VecGetArray(pointVec, &pV));
3561: for (ccell = 0; ccell < numCoarseCells; ++ccell) {
3562: PetscReal pVReal[3];
3563: const PetscReal xi0[3] = {-1., -1., -1.};
3565: PetscCall(DMPlexGetClosureIndices(dmc, csection, globalCSection, coarseCells[ccell].index, PETSC_FALSE, &numCIndices, &cindices, NULL, NULL));
3566: /* Transform points from real space to coarse reference space */
3567: PetscCall(DMPlexComputeCellGeometryFEM(dmc, coarseCells[ccell].index, NULL, v0c, Jc, invJc, &detJc));
3568: for (d = 0; d < dim; ++d) pVReal[d] = PetscRealPart(pV[ccell * dim + d]);
3569: CoordinatesRealToRef(dim, dim, xi0, v0c, invJc, pVReal, x);
3571: if (id == PETSCFE_CLASSID) {
3572: PetscFE fe = (PetscFE)obj;
3574: /* Evaluate coarse basis on contained point */
3575: PetscCall(PetscFEGetDimension(fe, &cpdim));
3576: PetscCall(PetscFEComputeTabulation(fe, 1, x, 0, T));
3577: /* Get elemMat entries by multiplying by weight */
3578: for (i = 0; i < numFIndices; ++i) {
3579: PetscCall(PetscArrayzero(elemMat, cpdim));
3580: for (j = 0; j < cpdim; ++j) {
3581: 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;
3582: }
3583: /* Update interpolator */
3584: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, 1, numCIndices, elemMat));
3585: PetscCheck(numCIndices == cpdim, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of element matrix columns %" PetscInt_FMT " != %" PetscInt_FMT, numCIndices, cpdim);
3586: PetscCall(MatSetValues(mass, 1, &findices[i], numCIndices, cindices, elemMat, ADD_VALUES));
3587: }
3588: } else {
3589: cpdim = 1;
3590: for (i = 0; i < numFIndices; ++i) {
3591: PetscCall(PetscArrayzero(elemMat, cpdim));
3592: for (j = 0; j < cpdim; ++j) {
3593: for (c = 0; c < Nc; ++c) elemMat[j] += 1.0 * 1.0 * qweights[ccell * Nc + c] * detJ;
3594: }
3595: /* Update interpolator */
3596: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, 1, numCIndices, elemMat));
3597: 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));
3598: PetscCheck(numCIndices == cpdim, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of element matrix columns %" PetscInt_FMT " != %" PetscInt_FMT, numCIndices, cpdim);
3599: PetscCall(MatSetValues(mass, 1, &findices[i], numCIndices, cindices, elemMat, ADD_VALUES));
3600: }
3601: }
3602: PetscCall(DMPlexRestoreClosureIndices(dmc, csection, globalCSection, coarseCells[ccell].index, PETSC_FALSE, &numCIndices, &cindices, NULL, NULL));
3603: }
3604: PetscCall(VecRestoreArray(pointVec, &pV));
3605: PetscCall(PetscSFDestroy(&coarseCellSF));
3606: PetscCall(VecDestroy(&pointVec));
3607: PetscCall(DMPlexRestoreClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
3608: }
3609: if (id == PETSCFE_CLASSID) PetscCall(PetscTabulationDestroy(&T));
3610: }
3611: PetscCall(PetscFree3(v0, J, invJ));
3612: PetscCall(PetscFree3(v0c, Jc, invJc));
3613: PetscCall(PetscFree(elemMat));
3614: PetscCall(MatAssemblyBegin(mass, MAT_FINAL_ASSEMBLY));
3615: PetscCall(MatAssemblyEnd(mass, MAT_FINAL_ASSEMBLY));
3616: PetscFunctionReturn(PETSC_SUCCESS);
3617: }
3619: /*@
3620: DMPlexComputeInjectorFEM - Compute a mapping from coarse unknowns to fine unknowns
3622: Input Parameters:
3623: + dmc - The coarse mesh
3624: . dmf - The fine mesh
3625: - ctx - The application context
3627: Output Parameter:
3628: . sc - The mapping
3630: Level: developer
3632: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexComputeInterpolatorNested()`
3633: @*/
3634: PetscErrorCode DMPlexComputeInjectorFEM(DM dmc, DM dmf, VecScatter *sc, PetscCtx ctx)
3635: {
3636: PetscDS prob;
3637: PetscFE *feRef;
3638: PetscFV *fvRef;
3639: Vec fv, cv;
3640: IS fis, cis;
3641: PetscSection fsection, fglobalSection, csection, cglobalSection;
3642: PetscInt *cmap, *cellCIndices, *cellFIndices, *cindices, *findices;
3643: PetscInt cTotDim, fTotDim = 0, Nf, f, field, cStart, cEnd, c, dim, d, startC, endC, offsetC, offsetF, m;
3644: PetscBool *needAvg;
3646: PetscFunctionBegin;
3647: PetscCall(PetscLogEventBegin(DMPLEX_InjectorFEM, dmc, dmf, 0, 0));
3648: PetscCall(DMGetDimension(dmf, &dim));
3649: PetscCall(DMGetLocalSection(dmf, &fsection));
3650: PetscCall(DMGetGlobalSection(dmf, &fglobalSection));
3651: PetscCall(DMGetLocalSection(dmc, &csection));
3652: PetscCall(DMGetGlobalSection(dmc, &cglobalSection));
3653: PetscCall(PetscSectionGetNumFields(fsection, &Nf));
3654: PetscCall(DMPlexGetSimplexOrBoxCells(dmc, 0, &cStart, &cEnd));
3655: PetscCall(DMGetDS(dmc, &prob));
3656: PetscCall(PetscCalloc3(Nf, &feRef, Nf, &fvRef, Nf, &needAvg));
3657: for (f = 0; f < Nf; ++f) {
3658: PetscObject obj;
3659: PetscClassId id;
3660: PetscInt fNb = 0, Nc = 0;
3662: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
3663: PetscCall(PetscObjectGetClassId(obj, &id));
3664: if (id == PETSCFE_CLASSID) {
3665: PetscFE fe = (PetscFE)obj;
3666: PetscSpace sp;
3667: PetscInt maxDegree;
3669: PetscCall(PetscFERefine(fe, &feRef[f]));
3670: PetscCall(PetscFEGetDimension(feRef[f], &fNb));
3671: PetscCall(PetscFEGetNumComponents(fe, &Nc));
3672: PetscCall(PetscFEGetBasisSpace(fe, &sp));
3673: PetscCall(PetscSpaceGetDegree(sp, NULL, &maxDegree));
3674: if (!maxDegree) needAvg[f] = PETSC_TRUE;
3675: } else if (id == PETSCFV_CLASSID) {
3676: PetscFV fv = (PetscFV)obj;
3677: PetscDualSpace Q;
3679: PetscCall(PetscFVRefine(fv, &fvRef[f]));
3680: PetscCall(PetscFVGetDualSpace(fvRef[f], &Q));
3681: PetscCall(PetscDualSpaceGetDimension(Q, &fNb));
3682: PetscCall(PetscFVGetNumComponents(fv, &Nc));
3683: needAvg[f] = PETSC_TRUE;
3684: }
3685: fTotDim += fNb;
3686: }
3687: PetscCall(PetscDSGetTotalDimension(prob, &cTotDim));
3688: PetscCall(PetscMalloc1(cTotDim, &cmap));
3689: for (field = 0, offsetC = 0, offsetF = 0; field < Nf; ++field) {
3690: PetscFE feC;
3691: PetscFV fvC;
3692: PetscDualSpace QF, QC;
3693: PetscInt order = -1, NcF, NcC, fpdim, cpdim;
3695: if (feRef[field]) {
3696: PetscCall(PetscDSGetDiscretization(prob, field, (PetscObject *)&feC));
3697: PetscCall(PetscFEGetNumComponents(feC, &NcC));
3698: PetscCall(PetscFEGetNumComponents(feRef[field], &NcF));
3699: PetscCall(PetscFEGetDualSpace(feRef[field], &QF));
3700: PetscCall(PetscDualSpaceGetOrder(QF, &order));
3701: PetscCall(PetscDualSpaceGetDimension(QF, &fpdim));
3702: PetscCall(PetscFEGetDualSpace(feC, &QC));
3703: PetscCall(PetscDualSpaceGetDimension(QC, &cpdim));
3704: } else {
3705: PetscCall(PetscDSGetDiscretization(prob, field, (PetscObject *)&fvC));
3706: PetscCall(PetscFVGetNumComponents(fvC, &NcC));
3707: PetscCall(PetscFVGetNumComponents(fvRef[field], &NcF));
3708: PetscCall(PetscFVGetDualSpace(fvRef[field], &QF));
3709: PetscCall(PetscDualSpaceGetDimension(QF, &fpdim));
3710: PetscCall(PetscFVGetDualSpace(fvC, &QC));
3711: PetscCall(PetscDualSpaceGetDimension(QC, &cpdim));
3712: }
3713: 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);
3714: for (c = 0; c < cpdim; ++c) {
3715: PetscQuadrature cfunc;
3716: const PetscReal *cqpoints, *cqweights;
3717: PetscInt NqcC, NpC;
3718: PetscBool found = PETSC_FALSE;
3720: PetscCall(PetscDualSpaceGetFunctional(QC, c, &cfunc));
3721: PetscCall(PetscQuadratureGetData(cfunc, NULL, &NqcC, &NpC, &cqpoints, &cqweights));
3722: 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);
3723: PetscCheck(NpC == 1 || !feRef[field], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Do not know how to do injection for moments");
3724: for (f = 0; f < fpdim; ++f) {
3725: PetscQuadrature ffunc;
3726: const PetscReal *fqpoints, *fqweights;
3727: PetscReal sum = 0.0;
3728: PetscInt NqcF, NpF;
3730: PetscCall(PetscDualSpaceGetFunctional(QF, f, &ffunc));
3731: PetscCall(PetscQuadratureGetData(ffunc, NULL, &NqcF, &NpF, &fqpoints, &fqweights));
3732: 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);
3733: if (NpC != NpF) continue;
3734: for (d = 0; d < dim; ++d) sum += PetscAbsReal(cqpoints[d] - fqpoints[d]);
3735: if (sum > 1.0e-9) continue;
3736: for (d = 0; d < NcC; ++d) sum += PetscAbsReal(cqweights[d] * fqweights[d]);
3737: if (sum < 1.0e-9) continue;
3738: cmap[offsetC + c] = offsetF + f;
3739: found = PETSC_TRUE;
3740: break;
3741: }
3742: if (!found) {
3743: /* TODO We really want the average here, but some asshole put VecScatter in the interface */
3744: PetscCheck(fvRef[field] || (feRef[field] && order == 0), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not locate matching functional for injection");
3745: cmap[offsetC + c] = offsetF + 0;
3746: }
3747: }
3748: offsetC += cpdim;
3749: offsetF += fpdim;
3750: }
3751: for (f = 0; f < Nf; ++f) {
3752: PetscCall(PetscFEDestroy(&feRef[f]));
3753: PetscCall(PetscFVDestroy(&fvRef[f]));
3754: }
3755: PetscCall(PetscFree3(feRef, fvRef, needAvg));
3757: PetscCall(DMGetGlobalVector(dmf, &fv));
3758: PetscCall(DMGetGlobalVector(dmc, &cv));
3759: PetscCall(VecGetOwnershipRange(cv, &startC, &endC));
3760: PetscCall(PetscSectionGetConstrainedStorageSize(cglobalSection, &m));
3761: PetscCall(PetscMalloc2(cTotDim, &cellCIndices, fTotDim, &cellFIndices));
3762: PetscCall(PetscMalloc1(m, &cindices));
3763: PetscCall(PetscMalloc1(m, &findices));
3764: for (d = 0; d < m; ++d) cindices[d] = findices[d] = -1;
3765: for (c = cStart; c < cEnd; ++c) {
3766: PetscCall(DMPlexMatGetClosureIndicesRefined(dmf, fsection, fglobalSection, dmc, csection, cglobalSection, c, cellCIndices, cellFIndices));
3767: for (d = 0; d < cTotDim; ++d) {
3768: if (cellCIndices[d] < startC || cellCIndices[d] >= endC) continue;
3769: 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]]);
3770: cindices[cellCIndices[d] - startC] = cellCIndices[d];
3771: findices[cellCIndices[d] - startC] = cellFIndices[cmap[d]];
3772: }
3773: }
3774: PetscCall(PetscFree(cmap));
3775: PetscCall(PetscFree2(cellCIndices, cellFIndices));
3777: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, m, cindices, PETSC_OWN_POINTER, &cis));
3778: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, m, findices, PETSC_OWN_POINTER, &fis));
3779: PetscCall(VecScatterCreate(cv, cis, fv, fis, sc));
3780: PetscCall(ISDestroy(&cis));
3781: PetscCall(ISDestroy(&fis));
3782: PetscCall(DMRestoreGlobalVector(dmf, &fv));
3783: PetscCall(DMRestoreGlobalVector(dmc, &cv));
3784: PetscCall(PetscLogEventEnd(DMPLEX_InjectorFEM, dmc, dmf, 0, 0));
3785: PetscFunctionReturn(PETSC_SUCCESS);
3786: }
3788: /*@
3789: DMPlexGetCellFields - Retrieve the field values values for a chunk of cells
3791: Input Parameters:
3792: + dm - The `DM`
3793: . cellIS - The cells to include
3794: . locX - A local vector with the solution fields
3795: . locX_t - A local vector with solution field time derivatives, or `NULL`
3796: - locA - A local vector with auxiliary fields, or `NULL`
3798: Output Parameters:
3799: + u - The field coefficients
3800: . u_t - The fields derivative coefficients
3801: - a - The auxiliary field coefficients
3803: Level: developer
3805: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetFaceFields()`
3806: @*/
3807: PetscErrorCode DMPlexGetCellFields(DM dm, IS cellIS, Vec locX, PeOp Vec locX_t, PeOp Vec locA, PetscScalar *u[], PetscScalar *u_t[], PetscScalar *a[])
3808: {
3809: DM plex, plexA = NULL;
3810: DMEnclosureType encAux;
3811: PetscSection section, sectionAux;
3812: PetscDS prob;
3813: const PetscInt *cells;
3814: PetscInt cStart, cEnd, numCells, totDim, totDimAux, c;
3816: PetscFunctionBegin;
3821: PetscAssertPointer(u, 6);
3822: PetscAssertPointer(u_t, 7);
3823: PetscAssertPointer(a, 8);
3824: PetscCall(DMPlexConvertPlex(dm, &plex, PETSC_FALSE));
3825: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
3826: PetscCall(DMGetLocalSection(dm, §ion));
3827: PetscCall(DMGetCellDS(dm, cells ? cells[cStart] : cStart, &prob, NULL));
3828: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
3829: if (locA) {
3830: DM dmAux;
3831: PetscDS probAux;
3833: PetscCall(VecGetDM(locA, &dmAux));
3834: PetscCall(DMGetEnclosureRelation(dmAux, dm, &encAux));
3835: PetscCall(DMPlexConvertPlex(dmAux, &plexA, PETSC_FALSE));
3836: PetscCall(DMGetLocalSection(dmAux, §ionAux));
3837: PetscCall(DMGetDS(dmAux, &probAux));
3838: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
3839: }
3840: numCells = cEnd - cStart;
3841: PetscCall(DMGetWorkArray(dm, numCells * totDim, MPIU_SCALAR, u));
3842: if (locX_t) PetscCall(DMGetWorkArray(dm, numCells * totDim, MPIU_SCALAR, u_t));
3843: else *u_t = NULL;
3844: if (locA) PetscCall(DMGetWorkArray(dm, numCells * totDimAux, MPIU_SCALAR, a));
3845: else *a = NULL;
3846: for (c = cStart; c < cEnd; ++c) {
3847: const PetscInt cell = cells ? cells[c] : c;
3848: const PetscInt cind = c - cStart;
3849: PetscScalar *x = NULL, *x_t = NULL, *ul = *u, *ul_t = *u_t, *al = *a;
3851: PetscCall(DMPlexVecGetClosure(plex, section, locX, cell, NULL, &x));
3852: for (PetscInt i = 0; i < totDim; ++i) ul[cind * totDim + i] = x[i];
3853: PetscCall(DMPlexVecRestoreClosure(plex, section, locX, cell, NULL, &x));
3854: if (locX_t) {
3855: PetscCall(DMPlexVecGetClosure(plex, section, locX_t, cell, NULL, &x_t));
3856: for (PetscInt i = 0; i < totDim; ++i) ul_t[cind * totDim + i] = x_t[i];
3857: PetscCall(DMPlexVecRestoreClosure(plex, section, locX_t, cell, NULL, &x_t));
3858: }
3859: if (locA) {
3860: PetscInt subcell;
3861: PetscCall(DMGetEnclosurePoint(plexA, dm, encAux, cell, &subcell));
3862: PetscCall(DMPlexVecGetClosure(plexA, sectionAux, locA, subcell, NULL, &x));
3863: for (PetscInt i = 0; i < totDimAux; ++i) al[cind * totDimAux + i] = x[i];
3864: PetscCall(DMPlexVecRestoreClosure(plexA, sectionAux, locA, subcell, NULL, &x));
3865: }
3866: }
3867: PetscCall(DMDestroy(&plex));
3868: if (locA) PetscCall(DMDestroy(&plexA));
3869: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
3870: PetscFunctionReturn(PETSC_SUCCESS);
3871: }
3873: /*@
3874: DMPlexRestoreCellFields - Restore the field values values for a chunk of cells
3876: Input Parameters:
3877: + dm - The `DM`
3878: . cellIS - The cells to include
3879: . locX - A local vector with the solution fields
3880: . locX_t - A local vector with solution field time derivatives, or `NULL`
3881: - locA - A local vector with auxiliary fields, or `NULL`
3883: Output Parameters:
3884: + u - The field coefficients
3885: . u_t - The fields derivative coefficients
3886: - a - The auxiliary field coefficients
3888: Level: developer
3890: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetFaceFields()`
3891: @*/
3892: PetscErrorCode DMPlexRestoreCellFields(DM dm, IS cellIS, Vec locX, PeOp Vec locX_t, PeOp Vec locA, PetscScalar *u[], PetscScalar *u_t[], PetscScalar *a[])
3893: {
3894: PetscFunctionBegin;
3895: PetscCall(DMRestoreWorkArray(dm, 0, MPIU_SCALAR, u));
3896: if (locX_t) PetscCall(DMRestoreWorkArray(dm, 0, MPIU_SCALAR, u_t));
3897: if (locA) PetscCall(DMRestoreWorkArray(dm, 0, MPIU_SCALAR, a));
3898: PetscFunctionReturn(PETSC_SUCCESS);
3899: }
3901: static PetscErrorCode DMPlexGetHybridCellFields(DM dm, IS cellIS, Vec locX, Vec locX_t, Vec locA, PetscScalar **u, PetscScalar **u_t, PetscScalar **a)
3902: {
3903: DM plex, plexA = NULL;
3904: DMEnclosureType encAux;
3905: PetscSection section, sectionAux;
3906: PetscDS ds, dsIn;
3907: const PetscInt *cells;
3908: PetscInt cStart, cEnd, numCells, c, totDim, totDimAux, Nf, f;
3910: PetscFunctionBegin;
3916: PetscAssertPointer(u, 6);
3917: PetscAssertPointer(u_t, 7);
3918: PetscAssertPointer(a, 8);
3919: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
3920: numCells = cEnd - cStart;
3921: PetscCall(DMPlexConvertPlex(dm, &plex, PETSC_FALSE));
3922: PetscCall(DMGetLocalSection(dm, §ion));
3923: PetscCall(DMGetCellDS(dm, cells ? cells[cStart] : cStart, &ds, &dsIn));
3924: PetscCall(PetscDSGetNumFields(dsIn, &Nf));
3925: PetscCall(PetscDSGetTotalDimension(dsIn, &totDim));
3926: if (locA) {
3927: DM dmAux;
3928: PetscDS probAux;
3930: PetscCall(VecGetDM(locA, &dmAux));
3931: PetscCall(DMGetEnclosureRelation(dmAux, dm, &encAux));
3932: PetscCall(DMPlexConvertPlex(dmAux, &plexA, PETSC_FALSE));
3933: PetscCall(DMGetLocalSection(dmAux, §ionAux));
3934: PetscCall(DMGetDS(dmAux, &probAux));
3935: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
3936: }
3937: PetscCall(DMGetWorkArray(dm, numCells * totDim, MPIU_SCALAR, u));
3938: if (locX_t) PetscCall(DMGetWorkArray(dm, numCells * totDim, MPIU_SCALAR, u_t));
3939: else {
3940: *u_t = NULL;
3941: }
3942: if (locA) PetscCall(DMGetWorkArray(dm, numCells * totDimAux, MPIU_SCALAR, a));
3943: else {
3944: *a = NULL;
3945: }
3946: // Loop over cohesive cells
3947: for (c = cStart; c < cEnd; ++c) {
3948: const PetscInt cell = cells ? cells[c] : c;
3949: const PetscInt cind = c - cStart;
3950: PetscScalar *xf = NULL, *xc = NULL, *x = NULL, *xf_t = NULL, *xc_t = NULL;
3951: PetscScalar *ul = &(*u)[cind * totDim], *ul_t = PetscSafePointerPlusOffset(*u_t, cind * totDim);
3952: const PetscInt *cone, *ornt;
3953: PetscInt Nx = 0, Nxf, s;
3955: PetscCall(DMPlexGetCone(dm, cell, &cone));
3956: PetscCall(DMPlexGetConeOrientation(dm, cell, &ornt));
3957: // Put in cohesive unknowns
3958: PetscCall(DMPlexVecGetClosure(plex, section, locX, cell, &Nxf, &xf));
3959: if (locX_t) PetscCall(DMPlexVecGetClosure(plex, section, locX_t, cell, NULL, &xf_t));
3960: for (f = 0; f < Nf; ++f) {
3961: PetscInt fdofIn, foff, foffIn;
3962: PetscBool cohesive;
3964: PetscCall(PetscDSGetCohesive(dsIn, f, &cohesive));
3965: if (!cohesive) continue;
3966: PetscCall(PetscDSGetFieldSize(dsIn, f, &fdofIn));
3967: PetscCall(PetscDSGetFieldOffsetCohesive(ds, f, &foff));
3968: PetscCall(PetscDSGetFieldOffsetCohesive(dsIn, f, &foffIn));
3969: for (PetscInt i = 0; i < fdofIn; ++i) ul[foffIn + i] = xf[foff + i];
3970: if (locX_t)
3971: for (PetscInt i = 0; i < fdofIn; ++i) ul_t[foffIn + i] = xf_t[foff + i];
3972: Nx += fdofIn;
3973: }
3974: PetscCall(DMPlexVecRestoreClosure(plex, section, locX, cell, &Nxf, &xf));
3975: if (locX_t) PetscCall(DMPlexVecRestoreClosure(plex, section, locX_t, cell, NULL, &xf_t));
3976: // Loop over sides of surface
3977: PetscCheck(ornt[0] == ornt[1], PETSC_COMM_SELF, PETSC_ERR_SUP, "Face %" PetscInt_FMT " in hybrid cell %" PetscInt_FMT " has orientation %" PetscInt_FMT " != %" PetscInt_FMT " of face %" PetscInt_FMT, cone[0], cell, ornt[0], ornt[1], cone[1]);
3978: for (s = 0; s < 2; ++s) {
3979: const PetscInt *support;
3980: const PetscInt face = cone[s];
3981: PetscDS dsC;
3982: PetscInt ssize, ncell, Nxc;
3984: // I don't think I need the face to have 0 orientation in the hybrid cell
3985: //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]);
3986: PetscCall(DMPlexGetSupport(dm, face, &support));
3987: PetscCall(DMPlexGetSupportSize(dm, face, &ssize));
3988: if (support[0] == cell) ncell = support[1];
3989: else if (support[1] == cell) ncell = support[0];
3990: else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " does not have cell %" PetscInt_FMT " in its support", face, cell);
3991: // Get closure of both face and cell, stick in cell for normal fields and face for cohesive fields
3992: PetscCall(DMGetCellDS(dm, ncell, &dsC, NULL));
3993: PetscCall(DMPlexVecGetClosure(plex, section, locX, ncell, &Nxc, &xc));
3994: if (locX_t) PetscCall(DMPlexVecGetClosure(plex, section, locX_t, ncell, NULL, &xc_t));
3995: for (f = 0; f < Nf; ++f) {
3996: PetscInt fdofIn, foffIn, foff;
3997: PetscBool cohesive;
3999: PetscCall(PetscDSGetCohesive(dsIn, f, &cohesive));
4000: if (cohesive) continue;
4001: PetscCall(PetscDSGetFieldSize(dsIn, f, &fdofIn));
4002: PetscCall(PetscDSGetFieldOffset(dsC, f, &foff));
4003: PetscCall(PetscDSGetFieldOffsetCohesive(dsIn, f, &foffIn));
4004: for (PetscInt i = 0; i < fdofIn; ++i) ul[foffIn + s * fdofIn + i] = xc[foff + i];
4005: if (locX_t)
4006: for (PetscInt i = 0; i < fdofIn; ++i) ul_t[foffIn + s * fdofIn + i] = xc_t[foff + i];
4007: Nx += fdofIn;
4008: }
4009: PetscCall(DMPlexVecRestoreClosure(plex, section, locX, ncell, &Nxc, &xc));
4010: if (locX_t) PetscCall(DMPlexVecRestoreClosure(plex, section, locX_t, ncell, NULL, &xc_t));
4011: }
4012: 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);
4014: if (locA) {
4015: PetscScalar *al = &(*a)[cind * totDimAux];
4016: PetscInt subcell;
4018: PetscCall(DMGetEnclosurePoint(plexA, dm, encAux, cell, &subcell));
4019: PetscCall(DMPlexVecGetClosure(plexA, sectionAux, locA, subcell, &Nx, &x));
4020: 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);
4021: for (PetscInt i = 0; i < totDimAux; ++i) al[i] = x[i];
4022: PetscCall(DMPlexVecRestoreClosure(plexA, sectionAux, locA, subcell, &Nx, &x));
4023: }
4024: }
4025: PetscCall(DMDestroy(&plex));
4026: PetscCall(DMDestroy(&plexA));
4027: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
4028: PetscFunctionReturn(PETSC_SUCCESS);
4029: }
4031: /*
4032: DMPlexGetHybridFields - Get the field values for the negative side (s = 0) and positive side (s = 1) of the interface
4034: Input Parameters:
4035: + dm - The full domain DM
4036: . dmX - An array of DM for the field, say an auxiliary DM, indexed by s
4037: . dsX - An array of PetscDS for the field, indexed by s
4038: . cellIS - The interface cells for which we want values
4039: . locX - An array of local vectors with the field values, indexed by s
4040: - useCell - Flag to have values come from neighboring cell rather than endcap face
4042: Output Parameter:
4043: . x - An array of field values, indexed by s
4045: Note:
4046: The arrays in `x` will be allocated using `DMGetWorkArray()`, and must be returned using `DMPlexRestoreHybridFields()`.
4048: Level: advanced
4050: .seealso: `DMPlexRestoreHybridFields()`, `DMGetWorkArray()`
4051: */
4052: static PetscErrorCode DMPlexGetHybridFields(DM dm, DM dmX[], PetscDS dsX[], IS cellIS, Vec locX[], PetscBool useCell, PetscScalar *x[])
4053: {
4054: DM plexX[2];
4055: DMEnclosureType encX[2];
4056: PetscSection sectionX[2];
4057: const PetscInt *cells;
4058: PetscInt cStart, cEnd, numCells, c, s, totDimX[2];
4060: PetscFunctionBegin;
4061: PetscAssertPointer(locX, 5);
4062: if (!locX[0] || !locX[1]) PetscFunctionReturn(PETSC_SUCCESS);
4063: PetscAssertPointer(dmX, 2);
4064: PetscAssertPointer(dsX, 3);
4066: PetscAssertPointer(x, 7);
4067: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
4068: numCells = cEnd - cStart;
4069: for (s = 0; s < 2; ++s) {
4073: PetscCall(DMPlexConvertPlex(dmX[s], &plexX[s], PETSC_FALSE));
4074: PetscCall(DMGetEnclosureRelation(dmX[s], dm, &encX[s]));
4075: PetscCall(DMGetLocalSection(dmX[s], §ionX[s]));
4076: PetscCall(PetscDSGetTotalDimension(dsX[s], &totDimX[s]));
4077: PetscCall(DMGetWorkArray(dmX[s], numCells * totDimX[s], MPIU_SCALAR, &x[s]));
4078: }
4079: for (c = cStart; c < cEnd; ++c) {
4080: const PetscInt cell = cells ? cells[c] : c;
4081: const PetscInt cind = c - cStart;
4082: const PetscInt *cone, *ornt;
4084: PetscCall(DMPlexGetCone(dm, cell, &cone));
4085: PetscCall(DMPlexGetConeOrientation(dm, cell, &ornt));
4086: //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]);
4087: for (s = 0; s < 2; ++s) {
4088: const PetscInt tdX = totDimX[s];
4089: PetscScalar *closure = NULL, *xl = &x[s][cind * tdX];
4090: PetscInt face = cone[s], point = face, subpoint, Nx, i;
4092: if (useCell) {
4093: const PetscInt *support;
4094: PetscInt ssize;
4096: PetscCall(DMPlexGetSupport(dm, face, &support));
4097: PetscCall(DMPlexGetSupportSize(dm, face, &ssize));
4098: 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);
4099: if (support[0] == cell) point = support[1];
4100: else if (support[1] == cell) point = support[0];
4101: else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " does not have cell %" PetscInt_FMT " in its support", face, cell);
4102: }
4103: PetscCall(DMGetEnclosurePoint(plexX[s], dm, encX[s], point, &subpoint));
4104: PetscCall(DMPlexVecGetOrientedClosure(plexX[s], sectionX[s], PETSC_FALSE, locX[s], subpoint, ornt[s], &Nx, &closure));
4105: 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);
4106: for (i = 0; i < Nx; ++i) xl[i] = closure[i];
4107: PetscCall(DMPlexVecRestoreClosure(plexX[s], sectionX[s], locX[s], subpoint, &Nx, &closure));
4108: }
4109: }
4110: for (s = 0; s < 2; ++s) PetscCall(DMDestroy(&plexX[s]));
4111: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
4112: PetscFunctionReturn(PETSC_SUCCESS);
4113: }
4115: static PetscErrorCode DMPlexRestoreHybridFields(DM dm, DM dmX[], PetscDS dsX[], IS cellIS, Vec locX[], PetscBool useCell, PetscScalar *x[])
4116: {
4117: PetscFunctionBegin;
4118: if (!locX[0] || !locX[1]) PetscFunctionReturn(PETSC_SUCCESS);
4119: PetscCall(DMRestoreWorkArray(dmX[0], 0, MPIU_SCALAR, &x[0]));
4120: PetscCall(DMRestoreWorkArray(dmX[1], 0, MPIU_SCALAR, &x[1]));
4121: PetscFunctionReturn(PETSC_SUCCESS);
4122: }
4124: /*@
4125: DMPlexGetFaceFields - Retrieve the field values values for a chunk of faces
4127: Input Parameters:
4128: + dm - The `DM`
4129: . fStart - The first face to include
4130: . fEnd - The first face to exclude
4131: . locX - A local vector with the solution fields
4132: . locX_t - A local vector with solution field time derivatives, or `NULL`
4133: . faceGeometry - A local vector with face geometry
4134: . cellGeometry - A local vector with cell geometry
4135: - locGrad - A local vector with field gradients, or `NULL`
4137: Output Parameters:
4138: + Nface - The number of faces with field values
4139: . uL - The field values at the left side of the face
4140: - uR - The field values at the right side of the face
4142: Level: developer
4144: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellFields()`
4145: @*/
4146: 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[])
4147: {
4148: DM dmFace, dmCell, dmGrad = NULL;
4149: PetscSection section;
4150: PetscDS prob;
4151: DMLabel ghostLabel;
4152: const PetscScalar *facegeom, *cellgeom, *x, *lgrad;
4153: PetscBool *isFE;
4154: PetscInt dim, Nf, f, Nc, numFaces = fEnd - fStart, iface, face;
4156: PetscFunctionBegin;
4163: PetscAssertPointer(uL, 10);
4164: PetscAssertPointer(uR, 11);
4165: PetscCall(DMGetDimension(dm, &dim));
4166: PetscCall(DMGetDS(dm, &prob));
4167: PetscCall(DMGetLocalSection(dm, §ion));
4168: PetscCall(PetscDSGetNumFields(prob, &Nf));
4169: PetscCall(PetscDSGetTotalComponents(prob, &Nc));
4170: PetscCall(PetscMalloc1(Nf, &isFE));
4171: for (f = 0; f < Nf; ++f) {
4172: PetscObject obj;
4173: PetscClassId id;
4175: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
4176: PetscCall(PetscObjectGetClassId(obj, &id));
4177: if (id == PETSCFE_CLASSID) {
4178: isFE[f] = PETSC_TRUE;
4179: } else if (id == PETSCFV_CLASSID) {
4180: isFE[f] = PETSC_FALSE;
4181: } else {
4182: isFE[f] = PETSC_FALSE;
4183: }
4184: }
4185: PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
4186: PetscCall(VecGetArrayRead(locX, &x));
4187: PetscCall(VecGetDM(faceGeometry, &dmFace));
4188: PetscCall(VecGetArrayRead(faceGeometry, &facegeom));
4189: PetscCall(VecGetDM(cellGeometry, &dmCell));
4190: PetscCall(VecGetArrayRead(cellGeometry, &cellgeom));
4191: if (locGrad) {
4192: PetscCall(VecGetDM(locGrad, &dmGrad));
4193: PetscCall(VecGetArrayRead(locGrad, &lgrad));
4194: }
4195: PetscCall(DMGetWorkArray(dm, numFaces * Nc, MPIU_SCALAR, uL));
4196: PetscCall(DMGetWorkArray(dm, numFaces * Nc, MPIU_SCALAR, uR));
4197: /* Right now just eat the extra work for FE (could make a cell loop) */
4198: for (face = fStart, iface = 0; face < fEnd; ++face) {
4199: const PetscInt *cells;
4200: PetscFVFaceGeom *fg;
4201: PetscFVCellGeom *cgL, *cgR;
4202: PetscScalar *xL, *xR, *gL, *gR;
4203: PetscScalar *uLl = *uL, *uRl = *uR;
4204: PetscInt ghost, nsupp, nchild;
4206: PetscCall(DMLabelGetValue(ghostLabel, face, &ghost));
4207: PetscCall(DMPlexGetSupportSize(dm, face, &nsupp));
4208: PetscCall(DMPlexGetTreeChildren(dm, face, &nchild, NULL));
4209: if (ghost >= 0 || nsupp > 2 || nchild > 0) continue;
4210: PetscCall(DMPlexPointLocalRead(dmFace, face, facegeom, &fg));
4211: PetscCall(DMPlexGetSupport(dm, face, &cells));
4212: PetscCall(DMPlexPointLocalRead(dmCell, cells[0], cellgeom, &cgL));
4213: PetscCall(DMPlexPointLocalRead(dmCell, cells[1], cellgeom, &cgR));
4214: for (f = 0; f < Nf; ++f) {
4215: PetscInt off;
4217: PetscCall(PetscDSGetComponentOffset(prob, f, &off));
4218: if (isFE[f]) {
4219: const PetscInt *cone;
4220: PetscInt comp, coneSizeL, coneSizeR, faceLocL, faceLocR, ldof, rdof, d;
4222: xL = xR = NULL;
4223: PetscCall(PetscSectionGetFieldComponents(section, f, &comp));
4224: PetscCall(DMPlexVecGetClosure(dm, section, locX, cells[0], &ldof, &xL));
4225: PetscCall(DMPlexVecGetClosure(dm, section, locX, cells[1], &rdof, &xR));
4226: PetscCall(DMPlexGetCone(dm, cells[0], &cone));
4227: PetscCall(DMPlexGetConeSize(dm, cells[0], &coneSizeL));
4228: for (faceLocL = 0; faceLocL < coneSizeL; ++faceLocL)
4229: if (cone[faceLocL] == face) break;
4230: PetscCall(DMPlexGetCone(dm, cells[1], &cone));
4231: PetscCall(DMPlexGetConeSize(dm, cells[1], &coneSizeR));
4232: for (faceLocR = 0; faceLocR < coneSizeR; ++faceLocR)
4233: if (cone[faceLocR] == face) break;
4234: 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]);
4235: /* Check that FEM field has values in the right cell (sometimes its an FV ghost cell) */
4236: /* TODO: this is a hack that might not be right for nonconforming */
4237: if (faceLocL < coneSizeL) {
4238: PetscCall(PetscFEEvaluateFaceFields_Internal(prob, f, faceLocL, xL, &uLl[iface * Nc + off]));
4239: if (rdof == ldof && faceLocR < coneSizeR) PetscCall(PetscFEEvaluateFaceFields_Internal(prob, f, faceLocR, xR, &uRl[iface * Nc + off]));
4240: else {
4241: for (d = 0; d < comp; ++d) uRl[iface * Nc + off + d] = uLl[iface * Nc + off + d];
4242: }
4243: } else {
4244: PetscCall(PetscFEEvaluateFaceFields_Internal(prob, f, faceLocR, xR, &uRl[iface * Nc + off]));
4245: PetscCall(PetscSectionGetFieldComponents(section, f, &comp));
4246: for (d = 0; d < comp; ++d) uLl[iface * Nc + off + d] = uRl[iface * Nc + off + d];
4247: }
4248: PetscCall(DMPlexVecRestoreClosure(dm, section, locX, cells[0], &ldof, &xL));
4249: PetscCall(DMPlexVecRestoreClosure(dm, section, locX, cells[1], &rdof, &xR));
4250: } else {
4251: PetscFV fv;
4252: PetscInt numComp;
4254: PetscCall(PetscDSGetDiscretization(prob, f, (PetscObject *)&fv));
4255: PetscCall(PetscFVGetNumComponents(fv, &numComp));
4256: PetscCall(DMPlexPointLocalFieldRead(dm, cells[0], f, x, &xL));
4257: PetscCall(DMPlexPointLocalFieldRead(dm, cells[1], f, x, &xR));
4258: if (dmGrad) {
4259: PetscReal dxL[3], dxR[3];
4261: PetscCall(DMPlexPointLocalRead(dmGrad, cells[0], lgrad, &gL));
4262: PetscCall(DMPlexPointLocalRead(dmGrad, cells[1], lgrad, &gR));
4263: DMPlex_WaxpyD_Internal(dim, -1, cgL->centroid, fg->centroid, dxL);
4264: DMPlex_WaxpyD_Internal(dim, -1, cgR->centroid, fg->centroid, dxR);
4265: for (PetscInt c = 0; c < numComp; ++c) {
4266: uLl[iface * Nc + off + c] = xL[c] + DMPlex_DotD_Internal(dim, &gL[c * dim], dxL);
4267: uRl[iface * Nc + off + c] = xR[c] + DMPlex_DotD_Internal(dim, &gR[c * dim], dxR);
4268: }
4269: } else {
4270: for (PetscInt c = 0; c < numComp; ++c) {
4271: uLl[iface * Nc + off + c] = xL[c];
4272: uRl[iface * Nc + off + c] = xR[c];
4273: }
4274: }
4275: }
4276: }
4277: ++iface;
4278: }
4279: *Nface = iface;
4280: PetscCall(VecRestoreArrayRead(locX, &x));
4281: PetscCall(VecRestoreArrayRead(faceGeometry, &facegeom));
4282: PetscCall(VecRestoreArrayRead(cellGeometry, &cellgeom));
4283: if (locGrad) PetscCall(VecRestoreArrayRead(locGrad, &lgrad));
4284: PetscCall(PetscFree(isFE));
4285: PetscFunctionReturn(PETSC_SUCCESS);
4286: }
4288: /*@
4289: DMPlexRestoreFaceFields - Restore the field values values for a chunk of faces
4291: Input Parameters:
4292: + dm - The `DM`
4293: . fStart - The first face to include
4294: . fEnd - The first face to exclude
4295: . locX - A local vector with the solution fields
4296: . locX_t - A local vector with solution field time derivatives, or `NULL`
4297: . faceGeometry - A local vector with face geometry
4298: . cellGeometry - A local vector with cell geometry
4299: - locGrad - A local vector with field gradients, or `NULL`
4301: Output Parameters:
4302: + Nface - The number of faces with field values
4303: . uL - The field values at the left side of the face
4304: - uR - The field values at the right side of the face
4306: Level: developer
4308: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetFaceFields()`
4309: @*/
4310: 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[])
4311: {
4312: PetscFunctionBegin;
4313: PetscCall(DMRestoreWorkArray(dm, 0, MPIU_SCALAR, uL));
4314: PetscCall(DMRestoreWorkArray(dm, 0, MPIU_SCALAR, uR));
4315: PetscFunctionReturn(PETSC_SUCCESS);
4316: }
4318: /*@
4319: DMPlexGetFaceGeometry - Retrieve the geometric values for a chunk of faces
4321: Input Parameters:
4322: + dm - The `DM`
4323: . fStart - The first face to include
4324: . fEnd - The first face to exclude
4325: . faceGeometry - A local vector with face geometry
4326: - cellGeometry - A local vector with cell geometry
4328: Output Parameters:
4329: + Nface - The number of faces with field values
4330: . fgeom - The face centroid and normals
4331: - vol - The cell volumes
4333: Level: developer
4335: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellFields()`
4336: @*/
4337: PetscErrorCode DMPlexGetFaceGeometry(DM dm, PetscInt fStart, PetscInt fEnd, Vec faceGeometry, Vec cellGeometry, PetscInt *Nface, PetscFVFaceGeom *fgeom[], PetscReal *vol[])
4338: {
4339: DM dmFace, dmCell;
4340: DMLabel ghostLabel;
4341: const PetscScalar *facegeom, *cellgeom;
4342: PetscInt dim, numFaces = fEnd - fStart, iface, face;
4344: PetscFunctionBegin;
4348: PetscAssertPointer(fgeom, 7);
4349: PetscAssertPointer(vol, 8);
4350: PetscCall(DMGetDimension(dm, &dim));
4351: PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
4352: PetscCall(VecGetDM(faceGeometry, &dmFace));
4353: PetscCall(VecGetArrayRead(faceGeometry, &facegeom));
4354: PetscCall(VecGetDM(cellGeometry, &dmCell));
4355: PetscCall(VecGetArrayRead(cellGeometry, &cellgeom));
4356: PetscCall(PetscMalloc1(numFaces, fgeom));
4357: PetscCall(DMGetWorkArray(dm, numFaces * 2, MPIU_SCALAR, vol));
4358: for (face = fStart, iface = 0; face < fEnd; ++face) {
4359: const PetscInt *cells;
4360: PetscFVFaceGeom *fg;
4361: PetscFVCellGeom *cgL, *cgR;
4362: PetscFVFaceGeom *fgeoml = *fgeom;
4363: PetscReal *voll = *vol;
4364: PetscInt ghost, d, nchild, nsupp;
4366: PetscCall(DMLabelGetValue(ghostLabel, face, &ghost));
4367: PetscCall(DMPlexGetSupportSize(dm, face, &nsupp));
4368: PetscCall(DMPlexGetTreeChildren(dm, face, &nchild, NULL));
4369: if (ghost >= 0 || nsupp > 2 || nchild > 0) continue;
4370: PetscCall(DMPlexPointLocalRead(dmFace, face, facegeom, &fg));
4371: PetscCall(DMPlexGetSupport(dm, face, &cells));
4372: PetscCall(DMPlexPointLocalRead(dmCell, cells[0], cellgeom, &cgL));
4373: PetscCall(DMPlexPointLocalRead(dmCell, cells[1], cellgeom, &cgR));
4374: for (d = 0; d < dim; ++d) {
4375: fgeoml[iface].centroid[d] = fg->centroid[d];
4376: fgeoml[iface].normal[d] = fg->normal[d];
4377: }
4378: voll[iface * 2 + 0] = cgL->volume;
4379: voll[iface * 2 + 1] = cgR->volume;
4380: ++iface;
4381: }
4382: *Nface = iface;
4383: PetscCall(VecRestoreArrayRead(faceGeometry, &facegeom));
4384: PetscCall(VecRestoreArrayRead(cellGeometry, &cellgeom));
4385: PetscFunctionReturn(PETSC_SUCCESS);
4386: }
4388: /*@
4389: DMPlexRestoreFaceGeometry - Restore the field values values for a chunk of faces
4391: Input Parameters:
4392: + dm - The `DM`
4393: . fStart - The first face to include
4394: . fEnd - The first face to exclude
4395: . faceGeometry - A local vector with face geometry
4396: - cellGeometry - A local vector with cell geometry
4398: Output Parameters:
4399: + Nface - The number of faces with field values
4400: . fgeom - The face centroid and normals
4401: - vol - The cell volumes
4403: Level: developer
4405: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetFaceFields()`
4406: @*/
4407: PetscErrorCode DMPlexRestoreFaceGeometry(DM dm, PetscInt fStart, PetscInt fEnd, Vec faceGeometry, Vec cellGeometry, PetscInt *Nface, PetscFVFaceGeom *fgeom[], PetscReal *vol[])
4408: {
4409: PetscFunctionBegin;
4410: PetscCall(PetscFree(*fgeom));
4411: PetscCall(DMRestoreWorkArray(dm, 0, MPIU_REAL, vol));
4412: PetscFunctionReturn(PETSC_SUCCESS);
4413: }
4415: PetscErrorCode DMSNESGetFEGeom(DMField coordField, IS pointIS, PetscQuadrature quad, PetscFEGeomMode mode, PetscFEGeom **geom)
4416: {
4417: char composeStr[33] = {0};
4418: PetscObjectId id;
4419: PetscContainer container;
4421: PetscFunctionBegin;
4422: PetscCall(PetscObjectGetId((PetscObject)quad, &id));
4423: PetscCall(PetscSNPrintf(composeStr, 32, "DMSNESGetFEGeom_%" PetscInt64_FMT "\n", id));
4424: PetscCall(PetscObjectQuery((PetscObject)pointIS, composeStr, (PetscObject *)&container));
4425: if (container) {
4426: PetscCall(PetscContainerGetPointer(container, geom));
4427: } else {
4428: PetscCall(DMFieldCreateFEGeom(coordField, pointIS, quad, mode, geom));
4429: PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
4430: PetscCall(PetscContainerSetPointer(container, (void *)*geom));
4431: PetscCall(PetscContainerSetCtxDestroy(container, PetscContainerCtxDestroy_PetscFEGeom));
4432: PetscCall(PetscObjectCompose((PetscObject)pointIS, composeStr, (PetscObject)container));
4433: PetscCall(PetscContainerDestroy(&container));
4434: }
4435: PetscFunctionReturn(PETSC_SUCCESS);
4436: }
4438: PetscErrorCode DMSNESRestoreFEGeom(DMField coordField, IS pointIS, PetscQuadrature quad, PetscBool faceData, PetscFEGeom **geom)
4439: {
4440: PetscFunctionBegin;
4441: *geom = NULL;
4442: PetscFunctionReturn(PETSC_SUCCESS);
4443: }
4445: PetscErrorCode DMPlexComputeResidual_Patch_Internal(DM dm, PetscSection section, IS cellIS, PetscReal t, Vec locX, Vec locX_t, Vec locF, PetscCtx ctx)
4446: {
4447: DM_Plex *mesh = (DM_Plex *)dm->data;
4448: const char *name = "Residual";
4449: DM dmAux = NULL;
4450: DMLabel ghostLabel = NULL;
4451: PetscDS prob = NULL;
4452: PetscDS probAux = NULL;
4453: PetscBool useFEM = PETSC_FALSE;
4454: PetscBool isImplicit = (locX_t || t == PETSC_MIN_REAL) ? PETSC_TRUE : PETSC_FALSE;
4455: DMField coordField = NULL;
4456: Vec locA;
4457: PetscScalar *u = NULL, *u_t, *a, *uL = NULL, *uR = NULL;
4458: IS chunkIS;
4459: const PetscInt *cells;
4460: PetscInt cStart, cEnd, numCells;
4461: PetscInt Nf, f, totDim, totDimAux, numChunks, cellChunkSize, chunk, fStart, fEnd;
4462: PetscInt maxDegree = PETSC_INT_MAX;
4463: PetscFormKey key;
4464: PetscQuadrature affineQuad = NULL, *quads = NULL;
4465: PetscFEGeom *affineGeom = NULL, **geoms = NULL;
4467: PetscFunctionBegin;
4468: PetscCall(PetscLogEventBegin(DMPLEX_ResidualFEM, dm, 0, 0, 0));
4469: /* FEM+FVM */
4470: /* 1: Get sizes from dm and dmAux */
4471: PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
4472: PetscCall(DMGetDS(dm, &prob));
4473: PetscCall(PetscDSGetNumFields(prob, &Nf));
4474: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
4475: PetscCall(DMGetAuxiliaryVec(dm, NULL, 0, 0, &locA));
4476: if (locA) {
4477: PetscCall(VecGetDM(locA, &dmAux));
4478: PetscCall(DMGetDS(dmAux, &probAux));
4479: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
4480: }
4481: /* 2: Get geometric data */
4482: for (f = 0; f < Nf; ++f) {
4483: PetscObject obj;
4484: PetscClassId id;
4485: PetscBool fimp;
4487: PetscCall(PetscDSGetImplicit(prob, f, &fimp));
4488: if (isImplicit != fimp) continue;
4489: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
4490: PetscCall(PetscObjectGetClassId(obj, &id));
4491: if (id == PETSCFE_CLASSID) useFEM = PETSC_TRUE;
4492: PetscCheck(id != PETSCFV_CLASSID, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Use of FVM with PCPATCH not yet implemented");
4493: }
4494: if (useFEM) {
4495: PetscCall(DMGetCoordinateField(dm, &coordField));
4496: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
4497: if (maxDegree <= 1) {
4498: PetscCall(DMFieldCreateDefaultQuadrature(coordField, cellIS, &affineQuad));
4499: if (affineQuad) PetscCall(DMSNESGetFEGeom(coordField, cellIS, affineQuad, PETSC_FEGEOM_BASIC, &affineGeom));
4500: } else {
4501: PetscCall(PetscCalloc2(Nf, &quads, Nf, &geoms));
4502: for (f = 0; f < Nf; ++f) {
4503: PetscObject obj;
4504: PetscClassId id;
4505: PetscBool fimp;
4507: PetscCall(PetscDSGetImplicit(prob, f, &fimp));
4508: if (isImplicit != fimp) continue;
4509: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
4510: PetscCall(PetscObjectGetClassId(obj, &id));
4511: if (id == PETSCFE_CLASSID) {
4512: PetscFE fe = (PetscFE)obj;
4514: PetscCall(PetscFEGetQuadrature(fe, &quads[f]));
4515: PetscCall(PetscObjectReference((PetscObject)quads[f]));
4516: PetscCall(DMSNESGetFEGeom(coordField, cellIS, quads[f], PETSC_FEGEOM_BASIC, &geoms[f]));
4517: }
4518: }
4519: }
4520: }
4521: /* Loop over chunks */
4522: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
4523: PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
4524: if (useFEM) PetscCall(ISCreate(PETSC_COMM_SELF, &chunkIS));
4525: numCells = cEnd - cStart;
4526: numChunks = 1;
4527: cellChunkSize = numCells / numChunks;
4528: numChunks = PetscMin(1, numCells);
4529: key.label = NULL;
4530: key.value = 0;
4531: key.part = 0;
4532: for (chunk = 0; chunk < numChunks; ++chunk) {
4533: PetscScalar *elemVec, *fluxL = NULL, *fluxR = NULL;
4534: PetscReal *vol = NULL;
4535: PetscFVFaceGeom *fgeom = NULL;
4536: PetscInt cS = cStart + chunk * cellChunkSize, cE = PetscMin(cS + cellChunkSize, cEnd), numCells = cE - cS, c;
4537: PetscInt numFaces = 0;
4539: /* Extract field coefficients */
4540: if (useFEM) {
4541: PetscCall(ISGetPointSubrange(chunkIS, cS, cE, cells));
4542: PetscCall(DMPlexGetCellFields(dm, chunkIS, locX, locX_t, locA, &u, &u_t, &a));
4543: PetscCall(DMGetWorkArray(dm, numCells * totDim, MPIU_SCALAR, &elemVec));
4544: PetscCall(PetscArrayzero(elemVec, numCells * totDim));
4545: }
4546: /* TODO We will interlace both our field coefficients (u, u_t, uL, uR, etc.) and our output (elemVec, fL, fR). I think this works */
4547: /* Loop over fields */
4548: for (f = 0; f < Nf; ++f) {
4549: PetscObject obj;
4550: PetscClassId id;
4551: PetscBool fimp;
4552: PetscInt numChunks, numBatches, batchSize, numBlocks, blockSize, Ne, Nr, offset;
4554: key.field = f;
4555: PetscCall(PetscDSGetImplicit(prob, f, &fimp));
4556: if (isImplicit != fimp) continue;
4557: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
4558: PetscCall(PetscObjectGetClassId(obj, &id));
4559: if (id == PETSCFE_CLASSID) {
4560: PetscFE fe = (PetscFE)obj;
4561: PetscFEGeom *geom = affineGeom ? affineGeom : geoms[f];
4562: PetscFEGeom *chunkGeom = NULL;
4563: PetscQuadrature quad = affineQuad ? affineQuad : quads[f];
4564: PetscInt Nq, Nb;
4566: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
4567: PetscCall(PetscQuadratureGetData(quad, NULL, NULL, &Nq, NULL, NULL));
4568: PetscCall(PetscFEGetDimension(fe, &Nb));
4569: blockSize = Nb;
4570: batchSize = numBlocks * blockSize;
4571: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
4572: numChunks = numCells / (numBatches * batchSize);
4573: Ne = numChunks * numBatches * batchSize;
4574: Nr = numCells % (numBatches * batchSize);
4575: offset = numCells - Nr;
4576: /* Integrate FE residual to get elemVec (need fields at quadrature points) */
4577: /* 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) */
4578: PetscCall(PetscFEGeomGetChunk(geom, 0, offset, &chunkGeom));
4579: PetscCall(PetscFEIntegrateResidual(prob, key, Ne, chunkGeom, u, u_t, probAux, a, t, elemVec));
4580: PetscCall(PetscFEGeomGetChunk(geom, offset, numCells, &chunkGeom));
4581: PetscCall(PetscFEIntegrateResidual(prob, key, Nr, chunkGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), probAux, &a[offset * totDimAux], t, &elemVec[offset * totDim]));
4582: PetscCall(PetscFEGeomRestoreChunk(geom, offset, numCells, &chunkGeom));
4583: } else if (id == PETSCFV_CLASSID) {
4584: PetscFV fv = (PetscFV)obj;
4586: Ne = numFaces;
4587: /* Riemann solve over faces (need fields at face centroids) */
4588: /* We need to evaluate FE fields at those coordinates */
4589: PetscCall(PetscFVIntegrateRHSFunction(fv, prob, f, Ne, fgeom, vol, uL, uR, fluxL, fluxR));
4590: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, f);
4591: }
4592: /* Loop over domain */
4593: if (useFEM) {
4594: /* Add elemVec to locX */
4595: for (c = cS; c < cE; ++c) {
4596: const PetscInt cell = cells ? cells[c] : c;
4597: const PetscInt cind = c - cStart;
4599: if (mesh->printFEM > 1) PetscCall(DMPrintCellVector(cell, name, totDim, &elemVec[cind * totDim]));
4600: if (ghostLabel) {
4601: PetscInt ghostVal;
4603: PetscCall(DMLabelGetValue(ghostLabel, cell, &ghostVal));
4604: if (ghostVal > 0) continue;
4605: }
4606: PetscCall(DMPlexVecSetClosure(dm, section, locF, cell, &elemVec[cind * totDim], ADD_ALL_VALUES));
4607: }
4608: }
4609: /* Handle time derivative */
4610: if (locX_t) {
4611: PetscScalar *x_t, *fa;
4613: PetscCall(VecGetArray(locF, &fa));
4614: PetscCall(VecGetArray(locX_t, &x_t));
4615: for (f = 0; f < Nf; ++f) {
4616: PetscFV fv;
4617: PetscObject obj;
4618: PetscClassId id;
4619: PetscInt pdim;
4621: PetscCall(PetscDSGetDiscretization(prob, f, &obj));
4622: PetscCall(PetscObjectGetClassId(obj, &id));
4623: if (id != PETSCFV_CLASSID) continue;
4624: fv = (PetscFV)obj;
4625: PetscCall(PetscFVGetNumComponents(fv, &pdim));
4626: for (c = cS; c < cE; ++c) {
4627: const PetscInt cell = cells ? cells[c] : c;
4628: PetscScalar *u_t, *r;
4630: if (ghostLabel) {
4631: PetscInt ghostVal;
4633: PetscCall(DMLabelGetValue(ghostLabel, cell, &ghostVal));
4634: if (ghostVal > 0) continue;
4635: }
4636: PetscCall(DMPlexPointLocalFieldRead(dm, cell, f, x_t, &u_t));
4637: PetscCall(DMPlexPointLocalFieldRef(dm, cell, f, fa, &r));
4638: for (PetscInt d = 0; d < pdim; ++d) r[d] += u_t[d];
4639: }
4640: }
4641: PetscCall(VecRestoreArray(locX_t, &x_t));
4642: PetscCall(VecRestoreArray(locF, &fa));
4643: }
4644: if (useFEM) {
4645: PetscCall(DMPlexRestoreCellFields(dm, chunkIS, locX, locX_t, locA, &u, &u_t, &a));
4646: PetscCall(DMRestoreWorkArray(dm, numCells * totDim, MPIU_SCALAR, &elemVec));
4647: }
4648: }
4649: if (useFEM) PetscCall(ISDestroy(&chunkIS));
4650: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
4651: /* TODO Could include boundary residual here (see DMPlexComputeResidualByKey) */
4652: if (useFEM) {
4653: if (maxDegree <= 1) {
4654: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, affineQuad, PETSC_FALSE, &affineGeom));
4655: PetscCall(PetscQuadratureDestroy(&affineQuad));
4656: } else {
4657: for (f = 0; f < Nf; ++f) {
4658: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, quads[f], PETSC_FALSE, &geoms[f]));
4659: PetscCall(PetscQuadratureDestroy(&quads[f]));
4660: }
4661: PetscCall(PetscFree2(quads, geoms));
4662: }
4663: }
4664: PetscCall(PetscLogEventEnd(DMPLEX_ResidualFEM, dm, 0, 0, 0));
4665: PetscFunctionReturn(PETSC_SUCCESS);
4666: }
4668: /*
4669: 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
4671: X - The local solution vector
4672: X_t - The local solution time derivative vector, or NULL
4673: */
4674: 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)
4675: {
4676: DM_Plex *mesh = (DM_Plex *)dm->data;
4677: const char *name = "Jacobian", *nameP = "JacobianPre";
4678: DM dmAux = NULL;
4679: PetscDS prob, probAux = NULL;
4680: PetscSection sectionAux = NULL;
4681: Vec A;
4682: DMField coordField;
4683: PetscFEGeom *cgeomFEM;
4684: PetscQuadrature qGeom = NULL;
4685: Mat J = Jac, JP = JacP;
4686: PetscScalar *work, *u = NULL, *u_t = NULL, *a = NULL, *elemMat = NULL, *elemMatP = NULL, *elemMatD = NULL;
4687: PetscBool hasJac, hasPrec, hasDyn, assembleJac, *isFE, hasFV = PETSC_FALSE;
4688: const PetscInt *cells;
4689: PetscFormKey key;
4690: PetscInt Nf, fieldI, fieldJ, maxDegree, numCells, cStart, cEnd, numChunks, chunkSize, chunk, totDim, totDimAux = 0, sz, wsz, off = 0, offCell = 0;
4692: PetscFunctionBegin;
4693: PetscCall(ISGetLocalSize(cellIS, &numCells));
4694: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
4695: PetscCall(PetscLogEventBegin(DMPLEX_JacobianFEM, dm, 0, 0, 0));
4696: PetscCall(DMGetDS(dm, &prob));
4697: PetscCall(DMGetAuxiliaryVec(dm, NULL, 0, 0, &A));
4698: if (A) {
4699: PetscCall(VecGetDM(A, &dmAux));
4700: PetscCall(DMGetLocalSection(dmAux, §ionAux));
4701: PetscCall(DMGetDS(dmAux, &probAux));
4702: }
4703: /* Get flags */
4704: PetscCall(PetscDSGetNumFields(prob, &Nf));
4705: PetscCall(DMGetWorkArray(dm, Nf, MPI_C_BOOL, &isFE));
4706: for (fieldI = 0; fieldI < Nf; ++fieldI) {
4707: PetscObject disc;
4708: PetscClassId id;
4709: PetscCall(PetscDSGetDiscretization(prob, fieldI, &disc));
4710: PetscCall(PetscObjectGetClassId(disc, &id));
4711: if (id == PETSCFE_CLASSID) {
4712: isFE[fieldI] = PETSC_TRUE;
4713: } else if (id == PETSCFV_CLASSID) {
4714: hasFV = PETSC_TRUE;
4715: isFE[fieldI] = PETSC_FALSE;
4716: }
4717: }
4718: PetscCall(PetscDSHasJacobian(prob, &hasJac));
4719: PetscCall(PetscDSHasJacobianPreconditioner(prob, &hasPrec));
4720: PetscCall(PetscDSHasDynamicJacobian(prob, &hasDyn));
4721: assembleJac = hasJac && hasPrec && (Jac != JacP) ? PETSC_TRUE : PETSC_FALSE;
4722: hasDyn = hasDyn && (X_tShift != 0.0) ? PETSC_TRUE : PETSC_FALSE;
4723: if (hasFV) PetscCall(MatSetOption(JP, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE)); /* No allocated space for FV stuff, so ignore the zero entries */
4724: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
4725: if (probAux) PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
4726: /* Compute batch sizes */
4727: if (isFE[0]) {
4728: PetscFE fe;
4729: PetscQuadrature q;
4730: PetscInt numQuadPoints, numBatches, batchSize, numBlocks, blockSize, Nb;
4732: PetscCall(PetscDSGetDiscretization(prob, 0, (PetscObject *)&fe));
4733: PetscCall(PetscFEGetQuadrature(fe, &q));
4734: PetscCall(PetscQuadratureGetData(q, NULL, NULL, &numQuadPoints, NULL, NULL));
4735: PetscCall(PetscFEGetDimension(fe, &Nb));
4736: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
4737: blockSize = Nb * numQuadPoints;
4738: batchSize = numBlocks * blockSize;
4739: chunkSize = numBatches * batchSize;
4740: numChunks = numCells / chunkSize + numCells % chunkSize;
4741: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
4742: } else {
4743: chunkSize = numCells;
4744: numChunks = 1;
4745: }
4746: /* Get work space */
4747: 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;
4748: PetscCall(DMGetWorkArray(dm, wsz, MPIU_SCALAR, &work));
4749: PetscCall(PetscArrayzero(work, wsz));
4750: off = 0;
4751: u = X ? (sz = chunkSize * totDim, off += sz, work + off - sz) : NULL;
4752: u_t = X_t ? (sz = chunkSize * totDim, off += sz, work + off - sz) : NULL;
4753: a = dmAux ? (sz = chunkSize * totDimAux, off += sz, work + off - sz) : NULL;
4754: elemMat = hasJac ? (sz = chunkSize * totDim * totDim, off += sz, work + off - sz) : NULL;
4755: elemMatP = hasPrec ? (sz = chunkSize * totDim * totDim, off += sz, work + off - sz) : NULL;
4756: elemMatD = hasDyn ? (sz = chunkSize * totDim * totDim, off += sz, work + off - sz) : NULL;
4757: PetscCheck(off == wsz, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Error is workspace size %" PetscInt_FMT " should be %" PetscInt_FMT, off, wsz);
4758: /* Setup geometry */
4759: PetscCall(DMGetCoordinateField(dm, &coordField));
4760: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
4761: if (maxDegree <= 1) PetscCall(DMFieldCreateDefaultQuadrature(coordField, cellIS, &qGeom));
4762: if (!qGeom) {
4763: PetscFE fe;
4765: PetscCall(PetscDSGetDiscretization(prob, 0, (PetscObject *)&fe));
4766: PetscCall(PetscFEGetQuadrature(fe, &qGeom));
4767: PetscCall(PetscObjectReference((PetscObject)qGeom));
4768: }
4769: PetscCall(DMSNESGetFEGeom(coordField, cellIS, qGeom, PETSC_FEGEOM_BASIC, &cgeomFEM));
4770: /* Compute volume integrals */
4771: if (assembleJac) PetscCall(MatZeroEntries(J));
4772: PetscCall(MatZeroEntries(JP));
4773: key.label = NULL;
4774: key.value = 0;
4775: key.part = 0;
4776: for (chunk = 0; chunk < numChunks; ++chunk, offCell += chunkSize) {
4777: const PetscInt Ncell = PetscMin(chunkSize, numCells - offCell);
4779: /* Extract values */
4780: for (PetscInt c = 0; c < Ncell; ++c) {
4781: const PetscInt cell = cells ? cells[c + offCell] : c + offCell;
4782: PetscScalar *x = NULL, *x_t = NULL;
4784: if (X) {
4785: PetscCall(DMPlexVecGetClosure(dm, section, X, cell, NULL, &x));
4786: for (PetscInt i = 0; i < totDim; ++i) u[c * totDim + i] = x[i];
4787: PetscCall(DMPlexVecRestoreClosure(dm, section, X, cell, NULL, &x));
4788: }
4789: if (X_t) {
4790: PetscCall(DMPlexVecGetClosure(dm, section, X_t, cell, NULL, &x_t));
4791: for (PetscInt i = 0; i < totDim; ++i) u_t[c * totDim + i] = x_t[i];
4792: PetscCall(DMPlexVecRestoreClosure(dm, section, X_t, cell, NULL, &x_t));
4793: }
4794: if (dmAux) {
4795: PetscCall(DMPlexVecGetClosure(dmAux, sectionAux, A, cell, NULL, &x));
4796: for (PetscInt i = 0; i < totDimAux; ++i) a[c * totDimAux + i] = x[i];
4797: PetscCall(DMPlexVecRestoreClosure(dmAux, sectionAux, A, cell, NULL, &x));
4798: }
4799: }
4800: for (fieldI = 0; fieldI < Nf; ++fieldI) {
4801: PetscFE fe;
4802: PetscCall(PetscDSGetDiscretization(prob, fieldI, (PetscObject *)&fe));
4803: for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
4804: key.field = fieldI * Nf + fieldJ;
4805: if (hasJac) PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN, key, Ncell, cgeomFEM, u, u_t, probAux, a, t, X_tShift, elemMat));
4806: if (hasPrec) PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN_PRE, key, Ncell, cgeomFEM, u, u_t, probAux, a, t, X_tShift, elemMatP));
4807: if (hasDyn) PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN_DYN, key, Ncell, cgeomFEM, u, u_t, probAux, a, t, X_tShift, elemMatD));
4808: }
4809: /* For finite volume, add the identity */
4810: if (!isFE[fieldI]) {
4811: PetscFV fv;
4812: PetscInt eOffset = 0, Nc, fc, foff;
4814: PetscCall(PetscDSGetFieldOffset(prob, fieldI, &foff));
4815: PetscCall(PetscDSGetDiscretization(prob, fieldI, (PetscObject *)&fv));
4816: PetscCall(PetscFVGetNumComponents(fv, &Nc));
4817: for (PetscInt c = 0; c < chunkSize; ++c, eOffset += totDim * totDim) {
4818: for (fc = 0; fc < Nc; ++fc) {
4819: const PetscInt i = foff + fc;
4820: if (hasJac) elemMat[eOffset + i * totDim + i] = 1.0;
4821: if (hasPrec) elemMatP[eOffset + i * totDim + i] = 1.0;
4822: }
4823: }
4824: }
4825: }
4826: /* Add contribution from X_t */
4827: if (hasDyn) {
4828: for (PetscInt c = 0; c < chunkSize * totDim * totDim; ++c) elemMat[c] += X_tShift * elemMatD[c];
4829: }
4830: /* Insert values into matrix */
4831: for (PetscInt c = 0; c < Ncell; ++c) {
4832: const PetscInt cell = cells ? cells[c + offCell] : c + offCell;
4833: if (mesh->printFEM > 1) {
4834: if (hasJac) PetscCall(DMPrintCellMatrix(cell, name, totDim, totDim, &elemMat[(c - cStart) * totDim * totDim]));
4835: if (hasPrec) PetscCall(DMPrintCellMatrix(cell, nameP, totDim, totDim, &elemMatP[(c - cStart) * totDim * totDim]));
4836: }
4837: if (assembleJac) PetscCall(DMPlexMatSetClosure_Internal(dm, section, globalSection, mesh->useMatClPerm, Jac, cell, &elemMat[(c - cStart) * totDim * totDim], ADD_VALUES));
4838: PetscCall(DMPlexMatSetClosure_Internal(dm, section, globalSection, mesh->useMatClPerm, JP, cell, &elemMat[(c - cStart) * totDim * totDim], ADD_VALUES));
4839: }
4840: }
4841: /* Cleanup */
4842: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, qGeom, PETSC_FALSE, &cgeomFEM));
4843: PetscCall(PetscQuadratureDestroy(&qGeom));
4844: if (hasFV) PetscCall(MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_FALSE));
4845: PetscCall(DMRestoreWorkArray(dm, Nf, MPI_C_BOOL, &isFE));
4846: 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));
4847: /* Compute boundary integrals */
4848: /* PetscCall(DMPlexComputeBdJacobian_Internal(dm, X, X_t, t, X_tShift, Jac, JacP, ctx)); */
4849: /* Assemble matrix */
4850: if (assembleJac) {
4851: PetscCall(MatAssemblyBegin(Jac, MAT_FINAL_ASSEMBLY));
4852: PetscCall(MatAssemblyEnd(Jac, MAT_FINAL_ASSEMBLY));
4853: }
4854: PetscCall(MatAssemblyBegin(JacP, MAT_FINAL_ASSEMBLY));
4855: PetscCall(MatAssemblyEnd(JacP, MAT_FINAL_ASSEMBLY));
4856: PetscCall(PetscLogEventEnd(DMPLEX_JacobianFEM, dm, 0, 0, 0));
4857: PetscFunctionReturn(PETSC_SUCCESS);
4858: }
4860: /* FEM Assembly Function */
4862: static PetscErrorCode DMConvertPlex_Internal(DM dm, DM *plex, PetscBool copy)
4863: {
4864: PetscBool isPlex;
4866: PetscFunctionBegin;
4867: PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMPLEX, &isPlex));
4868: if (isPlex) {
4869: *plex = dm;
4870: PetscCall(PetscObjectReference((PetscObject)dm));
4871: } else {
4872: PetscCall(PetscObjectQuery((PetscObject)dm, "dm_plex", (PetscObject *)plex));
4873: if (!*plex) {
4874: PetscCall(DMConvert(dm, DMPLEX, plex));
4875: PetscCall(PetscObjectCompose((PetscObject)dm, "dm_plex", (PetscObject)*plex));
4876: } else {
4877: PetscCall(PetscObjectReference((PetscObject)*plex));
4878: }
4879: if (copy) PetscCall(DMCopyAuxiliaryVec(dm, *plex));
4880: }
4881: PetscFunctionReturn(PETSC_SUCCESS);
4882: }
4884: /*@
4885: DMPlexGetGeometryFVM - Return precomputed geometric data
4887: Collective
4889: Input Parameter:
4890: . dm - The `DM`
4892: Output Parameters:
4893: + facegeom - The values precomputed from face geometry
4894: . cellgeom - The values precomputed from cell geometry
4895: - minRadius - The minimum radius over the mesh of an inscribed sphere in a cell, or `NULL` if not needed
4897: Level: developer
4899: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMTSSetRHSFunctionLocal()`
4900: @*/
4901: PetscErrorCode DMPlexGetGeometryFVM(DM dm, Vec *facegeom, Vec *cellgeom, PeOp PetscReal *minRadius)
4902: {
4903: DM plex;
4905: PetscFunctionBegin;
4907: PetscCall(DMConvertPlex_Internal(dm, &plex, PETSC_TRUE));
4908: PetscCall(DMPlexGetDataFVM(plex, NULL, cellgeom, facegeom, NULL));
4909: if (minRadius) PetscCall(DMPlexGetMinRadius(plex, minRadius));
4910: PetscCall(DMDestroy(&plex));
4911: PetscFunctionReturn(PETSC_SUCCESS);
4912: }
4914: /*@
4915: DMPlexGetGradientDM - Return gradient data layout
4917: Collective
4919: Input Parameters:
4920: + dm - The `DM`
4921: - fv - The `PetscFV`
4923: Output Parameter:
4924: . dmGrad - The layout for gradient values
4926: Level: developer
4928: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetGeometryFVM()`
4929: @*/
4930: PetscErrorCode DMPlexGetGradientDM(DM dm, PetscFV fv, DM *dmGrad)
4931: {
4932: DM plex;
4933: PetscBool computeGradients;
4935: PetscFunctionBegin;
4938: PetscAssertPointer(dmGrad, 3);
4939: PetscCall(PetscFVGetComputeGradients(fv, &computeGradients));
4940: if (!computeGradients) {
4941: *dmGrad = NULL;
4942: PetscFunctionReturn(PETSC_SUCCESS);
4943: }
4944: PetscCall(DMConvertPlex_Internal(dm, &plex, PETSC_TRUE));
4945: PetscCall(DMPlexGetDataFVM(plex, fv, NULL, NULL, dmGrad));
4946: PetscCall(DMDestroy(&plex));
4947: PetscFunctionReturn(PETSC_SUCCESS);
4948: }
4950: /*@
4951: DMPlexComputeBdResidualSingleByKey - Compute the local boundary residual for terms matching the input key
4953: Not collective
4955: Input Parameters:
4956: + dm - The output `DM`
4957: . wf - The `PetscWeakForm` holding forms on this boundary
4958: . key - The `PetscFormKey` indicating what should be integrated
4959: . facetIS - The `IS` giving a set of faces to integrate over
4960: . locX - The local solution
4961: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
4962: . t - The time
4963: - coordField - The `DMField` object with coordinates for these faces
4965: Output Parameter:
4966: . locF - The local residual
4968: Level: developer
4970: .seealso: `DMPlexComputeBdResidualSingle()`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeResidualHybridByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
4971: @*/
4972: PetscErrorCode DMPlexComputeBdResidualSingleByKey(DM dm, PetscWeakForm wf, PetscFormKey key, IS facetIS, Vec locX, Vec locX_t, PetscReal t, DMField coordField, Vec locF)
4973: {
4974: DM_Plex *mesh = (DM_Plex *)dm->data;
4975: DM plex = NULL, plexA = NULL;
4976: const char *name = "BdResidual";
4977: DMEnclosureType encAux;
4978: PetscDS prob, probAux = NULL;
4979: PetscSection section, sectionAux = NULL;
4980: Vec locA = NULL;
4981: PetscScalar *u = NULL, *u_t = NULL, *a = NULL, *elemVec = NULL;
4982: PetscInt totDim, totDimAux = 0;
4984: PetscFunctionBegin;
4985: PetscCall(DMConvert(dm, DMPLEX, &plex));
4986: PetscCall(DMGetLocalSection(dm, §ion));
4987: PetscCall(DMGetDS(dm, &prob));
4988: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
4989: PetscCall(DMGetAuxiliaryVec(dm, key.label, key.value, key.part, &locA));
4990: if (locA) {
4991: DM dmAux;
4993: PetscCall(VecGetDM(locA, &dmAux));
4994: PetscCall(DMGetEnclosureRelation(dmAux, dm, &encAux));
4995: PetscCall(DMConvert(dmAux, DMPLEX, &plexA));
4996: PetscCall(DMGetDS(plexA, &probAux));
4997: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
4998: PetscCall(DMGetLocalSection(plexA, §ionAux));
4999: }
5000: {
5001: PetscFEGeom *fgeom;
5002: PetscInt maxDegree;
5003: PetscQuadrature qGeom = NULL;
5004: IS pointIS;
5005: const PetscInt *points;
5006: PetscInt numFaces, face, Nq;
5008: PetscCall(DMLabelGetStratumIS(key.label, key.value, &pointIS));
5009: if (!pointIS) goto end; /* No points with that id on this process */
5010: {
5011: IS isectIS;
5013: /* TODO: Special cases of ISIntersect where it is quick to check a priori if one is a superset of the other */
5014: PetscCall(ISIntersect_Caching_Internal(facetIS, pointIS, &isectIS));
5015: PetscCall(ISDestroy(&pointIS));
5016: pointIS = isectIS;
5017: }
5018: PetscCall(ISGetLocalSize(pointIS, &numFaces));
5019: PetscCall(ISGetIndices(pointIS, &points));
5020: PetscCall(PetscMalloc4(numFaces * totDim, &u, (locX_t ? (size_t)numFaces * totDim : 0), &u_t, numFaces * totDim, &elemVec, (locA ? (size_t)numFaces * totDimAux : 0), &a));
5021: PetscCall(DMFieldGetDegree(coordField, pointIS, NULL, &maxDegree));
5022: if (maxDegree <= 1) PetscCall(DMFieldCreateDefaultQuadrature(coordField, pointIS, &qGeom));
5023: if (!qGeom) {
5024: PetscFE fe;
5026: PetscCall(PetscDSGetDiscretization(prob, key.field, (PetscObject *)&fe));
5027: PetscCall(PetscFEGetFaceQuadrature(fe, &qGeom));
5028: PetscCall(PetscObjectReference((PetscObject)qGeom));
5029: }
5030: PetscCall(PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL));
5031: PetscCall(DMSNESGetFEGeom(coordField, pointIS, qGeom, PETSC_FEGEOM_BOUNDARY, &fgeom));
5032: for (face = 0; face < numFaces; ++face) {
5033: const PetscInt point = points[face], *support;
5034: PetscScalar *x = NULL;
5036: PetscCall(DMPlexGetSupport(dm, point, &support));
5037: PetscCall(DMPlexVecGetClosure(plex, section, locX, support[0], NULL, &x));
5038: for (PetscInt i = 0; i < totDim; ++i) u[face * totDim + i] = x[i];
5039: PetscCall(DMPlexVecRestoreClosure(plex, section, locX, support[0], NULL, &x));
5040: if (locX_t) {
5041: PetscCall(DMPlexVecGetClosure(plex, section, locX_t, support[0], NULL, &x));
5042: for (PetscInt i = 0; i < totDim; ++i) u_t[face * totDim + i] = x[i];
5043: PetscCall(DMPlexVecRestoreClosure(plex, section, locX_t, support[0], NULL, &x));
5044: }
5045: if (locA) {
5046: PetscInt subp;
5048: PetscCall(DMGetEnclosurePoint(plexA, dm, encAux, support[0], &subp));
5049: PetscCall(DMPlexVecGetClosure(plexA, sectionAux, locA, subp, NULL, &x));
5050: for (PetscInt i = 0; i < totDimAux; ++i) a[face * totDimAux + i] = x[i];
5051: PetscCall(DMPlexVecRestoreClosure(plexA, sectionAux, locA, subp, NULL, &x));
5052: }
5053: }
5054: PetscCall(PetscArrayzero(elemVec, numFaces * totDim));
5055: {
5056: PetscFE fe;
5057: PetscInt Nb;
5058: PetscFEGeom *chunkGeom = NULL;
5059: /* Conforming batches */
5060: PetscInt numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
5061: /* Remainder */
5062: PetscInt Nr, offset;
5064: PetscCall(PetscDSGetDiscretization(prob, key.field, (PetscObject *)&fe));
5065: PetscCall(PetscFEGetDimension(fe, &Nb));
5066: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
5067: /* TODO: documentation is unclear about what is going on with these numbers: how should Nb / Nq factor in ? */
5068: blockSize = Nb;
5069: batchSize = numBlocks * blockSize;
5070: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
5071: numChunks = numFaces / (numBatches * batchSize);
5072: Ne = numChunks * numBatches * batchSize;
5073: Nr = numFaces % (numBatches * batchSize);
5074: offset = numFaces - Nr;
5075: PetscCall(PetscFEGeomGetChunk(fgeom, 0, offset, &chunkGeom));
5076: PetscCall(PetscFEIntegrateBdResidual(prob, wf, key, Ne, chunkGeom, u, u_t, probAux, a, t, elemVec));
5077: PetscCall(PetscFEGeomRestoreChunk(fgeom, 0, offset, &chunkGeom));
5078: PetscCall(PetscFEGeomGetChunk(fgeom, offset, numFaces, &chunkGeom));
5079: PetscCall(PetscFEIntegrateBdResidual(prob, wf, key, Nr, chunkGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), probAux, PetscSafePointerPlusOffset(a, offset * totDimAux), t, &elemVec[offset * totDim]));
5080: PetscCall(PetscFEGeomRestoreChunk(fgeom, offset, numFaces, &chunkGeom));
5081: }
5082: for (face = 0; face < numFaces; ++face) {
5083: const PetscInt point = points[face], *support;
5085: if (mesh->printFEM > 1) PetscCall(DMPrintCellVector(point, name, totDim, &elemVec[face * totDim]));
5086: PetscCall(DMPlexGetSupport(plex, point, &support));
5087: PetscCall(DMPlexVecSetClosure(plex, NULL, locF, support[0], &elemVec[face * totDim], ADD_ALL_VALUES));
5088: }
5089: PetscCall(DMSNESRestoreFEGeom(coordField, pointIS, qGeom, PETSC_TRUE, &fgeom));
5090: PetscCall(PetscQuadratureDestroy(&qGeom));
5091: PetscCall(ISRestoreIndices(pointIS, &points));
5092: PetscCall(ISDestroy(&pointIS));
5093: PetscCall(PetscFree4(u, u_t, elemVec, a));
5094: }
5095: end:
5096: if (mesh->printFEM) {
5097: PetscSection s;
5098: Vec locFbc;
5099: PetscInt pStart, pEnd, maxDof;
5100: PetscScalar *zeroes;
5102: PetscCall(DMGetLocalSection(dm, &s));
5103: PetscCall(VecDuplicate(locF, &locFbc));
5104: PetscCall(VecCopy(locF, locFbc));
5105: PetscCall(PetscSectionGetChart(s, &pStart, &pEnd));
5106: PetscCall(PetscSectionGetMaxDof(s, &maxDof));
5107: PetscCall(PetscCalloc1(maxDof, &zeroes));
5108: for (PetscInt p = pStart; p < pEnd; p++) PetscCall(VecSetValuesSection(locFbc, s, p, zeroes, INSERT_BC_VALUES));
5109: PetscCall(PetscFree(zeroes));
5110: PetscCall(DMPrintLocalVec(dm, name, mesh->printTol, locFbc));
5111: PetscCall(VecDestroy(&locFbc));
5112: }
5113: PetscCall(DMDestroy(&plex));
5114: PetscCall(DMDestroy(&plexA));
5115: PetscFunctionReturn(PETSC_SUCCESS);
5116: }
5118: /*@
5119: DMPlexComputeBdResidualSingle - Compute the local boundary residual
5121: Not collective
5123: Input Parameters:
5124: + dm - The output `DM`
5125: . wf - The `PetscWeakForm` holding forms on this boundary
5126: . key - The `PetscFormKey` indicating what should be integrated
5127: . locX - The local solution
5128: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
5129: - t - The time
5131: Output Parameter:
5132: . locF - The local residual
5134: Level: developer
5136: .seealso: `DMPlexComputeBdResidualSingleByKey()`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeResidualHybridByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
5137: @*/
5138: PetscErrorCode DMPlexComputeBdResidualSingle(DM dm, PetscWeakForm wf, PetscFormKey key, Vec locX, Vec locX_t, PetscReal t, Vec locF)
5139: {
5140: DMField coordField;
5141: DMLabel depthLabel;
5142: IS facetIS;
5143: PetscInt dim;
5145: PetscFunctionBegin;
5146: PetscCall(DMGetDimension(dm, &dim));
5147: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
5148: PetscCall(DMLabelGetStratumIS(depthLabel, dim - 1, &facetIS));
5149: PetscCall(DMGetCoordinateField(dm, &coordField));
5150: PetscCall(DMPlexComputeBdResidualSingleByKey(dm, wf, key, facetIS, locX, locX_t, t, coordField, locF));
5151: PetscCall(ISDestroy(&facetIS));
5152: PetscFunctionReturn(PETSC_SUCCESS);
5153: }
5155: static PetscErrorCode DMPlexComputeBdResidual_Internal(DM dm, Vec locX, Vec locX_t, PetscReal t, Vec locF, PetscCtx ctx)
5156: {
5157: PetscDS prob;
5158: PetscInt numBd;
5159: DMField coordField = NULL;
5160: IS facetIS = NULL;
5161: DMLabel depthLabel;
5162: PetscInt dim;
5164: PetscFunctionBegin;
5165: PetscCall(DMGetDS(dm, &prob));
5166: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
5167: PetscCall(DMGetDimension(dm, &dim));
5168: PetscCall(DMLabelGetStratumIS(depthLabel, dim - 1, &facetIS));
5169: /* Filter out ghost facets (SF leaves) so that boundary residual contributions
5170: from shared facets are only assembled on the owning rank. Without this,
5171: internal boundary natural BCs at partition junctions get double-counted
5172: because LocalToGlobal with ADD_VALUES sums contributions from all ranks. */
5173: if (facetIS) {
5174: PetscSF sf;
5175: PetscInt nleaves;
5176: const PetscInt *leaves;
5178: PetscCall(DMGetPointSF(dm, &sf));
5179: PetscCall(PetscSFGetGraph(sf, NULL, &nleaves, &leaves, NULL));
5180: if (nleaves > 0 && leaves) {
5181: IS leafIS, ownedFacetIS;
5183: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, nleaves, leaves, PETSC_USE_POINTER, &leafIS));
5184: PetscCall(ISDifference(facetIS, leafIS, &ownedFacetIS));
5185: PetscCall(ISDestroy(&leafIS));
5186: PetscCall(ISDestroy(&facetIS));
5187: facetIS = ownedFacetIS;
5188: }
5189: }
5190: PetscCall(PetscDSGetNumBoundary(prob, &numBd));
5191: for (PetscInt bd = 0; bd < numBd; ++bd) {
5192: PetscWeakForm wf;
5193: DMBoundaryConditionType type;
5194: DMLabel label;
5195: const PetscInt *values;
5196: PetscInt field, numValues, v;
5197: PetscObject obj;
5198: PetscClassId id;
5199: PetscFormKey key;
5201: PetscCall(PetscDSGetBoundary(prob, bd, &wf, &type, NULL, &label, &numValues, &values, &field, NULL, NULL, NULL, NULL, NULL));
5202: if (!(type & DM_BC_NATURAL)) continue;
5203: PetscCall(PetscDSGetDiscretization(prob, field, &obj));
5204: PetscCall(PetscObjectGetClassId(obj, &id));
5205: if (id != PETSCFE_CLASSID) continue;
5206: if (!facetIS) {
5207: DMLabel depthLabel;
5208: PetscInt dim;
5210: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
5211: PetscCall(DMGetDimension(dm, &dim));
5212: PetscCall(DMLabelGetStratumIS(depthLabel, dim - 1, &facetIS));
5213: }
5214: PetscCall(DMGetCoordinateField(dm, &coordField));
5215: for (v = 0; v < numValues; ++v) {
5216: key.label = label;
5217: key.value = values[v];
5218: key.field = field;
5219: key.part = 0;
5220: PetscCall(DMPlexComputeBdResidualSingleByKey(dm, wf, key, facetIS, locX, locX_t, t, coordField, locF));
5221: }
5222: }
5223: PetscCall(ISDestroy(&facetIS));
5224: PetscFunctionReturn(PETSC_SUCCESS);
5225: }
5227: /*@
5228: DMPlexComputeResidualByKey - Compute the local residual for terms matching the input key
5230: Collective
5232: Input Parameters:
5233: + dm - The output `DM`
5234: . key - The `PetscFormKey` indicating what should be integrated
5235: . cellIS - The `IS` giving a set of cells to integrate over
5236: . time - The time, or `PETSC_MIN_REAL` to include implicit terms in a time-independent problems
5237: . locX - The local solution
5238: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
5239: . t - The time
5240: - ctx - An optional application context, passed to the pointwise functions
5242: Output Parameter:
5243: . locF - The local residual
5245: Level: developer
5247: .seealso: `DMPlexComputeJacobianByKey()`, `DMPlexComputeResidualHybridByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
5248: @*/
5249: PetscErrorCode DMPlexComputeResidualByKey(DM dm, PetscFormKey key, IS cellIS, PetscReal time, Vec locX, Vec locX_t, PetscReal t, Vec locF, PetscCtx ctx)
5250: {
5251: DM_Plex *mesh = (DM_Plex *)dm->data;
5252: const char *name = "Residual";
5253: DM dmAux = NULL;
5254: DM dmGrad = NULL;
5255: DMLabel ghostLabel = NULL;
5256: PetscDS ds = NULL;
5257: PetscDS dsAux = NULL;
5258: PetscSection section = NULL;
5259: PetscBool useFEM = PETSC_FALSE;
5260: PetscBool useFVM = PETSC_FALSE;
5261: PetscBool isImplicit = (locX_t || time == PETSC_MIN_REAL) ? PETSC_TRUE : PETSC_FALSE;
5262: PetscFV fvm = NULL;
5263: DMField coordField = NULL;
5264: Vec locA, cellGeometryFVM = NULL, faceGeometryFVM = NULL, locGrad = NULL;
5265: PetscScalar *u = NULL, *u_t, *a, *uL, *uR;
5266: IS chunkIS;
5267: const PetscInt *cells;
5268: PetscInt cStart, cEnd, numCells;
5269: PetscInt Nf, f, totDim, totDimAux, numChunks, cellChunkSize, faceChunkSize, chunk, fStart, fEnd;
5270: PetscInt maxDegree = PETSC_INT_MAX;
5271: PetscQuadrature affineQuad = NULL, *quads = NULL;
5272: PetscFEGeom *affineGeom = NULL, **geoms = NULL;
5274: PetscFunctionBegin;
5275: PetscCall(PetscLogEventBegin(DMPLEX_ResidualFEM, dm, 0, 0, 0));
5276: if (!cellIS) goto end;
5277: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
5278: if (cStart >= cEnd) goto end;
5279: /* TODO The places where we have to use isFE are probably the member functions for the PetscDisc class */
5280: /* TODO The FVM geometry is over-manipulated. Make the precalc functions return exactly what we need */
5281: /* FEM+FVM */
5282: PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
5283: /* 1: Get sizes from dm and dmAux */
5284: PetscCall(DMGetLocalSection(dm, §ion));
5285: PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
5286: PetscCall(DMGetCellDS(dm, cells ? cells[cStart] : cStart, &ds, NULL));
5287: PetscCall(PetscDSGetNumFields(ds, &Nf));
5288: PetscCall(PetscDSGetTotalDimension(ds, &totDim));
5289: PetscCall(DMGetAuxiliaryVec(dm, key.label, key.value, key.part, &locA));
5290: if (locA) {
5291: PetscInt subcell;
5292: PetscCall(VecGetDM(locA, &dmAux));
5293: PetscCall(DMGetEnclosurePoint(dmAux, dm, DM_ENC_UNKNOWN, cells ? cells[cStart] : cStart, &subcell));
5294: PetscCall(DMGetCellDS(dmAux, subcell, &dsAux, NULL));
5295: PetscCall(PetscDSGetTotalDimension(dsAux, &totDimAux));
5296: }
5297: /* 2: Get geometric data */
5298: for (f = 0; f < Nf; ++f) {
5299: PetscObject obj;
5300: PetscClassId id;
5301: PetscBool fimp;
5303: PetscCall(PetscDSGetImplicit(ds, f, &fimp));
5304: if (isImplicit != fimp) continue;
5305: PetscCall(PetscDSGetDiscretization(ds, f, &obj));
5306: PetscCall(PetscObjectGetClassId(obj, &id));
5307: if (id == PETSCFE_CLASSID) useFEM = PETSC_TRUE;
5308: if (id == PETSCFV_CLASSID) {
5309: useFVM = PETSC_TRUE;
5310: fvm = (PetscFV)obj;
5311: }
5312: }
5313: if (useFEM) {
5314: PetscCall(DMGetCoordinateField(dm, &coordField));
5315: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
5316: if (maxDegree <= 1) {
5317: PetscCall(DMFieldCreateDefaultQuadrature(coordField, cellIS, &affineQuad));
5318: if (affineQuad) PetscCall(DMSNESGetFEGeom(coordField, cellIS, affineQuad, PETSC_FEGEOM_BASIC, &affineGeom));
5319: } else {
5320: PetscCall(PetscCalloc2(Nf, &quads, Nf, &geoms));
5321: for (f = 0; f < Nf; ++f) {
5322: PetscObject obj;
5323: PetscClassId id;
5324: PetscBool fimp;
5326: PetscCall(PetscDSGetImplicit(ds, f, &fimp));
5327: if (isImplicit != fimp) continue;
5328: PetscCall(PetscDSGetDiscretization(ds, f, &obj));
5329: PetscCall(PetscObjectGetClassId(obj, &id));
5330: if (id == PETSCFE_CLASSID) {
5331: PetscFE fe = (PetscFE)obj;
5333: PetscCall(PetscFEGetQuadrature(fe, &quads[f]));
5334: PetscCall(PetscObjectReference((PetscObject)quads[f]));
5335: PetscCall(DMSNESGetFEGeom(coordField, cellIS, quads[f], PETSC_FEGEOM_BASIC, &geoms[f]));
5336: }
5337: }
5338: }
5339: }
5340: // Handle non-essential (e.g. outflow) boundary values
5341: if (useFVM) {
5342: PetscCall(DMPlexInsertBoundaryValuesFVM(dm, fvm, locX, time, &locGrad));
5343: PetscCall(DMPlexGetGeometryFVM(dm, &faceGeometryFVM, &cellGeometryFVM, NULL));
5344: PetscCall(DMPlexGetGradientDM(dm, fvm, &dmGrad));
5345: }
5346: /* Loop over chunks */
5347: if (useFEM) PetscCall(ISCreate(PETSC_COMM_SELF, &chunkIS));
5348: numCells = cEnd - cStart;
5349: numChunks = 1;
5350: cellChunkSize = numCells / numChunks;
5351: faceChunkSize = (fEnd - fStart) / numChunks;
5352: numChunks = PetscMin(1, numCells);
5353: for (chunk = 0; chunk < numChunks; ++chunk) {
5354: PetscScalar *elemVec, *fluxL, *fluxR;
5355: PetscReal *vol;
5356: PetscFVFaceGeom *fgeom;
5357: PetscInt cS = cStart + chunk * cellChunkSize, cE = PetscMin(cS + cellChunkSize, cEnd), numCells = cE - cS, c;
5358: PetscInt fS = fStart + chunk * faceChunkSize, fE = PetscMin(fS + faceChunkSize, fEnd), numFaces = 0, face;
5360: /* Extract field coefficients */
5361: if (useFEM) {
5362: PetscCall(ISGetPointSubrange(chunkIS, cS, cE, cells));
5363: PetscCall(DMPlexGetCellFields(dm, chunkIS, locX, locX_t, locA, &u, &u_t, &a));
5364: PetscCall(DMGetWorkArray(dm, numCells * totDim, MPIU_SCALAR, &elemVec));
5365: PetscCall(PetscArrayzero(elemVec, numCells * totDim));
5366: }
5367: if (useFVM) {
5368: PetscCall(DMPlexGetFaceFields(dm, fS, fE, locX, locX_t, faceGeometryFVM, cellGeometryFVM, locGrad, &numFaces, &uL, &uR));
5369: PetscCall(DMPlexGetFaceGeometry(dm, fS, fE, faceGeometryFVM, cellGeometryFVM, &numFaces, &fgeom, &vol));
5370: PetscCall(DMGetWorkArray(dm, numFaces * totDim, MPIU_SCALAR, &fluxL));
5371: PetscCall(DMGetWorkArray(dm, numFaces * totDim, MPIU_SCALAR, &fluxR));
5372: PetscCall(PetscArrayzero(fluxL, numFaces * totDim));
5373: PetscCall(PetscArrayzero(fluxR, numFaces * totDim));
5374: }
5375: /* TODO We will interlace both our field coefficients (u, u_t, uL, uR, etc.) and our output (elemVec, fL, fR). I think this works */
5376: /* Loop over fields */
5377: for (f = 0; f < Nf; ++f) {
5378: PetscObject obj;
5379: PetscClassId id;
5380: PetscBool fimp;
5381: PetscInt numChunks, numBatches, batchSize, numBlocks, blockSize, Ne, Nr, offset;
5383: key.field = f;
5384: PetscCall(PetscDSGetImplicit(ds, f, &fimp));
5385: if (isImplicit != fimp) continue;
5386: PetscCall(PetscDSGetDiscretization(ds, f, &obj));
5387: PetscCall(PetscObjectGetClassId(obj, &id));
5388: if (id == PETSCFE_CLASSID) {
5389: PetscFE fe = (PetscFE)obj;
5390: PetscFEGeom *geom = affineGeom ? affineGeom : geoms[f];
5391: PetscFEGeom *chunkGeom = NULL;
5392: PetscQuadrature quad = affineQuad ? affineQuad : quads[f];
5393: PetscInt Nq, Nb;
5395: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
5396: PetscCall(PetscQuadratureGetData(quad, NULL, NULL, &Nq, NULL, NULL));
5397: PetscCall(PetscFEGetDimension(fe, &Nb));
5398: blockSize = Nb;
5399: batchSize = numBlocks * blockSize;
5400: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
5401: numChunks = numCells / (numBatches * batchSize);
5402: Ne = numChunks * numBatches * batchSize;
5403: Nr = numCells % (numBatches * batchSize);
5404: offset = numCells - Nr;
5405: /* Integrate FE residual to get elemVec (need fields at quadrature points) */
5406: /* 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) */
5407: PetscCall(PetscFEGeomGetChunk(geom, 0, offset, &chunkGeom));
5408: PetscCall(PetscFEIntegrateResidual(ds, key, Ne, chunkGeom, u, u_t, dsAux, a, t, elemVec));
5409: PetscCall(PetscFEGeomGetChunk(geom, offset, numCells, &chunkGeom));
5410: PetscCall(PetscFEIntegrateResidual(ds, key, Nr, chunkGeom, &u[offset * totDim], PetscSafePointerPlusOffset(u_t, offset * totDim), dsAux, PetscSafePointerPlusOffset(a, offset * totDimAux), t, &elemVec[offset * totDim]));
5411: PetscCall(PetscFEGeomRestoreChunk(geom, offset, numCells, &chunkGeom));
5412: } else if (id == PETSCFV_CLASSID) {
5413: PetscFV fv = (PetscFV)obj;
5415: Ne = numFaces;
5416: /* Riemann solve over faces (need fields at face centroids) */
5417: /* We need to evaluate FE fields at those coordinates */
5418: PetscCall(PetscFVIntegrateRHSFunction(fv, ds, f, Ne, fgeom, vol, uL, uR, fluxL, fluxR));
5419: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %" PetscInt_FMT, f);
5420: }
5421: /* Loop over domain */
5422: if (useFEM) {
5423: /* Add elemVec to locX */
5424: for (c = cS; c < cE; ++c) {
5425: const PetscInt cell = cells ? cells[c] : c;
5426: const PetscInt cind = c - cStart;
5428: if (mesh->printFEM > 1) PetscCall(DMPrintCellVector(cell, name, totDim, &elemVec[cind * totDim]));
5429: if (ghostLabel) {
5430: PetscInt ghostVal;
5432: PetscCall(DMLabelGetValue(ghostLabel, cell, &ghostVal));
5433: if (ghostVal > 0) continue;
5434: }
5435: PetscCall(DMPlexVecSetClosure(dm, section, locF, cell, &elemVec[cind * totDim], ADD_ALL_VALUES));
5436: }
5437: }
5438: if (useFVM) {
5439: PetscScalar *fa;
5440: PetscInt iface;
5442: PetscCall(VecGetArray(locF, &fa));
5443: for (f = 0; f < Nf; ++f) {
5444: PetscFV fv;
5445: PetscObject obj;
5446: PetscClassId id;
5447: PetscInt cdim, foff, pdim;
5449: PetscCall(DMGetCoordinateDim(dm, &cdim));
5450: PetscCall(PetscDSGetDiscretization(ds, f, &obj));
5451: PetscCall(PetscDSGetFieldOffset(ds, f, &foff));
5452: PetscCall(PetscObjectGetClassId(obj, &id));
5453: if (id != PETSCFV_CLASSID) continue;
5454: fv = (PetscFV)obj;
5455: PetscCall(PetscFVGetNumComponents(fv, &pdim));
5456: /* Accumulate fluxes to cells */
5457: for (face = fS, iface = 0; face < fE; ++face) {
5458: const PetscInt *scells;
5459: PetscScalar *fL = NULL, *fR = NULL;
5460: PetscInt ghost, d, nsupp, nchild;
5462: PetscCall(DMLabelGetValue(ghostLabel, face, &ghost));
5463: PetscCall(DMPlexGetSupportSize(dm, face, &nsupp));
5464: PetscCall(DMPlexGetTreeChildren(dm, face, &nchild, NULL));
5465: if (ghost >= 0 || nsupp > 2 || nchild > 0) continue;
5466: PetscCall(DMPlexGetSupport(dm, face, &scells));
5467: PetscCall(DMLabelGetValue(ghostLabel, scells[0], &ghost));
5468: if (ghost <= 0) PetscCall(DMPlexPointLocalFieldRef(dm, scells[0], f, fa, &fL));
5469: PetscCall(DMLabelGetValue(ghostLabel, scells[1], &ghost));
5470: if (ghost <= 0) PetscCall(DMPlexPointLocalFieldRef(dm, scells[1], f, fa, &fR));
5471: if (mesh->printFVM > 1) {
5472: PetscCall(DMPrintCellVectorReal(face, "Residual: normal", cdim, fgeom[iface].normal));
5473: PetscCall(DMPrintCellVector(face, "Residual: left state", pdim, &uL[iface * totDim + foff]));
5474: PetscCall(DMPrintCellVector(face, "Residual: right state", pdim, &uR[iface * totDim + foff]));
5475: PetscCall(DMPrintCellVector(face, "Residual: left flux", pdim, &fluxL[iface * totDim + foff]));
5476: PetscCall(DMPrintCellVector(face, "Residual: right flux", pdim, &fluxR[iface * totDim + foff]));
5477: }
5478: for (d = 0; d < pdim; ++d) {
5479: if (fL) fL[d] -= fluxL[iface * totDim + foff + d];
5480: if (fR) fR[d] += fluxR[iface * totDim + foff + d];
5481: }
5482: ++iface;
5483: }
5484: }
5485: PetscCall(VecRestoreArray(locF, &fa));
5486: }
5487: /* Handle time derivative */
5488: if (locX_t) {
5489: PetscScalar *x_t, *fa;
5491: PetscCall(VecGetArray(locF, &fa));
5492: PetscCall(VecGetArray(locX_t, &x_t));
5493: for (f = 0; f < Nf; ++f) {
5494: PetscFV fv;
5495: PetscObject obj;
5496: PetscClassId id;
5497: PetscInt pdim;
5499: PetscCall(PetscDSGetDiscretization(ds, f, &obj));
5500: PetscCall(PetscObjectGetClassId(obj, &id));
5501: if (id != PETSCFV_CLASSID) continue;
5502: fv = (PetscFV)obj;
5503: PetscCall(PetscFVGetNumComponents(fv, &pdim));
5504: for (c = cS; c < cE; ++c) {
5505: const PetscInt cell = cells ? cells[c] : c;
5506: PetscScalar *u_t, *r;
5508: if (ghostLabel) {
5509: PetscInt ghostVal;
5511: PetscCall(DMLabelGetValue(ghostLabel, cell, &ghostVal));
5512: if (ghostVal > 0) continue;
5513: }
5514: PetscCall(DMPlexPointLocalFieldRead(dm, cell, f, x_t, &u_t));
5515: PetscCall(DMPlexPointLocalFieldRef(dm, cell, f, fa, &r));
5516: for (PetscInt d = 0; d < pdim; ++d) r[d] += u_t[d];
5517: }
5518: }
5519: PetscCall(VecRestoreArray(locX_t, &x_t));
5520: PetscCall(VecRestoreArray(locF, &fa));
5521: }
5522: if (useFEM) {
5523: PetscCall(DMPlexRestoreCellFields(dm, chunkIS, locX, locX_t, locA, &u, &u_t, &a));
5524: PetscCall(DMRestoreWorkArray(dm, numCells * totDim, MPIU_SCALAR, &elemVec));
5525: }
5526: if (useFVM) {
5527: PetscCall(DMPlexRestoreFaceFields(dm, fS, fE, locX, locX_t, faceGeometryFVM, cellGeometryFVM, locGrad, &numFaces, &uL, &uR));
5528: PetscCall(DMPlexRestoreFaceGeometry(dm, fS, fE, faceGeometryFVM, cellGeometryFVM, &numFaces, &fgeom, &vol));
5529: PetscCall(DMRestoreWorkArray(dm, numFaces * totDim, MPIU_SCALAR, &fluxL));
5530: PetscCall(DMRestoreWorkArray(dm, numFaces * totDim, MPIU_SCALAR, &fluxR));
5531: if (dmGrad) PetscCall(DMRestoreLocalVector(dmGrad, &locGrad));
5532: }
5533: }
5534: if (useFEM) PetscCall(ISDestroy(&chunkIS));
5535: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
5537: if (useFEM) {
5538: PetscCall(DMPlexComputeBdResidual_Internal(dm, locX, locX_t, t, locF, ctx));
5540: if (maxDegree <= 1) {
5541: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, affineQuad, PETSC_FALSE, &affineGeom));
5542: PetscCall(PetscQuadratureDestroy(&affineQuad));
5543: } else {
5544: for (f = 0; f < Nf; ++f) {
5545: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, quads[f], PETSC_FALSE, &geoms[f]));
5546: PetscCall(PetscQuadratureDestroy(&quads[f]));
5547: }
5548: PetscCall(PetscFree2(quads, geoms));
5549: }
5550: }
5552: /* FEM */
5553: /* 1: Get sizes from dm and dmAux */
5554: /* 2: Get geometric data */
5555: /* 3: Handle boundary values */
5556: /* 4: Loop over domain */
5557: /* Extract coefficients */
5558: /* Loop over fields */
5559: /* Set tiling for FE*/
5560: /* Integrate FE residual to get elemVec */
5561: /* Loop over subdomain */
5562: /* Loop over quad points */
5563: /* Transform coords to real space */
5564: /* Evaluate field and aux fields at point */
5565: /* Evaluate residual at point */
5566: /* Transform residual to real space */
5567: /* Add residual to elemVec */
5568: /* Loop over domain */
5569: /* Add elemVec to locX */
5571: /* FVM */
5572: /* Get geometric data */
5573: /* If using gradients */
5574: /* Compute gradient data */
5575: /* Loop over domain faces */
5576: /* Count computational faces */
5577: /* Reconstruct cell gradient */
5578: /* Loop over domain cells */
5579: /* Limit cell gradients */
5580: /* Handle boundary values */
5581: /* Loop over domain faces */
5582: /* Read out field, centroid, normal, volume for each side of face */
5583: /* Riemann solve over faces */
5584: /* Loop over domain faces */
5585: /* Accumulate fluxes to cells */
5586: /* TODO Change printFEM to printDisc here */
5587: if (mesh->printFEM) {
5588: Vec locFbc;
5589: PetscInt pStart, pEnd, p, maxDof;
5590: PetscScalar *zeroes;
5592: PetscCall(VecDuplicate(locF, &locFbc));
5593: PetscCall(VecCopy(locF, locFbc));
5594: PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
5595: PetscCall(PetscSectionGetMaxDof(section, &maxDof));
5596: PetscCall(PetscCalloc1(maxDof, &zeroes));
5597: for (p = pStart; p < pEnd; p++) PetscCall(VecSetValuesSection(locFbc, section, p, zeroes, INSERT_BC_VALUES));
5598: PetscCall(PetscFree(zeroes));
5599: PetscCall(DMPrintLocalVec(dm, name, mesh->printTol, locFbc));
5600: PetscCall(VecDestroy(&locFbc));
5601: }
5602: end:
5603: PetscCall(PetscLogEventEnd(DMPLEX_ResidualFEM, dm, 0, 0, 0));
5604: PetscFunctionReturn(PETSC_SUCCESS);
5605: }
5607: /*@
5608: DMPlexComputeResidualHybridByKey - Compute the local residual over hybrid cells for terms matching the input key
5610: Collective
5612: Input Parameters:
5613: + dm - The output `DM`
5614: . key - The `PetscFormKey` array (left cell, right cell, cohesive cell) indicating what should be integrated
5615: . cellIS - The `IS` give a set of cells to integrate over
5616: . time - The time, or `PETSC_MIN_REAL` to include implicit terms in a time-independent problems
5617: . locX - The local solution
5618: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
5619: . t - The time
5620: - ctx - An optional application context, passed to the pointwise functions
5622: Output Parameter:
5623: . locF - The local residual
5625: Level: developer
5627: .seealso: `DMPlexComputeResidualByKey()`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
5628: @*/
5629: PetscErrorCode DMPlexComputeResidualHybridByKey(DM dm, PetscFormKey key[], IS cellIS, PetscReal time, Vec locX, Vec locX_t, PetscReal t, Vec locF, PetscCtx ctx)
5630: {
5631: DM_Plex *mesh = (DM_Plex *)dm->data;
5632: const char *name = "Hybrid Residual";
5633: DM dmAux[3] = {NULL, NULL, NULL};
5634: DMLabel ghostLabel = NULL;
5635: PetscDS ds = NULL;
5636: PetscDS dsIn = NULL;
5637: PetscDS dsAux[3] = {NULL, NULL, NULL};
5638: Vec locA[3] = {NULL, NULL, NULL};
5639: DM dmScale[3] = {NULL, NULL, NULL};
5640: PetscDS dsScale[3] = {NULL, NULL, NULL};
5641: Vec locS[3] = {NULL, NULL, NULL};
5642: PetscSection section = NULL;
5643: DMField coordField = NULL;
5644: PetscScalar *a[3] = {NULL, NULL, NULL};
5645: PetscScalar *s[3] = {NULL, NULL, NULL};
5646: PetscScalar *u = NULL, *u_t;
5647: PetscScalar *elemVecNeg, *elemVecPos, *elemVecCoh;
5648: IS chunkISF, chunkISN;
5649: const PetscInt *cells;
5650: PetscInt *faces, *neighbors;
5651: PetscInt cStart, cEnd, numCells;
5652: PetscInt Nf, f, totDim, totDimIn, totDimAux[3], totDimScale[3], numChunks, cellChunkSize, chunk;
5653: PetscInt maxDegree = PETSC_INT_MAX;
5654: PetscQuadrature affineQuadF = NULL, *quadsF = NULL;
5655: PetscFEGeom *affineGeomF = NULL, **geomsF = NULL;
5656: PetscQuadrature affineQuadN = NULL, *quadsN = NULL;
5657: PetscFEGeom *affineGeomN = NULL, **geomsN = NULL;
5659: PetscFunctionBegin;
5660: PetscCall(PetscLogEventBegin(DMPLEX_ResidualFEM, dm, 0, 0, 0));
5661: if (!cellIS) goto end;
5662: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
5663: PetscCall(ISGetLocalSize(cellIS, &numCells));
5664: if (cStart >= cEnd) goto end;
5665: if ((key[0].label == key[1].label) && (key[0].value == key[1].value) && (key[0].part == key[1].part)) {
5666: const char *name;
5667: PetscCall(PetscObjectGetName((PetscObject)key[0].label, &name));
5668: 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);
5669: }
5670: /* TODO The places where we have to use isFE are probably the member functions for the PetscDisc class */
5671: /* FEM */
5672: /* 1: Get sizes from dm and dmAux */
5673: PetscCall(DMGetLocalSection(dm, §ion));
5674: PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
5675: PetscCall(DMGetCellDS(dm, cells ? cells[cStart] : cStart, &ds, &dsIn));
5676: PetscCall(PetscDSGetNumFields(ds, &Nf));
5677: PetscCall(PetscDSGetTotalDimension(ds, &totDim));
5678: PetscCall(PetscDSGetTotalDimension(dsIn, &totDimIn));
5679: PetscCall(DMGetAuxiliaryVec(dm, key[2].label, key[2].value, key[2].part, &locA[2]));
5680: if (locA[2]) {
5681: const PetscInt cellStart = cells ? cells[cStart] : cStart;
5683: PetscCall(VecGetDM(locA[2], &dmAux[2]));
5684: PetscCall(DMGetCellDS(dmAux[2], cellStart, &dsAux[2], NULL));
5685: PetscCall(PetscDSGetTotalDimension(dsAux[2], &totDimAux[2]));
5686: {
5687: const PetscInt *cone;
5688: PetscInt c;
5690: PetscCall(DMPlexGetCone(dm, cellStart, &cone));
5691: for (c = 0; c < 2; ++c) {
5692: const PetscInt *support;
5693: PetscInt ssize, s;
5695: PetscCall(DMPlexGetSupport(dm, cone[c], &support));
5696: PetscCall(DMPlexGetSupportSize(dm, cone[c], &ssize));
5697: 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);
5698: if (support[0] == cellStart) s = 1;
5699: else if (support[1] == cellStart) s = 0;
5700: else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " does not have cell %" PetscInt_FMT " in its support", cone[c], cellStart);
5701: PetscCall(DMGetAuxiliaryVec(dm, key[c].label, key[c].value, key[c].part, &locA[c]));
5702: 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);
5703: if (locA[c]) PetscCall(VecGetDM(locA[c], &dmAux[c]));
5704: else dmAux[c] = dmAux[2];
5705: PetscCall(DMGetCellDS(dmAux[c], support[s], &dsAux[c], NULL));
5706: PetscCall(PetscDSGetTotalDimension(dsAux[c], &totDimAux[c]));
5707: }
5708: }
5709: }
5710: /* Handle mass matrix scaling
5711: The field in key[2] is the field to be scaled, and the scaling field is the first in the dsScale */
5712: PetscCall(DMGetAuxiliaryVec(dm, key[2].label, -key[2].value, key[2].part, &locS[2]));
5713: if (locS[2]) {
5714: const PetscInt cellStart = cells ? cells[cStart] : cStart;
5715: PetscInt Nb, Nbs;
5717: PetscCall(VecGetDM(locS[2], &dmScale[2]));
5718: PetscCall(DMGetCellDS(dmScale[2], cellStart, &dsScale[2], NULL));
5719: PetscCall(PetscDSGetTotalDimension(dsScale[2], &totDimScale[2]));
5720: // BRAD: This is not set correctly
5721: key[2].field = 2;
5722: PetscCall(PetscDSGetFieldSize(ds, key[2].field, &Nb));
5723: PetscCall(PetscDSGetFieldSize(dsScale[2], 0, &Nbs));
5724: 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);
5725: {
5726: const PetscInt *cone;
5728: locS[1] = locS[0] = locS[2];
5729: dmScale[1] = dmScale[0] = dmScale[2];
5730: PetscCall(DMPlexGetCone(dm, cellStart, &cone));
5731: for (PetscInt c = 0; c < 2; ++c) {
5732: const PetscInt *support;
5733: PetscInt ssize, s;
5735: PetscCall(DMPlexGetSupport(dm, cone[c], &support));
5736: PetscCall(DMPlexGetSupportSize(dm, cone[c], &ssize));
5737: 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);
5738: if (support[0] == cellStart) s = 1;
5739: else if (support[1] == cellStart) s = 0;
5740: else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " does not have cell %" PetscInt_FMT " in its support", cone[c], cellStart);
5741: PetscCall(DMGetCellDS(dmScale[c], support[s], &dsScale[c], NULL));
5742: PetscCall(PetscDSGetTotalDimension(dsScale[c], &totDimScale[c]));
5743: }
5744: }
5745: }
5746: /* 2: Setup geometric data */
5747: PetscCall(DMGetCoordinateField(dm, &coordField));
5748: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
5749: if (maxDegree > 1) {
5750: PetscCall(PetscCalloc4(Nf, &quadsF, Nf, &geomsF, Nf, &quadsN, Nf, &geomsN));
5751: for (f = 0; f < Nf; ++f) {
5752: PetscFE fe;
5753: PetscBool isCohesiveField;
5755: PetscCall(PetscDSGetDiscretization(ds, f, (PetscObject *)&fe));
5756: if (fe) {
5757: PetscCall(PetscFEGetQuadrature(fe, &quadsF[f]));
5758: PetscCall(PetscObjectReference((PetscObject)quadsF[f]));
5759: }
5760: PetscCall(PetscDSGetDiscretization(dsIn, f, (PetscObject *)&fe));
5761: PetscCall(PetscDSGetCohesive(dsIn, f, &isCohesiveField));
5762: if (fe) {
5763: if (isCohesiveField) {
5764: for (PetscInt g = 0; g < Nf; ++g) {
5765: PetscCall(PetscDSGetDiscretization(dsIn, g, (PetscObject *)&fe));
5766: PetscCall(PetscDSGetCohesive(dsIn, g, &isCohesiveField));
5767: if (!isCohesiveField) break;
5768: }
5769: }
5770: PetscCall(PetscFEGetQuadrature(fe, &quadsN[f]));
5771: PetscCall(PetscObjectReference((PetscObject)quadsN[f]));
5772: }
5773: }
5774: }
5775: /* Loop over chunks */
5776: cellChunkSize = numCells;
5777: numChunks = !numCells ? 0 : PetscCeilReal(((PetscReal)numCells) / cellChunkSize);
5778: PetscCall(PetscCalloc2(2 * cellChunkSize, &faces, 2 * cellChunkSize, &neighbors));
5779: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 2 * cellChunkSize, faces, PETSC_USE_POINTER, &chunkISF));
5780: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 2 * cellChunkSize, neighbors, PETSC_USE_POINTER, &chunkISN));
5781: /* Extract field coefficients */
5782: /* NOTE This needs the end cap faces to have identical orientations */
5783: PetscCall(DMPlexGetHybridCellFields(dm, cellIS, locX, locX_t, locA[2], &u, &u_t, &a[2]));
5784: PetscCall(DMPlexGetHybridFields(dm, dmAux, dsAux, cellIS, locA, PETSC_TRUE, a));
5785: PetscCall(DMPlexGetHybridFields(dm, dmScale, dsScale, cellIS, locS, PETSC_TRUE, s));
5786: PetscCall(DMGetWorkArray(dm, cellChunkSize * totDim, MPIU_SCALAR, &elemVecNeg));
5787: PetscCall(DMGetWorkArray(dm, cellChunkSize * totDim, MPIU_SCALAR, &elemVecPos));
5788: PetscCall(DMGetWorkArray(dm, cellChunkSize * totDim, MPIU_SCALAR, &elemVecCoh));
5789: for (chunk = 0; chunk < numChunks; ++chunk) {
5790: PetscInt cS = cStart + chunk * cellChunkSize, cE = PetscMin(cS + cellChunkSize, cEnd), numCells = cE - cS, c;
5791: PetscSF sf;
5792: const PetscInt *leaves;
5793: PetscInt Nl;
5795: PetscCall(PetscArrayzero(elemVecNeg, cellChunkSize * totDim));
5796: PetscCall(PetscArrayzero(elemVecPos, cellChunkSize * totDim));
5797: PetscCall(PetscArrayzero(elemVecCoh, cellChunkSize * totDim));
5798: /* Get faces and neighbors */
5799: PetscCall(DMGetPointSF(dm, &sf));
5800: PetscCall(PetscSFGetGraph(sf, NULL, &Nl, &leaves, NULL));
5801: for (c = cS; c < cE; ++c) {
5802: const PetscInt cell = cells ? cells[c] : c;
5803: const PetscInt *cone, *support;
5804: PetscInt pos = -1;
5806: if (leaves) PetscCall(PetscFindInt(cell, Nl, leaves, &pos));
5807: PetscCheck(pos < 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Hybrid Cell %" PetscInt_FMT " is a ghost cell, so it should not be assembled", cell);
5808: PetscCall(DMPlexGetCone(dm, cell, &cone));
5809: faces[(c - cS) * 2 + 0] = cone[0];
5810: faces[(c - cS) * 2 + 1] = cone[1];
5811: PetscCall(DMPlexGetSupport(dm, cone[0], &support));
5812: neighbors[(c - cS) * 2 + 0] = support[0] == cell ? support[1] : support[0];
5813: PetscCall(DMPlexGetSupport(dm, cone[1], &support));
5814: neighbors[(c - cS) * 2 + 1] = support[0] == cell ? support[1] : support[0];
5815: }
5816: PetscCall(ISGeneralSetIndices(chunkISF, 2 * cellChunkSize, faces, PETSC_USE_POINTER));
5817: PetscCall(ISGeneralSetIndices(chunkISN, 2 * cellChunkSize, neighbors, PETSC_USE_POINTER));
5818: /* Get geometric data */
5819: if (maxDegree <= 1) {
5820: if (!affineQuadF) PetscCall(DMFieldCreateDefaultQuadrature(coordField, chunkISF, &affineQuadF));
5821: if (affineQuadF) PetscCall(DMSNESGetFEGeom(coordField, chunkISF, affineQuadF, PETSC_FEGEOM_COHESIVE, &affineGeomF));
5822: if (!affineQuadN) {
5823: PetscInt dim;
5824: PetscCall(PetscQuadratureGetData(affineQuadF, &dim, NULL, NULL, NULL, NULL));
5825: PetscCall(DMFieldCreateDefaultFaceQuadrature(coordField, chunkISN, &affineQuadN));
5826: PetscCall(PetscQuadratureSetData(affineQuadN, dim + 1, PETSC_DECIDE, PETSC_DECIDE, NULL, NULL));
5827: }
5828: if (affineQuadN) PetscCall(DMSNESGetFEGeom(coordField, chunkISN, affineQuadN, PETSC_FEGEOM_BASIC, &affineGeomN));
5829: } else {
5830: for (f = 0; f < Nf; ++f) {
5831: if (quadsF[f]) PetscCall(DMSNESGetFEGeom(coordField, chunkISF, quadsF[f], PETSC_FEGEOM_COHESIVE, &geomsF[f]));
5832: if (quadsN[f]) PetscCall(DMSNESGetFEGeom(coordField, chunkISN, quadsN[f], PETSC_FEGEOM_BASIC, &geomsN[f]));
5833: }
5834: }
5835: /* Loop over fields */
5836: for (f = 0; f < Nf; ++f) {
5837: PetscFE fe;
5838: PetscFEGeom *geomF = affineGeomF ? affineGeomF : geomsF[f];
5839: PetscFEGeom *chunkGeomF = NULL, *remGeomF = NULL;
5840: PetscFEGeom *geomN = affineGeomN ? affineGeomN : geomsN[f];
5841: PetscFEGeom *chunkGeomN = NULL, *remGeomN = NULL;
5842: PetscQuadrature quadF = affineQuadF ? affineQuadF : quadsF[f];
5843: PetscInt numChunks, numBatches, batchSize, numBlocks, blockSize, Ne, Nr, offset, Nq, Nb;
5844: PetscBool isCohesiveField;
5846: PetscCall(PetscDSGetDiscretization(ds, f, (PetscObject *)&fe));
5847: if (!fe) continue;
5848: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
5849: PetscCall(PetscQuadratureGetData(quadF, NULL, NULL, &Nq, NULL, NULL));
5850: PetscCall(PetscFEGetDimension(fe, &Nb));
5851: blockSize = Nb;
5852: batchSize = numBlocks * blockSize;
5853: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
5854: numChunks = numCells / (numBatches * batchSize);
5855: Ne = numChunks * numBatches * batchSize;
5856: Nr = numCells % (numBatches * batchSize);
5857: offset = numCells - Nr;
5858: PetscCall(PetscFEGeomGetChunk(geomF, 0, offset * 2, &chunkGeomF));
5859: PetscCall(PetscFEGeomGetChunk(geomF, offset * 2, numCells * 2, &remGeomF));
5860: PetscCall(PetscFEGeomGetChunk(geomN, 0, offset * 2, &chunkGeomN));
5861: PetscCall(PetscFEGeomGetChunk(geomN, offset * 2, numCells * 2, &remGeomN));
5862: PetscCall(PetscDSGetCohesive(ds, f, &isCohesiveField));
5863: // TODO Do I need to set isCohesive on the chunks?
5864: key[0].field = f;
5865: key[1].field = f;
5866: key[2].field = f;
5867: PetscCall(PetscFEIntegrateHybridResidual(ds, dsIn, key[0], 0, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[0], a[0], t, elemVecNeg));
5868: 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]));
5869: PetscCall(PetscFEIntegrateHybridResidual(ds, dsIn, key[1], 1, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[1], a[1], t, elemVecPos));
5870: 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]));
5871: PetscCall(PetscFEIntegrateHybridResidual(ds, dsIn, key[2], 2, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[2], a[2], t, elemVecCoh));
5872: 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]));
5873: PetscCall(PetscFEGeomRestoreChunk(geomF, offset, numCells, &remGeomF));
5874: PetscCall(PetscFEGeomRestoreChunk(geomF, 0, offset, &chunkGeomF));
5875: PetscCall(PetscFEGeomRestoreChunk(geomN, offset, numCells, &remGeomN));
5876: PetscCall(PetscFEGeomRestoreChunk(geomN, 0, offset, &chunkGeomN));
5877: }
5878: /* Add elemVec to locX */
5879: for (c = cS; c < cE; ++c) {
5880: const PetscInt cell = cells ? cells[c] : c;
5881: const PetscInt cind = c - cStart;
5883: /* Scale element values */
5884: if (locS[0]) {
5885: PetscInt Nb, off = cind * totDim, soff = cind * totDimScale[0];
5886: PetscBool cohesive;
5888: for (f = 0; f < Nf; ++f) {
5889: PetscCall(PetscDSGetFieldSize(ds, f, &Nb));
5890: PetscCall(PetscDSGetCohesive(ds, f, &cohesive));
5891: if (f == key[2].field) {
5892: PetscCheck(cohesive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Scaling should not happen for face fields");
5893: // No cohesive scaling field is currently input
5894: for (PetscInt i = 0; i < Nb; ++i) elemVecCoh[off + i] += s[0][soff + i] * elemVecNeg[off + i] + s[1][soff + i] * elemVecPos[off + i];
5895: off += Nb;
5896: } else {
5897: const PetscInt N = cohesive ? Nb : Nb * 2;
5899: for (PetscInt i = 0; i < N; ++i) elemVecCoh[off + i] += elemVecNeg[off + i] + elemVecPos[off + i];
5900: off += N;
5901: }
5902: }
5903: } else {
5904: for (PetscInt i = cind * totDim; i < (cind + 1) * totDim; ++i) elemVecCoh[i] += elemVecNeg[i] + elemVecPos[i];
5905: }
5906: if (mesh->printFEM > 1) PetscCall(DMPrintCellVector(cell, name, totDim, &elemVecCoh[cind * totDim]));
5907: if (ghostLabel) {
5908: PetscInt ghostVal;
5910: PetscCall(DMLabelGetValue(ghostLabel, cell, &ghostVal));
5911: if (ghostVal > 0) continue;
5912: }
5913: PetscCall(DMPlexVecSetClosure(dm, section, locF, cell, &elemVecCoh[cind * totDim], ADD_ALL_VALUES));
5914: }
5915: }
5916: PetscCall(DMPlexRestoreCellFields(dm, cellIS, locX, locX_t, locA[2], &u, &u_t, &a[2]));
5917: PetscCall(DMPlexRestoreHybridFields(dm, dmAux, dsAux, cellIS, locA, PETSC_TRUE, a));
5918: PetscCall(DMPlexRestoreHybridFields(dm, dmScale, dsScale, cellIS, locS, PETSC_TRUE, s));
5919: PetscCall(DMRestoreWorkArray(dm, numCells * totDim, MPIU_SCALAR, &elemVecNeg));
5920: PetscCall(DMRestoreWorkArray(dm, numCells * totDim, MPIU_SCALAR, &elemVecPos));
5921: PetscCall(DMRestoreWorkArray(dm, numCells * totDim, MPIU_SCALAR, &elemVecCoh));
5922: PetscCall(PetscFree2(faces, neighbors));
5923: PetscCall(ISDestroy(&chunkISF));
5924: PetscCall(ISDestroy(&chunkISN));
5925: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
5926: if (maxDegree <= 1) {
5927: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, affineQuadF, PETSC_FALSE, &affineGeomF));
5928: PetscCall(PetscQuadratureDestroy(&affineQuadF));
5929: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, affineQuadN, PETSC_FALSE, &affineGeomN));
5930: PetscCall(PetscQuadratureDestroy(&affineQuadN));
5931: } else {
5932: for (f = 0; f < Nf; ++f) {
5933: if (geomsF) PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, quadsF[f], PETSC_FALSE, &geomsF[f]));
5934: if (quadsF) PetscCall(PetscQuadratureDestroy(&quadsF[f]));
5935: if (geomsN) PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, quadsN[f], PETSC_FALSE, &geomsN[f]));
5936: if (quadsN) PetscCall(PetscQuadratureDestroy(&quadsN[f]));
5937: }
5938: PetscCall(PetscFree4(quadsF, geomsF, quadsN, geomsN));
5939: }
5940: if (mesh->printFEM) {
5941: Vec locFbc;
5942: PetscInt pStart, pEnd, p, maxDof;
5943: PetscScalar *zeroes;
5945: PetscCall(VecDuplicate(locF, &locFbc));
5946: PetscCall(VecCopy(locF, locFbc));
5947: PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
5948: PetscCall(PetscSectionGetMaxDof(section, &maxDof));
5949: PetscCall(PetscCalloc1(maxDof, &zeroes));
5950: for (p = pStart; p < pEnd; p++) PetscCall(VecSetValuesSection(locFbc, section, p, zeroes, INSERT_BC_VALUES));
5951: PetscCall(PetscFree(zeroes));
5952: PetscCall(DMPrintLocalVec(dm, name, mesh->printTol, locFbc));
5953: PetscCall(VecDestroy(&locFbc));
5954: }
5955: end:
5956: PetscCall(PetscLogEventEnd(DMPLEX_ResidualFEM, dm, 0, 0, 0));
5957: PetscFunctionReturn(PETSC_SUCCESS);
5958: }
5960: /*@
5961: DMPlexComputeBdJacobianSingleByLabel - Compute the local boundary Jacobian for terms matching the input label
5963: Not collective
5965: Input Parameters:
5966: + dm - The output `DM`
5967: . wf - The `PetscWeakForm` holding forms on this boundary
5968: . label - The `DMLabel` indicating what faces should be integrated over
5969: . numValues - The number of label values
5970: . values - The array of label values
5971: . fieldI - The test field for these integrals
5972: . facetIS - The `IS` giving the set of possible faces to integrate over (intersected with the label)
5973: . locX - The local solution
5974: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
5975: . t - The time
5976: . coordField - The `DMField` object with coordinates for these faces
5977: - X_tShift - The multiplier for dF/dxdot
5979: Output Parameters:
5980: + Jac - The local Jacobian
5981: - JacP - The local Jacobian preconditioner
5983: Level: developer
5985: .seealso: `DMPlexComputeBdJacobianSingle()`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeResidualHybridByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
5986: @*/
5987: 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)
5988: {
5989: DM_Plex *mesh = (DM_Plex *)dm->data;
5990: DM plex = NULL, plexA = NULL, tdm;
5991: DMEnclosureType encAux;
5992: PetscDS ds, dsAux = NULL;
5993: PetscSection section, sectionAux = NULL;
5994: PetscSection globalSection;
5995: Vec locA = NULL, tv;
5996: PetscScalar *u = NULL, *u_t = NULL, *a = NULL, *elemMat = NULL, *elemMatP = NULL;
5997: PetscInt Nf, totDim, totDimAux = 0;
5998: PetscBool hasJac = PETSC_FALSE, hasPrec = PETSC_FALSE, transform;
6000: PetscFunctionBegin;
6001: PetscCall(DMHasBasisTransform(dm, &transform));
6002: PetscCall(DMGetBasisTransformDM_Internal(dm, &tdm));
6003: PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
6004: PetscCall(DMGetLocalSection(dm, §ion));
6005: PetscCall(DMGetDS(dm, &ds));
6006: PetscCall(PetscDSGetNumFields(ds, &Nf));
6007: PetscCall(PetscDSGetTotalDimension(ds, &totDim));
6008: PetscCall(PetscWeakFormHasBdJacobian(wf, &hasJac));
6009: PetscCall(PetscWeakFormHasBdJacobianPreconditioner(wf, &hasPrec));
6010: if (!hasJac && !hasPrec) PetscFunctionReturn(PETSC_SUCCESS);
6011: PetscCall(DMConvert(dm, DMPLEX, &plex));
6012: PetscCall(DMGetAuxiliaryVec(dm, label, values[0], 0, &locA));
6013: if (locA) {
6014: DM dmAux;
6016: PetscCall(VecGetDM(locA, &dmAux));
6017: PetscCall(DMGetEnclosureRelation(dmAux, dm, &encAux));
6018: PetscCall(DMConvert(dmAux, DMPLEX, &plexA));
6019: PetscCall(DMGetDS(plexA, &dsAux));
6020: PetscCall(PetscDSGetTotalDimension(dsAux, &totDimAux));
6021: PetscCall(DMGetLocalSection(plexA, §ionAux));
6022: }
6024: PetscCall(DMGetGlobalSection(dm, &globalSection));
6025: for (PetscInt v = 0; v < numValues; ++v) {
6026: PetscFEGeom *fgeom;
6027: PetscInt maxDegree;
6028: PetscQuadrature qGeom = NULL;
6029: IS pointIS;
6030: const PetscInt *points;
6031: PetscFormKey key;
6032: PetscInt numFaces, face, Nq;
6034: key.label = label;
6035: key.value = values[v];
6036: key.part = 0;
6037: PetscCall(DMLabelGetStratumIS(label, values[v], &pointIS));
6038: if (!pointIS) continue; /* No points with that id on this process */
6039: {
6040: IS isectIS;
6042: /* TODO: Special cases of ISIntersect where it is quick to check a prior if one is a superset of the other */
6043: PetscCall(ISIntersect_Caching_Internal(facetIS, pointIS, &isectIS));
6044: PetscCall(ISDestroy(&pointIS));
6045: pointIS = isectIS;
6046: }
6047: PetscCall(ISGetLocalSize(pointIS, &numFaces));
6048: PetscCall(ISGetIndices(pointIS, &points));
6049: 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));
6050: PetscCall(DMFieldGetDegree(coordField, pointIS, NULL, &maxDegree));
6051: if (maxDegree <= 1) PetscCall(DMFieldCreateDefaultQuadrature(coordField, pointIS, &qGeom));
6052: if (!qGeom) {
6053: PetscFE fe;
6055: PetscCall(PetscDSGetDiscretization(ds, fieldI, (PetscObject *)&fe));
6056: PetscCall(PetscFEGetFaceQuadrature(fe, &qGeom));
6057: PetscCall(PetscObjectReference((PetscObject)qGeom));
6058: }
6059: PetscCall(PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL));
6060: PetscCall(DMSNESGetFEGeom(coordField, pointIS, qGeom, PETSC_FEGEOM_BOUNDARY, &fgeom));
6061: for (face = 0; face < numFaces; ++face) {
6062: const PetscInt point = points[face], *support;
6063: PetscScalar *x = NULL;
6065: PetscCall(DMPlexGetSupport(dm, point, &support));
6066: PetscCall(DMPlexVecGetClosure(plex, section, locX, support[0], NULL, &x));
6067: for (PetscInt i = 0; i < totDim; ++i) u[face * totDim + i] = x[i];
6068: PetscCall(DMPlexVecRestoreClosure(plex, section, locX, support[0], NULL, &x));
6069: if (locX_t) {
6070: PetscCall(DMPlexVecGetClosure(plex, section, locX_t, support[0], NULL, &x));
6071: for (PetscInt i = 0; i < totDim; ++i) u_t[face * totDim + i] = x[i];
6072: PetscCall(DMPlexVecRestoreClosure(plex, section, locX_t, support[0], NULL, &x));
6073: }
6074: if (locA) {
6075: PetscInt subp;
6076: PetscCall(DMGetEnclosurePoint(plexA, dm, encAux, support[0], &subp));
6077: PetscCall(DMPlexVecGetClosure(plexA, sectionAux, locA, subp, NULL, &x));
6078: for (PetscInt i = 0; i < totDimAux; ++i) a[face * totDimAux + i] = x[i];
6079: PetscCall(DMPlexVecRestoreClosure(plexA, sectionAux, locA, subp, NULL, &x));
6080: }
6081: }
6082: if (elemMat) PetscCall(PetscArrayzero(elemMat, numFaces * totDim * totDim));
6083: if (elemMatP) PetscCall(PetscArrayzero(elemMatP, numFaces * totDim * totDim));
6084: {
6085: PetscFE fe;
6086: PetscInt Nb;
6087: /* Conforming batches */
6088: PetscInt numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
6089: /* Remainder */
6090: PetscFEGeom *chunkGeom = NULL;
6091: PetscInt fieldJ, Nr, offset;
6093: PetscCall(PetscDSGetDiscretization(ds, fieldI, (PetscObject *)&fe));
6094: PetscCall(PetscFEGetDimension(fe, &Nb));
6095: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
6096: blockSize = Nb;
6097: batchSize = numBlocks * blockSize;
6098: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
6099: numChunks = numFaces / (numBatches * batchSize);
6100: Ne = numChunks * numBatches * batchSize;
6101: Nr = numFaces % (numBatches * batchSize);
6102: offset = numFaces - Nr;
6103: PetscCall(PetscFEGeomGetChunk(fgeom, 0, offset, &chunkGeom));
6104: for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
6105: key.field = fieldI * Nf + fieldJ;
6106: if (hasJac) PetscCall(PetscFEIntegrateBdJacobian(ds, wf, PETSCFE_JACOBIAN, key, Ne, chunkGeom, u, u_t, dsAux, a, t, X_tShift, elemMat));
6107: if (hasPrec) PetscCall(PetscFEIntegrateBdJacobian(ds, wf, PETSCFE_JACOBIAN_PRE, key, Ne, chunkGeom, u, u_t, dsAux, a, t, X_tShift, elemMatP));
6108: }
6109: PetscCall(PetscFEGeomGetChunk(fgeom, offset, numFaces, &chunkGeom));
6110: for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
6111: key.field = fieldI * Nf + fieldJ;
6112: if (hasJac)
6113: 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]));
6114: if (hasPrec)
6115: 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]));
6116: }
6117: PetscCall(PetscFEGeomRestoreChunk(fgeom, offset, numFaces, &chunkGeom));
6118: }
6119: for (face = 0; face < numFaces; ++face) {
6120: const PetscInt point = points[face], *support;
6122: /* Transform to global basis before insertion in Jacobian */
6123: PetscCall(DMPlexGetSupport(plex, point, &support));
6124: if (hasJac && transform) PetscCall(DMPlexBasisTransformPointTensor_Internal(dm, tdm, tv, support[0], PETSC_TRUE, totDim, &elemMat[face * totDim * totDim]));
6125: if (hasPrec && transform) PetscCall(DMPlexBasisTransformPointTensor_Internal(dm, tdm, tv, support[0], PETSC_TRUE, totDim, &elemMatP[face * totDim * totDim]));
6126: if (hasPrec) {
6127: if (hasJac) {
6128: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(point, "BdJacobian", totDim, totDim, &elemMat[face * totDim * totDim]));
6129: PetscCall(DMPlexMatSetClosure_Internal(plex, section, globalSection, mesh->useMatClPerm, Jac, support[0], &elemMat[face * totDim * totDim], ADD_VALUES));
6130: }
6131: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(point, "BdJacobian", totDim, totDim, &elemMatP[face * totDim * totDim]));
6132: PetscCall(DMPlexMatSetClosure_Internal(plex, section, globalSection, mesh->useMatClPerm, JacP, support[0], &elemMatP[face * totDim * totDim], ADD_VALUES));
6133: } else {
6134: if (hasJac) {
6135: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(point, "BdJacobian", totDim, totDim, &elemMat[face * totDim * totDim]));
6136: PetscCall(DMPlexMatSetClosure_Internal(plex, section, globalSection, mesh->useMatClPerm, Jac, support[0], &elemMat[face * totDim * totDim], ADD_VALUES));
6137: }
6138: }
6139: }
6140: PetscCall(DMSNESRestoreFEGeom(coordField, pointIS, qGeom, PETSC_TRUE, &fgeom));
6141: PetscCall(PetscQuadratureDestroy(&qGeom));
6142: PetscCall(ISRestoreIndices(pointIS, &points));
6143: PetscCall(ISDestroy(&pointIS));
6144: PetscCall(PetscFree5(u, u_t, elemMat, elemMatP, a));
6145: }
6146: PetscCall(DMDestroy(&plex));
6147: PetscCall(DMDestroy(&plexA));
6148: PetscFunctionReturn(PETSC_SUCCESS);
6149: }
6151: /*@
6152: DMPlexComputeBdJacobianSingle - Compute the local boundary Jacobian
6154: Not collective
6156: Input Parameters:
6157: + dm - The output `DM`
6158: . wf - The `PetscWeakForm` holding forms on this boundary
6159: . label - The `DMLabel` indicating what faces should be integrated over
6160: . numValues - The number of label values
6161: . values - The array of label values
6162: . fieldI - The test field for these integrals
6163: . locX - The local solution
6164: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
6165: . t - The time
6166: - X_tShift - The multiplier for dF/dxdot
6168: Output Parameters:
6169: + Jac - The local Jacobian
6170: - JacP - The local Jacobian preconditioner
6172: Level: developer
6174: .seealso: `DMPlexComputeBdJacobianSingleByLabel()`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeResidualHybridByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
6175: @*/
6176: 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)
6177: {
6178: DMField coordField;
6179: DMLabel depthLabel;
6180: IS facetIS;
6181: PetscInt dim;
6183: PetscFunctionBegin;
6184: PetscCall(DMGetDimension(dm, &dim));
6185: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
6186: PetscCall(DMLabelGetStratumIS(depthLabel, dim - 1, &facetIS));
6187: PetscCall(DMGetCoordinateField(dm, &coordField));
6188: PetscCall(DMPlexComputeBdJacobianSingleByLabel(dm, wf, label, numValues, values, fieldI, facetIS, locX, locX_t, t, coordField, X_tShift, Jac, JacP));
6189: PetscCall(ISDestroy(&facetIS));
6190: PetscFunctionReturn(PETSC_SUCCESS);
6191: }
6193: static PetscErrorCode DMPlexComputeBdJacobian_Internal(DM dm, Vec locX, Vec locX_t, PetscReal t, PetscReal X_tShift, Mat Jac, Mat JacP, PetscCtx ctx)
6194: {
6195: PetscDS prob;
6196: PetscInt dim, numBd, bd;
6197: DMLabel depthLabel;
6198: DMField coordField = NULL;
6199: IS facetIS;
6201: PetscFunctionBegin;
6202: PetscCall(DMGetDS(dm, &prob));
6203: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
6204: PetscCall(DMGetDimension(dm, &dim));
6205: PetscCall(DMLabelGetStratumIS(depthLabel, dim - 1, &facetIS));
6206: PetscCall(PetscDSGetNumBoundary(prob, &numBd));
6207: PetscCall(DMGetCoordinateField(dm, &coordField));
6208: for (bd = 0; bd < numBd; ++bd) {
6209: PetscWeakForm wf;
6210: DMBoundaryConditionType type;
6211: DMLabel label;
6212: const PetscInt *values;
6213: PetscInt fieldI, numValues;
6214: PetscObject obj;
6215: PetscClassId id;
6217: PetscCall(PetscDSGetBoundary(prob, bd, &wf, &type, NULL, &label, &numValues, &values, &fieldI, NULL, NULL, NULL, NULL, NULL));
6218: if (type & DM_BC_ESSENTIAL) continue;
6219: PetscCall(PetscDSGetDiscretization(prob, fieldI, &obj));
6220: PetscCall(PetscObjectGetClassId(obj, &id));
6221: if (id != PETSCFE_CLASSID) continue;
6222: PetscCall(DMPlexComputeBdJacobianSingleByLabel(dm, wf, label, numValues, values, fieldI, facetIS, locX, locX_t, t, coordField, X_tShift, Jac, JacP));
6223: }
6224: PetscCall(ISDestroy(&facetIS));
6225: PetscFunctionReturn(PETSC_SUCCESS);
6226: }
6228: /*@
6229: DMPlexComputeJacobianByKey - Compute the local Jacobian for terms matching the input key
6231: Collective
6233: Input Parameters:
6234: + dm - The output `DM`
6235: . key - The `PetscFormKey` indicating what should be integrated
6236: . cellIS - The `IS` give a set of cells to integrate over
6237: . t - The time
6238: . X_tShift - The multiplier for the Jacobian with respect to $X_t$
6239: . locX - The local solution
6240: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
6241: - ctx - An optional application context, passed to the pointwise functions
6243: Output Parameters:
6244: + Jac - The local Jacobian
6245: - JacP - The local Jacobian preconditioner
6247: Level: developer
6249: .seealso: `DMPlexComputeResidualByKey()`, `DMPlexComputeResidualHybridByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
6250: @*/
6251: PetscErrorCode DMPlexComputeJacobianByKey(DM dm, PetscFormKey key, IS cellIS, PetscReal t, PetscReal X_tShift, Vec locX, Vec locX_t, Mat Jac, Mat JacP, PetscCtx ctx)
6252: {
6253: DM_Plex *mesh = (DM_Plex *)dm->data;
6254: const char *name = "Jacobian";
6255: DM dmAux = NULL, plex, tdm;
6256: DMEnclosureType encAux;
6257: Vec A, tv;
6258: DMField coordField;
6259: PetscDS prob, probAux = NULL;
6260: PetscSection section, globalSection, sectionAux;
6261: PetscScalar *elemMat, *elemMatP, *elemMatD, *u, *u_t, *a = NULL;
6262: const PetscInt *cells;
6263: PetscInt Nf, fieldI, fieldJ;
6264: PetscInt totDim, totDimAux = 0, cStart, cEnd, numCells, c;
6265: PetscBool hasJac = PETSC_FALSE, hasPrec = PETSC_FALSE, hasDyn, hasFV = PETSC_FALSE, transform;
6267: PetscFunctionBegin;
6268: PetscCall(PetscLogEventBegin(DMPLEX_JacobianFEM, dm, 0, 0, 0));
6269: PetscCall(DMGetLocalSection(dm, §ion));
6270: PetscCall(DMGetGlobalSection(dm, &globalSection));
6271: PetscCall(DMGetAuxiliaryVec(dm, key.label, key.value, key.part, &A));
6272: if (A) {
6273: PetscCall(VecGetDM(A, &dmAux));
6274: PetscCall(DMGetEnclosureRelation(dmAux, dm, &encAux));
6275: PetscCall(DMConvert(dmAux, DMPLEX, &plex));
6276: PetscCall(DMGetLocalSection(plex, §ionAux));
6277: PetscCall(DMGetDS(dmAux, &probAux));
6278: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
6279: }
6280: PetscCall(DMGetCoordinateField(dm, &coordField));
6281: if (!cellIS) goto end;
6282: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
6283: PetscCall(ISGetLocalSize(cellIS, &numCells));
6284: if (cStart >= cEnd) goto end;
6285: PetscCall(DMHasBasisTransform(dm, &transform));
6286: PetscCall(DMGetBasisTransformDM_Internal(dm, &tdm));
6287: PetscCall(DMGetBasisTransformVec_Internal(dm, &tv));
6288: PetscCall(DMGetCellDS(dm, cells ? cells[cStart] : cStart, &prob, NULL));
6289: PetscCall(PetscDSGetNumFields(prob, &Nf));
6290: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
6291: PetscCall(PetscDSHasJacobian(prob, &hasJac));
6292: PetscCall(PetscDSHasJacobianPreconditioner(prob, &hasPrec));
6293: /* user passed in the same matrix, avoid double contributions and
6294: only assemble the Jacobian */
6295: if (hasJac && Jac == JacP) hasPrec = PETSC_FALSE;
6296: PetscCall(PetscDSHasDynamicJacobian(prob, &hasDyn));
6297: hasDyn = hasDyn && (X_tShift != 0.0) ? PETSC_TRUE : PETSC_FALSE;
6298: 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));
6299: if (dmAux) PetscCall(PetscMalloc1(numCells * totDimAux, &a));
6300: for (c = cStart; c < cEnd; ++c) {
6301: const PetscInt cell = cells ? cells[c] : c;
6302: const PetscInt cind = c - cStart;
6303: PetscScalar *x = NULL, *x_t = NULL;
6305: PetscCall(DMPlexVecGetClosure(dm, section, locX, cell, NULL, &x));
6306: for (PetscInt i = 0; i < totDim; ++i) u[cind * totDim + i] = x[i];
6307: PetscCall(DMPlexVecRestoreClosure(dm, section, locX, cell, NULL, &x));
6308: if (locX_t) {
6309: PetscCall(DMPlexVecGetClosure(dm, section, locX_t, cell, NULL, &x_t));
6310: for (PetscInt i = 0; i < totDim; ++i) u_t[cind * totDim + i] = x_t[i];
6311: PetscCall(DMPlexVecRestoreClosure(dm, section, locX_t, cell, NULL, &x_t));
6312: }
6313: if (dmAux) {
6314: PetscInt subcell;
6315: PetscCall(DMGetEnclosurePoint(dmAux, dm, encAux, cell, &subcell));
6316: PetscCall(DMPlexVecGetClosure(plex, sectionAux, A, subcell, NULL, &x));
6317: for (PetscInt i = 0; i < totDimAux; ++i) a[cind * totDimAux + i] = x[i];
6318: PetscCall(DMPlexVecRestoreClosure(plex, sectionAux, A, subcell, NULL, &x));
6319: }
6320: }
6321: if (hasJac) PetscCall(PetscArrayzero(elemMat, numCells * totDim * totDim));
6322: if (hasPrec) PetscCall(PetscArrayzero(elemMatP, numCells * totDim * totDim));
6323: if (hasDyn) PetscCall(PetscArrayzero(elemMatD, numCells * totDim * totDim));
6324: for (fieldI = 0; fieldI < Nf; ++fieldI) {
6325: PetscClassId id;
6326: PetscFE fe;
6327: PetscQuadrature qGeom = NULL;
6328: PetscInt Nb;
6329: /* Conforming batches */
6330: PetscInt numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
6331: /* Remainder */
6332: PetscInt Nr, offset, Nq;
6333: PetscInt maxDegree;
6334: PetscFEGeom *cgeomFEM, *chunkGeom = NULL, *remGeom = NULL;
6336: PetscCall(PetscDSGetDiscretization(prob, fieldI, (PetscObject *)&fe));
6337: PetscCall(PetscObjectGetClassId((PetscObject)fe, &id));
6338: if (id == PETSCFV_CLASSID) {
6339: hasFV = PETSC_TRUE;
6340: continue;
6341: }
6342: PetscCall(PetscFEGetDimension(fe, &Nb));
6343: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
6344: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
6345: if (maxDegree <= 1) PetscCall(DMFieldCreateDefaultQuadrature(coordField, cellIS, &qGeom));
6346: if (!qGeom) {
6347: PetscCall(PetscFEGetQuadrature(fe, &qGeom));
6348: PetscCall(PetscObjectReference((PetscObject)qGeom));
6349: }
6350: PetscCall(PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL));
6351: PetscCall(DMSNESGetFEGeom(coordField, cellIS, qGeom, PETSC_FEGEOM_BASIC, &cgeomFEM));
6352: blockSize = Nb;
6353: batchSize = numBlocks * blockSize;
6354: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
6355: numChunks = numCells / (numBatches * batchSize);
6356: Ne = numChunks * numBatches * batchSize;
6357: Nr = numCells % (numBatches * batchSize);
6358: offset = numCells - Nr;
6359: PetscCall(PetscFEGeomGetChunk(cgeomFEM, 0, offset, &chunkGeom));
6360: PetscCall(PetscFEGeomGetChunk(cgeomFEM, offset, numCells, &remGeom));
6361: for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
6362: key.field = fieldI * Nf + fieldJ;
6363: if (hasJac) {
6364: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN, key, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMat));
6365: 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]));
6366: }
6367: if (hasPrec) {
6368: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN_PRE, key, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMatP));
6369: 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]));
6370: }
6371: if (hasDyn) {
6372: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN_DYN, key, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMatD));
6373: 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]));
6374: }
6375: }
6376: PetscCall(PetscFEGeomRestoreChunk(cgeomFEM, offset, numCells, &remGeom));
6377: PetscCall(PetscFEGeomRestoreChunk(cgeomFEM, 0, offset, &chunkGeom));
6378: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, qGeom, PETSC_FALSE, &cgeomFEM));
6379: PetscCall(PetscQuadratureDestroy(&qGeom));
6380: }
6381: /* Add contribution from X_t */
6382: if (hasDyn) {
6383: for (c = 0; c < numCells * totDim * totDim; ++c) elemMat[c] += X_tShift * elemMatD[c];
6384: }
6385: if (hasFV) {
6386: PetscClassId id;
6387: PetscFV fv;
6388: PetscInt offsetI, NcI, NbI = 1, fc, f;
6390: for (fieldI = 0; fieldI < Nf; ++fieldI) {
6391: PetscCall(PetscDSGetDiscretization(prob, fieldI, (PetscObject *)&fv));
6392: PetscCall(PetscDSGetFieldOffset(prob, fieldI, &offsetI));
6393: PetscCall(PetscObjectGetClassId((PetscObject)fv, &id));
6394: if (id != PETSCFV_CLASSID) continue;
6395: /* Put in the weighted identity */
6396: PetscCall(PetscFVGetNumComponents(fv, &NcI));
6397: for (c = cStart; c < cEnd; ++c) {
6398: const PetscInt cind = c - cStart;
6399: const PetscInt eOffset = cind * totDim * totDim;
6400: PetscReal vol;
6402: PetscCall(DMPlexComputeCellGeometryFVM(dm, c, &vol, NULL, NULL));
6403: for (fc = 0; fc < NcI; ++fc) {
6404: for (f = 0; f < NbI; ++f) {
6405: const PetscInt i = offsetI + f * NcI + fc;
6406: if (hasPrec) {
6407: if (hasJac) elemMat[eOffset + i * totDim + i] = vol;
6408: elemMatP[eOffset + i * totDim + i] = vol;
6409: } else {
6410: elemMat[eOffset + i * totDim + i] = vol;
6411: }
6412: }
6413: }
6414: }
6415: }
6416: /* No allocated space for FV stuff, so ignore the zero entries */
6417: PetscCall(MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE));
6418: }
6419: /* Insert values into matrix */
6420: for (c = cStart; c < cEnd; ++c) {
6421: const PetscInt cell = cells ? cells[c] : c;
6422: const PetscInt cind = c - cStart;
6424: /* Transform to global basis before insertion in Jacobian */
6425: if (transform) PetscCall(DMPlexBasisTransformPointTensor_Internal(dm, tdm, tv, cell, PETSC_TRUE, totDim, &elemMat[cind * totDim * totDim]));
6426: if (hasPrec) {
6427: if (hasJac) {
6428: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, totDim, &elemMat[cind * totDim * totDim]));
6429: PetscCall(DMPlexMatSetClosure_Internal(dm, section, globalSection, mesh->useMatClPerm, Jac, cell, &elemMat[cind * totDim * totDim], ADD_VALUES));
6430: }
6431: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, totDim, &elemMatP[cind * totDim * totDim]));
6432: PetscCall(DMPlexMatSetClosure_Internal(dm, section, globalSection, mesh->useMatClPerm, JacP, cell, &elemMatP[cind * totDim * totDim], ADD_VALUES));
6433: } else {
6434: if (hasJac) {
6435: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, totDim, &elemMat[cind * totDim * totDim]));
6436: PetscCall(DMPlexMatSetClosure_Internal(dm, section, globalSection, mesh->useMatClPerm, JacP, cell, &elemMat[cind * totDim * totDim], ADD_VALUES));
6437: }
6438: }
6439: }
6440: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
6441: if (hasFV) PetscCall(MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_FALSE));
6442: PetscCall(PetscFree5(u, u_t, elemMat, elemMatP, elemMatD));
6443: if (dmAux) PetscCall(PetscFree(a));
6444: /* Compute boundary integrals */
6445: PetscCall(DMPlexComputeBdJacobian_Internal(dm, locX, locX_t, t, X_tShift, Jac, JacP, ctx));
6446: /* Assemble matrix */
6447: end:
6448: {
6449: if (dmAux) PetscCall(DMDestroy(&plex));
6450: if (hasJac && hasPrec) {
6451: PetscCall(MatAssemblyBegin(Jac, MAT_FINAL_ASSEMBLY));
6452: PetscCall(MatAssemblyEnd(Jac, MAT_FINAL_ASSEMBLY));
6453: }
6454: }
6455: PetscCall(MatAssemblyBegin(JacP, MAT_FINAL_ASSEMBLY));
6456: PetscCall(MatAssemblyEnd(JacP, MAT_FINAL_ASSEMBLY));
6457: PetscCall(PetscLogEventEnd(DMPLEX_JacobianFEM, dm, 0, 0, 0));
6458: PetscFunctionReturn(PETSC_SUCCESS);
6459: }
6461: /*@
6462: DMPlexComputeJacobianByKeyGeneral - Assemble the Jacobian and its preconditioning matrix over a cell range
6463: described by a `PetscFormKey` for a general (possibly non-square, non-nested) pair of row/column `DM`s.
6465: Collective
6467: Input Parameters:
6468: + dmr - the row `DMPLEX`
6469: . dmc - the column `DMPLEX`
6470: . key - the `PetscFormKey` selecting the label, value, part, and field for assembly
6471: . cellIS - the `IS` listing cells to process, or `NULL`
6472: . t - the current time
6473: . X_tShift - the time-derivative shift used to combine dynamic and static Jacobian contributions
6474: . locX - the local solution vector
6475: . locX_t - the local time-derivative vector, or `NULL`
6476: - ctx - the application context (unused; kept for API symmetry)
6478: Output Parameters:
6479: + Jac - the assembled Jacobian matrix
6480: - JacP - the assembled matrix from which the preconditioner is constructed
6482: Level: developer
6484: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `PetscFormKey`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeInterpolatorGeneral()`
6485: @*/
6486: 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)
6487: {
6488: DM_Plex *mesh = (DM_Plex *)dmr->data;
6489: const char *name = "Jacobian";
6490: DM dmAux = NULL, plex, tdm;
6491: PetscInt printFEM = mesh->printFEM;
6492: PetscBool clPerm = mesh->useMatClPerm;
6493: DMEnclosureType encAux;
6494: Vec A, tv;
6495: DMField coordField;
6496: PetscDS rds, cds, dsAux = NULL;
6497: PetscSection rsection, rglobalSection, csection, cglobalSection, sectionAux;
6498: PetscScalar *elemMat, *elemMatP, *elemMatD, *u, *u_t, *a = NULL;
6499: const PetscInt *cells;
6500: PetscInt Nf, cNf;
6501: PetscInt totDim, ctotDim, totDimAux = 0, cStart, cEnd, numCells;
6502: PetscBool hasJac = PETSC_FALSE, hasPrec = PETSC_FALSE, hasDyn, hasFV = PETSC_FALSE, transform;
6503: MPI_Comm comm;
6505: PetscFunctionBegin;
6506: PetscCall(PetscObjectGetComm((PetscObject)dmr, &comm));
6507: PetscCall(PetscLogEventBegin(DMPLEX_JacobianFEM, dmr, 0, 0, 0));
6508: PetscCall(DMGetLocalSection(dmr, &rsection));
6509: PetscCall(DMGetGlobalSection(dmr, &rglobalSection));
6510: PetscCall(DMGetLocalSection(dmc, &csection));
6511: PetscCall(DMGetGlobalSection(dmc, &cglobalSection));
6512: PetscCall(DMGetAuxiliaryVec(dmr, key.label, key.value, key.part, &A));
6513: if (A) {
6514: PetscCall(VecGetDM(A, &dmAux));
6515: PetscCall(DMGetEnclosureRelation(dmAux, dmr, &encAux));
6516: PetscCall(DMConvert(dmAux, DMPLEX, &plex));
6517: PetscCall(DMGetLocalSection(plex, §ionAux));
6518: PetscCall(DMGetDS(dmAux, &dsAux));
6519: PetscCall(PetscDSGetTotalDimension(dsAux, &totDimAux));
6520: }
6521: PetscCall(DMGetCoordinateField(dmr, &coordField));
6522: if (!cellIS) goto end;
6523: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
6524: PetscCall(ISGetLocalSize(cellIS, &numCells));
6525: if (cStart >= cEnd) goto end;
6526: PetscCall(DMHasBasisTransform(dmr, &transform));
6527: PetscCall(DMGetBasisTransformDM_Internal(dmr, &tdm));
6528: PetscCall(DMGetBasisTransformVec_Internal(dmr, &tv));
6529: PetscCall(DMGetCellDS(dmr, cells ? cells[cStart] : cStart, &rds, NULL));
6530: PetscCall(DMGetCellDS(dmc, cells ? cells[cStart] : cStart, &cds, NULL));
6531: PetscCall(PetscDSGetNumFields(rds, &Nf));
6532: PetscCall(PetscDSGetNumFields(cds, &cNf));
6533: PetscCheck(Nf == cNf, comm, PETSC_ERR_ARG_WRONG, "Number of row fields %" PetscInt_FMT " != %" PetscInt_FMT " number of columns field", Nf, cNf);
6534: PetscCall(PetscDSGetTotalDimension(rds, &totDim));
6535: PetscCall(PetscDSGetTotalDimension(cds, &ctotDim));
6536: PetscCall(PetscDSHasJacobian(rds, &hasJac));
6537: PetscCall(PetscDSHasJacobianPreconditioner(rds, &hasPrec));
6538: /* user passed in the same matrix, avoid double contributions and
6539: only assemble the Jacobian */
6540: if (hasJac && Jac == JacP) hasPrec = PETSC_FALSE;
6541: PetscCall(PetscDSHasDynamicJacobian(rds, &hasDyn));
6542: hasDyn = hasDyn && (X_tShift != 0.0) ? PETSC_TRUE : PETSC_FALSE;
6543: 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));
6544: if (dmAux) PetscCall(PetscMalloc1(numCells * totDimAux, &a));
6545: for (PetscInt c = cStart; c < cEnd; ++c) {
6546: const PetscInt cell = cells ? cells[c] : c;
6547: const PetscInt cind = c - cStart;
6548: PetscScalar *x = NULL, *x_t = NULL;
6550: PetscCall(DMPlexVecGetClosure(dmr, rsection, locX, cell, NULL, &x));
6551: for (PetscInt i = 0; i < totDim; ++i) u[cind * totDim + i] = x[i];
6552: PetscCall(DMPlexVecRestoreClosure(dmr, rsection, locX, cell, NULL, &x));
6553: if (locX_t) {
6554: PetscCall(DMPlexVecGetClosure(dmr, rsection, locX_t, cell, NULL, &x_t));
6555: for (PetscInt i = 0; i < totDim; ++i) u_t[cind * totDim + i] = x_t[i];
6556: PetscCall(DMPlexVecRestoreClosure(dmr, rsection, locX_t, cell, NULL, &x_t));
6557: }
6558: if (dmAux) {
6559: PetscInt subcell;
6560: PetscCall(DMGetEnclosurePoint(dmAux, dmr, encAux, cell, &subcell));
6561: PetscCall(DMPlexVecGetClosure(plex, sectionAux, A, subcell, NULL, &x));
6562: for (PetscInt i = 0; i < totDimAux; ++i) a[cind * totDimAux + i] = x[i];
6563: PetscCall(DMPlexVecRestoreClosure(plex, sectionAux, A, subcell, NULL, &x));
6564: }
6565: }
6566: if (hasJac) PetscCall(PetscArrayzero(elemMat, numCells * totDim * ctotDim));
6567: if (hasPrec) PetscCall(PetscArrayzero(elemMatP, numCells * totDim * ctotDim));
6568: if (hasDyn) PetscCall(PetscArrayzero(elemMatD, numCells * totDim * ctotDim));
6569: for (PetscInt fieldI = 0; fieldI < Nf; ++fieldI) {
6570: PetscClassId id;
6571: PetscFE fe;
6572: PetscQuadrature qGeom = NULL;
6573: PetscInt Nb;
6574: /* Conforming batches */
6575: PetscInt numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
6576: /* Remainder */
6577: PetscInt Nr, offset, Nq;
6578: PetscInt maxDegree;
6579: PetscFEGeom *cgeomFEM, *chunkGeom = NULL, *remGeom = NULL;
6581: PetscCall(PetscDSGetDiscretization(rds, fieldI, (PetscObject *)&fe));
6582: PetscCall(PetscObjectGetClassId((PetscObject)fe, &id));
6583: if (id == PETSCFV_CLASSID) {
6584: hasFV = PETSC_TRUE;
6585: continue;
6586: }
6587: PetscCall(PetscFEGetDimension(fe, &Nb));
6588: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
6589: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
6590: if (maxDegree <= 1) PetscCall(DMFieldCreateDefaultQuadrature(coordField, cellIS, &qGeom));
6591: if (!qGeom) {
6592: PetscCall(PetscFEGetQuadrature(fe, &qGeom));
6593: PetscCall(PetscObjectReference((PetscObject)qGeom));
6594: }
6595: PetscCall(PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL));
6596: PetscCall(DMSNESGetFEGeom(coordField, cellIS, qGeom, PETSC_FEGEOM_BASIC, &cgeomFEM));
6597: blockSize = Nb;
6598: batchSize = numBlocks * blockSize;
6599: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
6600: numChunks = numCells / (numBatches * batchSize);
6601: Ne = numChunks * numBatches * batchSize;
6602: Nr = numCells % (numBatches * batchSize);
6603: offset = numCells - Nr;
6604: PetscCall(PetscFEGeomGetChunk(cgeomFEM, 0, offset, &chunkGeom));
6605: PetscCall(PetscFEGeomGetChunk(cgeomFEM, offset, numCells, &remGeom));
6606: for (PetscInt fieldJ = 0; fieldJ < Nf; ++fieldJ) {
6607: key.field = fieldI * Nf + fieldJ;
6608: if (hasJac) {
6609: PetscCall(PetscFEIntegrateJacobian(rds, cds, PETSCFE_JACOBIAN, key, Ne, chunkGeom, u, u_t, dsAux, a, t, X_tShift, elemMat));
6610: 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]));
6611: }
6612: if (hasPrec) {
6613: PetscCall(PetscFEIntegrateJacobian(rds, cds, PETSCFE_JACOBIAN_PRE, key, Ne, chunkGeom, u, u_t, dsAux, a, t, X_tShift, elemMatP));
6614: 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]));
6615: }
6616: if (hasDyn) {
6617: PetscCall(PetscFEIntegrateJacobian(rds, cds, PETSCFE_JACOBIAN_DYN, key, Ne, chunkGeom, u, u_t, dsAux, a, t, X_tShift, elemMatD));
6618: 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]));
6619: }
6620: }
6621: PetscCall(PetscFEGeomRestoreChunk(cgeomFEM, offset, numCells, &remGeom));
6622: PetscCall(PetscFEGeomRestoreChunk(cgeomFEM, 0, offset, &chunkGeom));
6623: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, qGeom, PETSC_FALSE, &cgeomFEM));
6624: PetscCall(PetscQuadratureDestroy(&qGeom));
6625: }
6626: /* Add contribution from X_t */
6627: if (hasDyn) {
6628: for (PetscInt c = 0; c < numCells * totDim * ctotDim; ++c) elemMat[c] += X_tShift * elemMatD[c];
6629: }
6630: if (hasFV) {
6631: PetscClassId id;
6632: PetscFV fv;
6633: PetscInt offsetI, NcI, NbI = 1;
6635: for (PetscInt fieldI = 0; fieldI < Nf; ++fieldI) {
6636: PetscCall(PetscDSGetDiscretization(rds, fieldI, (PetscObject *)&fv));
6637: PetscCall(PetscDSGetFieldOffset(rds, fieldI, &offsetI));
6638: PetscCall(PetscObjectGetClassId((PetscObject)fv, &id));
6639: if (id != PETSCFV_CLASSID) continue;
6640: /* Put in the weighted identity */
6641: PetscCall(PetscFVGetNumComponents(fv, &NcI));
6642: for (PetscInt c = cStart; c < cEnd; ++c) {
6643: const PetscInt cind = c - cStart;
6644: const PetscInt eOffset = cind * totDim * ctotDim;
6645: PetscReal vol;
6647: PetscCall(DMPlexComputeCellGeometryFVM(dmr, c, &vol, NULL, NULL));
6648: for (PetscInt fc = 0; fc < NcI; ++fc) {
6649: for (PetscInt f = 0; f < NbI; ++f) {
6650: const PetscInt i = offsetI + f * NcI + fc;
6651: if (hasPrec) {
6652: if (hasJac) elemMat[eOffset + i * ctotDim + i] = vol;
6653: elemMatP[eOffset + i * ctotDim + i] = vol;
6654: } else {
6655: elemMat[eOffset + i * ctotDim + i] = vol;
6656: }
6657: }
6658: }
6659: }
6660: }
6661: /* No allocated space for FV stuff, so ignore the zero entries */
6662: PetscCall(MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE));
6663: }
6664: /* Insert values into matrix */
6665: for (PetscInt c = cStart; c < cEnd; ++c) {
6666: const PetscInt cell = cells ? cells[c] : c;
6667: const PetscInt cind = c - cStart;
6669: /* Transform to global basis before insertion in Jacobian */
6670: if (transform) PetscCall(DMPlexBasisTransformPointTensor_Internal(dmr, tdm, tv, cell, PETSC_TRUE, totDim, &elemMat[cind * totDim * ctotDim]));
6671: if (hasPrec) {
6672: if (hasJac) {
6673: if (printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, ctotDim, &elemMat[cind * totDim * ctotDim]));
6674: PetscCall(DMPlexMatSetClosureGeneral(dmr, rsection, rglobalSection, clPerm, dmc, csection, cglobalSection, clPerm, Jac, cell, &elemMat[cind * totDim * ctotDim], ADD_VALUES));
6675: }
6676: if (printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, ctotDim, &elemMatP[cind * totDim * ctotDim]));
6677: PetscCall(DMPlexMatSetClosureGeneral(dmr, rsection, rglobalSection, clPerm, dmc, csection, cglobalSection, clPerm, JacP, cell, &elemMatP[cind * totDim * ctotDim], ADD_VALUES));
6678: } else {
6679: if (hasJac) {
6680: if (printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, ctotDim, &elemMat[cind * totDim * ctotDim]));
6681: PetscCall(DMPlexMatSetClosureGeneral(dmr, rsection, rglobalSection, clPerm, dmc, csection, cglobalSection, clPerm, JacP, cell, &elemMat[cind * totDim * ctotDim], ADD_VALUES));
6682: }
6683: }
6684: }
6685: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
6686: if (hasFV) PetscCall(MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_FALSE));
6687: PetscCall(PetscFree5(u, u_t, elemMat, elemMatP, elemMatD));
6688: if (dmAux) PetscCall(PetscFree(a));
6689: /* Compute boundary integrals */
6690: PetscCall(DMPlexComputeBdJacobian_Internal(dmr, locX, locX_t, t, X_tShift, Jac, JacP, ctx));
6691: /* Assemble matrix */
6692: end:
6693: {
6694: if (dmAux) PetscCall(DMDestroy(&plex));
6695: if (hasJac && hasPrec) {
6696: PetscCall(MatAssemblyBegin(Jac, MAT_FINAL_ASSEMBLY));
6697: PetscCall(MatAssemblyEnd(Jac, MAT_FINAL_ASSEMBLY));
6698: }
6699: }
6700: PetscCall(MatAssemblyBegin(JacP, MAT_FINAL_ASSEMBLY));
6701: PetscCall(MatAssemblyEnd(JacP, MAT_FINAL_ASSEMBLY));
6702: PetscCall(PetscLogEventEnd(DMPLEX_JacobianFEM, dmr, 0, 0, 0));
6703: PetscFunctionReturn(PETSC_SUCCESS);
6704: }
6706: /*@
6707: DMPlexComputeJacobianHybridByKey - Compute the local Jacobian over hybrid cells for terms matching the input key
6709: Collective
6711: Input Parameters:
6712: + dm - The output `DM`
6713: . key - The `PetscFormKey` array (left cell, right cell, cohesive cell) indicating what should be integrated
6714: . cellIS - The `IS` give a set of cells to integrate over
6715: . t - The time
6716: . X_tShift - The multiplier for the Jacobian with respect to $X_t$
6717: . locX - The local solution
6718: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
6719: - ctx - An optional application context, passed to the pointwise functions
6721: Output Parameters:
6722: + Jac - The local Jacobian
6723: - JacP - The local Jacobian preconditioner
6725: Level: developer
6727: .seealso: `DMPlexComputeResidualByKey()`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeResidualHybridByKey()`, `PetscFormKey`
6728: @*/
6729: PetscErrorCode DMPlexComputeJacobianHybridByKey(DM dm, PetscFormKey key[], IS cellIS, PetscReal t, PetscReal X_tShift, Vec locX, Vec locX_t, Mat Jac, Mat JacP, PetscCtx ctx)
6730: {
6731: DM_Plex *mesh = (DM_Plex *)dm->data;
6732: const char *name = "Hybrid Jacobian";
6733: DM dmAux[3] = {NULL, NULL, NULL};
6734: DMLabel ghostLabel = NULL;
6735: DM plex = NULL;
6736: DM plexA = NULL;
6737: PetscDS ds = NULL;
6738: PetscDS dsIn = NULL;
6739: PetscDS dsAux[3] = {NULL, NULL, NULL};
6740: Vec locA[3] = {NULL, NULL, NULL};
6741: DM dmScale[3] = {NULL, NULL, NULL};
6742: PetscDS dsScale[3] = {NULL, NULL, NULL};
6743: Vec locS[3] = {NULL, NULL, NULL};
6744: PetscSection section = NULL;
6745: PetscSection sectionAux[3] = {NULL, NULL, NULL};
6746: DMField coordField = NULL;
6747: PetscScalar *a[3] = {NULL, NULL, NULL};
6748: PetscScalar *s[3] = {NULL, NULL, NULL};
6749: PetscScalar *u = NULL, *u_t;
6750: PetscScalar *elemMatNeg, *elemMatPos, *elemMatCoh;
6751: PetscScalar *elemMatNegP, *elemMatPosP, *elemMatCohP;
6752: PetscSection globalSection;
6753: IS chunkISF, chunkISN;
6754: const PetscInt *cells;
6755: PetscInt *faces, *neighbors;
6756: PetscInt cStart, cEnd, numCells;
6757: PetscInt Nf, fieldI, fieldJ, totDim, totDimIn, totDimAux[3], totDimScale[3], numChunks, cellChunkSize, chunk;
6758: PetscInt maxDegree = PETSC_INT_MAX;
6759: PetscQuadrature affineQuadF = NULL, *quadsF = NULL;
6760: PetscFEGeom *affineGeomF = NULL, **geomsF = NULL;
6761: PetscQuadrature affineQuadN = NULL;
6762: PetscFEGeom *affineGeomN = NULL;
6763: PetscBool hasBdJac, hasBdPrec;
6765: PetscFunctionBegin;
6766: PetscCall(PetscLogEventBegin(DMPLEX_JacobianFEM, dm, 0, 0, 0));
6767: if (!cellIS) goto end;
6768: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
6769: PetscCall(ISGetLocalSize(cellIS, &numCells));
6770: if (cStart >= cEnd) goto end;
6771: if ((key[0].label == key[1].label) && (key[0].value == key[1].value) && (key[0].part == key[1].part)) {
6772: const char *name;
6773: PetscCall(PetscObjectGetName((PetscObject)key[0].label, &name));
6774: 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);
6775: }
6776: PetscCall(DMConvert(dm, DMPLEX, &plex));
6777: PetscCall(DMGetLocalSection(dm, §ion));
6778: PetscCall(DMGetGlobalSection(dm, &globalSection));
6779: PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
6780: PetscCall(DMGetCellDS(dm, cells ? cells[cStart] : cStart, &ds, &dsIn));
6781: PetscCall(PetscDSGetNumFields(ds, &Nf));
6782: PetscCall(PetscDSGetTotalDimension(ds, &totDim));
6783: PetscCall(PetscDSGetTotalDimension(dsIn, &totDimIn));
6784: PetscCall(PetscDSHasBdJacobian(ds, &hasBdJac));
6785: PetscCall(PetscDSHasBdJacobianPreconditioner(ds, &hasBdPrec));
6786: PetscCall(DMGetAuxiliaryVec(dm, key[2].label, key[2].value, key[2].part, &locA[2]));
6787: if (locA[2]) {
6788: const PetscInt cellStart = cells ? cells[cStart] : cStart;
6790: PetscCall(VecGetDM(locA[2], &dmAux[2]));
6791: PetscCall(DMConvert(dmAux[2], DMPLEX, &plexA));
6792: PetscCall(DMGetLocalSection(dmAux[2], §ionAux[2]));
6793: PetscCall(DMGetCellDS(dmAux[2], cellStart, &dsAux[2], NULL));
6794: PetscCall(PetscDSGetTotalDimension(dsAux[2], &totDimAux[2]));
6795: {
6796: const PetscInt *cone;
6797: PetscInt c;
6799: PetscCall(DMPlexGetCone(dm, cellStart, &cone));
6800: for (c = 0; c < 2; ++c) {
6801: const PetscInt *support;
6802: PetscInt ssize, s;
6804: PetscCall(DMPlexGetSupport(dm, cone[c], &support));
6805: PetscCall(DMPlexGetSupportSize(dm, cone[c], &ssize));
6806: 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);
6807: if (support[0] == cellStart) s = 1;
6808: else if (support[1] == cellStart) s = 0;
6809: else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " does not have cell %" PetscInt_FMT " in its support", cone[c], cellStart);
6810: PetscCall(DMGetAuxiliaryVec(dm, key[c].label, key[c].value, key[c].part, &locA[c]));
6811: if (locA[c]) PetscCall(VecGetDM(locA[c], &dmAux[c]));
6812: else dmAux[c] = dmAux[2];
6813: PetscCall(DMGetCellDS(dmAux[c], support[s], &dsAux[c], NULL));
6814: PetscCall(PetscDSGetTotalDimension(dsAux[c], &totDimAux[c]));
6815: }
6816: }
6817: }
6818: /* Handle mass matrix scaling
6819: The field in key[2] is the field to be scaled, and the scaling field is the first in the dsScale */
6820: PetscCall(DMGetAuxiliaryVec(dm, key[2].label, -key[2].value, key[2].part, &locS[2]));
6821: if (locS[2]) {
6822: const PetscInt cellStart = cells ? cells[cStart] : cStart;
6823: PetscInt Nb, Nbs;
6825: PetscCall(VecGetDM(locS[2], &dmScale[2]));
6826: PetscCall(DMGetCellDS(dmScale[2], cells ? cells[cStart] : cStart, &dsScale[2], NULL));
6827: PetscCall(PetscDSGetTotalDimension(dsScale[2], &totDimScale[2]));
6828: // BRAD: This is not set correctly
6829: key[2].field = 2;
6830: PetscCall(PetscDSGetFieldSize(ds, key[2].field, &Nb));
6831: PetscCall(PetscDSGetFieldSize(dsScale[2], 0, &Nbs));
6832: 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);
6833: {
6834: const PetscInt *cone;
6836: locS[1] = locS[0] = locS[2];
6837: dmScale[1] = dmScale[0] = dmScale[2];
6838: PetscCall(DMPlexGetCone(dm, cellStart, &cone));
6839: for (PetscInt c = 0; c < 2; ++c) {
6840: const PetscInt *support;
6841: PetscInt ssize, s;
6843: PetscCall(DMPlexGetSupport(dm, cone[c], &support));
6844: PetscCall(DMPlexGetSupportSize(dm, cone[c], &ssize));
6845: 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);
6846: if (support[0] == cellStart) s = 1;
6847: else if (support[1] == cellStart) s = 0;
6848: else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " does not have cell %" PetscInt_FMT " in its support", cone[c], cellStart);
6849: PetscCall(DMGetCellDS(dmScale[c], support[s], &dsScale[c], NULL));
6850: PetscCall(PetscDSGetTotalDimension(dsScale[c], &totDimScale[c]));
6851: }
6852: }
6853: }
6854: /* 2: Setup geometric data */
6855: PetscCall(DMGetCoordinateField(dm, &coordField));
6856: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
6857: if (maxDegree > 1) {
6858: PetscCall(PetscCalloc2(Nf, &quadsF, Nf, &geomsF));
6859: for (PetscInt f = 0; f < Nf; ++f) {
6860: PetscFE fe;
6862: PetscCall(PetscDSGetDiscretization(ds, f, (PetscObject *)&fe));
6863: if (fe) {
6864: PetscCall(PetscFEGetQuadrature(fe, &quadsF[f]));
6865: PetscCall(PetscObjectReference((PetscObject)quadsF[f]));
6866: }
6867: }
6868: }
6869: /* Loop over chunks */
6870: cellChunkSize = numCells;
6871: numChunks = !numCells ? 0 : PetscCeilReal(((PetscReal)numCells) / cellChunkSize);
6872: PetscCall(PetscCalloc2(2 * cellChunkSize, &faces, 2 * cellChunkSize, &neighbors));
6873: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 2 * cellChunkSize, faces, PETSC_USE_POINTER, &chunkISF));
6874: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, 2 * cellChunkSize, neighbors, PETSC_USE_POINTER, &chunkISN));
6875: /* Extract field coefficients */
6876: /* NOTE This needs the end cap faces to have identical orientations */
6877: PetscCall(DMPlexGetHybridCellFields(dm, cellIS, locX, locX_t, locA[2], &u, &u_t, &a[2]));
6878: PetscCall(DMPlexGetHybridFields(dm, dmAux, dsAux, cellIS, locA, PETSC_TRUE, a));
6879: PetscCall(DMPlexGetHybridFields(dm, dmScale, dsScale, cellIS, locS, PETSC_TRUE, s));
6880: PetscCall(DMGetWorkArray(dm, hasBdJac ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatNeg));
6881: PetscCall(DMGetWorkArray(dm, hasBdJac ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatPos));
6882: PetscCall(DMGetWorkArray(dm, hasBdJac ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatCoh));
6883: PetscCall(DMGetWorkArray(dm, hasBdPrec ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatNegP));
6884: PetscCall(DMGetWorkArray(dm, hasBdPrec ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatPosP));
6885: PetscCall(DMGetWorkArray(dm, hasBdPrec ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatCohP));
6886: for (chunk = 0; chunk < numChunks; ++chunk) {
6887: PetscInt cS = cStart + chunk * cellChunkSize, cE = PetscMin(cS + cellChunkSize, cEnd), numCells = cE - cS, c;
6889: if (hasBdJac) {
6890: PetscCall(PetscArrayzero(elemMatNeg, cellChunkSize * totDim * totDim));
6891: PetscCall(PetscArrayzero(elemMatPos, cellChunkSize * totDim * totDim));
6892: PetscCall(PetscArrayzero(elemMatCoh, cellChunkSize * totDim * totDim));
6893: }
6894: if (hasBdPrec) {
6895: PetscCall(PetscArrayzero(elemMatNegP, cellChunkSize * totDim * totDim));
6896: PetscCall(PetscArrayzero(elemMatPosP, cellChunkSize * totDim * totDim));
6897: PetscCall(PetscArrayzero(elemMatCohP, cellChunkSize * totDim * totDim));
6898: }
6899: /* Get faces */
6900: for (c = cS; c < cE; ++c) {
6901: const PetscInt cell = cells ? cells[c] : c;
6902: const PetscInt *cone, *support;
6903: PetscCall(DMPlexGetCone(plex, cell, &cone));
6904: faces[(c - cS) * 2 + 0] = cone[0];
6905: faces[(c - cS) * 2 + 1] = cone[1];
6906: PetscCall(DMPlexGetSupport(dm, cone[0], &support));
6907: neighbors[(c - cS) * 2 + 0] = support[0] == cell ? support[1] : support[0];
6908: PetscCall(DMPlexGetSupport(dm, cone[1], &support));
6909: neighbors[(c - cS) * 2 + 1] = support[0] == cell ? support[1] : support[0];
6910: }
6911: PetscCall(ISGeneralSetIndices(chunkISF, 2 * cellChunkSize, faces, PETSC_USE_POINTER));
6912: PetscCall(ISGeneralSetIndices(chunkISN, 2 * cellChunkSize, neighbors, PETSC_USE_POINTER));
6913: if (maxDegree <= 1) {
6914: if (!affineQuadF) PetscCall(DMFieldCreateDefaultQuadrature(coordField, chunkISF, &affineQuadF));
6915: if (affineQuadF) PetscCall(DMSNESGetFEGeom(coordField, chunkISF, affineQuadF, PETSC_FEGEOM_COHESIVE, &affineGeomF));
6916: if (!affineQuadN) {
6917: PetscInt dim;
6918: PetscCall(PetscQuadratureGetData(affineQuadF, &dim, NULL, NULL, NULL, NULL));
6919: PetscCall(DMFieldCreateDefaultFaceQuadrature(coordField, chunkISN, &affineQuadN));
6920: PetscCall(PetscQuadratureSetData(affineQuadN, dim + 1, PETSC_DECIDE, PETSC_DECIDE, NULL, NULL));
6921: }
6922: if (affineQuadN) PetscCall(DMSNESGetFEGeom(coordField, chunkISN, affineQuadN, PETSC_FEGEOM_BASIC, &affineGeomN));
6923: } else {
6924: for (PetscInt f = 0; f < Nf; ++f) {
6925: if (quadsF[f]) PetscCall(DMSNESGetFEGeom(coordField, chunkISF, quadsF[f], PETSC_FEGEOM_COHESIVE, &geomsF[f]));
6926: }
6927: }
6929: for (fieldI = 0; fieldI < Nf; ++fieldI) {
6930: PetscFE feI;
6931: PetscFEGeom *geomF = affineGeomF ? affineGeomF : geomsF[fieldI];
6932: PetscFEGeom *chunkGeomF = NULL, *remGeomF = NULL;
6933: PetscFEGeom *geomN = affineGeomN ? affineGeomN : geomsF[fieldI];
6934: PetscFEGeom *chunkGeomN = NULL, *remGeomN = NULL;
6935: PetscQuadrature quadF = affineQuadF ? affineQuadF : quadsF[fieldI];
6936: PetscInt numChunks, numBatches, batchSize, numBlocks, blockSize, Ne, Nr, offset, Nq, Nb;
6937: PetscBool isCohesiveField;
6939: PetscCall(PetscDSGetDiscretization(ds, fieldI, (PetscObject *)&feI));
6940: if (!feI) continue;
6941: PetscCall(PetscFEGetTileSizes(feI, NULL, &numBlocks, NULL, &numBatches));
6942: PetscCall(PetscQuadratureGetData(quadF, NULL, NULL, &Nq, NULL, NULL));
6943: PetscCall(PetscFEGetDimension(feI, &Nb));
6944: blockSize = Nb;
6945: batchSize = numBlocks * blockSize;
6946: PetscCall(PetscFESetTileSizes(feI, blockSize, numBlocks, batchSize, numBatches));
6947: numChunks = numCells / (numBatches * batchSize);
6948: Ne = numChunks * numBatches * batchSize;
6949: Nr = numCells % (numBatches * batchSize);
6950: offset = numCells - Nr;
6951: PetscCall(PetscFEGeomGetChunk(geomF, 0, offset * 2, &chunkGeomF));
6952: PetscCall(PetscFEGeomGetChunk(geomF, offset * 2, numCells * 2, &remGeomF));
6953: PetscCall(PetscFEGeomGetChunk(geomN, 0, offset * 2, &chunkGeomN));
6954: PetscCall(PetscFEGeomGetChunk(geomN, offset * 2, numCells * 2, &remGeomN));
6955: PetscCall(PetscDSGetCohesive(ds, fieldI, &isCohesiveField));
6956: for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
6957: PetscFE feJ;
6959: PetscCall(PetscDSGetDiscretization(ds, fieldJ, (PetscObject *)&feJ));
6960: if (!feJ) continue;
6961: key[0].field = fieldI * Nf + fieldJ;
6962: key[1].field = fieldI * Nf + fieldJ;
6963: key[2].field = fieldI * Nf + fieldJ;
6964: if (hasBdJac) {
6965: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN, key[0], 0, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[0], a[0], t, X_tShift, elemMatNeg));
6966: 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]));
6967: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN, key[1], 1, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[1], a[1], t, X_tShift, elemMatPos));
6968: 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]));
6969: }
6970: if (hasBdPrec) {
6971: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN_PRE, key[0], 0, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[0], a[0], t, X_tShift, elemMatNegP));
6972: 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]));
6973: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN_PRE, key[1], 1, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[1], a[1], t, X_tShift, elemMatPosP));
6974: 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]));
6975: }
6976: if (hasBdJac) {
6977: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN, key[2], 2, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[2], a[2], t, X_tShift, elemMatCoh));
6978: 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]));
6979: }
6980: if (hasBdPrec) {
6981: PetscCall(PetscFEIntegrateHybridJacobian(ds, dsIn, PETSCFE_JACOBIAN_PRE, key[2], 2, Ne, chunkGeomF, chunkGeomN, u, u_t, dsAux[2], a[2], t, X_tShift, elemMatCohP));
6982: 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]));
6983: }
6984: }
6985: PetscCall(PetscFEGeomRestoreChunk(geomF, offset, numCells, &remGeomF));
6986: PetscCall(PetscFEGeomRestoreChunk(geomF, 0, offset, &chunkGeomF));
6987: PetscCall(PetscFEGeomRestoreChunk(geomN, offset, numCells, &remGeomN));
6988: PetscCall(PetscFEGeomRestoreChunk(geomN, 0, offset, &chunkGeomN));
6989: }
6990: /* Insert values into matrix */
6991: for (c = cS; c < cE; ++c) {
6992: const PetscInt cell = cells ? cells[c] : c;
6993: const PetscInt cind = c - cS, coff = cind * totDim * totDim;
6995: /* Scale element values */
6996: if (locS[0]) {
6997: PetscInt Nb, soff = cind * totDimScale[0], off = 0;
6998: PetscBool cohesive;
7000: for (fieldI = 0; fieldI < Nf; ++fieldI) {
7001: PetscCall(PetscDSGetFieldSize(ds, fieldI, &Nb));
7002: PetscCall(PetscDSGetCohesive(ds, fieldI, &cohesive));
7004: if (fieldI == key[2].field) {
7005: PetscCheck(cohesive, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Scaling should not happen for face fields");
7006: for (PetscInt i = 0; i < Nb; ++i) {
7007: for (PetscInt 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];
7008: if (hasBdPrec)
7009: for (PetscInt 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];
7010: }
7011: off += Nb;
7012: } else {
7013: const PetscInt N = cohesive ? Nb : Nb * 2;
7015: for (PetscInt i = 0; i < N; ++i) {
7016: for (PetscInt j = 0; j < totDim; ++j) elemMatCoh[coff + (off + i) * totDim + j] += elemMatNeg[coff + (off + i) * totDim + j] + elemMatPos[coff + (off + i) * totDim + j];
7017: if (hasBdPrec)
7018: for (PetscInt j = 0; j < totDim; ++j) elemMatCohP[coff + (off + i) * totDim + j] += elemMatNegP[coff + (off + i) * totDim + j] + elemMatPosP[coff + (off + i) * totDim + j];
7019: }
7020: off += N;
7021: }
7022: }
7023: } else {
7024: for (PetscInt i = 0; i < totDim * totDim; ++i) elemMatCoh[coff + i] += elemMatNeg[coff + i] + elemMatPos[coff + i];
7025: if (hasBdPrec)
7026: for (PetscInt i = 0; i < totDim * totDim; ++i) elemMatCohP[coff + i] += elemMatNegP[coff + i] + elemMatPosP[coff + i];
7027: }
7028: if (hasBdPrec) {
7029: if (hasBdJac) {
7030: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, totDim, &elemMatCoh[cind * totDim * totDim]));
7031: PetscCall(DMPlexMatSetClosure_Internal(plex, section, globalSection, mesh->useMatClPerm, Jac, cell, &elemMatCoh[cind * totDim * totDim], ADD_VALUES));
7032: }
7033: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, totDim, &elemMatCohP[cind * totDim * totDim]));
7034: PetscCall(DMPlexMatSetClosure(plex, section, globalSection, JacP, cell, &elemMatCohP[cind * totDim * totDim], ADD_VALUES));
7035: } else if (hasBdJac) {
7036: if (mesh->printFEM > 1) PetscCall(DMPrintCellMatrix(cell, name, totDim, totDim, &elemMatCoh[cind * totDim * totDim]));
7037: PetscCall(DMPlexMatSetClosure_Internal(plex, section, globalSection, mesh->useMatClPerm, JacP, cell, &elemMatCoh[cind * totDim * totDim], ADD_VALUES));
7038: }
7039: }
7040: }
7041: PetscCall(DMPlexRestoreCellFields(dm, cellIS, locX, locX_t, locA[2], &u, &u_t, &a[2]));
7042: PetscCall(DMPlexRestoreHybridFields(dm, dmAux, dsAux, cellIS, locA, PETSC_TRUE, a));
7043: PetscCall(DMRestoreWorkArray(dm, hasBdJac ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatNeg));
7044: PetscCall(DMRestoreWorkArray(dm, hasBdJac ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatPos));
7045: PetscCall(DMRestoreWorkArray(dm, hasBdJac ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatCoh));
7046: PetscCall(DMRestoreWorkArray(dm, hasBdPrec ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatNegP));
7047: PetscCall(DMRestoreWorkArray(dm, hasBdPrec ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatPosP));
7048: PetscCall(DMRestoreWorkArray(dm, hasBdPrec ? cellChunkSize * totDim * totDim : 0, MPIU_SCALAR, &elemMatCohP));
7049: PetscCall(PetscFree2(faces, neighbors));
7050: PetscCall(ISDestroy(&chunkISF));
7051: PetscCall(ISDestroy(&chunkISN));
7052: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
7053: if (maxDegree <= 1) {
7054: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, affineQuadF, PETSC_FALSE, &affineGeomF));
7055: PetscCall(PetscQuadratureDestroy(&affineQuadF));
7056: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, affineQuadN, PETSC_FALSE, &affineGeomN));
7057: PetscCall(PetscQuadratureDestroy(&affineQuadN));
7058: } else {
7059: for (PetscInt f = 0; f < Nf; ++f) {
7060: if (geomsF) PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, quadsF[f], PETSC_FALSE, &geomsF[f]));
7061: if (quadsF) PetscCall(PetscQuadratureDestroy(&quadsF[f]));
7062: }
7063: PetscCall(PetscFree2(quadsF, geomsF));
7064: }
7065: if (dmAux[2]) PetscCall(DMDestroy(&plexA));
7066: PetscCall(DMDestroy(&plex));
7067: end:
7068: PetscCall(PetscLogEventEnd(DMPLEX_JacobianFEM, dm, 0, 0, 0));
7069: PetscFunctionReturn(PETSC_SUCCESS);
7070: }
7072: /*@
7073: DMPlexComputeJacobianActionByKey - Compute the local Jacobian for terms matching the input key
7075: Collective
7077: Input Parameters:
7078: + dm - The output `DM`
7079: . key - The `PetscFormKey` indicating what should be integrated
7080: . cellIS - The `IS` give a set of cells to integrate over
7081: . t - The time
7082: . X_tShift - The multiplier for the Jacobian with respect to $X_t$
7083: . locX - The local solution
7084: . locX_t - The time derivative of the local solution, or `NULL` for time-independent problems
7085: . locY - The local vector acted on by J
7086: - ctx - An optional application context, passed to the pointwise functions
7088: Output Parameter:
7089: . locF - The local residual F = J(X) Y
7091: Level: developer
7093: .seealso: `DMPlexComputeResidualByKey()`, `DMPlexComputeJacobianByKey()`, `DMPlexComputeResidualHybridByKey()`, `DMPlexComputeJacobianHybridByKey()`, `PetscFormKey`
7094: @*/
7095: PetscErrorCode DMPlexComputeJacobianActionByKey(DM dm, PetscFormKey key, IS cellIS, PetscReal t, PetscReal X_tShift, Vec locX, Vec locX_t, Vec locY, Vec locF, PetscCtx ctx)
7096: {
7097: DM_Plex *mesh = (DM_Plex *)dm->data;
7098: const char *name = "Jacobian";
7099: DM dmAux = NULL, plex, plexAux = NULL;
7100: DMEnclosureType encAux;
7101: Vec A;
7102: DMField coordField;
7103: PetscDS prob, probAux = NULL;
7104: PetscQuadrature quad;
7105: PetscSection section, globalSection, sectionAux;
7106: PetscScalar *elemMat, *elemMatD, *u, *u_t, *a = NULL, *y, *z;
7107: const PetscInt *cells;
7108: PetscInt Nf, fieldI, fieldJ;
7109: PetscInt totDim, totDimAux = 0, cStart, cEnd, numCells, c;
7110: PetscBool hasDyn;
7112: PetscFunctionBegin;
7113: PetscCall(PetscLogEventBegin(DMPLEX_JacobianFEM, dm, 0, 0, 0));
7114: PetscCall(DMConvert(dm, DMPLEX, &plex));
7115: PetscCall(ISGetLocalSize(cellIS, &numCells));
7116: PetscCall(ISGetPointRange(cellIS, &cStart, &cEnd, &cells));
7117: PetscCall(DMGetLocalSection(dm, §ion));
7118: PetscCall(DMGetGlobalSection(dm, &globalSection));
7119: PetscCall(DMGetCellDS(dm, cells ? cells[cStart] : cStart, &prob, NULL));
7120: PetscCall(PetscDSGetNumFields(prob, &Nf));
7121: PetscCall(PetscDSGetTotalDimension(prob, &totDim));
7122: PetscCall(PetscDSHasDynamicJacobian(prob, &hasDyn));
7123: hasDyn = hasDyn && (X_tShift != 0.0) ? PETSC_TRUE : PETSC_FALSE;
7124: PetscCall(DMGetAuxiliaryVec(dm, key.label, key.value, key.part, &A));
7125: if (A) {
7126: PetscCall(VecGetDM(A, &dmAux));
7127: PetscCall(DMGetEnclosureRelation(dmAux, dm, &encAux));
7128: PetscCall(DMConvert(dmAux, DMPLEX, &plexAux));
7129: PetscCall(DMGetLocalSection(plexAux, §ionAux));
7130: PetscCall(DMGetDS(dmAux, &probAux));
7131: PetscCall(PetscDSGetTotalDimension(probAux, &totDimAux));
7132: }
7133: PetscCall(VecSet(locF, 0.0));
7134: 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));
7135: if (dmAux) PetscCall(PetscMalloc1(numCells * totDimAux, &a));
7136: PetscCall(DMGetCoordinateField(dm, &coordField));
7137: for (c = cStart; c < cEnd; ++c) {
7138: const PetscInt cell = cells ? cells[c] : c;
7139: const PetscInt cind = c - cStart;
7140: PetscScalar *x = NULL, *x_t = NULL;
7142: PetscCall(DMPlexVecGetClosure(plex, section, locX, cell, NULL, &x));
7143: for (PetscInt i = 0; i < totDim; ++i) u[cind * totDim + i] = x[i];
7144: PetscCall(DMPlexVecRestoreClosure(plex, section, locX, cell, NULL, &x));
7145: if (locX_t) {
7146: PetscCall(DMPlexVecGetClosure(plex, section, locX_t, cell, NULL, &x_t));
7147: for (PetscInt i = 0; i < totDim; ++i) u_t[cind * totDim + i] = x_t[i];
7148: PetscCall(DMPlexVecRestoreClosure(plex, section, locX_t, cell, NULL, &x_t));
7149: }
7150: if (dmAux) {
7151: PetscInt subcell;
7152: PetscCall(DMGetEnclosurePoint(dmAux, dm, encAux, cell, &subcell));
7153: PetscCall(DMPlexVecGetClosure(plexAux, sectionAux, A, subcell, NULL, &x));
7154: for (PetscInt i = 0; i < totDimAux; ++i) a[cind * totDimAux + i] = x[i];
7155: PetscCall(DMPlexVecRestoreClosure(plexAux, sectionAux, A, subcell, NULL, &x));
7156: }
7157: PetscCall(DMPlexVecGetClosure(plex, section, locY, cell, NULL, &x));
7158: for (PetscInt i = 0; i < totDim; ++i) y[cind * totDim + i] = x[i];
7159: PetscCall(DMPlexVecRestoreClosure(plex, section, locY, cell, NULL, &x));
7160: }
7161: PetscCall(PetscArrayzero(elemMat, numCells * totDim * totDim));
7162: if (hasDyn) PetscCall(PetscArrayzero(elemMatD, numCells * totDim * totDim));
7163: for (fieldI = 0; fieldI < Nf; ++fieldI) {
7164: PetscFE fe;
7165: PetscInt Nb;
7166: /* Conforming batches */
7167: PetscInt numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
7168: /* Remainder */
7169: PetscInt Nr, offset, Nq;
7170: PetscQuadrature qGeom = NULL;
7171: PetscInt maxDegree;
7172: PetscFEGeom *cgeomFEM, *chunkGeom = NULL, *remGeom = NULL;
7174: PetscCall(PetscDSGetDiscretization(prob, fieldI, (PetscObject *)&fe));
7175: PetscCall(PetscFEGetQuadrature(fe, &quad));
7176: PetscCall(PetscFEGetDimension(fe, &Nb));
7177: PetscCall(PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches));
7178: PetscCall(DMFieldGetDegree(coordField, cellIS, NULL, &maxDegree));
7179: if (maxDegree <= 1) PetscCall(DMFieldCreateDefaultQuadrature(coordField, cellIS, &qGeom));
7180: if (!qGeom) {
7181: PetscCall(PetscFEGetQuadrature(fe, &qGeom));
7182: PetscCall(PetscObjectReference((PetscObject)qGeom));
7183: }
7184: PetscCall(PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL));
7185: PetscCall(DMSNESGetFEGeom(coordField, cellIS, qGeom, PETSC_FEGEOM_BASIC, &cgeomFEM));
7186: blockSize = Nb;
7187: batchSize = numBlocks * blockSize;
7188: PetscCall(PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches));
7189: numChunks = numCells / (numBatches * batchSize);
7190: Ne = numChunks * numBatches * batchSize;
7191: Nr = numCells % (numBatches * batchSize);
7192: offset = numCells - Nr;
7193: PetscCall(PetscFEGeomGetChunk(cgeomFEM, 0, offset, &chunkGeom));
7194: PetscCall(PetscFEGeomGetChunk(cgeomFEM, offset, numCells, &remGeom));
7195: for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
7196: key.field = fieldI * Nf + fieldJ;
7197: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN, key, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMat));
7198: 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]));
7199: if (hasDyn) {
7200: PetscCall(PetscFEIntegrateJacobian(prob, prob, PETSCFE_JACOBIAN_DYN, key, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMatD));
7201: 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]));
7202: }
7203: }
7204: PetscCall(PetscFEGeomRestoreChunk(cgeomFEM, offset, numCells, &remGeom));
7205: PetscCall(PetscFEGeomRestoreChunk(cgeomFEM, 0, offset, &chunkGeom));
7206: PetscCall(DMSNESRestoreFEGeom(coordField, cellIS, qGeom, PETSC_FALSE, &cgeomFEM));
7207: PetscCall(PetscQuadratureDestroy(&qGeom));
7208: }
7209: if (hasDyn) {
7210: for (c = 0; c < numCells * totDim * totDim; ++c) elemMat[c] += X_tShift * elemMatD[c];
7211: }
7212: for (c = cStart; c < cEnd; ++c) {
7213: const PetscInt cell = cells ? cells[c] : c;
7214: const PetscInt cind = c - cStart;
7215: const PetscBLASInt one = 1;
7216: PetscBLASInt M;
7217: const PetscScalar a = 1.0, b = 0.0;
7219: PetscCall(PetscBLASIntCast(totDim, &M));
7220: PetscCallBLAS("BLASgemv", BLASgemv_("N", &M, &M, &a, &elemMat[cind * totDim * totDim], &M, &y[cind * totDim], &one, &b, z, &one));
7221: if (mesh->printFEM > 1) {
7222: PetscCall(DMPrintCellMatrix(c, name, totDim, totDim, &elemMat[cind * totDim * totDim]));
7223: PetscCall(DMPrintCellVector(c, "Y", totDim, &y[cind * totDim]));
7224: PetscCall(DMPrintCellVector(c, "Z", totDim, z));
7225: }
7226: PetscCall(DMPlexVecSetClosure(dm, section, locF, cell, z, ADD_VALUES));
7227: }
7228: PetscCall(PetscFree6(u, u_t, elemMat, elemMatD, y, z));
7229: if (mesh->printFEM) {
7230: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)locF), "Z:\n"));
7231: PetscCall(VecView(locF, NULL));
7232: }
7233: PetscCall(ISRestorePointRange(cellIS, &cStart, &cEnd, &cells));
7234: PetscCall(PetscFree(a));
7235: PetscCall(DMDestroy(&plexAux));
7236: PetscCall(DMDestroy(&plex));
7237: PetscCall(PetscLogEventEnd(DMPLEX_JacobianFEM, dm, 0, 0, 0));
7238: PetscFunctionReturn(PETSC_SUCCESS);
7239: }
7241: 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[])
7242: {
7243: f0[0] = u[0];
7244: }
7246: 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[])
7247: {
7248: f0[0] = x[(int)PetscRealPart(constants[0])] * u[0];
7249: }
7251: 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[])
7252: {
7253: f0[0] = 0.0;
7254: for (PetscInt d = 0; d < dim; ++d) f0[0] += PetscSqr(x[d]) * u[0];
7255: }
7257: /*@
7258: DMPlexComputeMoments - Compute the first three moments for a field
7260: Noncollective
7262: Input Parameters:
7263: + dm - the `DMPLEX`
7264: - u - the field
7266: Output Parameter:
7267: . moments - the field moments
7269: Level: intermediate
7271: Note:
7272: The `moments` array should be of length cdim + 2, where cdim is the number of components for the coordinate field.
7274: .seealso: `DM`, `DMPLEX`, `DMSwarmComputeMoments()`
7275: @*/
7276: PetscErrorCode DMPlexComputeMoments(DM dm, Vec u, PetscReal moments[])
7277: {
7278: PetscDS ds;
7279: PetscScalar mom, constants[1];
7280: const PetscScalar *oldConstants;
7281: PetscInt cdim, Nf, field = 0, Ncon;
7282: MPI_Comm comm;
7283: void *ctx;
7285: PetscFunctionBeginUser;
7286: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
7287: PetscCall(DMGetCoordinateDim(dm, &cdim));
7288: PetscCall(DMGetApplicationContext(dm, &ctx));
7289: PetscCall(DMGetDS(dm, &ds));
7290: PetscCall(PetscDSGetNumFields(ds, &Nf));
7291: PetscCall(PetscDSGetConstants(ds, &Ncon, &oldConstants));
7292: PetscCheck(Nf == 1, comm, PETSC_ERR_ARG_WRONG, "We currently only support 1 field, not %" PetscInt_FMT, Nf);
7293: PetscCall(PetscDSSetObjective(ds, field, &f0_1));
7294: PetscCall(DMPlexComputeIntegralFEM(dm, u, &mom, ctx));
7295: moments[0] = PetscRealPart(mom);
7296: for (PetscInt c = 0; c < cdim; ++c) {
7297: constants[0] = c;
7298: PetscCall(PetscDSSetConstants(ds, 1, constants));
7299: PetscCall(PetscDSSetObjective(ds, field, &f0_x));
7300: PetscCall(DMPlexComputeIntegralFEM(dm, u, &mom, ctx));
7301: moments[c + 1] = PetscRealPart(mom);
7302: }
7303: PetscCall(PetscDSSetObjective(ds, field, &f0_x2));
7304: PetscCall(DMPlexComputeIntegralFEM(dm, u, &mom, ctx));
7305: moments[cdim + 1] = PetscRealPart(mom);
7306: PetscCall(PetscDSSetConstants(ds, Ncon, (PetscScalar *)oldConstants));
7307: PetscFunctionReturn(PETSC_SUCCESS);
7308: }