xref: /petsc/src/dm/impls/plex/plexgeometry.c (revision 1f08e9caf7f0fce05319addd8259603a6d4b7a93)
1*1f08e9caSMatthew G. Knepley #include "petscdm.h"
2*1f08e9caSMatthew G. Knepley #include "petscdmtypes.h"
3*1f08e9caSMatthew G. Knepley #include "petscsystypes.h"
4af0996ceSBarry Smith #include <petsc/private/dmpleximpl.h>  /*I      "petscdmplex.h"   I*/
59d150b73SToby Isaac #include <petsc/private/petscfeimpl.h> /*I      "petscfe.h"       I*/
69d150b73SToby Isaac #include <petscblaslapack.h>
7af74b616SDave May #include <petsctime.h>
8ccd2543fSMatthew G Knepley 
9530e699aSMatthew G. Knepley const char *const DMPlexCoordMaps[] = {"none", "shear", "flare", "annulus", "shell", "sinusoid", "unknown", "DMPlexCoordMap", "DM_COORD_MAP_", NULL};
10be664eb1SMatthew G. Knepley 
113985bb02SVaclav Hapla /*@
123985bb02SVaclav Hapla   DMPlexFindVertices - Try to find DAG points based on their coordinates.
133985bb02SVaclav Hapla 
1420f4b53cSBarry Smith   Not Collective (provided `DMGetCoordinatesLocalSetUp()` has been already called)
153985bb02SVaclav Hapla 
163985bb02SVaclav Hapla   Input Parameters:
1720f4b53cSBarry Smith + dm          - The `DMPLEX` object
1820f4b53cSBarry Smith . coordinates - The `Vec` of coordinates of the sought points
1920f4b53cSBarry Smith - eps         - The tolerance or `PETSC_DEFAULT`
203985bb02SVaclav Hapla 
212fe279fdSBarry Smith   Output Parameter:
2220f4b53cSBarry Smith . points - The `IS` of found DAG points or -1
233985bb02SVaclav Hapla 
243985bb02SVaclav Hapla   Level: intermediate
253985bb02SVaclav Hapla 
263985bb02SVaclav Hapla   Notes:
2720f4b53cSBarry Smith   The length of `Vec` coordinates must be npoints * dim where dim is the spatial dimension returned by `DMGetCoordinateDim()` and npoints is the number of sought points.
283985bb02SVaclav Hapla 
2920f4b53cSBarry Smith   The output `IS` is living on `PETSC_COMM_SELF` and its length is npoints.
30d3e1f4ccSVaclav Hapla   Each rank does the search independently.
3120f4b53cSBarry Smith   If this rank's local `DMPLEX` portion contains the DAG point corresponding to the i-th tuple of coordinates, the i-th entry of the output `IS` is set to that DAG point, otherwise to -1.
323985bb02SVaclav Hapla 
3320f4b53cSBarry Smith   The output `IS` must be destroyed by user.
343985bb02SVaclav Hapla 
353985bb02SVaclav Hapla   The tolerance is interpreted as the maximum Euclidean (L2) distance of the sought point from the specified coordinates.
363985bb02SVaclav Hapla 
37d3e1f4ccSVaclav Hapla   Complexity of this function is currently O(mn) with m number of vertices to find and n number of vertices in the local mesh. This could probably be improved if needed.
38335ef845SVaclav Hapla 
3920f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexCreate()`, `DMGetCoordinatesLocal()`
403985bb02SVaclav Hapla @*/
41d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexFindVertices(DM dm, Vec coordinates, PetscReal eps, IS *points)
42d71ae5a4SJacob Faibussowitsch {
4337900f7dSMatthew G. Knepley   PetscInt           c, cdim, i, j, o, p, vStart, vEnd;
44d3e1f4ccSVaclav Hapla   PetscInt           npoints;
45d3e1f4ccSVaclav Hapla   const PetscScalar *coord;
463985bb02SVaclav Hapla   Vec                allCoordsVec;
473985bb02SVaclav Hapla   const PetscScalar *allCoords;
48d3e1f4ccSVaclav Hapla   PetscInt          *dagPoints;
493985bb02SVaclav Hapla 
503985bb02SVaclav Hapla   PetscFunctionBegin;
513985bb02SVaclav Hapla   if (eps < 0) eps = PETSC_SQRT_MACHINE_EPSILON;
529566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &cdim));
53d3e1f4ccSVaclav Hapla   {
54d3e1f4ccSVaclav Hapla     PetscInt n;
55d3e1f4ccSVaclav Hapla 
569566063dSJacob Faibussowitsch     PetscCall(VecGetLocalSize(coordinates, &n));
5763a3b9bcSJacob Faibussowitsch     PetscCheck(n % cdim == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Given coordinates Vec has local length %" PetscInt_FMT " not divisible by coordinate dimension %" PetscInt_FMT " of given DM", n, cdim);
58d3e1f4ccSVaclav Hapla     npoints = n / cdim;
59d3e1f4ccSVaclav Hapla   }
609566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinatesLocal(dm, &allCoordsVec));
619566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(allCoordsVec, &allCoords));
629566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(coordinates, &coord));
639566063dSJacob Faibussowitsch   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
6476bd3646SJed Brown   if (PetscDefined(USE_DEBUG)) {
65335ef845SVaclav Hapla     /* check coordinate section is consistent with DM dimension */
66335ef845SVaclav Hapla     PetscSection cs;
67335ef845SVaclav Hapla     PetscInt     ndof;
68335ef845SVaclav Hapla 
699566063dSJacob Faibussowitsch     PetscCall(DMGetCoordinateSection(dm, &cs));
703985bb02SVaclav Hapla     for (p = vStart; p < vEnd; p++) {
719566063dSJacob Faibussowitsch       PetscCall(PetscSectionGetDof(cs, p, &ndof));
7263a3b9bcSJacob Faibussowitsch       PetscCheck(ndof == cdim, PETSC_COMM_SELF, PETSC_ERR_PLIB, "point %" PetscInt_FMT ": ndof = %" PetscInt_FMT " != %" PetscInt_FMT " = cdim", p, ndof, cdim);
73335ef845SVaclav Hapla     }
74335ef845SVaclav Hapla   }
759566063dSJacob Faibussowitsch   PetscCall(PetscMalloc1(npoints, &dagPoints));
76eca9f518SVaclav Hapla   if (eps == 0.0) {
7737900f7dSMatthew G. Knepley     for (i = 0, j = 0; i < npoints; i++, j += cdim) {
78eca9f518SVaclav Hapla       dagPoints[i] = -1;
7937900f7dSMatthew G. Knepley       for (p = vStart, o = 0; p < vEnd; p++, o += cdim) {
8037900f7dSMatthew G. Knepley         for (c = 0; c < cdim; c++) {
81d3e1f4ccSVaclav Hapla           if (coord[j + c] != allCoords[o + c]) break;
82eca9f518SVaclav Hapla         }
8337900f7dSMatthew G. Knepley         if (c == cdim) {
84eca9f518SVaclav Hapla           dagPoints[i] = p;
85eca9f518SVaclav Hapla           break;
86eca9f518SVaclav Hapla         }
87eca9f518SVaclav Hapla       }
88eca9f518SVaclav Hapla     }
89d3e1f4ccSVaclav Hapla   } else {
9037900f7dSMatthew G. Knepley     for (i = 0, j = 0; i < npoints; i++, j += cdim) {
91d3e1f4ccSVaclav Hapla       PetscReal norm;
92d3e1f4ccSVaclav Hapla 
93335ef845SVaclav Hapla       dagPoints[i] = -1;
9437900f7dSMatthew G. Knepley       for (p = vStart, o = 0; p < vEnd; p++, o += cdim) {
953985bb02SVaclav Hapla         norm = 0.0;
96ad540459SPierre Jolivet         for (c = 0; c < cdim; c++) norm += PetscRealPart(PetscSqr(coord[j + c] - allCoords[o + c]));
973985bb02SVaclav Hapla         norm = PetscSqrtReal(norm);
983985bb02SVaclav Hapla         if (norm <= eps) {
993985bb02SVaclav Hapla           dagPoints[i] = p;
1003985bb02SVaclav Hapla           break;
1013985bb02SVaclav Hapla         }
1023985bb02SVaclav Hapla       }
1033985bb02SVaclav Hapla     }
104d3e1f4ccSVaclav Hapla   }
1059566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(allCoordsVec, &allCoords));
1069566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(coordinates, &coord));
1079566063dSJacob Faibussowitsch   PetscCall(ISCreateGeneral(PETSC_COMM_SELF, npoints, dagPoints, PETSC_OWN_POINTER, points));
1083ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1093985bb02SVaclav Hapla }
1103985bb02SVaclav Hapla 
1116363a54bSMatthew G. Knepley #if 0
112d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexGetLineIntersection_2D_Internal(const PetscReal segmentA[], const PetscReal segmentB[], PetscReal intersection[], PetscBool *hasIntersection)
113d71ae5a4SJacob Faibussowitsch {
114fea14342SMatthew G. Knepley   const PetscReal p0_x  = segmentA[0 * 2 + 0];
115fea14342SMatthew G. Knepley   const PetscReal p0_y  = segmentA[0 * 2 + 1];
116fea14342SMatthew G. Knepley   const PetscReal p1_x  = segmentA[1 * 2 + 0];
117fea14342SMatthew G. Knepley   const PetscReal p1_y  = segmentA[1 * 2 + 1];
118fea14342SMatthew G. Knepley   const PetscReal p2_x  = segmentB[0 * 2 + 0];
119fea14342SMatthew G. Knepley   const PetscReal p2_y  = segmentB[0 * 2 + 1];
120fea14342SMatthew G. Knepley   const PetscReal p3_x  = segmentB[1 * 2 + 0];
121fea14342SMatthew G. Knepley   const PetscReal p3_y  = segmentB[1 * 2 + 1];
122fea14342SMatthew G. Knepley   const PetscReal s1_x  = p1_x - p0_x;
123fea14342SMatthew G. Knepley   const PetscReal s1_y  = p1_y - p0_y;
124fea14342SMatthew G. Knepley   const PetscReal s2_x  = p3_x - p2_x;
125fea14342SMatthew G. Knepley   const PetscReal s2_y  = p3_y - p2_y;
126fea14342SMatthew G. Knepley   const PetscReal denom = (-s2_x * s1_y + s1_x * s2_y);
127fea14342SMatthew G. Knepley 
128fea14342SMatthew G. Knepley   PetscFunctionBegin;
129fea14342SMatthew G. Knepley   *hasIntersection = PETSC_FALSE;
130fea14342SMatthew G. Knepley   /* Non-parallel lines */
131fea14342SMatthew G. Knepley   if (denom != 0.0) {
132fea14342SMatthew G. Knepley     const PetscReal s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / denom;
133fea14342SMatthew G. Knepley     const PetscReal t = (s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / denom;
134fea14342SMatthew G. Knepley 
135fea14342SMatthew G. Knepley     if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
136fea14342SMatthew G. Knepley       *hasIntersection = PETSC_TRUE;
137fea14342SMatthew G. Knepley       if (intersection) {
138fea14342SMatthew G. Knepley         intersection[0] = p0_x + (t * s1_x);
139fea14342SMatthew G. Knepley         intersection[1] = p0_y + (t * s1_y);
140fea14342SMatthew G. Knepley       }
141fea14342SMatthew G. Knepley     }
142fea14342SMatthew G. Knepley   }
1433ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
144fea14342SMatthew G. Knepley }
145fea14342SMatthew G. Knepley 
146ddce0771SMatthew G. Knepley /* The plane is segmentB x segmentC: https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection */
147d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexGetLinePlaneIntersection_3D_Internal(const PetscReal segmentA[], const PetscReal segmentB[], const PetscReal segmentC[], PetscReal intersection[], PetscBool *hasIntersection)
148d71ae5a4SJacob Faibussowitsch {
149ddce0771SMatthew G. Knepley   const PetscReal p0_x  = segmentA[0 * 3 + 0];
150ddce0771SMatthew G. Knepley   const PetscReal p0_y  = segmentA[0 * 3 + 1];
151ddce0771SMatthew G. Knepley   const PetscReal p0_z  = segmentA[0 * 3 + 2];
152ddce0771SMatthew G. Knepley   const PetscReal p1_x  = segmentA[1 * 3 + 0];
153ddce0771SMatthew G. Knepley   const PetscReal p1_y  = segmentA[1 * 3 + 1];
154ddce0771SMatthew G. Knepley   const PetscReal p1_z  = segmentA[1 * 3 + 2];
155ddce0771SMatthew G. Knepley   const PetscReal q0_x  = segmentB[0 * 3 + 0];
156ddce0771SMatthew G. Knepley   const PetscReal q0_y  = segmentB[0 * 3 + 1];
157ddce0771SMatthew G. Knepley   const PetscReal q0_z  = segmentB[0 * 3 + 2];
158ddce0771SMatthew G. Knepley   const PetscReal q1_x  = segmentB[1 * 3 + 0];
159ddce0771SMatthew G. Knepley   const PetscReal q1_y  = segmentB[1 * 3 + 1];
160ddce0771SMatthew G. Knepley   const PetscReal q1_z  = segmentB[1 * 3 + 2];
161ddce0771SMatthew G. Knepley   const PetscReal r0_x  = segmentC[0 * 3 + 0];
162ddce0771SMatthew G. Knepley   const PetscReal r0_y  = segmentC[0 * 3 + 1];
163ddce0771SMatthew G. Knepley   const PetscReal r0_z  = segmentC[0 * 3 + 2];
164ddce0771SMatthew G. Knepley   const PetscReal r1_x  = segmentC[1 * 3 + 0];
165ddce0771SMatthew G. Knepley   const PetscReal r1_y  = segmentC[1 * 3 + 1];
166ddce0771SMatthew G. Knepley   const PetscReal r1_z  = segmentC[1 * 3 + 2];
167ddce0771SMatthew G. Knepley   const PetscReal s0_x  = p1_x - p0_x;
168ddce0771SMatthew G. Knepley   const PetscReal s0_y  = p1_y - p0_y;
169ddce0771SMatthew G. Knepley   const PetscReal s0_z  = p1_z - p0_z;
170ddce0771SMatthew G. Knepley   const PetscReal s1_x  = q1_x - q0_x;
171ddce0771SMatthew G. Knepley   const PetscReal s1_y  = q1_y - q0_y;
172ddce0771SMatthew G. Knepley   const PetscReal s1_z  = q1_z - q0_z;
173ddce0771SMatthew G. Knepley   const PetscReal s2_x  = r1_x - r0_x;
174ddce0771SMatthew G. Knepley   const PetscReal s2_y  = r1_y - r0_y;
175ddce0771SMatthew G. Knepley   const PetscReal s2_z  = r1_z - r0_z;
176ddce0771SMatthew G. Knepley   const PetscReal s3_x  = s1_y * s2_z - s1_z * s2_y; /* s1 x s2 */
177ddce0771SMatthew G. Knepley   const PetscReal s3_y  = s1_z * s2_x - s1_x * s2_z;
178ddce0771SMatthew G. Knepley   const PetscReal s3_z  = s1_x * s2_y - s1_y * s2_x;
179ddce0771SMatthew G. Knepley   const PetscReal s4_x  = s0_y * s2_z - s0_z * s2_y; /* s0 x s2 */
180ddce0771SMatthew G. Knepley   const PetscReal s4_y  = s0_z * s2_x - s0_x * s2_z;
181ddce0771SMatthew G. Knepley   const PetscReal s4_z  = s0_x * s2_y - s0_y * s2_x;
182ddce0771SMatthew G. Knepley   const PetscReal s5_x  = s1_y * s0_z - s1_z * s0_y; /* s1 x s0 */
183ddce0771SMatthew G. Knepley   const PetscReal s5_y  = s1_z * s0_x - s1_x * s0_z;
184ddce0771SMatthew G. Knepley   const PetscReal s5_z  = s1_x * s0_y - s1_y * s0_x;
185ddce0771SMatthew G. Knepley   const PetscReal denom = -(s0_x * s3_x + s0_y * s3_y + s0_z * s3_z); /* -s0 . (s1 x s2) */
186ddce0771SMatthew G. Knepley 
187ddce0771SMatthew G. Knepley   PetscFunctionBegin;
188ddce0771SMatthew G. Knepley   *hasIntersection = PETSC_FALSE;
189ddce0771SMatthew G. Knepley   /* Line not parallel to plane */
190ddce0771SMatthew G. Knepley   if (denom != 0.0) {
191ddce0771SMatthew G. Knepley     const PetscReal t = (s3_x * (p0_x - q0_x) + s3_y * (p0_y - q0_y) + s3_z * (p0_z - q0_z)) / denom;
192ddce0771SMatthew G. Knepley     const PetscReal u = (s4_x * (p0_x - q0_x) + s4_y * (p0_y - q0_y) + s4_z * (p0_z - q0_z)) / denom;
193ddce0771SMatthew G. Knepley     const PetscReal v = (s5_x * (p0_x - q0_x) + s5_y * (p0_y - q0_y) + s5_z * (p0_z - q0_z)) / denom;
194ddce0771SMatthew G. Knepley 
195ddce0771SMatthew G. Knepley     if (t >= 0 && t <= 1 && u >= 0 && u <= 1 && v >= 0 && v <= 1) {
196ddce0771SMatthew G. Knepley       *hasIntersection = PETSC_TRUE;
197ddce0771SMatthew G. Knepley       if (intersection) {
198ddce0771SMatthew G. Knepley         intersection[0] = p0_x + (t * s0_x);
199ddce0771SMatthew G. Knepley         intersection[1] = p0_y + (t * s0_y);
200ddce0771SMatthew G. Knepley         intersection[2] = p0_z + (t * s0_z);
201ddce0771SMatthew G. Knepley       }
202ddce0771SMatthew G. Knepley     }
203ddce0771SMatthew G. Knepley   }
2043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
205ddce0771SMatthew G. Knepley }
2066363a54bSMatthew G. Knepley #endif
2076363a54bSMatthew G. Knepley 
2086363a54bSMatthew G. Knepley static PetscErrorCode DMPlexGetPlaneSimplexIntersection_Coords_Internal(DM dm, PetscInt dim, PetscInt cdim, const PetscScalar coords[], const PetscReal p[], const PetscReal normal[], PetscBool *pos, PetscInt *Nint, PetscReal intPoints[])
2096363a54bSMatthew G. Knepley {
2106363a54bSMatthew G. Knepley   PetscReal d[4]; // distance of vertices to the plane
2116363a54bSMatthew G. Knepley   PetscReal dp;   // distance from origin to the plane
2126363a54bSMatthew G. Knepley   PetscInt  n = 0;
2136363a54bSMatthew G. Knepley 
2146363a54bSMatthew G. Knepley   PetscFunctionBegin;
2156363a54bSMatthew G. Knepley   if (pos) *pos = PETSC_FALSE;
2166363a54bSMatthew G. Knepley   if (Nint) *Nint = 0;
2176363a54bSMatthew G. Knepley   if (PetscDefined(USE_DEBUG)) {
2186363a54bSMatthew G. Knepley     PetscReal mag = DMPlex_NormD_Internal(cdim, normal);
219b58dcb05SPierre Jolivet     PetscCheck(PetscAbsReal(mag - (PetscReal)1.0) < PETSC_SMALL, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Normal vector is not normalized: %g", (double)mag);
2206363a54bSMatthew G. Knepley   }
2216363a54bSMatthew G. Knepley 
2226363a54bSMatthew G. Knepley   dp = DMPlex_DotRealD_Internal(cdim, normal, p);
2236363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < dim + 1; ++v) {
2246363a54bSMatthew G. Knepley     // d[v] is positive, zero, or negative if vertex i is above, on, or below the plane
2256363a54bSMatthew G. Knepley #if defined(PETSC_USE_COMPLEX)
2266363a54bSMatthew G. Knepley     PetscReal c[4];
2276363a54bSMatthew G. Knepley     for (PetscInt i = 0; i < cdim; ++i) c[i] = PetscRealPart(coords[v * cdim + i]);
2286363a54bSMatthew G. Knepley     d[v] = DMPlex_DotRealD_Internal(cdim, normal, c);
2296363a54bSMatthew G. Knepley #else
2306363a54bSMatthew G. Knepley     d[v] = DMPlex_DotRealD_Internal(cdim, normal, &coords[v * cdim]);
2316363a54bSMatthew G. Knepley #endif
2326363a54bSMatthew G. Knepley     d[v] -= dp;
2336363a54bSMatthew G. Knepley   }
2346363a54bSMatthew G. Knepley 
2356363a54bSMatthew G. Knepley   // If all d are positive or negative, no intersection
2366363a54bSMatthew G. Knepley   {
2376363a54bSMatthew G. Knepley     PetscInt v;
2386363a54bSMatthew G. Knepley     for (v = 0; v < dim + 1; ++v)
2396363a54bSMatthew G. Knepley       if (d[v] >= 0.) break;
2406363a54bSMatthew G. Knepley     if (v == dim + 1) PetscFunctionReturn(PETSC_SUCCESS);
2416363a54bSMatthew G. Knepley     for (v = 0; v < dim + 1; ++v)
2426363a54bSMatthew G. Knepley       if (d[v] <= 0.) break;
2436363a54bSMatthew G. Knepley     if (v == dim + 1) {
2446363a54bSMatthew G. Knepley       if (pos) *pos = PETSC_TRUE;
2456363a54bSMatthew G. Knepley       PetscFunctionReturn(PETSC_SUCCESS);
2466363a54bSMatthew G. Knepley     }
2476363a54bSMatthew G. Knepley   }
2486363a54bSMatthew G. Knepley 
2496363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < dim + 1; ++v) {
2506363a54bSMatthew G. Knepley     // Points with zero distance are automatically added to the list.
2516363a54bSMatthew G. Knepley     if (PetscAbsReal(d[v]) < PETSC_MACHINE_EPSILON) {
2526363a54bSMatthew G. Knepley       for (PetscInt i = 0; i < cdim; ++i) intPoints[n * cdim + i] = PetscRealPart(coords[v * cdim + i]);
2536363a54bSMatthew G. Knepley       ++n;
2546363a54bSMatthew G. Knepley     } else {
2556363a54bSMatthew G. Knepley       // For each point with nonzero distance, seek another point with opposite sign
2566363a54bSMatthew G. Knepley       // and higher index, and compute the intersection of the line between those
2576363a54bSMatthew G. Knepley       // points and the plane.
2586363a54bSMatthew G. Knepley       for (PetscInt w = v + 1; w < dim + 1; ++w) {
2596363a54bSMatthew G. Knepley         if (d[v] * d[w] < 0.) {
2606363a54bSMatthew G. Knepley           PetscReal inv_dist = 1. / (d[v] - d[w]);
2616363a54bSMatthew G. Knepley           for (PetscInt i = 0; i < cdim; ++i) intPoints[n * cdim + i] = (d[v] * PetscRealPart(coords[w * cdim + i]) - d[w] * PetscRealPart(coords[v * cdim + i])) * inv_dist;
2626363a54bSMatthew G. Knepley           ++n;
2636363a54bSMatthew G. Knepley         }
2646363a54bSMatthew G. Knepley       }
2656363a54bSMatthew G. Knepley     }
2666363a54bSMatthew G. Knepley   }
2676363a54bSMatthew G. Knepley   // TODO order output points if there are 4
2686363a54bSMatthew G. Knepley   *Nint = n;
2696363a54bSMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
2706363a54bSMatthew G. Knepley }
2716363a54bSMatthew G. Knepley 
2726363a54bSMatthew G. Knepley static PetscErrorCode DMPlexGetPlaneSimplexIntersection_Internal(DM dm, PetscInt dim, PetscInt c, const PetscReal p[], const PetscReal normal[], PetscBool *pos, PetscInt *Nint, PetscReal intPoints[])
2736363a54bSMatthew G. Knepley {
2746363a54bSMatthew G. Knepley   const PetscScalar *array;
2756363a54bSMatthew G. Knepley   PetscScalar       *coords = NULL;
2766363a54bSMatthew G. Knepley   PetscInt           numCoords;
2776363a54bSMatthew G. Knepley   PetscBool          isDG;
2786363a54bSMatthew G. Knepley   PetscInt           cdim;
2796363a54bSMatthew G. Knepley 
2806363a54bSMatthew G. Knepley   PetscFunctionBegin;
2816363a54bSMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &cdim));
2826363a54bSMatthew G. Knepley   PetscCheck(cdim == dim, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "DM has coordinates in %" PetscInt_FMT "D instead of %" PetscInt_FMT "D", cdim, dim);
2836363a54bSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
2846363a54bSMatthew G. Knepley   PetscCheck(numCoords == dim * (dim + 1), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Tetrahedron should have %" PetscInt_FMT " coordinates, not %" PetscInt_FMT, dim * (dim + 1), numCoords);
2856363a54bSMatthew G. Knepley   PetscCall(PetscArrayzero(intPoints, dim * (dim + 1)));
2866363a54bSMatthew G. Knepley 
2876363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, coords, p, normal, pos, Nint, intPoints));
2886363a54bSMatthew G. Knepley 
2896363a54bSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
2906363a54bSMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
2916363a54bSMatthew G. Knepley }
2926363a54bSMatthew G. Knepley 
2936363a54bSMatthew G. Knepley static PetscErrorCode DMPlexGetPlaneQuadIntersection_Internal(DM dm, PetscInt dim, PetscInt c, const PetscReal p[], const PetscReal normal[], PetscBool *pos, PetscInt *Nint, PetscReal intPoints[])
2946363a54bSMatthew G. Knepley {
2956363a54bSMatthew G. Knepley   const PetscScalar *array;
2966363a54bSMatthew G. Knepley   PetscScalar       *coords = NULL;
2976363a54bSMatthew G. Knepley   PetscInt           numCoords;
2986363a54bSMatthew G. Knepley   PetscBool          isDG;
2996363a54bSMatthew G. Knepley   PetscInt           cdim;
3006363a54bSMatthew G. Knepley   PetscScalar        tcoords[6] = {0., 0., 0., 0., 0., 0.};
3016363a54bSMatthew G. Knepley   const PetscInt     vertsA[3]  = {0, 1, 3};
3026363a54bSMatthew G. Knepley   const PetscInt     vertsB[3]  = {1, 2, 3};
3036363a54bSMatthew G. Knepley   PetscInt           NintA, NintB;
3046363a54bSMatthew G. Knepley 
3056363a54bSMatthew G. Knepley   PetscFunctionBegin;
3066363a54bSMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &cdim));
3076363a54bSMatthew G. Knepley   PetscCheck(cdim == dim, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "DM has coordinates in %" PetscInt_FMT "D instead of %" PetscInt_FMT "D", cdim, dim);
3086363a54bSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
3096363a54bSMatthew G. Knepley   PetscCheck(numCoords == dim * 4, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Quadrilateral should have %" PetscInt_FMT " coordinates, not %" PetscInt_FMT, dim * 4, numCoords);
3106363a54bSMatthew G. Knepley   PetscCall(PetscArrayzero(intPoints, dim * 4));
3116363a54bSMatthew G. Knepley 
3126363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 3; ++v)
3136363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsA[v] * cdim + d];
3146363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintA, intPoints));
3156363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 3; ++v)
3166363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsB[v] * cdim + d];
3176363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintB, &intPoints[NintA * cdim]));
3186363a54bSMatthew G. Knepley   *Nint = NintA + NintB;
3196363a54bSMatthew G. Knepley 
3206363a54bSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
3216363a54bSMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
3226363a54bSMatthew G. Knepley }
3236363a54bSMatthew G. Knepley 
3246363a54bSMatthew G. Knepley static PetscErrorCode DMPlexGetPlaneHexIntersection_Internal(DM dm, PetscInt dim, PetscInt c, const PetscReal p[], const PetscReal normal[], PetscBool *pos, PetscInt *Nint, PetscReal intPoints[])
3256363a54bSMatthew G. Knepley {
3266363a54bSMatthew G. Knepley   const PetscScalar *array;
3276363a54bSMatthew G. Knepley   PetscScalar       *coords = NULL;
3286363a54bSMatthew G. Knepley   PetscInt           numCoords;
3296363a54bSMatthew G. Knepley   PetscBool          isDG;
3306363a54bSMatthew G. Knepley   PetscInt           cdim;
3316363a54bSMatthew G. Knepley   PetscScalar        tcoords[12] = {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.};
3326363a54bSMatthew G. Knepley   // We split using the (2, 4) main diagonal, so all tets contain those vertices
3336363a54bSMatthew G. Knepley   const PetscInt vertsA[4] = {0, 1, 2, 4};
3346363a54bSMatthew G. Knepley   const PetscInt vertsB[4] = {0, 2, 3, 4};
3356363a54bSMatthew G. Knepley   const PetscInt vertsC[4] = {1, 7, 2, 4};
3366363a54bSMatthew G. Knepley   const PetscInt vertsD[4] = {2, 7, 6, 4};
3376363a54bSMatthew G. Knepley   const PetscInt vertsE[4] = {3, 5, 4, 2};
3386363a54bSMatthew G. Knepley   const PetscInt vertsF[4] = {4, 5, 6, 2};
3396363a54bSMatthew G. Knepley   PetscInt       NintA, NintB, NintC, NintD, NintE, NintF, Nsum = 0;
3406363a54bSMatthew G. Knepley 
3416363a54bSMatthew G. Knepley   PetscFunctionBegin;
3426363a54bSMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &cdim));
3436363a54bSMatthew G. Knepley   PetscCheck(cdim == dim, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "DM has coordinates in %" PetscInt_FMT "D instead of %" PetscInt_FMT "D", cdim, dim);
3446363a54bSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
3456363a54bSMatthew G. Knepley   PetscCheck(numCoords == dim * 8, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Hexahedron should have %" PetscInt_FMT " coordinates, not %" PetscInt_FMT, dim * 8, numCoords);
3466363a54bSMatthew G. Knepley   PetscCall(PetscArrayzero(intPoints, dim * 18));
3476363a54bSMatthew G. Knepley 
3486363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 4; ++v)
3496363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsA[v] * cdim + d];
3506363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintA, &intPoints[Nsum * cdim]));
3516363a54bSMatthew G. Knepley   Nsum += NintA;
3526363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 4; ++v)
3536363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsB[v] * cdim + d];
3546363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintB, &intPoints[Nsum * cdim]));
3556363a54bSMatthew G. Knepley   Nsum += NintB;
3566363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 4; ++v)
3576363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsC[v] * cdim + d];
3586363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintC, &intPoints[Nsum * cdim]));
3596363a54bSMatthew G. Knepley   Nsum += NintC;
3606363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 4; ++v)
3616363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsD[v] * cdim + d];
3626363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintD, &intPoints[Nsum * cdim]));
3636363a54bSMatthew G. Knepley   Nsum += NintD;
3646363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 4; ++v)
3656363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsE[v] * cdim + d];
3666363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintE, &intPoints[Nsum * cdim]));
3676363a54bSMatthew G. Knepley   Nsum += NintE;
3686363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 4; ++v)
3696363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsF[v] * cdim + d];
3706363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintF, &intPoints[Nsum * cdim]));
3716363a54bSMatthew G. Knepley   Nsum += NintF;
3726363a54bSMatthew G. Knepley   *Nint = Nsum;
3736363a54bSMatthew G. Knepley 
3746363a54bSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
3756363a54bSMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
3766363a54bSMatthew G. Knepley }
3776363a54bSMatthew G. Knepley 
3786363a54bSMatthew G. Knepley /*
3796363a54bSMatthew G. Knepley   DMPlexGetPlaneCellIntersection_Internal - Finds the intersection of a plane with a cell
3806363a54bSMatthew G. Knepley 
3816363a54bSMatthew G. Knepley   Not collective
3826363a54bSMatthew G. Knepley 
3836363a54bSMatthew G. Knepley   Input Parameters:
3846363a54bSMatthew G. Knepley + dm     - the DM
3856363a54bSMatthew G. Knepley . c      - the mesh point
3866363a54bSMatthew G. Knepley . p      - a point on the plane.
3876363a54bSMatthew G. Knepley - normal - a normal vector to the plane, must be normalized
3886363a54bSMatthew G. Knepley 
3896363a54bSMatthew G. Knepley   Output Parameters:
3906363a54bSMatthew G. Knepley . pos       - `PETSC_TRUE` is the cell is on the positive side of the plane, `PETSC_FALSE` on the negative side
3916363a54bSMatthew G. Knepley + Nint      - the number of intersection points, in [0, 4]
3926363a54bSMatthew G. Knepley - intPoints - the coordinates of the intersection points, should be length at least 12
3936363a54bSMatthew G. Knepley 
394baca6076SPierre Jolivet   Note: The `pos` argument is only meaningful if the number of intersections is 0. The algorithmic idea comes from https://github.com/chrisk314/tet-plane-intersection.
3956363a54bSMatthew G. Knepley 
3966363a54bSMatthew G. Knepley   Level: developer
3976363a54bSMatthew G. Knepley 
3986363a54bSMatthew G. Knepley .seealso:
3996363a54bSMatthew G. Knepley @*/
4006363a54bSMatthew G. Knepley static PetscErrorCode DMPlexGetPlaneCellIntersection_Internal(DM dm, PetscInt c, const PetscReal p[], const PetscReal normal[], PetscBool *pos, PetscInt *Nint, PetscReal intPoints[])
4016363a54bSMatthew G. Knepley {
4026363a54bSMatthew G. Knepley   DMPolytopeType ct;
4036363a54bSMatthew G. Knepley 
4046363a54bSMatthew G. Knepley   PetscFunctionBegin;
4056363a54bSMatthew G. Knepley   PetscCall(DMPlexGetCellType(dm, c, &ct));
4066363a54bSMatthew G. Knepley   switch (ct) {
4076363a54bSMatthew G. Knepley   case DM_POLYTOPE_SEGMENT:
4086363a54bSMatthew G. Knepley   case DM_POLYTOPE_TRIANGLE:
4096363a54bSMatthew G. Knepley   case DM_POLYTOPE_TETRAHEDRON:
4106363a54bSMatthew G. Knepley     PetscCall(DMPlexGetPlaneSimplexIntersection_Internal(dm, DMPolytopeTypeGetDim(ct), c, p, normal, pos, Nint, intPoints));
4116363a54bSMatthew G. Knepley     break;
4126363a54bSMatthew G. Knepley   case DM_POLYTOPE_QUADRILATERAL:
4136363a54bSMatthew G. Knepley     PetscCall(DMPlexGetPlaneQuadIntersection_Internal(dm, DMPolytopeTypeGetDim(ct), c, p, normal, pos, Nint, intPoints));
4146363a54bSMatthew G. Knepley     break;
4156363a54bSMatthew G. Knepley   case DM_POLYTOPE_HEXAHEDRON:
4166363a54bSMatthew G. Knepley     PetscCall(DMPlexGetPlaneHexIntersection_Internal(dm, DMPolytopeTypeGetDim(ct), c, p, normal, pos, Nint, intPoints));
4176363a54bSMatthew G. Knepley     break;
4186363a54bSMatthew G. Knepley   default:
4196363a54bSMatthew G. Knepley     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "No plane intersection for cell %" PetscInt_FMT " with type %s", c, DMPolytopeTypes[ct]);
4206363a54bSMatthew G. Knepley   }
4216363a54bSMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
4226363a54bSMatthew G. Knepley }
423ddce0771SMatthew G. Knepley 
424d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexLocatePoint_Simplex_1D_Internal(DM dm, const PetscScalar point[], PetscInt c, PetscInt *cell)
425d71ae5a4SJacob Faibussowitsch {
42614bbb9f0SLawrence Mitchell   const PetscReal eps = PETSC_SQRT_MACHINE_EPSILON;
42714bbb9f0SLawrence Mitchell   const PetscReal x   = PetscRealPart(point[0]);
42814bbb9f0SLawrence Mitchell   PetscReal       v0, J, invJ, detJ;
42914bbb9f0SLawrence Mitchell   PetscReal       xi;
43014bbb9f0SLawrence Mitchell 
43114bbb9f0SLawrence Mitchell   PetscFunctionBegin;
4329566063dSJacob Faibussowitsch   PetscCall(DMPlexComputeCellGeometryFEM(dm, c, NULL, &v0, &J, &invJ, &detJ));
43314bbb9f0SLawrence Mitchell   xi = invJ * (x - v0);
43414bbb9f0SLawrence Mitchell 
43514bbb9f0SLawrence Mitchell   if ((xi >= -eps) && (xi <= 2. + eps)) *cell = c;
43614bbb9f0SLawrence Mitchell   else *cell = DMLOCATEPOINT_POINT_NOT_FOUND;
4373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43814bbb9f0SLawrence Mitchell }
43914bbb9f0SLawrence Mitchell 
440d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexLocatePoint_Simplex_2D_Internal(DM dm, const PetscScalar point[], PetscInt c, PetscInt *cell)
441d71ae5a4SJacob Faibussowitsch {
442f5ebc837SMatthew G. Knepley   const PetscReal eps   = PETSC_SQRT_MACHINE_EPSILON;
443*1f08e9caSMatthew G. Knepley   PetscReal       xi[2] = {0., 0.};
444*1f08e9caSMatthew G. Knepley   PetscReal       x[3], v0[3], J[9], invJ[9], detJ;
445*1f08e9caSMatthew G. Knepley   PetscInt        embedDim;
446ccd2543fSMatthew G Knepley 
447ccd2543fSMatthew G Knepley   PetscFunctionBegin;
448*1f08e9caSMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &embedDim));
4499566063dSJacob Faibussowitsch   PetscCall(DMPlexComputeCellGeometryFEM(dm, c, NULL, v0, J, invJ, &detJ));
450*1f08e9caSMatthew G. Knepley   for (PetscInt j = 0; j < embedDim; ++j) x[j] = PetscRealPart(point[j]);
451*1f08e9caSMatthew G. Knepley   for (PetscInt i = 0; i < 2; ++i) {
452*1f08e9caSMatthew G. Knepley     for (PetscInt j = 0; j < embedDim; ++j) xi[i] += invJ[i * embedDim + j] * (x[j] - v0[j]);
453*1f08e9caSMatthew G. Knepley   }
454*1f08e9caSMatthew G. Knepley   if ((xi[0] >= -eps) && (xi[1] >= -eps) && (xi[0] + xi[1] <= 2.0 + eps)) *cell = c;
455c1496c66SMatthew G. Knepley   else *cell = DMLOCATEPOINT_POINT_NOT_FOUND;
4563ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
457ccd2543fSMatthew G Knepley }
458ccd2543fSMatthew G Knepley 
459d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexClosestPoint_Simplex_2D_Internal(DM dm, const PetscScalar point[], PetscInt c, PetscReal cpoint[])
460d71ae5a4SJacob Faibussowitsch {
46162a38674SMatthew G. Knepley   const PetscInt embedDim = 2;
46262a38674SMatthew G. Knepley   PetscReal      x        = PetscRealPart(point[0]);
46362a38674SMatthew G. Knepley   PetscReal      y        = PetscRealPart(point[1]);
46462a38674SMatthew G. Knepley   PetscReal      v0[2], J[4], invJ[4], detJ;
46562a38674SMatthew G. Knepley   PetscReal      xi, eta, r;
46662a38674SMatthew G. Knepley 
46762a38674SMatthew G. Knepley   PetscFunctionBegin;
4689566063dSJacob Faibussowitsch   PetscCall(DMPlexComputeCellGeometryFEM(dm, c, NULL, v0, J, invJ, &detJ));
46962a38674SMatthew G. Knepley   xi  = invJ[0 * embedDim + 0] * (x - v0[0]) + invJ[0 * embedDim + 1] * (y - v0[1]);
47062a38674SMatthew G. Knepley   eta = invJ[1 * embedDim + 0] * (x - v0[0]) + invJ[1 * embedDim + 1] * (y - v0[1]);
47162a38674SMatthew G. Knepley 
47262a38674SMatthew G. Knepley   xi  = PetscMax(xi, 0.0);
47362a38674SMatthew G. Knepley   eta = PetscMax(eta, 0.0);
47462a38674SMatthew G. Knepley   if (xi + eta > 2.0) {
47562a38674SMatthew G. Knepley     r = (xi + eta) / 2.0;
47662a38674SMatthew G. Knepley     xi /= r;
47762a38674SMatthew G. Knepley     eta /= r;
47862a38674SMatthew G. Knepley   }
47962a38674SMatthew G. Knepley   cpoint[0] = J[0 * embedDim + 0] * xi + J[0 * embedDim + 1] * eta + v0[0];
48062a38674SMatthew G. Knepley   cpoint[1] = J[1 * embedDim + 0] * xi + J[1 * embedDim + 1] * eta + v0[1];
4813ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
48262a38674SMatthew G. Knepley }
48362a38674SMatthew G. Knepley 
48461451c10SMatthew G. Knepley // This is the ray-casting, or even-odd algorithm: https://en.wikipedia.org/wiki/Even%E2%80%93odd_rule
485dd301514SZach Atkins static PetscErrorCode DMPlexLocatePoint_Quad_2D_Linear_Internal(DM dm, const PetscScalar point[], PetscInt c, PetscInt *cell)
486d71ae5a4SJacob Faibussowitsch {
48776b3799dSMatthew G. Knepley   const PetscScalar *array;
488a1e44745SMatthew G. Knepley   PetscScalar       *coords    = NULL;
489ccd2543fSMatthew G Knepley   const PetscInt     faces[8]  = {0, 1, 1, 2, 2, 3, 3, 0};
490ccd2543fSMatthew G Knepley   PetscReal          x         = PetscRealPart(point[0]);
491ccd2543fSMatthew G Knepley   PetscReal          y         = PetscRealPart(point[1]);
492*1f08e9caSMatthew G. Knepley   PetscInt           crossings = 0, numCoords, embedDim;
49376b3799dSMatthew G. Knepley   PetscBool          isDG;
494ccd2543fSMatthew G Knepley 
495ccd2543fSMatthew G Knepley   PetscFunctionBegin;
49676b3799dSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
497*1f08e9caSMatthew G. Knepley   embedDim = numCoords / 4;
498*1f08e9caSMatthew G. Knepley   PetscCheck(!(numCoords % 4), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Quadrilateral should have 8 coordinates, not %" PetscInt_FMT, numCoords);
499*1f08e9caSMatthew G. Knepley   // Treat linear quads as Monge surfaces, so we just locate on the projection to x-y (could instead project to 2D)
500*1f08e9caSMatthew G. Knepley   for (PetscInt f = 0; f < 4; ++f) {
501*1f08e9caSMatthew G. Knepley     PetscReal x_i = PetscRealPart(coords[faces[2 * f + 0] * embedDim + 0]);
502*1f08e9caSMatthew G. Knepley     PetscReal y_i = PetscRealPart(coords[faces[2 * f + 0] * embedDim + 1]);
503*1f08e9caSMatthew G. Knepley     PetscReal x_j = PetscRealPart(coords[faces[2 * f + 1] * embedDim + 0]);
504*1f08e9caSMatthew G. Knepley     PetscReal y_j = PetscRealPart(coords[faces[2 * f + 1] * embedDim + 1]);
50561451c10SMatthew G. Knepley 
50661451c10SMatthew G. Knepley     if ((x == x_j) && (y == y_j)) {
50761451c10SMatthew G. Knepley       // point is a corner
50861451c10SMatthew G. Knepley       crossings = 1;
50961451c10SMatthew G. Knepley       break;
51061451c10SMatthew G. Knepley     }
51161451c10SMatthew G. Knepley     if ((y_j > y) != (y_i > y)) {
51261451c10SMatthew G. Knepley       PetscReal slope = (x - x_j) * (y_i - y_j) - (x_i - x_j) * (y - y_j);
51361451c10SMatthew G. Knepley       if (slope == 0) {
51461451c10SMatthew G. Knepley         // point is a corner
51561451c10SMatthew G. Knepley         crossings = 1;
51661451c10SMatthew G. Knepley         break;
51761451c10SMatthew G. Knepley       }
51861451c10SMatthew G. Knepley       if ((slope < 0) != (y_i < y_j)) ++crossings;
51961451c10SMatthew G. Knepley     }
520ccd2543fSMatthew G Knepley   }
521ccd2543fSMatthew G Knepley   if (crossings % 2) *cell = c;
522c1496c66SMatthew G. Knepley   else *cell = DMLOCATEPOINT_POINT_NOT_FOUND;
52376b3799dSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
5243ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
525ccd2543fSMatthew G Knepley }
526ccd2543fSMatthew G Knepley 
527dd301514SZach Atkins static PetscErrorCode DMPlexLocatePoint_Quad_2D_Internal(DM dm, const PetscScalar point[], PetscInt c, PetscInt *cell)
528dd301514SZach Atkins {
529dd301514SZach Atkins   DM           cdm;
530dd301514SZach Atkins   PetscInt     degree, dimR, dimC;
531dd301514SZach Atkins   PetscFE      fe;
532dd301514SZach Atkins   PetscClassId id;
533dd301514SZach Atkins   PetscSpace   sp;
5343b963e62SJose E. Roman   PetscReal    pointR[3], ref[3], error;
535dd301514SZach Atkins   Vec          coords;
536dd301514SZach Atkins   PetscBool    found = PETSC_FALSE;
537dd301514SZach Atkins 
538dd301514SZach Atkins   PetscFunctionBegin;
539dd301514SZach Atkins   PetscCall(DMGetDimension(dm, &dimR));
540dd301514SZach Atkins   PetscCall(DMGetCoordinateDM(dm, &cdm));
541dd301514SZach Atkins   PetscCall(DMGetDimension(cdm, &dimC));
542dd301514SZach Atkins   PetscCall(DMGetField(cdm, 0, NULL, (PetscObject *)&fe));
543dd301514SZach Atkins   PetscCall(PetscObjectGetClassId((PetscObject)fe, &id));
544dd301514SZach Atkins   if (id != PETSCFE_CLASSID) degree = 1;
545dd301514SZach Atkins   else {
546dd301514SZach Atkins     PetscCall(PetscFEGetBasisSpace(fe, &sp));
547dd301514SZach Atkins     PetscCall(PetscSpaceGetDegree(sp, &degree, NULL));
548dd301514SZach Atkins   }
549dd301514SZach Atkins   if (degree == 1) {
550dd301514SZach Atkins     /* Use simple location method for linear elements*/
551dd301514SZach Atkins     PetscCall(DMPlexLocatePoint_Quad_2D_Linear_Internal(dm, point, c, cell));
552dd301514SZach Atkins     PetscFunctionReturn(PETSC_SUCCESS);
553dd301514SZach Atkins   }
554dd301514SZach Atkins   /* Otherwise, we have to solve for the real to reference coordinates */
555dd301514SZach Atkins   PetscCall(DMGetCoordinatesLocal(dm, &coords));
556dd301514SZach Atkins   error = PETSC_SQRT_MACHINE_EPSILON;
557af9bd97cSZach Atkins   for (PetscInt d = 0; d < dimC; d++) pointR[d] = PetscRealPart(point[d]);
558af9bd97cSZach Atkins   PetscCall(DMPlexCoordinatesToReference_FE(cdm, fe, c, 1, pointR, ref, coords, dimC, dimR, 10, &error));
559dd301514SZach Atkins   if (error < PETSC_SQRT_MACHINE_EPSILON) found = PETSC_TRUE;
560dd301514SZach Atkins   if ((ref[0] > 1.0 + PETSC_SMALL) || (ref[0] < -1.0 - PETSC_SMALL) || (ref[1] > 1.0 + PETSC_SMALL) || (ref[1] < -1.0 - PETSC_SMALL)) found = PETSC_FALSE;
561dd301514SZach Atkins   if (PetscDefined(USE_DEBUG) && found) {
5623b963e62SJose E. Roman     PetscReal real[3], inverseError = 0, normPoint = DMPlex_NormD_Internal(dimC, pointR);
563dd301514SZach Atkins 
564af9bd97cSZach Atkins     normPoint = normPoint > PETSC_SMALL ? normPoint : 1.0;
565dd301514SZach Atkins     PetscCall(DMPlexReferenceToCoordinates_FE(cdm, fe, c, 1, ref, real, coords, dimC, dimR));
566af9bd97cSZach Atkins     inverseError = DMPlex_DistRealD_Internal(dimC, real, pointR);
567af9bd97cSZach Atkins     if (inverseError > PETSC_SQRT_MACHINE_EPSILON * normPoint) found = PETSC_FALSE;
568af9bd97cSZach Atkins     if (!found) PetscCall(PetscInfo(dm, "Point (%g, %g, %g) != Mapped Ref Coords (%g, %g, %g) with error %g\n", (double)pointR[0], (double)pointR[1], (double)pointR[2], (double)real[0], (double)real[1], (double)real[2], (double)inverseError));
569dd301514SZach Atkins   }
570dd301514SZach Atkins   if (found) *cell = c;
571dd301514SZach Atkins   else *cell = DMLOCATEPOINT_POINT_NOT_FOUND;
572dd301514SZach Atkins   PetscFunctionReturn(PETSC_SUCCESS);
573dd301514SZach Atkins }
574dd301514SZach Atkins 
575d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexLocatePoint_Simplex_3D_Internal(DM dm, const PetscScalar point[], PetscInt c, PetscInt *cell)
576d71ae5a4SJacob Faibussowitsch {
577ccd2543fSMatthew G Knepley   const PetscInt  embedDim = 3;
57837900f7dSMatthew G. Knepley   const PetscReal eps      = PETSC_SQRT_MACHINE_EPSILON;
579ccd2543fSMatthew G Knepley   PetscReal       v0[3], J[9], invJ[9], detJ;
580ccd2543fSMatthew G Knepley   PetscReal       x = PetscRealPart(point[0]);
581ccd2543fSMatthew G Knepley   PetscReal       y = PetscRealPart(point[1]);
582ccd2543fSMatthew G Knepley   PetscReal       z = PetscRealPart(point[2]);
583ccd2543fSMatthew G Knepley   PetscReal       xi, eta, zeta;
584ccd2543fSMatthew G Knepley 
585ccd2543fSMatthew G Knepley   PetscFunctionBegin;
5869566063dSJacob Faibussowitsch   PetscCall(DMPlexComputeCellGeometryFEM(dm, c, NULL, v0, J, invJ, &detJ));
587ccd2543fSMatthew G Knepley   xi   = invJ[0 * embedDim + 0] * (x - v0[0]) + invJ[0 * embedDim + 1] * (y - v0[1]) + invJ[0 * embedDim + 2] * (z - v0[2]);
588ccd2543fSMatthew G Knepley   eta  = invJ[1 * embedDim + 0] * (x - v0[0]) + invJ[1 * embedDim + 1] * (y - v0[1]) + invJ[1 * embedDim + 2] * (z - v0[2]);
589ccd2543fSMatthew G Knepley   zeta = invJ[2 * embedDim + 0] * (x - v0[0]) + invJ[2 * embedDim + 1] * (y - v0[1]) + invJ[2 * embedDim + 2] * (z - v0[2]);
590ccd2543fSMatthew G Knepley 
59137900f7dSMatthew G. Knepley   if ((xi >= -eps) && (eta >= -eps) && (zeta >= -eps) && (xi + eta + zeta <= 2.0 + eps)) *cell = c;
592c1496c66SMatthew G. Knepley   else *cell = DMLOCATEPOINT_POINT_NOT_FOUND;
5933ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
594ccd2543fSMatthew G Knepley }
595ccd2543fSMatthew G Knepley 
596dd301514SZach Atkins static PetscErrorCode DMPlexLocatePoint_Hex_3D_Linear_Internal(DM dm, const PetscScalar point[], PetscInt c, PetscInt *cell)
597d71ae5a4SJacob Faibussowitsch {
59876b3799dSMatthew G. Knepley   const PetscScalar *array;
599872a9804SMatthew G. Knepley   PetscScalar       *coords    = NULL;
6009371c9d4SSatish Balay   const PetscInt     faces[24] = {0, 3, 2, 1, 5, 4, 7, 6, 3, 0, 4, 5, 1, 2, 6, 7, 3, 5, 6, 2, 0, 1, 7, 4};
601ccd2543fSMatthew G Knepley   PetscBool          found     = PETSC_TRUE;
60276b3799dSMatthew G. Knepley   PetscInt           numCoords, f;
60376b3799dSMatthew G. Knepley   PetscBool          isDG;
604ccd2543fSMatthew G Knepley 
605ccd2543fSMatthew G Knepley   PetscFunctionBegin;
60676b3799dSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
60776b3799dSMatthew G. Knepley   PetscCheck(numCoords == 24, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Quadrilateral should have 8 coordinates, not %" PetscInt_FMT, numCoords);
608ccd2543fSMatthew G Knepley   for (f = 0; f < 6; ++f) {
609ccd2543fSMatthew G Knepley     /* Check the point is under plane */
610ccd2543fSMatthew G Knepley     /*   Get face normal */
611ccd2543fSMatthew G Knepley     PetscReal v_i[3];
612ccd2543fSMatthew G Knepley     PetscReal v_j[3];
613ccd2543fSMatthew G Knepley     PetscReal normal[3];
614ccd2543fSMatthew G Knepley     PetscReal pp[3];
615ccd2543fSMatthew G Knepley     PetscReal dot;
616ccd2543fSMatthew G Knepley 
617ccd2543fSMatthew G Knepley     v_i[0]    = PetscRealPart(coords[faces[f * 4 + 3] * 3 + 0] - coords[faces[f * 4 + 0] * 3 + 0]);
618ccd2543fSMatthew G Knepley     v_i[1]    = PetscRealPart(coords[faces[f * 4 + 3] * 3 + 1] - coords[faces[f * 4 + 0] * 3 + 1]);
619ccd2543fSMatthew G Knepley     v_i[2]    = PetscRealPart(coords[faces[f * 4 + 3] * 3 + 2] - coords[faces[f * 4 + 0] * 3 + 2]);
620ccd2543fSMatthew G Knepley     v_j[0]    = PetscRealPart(coords[faces[f * 4 + 1] * 3 + 0] - coords[faces[f * 4 + 0] * 3 + 0]);
621ccd2543fSMatthew G Knepley     v_j[1]    = PetscRealPart(coords[faces[f * 4 + 1] * 3 + 1] - coords[faces[f * 4 + 0] * 3 + 1]);
622ccd2543fSMatthew G Knepley     v_j[2]    = PetscRealPart(coords[faces[f * 4 + 1] * 3 + 2] - coords[faces[f * 4 + 0] * 3 + 2]);
623ccd2543fSMatthew G Knepley     normal[0] = v_i[1] * v_j[2] - v_i[2] * v_j[1];
624ccd2543fSMatthew G Knepley     normal[1] = v_i[2] * v_j[0] - v_i[0] * v_j[2];
625ccd2543fSMatthew G Knepley     normal[2] = v_i[0] * v_j[1] - v_i[1] * v_j[0];
626ccd2543fSMatthew G Knepley     pp[0]     = PetscRealPart(coords[faces[f * 4 + 0] * 3 + 0] - point[0]);
627ccd2543fSMatthew G Knepley     pp[1]     = PetscRealPart(coords[faces[f * 4 + 0] * 3 + 1] - point[1]);
628ccd2543fSMatthew G Knepley     pp[2]     = PetscRealPart(coords[faces[f * 4 + 0] * 3 + 2] - point[2]);
629ccd2543fSMatthew G Knepley     dot       = normal[0] * pp[0] + normal[1] * pp[1] + normal[2] * pp[2];
630ccd2543fSMatthew G Knepley 
631ccd2543fSMatthew G Knepley     /* Check that projected point is in face (2D location problem) */
632ccd2543fSMatthew G Knepley     if (dot < 0.0) {
633ccd2543fSMatthew G Knepley       found = PETSC_FALSE;
634ccd2543fSMatthew G Knepley       break;
635ccd2543fSMatthew G Knepley     }
636ccd2543fSMatthew G Knepley   }
637ccd2543fSMatthew G Knepley   if (found) *cell = c;
638c1496c66SMatthew G. Knepley   else *cell = DMLOCATEPOINT_POINT_NOT_FOUND;
63976b3799dSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
6403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
641ccd2543fSMatthew G Knepley }
642ccd2543fSMatthew G Knepley 
643dd301514SZach Atkins static PetscErrorCode DMPlexLocatePoint_Hex_3D_Internal(DM dm, const PetscScalar point[], PetscInt c, PetscInt *cell)
644dd301514SZach Atkins {
645dd301514SZach Atkins   DM           cdm;
646dd301514SZach Atkins   PetscInt     degree, dimR, dimC;
647dd301514SZach Atkins   PetscFE      fe;
648dd301514SZach Atkins   PetscClassId id;
649dd301514SZach Atkins   PetscSpace   sp;
650af9bd97cSZach Atkins   PetscReal    pointR[3], ref[3], error;
651dd301514SZach Atkins   Vec          coords;
652dd301514SZach Atkins   PetscBool    found = PETSC_FALSE;
653dd301514SZach Atkins 
654dd301514SZach Atkins   PetscFunctionBegin;
655dd301514SZach Atkins   PetscCall(DMGetDimension(dm, &dimR));
656dd301514SZach Atkins   PetscCall(DMGetCoordinateDM(dm, &cdm));
657dd301514SZach Atkins   PetscCall(DMGetDimension(cdm, &dimC));
658dd301514SZach Atkins   PetscCall(DMGetField(cdm, 0, NULL, (PetscObject *)&fe));
659dd301514SZach Atkins   PetscCall(PetscObjectGetClassId((PetscObject)fe, &id));
660dd301514SZach Atkins   if (id != PETSCFE_CLASSID) degree = 1;
661dd301514SZach Atkins   else {
662dd301514SZach Atkins     PetscCall(PetscFEGetBasisSpace(fe, &sp));
663dd301514SZach Atkins     PetscCall(PetscSpaceGetDegree(sp, &degree, NULL));
664dd301514SZach Atkins   }
665dd301514SZach Atkins   if (degree == 1) {
666dd301514SZach Atkins     /* Use simple location method for linear elements*/
667dd301514SZach Atkins     PetscCall(DMPlexLocatePoint_Hex_3D_Linear_Internal(dm, point, c, cell));
668dd301514SZach Atkins     PetscFunctionReturn(PETSC_SUCCESS);
669dd301514SZach Atkins   }
670dd301514SZach Atkins   /* Otherwise, we have to solve for the real to reference coordinates */
671dd301514SZach Atkins   PetscCall(DMGetCoordinatesLocal(dm, &coords));
672dd301514SZach Atkins   error = PETSC_SQRT_MACHINE_EPSILON;
673af9bd97cSZach Atkins   for (PetscInt d = 0; d < dimC; d++) pointR[d] = PetscRealPart(point[d]);
674af9bd97cSZach Atkins   PetscCall(DMPlexCoordinatesToReference_FE(cdm, fe, c, 1, pointR, ref, coords, dimC, dimR, 10, &error));
675dd301514SZach Atkins   if (error < PETSC_SQRT_MACHINE_EPSILON) found = PETSC_TRUE;
676dd301514SZach Atkins   if ((ref[0] > 1.0 + PETSC_SMALL) || (ref[0] < -1.0 - PETSC_SMALL) || (ref[1] > 1.0 + PETSC_SMALL) || (ref[1] < -1.0 - PETSC_SMALL) || (ref[2] > 1.0 + PETSC_SMALL) || (ref[2] < -1.0 - PETSC_SMALL)) found = PETSC_FALSE;
677dd301514SZach Atkins   if (PetscDefined(USE_DEBUG) && found) {
678af9bd97cSZach Atkins     PetscReal real[3], inverseError = 0, normPoint = DMPlex_NormD_Internal(dimC, pointR);
679dd301514SZach Atkins 
680af9bd97cSZach Atkins     normPoint = normPoint > PETSC_SMALL ? normPoint : 1.0;
681dd301514SZach Atkins     PetscCall(DMPlexReferenceToCoordinates_FE(cdm, fe, c, 1, ref, real, coords, dimC, dimR));
682af9bd97cSZach Atkins     inverseError = DMPlex_DistRealD_Internal(dimC, real, pointR);
683af9bd97cSZach Atkins     if (inverseError > PETSC_SQRT_MACHINE_EPSILON * normPoint) found = PETSC_FALSE;
684af9bd97cSZach Atkins     if (!found) PetscCall(PetscInfo(dm, "Point (%g, %g, %g) != Mapped Ref Coords (%g, %g, %g) with error %g\n", (double)pointR[0], (double)pointR[1], (double)pointR[2], (double)real[0], (double)real[1], (double)real[2], (double)inverseError));
685dd301514SZach Atkins   }
686dd301514SZach Atkins   if (found) *cell = c;
687dd301514SZach Atkins   else *cell = DMLOCATEPOINT_POINT_NOT_FOUND;
688dd301514SZach Atkins   PetscFunctionReturn(PETSC_SUCCESS);
689dd301514SZach Atkins }
690dd301514SZach Atkins 
691d71ae5a4SJacob Faibussowitsch static PetscErrorCode PetscGridHashInitialize_Internal(PetscGridHash box, PetscInt dim, const PetscScalar point[])
692d71ae5a4SJacob Faibussowitsch {
693c4eade1cSMatthew G. Knepley   PetscInt d;
694c4eade1cSMatthew G. Knepley 
695c4eade1cSMatthew G. Knepley   PetscFunctionBegin;
696c4eade1cSMatthew G. Knepley   box->dim = dim;
697378076f8SMatthew G. Knepley   for (d = 0; d < dim; ++d) box->lower[d] = box->upper[d] = point ? PetscRealPart(point[d]) : 0.;
6983ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
699c4eade1cSMatthew G. Knepley }
700c4eade1cSMatthew G. Knepley 
701d71ae5a4SJacob Faibussowitsch PetscErrorCode PetscGridHashCreate(MPI_Comm comm, PetscInt dim, const PetscScalar point[], PetscGridHash *box)
702d71ae5a4SJacob Faibussowitsch {
703c4eade1cSMatthew G. Knepley   PetscFunctionBegin;
7042b6f951bSStefano Zampini   PetscCall(PetscCalloc1(1, box));
7059566063dSJacob Faibussowitsch   PetscCall(PetscGridHashInitialize_Internal(*box, dim, point));
7063ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
707c4eade1cSMatthew G. Knepley }
708c4eade1cSMatthew G. Knepley 
709d71ae5a4SJacob Faibussowitsch PetscErrorCode PetscGridHashEnlarge(PetscGridHash box, const PetscScalar point[])
710d71ae5a4SJacob Faibussowitsch {
711c4eade1cSMatthew G. Knepley   PetscInt d;
712c4eade1cSMatthew G. Knepley 
713c4eade1cSMatthew G. Knepley   PetscFunctionBegin;
714c4eade1cSMatthew G. Knepley   for (d = 0; d < box->dim; ++d) {
715c4eade1cSMatthew G. Knepley     box->lower[d] = PetscMin(box->lower[d], PetscRealPart(point[d]));
716c4eade1cSMatthew G. Knepley     box->upper[d] = PetscMax(box->upper[d], PetscRealPart(point[d]));
717c4eade1cSMatthew G. Knepley   }
7183ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
719c4eade1cSMatthew G. Knepley }
720c4eade1cSMatthew G. Knepley 
7216363a54bSMatthew G. Knepley static PetscErrorCode DMPlexCreateGridHash(DM dm, PetscGridHash *box)
7226363a54bSMatthew G. Knepley {
7236363a54bSMatthew G. Knepley   Vec                coordinates;
724b48d1484SMatthew G. Knepley   const PetscScalar *a;
725b48d1484SMatthew G. Knepley   PetscInt           cdim, cStart, cEnd;
7266363a54bSMatthew G. Knepley 
7276363a54bSMatthew G. Knepley   PetscFunctionBegin;
7286363a54bSMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &cdim));
729b48d1484SMatthew G. Knepley   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
7306363a54bSMatthew G. Knepley   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
7316363a54bSMatthew G. Knepley 
732b48d1484SMatthew G. Knepley   PetscCall(VecGetArrayRead(coordinates, &a));
733b48d1484SMatthew G. Knepley   PetscCall(PetscGridHashCreate(PetscObjectComm((PetscObject)dm), cdim, a, box));
734b48d1484SMatthew G. Knepley   PetscCall(VecRestoreArrayRead(coordinates, &a));
735b48d1484SMatthew G. Knepley   for (PetscInt c = cStart; c < cEnd; ++c) {
736b48d1484SMatthew G. Knepley     const PetscScalar *array;
737b48d1484SMatthew G. Knepley     PetscScalar       *coords = NULL;
738b48d1484SMatthew G. Knepley     PetscInt           numCoords;
739b48d1484SMatthew G. Knepley     PetscBool          isDG;
7406363a54bSMatthew G. Knepley 
741b48d1484SMatthew G. Knepley     PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
742b48d1484SMatthew G. Knepley     for (PetscInt i = 0; i < numCoords / cdim; ++i) PetscCall(PetscGridHashEnlarge(*box, &coords[i * cdim]));
743b48d1484SMatthew G. Knepley     PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
744b48d1484SMatthew G. Knepley   }
7456363a54bSMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
7466363a54bSMatthew G. Knepley }
7476363a54bSMatthew G. Knepley 
748a4e35b19SJacob Faibussowitsch /*@C
74962a38674SMatthew G. Knepley   PetscGridHashSetGrid - Divide the grid into boxes
75062a38674SMatthew G. Knepley 
75120f4b53cSBarry Smith   Not Collective
75262a38674SMatthew G. Knepley 
75362a38674SMatthew G. Knepley   Input Parameters:
75462a38674SMatthew G. Knepley + box - The grid hash object
755a3b724e8SBarry Smith . n   - The number of boxes in each dimension, may use `PETSC_DETERMINE` for the entries
756a3b724e8SBarry Smith - h   - The box size in each dimension, only used if n[d] == `PETSC_DETERMINE`, if not needed you can pass in `NULL`
75762a38674SMatthew G. Knepley 
75862a38674SMatthew G. Knepley   Level: developer
75962a38674SMatthew G. Knepley 
7602fe279fdSBarry Smith .seealso: `DMPLEX`, `PetscGridHashCreate()`
761a4e35b19SJacob Faibussowitsch @*/
762d71ae5a4SJacob Faibussowitsch PetscErrorCode PetscGridHashSetGrid(PetscGridHash box, const PetscInt n[], const PetscReal h[])
763d71ae5a4SJacob Faibussowitsch {
764c4eade1cSMatthew G. Knepley   PetscInt d;
765c4eade1cSMatthew G. Knepley 
766c4eade1cSMatthew G. Knepley   PetscFunctionBegin;
7674f572ea9SToby Isaac   PetscAssertPointer(n, 2);
7684f572ea9SToby Isaac   if (h) PetscAssertPointer(h, 3);
769c4eade1cSMatthew G. Knepley   for (d = 0; d < box->dim; ++d) {
770c4eade1cSMatthew G. Knepley     box->extent[d] = box->upper[d] - box->lower[d];
771c4eade1cSMatthew G. Knepley     if (n[d] == PETSC_DETERMINE) {
77223f0ada9SStefano Zampini       PetscCheck(h, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Missing h");
773c4eade1cSMatthew G. Knepley       box->h[d] = h[d];
774c4eade1cSMatthew G. Knepley       box->n[d] = PetscCeilReal(box->extent[d] / h[d]);
775c4eade1cSMatthew G. Knepley     } else {
776c4eade1cSMatthew G. Knepley       box->n[d] = n[d];
777c4eade1cSMatthew G. Knepley       box->h[d] = box->extent[d] / n[d];
778c4eade1cSMatthew G. Knepley     }
779c4eade1cSMatthew G. Knepley   }
7803ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
781c4eade1cSMatthew G. Knepley }
782c4eade1cSMatthew G. Knepley 
783a4e35b19SJacob Faibussowitsch /*@C
78462a38674SMatthew G. Knepley   PetscGridHashGetEnclosingBox - Find the grid boxes containing each input point
78562a38674SMatthew G. Knepley 
78620f4b53cSBarry Smith   Not Collective
78762a38674SMatthew G. Knepley 
78862a38674SMatthew G. Knepley   Input Parameters:
78962a38674SMatthew G. Knepley + box       - The grid hash object
79062a38674SMatthew G. Knepley . numPoints - The number of input points
79162a38674SMatthew G. Knepley - points    - The input point coordinates
79262a38674SMatthew G. Knepley 
79362a38674SMatthew G. Knepley   Output Parameters:
794a3b724e8SBarry Smith + dboxes - An array of `numPoints` x `dim` integers expressing the enclosing box as (i_0, i_1, ..., i_dim)
795a3b724e8SBarry Smith - boxes  - An array of `numPoints` integers expressing the enclosing box as single number, or `NULL`
79662a38674SMatthew G. Knepley 
79762a38674SMatthew G. Knepley   Level: developer
79862a38674SMatthew G. Knepley 
799f5867de0SMatthew G. Knepley   Note:
800f5867de0SMatthew G. Knepley   This only guarantees that a box contains a point, not that a cell does.
801f5867de0SMatthew G. Knepley 
8022fe279fdSBarry Smith .seealso: `DMPLEX`, `PetscGridHashCreate()`
803a4e35b19SJacob Faibussowitsch @*/
804d71ae5a4SJacob Faibussowitsch PetscErrorCode PetscGridHashGetEnclosingBox(PetscGridHash box, PetscInt numPoints, const PetscScalar points[], PetscInt dboxes[], PetscInt boxes[])
805d71ae5a4SJacob Faibussowitsch {
806c4eade1cSMatthew G. Knepley   const PetscReal *lower = box->lower;
807c4eade1cSMatthew G. Knepley   const PetscReal *upper = box->upper;
808c4eade1cSMatthew G. Knepley   const PetscReal *h     = box->h;
809c4eade1cSMatthew G. Knepley   const PetscInt  *n     = box->n;
810c4eade1cSMatthew G. Knepley   const PetscInt   dim   = box->dim;
811c4eade1cSMatthew G. Knepley   PetscInt         d, p;
812c4eade1cSMatthew G. Knepley 
813c4eade1cSMatthew G. Knepley   PetscFunctionBegin;
814c4eade1cSMatthew G. Knepley   for (p = 0; p < numPoints; ++p) {
815c4eade1cSMatthew G. Knepley     for (d = 0; d < dim; ++d) {
8161c6dfc3eSMatthew G. Knepley       PetscInt dbox = PetscFloorReal((PetscRealPart(points[p * dim + d]) - lower[d]) / h[d]);
817c4eade1cSMatthew G. Knepley 
8181c6dfc3eSMatthew G. Knepley       if (dbox == n[d] && PetscAbsReal(PetscRealPart(points[p * dim + d]) - upper[d]) < 1.0e-9) dbox = n[d] - 1;
8192a705cacSMatthew G. Knepley       if (dbox == -1 && PetscAbsReal(PetscRealPart(points[p * dim + d]) - lower[d]) < 1.0e-9) dbox = 0;
820b48d1484SMatthew G. Knepley       PetscCheck(dbox >= 0 && dbox < n[d], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Input point %" PetscInt_FMT " (%g, %g, %g) is outside of our bounding box (%g, %g, %g) - (%g, %g, %g)", p, (double)PetscRealPart(points[p * dim + 0]), dim > 1 ? (double)PetscRealPart(points[p * dim + 1]) : 0.0, dim > 2 ? (double)PetscRealPart(points[p * dim + 2]) : 0.0, (double)lower[0], (double)lower[1], (double)lower[2], (double)upper[0], (double)upper[1], (double)upper[2]);
821c4eade1cSMatthew G. Knepley       dboxes[p * dim + d] = dbox;
822c4eade1cSMatthew G. Knepley     }
8239371c9d4SSatish Balay     if (boxes)
8249371c9d4SSatish Balay       for (d = dim - 2, boxes[p] = dboxes[p * dim + dim - 1]; d >= 0; --d) boxes[p] = boxes[p] * n[d] + dboxes[p * dim + d];
825c4eade1cSMatthew G. Knepley   }
8263ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
827c4eade1cSMatthew G. Knepley }
828c4eade1cSMatthew G. Knepley 
829af74b616SDave May /*
830af74b616SDave May   PetscGridHashGetEnclosingBoxQuery - Find the grid boxes containing each input point
831af74b616SDave May 
83220f4b53cSBarry Smith   Not Collective
833af74b616SDave May 
834af74b616SDave May   Input Parameters:
835af74b616SDave May + box         - The grid hash object
836f5867de0SMatthew G. Knepley . cellSection - The PetscSection mapping cells to boxes
837af74b616SDave May . numPoints   - The number of input points
838af74b616SDave May - points      - The input point coordinates
839af74b616SDave May 
840af74b616SDave May   Output Parameters:
84120f4b53cSBarry Smith + dboxes - An array of `numPoints`*`dim` integers expressing the enclosing box as (i_0, i_1, ..., i_dim)
84220f4b53cSBarry Smith . boxes  - An array of `numPoints` integers expressing the enclosing box as single number, or `NULL`
843af74b616SDave May - found  - Flag indicating if point was located within a box
844af74b616SDave May 
845af74b616SDave May   Level: developer
846af74b616SDave May 
847f5867de0SMatthew G. Knepley   Note:
84820f4b53cSBarry Smith   This does an additional check that a cell actually contains the point, and found is `PETSC_FALSE` if no cell does. Thus, this function requires that `cellSection` is already constructed.
849f5867de0SMatthew G. Knepley 
8502fe279fdSBarry Smith .seealso: `DMPLEX`, `PetscGridHashGetEnclosingBox()`
851af74b616SDave May */
852a4e35b19SJacob Faibussowitsch static PetscErrorCode PetscGridHashGetEnclosingBoxQuery(PetscGridHash box, PetscSection cellSection, PetscInt numPoints, const PetscScalar points[], PetscInt dboxes[], PetscInt boxes[], PetscBool *found)
853d71ae5a4SJacob Faibussowitsch {
854af74b616SDave May   const PetscReal *lower = box->lower;
855af74b616SDave May   const PetscReal *upper = box->upper;
856af74b616SDave May   const PetscReal *h     = box->h;
857af74b616SDave May   const PetscInt  *n     = box->n;
858af74b616SDave May   const PetscInt   dim   = box->dim;
859f5867de0SMatthew G. Knepley   PetscInt         bStart, bEnd, d, p;
860af74b616SDave May 
861af74b616SDave May   PetscFunctionBegin;
862f5867de0SMatthew G. Knepley   PetscValidHeaderSpecific(cellSection, PETSC_SECTION_CLASSID, 2);
863af74b616SDave May   *found = PETSC_FALSE;
864f5867de0SMatthew G. Knepley   PetscCall(PetscSectionGetChart(box->cellSection, &bStart, &bEnd));
865af74b616SDave May   for (p = 0; p < numPoints; ++p) {
866af74b616SDave May     for (d = 0; d < dim; ++d) {
867af74b616SDave May       PetscInt dbox = PetscFloorReal((PetscRealPart(points[p * dim + d]) - lower[d]) / h[d]);
868af74b616SDave May 
869af74b616SDave May       if (dbox == n[d] && PetscAbsReal(PetscRealPart(points[p * dim + d]) - upper[d]) < 1.0e-9) dbox = n[d] - 1;
8703ba16761SJacob Faibussowitsch       if (dbox < 0 || dbox >= n[d]) PetscFunctionReturn(PETSC_SUCCESS);
871af74b616SDave May       dboxes[p * dim + d] = dbox;
872af74b616SDave May     }
8739371c9d4SSatish Balay     if (boxes)
8749371c9d4SSatish Balay       for (d = dim - 2, boxes[p] = dboxes[p * dim + dim - 1]; d >= 0; --d) boxes[p] = boxes[p] * n[d] + dboxes[p * dim + d];
875f5867de0SMatthew G. Knepley     // It is possible for a box to overlap no grid cells
8763ba16761SJacob Faibussowitsch     if (boxes[p] < bStart || boxes[p] >= bEnd) PetscFunctionReturn(PETSC_SUCCESS);
877af74b616SDave May   }
878af74b616SDave May   *found = PETSC_TRUE;
8793ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
880af74b616SDave May }
881af74b616SDave May 
882d71ae5a4SJacob Faibussowitsch PetscErrorCode PetscGridHashDestroy(PetscGridHash *box)
883d71ae5a4SJacob Faibussowitsch {
884c4eade1cSMatthew G. Knepley   PetscFunctionBegin;
885c4eade1cSMatthew G. Knepley   if (*box) {
8869566063dSJacob Faibussowitsch     PetscCall(PetscSectionDestroy(&(*box)->cellSection));
8879566063dSJacob Faibussowitsch     PetscCall(ISDestroy(&(*box)->cells));
8889566063dSJacob Faibussowitsch     PetscCall(DMLabelDestroy(&(*box)->cellsSparse));
889c4eade1cSMatthew G. Knepley   }
8909566063dSJacob Faibussowitsch   PetscCall(PetscFree(*box));
8913ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
892c4eade1cSMatthew G. Knepley }
893c4eade1cSMatthew G. Knepley 
894d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexLocatePoint_Internal(DM dm, PetscInt dim, const PetscScalar point[], PetscInt cellStart, PetscInt *cell)
895d71ae5a4SJacob Faibussowitsch {
896ba2698f1SMatthew G. Knepley   DMPolytopeType ct;
897cafe43deSMatthew G. Knepley 
898cafe43deSMatthew G. Knepley   PetscFunctionBegin;
8999566063dSJacob Faibussowitsch   PetscCall(DMPlexGetCellType(dm, cellStart, &ct));
900ba2698f1SMatthew G. Knepley   switch (ct) {
901d71ae5a4SJacob Faibussowitsch   case DM_POLYTOPE_SEGMENT:
902d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexLocatePoint_Simplex_1D_Internal(dm, point, cellStart, cell));
903d71ae5a4SJacob Faibussowitsch     break;
904d71ae5a4SJacob Faibussowitsch   case DM_POLYTOPE_TRIANGLE:
905d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexLocatePoint_Simplex_2D_Internal(dm, point, cellStart, cell));
906d71ae5a4SJacob Faibussowitsch     break;
907d71ae5a4SJacob Faibussowitsch   case DM_POLYTOPE_QUADRILATERAL:
908d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexLocatePoint_Quad_2D_Internal(dm, point, cellStart, cell));
909d71ae5a4SJacob Faibussowitsch     break;
910d71ae5a4SJacob Faibussowitsch   case DM_POLYTOPE_TETRAHEDRON:
911d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexLocatePoint_Simplex_3D_Internal(dm, point, cellStart, cell));
912d71ae5a4SJacob Faibussowitsch     break;
913d71ae5a4SJacob Faibussowitsch   case DM_POLYTOPE_HEXAHEDRON:
914dd301514SZach Atkins     PetscCall(DMPlexLocatePoint_Hex_3D_Internal(dm, point, cellStart, cell));
915d71ae5a4SJacob Faibussowitsch     break;
916d71ae5a4SJacob Faibussowitsch   default:
917d71ae5a4SJacob Faibussowitsch     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "No point location for cell %" PetscInt_FMT " with type %s", cellStart, DMPolytopeTypes[ct]);
918cafe43deSMatthew G. Knepley   }
9193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
920cafe43deSMatthew G. Knepley }
921cafe43deSMatthew G. Knepley 
92262a38674SMatthew G. Knepley /*
92362a38674SMatthew G. Knepley   DMPlexClosestPoint_Internal - Returns the closest point in the cell to the given point
92462a38674SMatthew G. Knepley */
925a4e35b19SJacob Faibussowitsch static PetscErrorCode DMPlexClosestPoint_Internal(DM dm, PetscInt dim, const PetscScalar point[], PetscInt cell, PetscReal cpoint[])
926d71ae5a4SJacob Faibussowitsch {
927ba2698f1SMatthew G. Knepley   DMPolytopeType ct;
92862a38674SMatthew G. Knepley 
92962a38674SMatthew G. Knepley   PetscFunctionBegin;
9309566063dSJacob Faibussowitsch   PetscCall(DMPlexGetCellType(dm, cell, &ct));
931ba2698f1SMatthew G. Knepley   switch (ct) {
932d71ae5a4SJacob Faibussowitsch   case DM_POLYTOPE_TRIANGLE:
933d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexClosestPoint_Simplex_2D_Internal(dm, point, cell, cpoint));
934d71ae5a4SJacob Faibussowitsch     break;
93562a38674SMatthew G. Knepley #if 0
936ba2698f1SMatthew G. Knepley     case DM_POLYTOPE_QUADRILATERAL:
9379566063dSJacob Faibussowitsch     PetscCall(DMPlexClosestPoint_General_2D_Internal(dm, point, cell, cpoint));break;
938ba2698f1SMatthew G. Knepley     case DM_POLYTOPE_TETRAHEDRON:
9399566063dSJacob Faibussowitsch     PetscCall(DMPlexClosestPoint_Simplex_3D_Internal(dm, point, cell, cpoint));break;
940ba2698f1SMatthew G. Knepley     case DM_POLYTOPE_HEXAHEDRON:
9419566063dSJacob Faibussowitsch     PetscCall(DMPlexClosestPoint_General_3D_Internal(dm, point, cell, cpoint));break;
94262a38674SMatthew G. Knepley #endif
943d71ae5a4SJacob Faibussowitsch   default:
944d71ae5a4SJacob Faibussowitsch     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "No closest point location for cell %" PetscInt_FMT " with type %s", cell, DMPolytopeTypes[ct]);
94562a38674SMatthew G. Knepley   }
9463ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
94762a38674SMatthew G. Knepley }
94862a38674SMatthew G. Knepley 
94962a38674SMatthew G. Knepley /*
95020f4b53cSBarry Smith   DMPlexComputeGridHash_Internal - Create a grid hash structure covering the `DMPLEX`
95162a38674SMatthew G. Knepley 
95220f4b53cSBarry Smith   Collective
95362a38674SMatthew G. Knepley 
95462a38674SMatthew G. Knepley   Input Parameter:
95520f4b53cSBarry Smith . dm - The `DMPLEX`
95662a38674SMatthew G. Knepley 
95762a38674SMatthew G. Knepley   Output Parameter:
95862a38674SMatthew G. Knepley . localBox - The grid hash object
95962a38674SMatthew G. Knepley 
96062a38674SMatthew G. Knepley   Level: developer
96162a38674SMatthew G. Knepley 
9626363a54bSMatthew G. Knepley   Notes:
9636363a54bSMatthew G. Knepley   How do we determine all boxes intersecting a given cell?
9646363a54bSMatthew G. Knepley 
9656363a54bSMatthew G. Knepley   1) Get convex body enclosing cell. We will use a box called the box-hull.
9666363a54bSMatthew G. Knepley 
9676363a54bSMatthew G. Knepley   2) Get smallest brick of boxes enclosing the box-hull
9686363a54bSMatthew G. Knepley 
9696363a54bSMatthew G. Knepley   3) Each box is composed of 6 planes, 3 lower and 3 upper. We loop over dimensions, and
9706363a54bSMatthew G. Knepley      for each new plane determine whether the cell is on the negative side, positive side, or intersects it.
9716363a54bSMatthew G. Knepley 
9726363a54bSMatthew G. Knepley      a) If the cell is on the negative side of the lower planes, it is not in the box
9736363a54bSMatthew G. Knepley 
9746363a54bSMatthew G. Knepley      b) If the cell is on the positive side of the upper planes, it is not in the box
9756363a54bSMatthew G. Knepley 
9766363a54bSMatthew G. Knepley      c) If there is no intersection, it is in the box
9776363a54bSMatthew G. Knepley 
9786363a54bSMatthew G. Knepley      d) If any intersection point is within the box limits, it is in the box
9796363a54bSMatthew G. Knepley 
98020f4b53cSBarry Smith .seealso: `DMPLEX`, `PetscGridHashCreate()`, `PetscGridHashGetEnclosingBox()`
98162a38674SMatthew G. Knepley */
98266976f2fSJacob Faibussowitsch static PetscErrorCode DMPlexComputeGridHash_Internal(DM dm, PetscGridHash *localBox)
983d71ae5a4SJacob Faibussowitsch {
984f5867de0SMatthew G. Knepley   PetscInt        debug = ((DM_Plex *)dm->data)->printLocate;
985cafe43deSMatthew G. Knepley   PetscGridHash   lbox;
98696217254SMatthew G. Knepley   PetscSF         sf;
98796217254SMatthew G. Knepley   const PetscInt *leaves;
9886363a54bSMatthew G. Knepley   PetscInt       *dboxes, *boxes;
9896363a54bSMatthew G. Knepley   PetscInt        cdim, cStart, cEnd, Nl = -1;
990ddce0771SMatthew G. Knepley   PetscBool       flg;
991cafe43deSMatthew G. Knepley 
992cafe43deSMatthew G. Knepley   PetscFunctionBegin;
9936363a54bSMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &cdim));
9949566063dSJacob Faibussowitsch   PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
9956363a54bSMatthew G. Knepley   PetscCall(DMPlexCreateGridHash(dm, &lbox));
9966363a54bSMatthew G. Knepley   {
9976363a54bSMatthew G. Knepley     PetscInt n[3], d;
9986363a54bSMatthew G. Knepley 
9996363a54bSMatthew G. Knepley     PetscCall(PetscOptionsGetIntArray(NULL, ((PetscObject)dm)->prefix, "-dm_plex_hash_box_faces", n, &d, &flg));
10009371c9d4SSatish Balay     if (flg) {
10016363a54bSMatthew G. Knepley       for (PetscInt i = d; i < cdim; ++i) n[i] = n[d - 1];
10029371c9d4SSatish Balay     } else {
10036363a54bSMatthew G. Knepley       for (PetscInt i = 0; i < cdim; ++i) n[i] = PetscMax(2, PetscFloorReal(PetscPowReal((PetscReal)(cEnd - cStart), 1.0 / cdim) * 0.8));
10049371c9d4SSatish Balay     }
10059566063dSJacob Faibussowitsch     PetscCall(PetscGridHashSetGrid(lbox, n, NULL));
10069371c9d4SSatish Balay     if (debug)
10076363a54bSMatthew G. Knepley       PetscCall(PetscPrintf(PETSC_COMM_SELF, "GridHash:\n  (%g, %g, %g) -- (%g, %g, %g)\n  n %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT "\n  h %g %g %g\n", (double)lbox->lower[0], (double)lbox->lower[1], cdim > 2 ? (double)lbox->lower[2] : 0.,
10086363a54bSMatthew G. Knepley                             (double)lbox->upper[0], (double)lbox->upper[1], cdim > 2 ? (double)lbox->upper[2] : 0, n[0], n[1], cdim > 2 ? n[2] : 0, (double)lbox->h[0], (double)lbox->h[1], cdim > 2 ? (double)lbox->h[2] : 0.));
10096363a54bSMatthew G. Knepley   }
10106363a54bSMatthew G. Knepley 
101196217254SMatthew G. Knepley   PetscCall(DMGetPointSF(dm, &sf));
101296217254SMatthew G. Knepley   if (sf) PetscCall(PetscSFGetGraph(sf, NULL, &Nl, &leaves, NULL));
101396217254SMatthew G. Knepley   Nl = PetscMax(Nl, 0);
10146363a54bSMatthew G. Knepley   PetscCall(PetscCalloc2(16 * cdim, &dboxes, 16, &boxes));
10156363a54bSMatthew G. Knepley 
10166363a54bSMatthew G. Knepley   PetscCall(DMLabelCreate(PETSC_COMM_SELF, "cells", &lbox->cellsSparse));
10176363a54bSMatthew G. Knepley   PetscCall(DMLabelCreateIndex(lbox->cellsSparse, cStart, cEnd));
10186363a54bSMatthew G. Knepley   for (PetscInt c = cStart; c < cEnd; ++c) {
10196363a54bSMatthew G. Knepley     PetscReal          intPoints[6 * 6 * 6 * 3];
10206363a54bSMatthew G. Knepley     const PetscScalar *array;
10216363a54bSMatthew G. Knepley     PetscScalar       *coords            = NULL;
1022cafe43deSMatthew G. Knepley     const PetscReal   *h                 = lbox->h;
10236363a54bSMatthew G. Knepley     PetscReal          normal[9]         = {1., 0., 0., 0., 1., 0., 0., 0., 1.};
10246363a54bSMatthew G. Knepley     PetscReal         *lowerIntPoints[3] = {&intPoints[0 * 6 * 6 * 3], &intPoints[1 * 6 * 6 * 3], &intPoints[2 * 6 * 6 * 3]};
10256363a54bSMatthew G. Knepley     PetscReal         *upperIntPoints[3] = {&intPoints[3 * 6 * 6 * 3], &intPoints[4 * 6 * 6 * 3], &intPoints[5 * 6 * 6 * 3]};
10266363a54bSMatthew G. Knepley     PetscReal          lp[3], up[3], *tmp;
10276363a54bSMatthew G. Knepley     PetscInt           numCoords, idx, dlim[6], lowerInt[3], upperInt[3];
10286363a54bSMatthew G. Knepley     PetscBool          isDG, lower[3], upper[3];
1029cafe43deSMatthew G. Knepley 
103096217254SMatthew G. Knepley     PetscCall(PetscFindInt(c, Nl, leaves, &idx));
103196217254SMatthew G. Knepley     if (idx >= 0) continue;
10326363a54bSMatthew G. Knepley     // Get grid of boxes containing the cell
10336363a54bSMatthew G. Knepley     PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
10346363a54bSMatthew G. Knepley     PetscCall(PetscGridHashGetEnclosingBox(lbox, numCoords / cdim, coords, dboxes, boxes));
10356363a54bSMatthew G. Knepley     PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
10366363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) dlim[d * 2 + 0] = dlim[d * 2 + 1] = dboxes[d];
10376363a54bSMatthew G. Knepley     for (PetscInt d = cdim; d < 3; ++d) dlim[d * 2 + 0] = dlim[d * 2 + 1] = 0;
10386363a54bSMatthew G. Knepley     for (PetscInt e = 1; e < numCoords / cdim; ++e) {
10396363a54bSMatthew G. Knepley       for (PetscInt d = 0; d < cdim; ++d) {
10406363a54bSMatthew G. Knepley         dlim[d * 2 + 0] = PetscMin(dlim[d * 2 + 0], dboxes[e * cdim + d]);
10416363a54bSMatthew G. Knepley         dlim[d * 2 + 1] = PetscMax(dlim[d * 2 + 1], dboxes[e * cdim + d]);
1042ddce0771SMatthew G. Knepley       }
1043ddce0771SMatthew G. Knepley     }
10446363a54bSMatthew G. Knepley     if (debug > 4) {
10456363a54bSMatthew G. Knepley       for (PetscInt d = 0; d < cdim; ++d) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " direction %" PetscInt_FMT " box limits %" PetscInt_FMT "--%" PetscInt_FMT "\n", c, d, dlim[d * 2 + 0], dlim[d * 2 + 1]));
1046ddce0771SMatthew G. Knepley     }
10476363a54bSMatthew G. Knepley     // Initialize with lower planes for first box
10486363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) {
10496363a54bSMatthew G. Knepley       lp[d] = lbox->lower[d] + dlim[d * 2 + 0] * h[d];
10506363a54bSMatthew G. Knepley       up[d] = lp[d] + h[d];
10516363a54bSMatthew G. Knepley     }
10526363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) {
10536363a54bSMatthew G. Knepley       PetscCall(DMPlexGetPlaneCellIntersection_Internal(dm, c, lp, &normal[d * 3], &lower[d], &lowerInt[d], lowerIntPoints[d]));
10546363a54bSMatthew G. Knepley       if (debug > 4) {
10556363a54bSMatthew G. Knepley         if (!lowerInt[d])
10566363a54bSMatthew G. Knepley           PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " lower direction %" PetscInt_FMT " (%g, %g, %g) does not intersect %s\n", c, d, (double)lp[0], (double)lp[1], cdim > 2 ? (double)lp[2] : 0., lower[d] ? "positive" : "negative"));
10576363a54bSMatthew G. Knepley         else PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " lower direction %" PetscInt_FMT " (%g, %g, %g) intersects %" PetscInt_FMT " times\n", c, d, (double)lp[0], (double)lp[1], cdim > 2 ? (double)lp[2] : 0., lowerInt[d]));
1058cafe43deSMatthew G. Knepley       }
1059cafe43deSMatthew G. Knepley     }
10606363a54bSMatthew G. Knepley     // Loop over grid
10616363a54bSMatthew G. Knepley     for (PetscInt k = dlim[2 * 2 + 0]; k <= dlim[2 * 2 + 1]; ++k, lp[2] = up[2], up[2] += h[2]) {
10626363a54bSMatthew G. Knepley       if (cdim > 2) PetscCall(DMPlexGetPlaneCellIntersection_Internal(dm, c, up, &normal[3 * 2], &upper[2], &upperInt[2], upperIntPoints[2]));
10636363a54bSMatthew G. Knepley       if (cdim > 2 && debug > 4) {
10646363a54bSMatthew G. Knepley         if (!upperInt[2]) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " upper direction 2 (%g, %g, %g) does not intersect %s\n", c, (double)up[0], (double)up[1], cdim > 2 ? (double)up[2] : 0., upper[2] ? "positive" : "negative"));
10656363a54bSMatthew G. Knepley         else PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " upper direction 2 (%g, %g, %g) intersects %" PetscInt_FMT " times\n", c, (double)up[0], (double)up[1], cdim > 2 ? (double)up[2] : 0., upperInt[2]));
10666363a54bSMatthew G. Knepley       }
10676363a54bSMatthew G. Knepley       for (PetscInt j = dlim[1 * 2 + 0]; j <= dlim[1 * 2 + 1]; ++j, lp[1] = up[1], up[1] += h[1]) {
10686363a54bSMatthew G. Knepley         if (cdim > 1) PetscCall(DMPlexGetPlaneCellIntersection_Internal(dm, c, up, &normal[3 * 1], &upper[1], &upperInt[1], upperIntPoints[1]));
10696363a54bSMatthew G. Knepley         if (cdim > 1 && debug > 4) {
10706363a54bSMatthew G. Knepley           if (!upperInt[1])
10716363a54bSMatthew G. Knepley             PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " upper direction 1 (%g, %g, %g) does not intersect %s\n", c, (double)up[0], (double)up[1], cdim > 2 ? (double)up[2] : 0., upper[1] ? "positive" : "negative"));
10726363a54bSMatthew G. Knepley           else PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " upper direction 1 (%g, %g, %g) intersects %" PetscInt_FMT " times\n", c, (double)up[0], (double)up[1], cdim > 2 ? (double)up[2] : 0., upperInt[1]));
10736363a54bSMatthew G. Knepley         }
10746363a54bSMatthew G. Knepley         for (PetscInt i = dlim[0 * 2 + 0]; i <= dlim[0 * 2 + 1]; ++i, lp[0] = up[0], up[0] += h[0]) {
1075cafe43deSMatthew G. Knepley           const PetscInt box    = (k * lbox->n[1] + j) * lbox->n[0] + i;
10766363a54bSMatthew G. Knepley           PetscBool      excNeg = PETSC_TRUE;
10776363a54bSMatthew G. Knepley           PetscBool      excPos = PETSC_TRUE;
10786363a54bSMatthew G. Knepley           PetscInt       NlInt  = 0;
10796363a54bSMatthew G. Knepley           PetscInt       NuInt  = 0;
1080cafe43deSMatthew G. Knepley 
10816363a54bSMatthew G. Knepley           PetscCall(DMPlexGetPlaneCellIntersection_Internal(dm, c, up, &normal[3 * 0], &upper[0], &upperInt[0], upperIntPoints[0]));
10826363a54bSMatthew G. Knepley           if (debug > 4) {
10836363a54bSMatthew G. Knepley             if (!upperInt[0])
10846363a54bSMatthew G. Knepley               PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " upper direction 0 (%g, %g, %g) does not intersect %s\n", c, (double)up[0], (double)up[1], cdim > 2 ? (double)up[2] : 0., upper[0] ? "positive" : "negative"));
10856363a54bSMatthew G. Knepley             else PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " upper direction 0 (%g, %g, %g) intersects %" PetscInt_FMT " times\n", c, (double)up[0], (double)up[1], cdim > 2 ? (double)up[2] : 0., upperInt[0]));
10866363a54bSMatthew G. Knepley           }
10876363a54bSMatthew G. Knepley           for (PetscInt d = 0; d < cdim; ++d) {
10886363a54bSMatthew G. Knepley             NlInt += lowerInt[d];
10896363a54bSMatthew G. Knepley             NuInt += upperInt[d];
10906363a54bSMatthew G. Knepley           }
10916363a54bSMatthew G. Knepley           // If there is no intersection...
10926363a54bSMatthew G. Knepley           if (!NlInt && !NuInt) {
10936363a54bSMatthew G. Knepley             // If the cell is on the negative side of the lower planes, it is not in the box
10946363a54bSMatthew G. Knepley             for (PetscInt d = 0; d < cdim; ++d)
10956363a54bSMatthew G. Knepley               if (lower[d]) {
10966363a54bSMatthew G. Knepley                 excNeg = PETSC_FALSE;
10970b6bfacdSStefano Zampini                 break;
10980b6bfacdSStefano Zampini               }
10996363a54bSMatthew G. Knepley             // If the cell is on the positive side of the upper planes, it is not in the box
11006363a54bSMatthew G. Knepley             for (PetscInt d = 0; d < cdim; ++d)
11016363a54bSMatthew G. Knepley               if (!upper[d]) {
11026363a54bSMatthew G. Knepley                 excPos = PETSC_FALSE;
11039371c9d4SSatish Balay                 break;
1104ddce0771SMatthew G. Knepley               }
11056363a54bSMatthew G. Knepley             if (excNeg || excPos) {
11066363a54bSMatthew G. Knepley               if (debug && excNeg) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " is on the negative side of the lower plane\n", c));
11076363a54bSMatthew G. Knepley               if (debug && excPos) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " is on the positive side of the upper plane\n", c));
11086363a54bSMatthew G. Knepley               continue;
11096363a54bSMatthew G. Knepley             }
11106363a54bSMatthew G. Knepley             // Otherwise it is in the box
11116363a54bSMatthew G. Knepley             if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " is contained in box %" PetscInt_FMT "\n", c, box));
11126363a54bSMatthew G. Knepley             PetscCall(DMLabelSetValue(lbox->cellsSparse, c, box));
11136363a54bSMatthew G. Knepley             continue;
11146363a54bSMatthew G. Knepley           }
1115b3e8128dSjosephpu           /*
1116b3e8128dSjosephpu             If any intersection point is within the box limits, it is in the box
1117b3e8128dSjosephpu             We need to have tolerances here since intersection point calculations can introduce errors
1118b3e8128dSjosephpu             Initialize a count to track which planes have intersection outside the box.
1119b3e8128dSjosephpu             if two adjacent planes have intersection points upper and lower all outside the box, look
1120b3e8128dSjosephpu             first at if another plane has intersection points outside the box, if so, it is inside the cell
1121b3e8128dSjosephpu             look next if no intersection points exist on the other planes, and check if the planes are on the
1122b3e8128dSjosephpu             outside of the intersection points but on opposite ends. If so, the box cuts through the cell.
1123b3e8128dSjosephpu           */
1124b3e8128dSjosephpu           PetscInt outsideCount[6] = {0, 0, 0, 0, 0, 0};
11256363a54bSMatthew G. Knepley           for (PetscInt plane = 0; plane < cdim; ++plane) {
11266363a54bSMatthew G. Knepley             for (PetscInt ip = 0; ip < lowerInt[plane]; ++ip) {
11276363a54bSMatthew G. Knepley               PetscInt d;
11286363a54bSMatthew G. Knepley 
11296363a54bSMatthew G. Knepley               for (d = 0; d < cdim; ++d) {
1130b3e8128dSjosephpu                 if ((lowerIntPoints[plane][ip * cdim + d] < (lp[d] - PETSC_SMALL)) || (lowerIntPoints[plane][ip * cdim + d] > (up[d] + PETSC_SMALL))) {
1131b3e8128dSjosephpu                   if (lowerIntPoints[plane][ip * cdim + d] < (lp[d] - PETSC_SMALL)) outsideCount[d]++; // The lower point is to the left of this box, and we count it
1132b3e8128dSjosephpu                   break;
1133b3e8128dSjosephpu                 }
11346363a54bSMatthew G. Knepley               }
11356363a54bSMatthew G. Knepley               if (d == cdim) {
11366363a54bSMatthew G. Knepley                 if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " intersected lower plane %" PetscInt_FMT " of box %" PetscInt_FMT "\n", c, plane, box));
11376363a54bSMatthew G. Knepley                 PetscCall(DMLabelSetValue(lbox->cellsSparse, c, box));
11386363a54bSMatthew G. Knepley                 goto end;
11396363a54bSMatthew G. Knepley               }
11406363a54bSMatthew G. Knepley             }
11416363a54bSMatthew G. Knepley             for (PetscInt ip = 0; ip < upperInt[plane]; ++ip) {
11426363a54bSMatthew G. Knepley               PetscInt d;
11436363a54bSMatthew G. Knepley 
11446363a54bSMatthew G. Knepley               for (d = 0; d < cdim; ++d) {
1145b3e8128dSjosephpu                 if ((upperIntPoints[plane][ip * cdim + d] < (lp[d] - PETSC_SMALL)) || (upperIntPoints[plane][ip * cdim + d] > (up[d] + PETSC_SMALL))) {
1146b3e8128dSjosephpu                   if (upperIntPoints[plane][ip * cdim + d] > (up[d] + PETSC_SMALL)) outsideCount[cdim + d]++; // The upper point is to the right of this box, and we count it
1147b3e8128dSjosephpu                   break;
1148b3e8128dSjosephpu                 }
11496363a54bSMatthew G. Knepley               }
11506363a54bSMatthew G. Knepley               if (d == cdim) {
11516363a54bSMatthew G. Knepley                 if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " intersected upper plane %" PetscInt_FMT " of box %" PetscInt_FMT "\n", c, plane, box));
11526363a54bSMatthew G. Knepley                 PetscCall(DMLabelSetValue(lbox->cellsSparse, c, box));
11536363a54bSMatthew G. Knepley                 goto end;
1154ddce0771SMatthew G. Knepley               }
1155ddce0771SMatthew G. Knepley             }
1156cafe43deSMatthew G. Knepley           }
1157b3e8128dSjosephpu           /*
1158b3e8128dSjosephpu              Check the planes with intersections
1159b3e8128dSjosephpu              in 2D, check if the square falls in the middle of a cell
1160b3e8128dSjosephpu              ie all four planes have intersection points outside of the box
1161b3e8128dSjosephpu              You do not want to be doing this, because it means your grid hashing is finer than your grid,
1162b3e8128dSjosephpu              but we should still support it I guess
1163b3e8128dSjosephpu           */
1164b3e8128dSjosephpu           if (cdim == 2) {
1165b3e8128dSjosephpu             PetscInt nIntersects = 0;
1166b3e8128dSjosephpu             for (PetscInt d = 0; d < cdim; ++d) nIntersects += (outsideCount[d] + outsideCount[d + cdim]);
1167b3e8128dSjosephpu             // if the count adds up to 8, that means each plane has 2 external intersections and thus it is in the cell
1168b3e8128dSjosephpu             if (nIntersects == 8) {
1169b3e8128dSjosephpu               PetscCall(DMLabelSetValue(lbox->cellsSparse, c, box));
1170b3e8128dSjosephpu               goto end;
1171b3e8128dSjosephpu             }
1172b3e8128dSjosephpu           }
1173b3e8128dSjosephpu           /*
1174baca6076SPierre Jolivet              In 3 dimensions, if two adjacent planes have at least 3 intersections outside the cell in the appropriate direction,
1175b3e8128dSjosephpu              we then check the 3rd planar dimension. If a plane falls between intersection points, the cell belongs to that box.
1176b3e8128dSjosephpu              If the planes are on opposite sides of the intersection points, the cell belongs to that box and it passes through the cell.
1177b3e8128dSjosephpu           */
1178b3e8128dSjosephpu           if (cdim == 3) {
1179b3e8128dSjosephpu             PetscInt faces[3] = {0, 0, 0}, checkInternalFace = 0;
1180b3e8128dSjosephpu             // Find two adjacent planes with at least 3 intersection points in the upper and lower
1181b3e8128dSjosephpu             // if the third plane has 3 intersection points or more, a pyramid base is formed on that plane and it is in the cell
1182b3e8128dSjosephpu             for (PetscInt d = 0; d < cdim; ++d)
1183b3e8128dSjosephpu               if (outsideCount[d] >= 3 && outsideCount[cdim + d] >= 3) {
1184b3e8128dSjosephpu                 faces[d]++;
1185b3e8128dSjosephpu                 checkInternalFace++;
1186b3e8128dSjosephpu               }
1187b3e8128dSjosephpu             if (checkInternalFace == 3) {
1188b3e8128dSjosephpu               // All planes have 3 intersection points, add it.
1189b3e8128dSjosephpu               PetscCall(DMLabelSetValue(lbox->cellsSparse, c, box));
1190b3e8128dSjosephpu               goto end;
1191b3e8128dSjosephpu             }
1192b3e8128dSjosephpu             // Gross, figure out which adjacent faces have at least 3 points
1193b3e8128dSjosephpu             PetscInt nonIntersectingFace = -1;
1194b3e8128dSjosephpu             if (faces[0] == faces[1]) nonIntersectingFace = 2;
1195b3e8128dSjosephpu             if (faces[0] == faces[2]) nonIntersectingFace = 1;
1196b3e8128dSjosephpu             if (faces[1] == faces[2]) nonIntersectingFace = 0;
1197b3e8128dSjosephpu             if (nonIntersectingFace >= 0) {
1198b3e8128dSjosephpu               for (PetscInt plane = 0; plane < cdim; ++plane) {
1199b3e8128dSjosephpu                 if (!lowerInt[nonIntersectingFace] && !upperInt[nonIntersectingFace]) continue;
1200b3e8128dSjosephpu                 // If we have 2 adjacent sides with pyramids of intersection outside of them, and there is a point between the end caps at all, it must be between the two non intersecting ends, and the box is inside the cell.
1201b3e8128dSjosephpu                 for (PetscInt ip = 0; ip < lowerInt[nonIntersectingFace]; ++ip) {
1202b3e8128dSjosephpu                   if (lowerIntPoints[plane][ip * cdim + nonIntersectingFace] > lp[nonIntersectingFace] - PETSC_SMALL || lowerIntPoints[plane][ip * cdim + nonIntersectingFace] < up[nonIntersectingFace] + PETSC_SMALL) goto setpoint;
1203b3e8128dSjosephpu                 }
1204b3e8128dSjosephpu                 for (PetscInt ip = 0; ip < upperInt[nonIntersectingFace]; ++ip) {
1205b3e8128dSjosephpu                   if (upperIntPoints[plane][ip * cdim + nonIntersectingFace] > lp[nonIntersectingFace] - PETSC_SMALL || upperIntPoints[plane][ip * cdim + nonIntersectingFace] < up[nonIntersectingFace] + PETSC_SMALL) goto setpoint;
1206b3e8128dSjosephpu                 }
1207b3e8128dSjosephpu                 goto end;
1208b3e8128dSjosephpu               }
1209b3e8128dSjosephpu               // The points are within the bonds of the non intersecting planes, add it.
1210b3e8128dSjosephpu             setpoint:
1211b3e8128dSjosephpu               PetscCall(DMLabelSetValue(lbox->cellsSparse, c, box));
1212b3e8128dSjosephpu               goto end;
1213b3e8128dSjosephpu             }
1214b3e8128dSjosephpu           }
12156363a54bSMatthew G. Knepley         end:
12166363a54bSMatthew G. Knepley           lower[0]          = upper[0];
12176363a54bSMatthew G. Knepley           lowerInt[0]       = upperInt[0];
12186363a54bSMatthew G. Knepley           tmp               = lowerIntPoints[0];
12196363a54bSMatthew G. Knepley           lowerIntPoints[0] = upperIntPoints[0];
12206363a54bSMatthew G. Knepley           upperIntPoints[0] = tmp;
12216363a54bSMatthew G. Knepley         }
12226363a54bSMatthew G. Knepley         lp[0]             = lbox->lower[0] + dlim[0 * 2 + 0] * h[0];
12236363a54bSMatthew G. Knepley         up[0]             = lp[0] + h[0];
12246363a54bSMatthew G. Knepley         lower[1]          = upper[1];
12256363a54bSMatthew G. Knepley         lowerInt[1]       = upperInt[1];
12266363a54bSMatthew G. Knepley         tmp               = lowerIntPoints[1];
12276363a54bSMatthew G. Knepley         lowerIntPoints[1] = upperIntPoints[1];
12286363a54bSMatthew G. Knepley         upperIntPoints[1] = tmp;
12296363a54bSMatthew G. Knepley       }
12306363a54bSMatthew G. Knepley       lp[1]             = lbox->lower[1] + dlim[1 * 2 + 0] * h[1];
12316363a54bSMatthew G. Knepley       up[1]             = lp[1] + h[1];
12326363a54bSMatthew G. Knepley       lower[2]          = upper[2];
12336363a54bSMatthew G. Knepley       lowerInt[2]       = upperInt[2];
12346363a54bSMatthew G. Knepley       tmp               = lowerIntPoints[2];
12356363a54bSMatthew G. Knepley       lowerIntPoints[2] = upperIntPoints[2];
12366363a54bSMatthew G. Knepley       upperIntPoints[2] = tmp;
1237fea14342SMatthew G. Knepley     }
1238fea14342SMatthew G. Knepley   }
12396363a54bSMatthew G. Knepley   PetscCall(PetscFree2(dboxes, boxes));
12406363a54bSMatthew G. Knepley 
12419566063dSJacob Faibussowitsch   if (debug) PetscCall(DMLabelView(lbox->cellsSparse, PETSC_VIEWER_STDOUT_SELF));
12429566063dSJacob Faibussowitsch   PetscCall(DMLabelConvertToSection(lbox->cellsSparse, &lbox->cellSection, &lbox->cells));
12439566063dSJacob Faibussowitsch   PetscCall(DMLabelDestroy(&lbox->cellsSparse));
1244cafe43deSMatthew G. Knepley   *localBox = lbox;
12453ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1246cafe43deSMatthew G. Knepley }
1247cafe43deSMatthew G. Knepley 
1248d71ae5a4SJacob Faibussowitsch PetscErrorCode DMLocatePoints_Plex(DM dm, Vec v, DMPointLocationType ltype, PetscSF cellSF)
1249d71ae5a4SJacob Faibussowitsch {
1250f5867de0SMatthew G. Knepley   PetscInt        debug = ((DM_Plex *)dm->data)->printLocate;
1251cafe43deSMatthew G. Knepley   DM_Plex        *mesh  = (DM_Plex *)dm->data;
1252af74b616SDave May   PetscBool       hash = mesh->useHashLocation, reuse = PETSC_FALSE;
1253*1f08e9caSMatthew G. Knepley   PetscInt        bs, numPoints, numFound, *found = NULL;
1254*1f08e9caSMatthew G. Knepley   PetscInt        cdim, Nl = 0, cStart, cEnd, numCells;
1255d8206211SMatthew G. Knepley   PetscSF         sf;
1256d8206211SMatthew G. Knepley   const PetscInt *leaves;
1257cafe43deSMatthew G. Knepley   const PetscInt *boxCells;
12583a93e3b7SToby Isaac   PetscSFNode    *cells;
1259ccd2543fSMatthew G Knepley   PetscScalar    *a;
12603a93e3b7SToby Isaac   PetscMPIInt     result;
1261af74b616SDave May   PetscLogDouble  t0, t1;
12629cb35068SDave May   PetscReal       gmin[3], gmax[3];
12639cb35068SDave May   PetscInt        terminating_query_type[] = {0, 0, 0};
12646363a54bSMatthew G. Knepley   PetscMPIInt     rank;
1265ccd2543fSMatthew G Knepley 
1266ccd2543fSMatthew G Knepley   PetscFunctionBegin;
12676363a54bSMatthew G. Knepley   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
12689566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(DMPLEX_LocatePoints, 0, 0, 0, 0));
12699566063dSJacob Faibussowitsch   PetscCall(PetscTime(&t0));
12701dca8a05SBarry Smith   PetscCheck(ltype != DM_POINTLOCATION_NEAREST || hash, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Nearest point location only supported with grid hashing. Use -dm_plex_hash_location to enable it.");
1271*1f08e9caSMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &cdim));
12729566063dSJacob Faibussowitsch   PetscCall(VecGetBlockSize(v, &bs));
12739566063dSJacob Faibussowitsch   PetscCallMPI(MPI_Comm_compare(PetscObjectComm((PetscObject)cellSF), PETSC_COMM_SELF, &result));
12741dca8a05SBarry Smith   PetscCheck(result == MPI_IDENT || result == MPI_CONGRUENT, PetscObjectComm((PetscObject)cellSF), PETSC_ERR_SUP, "Trying parallel point location: only local point location supported");
1275d52c2f21SMatthew G. Knepley   // We ignore extra coordinates
1276*1f08e9caSMatthew G. Knepley   PetscCheck(bs >= cdim, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Block size for point vector %" PetscInt_FMT " must be the mesh coordinate dimension %" PetscInt_FMT, bs, cdim);
12776858538eSMatthew G. Knepley   PetscCall(DMGetCoordinatesLocalSetUp(dm));
12789566063dSJacob Faibussowitsch   PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
1279d8206211SMatthew G. Knepley   PetscCall(DMGetPointSF(dm, &sf));
1280d8206211SMatthew G. Knepley   if (sf) PetscCall(PetscSFGetGraph(sf, NULL, &Nl, &leaves, NULL));
1281d8206211SMatthew G. Knepley   Nl = PetscMax(Nl, 0);
12829566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(v, &numPoints));
12839566063dSJacob Faibussowitsch   PetscCall(VecGetArray(v, &a));
1284ccd2543fSMatthew G Knepley   numPoints /= bs;
1285af74b616SDave May   {
1286af74b616SDave May     const PetscSFNode *sf_cells;
1287af74b616SDave May 
12889566063dSJacob Faibussowitsch     PetscCall(PetscSFGetGraph(cellSF, NULL, NULL, NULL, &sf_cells));
1289af74b616SDave May     if (sf_cells) {
12909566063dSJacob Faibussowitsch       PetscCall(PetscInfo(dm, "[DMLocatePoints_Plex] Re-using existing StarForest node list\n"));
1291af74b616SDave May       cells = (PetscSFNode *)sf_cells;
1292af74b616SDave May       reuse = PETSC_TRUE;
1293af74b616SDave May     } else {
12949566063dSJacob Faibussowitsch       PetscCall(PetscInfo(dm, "[DMLocatePoints_Plex] Creating and initializing new StarForest node list\n"));
12959566063dSJacob Faibussowitsch       PetscCall(PetscMalloc1(numPoints, &cells));
1296af74b616SDave May       /* initialize cells if created */
1297*1f08e9caSMatthew G. Knepley       for (PetscInt p = 0; p < numPoints; p++) {
1298af74b616SDave May         cells[p].rank  = 0;
1299af74b616SDave May         cells[p].index = DMLOCATEPOINT_POINT_NOT_FOUND;
1300af74b616SDave May       }
1301af74b616SDave May     }
1302af74b616SDave May   }
130376b3799dSMatthew G. Knepley   PetscCall(DMGetBoundingBox(dm, gmin, gmax));
1304953fc75cSMatthew G. Knepley   if (hash) {
13059371c9d4SSatish Balay     if (!mesh->lbox) {
130696217254SMatthew G. Knepley       PetscCall(PetscInfo(dm, "Initializing grid hashing\n"));
13079371c9d4SSatish Balay       PetscCall(DMPlexComputeGridHash_Internal(dm, &mesh->lbox));
13089371c9d4SSatish Balay     }
1309cafe43deSMatthew G. Knepley     /* Designate the local box for each point */
1310cafe43deSMatthew G. Knepley     /* Send points to correct process */
1311cafe43deSMatthew G. Knepley     /* Search cells that lie in each subbox */
1312cafe43deSMatthew G. Knepley     /*   Should we bin points before doing search? */
13139566063dSJacob Faibussowitsch     PetscCall(ISGetIndices(mesh->lbox->cells, &boxCells));
1314953fc75cSMatthew G. Knepley   }
1315*1f08e9caSMatthew G. Knepley   numFound = 0;
1316*1f08e9caSMatthew G. Knepley   for (PetscInt p = 0; p < numPoints; ++p) {
1317ccd2543fSMatthew G Knepley     const PetscScalar *point   = &a[p * bs];
1318e56f9228SJed Brown     PetscInt           dbin[3] = {-1, -1, -1}, bin, cell = -1, cellOffset;
13199cb35068SDave May     PetscBool          point_outside_domain = PETSC_FALSE;
1320ccd2543fSMatthew G Knepley 
13219cb35068SDave May     /* check bounding box of domain */
1322*1f08e9caSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; d++) {
13239371c9d4SSatish Balay       if (PetscRealPart(point[d]) < gmin[d]) {
13249371c9d4SSatish Balay         point_outside_domain = PETSC_TRUE;
13259371c9d4SSatish Balay         break;
13269371c9d4SSatish Balay       }
13279371c9d4SSatish Balay       if (PetscRealPart(point[d]) > gmax[d]) {
13289371c9d4SSatish Balay         point_outside_domain = PETSC_TRUE;
13299371c9d4SSatish Balay         break;
13309371c9d4SSatish Balay       }
13319cb35068SDave May     }
13329cb35068SDave May     if (point_outside_domain) {
1333e9b685f5SMatthew G. Knepley       cells[p].rank  = 0;
1334e9b685f5SMatthew G. Knepley       cells[p].index = DMLOCATEPOINT_POINT_NOT_FOUND;
13359cb35068SDave May       terminating_query_type[0]++;
13369cb35068SDave May       continue;
13379cb35068SDave May     }
1338ccd2543fSMatthew G Knepley 
1339af74b616SDave May     /* check initial values in cells[].index - abort early if found */
1340af74b616SDave May     if (cells[p].index != DMLOCATEPOINT_POINT_NOT_FOUND) {
1341*1f08e9caSMatthew G. Knepley       PetscInt c = cells[p].index;
1342*1f08e9caSMatthew G. Knepley 
13433a93e3b7SToby Isaac       cells[p].index = DMLOCATEPOINT_POINT_NOT_FOUND;
1344*1f08e9caSMatthew G. Knepley       PetscCall(DMPlexLocatePoint_Internal(dm, cdim, point, c, &cell));
1345af74b616SDave May       if (cell >= 0) {
1346af74b616SDave May         cells[p].rank  = 0;
1347af74b616SDave May         cells[p].index = cell;
1348af74b616SDave May         numFound++;
1349af74b616SDave May       }
1350af74b616SDave May     }
13519cb35068SDave May     if (cells[p].index != DMLOCATEPOINT_POINT_NOT_FOUND) {
13529cb35068SDave May       terminating_query_type[1]++;
13539cb35068SDave May       continue;
13549cb35068SDave May     }
1355af74b616SDave May 
1356*1f08e9caSMatthew G. Knepley     if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, "[%d]Checking point %" PetscInt_FMT " (%.2g, %.2g, %.2g)\n", rank, p, (double)PetscRealPart(point[0]), (double)PetscRealPart(point[1]), cdim > 2 ? (double)PetscRealPart(point[2]) : 0.));
1357953fc75cSMatthew G. Knepley     if (hash) {
1358af74b616SDave May       PetscBool found_box;
1359af74b616SDave May 
1360af74b616SDave May       /* allow for case that point is outside box - abort early */
1361f5867de0SMatthew G. Knepley       PetscCall(PetscGridHashGetEnclosingBoxQuery(mesh->lbox, mesh->lbox->cellSection, 1, point, dbin, &bin, &found_box));
1362af74b616SDave May       if (found_box) {
1363*1f08e9caSMatthew G. Knepley         if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, "[%d]  Found point in box %" PetscInt_FMT " (%" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ")\n", rank, bin, dbin[0], dbin[1], cdim > 2 ? dbin[2] : 0));
1364cafe43deSMatthew G. Knepley         /* TODO Lay an interface over this so we can switch between Section (dense) and Label (sparse) */
13659566063dSJacob Faibussowitsch         PetscCall(PetscSectionGetDof(mesh->lbox->cellSection, bin, &numCells));
13669566063dSJacob Faibussowitsch         PetscCall(PetscSectionGetOffset(mesh->lbox->cellSection, bin, &cellOffset));
1367*1f08e9caSMatthew G. Knepley         for (PetscInt c = cellOffset; c < cellOffset + numCells; ++c) {
13686363a54bSMatthew G. Knepley           if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, "[%d]    Checking for point in cell %" PetscInt_FMT "\n", rank, boxCells[c]));
1369*1f08e9caSMatthew G. Knepley           PetscCall(DMPlexLocatePoint_Internal(dm, cdim, point, boxCells[c], &cell));
13703a93e3b7SToby Isaac           if (cell >= 0) {
13716363a54bSMatthew G. Knepley             if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, "[%d]      FOUND in cell %" PetscInt_FMT "\n", rank, cell));
13723a93e3b7SToby Isaac             cells[p].rank  = 0;
13733a93e3b7SToby Isaac             cells[p].index = cell;
13743a93e3b7SToby Isaac             numFound++;
13759cb35068SDave May             terminating_query_type[2]++;
13763a93e3b7SToby Isaac             break;
1377ccd2543fSMatthew G Knepley           }
13783a93e3b7SToby Isaac         }
1379af74b616SDave May       }
1380953fc75cSMatthew G. Knepley     } else {
1381dd301514SZach Atkins       PetscBool found = PETSC_FALSE;
1382*1f08e9caSMatthew G. Knepley       for (PetscInt c = cStart; c < cEnd; ++c) {
1383d8206211SMatthew G. Knepley         PetscInt idx;
1384d8206211SMatthew G. Knepley 
1385d8206211SMatthew G. Knepley         PetscCall(PetscFindInt(c, Nl, leaves, &idx));
1386d8206211SMatthew G. Knepley         if (idx >= 0) continue;
1387*1f08e9caSMatthew G. Knepley         PetscCall(DMPlexLocatePoint_Internal(dm, cdim, point, c, &cell));
13883a93e3b7SToby Isaac         if (cell >= 0) {
13893a93e3b7SToby Isaac           cells[p].rank  = 0;
13903a93e3b7SToby Isaac           cells[p].index = cell;
13913a93e3b7SToby Isaac           numFound++;
13929cb35068SDave May           terminating_query_type[2]++;
1393dd301514SZach Atkins           found = PETSC_TRUE;
13943a93e3b7SToby Isaac           break;
1395953fc75cSMatthew G. Knepley         }
1396953fc75cSMatthew G. Knepley       }
1397dd301514SZach Atkins       if (!found) terminating_query_type[0]++;
13983a93e3b7SToby Isaac     }
1399ccd2543fSMatthew G Knepley   }
14009566063dSJacob Faibussowitsch   if (hash) PetscCall(ISRestoreIndices(mesh->lbox->cells, &boxCells));
140162a38674SMatthew G. Knepley   if (ltype == DM_POINTLOCATION_NEAREST && hash && numFound < numPoints) {
1402*1f08e9caSMatthew G. Knepley     for (PetscInt p = 0; p < numPoints; p++) {
140362a38674SMatthew G. Knepley       const PetscScalar *point     = &a[p * bs];
1404d52e4eadSJose E. Roman       PetscReal          cpoint[3] = {0, 0, 0}, diff[3], best[3] = {PETSC_MAX_REAL, PETSC_MAX_REAL, PETSC_MAX_REAL}, dist, distMax = PETSC_MAX_REAL;
1405*1f08e9caSMatthew G. Knepley       PetscInt           dbin[3] = {-1, -1, -1}, bin, cellOffset, bestc = -1;
140662a38674SMatthew G. Knepley 
1407e9b685f5SMatthew G. Knepley       if (cells[p].index < 0) {
14089566063dSJacob Faibussowitsch         PetscCall(PetscGridHashGetEnclosingBox(mesh->lbox, 1, point, dbin, &bin));
14099566063dSJacob Faibussowitsch         PetscCall(PetscSectionGetDof(mesh->lbox->cellSection, bin, &numCells));
14109566063dSJacob Faibussowitsch         PetscCall(PetscSectionGetOffset(mesh->lbox->cellSection, bin, &cellOffset));
1411*1f08e9caSMatthew G. Knepley         for (PetscInt c = cellOffset; c < cellOffset + numCells; ++c) {
1412*1f08e9caSMatthew G. Knepley           PetscCall(DMPlexClosestPoint_Internal(dm, cdim, point, boxCells[c], cpoint));
1413*1f08e9caSMatthew G. Knepley           for (PetscInt d = 0; d < cdim; ++d) diff[d] = cpoint[d] - PetscRealPart(point[d]);
1414*1f08e9caSMatthew G. Knepley           dist = DMPlex_NormD_Internal(cdim, diff);
141562a38674SMatthew G. Knepley           if (dist < distMax) {
1416*1f08e9caSMatthew G. Knepley             for (PetscInt d = 0; d < cdim; ++d) best[d] = cpoint[d];
1417d92c4b9fSToby Isaac             bestc   = boxCells[c];
141862a38674SMatthew G. Knepley             distMax = dist;
141962a38674SMatthew G. Knepley           }
142062a38674SMatthew G. Knepley         }
1421d92c4b9fSToby Isaac         if (distMax < PETSC_MAX_REAL) {
1422d92c4b9fSToby Isaac           ++numFound;
1423d92c4b9fSToby Isaac           cells[p].rank  = 0;
1424d92c4b9fSToby Isaac           cells[p].index = bestc;
1425*1f08e9caSMatthew G. Knepley           for (PetscInt d = 0; d < cdim; ++d) a[p * bs + d] = best[d];
1426d92c4b9fSToby Isaac         }
142762a38674SMatthew G. Knepley       }
142862a38674SMatthew G. Knepley     }
142962a38674SMatthew G. Knepley   }
143062a38674SMatthew G. Knepley   /* This code is only be relevant when interfaced to parallel point location */
1431cafe43deSMatthew G. Knepley   /* Check for highest numbered proc that claims a point (do we care?) */
14322d1fa6caSMatthew G. Knepley   if (ltype == DM_POINTLOCATION_REMOVE && numFound < numPoints) {
14339566063dSJacob Faibussowitsch     PetscCall(PetscMalloc1(numFound, &found));
1434*1f08e9caSMatthew G. Knepley     numFound = 0;
1435*1f08e9caSMatthew G. Knepley     for (PetscInt p = 0; p < numPoints; p++) {
14363a93e3b7SToby Isaac       if (cells[p].rank >= 0 && cells[p].index >= 0) {
1437ad540459SPierre Jolivet         if (numFound < p) cells[numFound] = cells[p];
14383a93e3b7SToby Isaac         found[numFound++] = p;
14393a93e3b7SToby Isaac       }
14403a93e3b7SToby Isaac     }
14413a93e3b7SToby Isaac   }
14429566063dSJacob Faibussowitsch   PetscCall(VecRestoreArray(v, &a));
144348a46eb9SPierre Jolivet   if (!reuse) PetscCall(PetscSFSetGraph(cellSF, cEnd - cStart, numFound, found, PETSC_OWN_POINTER, cells, PETSC_OWN_POINTER));
14449566063dSJacob Faibussowitsch   PetscCall(PetscTime(&t1));
14459cb35068SDave May   if (hash) {
144663a3b9bcSJacob Faibussowitsch     PetscCall(PetscInfo(dm, "[DMLocatePoints_Plex] terminating_query_type : %" PetscInt_FMT " [outside domain] : %" PetscInt_FMT " [inside initial cell] : %" PetscInt_FMT " [hash]\n", terminating_query_type[0], terminating_query_type[1], terminating_query_type[2]));
14479cb35068SDave May   } else {
144863a3b9bcSJacob Faibussowitsch     PetscCall(PetscInfo(dm, "[DMLocatePoints_Plex] terminating_query_type : %" PetscInt_FMT " [outside domain] : %" PetscInt_FMT " [inside initial cell] : %" PetscInt_FMT " [brute-force]\n", terminating_query_type[0], terminating_query_type[1], terminating_query_type[2]));
14499cb35068SDave May   }
1450835f2295SStefano Zampini   PetscCall(PetscInfo(dm, "[DMLocatePoints_Plex] npoints %" PetscInt_FMT " : time(rank0) %1.2e (sec): points/sec %1.4e\n", numPoints, t1 - t0, numPoints / (t1 - t0)));
14519566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(DMPLEX_LocatePoints, 0, 0, 0, 0));
14523ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1453ccd2543fSMatthew G Knepley }
1454ccd2543fSMatthew G Knepley 
1455cc4c1da9SBarry Smith /*@
1456741bfc07SMatthew G. Knepley   DMPlexComputeProjection2Dto1D - Rewrite coordinates to be the 1D projection of the 2D coordinates
1457741bfc07SMatthew G. Knepley 
145820f4b53cSBarry Smith   Not Collective
1459741bfc07SMatthew G. Knepley 
14606b867d5aSJose E. Roman   Input/Output Parameter:
1461a3b724e8SBarry Smith . coords - The coordinates of a segment, on output the new y-coordinate, and 0 for x, an array of size 4, last two entries are unchanged
1462741bfc07SMatthew G. Knepley 
14636b867d5aSJose E. Roman   Output Parameter:
1464a3b724e8SBarry Smith . R - The rotation which accomplishes the projection, array of size 4
1465741bfc07SMatthew G. Knepley 
1466741bfc07SMatthew G. Knepley   Level: developer
1467741bfc07SMatthew G. Knepley 
14682fe279fdSBarry Smith .seealso: `DMPLEX`, `DMPlexComputeProjection3Dto1D()`, `DMPlexComputeProjection3Dto2D()`
1469741bfc07SMatthew G. Knepley @*/
1470d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexComputeProjection2Dto1D(PetscScalar coords[], PetscReal R[])
1471d71ae5a4SJacob Faibussowitsch {
147217fe8556SMatthew G. Knepley   const PetscReal x = PetscRealPart(coords[2] - coords[0]);
147317fe8556SMatthew G. Knepley   const PetscReal y = PetscRealPart(coords[3] - coords[1]);
14748b49ba18SBarry Smith   const PetscReal r = PetscSqrtReal(x * x + y * y), c = x / r, s = y / r;
147517fe8556SMatthew G. Knepley 
147617fe8556SMatthew G. Knepley   PetscFunctionBegin;
14779371c9d4SSatish Balay   R[0]      = c;
14789371c9d4SSatish Balay   R[1]      = -s;
14799371c9d4SSatish Balay   R[2]      = s;
14809371c9d4SSatish Balay   R[3]      = c;
148117fe8556SMatthew G. Knepley   coords[0] = 0.0;
14827f07f362SMatthew G. Knepley   coords[1] = r;
14833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
148417fe8556SMatthew G. Knepley }
148517fe8556SMatthew G. Knepley 
1486cc4c1da9SBarry Smith /*@
1487741bfc07SMatthew G. Knepley   DMPlexComputeProjection3Dto1D - Rewrite coordinates to be the 1D projection of the 3D coordinates
148828dbe442SToby Isaac 
148920f4b53cSBarry Smith   Not Collective
149028dbe442SToby Isaac 
14916b867d5aSJose E. Roman   Input/Output Parameter:
1492a3b724e8SBarry Smith . coords - The coordinates of a segment; on output, the new y-coordinate, and 0 for x and z, an array of size 6, the other entries are unchanged
1493741bfc07SMatthew G. Knepley 
14946b867d5aSJose E. Roman   Output Parameter:
1495a3b724e8SBarry Smith . R - The rotation which accomplishes the projection, an array of size 9
1496741bfc07SMatthew G. Knepley 
1497741bfc07SMatthew G. Knepley   Level: developer
1498741bfc07SMatthew G. Knepley 
14991d27aa22SBarry Smith   Note:
15001d27aa22SBarry Smith   This uses the basis completion described by Frisvad {cite}`frisvad2012building`
15011d27aa22SBarry Smith 
15022fe279fdSBarry Smith .seealso: `DMPLEX`, `DMPlexComputeProjection2Dto1D()`, `DMPlexComputeProjection3Dto2D()`
1503741bfc07SMatthew G. Knepley @*/
1504d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexComputeProjection3Dto1D(PetscScalar coords[], PetscReal R[])
1505d71ae5a4SJacob Faibussowitsch {
150628dbe442SToby Isaac   PetscReal x    = PetscRealPart(coords[3] - coords[0]);
150728dbe442SToby Isaac   PetscReal y    = PetscRealPart(coords[4] - coords[1]);
150828dbe442SToby Isaac   PetscReal z    = PetscRealPart(coords[5] - coords[2]);
150928dbe442SToby Isaac   PetscReal r    = PetscSqrtReal(x * x + y * y + z * z);
151028dbe442SToby Isaac   PetscReal rinv = 1. / r;
151128dbe442SToby Isaac 
15124d86920dSPierre Jolivet   PetscFunctionBegin;
15139371c9d4SSatish Balay   x *= rinv;
15149371c9d4SSatish Balay   y *= rinv;
15159371c9d4SSatish Balay   z *= rinv;
151628dbe442SToby Isaac   if (x > 0.) {
151728dbe442SToby Isaac     PetscReal inv1pX = 1. / (1. + x);
151828dbe442SToby Isaac 
15199371c9d4SSatish Balay     R[0] = x;
15209371c9d4SSatish Balay     R[1] = -y;
15219371c9d4SSatish Balay     R[2] = -z;
15229371c9d4SSatish Balay     R[3] = y;
15239371c9d4SSatish Balay     R[4] = 1. - y * y * inv1pX;
15249371c9d4SSatish Balay     R[5] = -y * z * inv1pX;
15259371c9d4SSatish Balay     R[6] = z;
15269371c9d4SSatish Balay     R[7] = -y * z * inv1pX;
15279371c9d4SSatish Balay     R[8] = 1. - z * z * inv1pX;
15289371c9d4SSatish Balay   } else {
152928dbe442SToby Isaac     PetscReal inv1mX = 1. / (1. - x);
153028dbe442SToby Isaac 
15319371c9d4SSatish Balay     R[0] = x;
15329371c9d4SSatish Balay     R[1] = z;
15339371c9d4SSatish Balay     R[2] = y;
15349371c9d4SSatish Balay     R[3] = y;
15359371c9d4SSatish Balay     R[4] = -y * z * inv1mX;
15369371c9d4SSatish Balay     R[5] = 1. - y * y * inv1mX;
15379371c9d4SSatish Balay     R[6] = z;
15389371c9d4SSatish Balay     R[7] = 1. - z * z * inv1mX;
15399371c9d4SSatish Balay     R[8] = -y * z * inv1mX;
154028dbe442SToby Isaac   }
154128dbe442SToby Isaac   coords[0] = 0.0;
154228dbe442SToby Isaac   coords[1] = r;
1543cc4c1da9SBarry Smith   coords[2] = 0.0;
15443ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
154528dbe442SToby Isaac }
154628dbe442SToby Isaac 
1547741bfc07SMatthew G. Knepley /*@
1548c871b86eSJed Brown   DMPlexComputeProjection3Dto2D - Rewrite coordinates of 3 or more coplanar 3D points to a common 2D basis for the
1549c871b86eSJed Brown   plane.  The normal is defined by positive orientation of the first 3 points.
1550741bfc07SMatthew G. Knepley 
155120f4b53cSBarry Smith   Not Collective
1552741bfc07SMatthew G. Knepley 
1553741bfc07SMatthew G. Knepley   Input Parameter:
15546b867d5aSJose E. Roman . coordSize - Length of coordinate array (3x number of points); must be at least 9 (3 points)
1555741bfc07SMatthew G. Knepley 
15566b867d5aSJose E. Roman   Input/Output Parameter:
15576b867d5aSJose E. Roman . coords - The interlaced coordinates of each coplanar 3D point; on output the first
15586b867d5aSJose E. Roman            2*coordSize/3 entries contain interlaced 2D points, with the rest undefined
15596b867d5aSJose E. Roman 
15606b867d5aSJose E. Roman   Output Parameter:
15616b867d5aSJose E. Roman . R - 3x3 row-major rotation matrix whose columns are the tangent basis [t1, t2, n].  Multiplying by R^T transforms from original frame to tangent frame.
1562741bfc07SMatthew G. Knepley 
1563741bfc07SMatthew G. Knepley   Level: developer
1564741bfc07SMatthew G. Knepley 
15652fe279fdSBarry Smith .seealso: `DMPLEX`, `DMPlexComputeProjection2Dto1D()`, `DMPlexComputeProjection3Dto1D()`
1566741bfc07SMatthew G. Knepley @*/
1567d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexComputeProjection3Dto2D(PetscInt coordSize, PetscScalar coords[], PetscReal R[])
1568d71ae5a4SJacob Faibussowitsch {
1569c871b86eSJed Brown   PetscReal      x1[3], x2[3], n[3], c[3], norm;
1570ccd2543fSMatthew G Knepley   const PetscInt dim = 3;
1571c871b86eSJed Brown   PetscInt       d, p;
1572ccd2543fSMatthew G Knepley 
1573ccd2543fSMatthew G Knepley   PetscFunctionBegin;
1574ccd2543fSMatthew G Knepley   /* 0) Calculate normal vector */
1575ccd2543fSMatthew G Knepley   for (d = 0; d < dim; ++d) {
15761ee9d5ecSMatthew G. Knepley     x1[d] = PetscRealPart(coords[1 * dim + d] - coords[0 * dim + d]);
15771ee9d5ecSMatthew G. Knepley     x2[d] = PetscRealPart(coords[2 * dim + d] - coords[0 * dim + d]);
1578ccd2543fSMatthew G Knepley   }
1579c871b86eSJed Brown   // n = x1 \otimes x2
1580ccd2543fSMatthew G Knepley   n[0] = x1[1] * x2[2] - x1[2] * x2[1];
1581ccd2543fSMatthew G Knepley   n[1] = x1[2] * x2[0] - x1[0] * x2[2];
1582ccd2543fSMatthew G Knepley   n[2] = x1[0] * x2[1] - x1[1] * x2[0];
15838b49ba18SBarry Smith   norm = PetscSqrtReal(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]);
1584c871b86eSJed Brown   for (d = 0; d < dim; d++) n[d] /= norm;
1585c871b86eSJed Brown   norm = PetscSqrtReal(x1[0] * x1[0] + x1[1] * x1[1] + x1[2] * x1[2]);
1586c871b86eSJed Brown   for (d = 0; d < dim; d++) x1[d] /= norm;
1587c871b86eSJed Brown   // x2 = n \otimes x1
1588c871b86eSJed Brown   x2[0] = n[1] * x1[2] - n[2] * x1[1];
1589c871b86eSJed Brown   x2[1] = n[2] * x1[0] - n[0] * x1[2];
1590c871b86eSJed Brown   x2[2] = n[0] * x1[1] - n[1] * x1[0];
1591c871b86eSJed Brown   for (d = 0; d < dim; d++) {
1592c871b86eSJed Brown     R[d * dim + 0] = x1[d];
1593c871b86eSJed Brown     R[d * dim + 1] = x2[d];
1594c871b86eSJed Brown     R[d * dim + 2] = n[d];
1595c871b86eSJed Brown     c[d]           = PetscRealPart(coords[0 * dim + d]);
159673868372SMatthew G. Knepley   }
1597c871b86eSJed Brown   for (p = 0; p < coordSize / dim; p++) {
1598c871b86eSJed Brown     PetscReal y[3];
1599c871b86eSJed Brown     for (d = 0; d < dim; d++) y[d] = PetscRealPart(coords[p * dim + d]) - c[d];
1600c871b86eSJed Brown     for (d = 0; d < 2; d++) coords[p * 2 + d] = R[0 * dim + d] * y[0] + R[1 * dim + d] * y[1] + R[2 * dim + d] * y[2];
16017f07f362SMatthew G. Knepley   }
16023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1603ccd2543fSMatthew G Knepley }
1604ccd2543fSMatthew G Knepley 
1605d71ae5a4SJacob Faibussowitsch PETSC_UNUSED static inline void Volume_Triangle_Internal(PetscReal *vol, PetscReal coords[])
1606d71ae5a4SJacob Faibussowitsch {
1607834e62ceSMatthew G. Knepley   /* Signed volume is 1/2 the determinant
1608834e62ceSMatthew G. Knepley 
1609834e62ceSMatthew G. Knepley    |  1  1  1 |
1610834e62ceSMatthew G. Knepley    | x0 x1 x2 |
1611834e62ceSMatthew G. Knepley    | y0 y1 y2 |
1612834e62ceSMatthew G. Knepley 
1613834e62ceSMatthew G. Knepley      but if x0,y0 is the origin, we have
1614834e62ceSMatthew G. Knepley 
1615834e62ceSMatthew G. Knepley    | x1 x2 |
1616834e62ceSMatthew G. Knepley    | y1 y2 |
1617834e62ceSMatthew G. Knepley   */
1618834e62ceSMatthew G. Knepley   const PetscReal x1 = coords[2] - coords[0], y1 = coords[3] - coords[1];
1619834e62ceSMatthew G. Knepley   const PetscReal x2 = coords[4] - coords[0], y2 = coords[5] - coords[1];
1620834e62ceSMatthew G. Knepley   PetscReal       M[4], detM;
16219371c9d4SSatish Balay   M[0] = x1;
16229371c9d4SSatish Balay   M[1] = x2;
16239371c9d4SSatish Balay   M[2] = y1;
16249371c9d4SSatish Balay   M[3] = y2;
1625923591dfSMatthew G. Knepley   DMPlex_Det2D_Internal(&detM, M);
1626834e62ceSMatthew G. Knepley   *vol = 0.5 * detM;
16273bc0b13bSBarry Smith   (void)PetscLogFlops(5.0);
1628834e62ceSMatthew G. Knepley }
1629834e62ceSMatthew G. Knepley 
1630d71ae5a4SJacob Faibussowitsch PETSC_UNUSED static inline void Volume_Tetrahedron_Internal(PetscReal *vol, PetscReal coords[])
1631d71ae5a4SJacob Faibussowitsch {
1632834e62ceSMatthew G. Knepley   /* Signed volume is 1/6th of the determinant
1633834e62ceSMatthew G. Knepley 
1634834e62ceSMatthew G. Knepley    |  1  1  1  1 |
1635834e62ceSMatthew G. Knepley    | x0 x1 x2 x3 |
1636834e62ceSMatthew G. Knepley    | y0 y1 y2 y3 |
1637834e62ceSMatthew G. Knepley    | z0 z1 z2 z3 |
1638834e62ceSMatthew G. Knepley 
1639834e62ceSMatthew G. Knepley      but if x0,y0,z0 is the origin, we have
1640834e62ceSMatthew G. Knepley 
1641834e62ceSMatthew G. Knepley    | x1 x2 x3 |
1642834e62ceSMatthew G. Knepley    | y1 y2 y3 |
1643834e62ceSMatthew G. Knepley    | z1 z2 z3 |
1644834e62ceSMatthew G. Knepley   */
1645834e62ceSMatthew G. Knepley   const PetscReal x1 = coords[3] - coords[0], y1 = coords[4] - coords[1], z1 = coords[5] - coords[2];
1646834e62ceSMatthew G. Knepley   const PetscReal x2 = coords[6] - coords[0], y2 = coords[7] - coords[1], z2 = coords[8] - coords[2];
1647834e62ceSMatthew G. Knepley   const PetscReal x3 = coords[9] - coords[0], y3 = coords[10] - coords[1], z3 = coords[11] - coords[2];
16480a3da2c2SToby Isaac   const PetscReal onesixth = ((PetscReal)1. / (PetscReal)6.);
1649834e62ceSMatthew G. Knepley   PetscReal       M[9], detM;
16509371c9d4SSatish Balay   M[0] = x1;
16519371c9d4SSatish Balay   M[1] = x2;
16529371c9d4SSatish Balay   M[2] = x3;
16539371c9d4SSatish Balay   M[3] = y1;
16549371c9d4SSatish Balay   M[4] = y2;
16559371c9d4SSatish Balay   M[5] = y3;
16569371c9d4SSatish Balay   M[6] = z1;
16579371c9d4SSatish Balay   M[7] = z2;
16589371c9d4SSatish Balay   M[8] = z3;
1659923591dfSMatthew G. Knepley   DMPlex_Det3D_Internal(&detM, M);
16600a3da2c2SToby Isaac   *vol = -onesixth * detM;
16613bc0b13bSBarry Smith   (void)PetscLogFlops(10.0);
1662834e62ceSMatthew G. Knepley }
1663834e62ceSMatthew G. Knepley 
1664d71ae5a4SJacob Faibussowitsch static inline void Volume_Tetrahedron_Origin_Internal(PetscReal *vol, PetscReal coords[])
1665d71ae5a4SJacob Faibussowitsch {
16660a3da2c2SToby Isaac   const PetscReal onesixth = ((PetscReal)1. / (PetscReal)6.);
1667923591dfSMatthew G. Knepley   DMPlex_Det3D_Internal(vol, coords);
16680a3da2c2SToby Isaac   *vol *= -onesixth;
16690ec8681fSMatthew G. Knepley }
16700ec8681fSMatthew G. Knepley 
1671d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputePointGeometry_Internal(DM dm, PetscInt e, PetscReal v0[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
1672d71ae5a4SJacob Faibussowitsch {
1673cb92db44SToby Isaac   PetscSection       coordSection;
1674cb92db44SToby Isaac   Vec                coordinates;
1675cb92db44SToby Isaac   const PetscScalar *coords;
1676cb92db44SToby Isaac   PetscInt           dim, d, off;
1677cb92db44SToby Isaac 
1678cb92db44SToby Isaac   PetscFunctionBegin;
16799566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
16809566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateSection(dm, &coordSection));
16819566063dSJacob Faibussowitsch   PetscCall(PetscSectionGetDof(coordSection, e, &dim));
16823ba16761SJacob Faibussowitsch   if (!dim) PetscFunctionReturn(PETSC_SUCCESS);
16839566063dSJacob Faibussowitsch   PetscCall(PetscSectionGetOffset(coordSection, e, &off));
16849566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(coordinates, &coords));
16859371c9d4SSatish Balay   if (v0) {
16869371c9d4SSatish Balay     for (d = 0; d < dim; d++) v0[d] = PetscRealPart(coords[off + d]);
16879371c9d4SSatish Balay   }
16889566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(coordinates, &coords));
1689cb92db44SToby Isaac   *detJ = 1.;
1690cb92db44SToby Isaac   if (J) {
1691cb92db44SToby Isaac     for (d = 0; d < dim * dim; d++) J[d] = 0.;
1692cb92db44SToby Isaac     for (d = 0; d < dim; d++) J[d * dim + d] = 1.;
1693cb92db44SToby Isaac     if (invJ) {
1694cb92db44SToby Isaac       for (d = 0; d < dim * dim; d++) invJ[d] = 0.;
1695cb92db44SToby Isaac       for (d = 0; d < dim; d++) invJ[d * dim + d] = 1.;
1696cb92db44SToby Isaac     }
1697cb92db44SToby Isaac   }
16983ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1699cb92db44SToby Isaac }
1700cb92db44SToby Isaac 
17016858538eSMatthew G. Knepley /*@C
17026858538eSMatthew G. Knepley   DMPlexGetCellCoordinates - Get coordinates for a cell, taking into account periodicity
17036858538eSMatthew G. Knepley 
170420f4b53cSBarry Smith   Not Collective
17056858538eSMatthew G. Knepley 
17066858538eSMatthew G. Knepley   Input Parameters:
170720f4b53cSBarry Smith + dm   - The `DMPLEX`
17086858538eSMatthew G. Knepley - cell - The cell number
17096858538eSMatthew G. Knepley 
17106858538eSMatthew G. Knepley   Output Parameters:
17116858538eSMatthew G. Knepley + isDG   - Using cellwise coordinates
17126858538eSMatthew G. Knepley . Nc     - The number of coordinates
17136858538eSMatthew G. Knepley . array  - The coordinate array
17146858538eSMatthew G. Knepley - coords - The cell coordinates
17156858538eSMatthew G. Knepley 
17166858538eSMatthew G. Knepley   Level: developer
17176858538eSMatthew G. Knepley 
171820f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexRestoreCellCoordinates()`, `DMGetCoordinatesLocal()`, `DMGetCellCoordinatesLocal()`
17196858538eSMatthew G. Knepley @*/
1720d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexGetCellCoordinates(DM dm, PetscInt cell, PetscBool *isDG, PetscInt *Nc, const PetscScalar *array[], PetscScalar *coords[])
1721d71ae5a4SJacob Faibussowitsch {
17226858538eSMatthew G. Knepley   DM                 cdm;
17236858538eSMatthew G. Knepley   Vec                coordinates;
17246858538eSMatthew G. Knepley   PetscSection       cs;
17256858538eSMatthew G. Knepley   const PetscScalar *ccoords;
17266858538eSMatthew G. Knepley   PetscInt           pStart, pEnd;
17276858538eSMatthew G. Knepley 
17286858538eSMatthew G. Knepley   PetscFunctionBeginHot;
17296858538eSMatthew G. Knepley   *isDG   = PETSC_FALSE;
17306858538eSMatthew G. Knepley   *Nc     = 0;
17316858538eSMatthew G. Knepley   *array  = NULL;
17326858538eSMatthew G. Knepley   *coords = NULL;
17336858538eSMatthew G. Knepley   /* Check for cellwise coordinates */
17346858538eSMatthew G. Knepley   PetscCall(DMGetCellCoordinateSection(dm, &cs));
17356858538eSMatthew G. Knepley   if (!cs) goto cg;
17366858538eSMatthew G. Knepley   /* Check that the cell exists in the cellwise section */
17376858538eSMatthew G. Knepley   PetscCall(PetscSectionGetChart(cs, &pStart, &pEnd));
17386858538eSMatthew G. Knepley   if (cell < pStart || cell >= pEnd) goto cg;
17396858538eSMatthew G. Knepley   /* Check for cellwise coordinates for this cell */
17406858538eSMatthew G. Knepley   PetscCall(PetscSectionGetDof(cs, cell, Nc));
17416858538eSMatthew G. Knepley   if (!*Nc) goto cg;
17426858538eSMatthew G. Knepley   /* Check for cellwise coordinates */
17436858538eSMatthew G. Knepley   PetscCall(DMGetCellCoordinatesLocalNoncollective(dm, &coordinates));
17446858538eSMatthew G. Knepley   if (!coordinates) goto cg;
17456858538eSMatthew G. Knepley   /* Get cellwise coordinates */
17466858538eSMatthew G. Knepley   PetscCall(DMGetCellCoordinateDM(dm, &cdm));
17476858538eSMatthew G. Knepley   PetscCall(VecGetArrayRead(coordinates, array));
17486858538eSMatthew G. Knepley   PetscCall(DMPlexPointLocalRead(cdm, cell, *array, &ccoords));
17496858538eSMatthew G. Knepley   PetscCall(DMGetWorkArray(cdm, *Nc, MPIU_SCALAR, coords));
17506858538eSMatthew G. Knepley   PetscCall(PetscArraycpy(*coords, ccoords, *Nc));
17516858538eSMatthew G. Knepley   PetscCall(VecRestoreArrayRead(coordinates, array));
17526858538eSMatthew G. Knepley   *isDG = PETSC_TRUE;
17533ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
17546858538eSMatthew G. Knepley cg:
17556858538eSMatthew G. Knepley   /* Use continuous coordinates */
17566858538eSMatthew G. Knepley   PetscCall(DMGetCoordinateDM(dm, &cdm));
17576858538eSMatthew G. Knepley   PetscCall(DMGetCoordinateSection(dm, &cs));
17586858538eSMatthew G. Knepley   PetscCall(DMGetCoordinatesLocalNoncollective(dm, &coordinates));
1759e8e188d2SZach Atkins   PetscCall(DMPlexVecGetOrientedClosure_Internal(cdm, cs, PETSC_FALSE, coordinates, cell, 0, Nc, coords));
17603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
17616858538eSMatthew G. Knepley }
17626858538eSMatthew G. Knepley 
17636858538eSMatthew G. Knepley /*@C
17646858538eSMatthew G. Knepley   DMPlexRestoreCellCoordinates - Get coordinates for a cell, taking into account periodicity
17656858538eSMatthew G. Knepley 
176620f4b53cSBarry Smith   Not Collective
17676858538eSMatthew G. Knepley 
17686858538eSMatthew G. Knepley   Input Parameters:
176920f4b53cSBarry Smith + dm   - The `DMPLEX`
17706858538eSMatthew G. Knepley - cell - The cell number
17716858538eSMatthew G. Knepley 
17726858538eSMatthew G. Knepley   Output Parameters:
17736858538eSMatthew G. Knepley + isDG   - Using cellwise coordinates
17746858538eSMatthew G. Knepley . Nc     - The number of coordinates
17756858538eSMatthew G. Knepley . array  - The coordinate array
17766858538eSMatthew G. Knepley - coords - The cell coordinates
17776858538eSMatthew G. Knepley 
17786858538eSMatthew G. Knepley   Level: developer
17796858538eSMatthew G. Knepley 
178020f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexGetCellCoordinates()`, `DMGetCoordinatesLocal()`, `DMGetCellCoordinatesLocal()`
17816858538eSMatthew G. Knepley @*/
1782d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexRestoreCellCoordinates(DM dm, PetscInt cell, PetscBool *isDG, PetscInt *Nc, const PetscScalar *array[], PetscScalar *coords[])
1783d71ae5a4SJacob Faibussowitsch {
17846858538eSMatthew G. Knepley   DM           cdm;
17856858538eSMatthew G. Knepley   PetscSection cs;
17866858538eSMatthew G. Knepley   Vec          coordinates;
17876858538eSMatthew G. Knepley 
17886858538eSMatthew G. Knepley   PetscFunctionBeginHot;
17896858538eSMatthew G. Knepley   if (*isDG) {
17906858538eSMatthew G. Knepley     PetscCall(DMGetCellCoordinateDM(dm, &cdm));
17916858538eSMatthew G. Knepley     PetscCall(DMRestoreWorkArray(cdm, *Nc, MPIU_SCALAR, coords));
17926858538eSMatthew G. Knepley   } else {
17936858538eSMatthew G. Knepley     PetscCall(DMGetCoordinateDM(dm, &cdm));
17946858538eSMatthew G. Knepley     PetscCall(DMGetCoordinateSection(dm, &cs));
17956858538eSMatthew G. Knepley     PetscCall(DMGetCoordinatesLocalNoncollective(dm, &coordinates));
1796835f2295SStefano Zampini     PetscCall(DMPlexVecRestoreClosure(cdm, cs, coordinates, cell, Nc, coords));
17976858538eSMatthew G. Knepley   }
17983ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
17996858538eSMatthew G. Knepley }
18006858538eSMatthew G. Knepley 
1801d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeLineGeometry_Internal(DM dm, PetscInt e, PetscReal v0[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
1802d71ae5a4SJacob Faibussowitsch {
18036858538eSMatthew G. Knepley   const PetscScalar *array;
1804a1e44745SMatthew G. Knepley   PetscScalar       *coords = NULL;
18056858538eSMatthew G. Knepley   PetscInt           numCoords, d;
18066858538eSMatthew G. Knepley   PetscBool          isDG;
180717fe8556SMatthew G. Knepley 
180817fe8556SMatthew G. Knepley   PetscFunctionBegin;
18096858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
181008401ef6SPierre Jolivet   PetscCheck(!invJ || J, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "In order to compute invJ, J must not be NULL");
18117f07f362SMatthew G. Knepley   *detJ = 0.0;
181228dbe442SToby Isaac   if (numCoords == 6) {
181328dbe442SToby Isaac     const PetscInt dim = 3;
181428dbe442SToby Isaac     PetscReal      R[9], J0;
181528dbe442SToby Isaac 
18169371c9d4SSatish Balay     if (v0) {
18179371c9d4SSatish Balay       for (d = 0; d < dim; d++) v0[d] = PetscRealPart(coords[d]);
18189371c9d4SSatish Balay     }
18199566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeProjection3Dto1D(coords, R));
182028dbe442SToby Isaac     if (J) {
182128dbe442SToby Isaac       J0   = 0.5 * PetscRealPart(coords[1]);
18229371c9d4SSatish Balay       J[0] = R[0] * J0;
18239371c9d4SSatish Balay       J[1] = R[1];
18249371c9d4SSatish Balay       J[2] = R[2];
18259371c9d4SSatish Balay       J[3] = R[3] * J0;
18269371c9d4SSatish Balay       J[4] = R[4];
18279371c9d4SSatish Balay       J[5] = R[5];
18289371c9d4SSatish Balay       J[6] = R[6] * J0;
18299371c9d4SSatish Balay       J[7] = R[7];
18309371c9d4SSatish Balay       J[8] = R[8];
183128dbe442SToby Isaac       DMPlex_Det3D_Internal(detJ, J);
18322b6f951bSStefano Zampini       if (invJ) DMPlex_Invert3D_Internal(invJ, J, *detJ);
1833adac9986SMatthew G. Knepley     }
183428dbe442SToby Isaac   } else if (numCoords == 4) {
18357f07f362SMatthew G. Knepley     const PetscInt dim = 2;
18367f07f362SMatthew G. Knepley     PetscReal      R[4], J0;
18377f07f362SMatthew G. Knepley 
18389371c9d4SSatish Balay     if (v0) {
18399371c9d4SSatish Balay       for (d = 0; d < dim; d++) v0[d] = PetscRealPart(coords[d]);
18409371c9d4SSatish Balay     }
18419566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeProjection2Dto1D(coords, R));
184217fe8556SMatthew G. Knepley     if (J) {
18437f07f362SMatthew G. Knepley       J0   = 0.5 * PetscRealPart(coords[1]);
18449371c9d4SSatish Balay       J[0] = R[0] * J0;
18459371c9d4SSatish Balay       J[1] = R[1];
18469371c9d4SSatish Balay       J[2] = R[2] * J0;
18479371c9d4SSatish Balay       J[3] = R[3];
1848923591dfSMatthew G. Knepley       DMPlex_Det2D_Internal(detJ, J);
1849ad540459SPierre Jolivet       if (invJ) DMPlex_Invert2D_Internal(invJ, J, *detJ);
1850adac9986SMatthew G. Knepley     }
18517f07f362SMatthew G. Knepley   } else if (numCoords == 2) {
18527f07f362SMatthew G. Knepley     const PetscInt dim = 1;
18537f07f362SMatthew G. Knepley 
18549371c9d4SSatish Balay     if (v0) {
18559371c9d4SSatish Balay       for (d = 0; d < dim; d++) v0[d] = PetscRealPart(coords[d]);
18569371c9d4SSatish Balay     }
18577f07f362SMatthew G. Knepley     if (J) {
18587f07f362SMatthew G. Knepley       J[0]  = 0.5 * (PetscRealPart(coords[1]) - PetscRealPart(coords[0]));
185917fe8556SMatthew G. Knepley       *detJ = J[0];
18609566063dSJacob Faibussowitsch       PetscCall(PetscLogFlops(2.0));
18619371c9d4SSatish Balay       if (invJ) {
18629371c9d4SSatish Balay         invJ[0] = 1.0 / J[0];
18639371c9d4SSatish Balay         PetscCall(PetscLogFlops(1.0));
18649371c9d4SSatish Balay       }
1865adac9986SMatthew G. Knepley     }
18666858538eSMatthew G. Knepley   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The number of coordinates for segment %" PetscInt_FMT " is %" PetscInt_FMT " != 2 or 4 or 6", e, numCoords);
18676858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
18683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
186917fe8556SMatthew G. Knepley }
187017fe8556SMatthew G. Knepley 
1871d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeTriangleGeometry_Internal(DM dm, PetscInt e, PetscReal v0[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
1872d71ae5a4SJacob Faibussowitsch {
18736858538eSMatthew G. Knepley   const PetscScalar *array;
1874a1e44745SMatthew G. Knepley   PetscScalar       *coords = NULL;
18756858538eSMatthew G. Knepley   PetscInt           numCoords, d;
18766858538eSMatthew G. Knepley   PetscBool          isDG;
1877ccd2543fSMatthew G Knepley 
1878ccd2543fSMatthew G Knepley   PetscFunctionBegin;
18796858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
18806858538eSMatthew G. Knepley   PetscCheck(!invJ || J, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "In order to compute invJ, J must not be NULL");
18817f07f362SMatthew G. Knepley   *detJ = 0.0;
1882ccd2543fSMatthew G Knepley   if (numCoords == 9) {
18837f07f362SMatthew G. Knepley     const PetscInt dim = 3;
18847f07f362SMatthew G. Knepley     PetscReal      R[9], J0[9] = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0};
18857f07f362SMatthew G. Knepley 
18869371c9d4SSatish Balay     if (v0) {
18879371c9d4SSatish Balay       for (d = 0; d < dim; d++) v0[d] = PetscRealPart(coords[d]);
18889371c9d4SSatish Balay     }
18899566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeProjection3Dto2D(numCoords, coords, R));
18907f07f362SMatthew G. Knepley     if (J) {
1891b7ad821dSMatthew G. Knepley       const PetscInt pdim = 2;
1892b7ad821dSMatthew G. Knepley 
1893b7ad821dSMatthew G. Knepley       for (d = 0; d < pdim; d++) {
1894ad540459SPierre Jolivet         for (PetscInt f = 0; f < pdim; f++) J0[d * dim + f] = 0.5 * (PetscRealPart(coords[(f + 1) * pdim + d]) - PetscRealPart(coords[0 * pdim + d]));
18957f07f362SMatthew G. Knepley       }
18969566063dSJacob Faibussowitsch       PetscCall(PetscLogFlops(8.0));
1897923591dfSMatthew G. Knepley       DMPlex_Det3D_Internal(detJ, J0);
18987f07f362SMatthew G. Knepley       for (d = 0; d < dim; d++) {
18996858538eSMatthew G. Knepley         for (PetscInt f = 0; f < dim; f++) {
19007f07f362SMatthew G. Knepley           J[d * dim + f] = 0.0;
1901ad540459SPierre Jolivet           for (PetscInt g = 0; g < dim; g++) J[d * dim + f] += R[d * dim + g] * J0[g * dim + f];
19027f07f362SMatthew G. Knepley         }
19037f07f362SMatthew G. Knepley       }
19049566063dSJacob Faibussowitsch       PetscCall(PetscLogFlops(18.0));
19057f07f362SMatthew G. Knepley     }
1906ad540459SPierre Jolivet     if (invJ) DMPlex_Invert3D_Internal(invJ, J, *detJ);
19077f07f362SMatthew G. Knepley   } else if (numCoords == 6) {
19087f07f362SMatthew G. Knepley     const PetscInt dim = 2;
19097f07f362SMatthew G. Knepley 
19109371c9d4SSatish Balay     if (v0) {
19119371c9d4SSatish Balay       for (d = 0; d < dim; d++) v0[d] = PetscRealPart(coords[d]);
19129371c9d4SSatish Balay     }
1913ccd2543fSMatthew G Knepley     if (J) {
1914ccd2543fSMatthew G Knepley       for (d = 0; d < dim; d++) {
1915ad540459SPierre Jolivet         for (PetscInt f = 0; f < dim; f++) J[d * dim + f] = 0.5 * (PetscRealPart(coords[(f + 1) * dim + d]) - PetscRealPart(coords[0 * dim + d]));
1916ccd2543fSMatthew G Knepley       }
19179566063dSJacob Faibussowitsch       PetscCall(PetscLogFlops(8.0));
1918923591dfSMatthew G. Knepley       DMPlex_Det2D_Internal(detJ, J);
1919ccd2543fSMatthew G Knepley     }
1920ad540459SPierre Jolivet     if (invJ) DMPlex_Invert2D_Internal(invJ, J, *detJ);
192163a3b9bcSJacob Faibussowitsch   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The number of coordinates for this triangle is %" PetscInt_FMT " != 6 or 9", numCoords);
19226858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
19233ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1924ccd2543fSMatthew G Knepley }
1925ccd2543fSMatthew G Knepley 
1926d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeRectangleGeometry_Internal(DM dm, PetscInt e, PetscBool isTensor, PetscInt Nq, const PetscReal points[], PetscReal v[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
1927d71ae5a4SJacob Faibussowitsch {
19286858538eSMatthew G. Knepley   const PetscScalar *array;
1929a1e44745SMatthew G. Knepley   PetscScalar       *coords = NULL;
19306858538eSMatthew G. Knepley   PetscInt           numCoords, d;
19316858538eSMatthew G. Knepley   PetscBool          isDG;
1932ccd2543fSMatthew G Knepley 
1933ccd2543fSMatthew G Knepley   PetscFunctionBegin;
19346858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
19356858538eSMatthew G. Knepley   PetscCheck(!invJ || J, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "In order to compute invJ, J must not be NULL");
1936dfccc68fSToby Isaac   if (!Nq) {
1937412e9a14SMatthew G. Knepley     PetscInt vorder[4] = {0, 1, 2, 3};
1938412e9a14SMatthew G. Knepley 
19399371c9d4SSatish Balay     if (isTensor) {
19409371c9d4SSatish Balay       vorder[2] = 3;
19419371c9d4SSatish Balay       vorder[3] = 2;
19429371c9d4SSatish Balay     }
19437f07f362SMatthew G. Knepley     *detJ = 0.0;
194499dec3a6SMatthew G. Knepley     if (numCoords == 12) {
194599dec3a6SMatthew G. Knepley       const PetscInt dim = 3;
194699dec3a6SMatthew G. Knepley       PetscReal      R[9], J0[9] = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0};
194799dec3a6SMatthew G. Knepley 
19489371c9d4SSatish Balay       if (v) {
19499371c9d4SSatish Balay         for (d = 0; d < dim; d++) v[d] = PetscRealPart(coords[d]);
19509371c9d4SSatish Balay       }
19519566063dSJacob Faibussowitsch       PetscCall(DMPlexComputeProjection3Dto2D(numCoords, coords, R));
195299dec3a6SMatthew G. Knepley       if (J) {
195399dec3a6SMatthew G. Knepley         const PetscInt pdim = 2;
195499dec3a6SMatthew G. Knepley 
195599dec3a6SMatthew G. Knepley         for (d = 0; d < pdim; d++) {
1956412e9a14SMatthew G. Knepley           J0[d * dim + 0] = 0.5 * (PetscRealPart(coords[vorder[1] * pdim + d]) - PetscRealPart(coords[vorder[0] * pdim + d]));
1957412e9a14SMatthew G. Knepley           J0[d * dim + 1] = 0.5 * (PetscRealPart(coords[vorder[2] * pdim + d]) - PetscRealPart(coords[vorder[1] * pdim + d]));
195899dec3a6SMatthew G. Knepley         }
19599566063dSJacob Faibussowitsch         PetscCall(PetscLogFlops(8.0));
1960923591dfSMatthew G. Knepley         DMPlex_Det3D_Internal(detJ, J0);
196199dec3a6SMatthew G. Knepley         for (d = 0; d < dim; d++) {
19626858538eSMatthew G. Knepley           for (PetscInt f = 0; f < dim; f++) {
196399dec3a6SMatthew G. Knepley             J[d * dim + f] = 0.0;
1964ad540459SPierre Jolivet             for (PetscInt g = 0; g < dim; g++) J[d * dim + f] += R[d * dim + g] * J0[g * dim + f];
196599dec3a6SMatthew G. Knepley           }
196699dec3a6SMatthew G. Knepley         }
19679566063dSJacob Faibussowitsch         PetscCall(PetscLogFlops(18.0));
196899dec3a6SMatthew G. Knepley       }
1969ad540459SPierre Jolivet       if (invJ) DMPlex_Invert3D_Internal(invJ, J, *detJ);
197071f58de1SToby Isaac     } else if (numCoords == 8) {
197199dec3a6SMatthew G. Knepley       const PetscInt dim = 2;
197299dec3a6SMatthew G. Knepley 
19739371c9d4SSatish Balay       if (v) {
19749371c9d4SSatish Balay         for (d = 0; d < dim; d++) v[d] = PetscRealPart(coords[d]);
19759371c9d4SSatish Balay       }
1976ccd2543fSMatthew G Knepley       if (J) {
1977ccd2543fSMatthew G Knepley         for (d = 0; d < dim; d++) {
1978412e9a14SMatthew G. Knepley           J[d * dim + 0] = 0.5 * (PetscRealPart(coords[vorder[1] * dim + d]) - PetscRealPart(coords[vorder[0] * dim + d]));
1979412e9a14SMatthew G. Knepley           J[d * dim + 1] = 0.5 * (PetscRealPart(coords[vorder[3] * dim + d]) - PetscRealPart(coords[vorder[0] * dim + d]));
1980ccd2543fSMatthew G Knepley         }
19819566063dSJacob Faibussowitsch         PetscCall(PetscLogFlops(8.0));
1982923591dfSMatthew G. Knepley         DMPlex_Det2D_Internal(detJ, J);
1983ccd2543fSMatthew G Knepley       }
1984ad540459SPierre Jolivet       if (invJ) DMPlex_Invert2D_Internal(invJ, J, *detJ);
198563a3b9bcSJacob Faibussowitsch     } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The number of coordinates for this quadrilateral is %" PetscInt_FMT " != 8 or 12", numCoords);
1986dfccc68fSToby Isaac   } else {
1987dfccc68fSToby Isaac     const PetscInt Nv         = 4;
1988dfccc68fSToby Isaac     const PetscInt dimR       = 2;
1989412e9a14SMatthew G. Knepley     PetscInt       zToPlex[4] = {0, 1, 3, 2};
1990dfccc68fSToby Isaac     PetscReal      zOrder[12];
1991dfccc68fSToby Isaac     PetscReal      zCoeff[12];
1992dfccc68fSToby Isaac     PetscInt       i, j, k, l, dim;
1993dfccc68fSToby Isaac 
19949371c9d4SSatish Balay     if (isTensor) {
19959371c9d4SSatish Balay       zToPlex[2] = 2;
19969371c9d4SSatish Balay       zToPlex[3] = 3;
19979371c9d4SSatish Balay     }
1998dfccc68fSToby Isaac     if (numCoords == 12) {
1999dfccc68fSToby Isaac       dim = 3;
2000dfccc68fSToby Isaac     } else if (numCoords == 8) {
2001dfccc68fSToby Isaac       dim = 2;
200263a3b9bcSJacob Faibussowitsch     } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The number of coordinates for this quadrilateral is %" PetscInt_FMT " != 8 or 12", numCoords);
2003dfccc68fSToby Isaac     for (i = 0; i < Nv; i++) {
2004dfccc68fSToby Isaac       PetscInt zi = zToPlex[i];
2005dfccc68fSToby Isaac 
2006ad540459SPierre Jolivet       for (j = 0; j < dim; j++) zOrder[dim * i + j] = PetscRealPart(coords[dim * zi + j]);
2007dfccc68fSToby Isaac     }
2008dfccc68fSToby Isaac     for (j = 0; j < dim; j++) {
20092df84da0SMatthew G. Knepley       /* Nodal basis for evaluation at the vertices: (1 \mp xi) (1 \mp eta):
20102df84da0SMatthew G. Knepley            \phi^0 = (1 - xi - eta + xi eta) --> 1      = 1/4 ( \phi^0 + \phi^1 + \phi^2 + \phi^3)
20112df84da0SMatthew G. Knepley            \phi^1 = (1 + xi - eta - xi eta) --> xi     = 1/4 (-\phi^0 + \phi^1 - \phi^2 + \phi^3)
20122df84da0SMatthew G. Knepley            \phi^2 = (1 - xi + eta - xi eta) --> eta    = 1/4 (-\phi^0 - \phi^1 + \phi^2 + \phi^3)
20132df84da0SMatthew G. Knepley            \phi^3 = (1 + xi + eta + xi eta) --> xi eta = 1/4 ( \phi^0 - \phi^1 - \phi^2 + \phi^3)
20142df84da0SMatthew G. Knepley       */
2015dfccc68fSToby Isaac       zCoeff[dim * 0 + j] = 0.25 * (zOrder[dim * 0 + j] + zOrder[dim * 1 + j] + zOrder[dim * 2 + j] + zOrder[dim * 3 + j]);
2016dfccc68fSToby Isaac       zCoeff[dim * 1 + j] = 0.25 * (-zOrder[dim * 0 + j] + zOrder[dim * 1 + j] - zOrder[dim * 2 + j] + zOrder[dim * 3 + j]);
2017dfccc68fSToby Isaac       zCoeff[dim * 2 + j] = 0.25 * (-zOrder[dim * 0 + j] - zOrder[dim * 1 + j] + zOrder[dim * 2 + j] + zOrder[dim * 3 + j]);
2018dfccc68fSToby Isaac       zCoeff[dim * 3 + j] = 0.25 * (zOrder[dim * 0 + j] - zOrder[dim * 1 + j] - zOrder[dim * 2 + j] + zOrder[dim * 3 + j]);
2019dfccc68fSToby Isaac     }
2020dfccc68fSToby Isaac     for (i = 0; i < Nq; i++) {
2021dfccc68fSToby Isaac       PetscReal xi = points[dimR * i], eta = points[dimR * i + 1];
2022dfccc68fSToby Isaac 
2023dfccc68fSToby Isaac       if (v) {
2024dfccc68fSToby Isaac         PetscReal extPoint[4];
2025dfccc68fSToby Isaac 
2026dfccc68fSToby Isaac         extPoint[0] = 1.;
2027dfccc68fSToby Isaac         extPoint[1] = xi;
2028dfccc68fSToby Isaac         extPoint[2] = eta;
2029dfccc68fSToby Isaac         extPoint[3] = xi * eta;
2030dfccc68fSToby Isaac         for (j = 0; j < dim; j++) {
2031dfccc68fSToby Isaac           PetscReal val = 0.;
2032dfccc68fSToby Isaac 
2033ad540459SPierre Jolivet           for (k = 0; k < Nv; k++) val += extPoint[k] * zCoeff[dim * k + j];
2034dfccc68fSToby Isaac           v[i * dim + j] = val;
2035dfccc68fSToby Isaac         }
2036dfccc68fSToby Isaac       }
2037dfccc68fSToby Isaac       if (J) {
2038dfccc68fSToby Isaac         PetscReal extJ[8];
2039dfccc68fSToby Isaac 
2040dfccc68fSToby Isaac         extJ[0] = 0.;
2041dfccc68fSToby Isaac         extJ[1] = 0.;
2042dfccc68fSToby Isaac         extJ[2] = 1.;
2043dfccc68fSToby Isaac         extJ[3] = 0.;
2044dfccc68fSToby Isaac         extJ[4] = 0.;
2045dfccc68fSToby Isaac         extJ[5] = 1.;
2046dfccc68fSToby Isaac         extJ[6] = eta;
2047dfccc68fSToby Isaac         extJ[7] = xi;
2048dfccc68fSToby Isaac         for (j = 0; j < dim; j++) {
2049dfccc68fSToby Isaac           for (k = 0; k < dimR; k++) {
2050dfccc68fSToby Isaac             PetscReal val = 0.;
2051dfccc68fSToby Isaac 
2052ad540459SPierre Jolivet             for (l = 0; l < Nv; l++) val += zCoeff[dim * l + j] * extJ[dimR * l + k];
2053dfccc68fSToby Isaac             J[i * dim * dim + dim * j + k] = val;
2054dfccc68fSToby Isaac           }
2055dfccc68fSToby Isaac         }
2056dfccc68fSToby Isaac         if (dim == 3) { /* put the cross product in the third component of the Jacobian */
2057dfccc68fSToby Isaac           PetscReal  x, y, z;
2058dfccc68fSToby Isaac           PetscReal *iJ = &J[i * dim * dim];
2059dfccc68fSToby Isaac           PetscReal  norm;
2060dfccc68fSToby Isaac 
2061dfccc68fSToby Isaac           x     = iJ[1 * dim + 0] * iJ[2 * dim + 1] - iJ[1 * dim + 1] * iJ[2 * dim + 0];
2062dfccc68fSToby Isaac           y     = iJ[0 * dim + 1] * iJ[2 * dim + 0] - iJ[0 * dim + 0] * iJ[2 * dim + 1];
2063dfccc68fSToby Isaac           z     = iJ[0 * dim + 0] * iJ[1 * dim + 1] - iJ[0 * dim + 1] * iJ[1 * dim + 0];
2064dfccc68fSToby Isaac           norm  = PetscSqrtReal(x * x + y * y + z * z);
2065dfccc68fSToby Isaac           iJ[2] = x / norm;
2066dfccc68fSToby Isaac           iJ[5] = y / norm;
2067dfccc68fSToby Isaac           iJ[8] = z / norm;
2068dfccc68fSToby Isaac           DMPlex_Det3D_Internal(&detJ[i], &J[i * dim * dim]);
2069ad540459SPierre Jolivet           if (invJ) DMPlex_Invert3D_Internal(&invJ[i * dim * dim], &J[i * dim * dim], detJ[i]);
2070dfccc68fSToby Isaac         } else {
2071dfccc68fSToby Isaac           DMPlex_Det2D_Internal(&detJ[i], &J[i * dim * dim]);
2072ad540459SPierre Jolivet           if (invJ) DMPlex_Invert2D_Internal(&invJ[i * dim * dim], &J[i * dim * dim], detJ[i]);
2073dfccc68fSToby Isaac         }
2074dfccc68fSToby Isaac       }
2075dfccc68fSToby Isaac     }
2076dfccc68fSToby Isaac   }
20776858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
20783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2079ccd2543fSMatthew G Knepley }
2080ccd2543fSMatthew G Knepley 
2081d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeTetrahedronGeometry_Internal(DM dm, PetscInt e, PetscReal v0[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
2082d71ae5a4SJacob Faibussowitsch {
20836858538eSMatthew G. Knepley   const PetscScalar *array;
2084a1e44745SMatthew G. Knepley   PetscScalar       *coords = NULL;
2085ccd2543fSMatthew G Knepley   const PetscInt     dim    = 3;
20866858538eSMatthew G. Knepley   PetscInt           numCoords, d;
20876858538eSMatthew G. Knepley   PetscBool          isDG;
2088ccd2543fSMatthew G Knepley 
2089ccd2543fSMatthew G Knepley   PetscFunctionBegin;
20906858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
20916858538eSMatthew G. Knepley   PetscCheck(!invJ || J, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "In order to compute invJ, J must not be NULL");
20927f07f362SMatthew G. Knepley   *detJ = 0.0;
20939371c9d4SSatish Balay   if (v0) {
20949371c9d4SSatish Balay     for (d = 0; d < dim; d++) v0[d] = PetscRealPart(coords[d]);
20959371c9d4SSatish Balay   }
2096ccd2543fSMatthew G Knepley   if (J) {
2097ccd2543fSMatthew G Knepley     for (d = 0; d < dim; d++) {
2098f0df753eSMatthew G. Knepley       /* I orient with outward face normals */
2099f0df753eSMatthew G. Knepley       J[d * dim + 0] = 0.5 * (PetscRealPart(coords[2 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
2100f0df753eSMatthew G. Knepley       J[d * dim + 1] = 0.5 * (PetscRealPart(coords[1 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
2101f0df753eSMatthew G. Knepley       J[d * dim + 2] = 0.5 * (PetscRealPart(coords[3 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
2102ccd2543fSMatthew G Knepley     }
21039566063dSJacob Faibussowitsch     PetscCall(PetscLogFlops(18.0));
2104923591dfSMatthew G. Knepley     DMPlex_Det3D_Internal(detJ, J);
2105ccd2543fSMatthew G Knepley   }
2106ad540459SPierre Jolivet   if (invJ) DMPlex_Invert3D_Internal(invJ, J, *detJ);
21076858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
21083ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2109ccd2543fSMatthew G Knepley }
2110ccd2543fSMatthew G Knepley 
2111d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeHexahedronGeometry_Internal(DM dm, PetscInt e, PetscInt Nq, const PetscReal points[], PetscReal v[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
2112d71ae5a4SJacob Faibussowitsch {
21136858538eSMatthew G. Knepley   const PetscScalar *array;
2114a1e44745SMatthew G. Knepley   PetscScalar       *coords = NULL;
2115ccd2543fSMatthew G Knepley   const PetscInt     dim    = 3;
21166858538eSMatthew G. Knepley   PetscInt           numCoords, d;
21176858538eSMatthew G. Knepley   PetscBool          isDG;
2118ccd2543fSMatthew G Knepley 
2119ccd2543fSMatthew G Knepley   PetscFunctionBegin;
21206858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
21216858538eSMatthew G. Knepley   PetscCheck(!invJ || J, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "In order to compute invJ, J must not be NULL");
2122dfccc68fSToby Isaac   if (!Nq) {
21237f07f362SMatthew G. Knepley     *detJ = 0.0;
21249371c9d4SSatish Balay     if (v) {
21259371c9d4SSatish Balay       for (d = 0; d < dim; d++) v[d] = PetscRealPart(coords[d]);
21269371c9d4SSatish Balay     }
2127ccd2543fSMatthew G Knepley     if (J) {
2128ccd2543fSMatthew G Knepley       for (d = 0; d < dim; d++) {
2129f0df753eSMatthew G. Knepley         J[d * dim + 0] = 0.5 * (PetscRealPart(coords[3 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
2130f0df753eSMatthew G. Knepley         J[d * dim + 1] = 0.5 * (PetscRealPart(coords[1 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
2131f0df753eSMatthew G. Knepley         J[d * dim + 2] = 0.5 * (PetscRealPart(coords[4 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
2132ccd2543fSMatthew G Knepley       }
21339566063dSJacob Faibussowitsch       PetscCall(PetscLogFlops(18.0));
2134923591dfSMatthew G. Knepley       DMPlex_Det3D_Internal(detJ, J);
2135ccd2543fSMatthew G Knepley     }
2136ad540459SPierre Jolivet     if (invJ) DMPlex_Invert3D_Internal(invJ, J, *detJ);
2137dfccc68fSToby Isaac   } else {
2138dfccc68fSToby Isaac     const PetscInt Nv         = 8;
2139dfccc68fSToby Isaac     const PetscInt zToPlex[8] = {0, 3, 1, 2, 4, 5, 7, 6};
2140dfccc68fSToby Isaac     const PetscInt dim        = 3;
2141dfccc68fSToby Isaac     const PetscInt dimR       = 3;
2142dfccc68fSToby Isaac     PetscReal      zOrder[24];
2143dfccc68fSToby Isaac     PetscReal      zCoeff[24];
2144dfccc68fSToby Isaac     PetscInt       i, j, k, l;
2145dfccc68fSToby Isaac 
2146dfccc68fSToby Isaac     for (i = 0; i < Nv; i++) {
2147dfccc68fSToby Isaac       PetscInt zi = zToPlex[i];
2148dfccc68fSToby Isaac 
2149ad540459SPierre Jolivet       for (j = 0; j < dim; j++) zOrder[dim * i + j] = PetscRealPart(coords[dim * zi + j]);
2150dfccc68fSToby Isaac     }
2151dfccc68fSToby Isaac     for (j = 0; j < dim; j++) {
2152dfccc68fSToby Isaac       zCoeff[dim * 0 + j] = 0.125 * (zOrder[dim * 0 + j] + zOrder[dim * 1 + j] + zOrder[dim * 2 + j] + zOrder[dim * 3 + j] + zOrder[dim * 4 + j] + zOrder[dim * 5 + j] + zOrder[dim * 6 + j] + zOrder[dim * 7 + j]);
2153dfccc68fSToby Isaac       zCoeff[dim * 1 + j] = 0.125 * (-zOrder[dim * 0 + j] + zOrder[dim * 1 + j] - zOrder[dim * 2 + j] + zOrder[dim * 3 + j] - zOrder[dim * 4 + j] + zOrder[dim * 5 + j] - zOrder[dim * 6 + j] + zOrder[dim * 7 + j]);
2154dfccc68fSToby Isaac       zCoeff[dim * 2 + j] = 0.125 * (-zOrder[dim * 0 + j] - zOrder[dim * 1 + j] + zOrder[dim * 2 + j] + zOrder[dim * 3 + j] - zOrder[dim * 4 + j] - zOrder[dim * 5 + j] + zOrder[dim * 6 + j] + zOrder[dim * 7 + j]);
2155dfccc68fSToby Isaac       zCoeff[dim * 3 + j] = 0.125 * (zOrder[dim * 0 + j] - zOrder[dim * 1 + j] - zOrder[dim * 2 + j] + zOrder[dim * 3 + j] + zOrder[dim * 4 + j] - zOrder[dim * 5 + j] - zOrder[dim * 6 + j] + zOrder[dim * 7 + j]);
2156dfccc68fSToby Isaac       zCoeff[dim * 4 + j] = 0.125 * (-zOrder[dim * 0 + j] - zOrder[dim * 1 + j] - zOrder[dim * 2 + j] - zOrder[dim * 3 + j] + zOrder[dim * 4 + j] + zOrder[dim * 5 + j] + zOrder[dim * 6 + j] + zOrder[dim * 7 + j]);
2157dfccc68fSToby Isaac       zCoeff[dim * 5 + j] = 0.125 * (+zOrder[dim * 0 + j] - zOrder[dim * 1 + j] + zOrder[dim * 2 + j] - zOrder[dim * 3 + j] - zOrder[dim * 4 + j] + zOrder[dim * 5 + j] - zOrder[dim * 6 + j] + zOrder[dim * 7 + j]);
2158dfccc68fSToby Isaac       zCoeff[dim * 6 + j] = 0.125 * (+zOrder[dim * 0 + j] + zOrder[dim * 1 + j] - zOrder[dim * 2 + j] - zOrder[dim * 3 + j] - zOrder[dim * 4 + j] - zOrder[dim * 5 + j] + zOrder[dim * 6 + j] + zOrder[dim * 7 + j]);
2159dfccc68fSToby Isaac       zCoeff[dim * 7 + j] = 0.125 * (-zOrder[dim * 0 + j] + zOrder[dim * 1 + j] + zOrder[dim * 2 + j] - zOrder[dim * 3 + j] + zOrder[dim * 4 + j] - zOrder[dim * 5 + j] - zOrder[dim * 6 + j] + zOrder[dim * 7 + j]);
2160dfccc68fSToby Isaac     }
2161dfccc68fSToby Isaac     for (i = 0; i < Nq; i++) {
2162dfccc68fSToby Isaac       PetscReal xi = points[dimR * i], eta = points[dimR * i + 1], theta = points[dimR * i + 2];
2163dfccc68fSToby Isaac 
2164dfccc68fSToby Isaac       if (v) {
216591d2b7ceSToby Isaac         PetscReal extPoint[8];
2166dfccc68fSToby Isaac 
2167dfccc68fSToby Isaac         extPoint[0] = 1.;
2168dfccc68fSToby Isaac         extPoint[1] = xi;
2169dfccc68fSToby Isaac         extPoint[2] = eta;
2170dfccc68fSToby Isaac         extPoint[3] = xi * eta;
2171dfccc68fSToby Isaac         extPoint[4] = theta;
2172dfccc68fSToby Isaac         extPoint[5] = theta * xi;
2173dfccc68fSToby Isaac         extPoint[6] = theta * eta;
2174dfccc68fSToby Isaac         extPoint[7] = theta * eta * xi;
2175dfccc68fSToby Isaac         for (j = 0; j < dim; j++) {
2176dfccc68fSToby Isaac           PetscReal val = 0.;
2177dfccc68fSToby Isaac 
2178ad540459SPierre Jolivet           for (k = 0; k < Nv; k++) val += extPoint[k] * zCoeff[dim * k + j];
2179dfccc68fSToby Isaac           v[i * dim + j] = val;
2180dfccc68fSToby Isaac         }
2181dfccc68fSToby Isaac       }
2182dfccc68fSToby Isaac       if (J) {
2183dfccc68fSToby Isaac         PetscReal extJ[24];
2184dfccc68fSToby Isaac 
21859371c9d4SSatish Balay         extJ[0]  = 0.;
21869371c9d4SSatish Balay         extJ[1]  = 0.;
21879371c9d4SSatish Balay         extJ[2]  = 0.;
21889371c9d4SSatish Balay         extJ[3]  = 1.;
21899371c9d4SSatish Balay         extJ[4]  = 0.;
21909371c9d4SSatish Balay         extJ[5]  = 0.;
21919371c9d4SSatish Balay         extJ[6]  = 0.;
21929371c9d4SSatish Balay         extJ[7]  = 1.;
21939371c9d4SSatish Balay         extJ[8]  = 0.;
21949371c9d4SSatish Balay         extJ[9]  = eta;
21959371c9d4SSatish Balay         extJ[10] = xi;
21969371c9d4SSatish Balay         extJ[11] = 0.;
21979371c9d4SSatish Balay         extJ[12] = 0.;
21989371c9d4SSatish Balay         extJ[13] = 0.;
21999371c9d4SSatish Balay         extJ[14] = 1.;
22009371c9d4SSatish Balay         extJ[15] = theta;
22019371c9d4SSatish Balay         extJ[16] = 0.;
22029371c9d4SSatish Balay         extJ[17] = xi;
22039371c9d4SSatish Balay         extJ[18] = 0.;
22049371c9d4SSatish Balay         extJ[19] = theta;
22059371c9d4SSatish Balay         extJ[20] = eta;
22069371c9d4SSatish Balay         extJ[21] = theta * eta;
22079371c9d4SSatish Balay         extJ[22] = theta * xi;
22089371c9d4SSatish Balay         extJ[23] = eta * xi;
2209dfccc68fSToby Isaac 
2210dfccc68fSToby Isaac         for (j = 0; j < dim; j++) {
2211dfccc68fSToby Isaac           for (k = 0; k < dimR; k++) {
2212dfccc68fSToby Isaac             PetscReal val = 0.;
2213dfccc68fSToby Isaac 
2214ad540459SPierre Jolivet             for (l = 0; l < Nv; l++) val += zCoeff[dim * l + j] * extJ[dimR * l + k];
2215dfccc68fSToby Isaac             J[i * dim * dim + dim * j + k] = val;
2216dfccc68fSToby Isaac           }
2217dfccc68fSToby Isaac         }
2218dfccc68fSToby Isaac         DMPlex_Det3D_Internal(&detJ[i], &J[i * dim * dim]);
2219ad540459SPierre Jolivet         if (invJ) DMPlex_Invert3D_Internal(&invJ[i * dim * dim], &J[i * dim * dim], detJ[i]);
2220dfccc68fSToby Isaac       }
2221dfccc68fSToby Isaac     }
2222dfccc68fSToby Isaac   }
22236858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
22243ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2225ccd2543fSMatthew G Knepley }
2226ccd2543fSMatthew G Knepley 
2227d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeTriangularPrismGeometry_Internal(DM dm, PetscInt e, PetscInt Nq, const PetscReal points[], PetscReal v[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
2228d71ae5a4SJacob Faibussowitsch {
22296858538eSMatthew G. Knepley   const PetscScalar *array;
22302df84da0SMatthew G. Knepley   PetscScalar       *coords = NULL;
22312df84da0SMatthew G. Knepley   const PetscInt     dim    = 3;
22326858538eSMatthew G. Knepley   PetscInt           numCoords, d;
22336858538eSMatthew G. Knepley   PetscBool          isDG;
22342df84da0SMatthew G. Knepley 
22352df84da0SMatthew G. Knepley   PetscFunctionBegin;
22366858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
22376858538eSMatthew G. Knepley   PetscCheck(!invJ || J, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "In order to compute invJ, J must not be NULL");
22382df84da0SMatthew G. Knepley   if (!Nq) {
22392df84da0SMatthew G. Knepley     /* Assume that the map to the reference is affine */
22402df84da0SMatthew G. Knepley     *detJ = 0.0;
22419371c9d4SSatish Balay     if (v) {
22429371c9d4SSatish Balay       for (d = 0; d < dim; d++) v[d] = PetscRealPart(coords[d]);
22439371c9d4SSatish Balay     }
22442df84da0SMatthew G. Knepley     if (J) {
22452df84da0SMatthew G. Knepley       for (d = 0; d < dim; d++) {
22462df84da0SMatthew G. Knepley         J[d * dim + 0] = 0.5 * (PetscRealPart(coords[2 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
22472df84da0SMatthew G. Knepley         J[d * dim + 1] = 0.5 * (PetscRealPart(coords[1 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
22482df84da0SMatthew G. Knepley         J[d * dim + 2] = 0.5 * (PetscRealPart(coords[4 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
22492df84da0SMatthew G. Knepley       }
22509566063dSJacob Faibussowitsch       PetscCall(PetscLogFlops(18.0));
22512df84da0SMatthew G. Knepley       DMPlex_Det3D_Internal(detJ, J);
22522df84da0SMatthew G. Knepley     }
2253ad540459SPierre Jolivet     if (invJ) DMPlex_Invert3D_Internal(invJ, J, *detJ);
22542df84da0SMatthew G. Knepley   } else {
22552df84da0SMatthew G. Knepley     const PetscInt dim  = 3;
22562df84da0SMatthew G. Knepley     const PetscInt dimR = 3;
22572df84da0SMatthew G. Knepley     const PetscInt Nv   = 6;
22582df84da0SMatthew G. Knepley     PetscReal      verts[18];
22592df84da0SMatthew G. Knepley     PetscReal      coeff[18];
22602df84da0SMatthew G. Knepley     PetscInt       i, j, k, l;
22612df84da0SMatthew G. Knepley 
22629371c9d4SSatish Balay     for (i = 0; i < Nv; ++i)
22639371c9d4SSatish Balay       for (j = 0; j < dim; ++j) verts[dim * i + j] = PetscRealPart(coords[dim * i + j]);
22642df84da0SMatthew G. Knepley     for (j = 0; j < dim; ++j) {
22652df84da0SMatthew G. Knepley       /* Check for triangle,
22662df84da0SMatthew G. Knepley            phi^0 = -1/2 (xi + eta)  chi^0 = delta(-1, -1)   x(xi) = \sum_k x_k phi^k(xi) = \sum_k chi^k(x) phi^k(xi)
22672df84da0SMatthew G. Knepley            phi^1 =  1/2 (1 + xi)    chi^1 = delta( 1, -1)   y(xi) = \sum_k y_k phi^k(xi) = \sum_k chi^k(y) phi^k(xi)
22682df84da0SMatthew G. Knepley            phi^2 =  1/2 (1 + eta)   chi^2 = delta(-1,  1)
22692df84da0SMatthew G. Knepley 
22702df84da0SMatthew G. Knepley            phi^0 + phi^1 + phi^2 = 1    coef_1   = 1/2 (         chi^1 + chi^2)
22712df84da0SMatthew G. Knepley           -phi^0 + phi^1 - phi^2 = xi   coef_xi  = 1/2 (-chi^0 + chi^1)
22722df84da0SMatthew G. Knepley           -phi^0 - phi^1 + phi^2 = eta  coef_eta = 1/2 (-chi^0         + chi^2)
22732df84da0SMatthew G. Knepley 
22742df84da0SMatthew G. Knepley           < chi_0 chi_1 chi_2> A /  1  1  1 \ / phi_0 \   <chi> I <phi>^T  so we need the inverse transpose
22752df84da0SMatthew G. Knepley                                  | -1  1 -1 | | phi_1 | =
22762df84da0SMatthew G. Knepley                                  \ -1 -1  1 / \ phi_2 /
22772df84da0SMatthew G. Knepley 
22782df84da0SMatthew G. Knepley           Check phi^0: 1/2 (phi^0 chi^1 + phi^0 chi^2 + phi^0 chi^0 - phi^0 chi^1 + phi^0 chi^0 - phi^0 chi^2) = phi^0 chi^0
22792df84da0SMatthew G. Knepley       */
22802df84da0SMatthew G. Knepley       /* Nodal basis for evaluation at the vertices: {-xi - eta, 1 + xi, 1 + eta} (1 \mp zeta):
22812df84da0SMatthew G. Knepley            \phi^0 = 1/4 (   -xi - eta        + xi zeta + eta zeta) --> /  1  1  1  1  1  1 \ 1
22822df84da0SMatthew G. Knepley            \phi^1 = 1/4 (1      + eta - zeta           - eta zeta) --> | -1  1 -1 -1 -1  1 | eta
22832df84da0SMatthew G. Knepley            \phi^2 = 1/4 (1 + xi       - zeta - xi zeta)            --> | -1 -1  1 -1  1 -1 | xi
22842df84da0SMatthew G. Knepley            \phi^3 = 1/4 (   -xi - eta        - xi zeta - eta zeta) --> | -1 -1 -1  1  1  1 | zeta
22852df84da0SMatthew G. Knepley            \phi^4 = 1/4 (1 + xi       + zeta + xi zeta)            --> |  1  1 -1 -1  1 -1 | xi zeta
22862df84da0SMatthew G. Knepley            \phi^5 = 1/4 (1      + eta + zeta           + eta zeta) --> \  1 -1  1 -1 -1  1 / eta zeta
22872df84da0SMatthew G. Knepley            1/4 /  0  1  1  0  1  1 \
22882df84da0SMatthew G. Knepley                | -1  1  0 -1  0  1 |
22892df84da0SMatthew G. Knepley                | -1  0  1 -1  1  0 |
22902df84da0SMatthew G. Knepley                |  0 -1 -1  0  1  1 |
22912df84da0SMatthew G. Knepley                |  1  0 -1 -1  1  0 |
22922df84da0SMatthew G. Knepley                \  1 -1  0 -1  0  1 /
22932df84da0SMatthew G. Knepley       */
22942df84da0SMatthew G. Knepley       coeff[dim * 0 + j] = (1. / 4.) * (verts[dim * 1 + j] + verts[dim * 2 + j] + verts[dim * 4 + j] + verts[dim * 5 + j]);
22952df84da0SMatthew G. Knepley       coeff[dim * 1 + j] = (1. / 4.) * (-verts[dim * 0 + j] + verts[dim * 1 + j] - verts[dim * 3 + j] + verts[dim * 5 + j]);
22962df84da0SMatthew G. Knepley       coeff[dim * 2 + j] = (1. / 4.) * (-verts[dim * 0 + j] + verts[dim * 2 + j] - verts[dim * 3 + j] + verts[dim * 4 + j]);
22972df84da0SMatthew G. Knepley       coeff[dim * 3 + j] = (1. / 4.) * (-verts[dim * 1 + j] - verts[dim * 2 + j] + verts[dim * 4 + j] + verts[dim * 5 + j]);
22982df84da0SMatthew G. Knepley       coeff[dim * 4 + j] = (1. / 4.) * (verts[dim * 0 + j] - verts[dim * 2 + j] - verts[dim * 3 + j] + verts[dim * 4 + j]);
22992df84da0SMatthew G. Knepley       coeff[dim * 5 + j] = (1. / 4.) * (verts[dim * 0 + j] - verts[dim * 1 + j] - verts[dim * 3 + j] + verts[dim * 5 + j]);
23002df84da0SMatthew G. Knepley       /* For reference prism:
23012df84da0SMatthew G. Knepley       {0, 0, 0}
23022df84da0SMatthew G. Knepley       {0, 1, 0}
23032df84da0SMatthew G. Knepley       {1, 0, 0}
23042df84da0SMatthew G. Knepley       {0, 0, 1}
23052df84da0SMatthew G. Knepley       {0, 0, 0}
23062df84da0SMatthew G. Knepley       {0, 0, 0}
23072df84da0SMatthew G. Knepley       */
23082df84da0SMatthew G. Knepley     }
23092df84da0SMatthew G. Knepley     for (i = 0; i < Nq; ++i) {
23102df84da0SMatthew G. Knepley       const PetscReal xi = points[dimR * i], eta = points[dimR * i + 1], zeta = points[dimR * i + 2];
23112df84da0SMatthew G. Knepley 
23122df84da0SMatthew G. Knepley       if (v) {
23132df84da0SMatthew G. Knepley         PetscReal extPoint[6];
23142df84da0SMatthew G. Knepley         PetscInt  c;
23152df84da0SMatthew G. Knepley 
23162df84da0SMatthew G. Knepley         extPoint[0] = 1.;
23172df84da0SMatthew G. Knepley         extPoint[1] = eta;
23182df84da0SMatthew G. Knepley         extPoint[2] = xi;
23192df84da0SMatthew G. Knepley         extPoint[3] = zeta;
23202df84da0SMatthew G. Knepley         extPoint[4] = xi * zeta;
23212df84da0SMatthew G. Knepley         extPoint[5] = eta * zeta;
23222df84da0SMatthew G. Knepley         for (c = 0; c < dim; ++c) {
23232df84da0SMatthew G. Knepley           PetscReal val = 0.;
23242df84da0SMatthew G. Knepley 
2325ad540459SPierre Jolivet           for (k = 0; k < Nv; ++k) val += extPoint[k] * coeff[k * dim + c];
23262df84da0SMatthew G. Knepley           v[i * dim + c] = val;
23272df84da0SMatthew G. Knepley         }
23282df84da0SMatthew G. Knepley       }
23292df84da0SMatthew G. Knepley       if (J) {
23302df84da0SMatthew G. Knepley         PetscReal extJ[18];
23312df84da0SMatthew G. Knepley 
23329371c9d4SSatish Balay         extJ[0]  = 0.;
23339371c9d4SSatish Balay         extJ[1]  = 0.;
23349371c9d4SSatish Balay         extJ[2]  = 0.;
23359371c9d4SSatish Balay         extJ[3]  = 0.;
23369371c9d4SSatish Balay         extJ[4]  = 1.;
23379371c9d4SSatish Balay         extJ[5]  = 0.;
23389371c9d4SSatish Balay         extJ[6]  = 1.;
23399371c9d4SSatish Balay         extJ[7]  = 0.;
23409371c9d4SSatish Balay         extJ[8]  = 0.;
23419371c9d4SSatish Balay         extJ[9]  = 0.;
23429371c9d4SSatish Balay         extJ[10] = 0.;
23439371c9d4SSatish Balay         extJ[11] = 1.;
23449371c9d4SSatish Balay         extJ[12] = zeta;
23459371c9d4SSatish Balay         extJ[13] = 0.;
23469371c9d4SSatish Balay         extJ[14] = xi;
23479371c9d4SSatish Balay         extJ[15] = 0.;
23489371c9d4SSatish Balay         extJ[16] = zeta;
23499371c9d4SSatish Balay         extJ[17] = eta;
23502df84da0SMatthew G. Knepley 
23512df84da0SMatthew G. Knepley         for (j = 0; j < dim; j++) {
23522df84da0SMatthew G. Knepley           for (k = 0; k < dimR; k++) {
23532df84da0SMatthew G. Knepley             PetscReal val = 0.;
23542df84da0SMatthew G. Knepley 
2355ad540459SPierre Jolivet             for (l = 0; l < Nv; l++) val += coeff[dim * l + j] * extJ[dimR * l + k];
23562df84da0SMatthew G. Knepley             J[i * dim * dim + dim * j + k] = val;
23572df84da0SMatthew G. Knepley           }
23582df84da0SMatthew G. Knepley         }
23592df84da0SMatthew G. Knepley         DMPlex_Det3D_Internal(&detJ[i], &J[i * dim * dim]);
2360ad540459SPierre Jolivet         if (invJ) DMPlex_Invert3D_Internal(&invJ[i * dim * dim], &J[i * dim * dim], detJ[i]);
23612df84da0SMatthew G. Knepley       }
23622df84da0SMatthew G. Knepley     }
23632df84da0SMatthew G. Knepley   }
23646858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
23653ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
23662df84da0SMatthew G. Knepley }
23672df84da0SMatthew G. Knepley 
2368d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeCellGeometryFEM_Implicit(DM dm, PetscInt cell, PetscQuadrature quad, PetscReal *v, PetscReal *J, PetscReal *invJ, PetscReal *detJ)
2369d71ae5a4SJacob Faibussowitsch {
2370ba2698f1SMatthew G. Knepley   DMPolytopeType   ct;
2371dfccc68fSToby Isaac   PetscInt         depth, dim, coordDim, coneSize, i;
2372dfccc68fSToby Isaac   PetscInt         Nq     = 0;
2373dfccc68fSToby Isaac   const PetscReal *points = NULL;
2374dfccc68fSToby Isaac   DMLabel          depthLabel;
2375c330f8ffSToby Isaac   PetscReal        xi0[3]   = {-1., -1., -1.}, v0[3], J0[9], detJ0;
2376dfccc68fSToby Isaac   PetscBool        isAffine = PETSC_TRUE;
2377dfccc68fSToby Isaac 
2378dfccc68fSToby Isaac   PetscFunctionBegin;
23799566063dSJacob Faibussowitsch   PetscCall(DMPlexGetDepth(dm, &depth));
23809566063dSJacob Faibussowitsch   PetscCall(DMPlexGetConeSize(dm, cell, &coneSize));
23819566063dSJacob Faibussowitsch   PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
23829566063dSJacob Faibussowitsch   PetscCall(DMLabelGetValue(depthLabel, cell, &dim));
238348a46eb9SPierre Jolivet   if (depth == 1 && dim == 1) PetscCall(DMGetDimension(dm, &dim));
23849566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &coordDim));
238563a3b9bcSJacob Faibussowitsch   PetscCheck(coordDim <= 3, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Unsupported coordinate dimension %" PetscInt_FMT " > 3", coordDim);
23869566063dSJacob Faibussowitsch   if (quad) PetscCall(PetscQuadratureGetData(quad, NULL, NULL, &Nq, &points, NULL));
23879566063dSJacob Faibussowitsch   PetscCall(DMPlexGetCellType(dm, cell, &ct));
2388ba2698f1SMatthew G. Knepley   switch (ct) {
2389ba2698f1SMatthew G. Knepley   case DM_POLYTOPE_POINT:
23909566063dSJacob Faibussowitsch     PetscCall(DMPlexComputePointGeometry_Internal(dm, cell, v, J, invJ, detJ));
2391dfccc68fSToby Isaac     isAffine = PETSC_FALSE;
2392dfccc68fSToby Isaac     break;
2393ba2698f1SMatthew G. Knepley   case DM_POLYTOPE_SEGMENT:
2394412e9a14SMatthew G. Knepley   case DM_POLYTOPE_POINT_PRISM_TENSOR:
23959566063dSJacob Faibussowitsch     if (Nq) PetscCall(DMPlexComputeLineGeometry_Internal(dm, cell, v0, J0, NULL, &detJ0));
23969566063dSJacob Faibussowitsch     else PetscCall(DMPlexComputeLineGeometry_Internal(dm, cell, v, J, invJ, detJ));
2397dfccc68fSToby Isaac     break;
2398ba2698f1SMatthew G. Knepley   case DM_POLYTOPE_TRIANGLE:
23999566063dSJacob Faibussowitsch     if (Nq) PetscCall(DMPlexComputeTriangleGeometry_Internal(dm, cell, v0, J0, NULL, &detJ0));
24009566063dSJacob Faibussowitsch     else PetscCall(DMPlexComputeTriangleGeometry_Internal(dm, cell, v, J, invJ, detJ));
2401dfccc68fSToby Isaac     break;
2402ba2698f1SMatthew G. Knepley   case DM_POLYTOPE_QUADRILATERAL:
24039566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeRectangleGeometry_Internal(dm, cell, PETSC_FALSE, Nq, points, v, J, invJ, detJ));
2404412e9a14SMatthew G. Knepley     isAffine = PETSC_FALSE;
2405412e9a14SMatthew G. Knepley     break;
2406412e9a14SMatthew G. Knepley   case DM_POLYTOPE_SEG_PRISM_TENSOR:
24079566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeRectangleGeometry_Internal(dm, cell, PETSC_TRUE, Nq, points, v, J, invJ, detJ));
2408dfccc68fSToby Isaac     isAffine = PETSC_FALSE;
2409dfccc68fSToby Isaac     break;
2410ba2698f1SMatthew G. Knepley   case DM_POLYTOPE_TETRAHEDRON:
24119566063dSJacob Faibussowitsch     if (Nq) PetscCall(DMPlexComputeTetrahedronGeometry_Internal(dm, cell, v0, J0, NULL, &detJ0));
24129566063dSJacob Faibussowitsch     else PetscCall(DMPlexComputeTetrahedronGeometry_Internal(dm, cell, v, J, invJ, detJ));
2413dfccc68fSToby Isaac     break;
2414ba2698f1SMatthew G. Knepley   case DM_POLYTOPE_HEXAHEDRON:
24159566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeHexahedronGeometry_Internal(dm, cell, Nq, points, v, J, invJ, detJ));
2416dfccc68fSToby Isaac     isAffine = PETSC_FALSE;
2417dfccc68fSToby Isaac     break;
24182df84da0SMatthew G. Knepley   case DM_POLYTOPE_TRI_PRISM:
24199566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeTriangularPrismGeometry_Internal(dm, cell, Nq, points, v, J, invJ, detJ));
24202df84da0SMatthew G. Knepley     isAffine = PETSC_FALSE;
24212df84da0SMatthew G. Knepley     break;
2422d71ae5a4SJacob Faibussowitsch   default:
2423d71ae5a4SJacob Faibussowitsch     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "No element geometry for cell %" PetscInt_FMT " with type %s", cell, DMPolytopeTypes[PetscMax(0, PetscMin(ct, DM_NUM_POLYTOPES))]);
2424dfccc68fSToby Isaac   }
24257318780aSToby Isaac   if (isAffine && Nq) {
2426dfccc68fSToby Isaac     if (v) {
2427ad540459SPierre Jolivet       for (i = 0; i < Nq; i++) CoordinatesRefToReal(coordDim, dim, xi0, v0, J0, &points[dim * i], &v[coordDim * i]);
2428dfccc68fSToby Isaac     }
24297318780aSToby Isaac     if (detJ) {
2430ad540459SPierre Jolivet       for (i = 0; i < Nq; i++) detJ[i] = detJ0;
24317318780aSToby Isaac     }
24327318780aSToby Isaac     if (J) {
24337318780aSToby Isaac       PetscInt k;
24347318780aSToby Isaac 
24357318780aSToby Isaac       for (i = 0, k = 0; i < Nq; i++) {
2436dfccc68fSToby Isaac         PetscInt j;
2437dfccc68fSToby Isaac 
2438ad540459SPierre Jolivet         for (j = 0; j < coordDim * coordDim; j++, k++) J[k] = J0[j];
24397318780aSToby Isaac       }
24407318780aSToby Isaac     }
24417318780aSToby Isaac     if (invJ) {
24427318780aSToby Isaac       PetscInt k;
24437318780aSToby Isaac       switch (coordDim) {
2444d71ae5a4SJacob Faibussowitsch       case 0:
2445d71ae5a4SJacob Faibussowitsch         break;
2446d71ae5a4SJacob Faibussowitsch       case 1:
2447d71ae5a4SJacob Faibussowitsch         invJ[0] = 1. / J0[0];
2448d71ae5a4SJacob Faibussowitsch         break;
2449d71ae5a4SJacob Faibussowitsch       case 2:
2450d71ae5a4SJacob Faibussowitsch         DMPlex_Invert2D_Internal(invJ, J0, detJ0);
2451d71ae5a4SJacob Faibussowitsch         break;
2452d71ae5a4SJacob Faibussowitsch       case 3:
2453d71ae5a4SJacob Faibussowitsch         DMPlex_Invert3D_Internal(invJ, J0, detJ0);
2454d71ae5a4SJacob Faibussowitsch         break;
24557318780aSToby Isaac       }
24567318780aSToby Isaac       for (i = 1, k = coordDim * coordDim; i < Nq; i++) {
24577318780aSToby Isaac         PetscInt j;
24587318780aSToby Isaac 
2459ad540459SPierre Jolivet         for (j = 0; j < coordDim * coordDim; j++, k++) invJ[k] = invJ[j];
2460dfccc68fSToby Isaac       }
2461dfccc68fSToby Isaac     }
2462dfccc68fSToby Isaac   }
24633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2464dfccc68fSToby Isaac }
2465dfccc68fSToby Isaac 
2466ccd2543fSMatthew G Knepley /*@C
24678e0841e0SMatthew G. Knepley   DMPlexComputeCellGeometryAffineFEM - Assuming an affine map, compute the Jacobian, inverse Jacobian, and Jacobian determinant for a given cell
2468ccd2543fSMatthew G Knepley 
246920f4b53cSBarry Smith   Collective
2470ccd2543fSMatthew G Knepley 
24714165533cSJose E. Roman   Input Parameters:
247220f4b53cSBarry Smith + dm   - the `DMPLEX`
2473ccd2543fSMatthew G Knepley - cell - the cell
2474ccd2543fSMatthew G Knepley 
24754165533cSJose E. Roman   Output Parameters:
24769b172b3aSMatthew Knepley + v0   - the translation part of this affine transform, meaning the translation to the origin (not the first vertex of the reference cell)
2477ccd2543fSMatthew G Knepley . J    - the Jacobian of the transform from the reference element
2478ccd2543fSMatthew G Knepley . invJ - the inverse of the Jacobian
2479ccd2543fSMatthew G Knepley - detJ - the Jacobian determinant
2480ccd2543fSMatthew G Knepley 
2481ccd2543fSMatthew G Knepley   Level: advanced
2482ccd2543fSMatthew G Knepley 
248320f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexComputeCellGeometryFEM()`, `DMGetCoordinateSection()`, `DMGetCoordinates()`
2484ccd2543fSMatthew G Knepley @*/
2485ce78bad3SBarry Smith PetscErrorCode DMPlexComputeCellGeometryAffineFEM(DM dm, PetscInt cell, PetscReal v0[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
2486d71ae5a4SJacob Faibussowitsch {
2487ccd2543fSMatthew G Knepley   PetscFunctionBegin;
24889566063dSJacob Faibussowitsch   PetscCall(DMPlexComputeCellGeometryFEM_Implicit(dm, cell, NULL, v0, J, invJ, detJ));
24893ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
24908e0841e0SMatthew G. Knepley }
24918e0841e0SMatthew G. Knepley 
2492d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeCellGeometryFEM_FE(DM dm, PetscFE fe, PetscInt point, PetscQuadrature quad, PetscReal v[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
2493d71ae5a4SJacob Faibussowitsch {
24946858538eSMatthew G. Knepley   const PetscScalar *array;
24958e0841e0SMatthew G. Knepley   PetscScalar       *coords = NULL;
24966858538eSMatthew G. Knepley   PetscInt           numCoords;
24976858538eSMatthew G. Knepley   PetscBool          isDG;
24986858538eSMatthew G. Knepley   PetscQuadrature    feQuad;
24998e0841e0SMatthew G. Knepley   const PetscReal   *quadPoints;
2500ef0bb6c7SMatthew G. Knepley   PetscTabulation    T;
25016858538eSMatthew G. Knepley   PetscInt           dim, cdim, pdim, qdim, Nq, q;
25028e0841e0SMatthew G. Knepley 
25038e0841e0SMatthew G. Knepley   PetscFunctionBegin;
25049566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dim));
25059566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &cdim));
25066858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, point, &isDG, &numCoords, &array, &coords));
2507dfccc68fSToby Isaac   if (!quad) { /* use the first point of the first functional of the dual space */
2508dfccc68fSToby Isaac     PetscDualSpace dsp;
2509dfccc68fSToby Isaac 
25109566063dSJacob Faibussowitsch     PetscCall(PetscFEGetDualSpace(fe, &dsp));
25119566063dSJacob Faibussowitsch     PetscCall(PetscDualSpaceGetFunctional(dsp, 0, &quad));
25129566063dSJacob Faibussowitsch     PetscCall(PetscQuadratureGetData(quad, &qdim, NULL, &Nq, &quadPoints, NULL));
2513dfccc68fSToby Isaac     Nq = 1;
2514dfccc68fSToby Isaac   } else {
25159566063dSJacob Faibussowitsch     PetscCall(PetscQuadratureGetData(quad, &qdim, NULL, &Nq, &quadPoints, NULL));
2516dfccc68fSToby Isaac   }
25179566063dSJacob Faibussowitsch   PetscCall(PetscFEGetDimension(fe, &pdim));
25189566063dSJacob Faibussowitsch   PetscCall(PetscFEGetQuadrature(fe, &feQuad));
2519dfccc68fSToby Isaac   if (feQuad == quad) {
25209566063dSJacob Faibussowitsch     PetscCall(PetscFEGetCellTabulation(fe, J ? 1 : 0, &T));
252163a3b9bcSJacob Faibussowitsch     PetscCheck(numCoords == pdim * cdim, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "There are %" PetscInt_FMT " coordinates for point %" PetscInt_FMT " != %" PetscInt_FMT "*%" PetscInt_FMT, numCoords, point, pdim, cdim);
2522dfccc68fSToby Isaac   } else {
25239566063dSJacob Faibussowitsch     PetscCall(PetscFECreateTabulation(fe, 1, Nq, quadPoints, J ? 1 : 0, &T));
2524dfccc68fSToby Isaac   }
252563a3b9bcSJacob Faibussowitsch   PetscCheck(qdim == dim, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Point dimension %" PetscInt_FMT " != quadrature dimension %" PetscInt_FMT, dim, qdim);
2526ef0bb6c7SMatthew G. Knepley   {
2527ef0bb6c7SMatthew G. Knepley     const PetscReal *basis    = T->T[0];
2528ef0bb6c7SMatthew G. Knepley     const PetscReal *basisDer = T->T[1];
2529ef0bb6c7SMatthew G. Knepley     PetscReal        detJt;
2530ef0bb6c7SMatthew G. Knepley 
2531b498ca8aSPierre Jolivet     PetscAssert(Nq == T->Np, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Np %" PetscInt_FMT " != %" PetscInt_FMT, Nq, T->Np);
2532b498ca8aSPierre Jolivet     PetscAssert(pdim == T->Nb, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nb %" PetscInt_FMT " != %" PetscInt_FMT, pdim, T->Nb);
2533166330a8SMatthew G. Knepley     PetscAssert(cdim == T->Nc, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nc %" PetscInt_FMT " != %" PetscInt_FMT, cdim, T->Nc);
2534166330a8SMatthew G. Knepley     PetscAssert(dim == T->cdim, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "cdim %" PetscInt_FMT " != %" PetscInt_FMT, dim, T->cdim);
2535dfccc68fSToby Isaac     if (v) {
25369566063dSJacob Faibussowitsch       PetscCall(PetscArrayzero(v, Nq * cdim));
2537f960e424SToby Isaac       for (q = 0; q < Nq; ++q) {
2538f960e424SToby Isaac         PetscInt i, k;
2539f960e424SToby Isaac 
2540301b184aSMatthew G. Knepley         for (k = 0; k < pdim; ++k) {
2541301b184aSMatthew G. Knepley           const PetscInt vertex = k / cdim;
2542ad540459SPierre Jolivet           for (i = 0; i < cdim; ++i) v[q * cdim + i] += basis[(q * pdim + k) * cdim + i] * PetscRealPart(coords[vertex * cdim + i]);
2543301b184aSMatthew G. Knepley         }
25449566063dSJacob Faibussowitsch         PetscCall(PetscLogFlops(2.0 * pdim * cdim));
2545f960e424SToby Isaac       }
2546f960e424SToby Isaac     }
25478e0841e0SMatthew G. Knepley     if (J) {
25489566063dSJacob Faibussowitsch       PetscCall(PetscArrayzero(J, Nq * cdim * cdim));
25498e0841e0SMatthew G. Knepley       for (q = 0; q < Nq; ++q) {
25508e0841e0SMatthew G. Knepley         PetscInt i, j, k, c, r;
25518e0841e0SMatthew G. Knepley 
25528e0841e0SMatthew G. Knepley         /* J = dx_i/d\xi_j = sum[k=0,n-1] dN_k/d\xi_j * x_i(k) */
2553301b184aSMatthew G. Knepley         for (k = 0; k < pdim; ++k) {
2554301b184aSMatthew G. Knepley           const PetscInt vertex = k / cdim;
2555301b184aSMatthew G. Knepley           for (j = 0; j < dim; ++j) {
2556ad540459SPierre Jolivet             for (i = 0; i < cdim; ++i) J[(q * cdim + i) * cdim + j] += basisDer[((q * pdim + k) * cdim + i) * dim + j] * PetscRealPart(coords[vertex * cdim + i]);
2557301b184aSMatthew G. Knepley           }
2558301b184aSMatthew G. Knepley         }
25599566063dSJacob Faibussowitsch         PetscCall(PetscLogFlops(2.0 * pdim * dim * cdim));
25608e0841e0SMatthew G. Knepley         if (cdim > dim) {
25618e0841e0SMatthew G. Knepley           for (c = dim; c < cdim; ++c)
25629371c9d4SSatish Balay             for (r = 0; r < cdim; ++r) J[r * cdim + c] = r == c ? 1.0 : 0.0;
25638e0841e0SMatthew G. Knepley         }
2564f960e424SToby Isaac         if (!detJ && !invJ) continue;
2565a63b72c6SToby Isaac         detJt = 0.;
25668e0841e0SMatthew G. Knepley         switch (cdim) {
25678e0841e0SMatthew G. Knepley         case 3:
2568037dc194SToby Isaac           DMPlex_Det3D_Internal(&detJt, &J[q * cdim * dim]);
2569ad540459SPierre Jolivet           if (invJ) DMPlex_Invert3D_Internal(&invJ[q * cdim * dim], &J[q * cdim * dim], detJt);
257017fe8556SMatthew G. Knepley           break;
257149dc4407SMatthew G. Knepley         case 2:
25729f328543SToby Isaac           DMPlex_Det2D_Internal(&detJt, &J[q * cdim * dim]);
2573ad540459SPierre Jolivet           if (invJ) DMPlex_Invert2D_Internal(&invJ[q * cdim * dim], &J[q * cdim * dim], detJt);
257449dc4407SMatthew G. Knepley           break;
25758e0841e0SMatthew G. Knepley         case 1:
2576037dc194SToby Isaac           detJt = J[q * cdim * dim];
2577037dc194SToby Isaac           if (invJ) invJ[q * cdim * dim] = 1.0 / detJt;
257849dc4407SMatthew G. Knepley         }
2579f960e424SToby Isaac         if (detJ) detJ[q] = detJt;
258049dc4407SMatthew G. Knepley       }
258108401ef6SPierre Jolivet     } else PetscCheck(!detJ && !invJ, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Need J to compute invJ or detJ");
258249dc4407SMatthew G. Knepley   }
25839566063dSJacob Faibussowitsch   if (feQuad != quad) PetscCall(PetscTabulationDestroy(&T));
25846858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, point, &isDG, &numCoords, &array, &coords));
25853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
25868e0841e0SMatthew G. Knepley }
25878e0841e0SMatthew G. Knepley 
25888e0841e0SMatthew G. Knepley /*@C
25898e0841e0SMatthew G. Knepley   DMPlexComputeCellGeometryFEM - Compute the Jacobian, inverse Jacobian, and Jacobian determinant at each quadrature point in the given cell
25908e0841e0SMatthew G. Knepley 
259120f4b53cSBarry Smith   Collective
25928e0841e0SMatthew G. Knepley 
25934165533cSJose E. Roman   Input Parameters:
259420f4b53cSBarry Smith + dm   - the `DMPLEX`
25958e0841e0SMatthew G. Knepley . cell - the cell
259620f4b53cSBarry Smith - quad - the quadrature containing the points in the reference element where the geometry will be evaluated.  If `quad` is `NULL`, geometry will be
2597dfccc68fSToby Isaac          evaluated at the first vertex of the reference element
25988e0841e0SMatthew G. Knepley 
25994165533cSJose E. Roman   Output Parameters:
2600dfccc68fSToby Isaac + v    - the image of the transformed quadrature points, otherwise the image of the first vertex in the closure of the reference element
26018e0841e0SMatthew G. Knepley . J    - the Jacobian of the transform from the reference element at each quadrature point
26028e0841e0SMatthew G. Knepley . invJ - the inverse of the Jacobian at each quadrature point
26038e0841e0SMatthew G. Knepley - detJ - the Jacobian determinant at each quadrature point
26048e0841e0SMatthew G. Knepley 
26058e0841e0SMatthew G. Knepley   Level: advanced
26068e0841e0SMatthew G. Knepley 
2607ac9d17c7SMatthew G. Knepley   Note:
2608ac9d17c7SMatthew G. Knepley   Implicit cell geometry must be used when the topological mesh dimension is not equal to the coordinate dimension, for instance for embedded manifolds.
2609ac9d17c7SMatthew G. Knepley 
261020f4b53cSBarry Smith .seealso: `DMPLEX`, `DMGetCoordinateSection()`, `DMGetCoordinates()`
26118e0841e0SMatthew G. Knepley @*/
2612ce78bad3SBarry Smith PetscErrorCode DMPlexComputeCellGeometryFEM(DM dm, PetscInt cell, PetscQuadrature quad, PetscReal *v, PetscReal J[], PetscReal invJ[], PetscReal *detJ)
2613d71ae5a4SJacob Faibussowitsch {
2614bb4a5db5SMatthew G. Knepley   DM       cdm;
2615dfccc68fSToby Isaac   PetscFE  fe = NULL;
2616ac9d17c7SMatthew G. Knepley   PetscInt dim, cdim;
26178e0841e0SMatthew G. Knepley 
26188e0841e0SMatthew G. Knepley   PetscFunctionBegin;
26194f572ea9SToby Isaac   PetscAssertPointer(detJ, 7);
2620ac9d17c7SMatthew G. Knepley   PetscCall(DMGetDimension(dm, &dim));
2621ac9d17c7SMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &cdim));
26229566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDM(dm, &cdm));
2623bb4a5db5SMatthew G. Knepley   if (cdm) {
2624dfccc68fSToby Isaac     PetscClassId id;
2625dfccc68fSToby Isaac     PetscInt     numFields;
2626e5e52638SMatthew G. Knepley     PetscDS      prob;
2627dfccc68fSToby Isaac     PetscObject  disc;
2628dfccc68fSToby Isaac 
26299566063dSJacob Faibussowitsch     PetscCall(DMGetNumFields(cdm, &numFields));
2630dfccc68fSToby Isaac     if (numFields) {
26319566063dSJacob Faibussowitsch       PetscCall(DMGetDS(cdm, &prob));
26329566063dSJacob Faibussowitsch       PetscCall(PetscDSGetDiscretization(prob, 0, &disc));
26339566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetClassId(disc, &id));
2634ad540459SPierre Jolivet       if (id == PETSCFE_CLASSID) fe = (PetscFE)disc;
2635dfccc68fSToby Isaac     }
2636dfccc68fSToby Isaac   }
2637ac9d17c7SMatthew G. Knepley   if (!fe || (dim != cdim)) PetscCall(DMPlexComputeCellGeometryFEM_Implicit(dm, cell, quad, v, J, invJ, detJ));
26389566063dSJacob Faibussowitsch   else PetscCall(DMPlexComputeCellGeometryFEM_FE(dm, fe, cell, quad, v, J, invJ, detJ));
26393ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2640ccd2543fSMatthew G Knepley }
2641834e62ceSMatthew G. Knepley 
2642d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeGeometryFVM_0D_Internal(DM dm, PetscInt dim, PetscInt cell, PetscReal *vol, PetscReal centroid[], PetscReal normal[])
2643d71ae5a4SJacob Faibussowitsch {
26449bf2564aSMatt McGurn   PetscSection       coordSection;
26459bf2564aSMatt McGurn   Vec                coordinates;
26469bf2564aSMatt McGurn   const PetscScalar *coords = NULL;
26479bf2564aSMatt McGurn   PetscInt           d, dof, off;
26489bf2564aSMatt McGurn 
26499bf2564aSMatt McGurn   PetscFunctionBegin;
26509566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
26519566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateSection(dm, &coordSection));
26529566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(coordinates, &coords));
26539bf2564aSMatt McGurn 
26549bf2564aSMatt McGurn   /* for a point the centroid is just the coord */
26559bf2564aSMatt McGurn   if (centroid) {
26569566063dSJacob Faibussowitsch     PetscCall(PetscSectionGetDof(coordSection, cell, &dof));
26579566063dSJacob Faibussowitsch     PetscCall(PetscSectionGetOffset(coordSection, cell, &off));
2658ad540459SPierre Jolivet     for (d = 0; d < dof; d++) centroid[d] = PetscRealPart(coords[off + d]);
26599bf2564aSMatt McGurn   }
26609bf2564aSMatt McGurn   if (normal) {
26619bf2564aSMatt McGurn     const PetscInt *support, *cones;
26629bf2564aSMatt McGurn     PetscInt        supportSize;
26639bf2564aSMatt McGurn     PetscReal       norm, sign;
26649bf2564aSMatt McGurn 
26659bf2564aSMatt McGurn     /* compute the norm based upon the support centroids */
26669566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupportSize(dm, cell, &supportSize));
26679566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupport(dm, cell, &support));
26689566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeCellGeometryFVM(dm, support[0], NULL, normal, NULL));
26699bf2564aSMatt McGurn 
26709bf2564aSMatt McGurn     /* Take the normal from the centroid of the support to the vertex*/
26719566063dSJacob Faibussowitsch     PetscCall(PetscSectionGetDof(coordSection, cell, &dof));
26729566063dSJacob Faibussowitsch     PetscCall(PetscSectionGetOffset(coordSection, cell, &off));
2673ad540459SPierre Jolivet     for (d = 0; d < dof; d++) normal[d] -= PetscRealPart(coords[off + d]);
26749bf2564aSMatt McGurn 
26759bf2564aSMatt McGurn     /* Determine the sign of the normal based upon its location in the support */
26769566063dSJacob Faibussowitsch     PetscCall(DMPlexGetCone(dm, support[0], &cones));
26779bf2564aSMatt McGurn     sign = cones[0] == cell ? 1.0 : -1.0;
26789bf2564aSMatt McGurn 
26799bf2564aSMatt McGurn     norm = DMPlex_NormD_Internal(dim, normal);
26809bf2564aSMatt McGurn     for (d = 0; d < dim; ++d) normal[d] /= (norm * sign);
26819bf2564aSMatt McGurn   }
2682ad540459SPierre Jolivet   if (vol) *vol = 1.0;
26839566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(coordinates, &coords));
26843ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
26859bf2564aSMatt McGurn }
26869bf2564aSMatt McGurn 
2687d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeGeometryFVM_1D_Internal(DM dm, PetscInt dim, PetscInt cell, PetscReal *vol, PetscReal centroid[], PetscReal normal[])
2688d71ae5a4SJacob Faibussowitsch {
26896858538eSMatthew G. Knepley   const PetscScalar *array;
2690a1e44745SMatthew G. Knepley   PetscScalar       *coords = NULL;
269121d6a034SMatthew G. Knepley   PetscInt           cdim, coordSize, d;
26926858538eSMatthew G. Knepley   PetscBool          isDG;
2693cc08537eSMatthew G. Knepley 
2694cc08537eSMatthew G. Knepley   PetscFunctionBegin;
269521d6a034SMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &cdim));
26966858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, cell, &isDG, &coordSize, &array, &coords));
269721d6a034SMatthew G. Knepley   PetscCheck(coordSize == cdim * 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Edge has %" PetscInt_FMT " coordinates != %" PetscInt_FMT, coordSize, cdim * 2);
2698cc08537eSMatthew G. Knepley   if (centroid) {
269921d6a034SMatthew G. Knepley     for (d = 0; d < cdim; ++d) centroid[d] = 0.5 * PetscRealPart(coords[d] + coords[cdim + d]);
2700cc08537eSMatthew G. Knepley   }
2701cc08537eSMatthew G. Knepley   if (normal) {
2702a60a936bSMatthew G. Knepley     PetscReal norm;
2703a60a936bSMatthew G. Knepley 
270421d6a034SMatthew G. Knepley     switch (cdim) {
270521d6a034SMatthew G. Knepley     case 3:
2706f315e28eSPierre Jolivet       normal[2] = 0.; /* fall through */
270721d6a034SMatthew G. Knepley     case 2:
270821d6a034SMatthew G. Knepley       normal[0] = -PetscRealPart(coords[1] - coords[cdim + 1]);
270921d6a034SMatthew G. Knepley       normal[1] = PetscRealPart(coords[0] - coords[cdim + 0]);
271021d6a034SMatthew G. Knepley       break;
271121d6a034SMatthew G. Knepley     case 1:
271221d6a034SMatthew G. Knepley       normal[0] = 1.0;
271321d6a034SMatthew G. Knepley       break;
271421d6a034SMatthew G. Knepley     default:
271521d6a034SMatthew G. Knepley       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Dimension %" PetscInt_FMT " not supported", cdim);
271621d6a034SMatthew G. Knepley     }
271721d6a034SMatthew G. Knepley     norm = DMPlex_NormD_Internal(cdim, normal);
271821d6a034SMatthew G. Knepley     for (d = 0; d < cdim; ++d) normal[d] /= norm;
2719cc08537eSMatthew G. Knepley   }
2720cc08537eSMatthew G. Knepley   if (vol) {
2721714b99b6SMatthew G. Knepley     *vol = 0.0;
272221d6a034SMatthew G. Knepley     for (d = 0; d < cdim; ++d) *vol += PetscSqr(PetscRealPart(coords[d] - coords[cdim + d]));
2723714b99b6SMatthew G. Knepley     *vol = PetscSqrtReal(*vol);
2724cc08537eSMatthew G. Knepley   }
27256858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, cell, &isDG, &coordSize, &array, &coords));
27263ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2727cc08537eSMatthew G. Knepley }
2728cc08537eSMatthew G. Knepley 
2729cc08537eSMatthew G. Knepley /* Centroid_i = (\sum_n A_n Cn_i) / A */
2730d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeGeometryFVM_2D_Internal(DM dm, PetscInt dim, PetscInt cell, PetscReal *vol, PetscReal centroid[], PetscReal normal[])
2731d71ae5a4SJacob Faibussowitsch {
2732412e9a14SMatthew G. Knepley   DMPolytopeType     ct;
27336858538eSMatthew G. Knepley   const PetscScalar *array;
2734cc08537eSMatthew G. Knepley   PetscScalar       *coords = NULL;
27356858538eSMatthew G. Knepley   PetscInt           coordSize;
27366858538eSMatthew G. Knepley   PetscBool          isDG;
2737793a2a13SMatthew G. Knepley   PetscInt           fv[4] = {0, 1, 2, 3};
27386858538eSMatthew G. Knepley   PetscInt           cdim, numCorners, p, d;
2739cc08537eSMatthew G. Knepley 
2740cc08537eSMatthew G. Knepley   PetscFunctionBegin;
2741793a2a13SMatthew G. Knepley   /* Must check for hybrid cells because prisms have a different orientation scheme */
27429566063dSJacob Faibussowitsch   PetscCall(DMPlexGetCellType(dm, cell, &ct));
2743412e9a14SMatthew G. Knepley   switch (ct) {
27449371c9d4SSatish Balay   case DM_POLYTOPE_SEG_PRISM_TENSOR:
27459371c9d4SSatish Balay     fv[2] = 3;
27469371c9d4SSatish Balay     fv[3] = 2;
27479371c9d4SSatish Balay     break;
2748d71ae5a4SJacob Faibussowitsch   default:
2749d71ae5a4SJacob Faibussowitsch     break;
2750412e9a14SMatthew G. Knepley   }
27519566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &cdim));
27526858538eSMatthew G. Knepley   PetscCall(DMPlexGetConeSize(dm, cell, &numCorners));
27536858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, cell, &isDG, &coordSize, &array, &coords));
27543f27a4e6SJed Brown   {
27553f27a4e6SJed Brown     PetscReal c[3] = {0., 0., 0.}, n[3] = {0., 0., 0.}, origin[3] = {0., 0., 0.}, norm;
2756793a2a13SMatthew G. Knepley 
27573f27a4e6SJed Brown     for (d = 0; d < cdim; d++) origin[d] = PetscRealPart(coords[d]);
27584f99dae5SMatthew G. Knepley     for (p = 0; p < numCorners - 2; ++p) {
27593f27a4e6SJed Brown       PetscReal e0[3] = {0., 0., 0.}, e1[3] = {0., 0., 0.};
27603f27a4e6SJed Brown       for (d = 0; d < cdim; d++) {
27613f27a4e6SJed Brown         e0[d] = PetscRealPart(coords[cdim * fv[p + 1] + d]) - origin[d];
27623f27a4e6SJed Brown         e1[d] = PetscRealPart(coords[cdim * fv[p + 2] + d]) - origin[d];
27633f27a4e6SJed Brown       }
27643f27a4e6SJed Brown       const PetscReal dx = e0[1] * e1[2] - e0[2] * e1[1];
27653f27a4e6SJed Brown       const PetscReal dy = e0[2] * e1[0] - e0[0] * e1[2];
27663f27a4e6SJed Brown       const PetscReal dz = e0[0] * e1[1] - e0[1] * e1[0];
27673f27a4e6SJed Brown       const PetscReal a  = PetscSqrtReal(dx * dx + dy * dy + dz * dz);
27684f99dae5SMatthew G. Knepley 
27694f99dae5SMatthew G. Knepley       n[0] += dx;
27704f99dae5SMatthew G. Knepley       n[1] += dy;
27714f99dae5SMatthew G. Knepley       n[2] += dz;
2772ad540459SPierre Jolivet       for (d = 0; d < cdim; d++) c[d] += a * PetscRealPart(origin[d] + coords[cdim * fv[p + 1] + d] + coords[cdim * fv[p + 2] + d]) / 3.;
2773ceee4971SMatthew G. Knepley     }
27744f99dae5SMatthew G. Knepley     norm = PetscSqrtReal(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]);
277561451c10SMatthew G. Knepley     // Allow zero volume cells
277661451c10SMatthew G. Knepley     if (norm != 0) {
27774f99dae5SMatthew G. Knepley       n[0] /= norm;
27784f99dae5SMatthew G. Knepley       n[1] /= norm;
27794f99dae5SMatthew G. Knepley       n[2] /= norm;
27804f99dae5SMatthew G. Knepley       c[0] /= norm;
27814f99dae5SMatthew G. Knepley       c[1] /= norm;
27824f99dae5SMatthew G. Knepley       c[2] /= norm;
278361451c10SMatthew G. Knepley     }
27844f99dae5SMatthew G. Knepley     if (vol) *vol = 0.5 * norm;
27859371c9d4SSatish Balay     if (centroid)
27869371c9d4SSatish Balay       for (d = 0; d < cdim; ++d) centroid[d] = c[d];
27879371c9d4SSatish Balay     if (normal)
27889371c9d4SSatish Balay       for (d = 0; d < cdim; ++d) normal[d] = n[d];
27890a1d6728SMatthew G. Knepley   }
27906858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, cell, &isDG, &coordSize, &array, &coords));
27913ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2792cc08537eSMatthew G. Knepley }
2793cc08537eSMatthew G. Knepley 
27940ec8681fSMatthew G. Knepley /* Centroid_i = (\sum_n V_n Cn_i) / V */
2795d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeGeometryFVM_3D_Internal(DM dm, PetscInt dim, PetscInt cell, PetscReal *vol, PetscReal centroid[], PetscReal normal[])
2796d71ae5a4SJacob Faibussowitsch {
2797412e9a14SMatthew G. Knepley   DMPolytopeType        ct;
27986858538eSMatthew G. Knepley   const PetscScalar    *array;
27990ec8681fSMatthew G. Knepley   PetscScalar          *coords = NULL;
28006858538eSMatthew G. Knepley   PetscInt              coordSize;
28016858538eSMatthew G. Knepley   PetscBool             isDG;
28023f27a4e6SJed Brown   PetscReal             vsum      = 0.0, vtmp, coordsTmp[3 * 3], origin[3];
28036858538eSMatthew G. Knepley   const PetscInt        order[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
28046858538eSMatthew G. Knepley   const PetscInt       *cone, *faceSizes, *faces;
28056858538eSMatthew G. Knepley   const DMPolytopeType *faceTypes;
2806793a2a13SMatthew G. Knepley   PetscBool             isHybrid = PETSC_FALSE;
28076858538eSMatthew G. Knepley   PetscInt              numFaces, f, fOff = 0, p, d;
28080ec8681fSMatthew G. Knepley 
28090ec8681fSMatthew G. Knepley   PetscFunctionBegin;
281063a3b9bcSJacob Faibussowitsch   PetscCheck(dim <= 3, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No support for dim %" PetscInt_FMT " > 3", dim);
2811793a2a13SMatthew G. Knepley   /* Must check for hybrid cells because prisms have a different orientation scheme */
28129566063dSJacob Faibussowitsch   PetscCall(DMPlexGetCellType(dm, cell, &ct));
2813412e9a14SMatthew G. Knepley   switch (ct) {
2814412e9a14SMatthew G. Knepley   case DM_POLYTOPE_POINT_PRISM_TENSOR:
2815412e9a14SMatthew G. Knepley   case DM_POLYTOPE_SEG_PRISM_TENSOR:
2816412e9a14SMatthew G. Knepley   case DM_POLYTOPE_TRI_PRISM_TENSOR:
2817d71ae5a4SJacob Faibussowitsch   case DM_POLYTOPE_QUAD_PRISM_TENSOR:
2818d71ae5a4SJacob Faibussowitsch     isHybrid = PETSC_TRUE;
2819d71ae5a4SJacob Faibussowitsch   default:
2820d71ae5a4SJacob Faibussowitsch     break;
2821412e9a14SMatthew G. Knepley   }
2822793a2a13SMatthew G. Knepley 
28239371c9d4SSatish Balay   if (centroid)
28249371c9d4SSatish Balay     for (d = 0; d < dim; ++d) centroid[d] = 0.0;
28256858538eSMatthew G. Knepley   PetscCall(DMPlexGetCone(dm, cell, &cone));
28266858538eSMatthew G. Knepley 
28276858538eSMatthew G. Knepley   // Using the closure of faces for coordinates does not work in periodic geometries, so we index into the cell coordinates
28286858538eSMatthew G. Knepley   PetscCall(DMPlexGetRawFaces_Internal(dm, ct, order, &numFaces, &faceTypes, &faceSizes, &faces));
28296858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, cell, &isDG, &coordSize, &array, &coords));
28300ec8681fSMatthew G. Knepley   for (f = 0; f < numFaces; ++f) {
2831793a2a13SMatthew G. Knepley     PetscBool flip = isHybrid && f == 0 ? PETSC_TRUE : PETSC_FALSE; /* The first hybrid face is reversed */
2832793a2a13SMatthew G. Knepley 
28333f27a4e6SJed Brown     // If using zero as the origin vertex for each tetrahedron, an element far from the origin will have positive and
28343f27a4e6SJed Brown     // negative volumes that nearly cancel, thus incurring rounding error. Here we define origin[] as the first vertex
28353f27a4e6SJed Brown     // so that all tetrahedra have positive volume.
28369371c9d4SSatish Balay     if (f == 0)
28379371c9d4SSatish Balay       for (d = 0; d < dim; d++) origin[d] = PetscRealPart(coords[d]);
28386858538eSMatthew G. Knepley     switch (faceTypes[f]) {
2839ba2698f1SMatthew G. Knepley     case DM_POLYTOPE_TRIANGLE:
28400ec8681fSMatthew G. Knepley       for (d = 0; d < dim; ++d) {
28416858538eSMatthew G. Knepley         coordsTmp[0 * dim + d] = PetscRealPart(coords[faces[fOff + 0] * dim + d]) - origin[d];
28426858538eSMatthew G. Knepley         coordsTmp[1 * dim + d] = PetscRealPart(coords[faces[fOff + 1] * dim + d]) - origin[d];
28436858538eSMatthew G. Knepley         coordsTmp[2 * dim + d] = PetscRealPart(coords[faces[fOff + 2] * dim + d]) - origin[d];
28440ec8681fSMatthew G. Knepley       }
28450ec8681fSMatthew G. Knepley       Volume_Tetrahedron_Origin_Internal(&vtmp, coordsTmp);
28466858538eSMatthew G. Knepley       if (flip) vtmp = -vtmp;
28470ec8681fSMatthew G. Knepley       vsum += vtmp;
28484f25033aSJed Brown       if (centroid) { /* Centroid of OABC = (a+b+c)/4 */
28490ec8681fSMatthew G. Knepley         for (d = 0; d < dim; ++d) {
28501ee9d5ecSMatthew G. Knepley           for (p = 0; p < 3; ++p) centroid[d] += coordsTmp[p * dim + d] * vtmp;
28510ec8681fSMatthew G. Knepley         }
28520ec8681fSMatthew G. Knepley       }
28530ec8681fSMatthew G. Knepley       break;
2854ba2698f1SMatthew G. Knepley     case DM_POLYTOPE_QUADRILATERAL:
28559371c9d4SSatish Balay     case DM_POLYTOPE_SEG_PRISM_TENSOR: {
2856793a2a13SMatthew G. Knepley       PetscInt fv[4] = {0, 1, 2, 3};
2857793a2a13SMatthew G. Knepley 
285815229ffcSPierre Jolivet       /* Side faces for hybrid cells are stored as tensor products */
28599371c9d4SSatish Balay       if (isHybrid && f > 1) {
28609371c9d4SSatish Balay         fv[2] = 3;
28619371c9d4SSatish Balay         fv[3] = 2;
28629371c9d4SSatish Balay       }
28630ec8681fSMatthew G. Knepley       /* DO FOR PYRAMID */
28640ec8681fSMatthew G. Knepley       /* First tet */
28650ec8681fSMatthew G. Knepley       for (d = 0; d < dim; ++d) {
28666858538eSMatthew G. Knepley         coordsTmp[0 * dim + d] = PetscRealPart(coords[faces[fOff + fv[0]] * dim + d]) - origin[d];
28676858538eSMatthew G. Knepley         coordsTmp[1 * dim + d] = PetscRealPart(coords[faces[fOff + fv[1]] * dim + d]) - origin[d];
28686858538eSMatthew G. Knepley         coordsTmp[2 * dim + d] = PetscRealPart(coords[faces[fOff + fv[3]] * dim + d]) - origin[d];
28690ec8681fSMatthew G. Knepley       }
28700ec8681fSMatthew G. Knepley       Volume_Tetrahedron_Origin_Internal(&vtmp, coordsTmp);
28716858538eSMatthew G. Knepley       if (flip) vtmp = -vtmp;
28720ec8681fSMatthew G. Knepley       vsum += vtmp;
28730ec8681fSMatthew G. Knepley       if (centroid) {
28740ec8681fSMatthew G. Knepley         for (d = 0; d < dim; ++d) {
28750ec8681fSMatthew G. Knepley           for (p = 0; p < 3; ++p) centroid[d] += coordsTmp[p * dim + d] * vtmp;
28760ec8681fSMatthew G. Knepley         }
28770ec8681fSMatthew G. Knepley       }
28780ec8681fSMatthew G. Knepley       /* Second tet */
28790ec8681fSMatthew G. Knepley       for (d = 0; d < dim; ++d) {
28806858538eSMatthew G. Knepley         coordsTmp[0 * dim + d] = PetscRealPart(coords[faces[fOff + fv[1]] * dim + d]) - origin[d];
28816858538eSMatthew G. Knepley         coordsTmp[1 * dim + d] = PetscRealPart(coords[faces[fOff + fv[2]] * dim + d]) - origin[d];
28826858538eSMatthew G. Knepley         coordsTmp[2 * dim + d] = PetscRealPart(coords[faces[fOff + fv[3]] * dim + d]) - origin[d];
28830ec8681fSMatthew G. Knepley       }
28840ec8681fSMatthew G. Knepley       Volume_Tetrahedron_Origin_Internal(&vtmp, coordsTmp);
28856858538eSMatthew G. Knepley       if (flip) vtmp = -vtmp;
28860ec8681fSMatthew G. Knepley       vsum += vtmp;
28870ec8681fSMatthew G. Knepley       if (centroid) {
28880ec8681fSMatthew G. Knepley         for (d = 0; d < dim; ++d) {
28890ec8681fSMatthew G. Knepley           for (p = 0; p < 3; ++p) centroid[d] += coordsTmp[p * dim + d] * vtmp;
28900ec8681fSMatthew G. Knepley         }
28910ec8681fSMatthew G. Knepley       }
28920ec8681fSMatthew G. Knepley       break;
2893793a2a13SMatthew G. Knepley     }
2894d71ae5a4SJacob Faibussowitsch     default:
2895d71ae5a4SJacob Faibussowitsch       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle face %" PetscInt_FMT " of type %s", cone[f], DMPolytopeTypes[ct]);
28960ec8681fSMatthew G. Knepley     }
28976858538eSMatthew G. Knepley     fOff += faceSizes[f];
28980ec8681fSMatthew G. Knepley   }
28996858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreRawFaces_Internal(dm, ct, order, &numFaces, &faceTypes, &faceSizes, &faces));
29006858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, cell, &isDG, &coordSize, &array, &coords));
29018763be8eSMatthew G. Knepley   if (vol) *vol = PetscAbsReal(vsum);
29029371c9d4SSatish Balay   if (normal)
29039371c9d4SSatish Balay     for (d = 0; d < dim; ++d) normal[d] = 0.0;
29049371c9d4SSatish Balay   if (centroid)
29059371c9d4SSatish Balay     for (d = 0; d < dim; ++d) centroid[d] = centroid[d] / (vsum * 4) + origin[d];
29063ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
29070ec8681fSMatthew G. Knepley }
29080ec8681fSMatthew G. Knepley 
2909834e62ceSMatthew G. Knepley /*@C
2910834e62ceSMatthew G. Knepley   DMPlexComputeCellGeometryFVM - Compute the volume for a given cell
2911834e62ceSMatthew G. Knepley 
291220f4b53cSBarry Smith   Collective
2913834e62ceSMatthew G. Knepley 
29144165533cSJose E. Roman   Input Parameters:
291520f4b53cSBarry Smith + dm   - the `DMPLEX`
2916834e62ceSMatthew G. Knepley - cell - the cell
2917834e62ceSMatthew G. Knepley 
29184165533cSJose E. Roman   Output Parameters:
291960225df5SJacob Faibussowitsch + vol      - the cell volume
2920cc08537eSMatthew G. Knepley . centroid - the cell centroid
2921cc08537eSMatthew G. Knepley - normal   - the cell normal, if appropriate
2922834e62ceSMatthew G. Knepley 
2923834e62ceSMatthew G. Knepley   Level: advanced
2924834e62ceSMatthew G. Knepley 
292520f4b53cSBarry Smith .seealso: `DMPLEX`, `DMGetCoordinateSection()`, `DMGetCoordinates()`
2926834e62ceSMatthew G. Knepley @*/
2927d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexComputeCellGeometryFVM(DM dm, PetscInt cell, PetscReal *vol, PetscReal centroid[], PetscReal normal[])
2928d71ae5a4SJacob Faibussowitsch {
29290ec8681fSMatthew G. Knepley   PetscInt depth, dim;
2930834e62ceSMatthew G. Knepley 
2931834e62ceSMatthew G. Knepley   PetscFunctionBegin;
29329566063dSJacob Faibussowitsch   PetscCall(DMPlexGetDepth(dm, &depth));
29339566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dim));
293408401ef6SPierre Jolivet   PetscCheck(depth == dim, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh must be interpolated");
29359566063dSJacob Faibussowitsch   PetscCall(DMPlexGetPointDepth(dm, cell, &depth));
2936011ea5d8SMatthew G. Knepley   switch (depth) {
2937d71ae5a4SJacob Faibussowitsch   case 0:
2938d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexComputeGeometryFVM_0D_Internal(dm, dim, cell, vol, centroid, normal));
2939d71ae5a4SJacob Faibussowitsch     break;
2940d71ae5a4SJacob Faibussowitsch   case 1:
2941d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexComputeGeometryFVM_1D_Internal(dm, dim, cell, vol, centroid, normal));
2942d71ae5a4SJacob Faibussowitsch     break;
2943d71ae5a4SJacob Faibussowitsch   case 2:
2944d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexComputeGeometryFVM_2D_Internal(dm, dim, cell, vol, centroid, normal));
2945d71ae5a4SJacob Faibussowitsch     break;
2946d71ae5a4SJacob Faibussowitsch   case 3:
2947d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexComputeGeometryFVM_3D_Internal(dm, dim, cell, vol, centroid, normal));
2948d71ae5a4SJacob Faibussowitsch     break;
2949d71ae5a4SJacob Faibussowitsch   default:
2950d71ae5a4SJacob Faibussowitsch     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Unsupported dimension %" PetscInt_FMT " (depth %" PetscInt_FMT ") for element geometry computation", dim, depth);
2951834e62ceSMatthew G. Knepley   }
29523ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2953834e62ceSMatthew G. Knepley }
2954113c68e6SMatthew G. Knepley 
2955c501906fSMatthew G. Knepley /*@
2956891a9168SMatthew G. Knepley   DMPlexComputeGeometryFVM - Computes the cell and face geometry for a finite volume method
2957891a9168SMatthew G. Knepley 
2958891a9168SMatthew G. Knepley   Input Parameter:
295920f4b53cSBarry Smith . dm - The `DMPLEX`
2960891a9168SMatthew G. Knepley 
2961891a9168SMatthew G. Knepley   Output Parameters:
296220f4b53cSBarry Smith + cellgeom - A `Vec` of `PetscFVCellGeom` data
296320f4b53cSBarry Smith - facegeom - A `Vec` of `PetscFVFaceGeom` data
2964891a9168SMatthew G. Knepley 
2965891a9168SMatthew G. Knepley   Level: developer
2966891a9168SMatthew G. Knepley 
296720f4b53cSBarry Smith .seealso: `DMPLEX`, `PetscFVFaceGeom`, `PetscFVCellGeom`
2968891a9168SMatthew G. Knepley @*/
2969d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexComputeGeometryFVM(DM dm, Vec *cellgeom, Vec *facegeom)
2970d71ae5a4SJacob Faibussowitsch {
2971113c68e6SMatthew G. Knepley   DM           dmFace, dmCell;
2972113c68e6SMatthew G. Knepley   DMLabel      ghostLabel;
2973113c68e6SMatthew G. Knepley   PetscSection sectionFace, sectionCell;
2974113c68e6SMatthew G. Knepley   PetscSection coordSection;
2975113c68e6SMatthew G. Knepley   Vec          coordinates;
2976113c68e6SMatthew G. Knepley   PetscScalar *fgeom, *cgeom;
2977113c68e6SMatthew G. Knepley   PetscReal    minradius, gminradius;
2978113c68e6SMatthew G. Knepley   PetscInt     dim, cStart, cEnd, cEndInterior, c, fStart, fEnd, f;
2979113c68e6SMatthew G. Knepley 
2980113c68e6SMatthew G. Knepley   PetscFunctionBegin;
29819566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dim));
29829566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateSection(dm, &coordSection));
29839566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
2984113c68e6SMatthew G. Knepley   /* Make cell centroids and volumes */
29859566063dSJacob Faibussowitsch   PetscCall(DMClone(dm, &dmCell));
29869566063dSJacob Faibussowitsch   PetscCall(DMSetCoordinateSection(dmCell, PETSC_DETERMINE, coordSection));
29879566063dSJacob Faibussowitsch   PetscCall(DMSetCoordinatesLocal(dmCell, coordinates));
29889566063dSJacob Faibussowitsch   PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &sectionCell));
29899566063dSJacob Faibussowitsch   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
29902827ebadSStefano Zampini   PetscCall(DMPlexGetCellTypeStratum(dm, DM_POLYTOPE_FV_GHOST, &cEndInterior, NULL));
29919566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetChart(sectionCell, cStart, cEnd));
29929566063dSJacob Faibussowitsch   for (c = cStart; c < cEnd; ++c) PetscCall(PetscSectionSetDof(sectionCell, c, (PetscInt)PetscCeilReal(((PetscReal)sizeof(PetscFVCellGeom)) / sizeof(PetscScalar))));
29939566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetUp(sectionCell));
29949566063dSJacob Faibussowitsch   PetscCall(DMSetLocalSection(dmCell, sectionCell));
29959566063dSJacob Faibussowitsch   PetscCall(PetscSectionDestroy(&sectionCell));
29969566063dSJacob Faibussowitsch   PetscCall(DMCreateLocalVector(dmCell, cellgeom));
2997485ad865SMatthew G. Knepley   if (cEndInterior < 0) cEndInterior = cEnd;
29989566063dSJacob Faibussowitsch   PetscCall(VecGetArray(*cellgeom, &cgeom));
2999113c68e6SMatthew G. Knepley   for (c = cStart; c < cEndInterior; ++c) {
3000113c68e6SMatthew G. Knepley     PetscFVCellGeom *cg;
3001113c68e6SMatthew G. Knepley 
30029566063dSJacob Faibussowitsch     PetscCall(DMPlexPointLocalRef(dmCell, c, cgeom, &cg));
30039566063dSJacob Faibussowitsch     PetscCall(PetscArrayzero(cg, 1));
30049566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeCellGeometryFVM(dmCell, c, &cg->volume, cg->centroid, NULL));
3005113c68e6SMatthew G. Knepley   }
3006113c68e6SMatthew G. Knepley   /* Compute face normals and minimum cell radius */
30079566063dSJacob Faibussowitsch   PetscCall(DMClone(dm, &dmFace));
30089566063dSJacob Faibussowitsch   PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &sectionFace));
30099566063dSJacob Faibussowitsch   PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
30109566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetChart(sectionFace, fStart, fEnd));
30119566063dSJacob Faibussowitsch   for (f = fStart; f < fEnd; ++f) PetscCall(PetscSectionSetDof(sectionFace, f, (PetscInt)PetscCeilReal(((PetscReal)sizeof(PetscFVFaceGeom)) / sizeof(PetscScalar))));
30129566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetUp(sectionFace));
30139566063dSJacob Faibussowitsch   PetscCall(DMSetLocalSection(dmFace, sectionFace));
30149566063dSJacob Faibussowitsch   PetscCall(PetscSectionDestroy(&sectionFace));
30159566063dSJacob Faibussowitsch   PetscCall(DMCreateLocalVector(dmFace, facegeom));
30169566063dSJacob Faibussowitsch   PetscCall(VecGetArray(*facegeom, &fgeom));
30179566063dSJacob Faibussowitsch   PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
3018113c68e6SMatthew G. Knepley   minradius = PETSC_MAX_REAL;
3019113c68e6SMatthew G. Knepley   for (f = fStart; f < fEnd; ++f) {
3020113c68e6SMatthew G. Knepley     PetscFVFaceGeom *fg;
3021113c68e6SMatthew G. Knepley     PetscReal        area;
3022412e9a14SMatthew G. Knepley     const PetscInt  *cells;
3023412e9a14SMatthew G. Knepley     PetscInt         ncells, ghost = -1, d, numChildren;
3024113c68e6SMatthew G. Knepley 
30259566063dSJacob Faibussowitsch     if (ghostLabel) PetscCall(DMLabelGetValue(ghostLabel, f, &ghost));
30269566063dSJacob Faibussowitsch     PetscCall(DMPlexGetTreeChildren(dm, f, &numChildren, NULL));
30279566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupport(dm, f, &cells));
30289566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupportSize(dm, f, &ncells));
3029412e9a14SMatthew G. Knepley     /* It is possible to get a face with no support when using partition overlap */
3030412e9a14SMatthew G. Knepley     if (!ncells || ghost >= 0 || numChildren) continue;
30319566063dSJacob Faibussowitsch     PetscCall(DMPlexPointLocalRef(dmFace, f, fgeom, &fg));
30329566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeCellGeometryFVM(dm, f, &area, fg->centroid, fg->normal));
3033113c68e6SMatthew G. Knepley     for (d = 0; d < dim; ++d) fg->normal[d] *= area;
3034113c68e6SMatthew G. Knepley     /* Flip face orientation if necessary to match ordering in support, and Update minimum radius */
3035113c68e6SMatthew G. Knepley     {
3036113c68e6SMatthew G. Knepley       PetscFVCellGeom *cL, *cR;
3037113c68e6SMatthew G. Knepley       PetscReal       *lcentroid, *rcentroid;
30380453c0cdSMatthew G. Knepley       PetscReal        l[3], r[3], v[3];
3039113c68e6SMatthew G. Knepley 
30409566063dSJacob Faibussowitsch       PetscCall(DMPlexPointLocalRead(dmCell, cells[0], cgeom, &cL));
3041113c68e6SMatthew G. Knepley       lcentroid = cells[0] >= cEndInterior ? fg->centroid : cL->centroid;
304206348e87SToby Isaac       if (ncells > 1) {
30439566063dSJacob Faibussowitsch         PetscCall(DMPlexPointLocalRead(dmCell, cells[1], cgeom, &cR));
3044113c68e6SMatthew G. Knepley         rcentroid = cells[1] >= cEndInterior ? fg->centroid : cR->centroid;
30459371c9d4SSatish Balay       } else {
304606348e87SToby Isaac         rcentroid = fg->centroid;
304706348e87SToby Isaac       }
30489566063dSJacob Faibussowitsch       PetscCall(DMLocalizeCoordinateReal_Internal(dm, dim, fg->centroid, lcentroid, l));
30499566063dSJacob Faibussowitsch       PetscCall(DMLocalizeCoordinateReal_Internal(dm, dim, fg->centroid, rcentroid, r));
30500453c0cdSMatthew G. Knepley       DMPlex_WaxpyD_Internal(dim, -1, l, r, v);
3051113c68e6SMatthew G. Knepley       if (DMPlex_DotRealD_Internal(dim, fg->normal, v) < 0) {
3052113c68e6SMatthew G. Knepley         for (d = 0; d < dim; ++d) fg->normal[d] = -fg->normal[d];
3053113c68e6SMatthew G. Knepley       }
3054113c68e6SMatthew G. Knepley       if (DMPlex_DotRealD_Internal(dim, fg->normal, v) <= 0) {
305563a3b9bcSJacob Faibussowitsch         PetscCheck(dim != 2, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Direction for face %" PetscInt_FMT " could not be fixed, normal (%g,%g) v (%g,%g)", f, (double)fg->normal[0], (double)fg->normal[1], (double)v[0], (double)v[1]);
305663a3b9bcSJacob Faibussowitsch         PetscCheck(dim != 3, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Direction for face %" PetscInt_FMT " could not be fixed, normal (%g,%g,%g) v (%g,%g,%g)", f, (double)fg->normal[0], (double)fg->normal[1], (double)fg->normal[2], (double)v[0], (double)v[1], (double)v[2]);
305763a3b9bcSJacob Faibussowitsch         SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Direction for face %" PetscInt_FMT " could not be fixed", f);
3058113c68e6SMatthew G. Knepley       }
3059113c68e6SMatthew G. Knepley       if (cells[0] < cEndInterior) {
3060113c68e6SMatthew G. Knepley         DMPlex_WaxpyD_Internal(dim, -1, fg->centroid, cL->centroid, v);
3061113c68e6SMatthew G. Knepley         minradius = PetscMin(minradius, DMPlex_NormD_Internal(dim, v));
3062113c68e6SMatthew G. Knepley       }
306306348e87SToby Isaac       if (ncells > 1 && cells[1] < cEndInterior) {
3064113c68e6SMatthew G. Knepley         DMPlex_WaxpyD_Internal(dim, -1, fg->centroid, cR->centroid, v);
3065113c68e6SMatthew G. Knepley         minradius = PetscMin(minradius, DMPlex_NormD_Internal(dim, v));
3066113c68e6SMatthew G. Knepley       }
3067113c68e6SMatthew G. Knepley     }
3068113c68e6SMatthew G. Knepley   }
3069462c564dSBarry Smith   PetscCallMPI(MPIU_Allreduce(&minradius, &gminradius, 1, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)dm)));
30709566063dSJacob Faibussowitsch   PetscCall(DMPlexSetMinRadius(dm, gminradius));
3071113c68e6SMatthew G. Knepley   /* Compute centroids of ghost cells */
3072113c68e6SMatthew G. Knepley   for (c = cEndInterior; c < cEnd; ++c) {
3073113c68e6SMatthew G. Knepley     PetscFVFaceGeom *fg;
3074113c68e6SMatthew G. Knepley     const PetscInt  *cone, *support;
3075113c68e6SMatthew G. Knepley     PetscInt         coneSize, supportSize, s;
3076113c68e6SMatthew G. Knepley 
30779566063dSJacob Faibussowitsch     PetscCall(DMPlexGetConeSize(dmCell, c, &coneSize));
307863a3b9bcSJacob Faibussowitsch     PetscCheck(coneSize == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Ghost cell %" PetscInt_FMT " has cone size %" PetscInt_FMT " != 1", c, coneSize);
30799566063dSJacob Faibussowitsch     PetscCall(DMPlexGetCone(dmCell, c, &cone));
30809566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupportSize(dmCell, cone[0], &supportSize));
308163a3b9bcSJacob Faibussowitsch     PetscCheck(supportSize == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " has support size %" PetscInt_FMT " != 2", cone[0], supportSize);
30829566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupport(dmCell, cone[0], &support));
30839566063dSJacob Faibussowitsch     PetscCall(DMPlexPointLocalRef(dmFace, cone[0], fgeom, &fg));
3084113c68e6SMatthew G. Knepley     for (s = 0; s < 2; ++s) {
3085113c68e6SMatthew G. Knepley       /* Reflect ghost centroid across plane of face */
3086113c68e6SMatthew G. Knepley       if (support[s] == c) {
3087640bce14SSatish Balay         PetscFVCellGeom *ci;
3088113c68e6SMatthew G. Knepley         PetscFVCellGeom *cg;
3089113c68e6SMatthew G. Knepley         PetscReal        c2f[3], a;
3090113c68e6SMatthew G. Knepley 
30919566063dSJacob Faibussowitsch         PetscCall(DMPlexPointLocalRead(dmCell, support[(s + 1) % 2], cgeom, &ci));
3092113c68e6SMatthew G. Knepley         DMPlex_WaxpyD_Internal(dim, -1, ci->centroid, fg->centroid, c2f); /* cell to face centroid */
3093113c68e6SMatthew G. Knepley         a = DMPlex_DotRealD_Internal(dim, c2f, fg->normal) / DMPlex_DotRealD_Internal(dim, fg->normal, fg->normal);
30949566063dSJacob Faibussowitsch         PetscCall(DMPlexPointLocalRef(dmCell, support[s], cgeom, &cg));
3095113c68e6SMatthew G. Knepley         DMPlex_WaxpyD_Internal(dim, 2 * a, fg->normal, ci->centroid, cg->centroid);
3096113c68e6SMatthew G. Knepley         cg->volume = ci->volume;
3097113c68e6SMatthew G. Knepley       }
3098113c68e6SMatthew G. Knepley     }
3099113c68e6SMatthew G. Knepley   }
31009566063dSJacob Faibussowitsch   PetscCall(VecRestoreArray(*facegeom, &fgeom));
31019566063dSJacob Faibussowitsch   PetscCall(VecRestoreArray(*cellgeom, &cgeom));
31029566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&dmCell));
31039566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&dmFace));
31043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3105113c68e6SMatthew G. Knepley }
3106113c68e6SMatthew G. Knepley 
3107cc4c1da9SBarry Smith /*@
3108113c68e6SMatthew G. Knepley   DMPlexGetMinRadius - Returns the minimum distance from any cell centroid to a face
3109113c68e6SMatthew G. Knepley 
311020f4b53cSBarry Smith   Not Collective
3111113c68e6SMatthew G. Knepley 
31124165533cSJose E. Roman   Input Parameter:
311320f4b53cSBarry Smith . dm - the `DMPLEX`
3114113c68e6SMatthew G. Knepley 
31154165533cSJose E. Roman   Output Parameter:
3116a5b23f4aSJose E. Roman . minradius - the minimum cell radius
3117113c68e6SMatthew G. Knepley 
3118113c68e6SMatthew G. Knepley   Level: developer
3119113c68e6SMatthew G. Knepley 
312020f4b53cSBarry Smith .seealso: `DMPLEX`, `DMGetCoordinates()`
3121113c68e6SMatthew G. Knepley @*/
3122d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexGetMinRadius(DM dm, PetscReal *minradius)
3123d71ae5a4SJacob Faibussowitsch {
3124113c68e6SMatthew G. Knepley   PetscFunctionBegin;
3125113c68e6SMatthew G. Knepley   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
31264f572ea9SToby Isaac   PetscAssertPointer(minradius, 2);
3127113c68e6SMatthew G. Knepley   *minradius = ((DM_Plex *)dm->data)->minradius;
31283ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3129113c68e6SMatthew G. Knepley }
3130113c68e6SMatthew G. Knepley 
3131cc4c1da9SBarry Smith /*@
3132113c68e6SMatthew G. Knepley   DMPlexSetMinRadius - Sets the minimum distance from the cell centroid to a face
3133113c68e6SMatthew G. Knepley 
313420f4b53cSBarry Smith   Logically Collective
3135113c68e6SMatthew G. Knepley 
31364165533cSJose E. Roman   Input Parameters:
313720f4b53cSBarry Smith + dm        - the `DMPLEX`
3138a5b23f4aSJose E. Roman - minradius - the minimum cell radius
3139113c68e6SMatthew G. Knepley 
3140113c68e6SMatthew G. Knepley   Level: developer
3141113c68e6SMatthew G. Knepley 
314220f4b53cSBarry Smith .seealso: `DMPLEX`, `DMSetCoordinates()`
3143113c68e6SMatthew G. Knepley @*/
3144d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexSetMinRadius(DM dm, PetscReal minradius)
3145d71ae5a4SJacob Faibussowitsch {
3146113c68e6SMatthew G. Knepley   PetscFunctionBegin;
3147113c68e6SMatthew G. Knepley   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
3148113c68e6SMatthew G. Knepley   ((DM_Plex *)dm->data)->minradius = minradius;
31493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3150113c68e6SMatthew G. Knepley }
3151856ac710SMatthew G. Knepley 
3152d71ae5a4SJacob Faibussowitsch static PetscErrorCode BuildGradientReconstruction_Internal(DM dm, PetscFV fvm, DM dmFace, PetscScalar *fgeom, DM dmCell, PetscScalar *cgeom)
3153d71ae5a4SJacob Faibussowitsch {
3154856ac710SMatthew G. Knepley   DMLabel      ghostLabel;
3155856ac710SMatthew G. Knepley   PetscScalar *dx, *grad, **gref;
3156856ac710SMatthew G. Knepley   PetscInt     dim, cStart, cEnd, c, cEndInterior, maxNumFaces;
3157856ac710SMatthew G. Knepley 
3158856ac710SMatthew G. Knepley   PetscFunctionBegin;
31599566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dim));
31609566063dSJacob Faibussowitsch   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
31612827ebadSStefano Zampini   PetscCall(DMPlexGetCellTypeStratum(dm, DM_POLYTOPE_FV_GHOST, &cEndInterior, NULL));
3162089217ebSMatthew G. Knepley   cEndInterior = cEndInterior < 0 ? cEnd : cEndInterior;
31639566063dSJacob Faibussowitsch   PetscCall(DMPlexGetMaxSizes(dm, &maxNumFaces, NULL));
31649566063dSJacob Faibussowitsch   PetscCall(PetscFVLeastSquaresSetMaxFaces(fvm, maxNumFaces));
31659566063dSJacob Faibussowitsch   PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
31669566063dSJacob Faibussowitsch   PetscCall(PetscMalloc3(maxNumFaces * dim, &dx, maxNumFaces * dim, &grad, maxNumFaces, &gref));
3167856ac710SMatthew G. Knepley   for (c = cStart; c < cEndInterior; c++) {
3168856ac710SMatthew G. Knepley     const PetscInt  *faces;
3169856ac710SMatthew G. Knepley     PetscInt         numFaces, usedFaces, f, d;
3170640bce14SSatish Balay     PetscFVCellGeom *cg;
3171856ac710SMatthew G. Knepley     PetscBool        boundary;
3172856ac710SMatthew G. Knepley     PetscInt         ghost;
3173856ac710SMatthew G. Knepley 
3174a79418b7SMatt McGurn     // do not attempt to compute a gradient reconstruction stencil in a ghost cell.  It will never be used
3175a79418b7SMatt McGurn     PetscCall(DMLabelGetValue(ghostLabel, c, &ghost));
3176a79418b7SMatt McGurn     if (ghost >= 0) continue;
3177a79418b7SMatt McGurn 
31789566063dSJacob Faibussowitsch     PetscCall(DMPlexPointLocalRead(dmCell, c, cgeom, &cg));
31799566063dSJacob Faibussowitsch     PetscCall(DMPlexGetConeSize(dm, c, &numFaces));
31809566063dSJacob Faibussowitsch     PetscCall(DMPlexGetCone(dm, c, &faces));
318163a3b9bcSJacob Faibussowitsch     PetscCheck(numFaces >= dim, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Cell %" PetscInt_FMT " has only %" PetscInt_FMT " faces, not enough for gradient reconstruction", c, numFaces);
3182856ac710SMatthew G. Knepley     for (f = 0, usedFaces = 0; f < numFaces; ++f) {
3183640bce14SSatish Balay       PetscFVCellGeom *cg1;
3184856ac710SMatthew G. Knepley       PetscFVFaceGeom *fg;
3185856ac710SMatthew G. Knepley       const PetscInt  *fcells;
3186856ac710SMatthew G. Knepley       PetscInt         ncell, side;
3187856ac710SMatthew G. Knepley 
31889566063dSJacob Faibussowitsch       PetscCall(DMLabelGetValue(ghostLabel, faces[f], &ghost));
31899566063dSJacob Faibussowitsch       PetscCall(DMIsBoundaryPoint(dm, faces[f], &boundary));
3190856ac710SMatthew G. Knepley       if ((ghost >= 0) || boundary) continue;
31919566063dSJacob Faibussowitsch       PetscCall(DMPlexGetSupport(dm, faces[f], &fcells));
3192856ac710SMatthew G. Knepley       side  = (c != fcells[0]); /* c is on left=0 or right=1 of face */
3193856ac710SMatthew G. Knepley       ncell = fcells[!side];    /* the neighbor */
31949566063dSJacob Faibussowitsch       PetscCall(DMPlexPointLocalRef(dmFace, faces[f], fgeom, &fg));
31959566063dSJacob Faibussowitsch       PetscCall(DMPlexPointLocalRead(dmCell, ncell, cgeom, &cg1));
3196856ac710SMatthew G. Knepley       for (d = 0; d < dim; ++d) dx[usedFaces * dim + d] = cg1->centroid[d] - cg->centroid[d];
3197856ac710SMatthew G. Knepley       gref[usedFaces++] = fg->grad[side]; /* Gradient reconstruction term will go here */
3198856ac710SMatthew G. Knepley     }
319928b400f6SJacob Faibussowitsch     PetscCheck(usedFaces, PETSC_COMM_SELF, PETSC_ERR_USER, "Mesh contains isolated cell (no neighbors). Is it intentional?");
32009566063dSJacob Faibussowitsch     PetscCall(PetscFVComputeGradient(fvm, usedFaces, dx, grad));
3201856ac710SMatthew G. Knepley     for (f = 0, usedFaces = 0; f < numFaces; ++f) {
32029566063dSJacob Faibussowitsch       PetscCall(DMLabelGetValue(ghostLabel, faces[f], &ghost));
32039566063dSJacob Faibussowitsch       PetscCall(DMIsBoundaryPoint(dm, faces[f], &boundary));
3204856ac710SMatthew G. Knepley       if ((ghost >= 0) || boundary) continue;
3205856ac710SMatthew G. Knepley       for (d = 0; d < dim; ++d) gref[usedFaces][d] = grad[usedFaces * dim + d];
3206856ac710SMatthew G. Knepley       ++usedFaces;
3207856ac710SMatthew G. Knepley     }
3208856ac710SMatthew G. Knepley   }
32099566063dSJacob Faibussowitsch   PetscCall(PetscFree3(dx, grad, gref));
32103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3211856ac710SMatthew G. Knepley }
3212856ac710SMatthew G. Knepley 
3213d71ae5a4SJacob Faibussowitsch static PetscErrorCode BuildGradientReconstruction_Internal_Tree(DM dm, PetscFV fvm, DM dmFace, PetscScalar *fgeom, DM dmCell, PetscScalar *cgeom)
3214d71ae5a4SJacob Faibussowitsch {
3215b81db932SToby Isaac   DMLabel      ghostLabel;
3216b81db932SToby Isaac   PetscScalar *dx, *grad, **gref;
3217b81db932SToby Isaac   PetscInt     dim, cStart, cEnd, c, cEndInterior, fStart, fEnd, f, nStart, nEnd, maxNumFaces = 0;
3218b81db932SToby Isaac   PetscSection neighSec;
3219b81db932SToby Isaac   PetscInt (*neighbors)[2];
3220b81db932SToby Isaac   PetscInt *counter;
3221b81db932SToby Isaac 
3222b81db932SToby Isaac   PetscFunctionBegin;
32239566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dim));
32249566063dSJacob Faibussowitsch   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
32252827ebadSStefano Zampini   PetscCall(DMPlexGetCellTypeStratum(dm, DM_POLYTOPE_FV_GHOST, &cEndInterior, NULL));
3226485ad865SMatthew G. Knepley   if (cEndInterior < 0) cEndInterior = cEnd;
32279566063dSJacob Faibussowitsch   PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &neighSec));
32289566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetChart(neighSec, cStart, cEndInterior));
32299566063dSJacob Faibussowitsch   PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
32309566063dSJacob Faibussowitsch   PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
3231b81db932SToby Isaac   for (f = fStart; f < fEnd; f++) {
3232b81db932SToby Isaac     const PetscInt *fcells;
3233b81db932SToby Isaac     PetscBool       boundary;
32345bc680faSToby Isaac     PetscInt        ghost = -1;
3235b81db932SToby Isaac     PetscInt        numChildren, numCells, c;
3236b81db932SToby Isaac 
32379566063dSJacob Faibussowitsch     if (ghostLabel) PetscCall(DMLabelGetValue(ghostLabel, f, &ghost));
32389566063dSJacob Faibussowitsch     PetscCall(DMIsBoundaryPoint(dm, f, &boundary));
32399566063dSJacob Faibussowitsch     PetscCall(DMPlexGetTreeChildren(dm, f, &numChildren, NULL));
3240b81db932SToby Isaac     if ((ghost >= 0) || boundary || numChildren) continue;
32419566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupportSize(dm, f, &numCells));
324206348e87SToby Isaac     if (numCells == 2) {
32439566063dSJacob Faibussowitsch       PetscCall(DMPlexGetSupport(dm, f, &fcells));
3244b81db932SToby Isaac       for (c = 0; c < 2; c++) {
3245b81db932SToby Isaac         PetscInt cell = fcells[c];
3246b81db932SToby Isaac 
324748a46eb9SPierre Jolivet         if (cell >= cStart && cell < cEndInterior) PetscCall(PetscSectionAddDof(neighSec, cell, 1));
3248b81db932SToby Isaac       }
3249b81db932SToby Isaac     }
325006348e87SToby Isaac   }
32519566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetUp(neighSec));
32529566063dSJacob Faibussowitsch   PetscCall(PetscSectionGetMaxDof(neighSec, &maxNumFaces));
32539566063dSJacob Faibussowitsch   PetscCall(PetscFVLeastSquaresSetMaxFaces(fvm, maxNumFaces));
3254b81db932SToby Isaac   nStart = 0;
32559566063dSJacob Faibussowitsch   PetscCall(PetscSectionGetStorageSize(neighSec, &nEnd));
325657508eceSPierre Jolivet   PetscCall(PetscMalloc1(nEnd - nStart, &neighbors));
325757508eceSPierre Jolivet   PetscCall(PetscCalloc1(cEndInterior - cStart, &counter));
3258b81db932SToby Isaac   for (f = fStart; f < fEnd; f++) {
3259b81db932SToby Isaac     const PetscInt *fcells;
3260b81db932SToby Isaac     PetscBool       boundary;
32615bc680faSToby Isaac     PetscInt        ghost = -1;
3262b81db932SToby Isaac     PetscInt        numChildren, numCells, c;
3263b81db932SToby Isaac 
32649566063dSJacob Faibussowitsch     if (ghostLabel) PetscCall(DMLabelGetValue(ghostLabel, f, &ghost));
32659566063dSJacob Faibussowitsch     PetscCall(DMIsBoundaryPoint(dm, f, &boundary));
32669566063dSJacob Faibussowitsch     PetscCall(DMPlexGetTreeChildren(dm, f, &numChildren, NULL));
3267b81db932SToby Isaac     if ((ghost >= 0) || boundary || numChildren) continue;
32689566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupportSize(dm, f, &numCells));
326906348e87SToby Isaac     if (numCells == 2) {
32709566063dSJacob Faibussowitsch       PetscCall(DMPlexGetSupport(dm, f, &fcells));
3271b81db932SToby Isaac       for (c = 0; c < 2; c++) {
3272b81db932SToby Isaac         PetscInt cell = fcells[c], off;
3273b81db932SToby Isaac 
3274e6885bbbSToby Isaac         if (cell >= cStart && cell < cEndInterior) {
32759566063dSJacob Faibussowitsch           PetscCall(PetscSectionGetOffset(neighSec, cell, &off));
3276b81db932SToby Isaac           off += counter[cell - cStart]++;
3277b81db932SToby Isaac           neighbors[off][0] = f;
3278b81db932SToby Isaac           neighbors[off][1] = fcells[1 - c];
3279b81db932SToby Isaac         }
3280b81db932SToby Isaac       }
3281b81db932SToby Isaac     }
328206348e87SToby Isaac   }
32839566063dSJacob Faibussowitsch   PetscCall(PetscFree(counter));
32849566063dSJacob Faibussowitsch   PetscCall(PetscMalloc3(maxNumFaces * dim, &dx, maxNumFaces * dim, &grad, maxNumFaces, &gref));
3285b81db932SToby Isaac   for (c = cStart; c < cEndInterior; c++) {
3286317218b9SToby Isaac     PetscInt         numFaces, f, d, off, ghost = -1;
3287640bce14SSatish Balay     PetscFVCellGeom *cg;
3288b81db932SToby Isaac 
32899566063dSJacob Faibussowitsch     PetscCall(DMPlexPointLocalRead(dmCell, c, cgeom, &cg));
32909566063dSJacob Faibussowitsch     PetscCall(PetscSectionGetDof(neighSec, c, &numFaces));
32919566063dSJacob Faibussowitsch     PetscCall(PetscSectionGetOffset(neighSec, c, &off));
3292a79418b7SMatt McGurn 
3293a79418b7SMatt McGurn     // do not attempt to compute a gradient reconstruction stencil in a ghost cell.  It will never be used
32949566063dSJacob Faibussowitsch     if (ghostLabel) PetscCall(DMLabelGetValue(ghostLabel, c, &ghost));
3295a79418b7SMatt McGurn     if (ghost >= 0) continue;
3296a79418b7SMatt McGurn 
329763a3b9bcSJacob Faibussowitsch     PetscCheck(numFaces >= dim, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Cell %" PetscInt_FMT " has only %" PetscInt_FMT " faces, not enough for gradient reconstruction", c, numFaces);
3298b81db932SToby Isaac     for (f = 0; f < numFaces; ++f) {
3299640bce14SSatish Balay       PetscFVCellGeom *cg1;
3300b81db932SToby Isaac       PetscFVFaceGeom *fg;
3301b81db932SToby Isaac       const PetscInt  *fcells;
3302b81db932SToby Isaac       PetscInt         ncell, side, nface;
3303b81db932SToby Isaac 
3304b81db932SToby Isaac       nface = neighbors[off + f][0];
3305b81db932SToby Isaac       ncell = neighbors[off + f][1];
33069566063dSJacob Faibussowitsch       PetscCall(DMPlexGetSupport(dm, nface, &fcells));
3307b81db932SToby Isaac       side = (c != fcells[0]);
33089566063dSJacob Faibussowitsch       PetscCall(DMPlexPointLocalRef(dmFace, nface, fgeom, &fg));
33099566063dSJacob Faibussowitsch       PetscCall(DMPlexPointLocalRead(dmCell, ncell, cgeom, &cg1));
3310b81db932SToby Isaac       for (d = 0; d < dim; ++d) dx[f * dim + d] = cg1->centroid[d] - cg->centroid[d];
3311b81db932SToby Isaac       gref[f] = fg->grad[side]; /* Gradient reconstruction term will go here */
3312b81db932SToby Isaac     }
33139566063dSJacob Faibussowitsch     PetscCall(PetscFVComputeGradient(fvm, numFaces, dx, grad));
3314b81db932SToby Isaac     for (f = 0; f < numFaces; ++f) {
3315b81db932SToby Isaac       for (d = 0; d < dim; ++d) gref[f][d] = grad[f * dim + d];
3316b81db932SToby Isaac     }
3317b81db932SToby Isaac   }
33189566063dSJacob Faibussowitsch   PetscCall(PetscFree3(dx, grad, gref));
33199566063dSJacob Faibussowitsch   PetscCall(PetscSectionDestroy(&neighSec));
33209566063dSJacob Faibussowitsch   PetscCall(PetscFree(neighbors));
33213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3322b81db932SToby Isaac }
3323b81db932SToby Isaac 
3324856ac710SMatthew G. Knepley /*@
3325856ac710SMatthew G. Knepley   DMPlexComputeGradientFVM - Compute geometric factors for gradient reconstruction, which are stored in the geometry data, and compute layout for gradient data
3326856ac710SMatthew G. Knepley 
332720f4b53cSBarry Smith   Collective
3328856ac710SMatthew G. Knepley 
33294165533cSJose E. Roman   Input Parameters:
333020f4b53cSBarry Smith + dm           - The `DMPLEX`
333120f4b53cSBarry Smith . fvm          - The `PetscFV`
333220f4b53cSBarry Smith - cellGeometry - The face geometry from `DMPlexComputeCellGeometryFVM()`
3333856ac710SMatthew G. Knepley 
33346b867d5aSJose E. Roman   Input/Output Parameter:
333520f4b53cSBarry Smith . faceGeometry - The face geometry from `DMPlexComputeFaceGeometryFVM()`; on output
33366b867d5aSJose E. Roman                  the geometric factors for gradient calculation are inserted
33376b867d5aSJose E. Roman 
33386b867d5aSJose E. Roman   Output Parameter:
333920f4b53cSBarry Smith . dmGrad - The `DM` describing the layout of gradient data
3340856ac710SMatthew G. Knepley 
3341856ac710SMatthew G. Knepley   Level: developer
3342856ac710SMatthew G. Knepley 
334320f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexGetFaceGeometryFVM()`, `DMPlexGetCellGeometryFVM()`
3344856ac710SMatthew G. Knepley @*/
3345d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexComputeGradientFVM(DM dm, PetscFV fvm, Vec faceGeometry, Vec cellGeometry, DM *dmGrad)
3346d71ae5a4SJacob Faibussowitsch {
3347856ac710SMatthew G. Knepley   DM           dmFace, dmCell;
3348856ac710SMatthew G. Knepley   PetscScalar *fgeom, *cgeom;
3349b81db932SToby Isaac   PetscSection sectionGrad, parentSection;
3350856ac710SMatthew G. Knepley   PetscInt     dim, pdim, cStart, cEnd, cEndInterior, c;
3351856ac710SMatthew G. Knepley 
3352856ac710SMatthew G. Knepley   PetscFunctionBegin;
33539566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dim));
33549566063dSJacob Faibussowitsch   PetscCall(PetscFVGetNumComponents(fvm, &pdim));
33559566063dSJacob Faibussowitsch   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
33562827ebadSStefano Zampini   PetscCall(DMPlexGetCellTypeStratum(dm, DM_POLYTOPE_FV_GHOST, &cEndInterior, NULL));
3357856ac710SMatthew G. Knepley   /* Construct the interpolant corresponding to each face from the least-square solution over the cell neighborhood */
33589566063dSJacob Faibussowitsch   PetscCall(VecGetDM(faceGeometry, &dmFace));
33599566063dSJacob Faibussowitsch   PetscCall(VecGetDM(cellGeometry, &dmCell));
33609566063dSJacob Faibussowitsch   PetscCall(VecGetArray(faceGeometry, &fgeom));
33619566063dSJacob Faibussowitsch   PetscCall(VecGetArray(cellGeometry, &cgeom));
33629566063dSJacob Faibussowitsch   PetscCall(DMPlexGetTree(dm, &parentSection, NULL, NULL, NULL, NULL));
3363b81db932SToby Isaac   if (!parentSection) {
33649566063dSJacob Faibussowitsch     PetscCall(BuildGradientReconstruction_Internal(dm, fvm, dmFace, fgeom, dmCell, cgeom));
3365b5a3613cSMatthew G. Knepley   } else {
33669566063dSJacob Faibussowitsch     PetscCall(BuildGradientReconstruction_Internal_Tree(dm, fvm, dmFace, fgeom, dmCell, cgeom));
3367b81db932SToby Isaac   }
33689566063dSJacob Faibussowitsch   PetscCall(VecRestoreArray(faceGeometry, &fgeom));
33699566063dSJacob Faibussowitsch   PetscCall(VecRestoreArray(cellGeometry, &cgeom));
3370856ac710SMatthew G. Knepley   /* Create storage for gradients */
33719566063dSJacob Faibussowitsch   PetscCall(DMClone(dm, dmGrad));
33729566063dSJacob Faibussowitsch   PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &sectionGrad));
33739566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetChart(sectionGrad, cStart, cEnd));
33749566063dSJacob Faibussowitsch   for (c = cStart; c < cEnd; ++c) PetscCall(PetscSectionSetDof(sectionGrad, c, pdim * dim));
33759566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetUp(sectionGrad));
33769566063dSJacob Faibussowitsch   PetscCall(DMSetLocalSection(*dmGrad, sectionGrad));
33779566063dSJacob Faibussowitsch   PetscCall(PetscSectionDestroy(&sectionGrad));
33783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3379856ac710SMatthew G. Knepley }
3380b27d5b9eSToby Isaac 
3381c501906fSMatthew G. Knepley /*@
3382c501906fSMatthew G. Knepley   DMPlexGetDataFVM - Retrieve precomputed cell geometry
3383c501906fSMatthew G. Knepley 
338420f4b53cSBarry Smith   Collective
3385c501906fSMatthew G. Knepley 
33864165533cSJose E. Roman   Input Parameters:
338720f4b53cSBarry Smith + dm - The `DM`
338820f4b53cSBarry Smith - fv - The `PetscFV`
3389c501906fSMatthew G. Knepley 
3390c501906fSMatthew G. Knepley   Output Parameters:
339160225df5SJacob Faibussowitsch + cellgeom - The cell geometry
339260225df5SJacob Faibussowitsch . facegeom - The face geometry
33936b867d5aSJose E. Roman - gradDM   - The gradient matrices
3394c501906fSMatthew G. Knepley 
3395c501906fSMatthew G. Knepley   Level: developer
3396c501906fSMatthew G. Knepley 
339720f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexComputeGeometryFVM()`
3398c501906fSMatthew G. Knepley @*/
3399d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexGetDataFVM(DM dm, PetscFV fv, Vec *cellgeom, Vec *facegeom, DM *gradDM)
3400d71ae5a4SJacob Faibussowitsch {
3401b27d5b9eSToby Isaac   PetscObject cellgeomobj, facegeomobj;
3402b27d5b9eSToby Isaac 
3403b27d5b9eSToby Isaac   PetscFunctionBegin;
34049566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject)dm, "DMPlex_cellgeom_fvm", &cellgeomobj));
3405b27d5b9eSToby Isaac   if (!cellgeomobj) {
3406b27d5b9eSToby Isaac     Vec cellgeomInt, facegeomInt;
3407b27d5b9eSToby Isaac 
34089566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeGeometryFVM(dm, &cellgeomInt, &facegeomInt));
34099566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject)dm, "DMPlex_cellgeom_fvm", (PetscObject)cellgeomInt));
34109566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject)dm, "DMPlex_facegeom_fvm", (PetscObject)facegeomInt));
34119566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&cellgeomInt));
34129566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&facegeomInt));
34139566063dSJacob Faibussowitsch     PetscCall(PetscObjectQuery((PetscObject)dm, "DMPlex_cellgeom_fvm", &cellgeomobj));
3414b27d5b9eSToby Isaac   }
34159566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject)dm, "DMPlex_facegeom_fvm", &facegeomobj));
3416b27d5b9eSToby Isaac   if (cellgeom) *cellgeom = (Vec)cellgeomobj;
3417b27d5b9eSToby Isaac   if (facegeom) *facegeom = (Vec)facegeomobj;
3418b27d5b9eSToby Isaac   if (gradDM) {
3419b27d5b9eSToby Isaac     PetscObject gradobj;
3420b27d5b9eSToby Isaac     PetscBool   computeGradients;
3421b27d5b9eSToby Isaac 
34229566063dSJacob Faibussowitsch     PetscCall(PetscFVGetComputeGradients(fv, &computeGradients));
3423b27d5b9eSToby Isaac     if (!computeGradients) {
3424b27d5b9eSToby Isaac       *gradDM = NULL;
34253ba16761SJacob Faibussowitsch       PetscFunctionReturn(PETSC_SUCCESS);
3426b27d5b9eSToby Isaac     }
34279566063dSJacob Faibussowitsch     PetscCall(PetscObjectQuery((PetscObject)dm, "DMPlex_dmgrad_fvm", &gradobj));
3428b27d5b9eSToby Isaac     if (!gradobj) {
3429b27d5b9eSToby Isaac       DM dmGradInt;
3430b27d5b9eSToby Isaac 
34319566063dSJacob Faibussowitsch       PetscCall(DMPlexComputeGradientFVM(dm, fv, (Vec)facegeomobj, (Vec)cellgeomobj, &dmGradInt));
34329566063dSJacob Faibussowitsch       PetscCall(PetscObjectCompose((PetscObject)dm, "DMPlex_dmgrad_fvm", (PetscObject)dmGradInt));
34339566063dSJacob Faibussowitsch       PetscCall(DMDestroy(&dmGradInt));
34349566063dSJacob Faibussowitsch       PetscCall(PetscObjectQuery((PetscObject)dm, "DMPlex_dmgrad_fvm", &gradobj));
3435b27d5b9eSToby Isaac     }
3436b27d5b9eSToby Isaac     *gradDM = (DM)gradobj;
3437b27d5b9eSToby Isaac   }
34383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3439b27d5b9eSToby Isaac }
3440d6143a4eSToby Isaac 
3441d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexCoordinatesToReference_NewtonUpdate(PetscInt dimC, PetscInt dimR, PetscScalar *J, PetscScalar *invJ, PetscScalar *work, PetscReal *resNeg, PetscReal *guess)
3442d71ae5a4SJacob Faibussowitsch {
34439d150b73SToby Isaac   PetscInt l, m;
34449d150b73SToby Isaac 
3445cd345991SToby Isaac   PetscFunctionBeginHot;
34469d150b73SToby Isaac   if (dimC == dimR && dimR <= 3) {
34479d150b73SToby Isaac     /* invert Jacobian, multiply */
34489d150b73SToby Isaac     PetscScalar det, idet;
34499d150b73SToby Isaac 
34509d150b73SToby Isaac     switch (dimR) {
3451d71ae5a4SJacob Faibussowitsch     case 1:
3452d71ae5a4SJacob Faibussowitsch       invJ[0] = 1. / J[0];
3453d71ae5a4SJacob Faibussowitsch       break;
34549d150b73SToby Isaac     case 2:
34559d150b73SToby Isaac       det     = J[0] * J[3] - J[1] * J[2];
34569d150b73SToby Isaac       idet    = 1. / det;
34579d150b73SToby Isaac       invJ[0] = J[3] * idet;
34589d150b73SToby Isaac       invJ[1] = -J[1] * idet;
34599d150b73SToby Isaac       invJ[2] = -J[2] * idet;
34609d150b73SToby Isaac       invJ[3] = J[0] * idet;
34619d150b73SToby Isaac       break;
34629371c9d4SSatish Balay     case 3: {
34639d150b73SToby Isaac       invJ[0] = J[4] * J[8] - J[5] * J[7];
34649d150b73SToby Isaac       invJ[1] = J[2] * J[7] - J[1] * J[8];
34659d150b73SToby Isaac       invJ[2] = J[1] * J[5] - J[2] * J[4];
34669d150b73SToby Isaac       det     = invJ[0] * J[0] + invJ[1] * J[3] + invJ[2] * J[6];
34679d150b73SToby Isaac       idet    = 1. / det;
34689d150b73SToby Isaac       invJ[0] *= idet;
34699d150b73SToby Isaac       invJ[1] *= idet;
34709d150b73SToby Isaac       invJ[2] *= idet;
34719d150b73SToby Isaac       invJ[3] = idet * (J[5] * J[6] - J[3] * J[8]);
34729d150b73SToby Isaac       invJ[4] = idet * (J[0] * J[8] - J[2] * J[6]);
34739d150b73SToby Isaac       invJ[5] = idet * (J[2] * J[3] - J[0] * J[5]);
34749d150b73SToby Isaac       invJ[6] = idet * (J[3] * J[7] - J[4] * J[6]);
34759d150b73SToby Isaac       invJ[7] = idet * (J[1] * J[6] - J[0] * J[7]);
34769d150b73SToby Isaac       invJ[8] = idet * (J[0] * J[4] - J[1] * J[3]);
34779371c9d4SSatish Balay     } break;
34789d150b73SToby Isaac     }
34799d150b73SToby Isaac     for (l = 0; l < dimR; l++) {
3480ad540459SPierre Jolivet       for (m = 0; m < dimC; m++) guess[l] += PetscRealPart(invJ[l * dimC + m]) * resNeg[m];
34819d150b73SToby Isaac     }
34829d150b73SToby Isaac   } else {
34839d150b73SToby Isaac #if defined(PETSC_USE_COMPLEX)
34849d150b73SToby Isaac     char transpose = 'C';
34859d150b73SToby Isaac #else
34869d150b73SToby Isaac     char transpose = 'T';
34879d150b73SToby Isaac #endif
3488835f2295SStefano Zampini     PetscBLASInt m, n, one = 1, worksize, info;
34899d150b73SToby Isaac 
3490835f2295SStefano Zampini     PetscCall(PetscBLASIntCast(dimR, &m));
3491835f2295SStefano Zampini     PetscCall(PetscBLASIntCast(dimC, &n));
3492835f2295SStefano Zampini     PetscCall(PetscBLASIntCast(dimC * dimC, &worksize));
3493ad540459SPierre Jolivet     for (l = 0; l < dimC; l++) invJ[l] = resNeg[l];
34949d150b73SToby Isaac 
3495792fecdfSBarry Smith     PetscCallBLAS("LAPACKgels", LAPACKgels_(&transpose, &m, &n, &one, J, &m, invJ, &n, work, &worksize, &info));
3496835f2295SStefano Zampini     PetscCheck(info == 0, PETSC_COMM_SELF, PETSC_ERR_LIB, "Bad argument to GELS %" PetscBLASInt_FMT, info);
34979d150b73SToby Isaac 
3498ad540459SPierre Jolivet     for (l = 0; l < dimR; l++) guess[l] += PetscRealPart(invJ[l]);
34999d150b73SToby Isaac   }
35003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
35019d150b73SToby Isaac }
35029d150b73SToby Isaac 
3503d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexCoordinatesToReference_Tensor(DM dm, PetscInt cell, PetscInt numPoints, const PetscReal realCoords[], PetscReal refCoords[], Vec coords, PetscInt dimC, PetscInt dimR)
3504d71ae5a4SJacob Faibussowitsch {
3505c0cbe899SToby Isaac   PetscInt     coordSize, i, j, k, l, m, maxIts = 7, numV = (1 << dimR);
35069d150b73SToby Isaac   PetscScalar *coordsScalar = NULL;
35079d150b73SToby Isaac   PetscReal   *cellData, *cellCoords, *cellCoeffs, *extJ, *resNeg;
35089d150b73SToby Isaac   PetscScalar *J, *invJ, *work;
35099d150b73SToby Isaac 
35109d150b73SToby Isaac   PetscFunctionBegin;
35119d150b73SToby Isaac   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
35129566063dSJacob Faibussowitsch   PetscCall(DMPlexVecGetClosure(dm, NULL, coords, cell, &coordSize, &coordsScalar));
35131dca8a05SBarry Smith   PetscCheck(coordSize >= dimC * numV, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Expecting at least %" PetscInt_FMT " coordinates, got %" PetscInt_FMT, dimC * (1 << dimR), coordSize);
35149566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, 2 * coordSize + dimR + dimC, MPIU_REAL, &cellData));
35159566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, 3 * dimR * dimC, MPIU_SCALAR, &J));
35169d150b73SToby Isaac   cellCoords = &cellData[0];
35179d150b73SToby Isaac   cellCoeffs = &cellData[coordSize];
35189d150b73SToby Isaac   extJ       = &cellData[2 * coordSize];
35199d150b73SToby Isaac   resNeg     = &cellData[2 * coordSize + dimR];
35209d150b73SToby Isaac   invJ       = &J[dimR * dimC];
35219d150b73SToby Isaac   work       = &J[2 * dimR * dimC];
35229d150b73SToby Isaac   if (dimR == 2) {
35239d150b73SToby Isaac     const PetscInt zToPlex[4] = {0, 1, 3, 2};
35249d150b73SToby Isaac 
35259d150b73SToby Isaac     for (i = 0; i < 4; i++) {
35269d150b73SToby Isaac       PetscInt plexI = zToPlex[i];
35279d150b73SToby Isaac 
3528ad540459SPierre Jolivet       for (j = 0; j < dimC; j++) cellCoords[dimC * i + j] = PetscRealPart(coordsScalar[dimC * plexI + j]);
35299d150b73SToby Isaac     }
35309d150b73SToby Isaac   } else if (dimR == 3) {
35319d150b73SToby Isaac     const PetscInt zToPlex[8] = {0, 3, 1, 2, 4, 5, 7, 6};
35329d150b73SToby Isaac 
35339d150b73SToby Isaac     for (i = 0; i < 8; i++) {
35349d150b73SToby Isaac       PetscInt plexI = zToPlex[i];
35359d150b73SToby Isaac 
3536ad540459SPierre Jolivet       for (j = 0; j < dimC; j++) cellCoords[dimC * i + j] = PetscRealPart(coordsScalar[dimC * plexI + j]);
35379d150b73SToby Isaac     }
35389d150b73SToby Isaac   } else {
3539ad540459SPierre Jolivet     for (i = 0; i < coordSize; i++) cellCoords[i] = PetscRealPart(coordsScalar[i]);
35409d150b73SToby Isaac   }
35419d150b73SToby Isaac   /* Perform the shuffling transform that converts values at the corners of [-1,1]^d to coefficients */
35429d150b73SToby Isaac   for (i = 0; i < dimR; i++) {
35439d150b73SToby Isaac     PetscReal *swap;
35449d150b73SToby Isaac 
35459d150b73SToby Isaac     for (j = 0; j < (numV / 2); j++) {
35469d150b73SToby Isaac       for (k = 0; k < dimC; k++) {
35479d150b73SToby Isaac         cellCoeffs[dimC * j + k]                = 0.5 * (cellCoords[dimC * (2 * j + 1) + k] + cellCoords[dimC * 2 * j + k]);
35489d150b73SToby Isaac         cellCoeffs[dimC * (j + (numV / 2)) + k] = 0.5 * (cellCoords[dimC * (2 * j + 1) + k] - cellCoords[dimC * 2 * j + k]);
35499d150b73SToby Isaac       }
35509d150b73SToby Isaac     }
35519d150b73SToby Isaac 
35529d150b73SToby Isaac     if (i < dimR - 1) {
35539d150b73SToby Isaac       swap       = cellCoeffs;
35549d150b73SToby Isaac       cellCoeffs = cellCoords;
35559d150b73SToby Isaac       cellCoords = swap;
35569d150b73SToby Isaac     }
35579d150b73SToby Isaac   }
35589566063dSJacob Faibussowitsch   PetscCall(PetscArrayzero(refCoords, numPoints * dimR));
35599d150b73SToby Isaac   for (j = 0; j < numPoints; j++) {
35609d150b73SToby Isaac     for (i = 0; i < maxIts; i++) {
35619d150b73SToby Isaac       PetscReal *guess = &refCoords[dimR * j];
35629d150b73SToby Isaac 
35639d150b73SToby Isaac       /* compute -residual and Jacobian */
3564ad540459SPierre Jolivet       for (k = 0; k < dimC; k++) resNeg[k] = realCoords[dimC * j + k];
3565ad540459SPierre Jolivet       for (k = 0; k < dimC * dimR; k++) J[k] = 0.;
35669d150b73SToby Isaac       for (k = 0; k < numV; k++) {
35679d150b73SToby Isaac         PetscReal extCoord = 1.;
35689d150b73SToby Isaac         for (l = 0; l < dimR; l++) {
35699d150b73SToby Isaac           PetscReal coord = guess[l];
35709d150b73SToby Isaac           PetscInt  dep   = (k & (1 << l)) >> l;
35719d150b73SToby Isaac 
35729d150b73SToby Isaac           extCoord *= dep * coord + !dep;
35739d150b73SToby Isaac           extJ[l] = dep;
35749d150b73SToby Isaac 
35759d150b73SToby Isaac           for (m = 0; m < dimR; m++) {
35769d150b73SToby Isaac             PetscReal coord = guess[m];
35779d150b73SToby Isaac             PetscInt  dep   = ((k & (1 << m)) >> m) && (m != l);
35789d150b73SToby Isaac             PetscReal mult  = dep * coord + !dep;
35799d150b73SToby Isaac 
35809d150b73SToby Isaac             extJ[l] *= mult;
35819d150b73SToby Isaac           }
35829d150b73SToby Isaac         }
35839d150b73SToby Isaac         for (l = 0; l < dimC; l++) {
35849d150b73SToby Isaac           PetscReal coeff = cellCoeffs[dimC * k + l];
35859d150b73SToby Isaac 
35869d150b73SToby Isaac           resNeg[l] -= coeff * extCoord;
3587ad540459SPierre Jolivet           for (m = 0; m < dimR; m++) J[dimR * l + m] += coeff * extJ[m];
35889d150b73SToby Isaac         }
35899d150b73SToby Isaac       }
359076bd3646SJed Brown       if (0 && PetscDefined(USE_DEBUG)) {
35910611203eSToby Isaac         PetscReal maxAbs = 0.;
35920611203eSToby Isaac 
3593ad540459SPierre Jolivet         for (l = 0; l < dimC; l++) maxAbs = PetscMax(maxAbs, PetscAbsReal(resNeg[l]));
359463a3b9bcSJacob Faibussowitsch         PetscCall(PetscInfo(dm, "cell %" PetscInt_FMT ", point %" PetscInt_FMT ", iter %" PetscInt_FMT ": res %g\n", cell, j, i, (double)maxAbs));
35950611203eSToby Isaac       }
35969d150b73SToby Isaac 
35979566063dSJacob Faibussowitsch       PetscCall(DMPlexCoordinatesToReference_NewtonUpdate(dimC, dimR, J, invJ, work, resNeg, guess));
35989d150b73SToby Isaac     }
35999d150b73SToby Isaac   }
36009566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, 3 * dimR * dimC, MPIU_SCALAR, &J));
36019566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, 2 * coordSize + dimR + dimC, MPIU_REAL, &cellData));
36029566063dSJacob Faibussowitsch   PetscCall(DMPlexVecRestoreClosure(dm, NULL, coords, cell, &coordSize, &coordsScalar));
36033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
36049d150b73SToby Isaac }
36059d150b73SToby Isaac 
3606d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexReferenceToCoordinates_Tensor(DM dm, PetscInt cell, PetscInt numPoints, const PetscReal refCoords[], PetscReal realCoords[], Vec coords, PetscInt dimC, PetscInt dimR)
3607d71ae5a4SJacob Faibussowitsch {
36089d150b73SToby Isaac   PetscInt     coordSize, i, j, k, l, numV = (1 << dimR);
36099d150b73SToby Isaac   PetscScalar *coordsScalar = NULL;
36109d150b73SToby Isaac   PetscReal   *cellData, *cellCoords, *cellCoeffs;
36119d150b73SToby Isaac 
36129d150b73SToby Isaac   PetscFunctionBegin;
36139d150b73SToby Isaac   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
36149566063dSJacob Faibussowitsch   PetscCall(DMPlexVecGetClosure(dm, NULL, coords, cell, &coordSize, &coordsScalar));
36151dca8a05SBarry Smith   PetscCheck(coordSize >= dimC * numV, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Expecting at least %" PetscInt_FMT " coordinates, got %" PetscInt_FMT, dimC * (1 << dimR), coordSize);
36169566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, 2 * coordSize, MPIU_REAL, &cellData));
36179d150b73SToby Isaac   cellCoords = &cellData[0];
36189d150b73SToby Isaac   cellCoeffs = &cellData[coordSize];
36199d150b73SToby Isaac   if (dimR == 2) {
36209d150b73SToby Isaac     const PetscInt zToPlex[4] = {0, 1, 3, 2};
36219d150b73SToby Isaac 
36229d150b73SToby Isaac     for (i = 0; i < 4; i++) {
36239d150b73SToby Isaac       PetscInt plexI = zToPlex[i];
36249d150b73SToby Isaac 
3625ad540459SPierre Jolivet       for (j = 0; j < dimC; j++) cellCoords[dimC * i + j] = PetscRealPart(coordsScalar[dimC * plexI + j]);
36269d150b73SToby Isaac     }
36279d150b73SToby Isaac   } else if (dimR == 3) {
36289d150b73SToby Isaac     const PetscInt zToPlex[8] = {0, 3, 1, 2, 4, 5, 7, 6};
36299d150b73SToby Isaac 
36309d150b73SToby Isaac     for (i = 0; i < 8; i++) {
36319d150b73SToby Isaac       PetscInt plexI = zToPlex[i];
36329d150b73SToby Isaac 
3633ad540459SPierre Jolivet       for (j = 0; j < dimC; j++) cellCoords[dimC * i + j] = PetscRealPart(coordsScalar[dimC * plexI + j]);
36349d150b73SToby Isaac     }
36359d150b73SToby Isaac   } else {
3636ad540459SPierre Jolivet     for (i = 0; i < coordSize; i++) cellCoords[i] = PetscRealPart(coordsScalar[i]);
36379d150b73SToby Isaac   }
36389d150b73SToby Isaac   /* Perform the shuffling transform that converts values at the corners of [-1,1]^d to coefficients */
36399d150b73SToby Isaac   for (i = 0; i < dimR; i++) {
36409d150b73SToby Isaac     PetscReal *swap;
36419d150b73SToby Isaac 
36429d150b73SToby Isaac     for (j = 0; j < (numV / 2); j++) {
36439d150b73SToby Isaac       for (k = 0; k < dimC; k++) {
36449d150b73SToby Isaac         cellCoeffs[dimC * j + k]                = 0.5 * (cellCoords[dimC * (2 * j + 1) + k] + cellCoords[dimC * 2 * j + k]);
36459d150b73SToby Isaac         cellCoeffs[dimC * (j + (numV / 2)) + k] = 0.5 * (cellCoords[dimC * (2 * j + 1) + k] - cellCoords[dimC * 2 * j + k]);
36469d150b73SToby Isaac       }
36479d150b73SToby Isaac     }
36489d150b73SToby Isaac 
36499d150b73SToby Isaac     if (i < dimR - 1) {
36509d150b73SToby Isaac       swap       = cellCoeffs;
36519d150b73SToby Isaac       cellCoeffs = cellCoords;
36529d150b73SToby Isaac       cellCoords = swap;
36539d150b73SToby Isaac     }
36549d150b73SToby Isaac   }
36559566063dSJacob Faibussowitsch   PetscCall(PetscArrayzero(realCoords, numPoints * dimC));
36569d150b73SToby Isaac   for (j = 0; j < numPoints; j++) {
36579d150b73SToby Isaac     const PetscReal *guess  = &refCoords[dimR * j];
36589d150b73SToby Isaac     PetscReal       *mapped = &realCoords[dimC * j];
36599d150b73SToby Isaac 
36609d150b73SToby Isaac     for (k = 0; k < numV; k++) {
36619d150b73SToby Isaac       PetscReal extCoord = 1.;
36629d150b73SToby Isaac       for (l = 0; l < dimR; l++) {
36639d150b73SToby Isaac         PetscReal coord = guess[l];
36649d150b73SToby Isaac         PetscInt  dep   = (k & (1 << l)) >> l;
36659d150b73SToby Isaac 
36669d150b73SToby Isaac         extCoord *= dep * coord + !dep;
36679d150b73SToby Isaac       }
36689d150b73SToby Isaac       for (l = 0; l < dimC; l++) {
36699d150b73SToby Isaac         PetscReal coeff = cellCoeffs[dimC * k + l];
36709d150b73SToby Isaac 
36719d150b73SToby Isaac         mapped[l] += coeff * extCoord;
36729d150b73SToby Isaac       }
36739d150b73SToby Isaac     }
36749d150b73SToby Isaac   }
36759566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, 2 * coordSize, MPIU_REAL, &cellData));
36769566063dSJacob Faibussowitsch   PetscCall(DMPlexVecRestoreClosure(dm, NULL, coords, cell, &coordSize, &coordsScalar));
36773ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
36789d150b73SToby Isaac }
36799d150b73SToby Isaac 
3680dd301514SZach Atkins PetscErrorCode DMPlexCoordinatesToReference_FE(DM dm, PetscFE fe, PetscInt cell, PetscInt numPoints, const PetscReal realCoords[], PetscReal refCoords[], Vec coords, PetscInt Nc, PetscInt dimR, PetscInt maxIter, PetscReal *tol)
3681d71ae5a4SJacob Faibussowitsch {
3682dd301514SZach Atkins   PetscInt     numComp, pdim, i, j, k, l, m, coordSize;
3683c6e120d1SToby Isaac   PetscScalar *nodes = NULL;
3684c6e120d1SToby Isaac   PetscReal   *invV, *modes;
3685c6e120d1SToby Isaac   PetscReal   *B, *D, *resNeg;
3686c6e120d1SToby Isaac   PetscScalar *J, *invJ, *work;
3687f0583139SZach Atkins   PetscReal    tolerance = tol == NULL ? 0.0 : *tol;
36889d150b73SToby Isaac 
36899d150b73SToby Isaac   PetscFunctionBegin;
36909566063dSJacob Faibussowitsch   PetscCall(PetscFEGetDimension(fe, &pdim));
36919566063dSJacob Faibussowitsch   PetscCall(PetscFEGetNumComponents(fe, &numComp));
369263a3b9bcSJacob Faibussowitsch   PetscCheck(numComp == Nc, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "coordinate discretization must have as many components (%" PetscInt_FMT ") as embedding dimension (!= %" PetscInt_FMT ")", numComp, Nc);
3693dd301514SZach Atkins   /* we shouldn't apply inverse closure permutation, if one exists */
3694dd301514SZach Atkins   PetscCall(DMPlexVecGetOrientedClosure_Internal(dm, NULL, PETSC_FALSE, coords, cell, 0, &coordSize, &nodes));
36959d150b73SToby Isaac   /* convert nodes to values in the stable evaluation basis */
36969566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, pdim, MPIU_REAL, &modes));
36979d150b73SToby Isaac   invV = fe->invV;
3698012b7cc6SMatthew G. Knepley   for (i = 0; i < pdim; ++i) {
3699012b7cc6SMatthew G. Knepley     modes[i] = 0.;
3700ad540459SPierre Jolivet     for (j = 0; j < pdim; ++j) modes[i] += invV[i * pdim + j] * PetscRealPart(nodes[j]);
37019d150b73SToby Isaac   }
37029566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, pdim * Nc + pdim * Nc * dimR + Nc, MPIU_REAL, &B));
37039c3cf19fSMatthew G. Knepley   D      = &B[pdim * Nc];
37049c3cf19fSMatthew G. Knepley   resNeg = &D[pdim * Nc * dimR];
37059566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, 3 * Nc * dimR, MPIU_SCALAR, &J));
37069c3cf19fSMatthew G. Knepley   invJ = &J[Nc * dimR];
37079c3cf19fSMatthew G. Knepley   work = &invJ[Nc * dimR];
3708ad540459SPierre Jolivet   for (i = 0; i < numPoints * dimR; i++) refCoords[i] = 0.;
37099d150b73SToby Isaac   for (j = 0; j < numPoints; j++) {
3710af9bd97cSZach Atkins     PetscReal normPoint = DMPlex_NormD_Internal(Nc, &realCoords[j * Nc]);
3711af9bd97cSZach Atkins     normPoint           = normPoint > PETSC_SMALL ? normPoint : 1.0;
37129b1f03cbSToby Isaac     for (i = 0; i < maxIter; i++) { /* we could batch this so that we're not making big B and D arrays all the time */
3713f0583139SZach Atkins       PetscReal *guess = &refCoords[j * dimR], error = 0;
37149566063dSJacob Faibussowitsch       PetscCall(PetscSpaceEvaluate(fe->basisSpace, 1, guess, B, D, NULL));
3715ad540459SPierre Jolivet       for (k = 0; k < Nc; k++) resNeg[k] = realCoords[j * Nc + k];
3716ad540459SPierre Jolivet       for (k = 0; k < Nc * dimR; k++) J[k] = 0.;
37179c3cf19fSMatthew G. Knepley       for (k = 0; k < pdim; k++) {
37189c3cf19fSMatthew G. Knepley         for (l = 0; l < Nc; l++) {
3719012b7cc6SMatthew G. Knepley           resNeg[l] -= modes[k] * B[k * Nc + l];
3720ad540459SPierre Jolivet           for (m = 0; m < dimR; m++) J[l * dimR + m] += modes[k] * D[(k * Nc + l) * dimR + m];
37219d150b73SToby Isaac         }
37229d150b73SToby Isaac       }
372376bd3646SJed Brown       if (0 && PetscDefined(USE_DEBUG)) {
37240611203eSToby Isaac         PetscReal maxAbs = 0.;
37250611203eSToby Isaac 
3726ad540459SPierre Jolivet         for (l = 0; l < Nc; l++) maxAbs = PetscMax(maxAbs, PetscAbsReal(resNeg[l]));
372763a3b9bcSJacob Faibussowitsch         PetscCall(PetscInfo(dm, "cell %" PetscInt_FMT ", point %" PetscInt_FMT ", iter %" PetscInt_FMT ": res %g\n", cell, j, i, (double)maxAbs));
37280611203eSToby Isaac       }
3729f0583139SZach Atkins       error = DMPlex_NormD_Internal(Nc, resNeg);
3730af9bd97cSZach Atkins       if (error < tolerance * normPoint) {
3731af9bd97cSZach Atkins         if (tol) *tol = error / normPoint;
3732dd301514SZach Atkins         break;
3733dd301514SZach Atkins       }
37349566063dSJacob Faibussowitsch       PetscCall(DMPlexCoordinatesToReference_NewtonUpdate(Nc, dimR, J, invJ, work, resNeg, guess));
37359d150b73SToby Isaac     }
37369d150b73SToby Isaac   }
37379566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, 3 * Nc * dimR, MPIU_SCALAR, &J));
37389566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, pdim * Nc + pdim * Nc * dimR + Nc, MPIU_REAL, &B));
37399566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, pdim, MPIU_REAL, &modes));
37409566063dSJacob Faibussowitsch   PetscCall(DMPlexVecRestoreClosure(dm, NULL, coords, cell, &coordSize, &nodes));
37413ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
37429d150b73SToby Isaac }
37439d150b73SToby Isaac 
37449c3cf19fSMatthew G. Knepley /* TODO: TOBY please fix this for Nc > 1 */
3745dd301514SZach Atkins PetscErrorCode DMPlexReferenceToCoordinates_FE(DM dm, PetscFE fe, PetscInt cell, PetscInt numPoints, const PetscReal refCoords[], PetscReal realCoords[], Vec coords, PetscInt Nc, PetscInt dimR)
3746d71ae5a4SJacob Faibussowitsch {
37479c3cf19fSMatthew G. Knepley   PetscInt     numComp, pdim, i, j, k, l, coordSize;
3748c6e120d1SToby Isaac   PetscScalar *nodes = NULL;
3749c6e120d1SToby Isaac   PetscReal   *invV, *modes;
37509d150b73SToby Isaac   PetscReal   *B;
37519d150b73SToby Isaac 
37529d150b73SToby Isaac   PetscFunctionBegin;
37539566063dSJacob Faibussowitsch   PetscCall(PetscFEGetDimension(fe, &pdim));
37549566063dSJacob Faibussowitsch   PetscCall(PetscFEGetNumComponents(fe, &numComp));
375563a3b9bcSJacob Faibussowitsch   PetscCheck(numComp == Nc, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "coordinate discretization must have as many components (%" PetscInt_FMT ") as embedding dimension (!= %" PetscInt_FMT ")", numComp, Nc);
3756dd301514SZach Atkins   /* we shouldn't apply inverse closure permutation, if one exists */
3757dd301514SZach Atkins   PetscCall(DMPlexVecGetOrientedClosure_Internal(dm, NULL, PETSC_FALSE, coords, cell, 0, &coordSize, &nodes));
37589d150b73SToby Isaac   /* convert nodes to values in the stable evaluation basis */
37599566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, pdim, MPIU_REAL, &modes));
37609d150b73SToby Isaac   invV = fe->invV;
3761012b7cc6SMatthew G. Knepley   for (i = 0; i < pdim; ++i) {
3762012b7cc6SMatthew G. Knepley     modes[i] = 0.;
3763ad540459SPierre Jolivet     for (j = 0; j < pdim; ++j) modes[i] += invV[i * pdim + j] * PetscRealPart(nodes[j]);
37649d150b73SToby Isaac   }
37659566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, numPoints * pdim * Nc, MPIU_REAL, &B));
37669566063dSJacob Faibussowitsch   PetscCall(PetscSpaceEvaluate(fe->basisSpace, numPoints, refCoords, B, NULL, NULL));
3767ad540459SPierre Jolivet   for (i = 0; i < numPoints * Nc; i++) realCoords[i] = 0.;
37689d150b73SToby Isaac   for (j = 0; j < numPoints; j++) {
37699c3cf19fSMatthew G. Knepley     PetscReal *mapped = &realCoords[j * Nc];
37709d150b73SToby Isaac 
37719c3cf19fSMatthew G. Knepley     for (k = 0; k < pdim; k++) {
3772ad540459SPierre Jolivet       for (l = 0; l < Nc; l++) mapped[l] += modes[k] * B[(j * pdim + k) * Nc + l];
37739d150b73SToby Isaac     }
37749d150b73SToby Isaac   }
37759566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, numPoints * pdim * Nc, MPIU_REAL, &B));
37769566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, pdim, MPIU_REAL, &modes));
37779566063dSJacob Faibussowitsch   PetscCall(DMPlexVecRestoreClosure(dm, NULL, coords, cell, &coordSize, &nodes));
37783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
37799d150b73SToby Isaac }
37809d150b73SToby Isaac 
3781d6143a4eSToby Isaac /*@
3782a4e35b19SJacob Faibussowitsch   DMPlexCoordinatesToReference - Pull coordinates back from the mesh to the reference element
3783a4e35b19SJacob Faibussowitsch   using a single element map.
3784d6143a4eSToby Isaac 
378520f4b53cSBarry Smith   Not Collective
3786d6143a4eSToby Isaac 
3787d6143a4eSToby Isaac   Input Parameters:
378820f4b53cSBarry Smith + dm         - The mesh, with coordinate maps defined either by a `PetscDS` for the coordinate `DM` (see `DMGetCoordinateDM()`) or
3789d6143a4eSToby Isaac                implicitly by the coordinates of the corner vertices of the cell: as an affine map for simplicial elements, or
3790d6143a4eSToby Isaac                as a multilinear map for tensor-product elements
3791d6143a4eSToby Isaac . cell       - the cell whose map is used.
3792d6143a4eSToby Isaac . numPoints  - the number of points to locate
379320f4b53cSBarry Smith - realCoords - (numPoints x coordinate dimension) array of coordinates (see `DMGetCoordinateDim()`)
3794d6143a4eSToby Isaac 
37952fe279fdSBarry Smith   Output Parameter:
379620f4b53cSBarry Smith . refCoords - (`numPoints` x `dimension`) array of reference coordinates (see `DMGetDimension()`)
37971b266c99SBarry Smith 
37981b266c99SBarry Smith   Level: intermediate
379973c9229bSMatthew Knepley 
3800a4e35b19SJacob Faibussowitsch   Notes:
3801a4e35b19SJacob Faibussowitsch   This inversion will be accurate inside the reference element, but may be inaccurate for
3802a4e35b19SJacob Faibussowitsch   mappings that do not extend uniquely outside the reference cell (e.g, most non-affine maps)
3803a4e35b19SJacob Faibussowitsch 
380420f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexReferenceToCoordinates()`
3805d6143a4eSToby Isaac @*/
3806d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexCoordinatesToReference(DM dm, PetscInt cell, PetscInt numPoints, const PetscReal realCoords[], PetscReal refCoords[])
3807d71ae5a4SJacob Faibussowitsch {
3808485ad865SMatthew G. Knepley   PetscInt dimC, dimR, depth, cStart, cEnd, i;
38099d150b73SToby Isaac   DM       coordDM = NULL;
38109d150b73SToby Isaac   Vec      coords;
38119d150b73SToby Isaac   PetscFE  fe = NULL;
38129d150b73SToby Isaac 
3813d6143a4eSToby Isaac   PetscFunctionBegin;
38149d150b73SToby Isaac   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
38159566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dimR));
38169566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &dimC));
38173ba16761SJacob Faibussowitsch   if (dimR <= 0 || dimC <= 0 || numPoints <= 0) PetscFunctionReturn(PETSC_SUCCESS);
38189566063dSJacob Faibussowitsch   PetscCall(DMPlexGetDepth(dm, &depth));
38199566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinatesLocal(dm, &coords));
38209566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDM(dm, &coordDM));
38219d150b73SToby Isaac   if (coordDM) {
38229d150b73SToby Isaac     PetscInt coordFields;
38239d150b73SToby Isaac 
38249566063dSJacob Faibussowitsch     PetscCall(DMGetNumFields(coordDM, &coordFields));
38259d150b73SToby Isaac     if (coordFields) {
38269d150b73SToby Isaac       PetscClassId id;
38279d150b73SToby Isaac       PetscObject  disc;
38289d150b73SToby Isaac 
38299566063dSJacob Faibussowitsch       PetscCall(DMGetField(coordDM, 0, NULL, &disc));
38309566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetClassId(disc, &id));
3831ad540459SPierre Jolivet       if (id == PETSCFE_CLASSID) fe = (PetscFE)disc;
38329d150b73SToby Isaac     }
38339d150b73SToby Isaac   }
38349566063dSJacob Faibussowitsch   PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
38351dca8a05SBarry Smith   PetscCheck(cell >= cStart && cell < cEnd, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "point %" PetscInt_FMT " not in cell range [%" PetscInt_FMT ",%" PetscInt_FMT ")", cell, cStart, cEnd);
38369d150b73SToby Isaac   if (!fe) { /* implicit discretization: affine or multilinear */
38379d150b73SToby Isaac     PetscInt  coneSize;
38389d150b73SToby Isaac     PetscBool isSimplex, isTensor;
38399d150b73SToby Isaac 
38409566063dSJacob Faibussowitsch     PetscCall(DMPlexGetConeSize(dm, cell, &coneSize));
38419d150b73SToby Isaac     isSimplex = (coneSize == (dimR + 1)) ? PETSC_TRUE : PETSC_FALSE;
38429d150b73SToby Isaac     isTensor  = (coneSize == ((depth == 1) ? (1 << dimR) : (2 * dimR))) ? PETSC_TRUE : PETSC_FALSE;
38439d150b73SToby Isaac     if (isSimplex) {
38449d150b73SToby Isaac       PetscReal detJ, *v0, *J, *invJ;
38459d150b73SToby Isaac 
38469566063dSJacob Faibussowitsch       PetscCall(DMGetWorkArray(dm, dimC + 2 * dimC * dimC, MPIU_REAL, &v0));
38479d150b73SToby Isaac       J    = &v0[dimC];
38489d150b73SToby Isaac       invJ = &J[dimC * dimC];
38499566063dSJacob Faibussowitsch       PetscCall(DMPlexComputeCellGeometryAffineFEM(dm, cell, v0, J, invJ, &detJ));
38509d150b73SToby Isaac       for (i = 0; i < numPoints; i++) { /* Apply the inverse affine transformation for each point */
3851c330f8ffSToby Isaac         const PetscReal x0[3] = {-1., -1., -1.};
3852c330f8ffSToby Isaac 
3853c330f8ffSToby Isaac         CoordinatesRealToRef(dimC, dimR, x0, v0, invJ, &realCoords[dimC * i], &refCoords[dimR * i]);
38549d150b73SToby Isaac       }
38559566063dSJacob Faibussowitsch       PetscCall(DMRestoreWorkArray(dm, dimC + 2 * dimC * dimC, MPIU_REAL, &v0));
38569d150b73SToby Isaac     } else if (isTensor) {
38579566063dSJacob Faibussowitsch       PetscCall(DMPlexCoordinatesToReference_Tensor(coordDM, cell, numPoints, realCoords, refCoords, coords, dimC, dimR));
385863a3b9bcSJacob Faibussowitsch     } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Unrecognized cone size %" PetscInt_FMT, coneSize);
38599d150b73SToby Isaac   } else {
3860dd301514SZach Atkins     PetscCall(DMPlexCoordinatesToReference_FE(coordDM, fe, cell, numPoints, realCoords, refCoords, coords, dimC, dimR, 7, NULL));
38619d150b73SToby Isaac   }
38623ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
38639d150b73SToby Isaac }
38649d150b73SToby Isaac 
38659d150b73SToby Isaac /*@
386615229ffcSPierre Jolivet   DMPlexReferenceToCoordinates - Map references coordinates to coordinates in the mesh for a single element map.
38679d150b73SToby Isaac 
386820f4b53cSBarry Smith   Not Collective
38699d150b73SToby Isaac 
38709d150b73SToby Isaac   Input Parameters:
38712fe279fdSBarry Smith + dm        - The mesh, with coordinate maps defined either by a PetscDS for the coordinate `DM` (see `DMGetCoordinateDM()`) or
38729d150b73SToby Isaac                implicitly by the coordinates of the corner vertices of the cell: as an affine map for simplicial elements, or
38739d150b73SToby Isaac                as a multilinear map for tensor-product elements
38749d150b73SToby Isaac . cell      - the cell whose map is used.
38759d150b73SToby Isaac . numPoints - the number of points to locate
38762fe279fdSBarry Smith - refCoords - (numPoints x dimension) array of reference coordinates (see `DMGetDimension()`)
38779d150b73SToby Isaac 
38782fe279fdSBarry Smith   Output Parameter:
38792fe279fdSBarry Smith . realCoords - (numPoints x coordinate dimension) array of coordinates (see `DMGetCoordinateDim()`)
38801b266c99SBarry Smith 
38811b266c99SBarry Smith   Level: intermediate
388273c9229bSMatthew Knepley 
38832fe279fdSBarry Smith .seealso: `DMPLEX`, `DMPlexCoordinatesToReference()`
38849d150b73SToby Isaac @*/
3885d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexReferenceToCoordinates(DM dm, PetscInt cell, PetscInt numPoints, const PetscReal refCoords[], PetscReal realCoords[])
3886d71ae5a4SJacob Faibussowitsch {
3887485ad865SMatthew G. Knepley   PetscInt dimC, dimR, depth, cStart, cEnd, i;
38889d150b73SToby Isaac   DM       coordDM = NULL;
38899d150b73SToby Isaac   Vec      coords;
38909d150b73SToby Isaac   PetscFE  fe = NULL;
38919d150b73SToby Isaac 
38929d150b73SToby Isaac   PetscFunctionBegin;
38939d150b73SToby Isaac   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
38949566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dimR));
38959566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &dimC));
38963ba16761SJacob Faibussowitsch   if (dimR <= 0 || dimC <= 0 || numPoints <= 0) PetscFunctionReturn(PETSC_SUCCESS);
38979566063dSJacob Faibussowitsch   PetscCall(DMPlexGetDepth(dm, &depth));
38989566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinatesLocal(dm, &coords));
38999566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDM(dm, &coordDM));
39009d150b73SToby Isaac   if (coordDM) {
39019d150b73SToby Isaac     PetscInt coordFields;
39029d150b73SToby Isaac 
39039566063dSJacob Faibussowitsch     PetscCall(DMGetNumFields(coordDM, &coordFields));
39049d150b73SToby Isaac     if (coordFields) {
39059d150b73SToby Isaac       PetscClassId id;
39069d150b73SToby Isaac       PetscObject  disc;
39079d150b73SToby Isaac 
39089566063dSJacob Faibussowitsch       PetscCall(DMGetField(coordDM, 0, NULL, &disc));
39099566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetClassId(disc, &id));
3910ad540459SPierre Jolivet       if (id == PETSCFE_CLASSID) fe = (PetscFE)disc;
39119d150b73SToby Isaac     }
39129d150b73SToby Isaac   }
39139566063dSJacob Faibussowitsch   PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
39141dca8a05SBarry Smith   PetscCheck(cell >= cStart && cell < cEnd, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "point %" PetscInt_FMT " not in cell range [%" PetscInt_FMT ",%" PetscInt_FMT ")", cell, cStart, cEnd);
39159d150b73SToby Isaac   if (!fe) { /* implicit discretization: affine or multilinear */
39169d150b73SToby Isaac     PetscInt  coneSize;
39179d150b73SToby Isaac     PetscBool isSimplex, isTensor;
39189d150b73SToby Isaac 
39199566063dSJacob Faibussowitsch     PetscCall(DMPlexGetConeSize(dm, cell, &coneSize));
39209d150b73SToby Isaac     isSimplex = (coneSize == (dimR + 1)) ? PETSC_TRUE : PETSC_FALSE;
39219d150b73SToby Isaac     isTensor  = (coneSize == ((depth == 1) ? (1 << dimR) : (2 * dimR))) ? PETSC_TRUE : PETSC_FALSE;
39229d150b73SToby Isaac     if (isSimplex) {
39239d150b73SToby Isaac       PetscReal detJ, *v0, *J;
39249d150b73SToby Isaac 
39259566063dSJacob Faibussowitsch       PetscCall(DMGetWorkArray(dm, dimC + 2 * dimC * dimC, MPIU_REAL, &v0));
39269d150b73SToby Isaac       J = &v0[dimC];
39279566063dSJacob Faibussowitsch       PetscCall(DMPlexComputeCellGeometryAffineFEM(dm, cell, v0, J, NULL, &detJ));
3928c330f8ffSToby Isaac       for (i = 0; i < numPoints; i++) { /* Apply the affine transformation for each point */
3929c330f8ffSToby Isaac         const PetscReal xi0[3] = {-1., -1., -1.};
3930c330f8ffSToby Isaac 
3931c330f8ffSToby Isaac         CoordinatesRefToReal(dimC, dimR, xi0, v0, J, &refCoords[dimR * i], &realCoords[dimC * i]);
39329d150b73SToby Isaac       }
39339566063dSJacob Faibussowitsch       PetscCall(DMRestoreWorkArray(dm, dimC + 2 * dimC * dimC, MPIU_REAL, &v0));
39349d150b73SToby Isaac     } else if (isTensor) {
39359566063dSJacob Faibussowitsch       PetscCall(DMPlexReferenceToCoordinates_Tensor(coordDM, cell, numPoints, refCoords, realCoords, coords, dimC, dimR));
393663a3b9bcSJacob Faibussowitsch     } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Unrecognized cone size %" PetscInt_FMT, coneSize);
39379d150b73SToby Isaac   } else {
39389566063dSJacob Faibussowitsch     PetscCall(DMPlexReferenceToCoordinates_FE(coordDM, fe, cell, numPoints, refCoords, realCoords, coords, dimC, dimR));
39399d150b73SToby Isaac   }
39403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3941d6143a4eSToby Isaac }
39420139fca9SMatthew G. Knepley 
3943be664eb1SMatthew G. Knepley void coordMap_identity(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[])
3944be664eb1SMatthew G. Knepley {
3945be664eb1SMatthew G. Knepley   const PetscInt Nc = uOff[1] - uOff[0];
3946be664eb1SMatthew G. Knepley   PetscInt       c;
3947be664eb1SMatthew G. Knepley 
3948be664eb1SMatthew G. Knepley   for (c = 0; c < Nc; ++c) f0[c] = u[c];
3949be664eb1SMatthew G. Knepley }
3950be664eb1SMatthew G. Knepley 
3951be664eb1SMatthew G. Knepley /* Shear applies the transformation, assuming we fix z,
3952be664eb1SMatthew G. Knepley   / 1  0  m_0 \
3953be664eb1SMatthew G. Knepley   | 0  1  m_1 |
3954be664eb1SMatthew G. Knepley   \ 0  0   1  /
3955be664eb1SMatthew G. Knepley */
3956be664eb1SMatthew G. Knepley void coordMap_shear(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 coords[])
3957be664eb1SMatthew G. Knepley {
3958be664eb1SMatthew G. Knepley   const PetscInt Nc = uOff[1] - uOff[0];
3959be664eb1SMatthew G. Knepley   const PetscInt ax = (PetscInt)PetscRealPart(constants[0]);
3960be664eb1SMatthew G. Knepley   PetscInt       c;
3961be664eb1SMatthew G. Knepley 
3962be664eb1SMatthew G. Knepley   for (c = 0; c < Nc; ++c) coords[c] = u[c] + constants[c + 1] * u[ax];
3963be664eb1SMatthew G. Knepley }
3964be664eb1SMatthew G. Knepley 
3965be664eb1SMatthew G. Knepley /* Flare applies the transformation, assuming we fix x_f,
3966be664eb1SMatthew G. Knepley 
3967be664eb1SMatthew G. Knepley    x_i = x_i * alpha_i x_f
3968be664eb1SMatthew G. Knepley */
3969be664eb1SMatthew G. Knepley void coordMap_flare(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 coords[])
3970be664eb1SMatthew G. Knepley {
3971be664eb1SMatthew G. Knepley   const PetscInt Nc = uOff[1] - uOff[0];
3972be664eb1SMatthew G. Knepley   const PetscInt cf = (PetscInt)PetscRealPart(constants[0]);
3973be664eb1SMatthew G. Knepley   PetscInt       c;
3974be664eb1SMatthew G. Knepley 
3975be664eb1SMatthew G. Knepley   for (c = 0; c < Nc; ++c) coords[c] = u[c] * (c == cf ? 1.0 : constants[c + 1] * u[cf]);
3976be664eb1SMatthew G. Knepley }
3977be664eb1SMatthew G. Knepley 
3978be664eb1SMatthew G. Knepley /*
3979be664eb1SMatthew G. Knepley   We would like to map the unit square to a quarter of the annulus between circles of radius 1 and 2. We start by mapping the straight sections, which
3980be664eb1SMatthew G. Knepley   will correspond to the top and bottom of our square. So
3981be664eb1SMatthew G. Knepley 
3982be664eb1SMatthew G. Knepley     (0,0)--(1,0)  ==>  (1,0)--(2,0)      Just a shift of (1,0)
3983be664eb1SMatthew G. Knepley     (0,1)--(1,1)  ==>  (0,1)--(0,2)      Switch x and y
3984be664eb1SMatthew G. Knepley 
3985be664eb1SMatthew G. Knepley   So it looks like we want to map each layer in y to a ray, so x is the radius and y is the angle:
3986be664eb1SMatthew G. Knepley 
3987be664eb1SMatthew G. Knepley     (x, y)  ==>  (x+1, \pi/2 y)                           in (r', \theta') space
3988be664eb1SMatthew G. Knepley             ==>  ((x+1) cos(\pi/2 y), (x+1) sin(\pi/2 y)) in (x', y') space
3989be664eb1SMatthew G. Knepley */
3990be664eb1SMatthew G. Knepley void coordMap_annulus(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 xp[])
3991be664eb1SMatthew G. Knepley {
3992be664eb1SMatthew G. Knepley   const PetscReal ri = PetscRealPart(constants[0]);
3993be664eb1SMatthew G. Knepley   const PetscReal ro = PetscRealPart(constants[1]);
3994be664eb1SMatthew G. Knepley 
3995be664eb1SMatthew G. Knepley   xp[0] = (x[0] * (ro - ri) + ri) * PetscCosReal(0.5 * PETSC_PI * x[1]);
3996be664eb1SMatthew G. Knepley   xp[1] = (x[0] * (ro - ri) + ri) * PetscSinReal(0.5 * PETSC_PI * x[1]);
3997be664eb1SMatthew G. Knepley }
3998be664eb1SMatthew G. Knepley 
3999be664eb1SMatthew G. Knepley /*
4000be664eb1SMatthew G. Knepley   We would like to map the unit cube to a hemisphere of the spherical shell between balls of radius 1 and 2. We want to map the bottom surface onto the
4001be664eb1SMatthew G. Knepley   lower hemisphere and the upper surface onto the top, letting z be the radius.
4002be664eb1SMatthew G. Knepley 
4003be664eb1SMatthew G. Knepley     (x, y)  ==>  ((z+3)/2, \pi/2 (|x| or |y|), arctan y/x)                                                  in (r', \theta', \phi') space
4004be664eb1SMatthew G. Knepley             ==>  ((z+3)/2 \cos(\theta') cos(\phi'), (z+3)/2 \cos(\theta') sin(\phi'), (z+3)/2 sin(\theta')) in (x', y', z') space
4005be664eb1SMatthew G. Knepley */
4006be664eb1SMatthew G. Knepley void coordMap_shell(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 xp[])
4007be664eb1SMatthew G. Knepley {
4008be664eb1SMatthew G. Knepley   const PetscReal pi4    = PETSC_PI / 4.0;
4009be664eb1SMatthew G. Knepley   const PetscReal ri     = PetscRealPart(constants[0]);
4010be664eb1SMatthew G. Knepley   const PetscReal ro     = PetscRealPart(constants[1]);
4011be664eb1SMatthew G. Knepley   const PetscReal rp     = (x[2] + 1) * 0.5 * (ro - ri) + ri;
4012be664eb1SMatthew G. Knepley   const PetscReal phip   = PetscAtan2Real(x[1], x[0]);
4013be664eb1SMatthew G. Knepley   const PetscReal thetap = 0.5 * PETSC_PI * (1.0 - ((((phip <= pi4) && (phip >= -pi4)) || ((phip >= 3.0 * pi4) || (phip <= -3.0 * pi4))) ? PetscAbsReal(x[0]) : PetscAbsReal(x[1])));
4014be664eb1SMatthew G. Knepley 
4015be664eb1SMatthew G. Knepley   xp[0] = rp * PetscCosReal(thetap) * PetscCosReal(phip);
4016be664eb1SMatthew G. Knepley   xp[1] = rp * PetscCosReal(thetap) * PetscSinReal(phip);
4017be664eb1SMatthew G. Knepley   xp[2] = rp * PetscSinReal(thetap);
4018be664eb1SMatthew G. Knepley }
4019be664eb1SMatthew G. Knepley 
4020530e699aSMatthew G. Knepley void coordMap_sinusoid(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 xp[])
4021530e699aSMatthew G. Knepley {
4022530e699aSMatthew G. Knepley   const PetscReal c = PetscRealPart(constants[0]);
4023530e699aSMatthew G. Knepley   const PetscReal m = PetscRealPart(constants[1]);
4024530e699aSMatthew G. Knepley   const PetscReal n = PetscRealPart(constants[2]);
4025530e699aSMatthew G. Knepley 
4026530e699aSMatthew G. Knepley   xp[0] = x[0];
4027530e699aSMatthew G. Knepley   xp[1] = x[1];
4028530e699aSMatthew G. Knepley   if (dim > 2) xp[2] = c * PetscCosReal(2. * m * PETSC_PI * x[0]) * PetscCosReal(2. * n * PETSC_PI * x[1]);
4029530e699aSMatthew G. Knepley }
4030530e699aSMatthew G. Knepley 
40310139fca9SMatthew G. Knepley /*@C
40322fe279fdSBarry Smith   DMPlexRemapGeometry - This function maps the original `DM` coordinates to new coordinates.
40330139fca9SMatthew G. Knepley 
403420f4b53cSBarry Smith   Not Collective
40350139fca9SMatthew G. Knepley 
40360139fca9SMatthew G. Knepley   Input Parameters:
40372fe279fdSBarry Smith + dm   - The `DM`
40380139fca9SMatthew G. Knepley . time - The time
4039a4e35b19SJacob Faibussowitsch - func - The function transforming current coordinates to new coordinates
40400139fca9SMatthew G. Knepley 
404120f4b53cSBarry Smith   Calling sequence of `func`:
40420139fca9SMatthew G. Knepley + dim          - The spatial dimension
40430139fca9SMatthew G. Knepley . Nf           - The number of input fields (here 1)
40440139fca9SMatthew G. Knepley . NfAux        - The number of input auxiliary fields
40450139fca9SMatthew G. Knepley . uOff         - The offset of the coordinates in u[] (here 0)
40460139fca9SMatthew G. Knepley . uOff_x       - The offset of the coordinates in u_x[] (here 0)
40470139fca9SMatthew G. Knepley . u            - The coordinate values at this point in space
404820f4b53cSBarry Smith . u_t          - The coordinate time derivative at this point in space (here `NULL`)
40490139fca9SMatthew G. Knepley . u_x          - The coordinate derivatives at this point in space
40500139fca9SMatthew G. Knepley . aOff         - The offset of each auxiliary field in u[]
40510139fca9SMatthew G. Knepley . aOff_x       - The offset of each auxiliary field in u_x[]
40520139fca9SMatthew G. Knepley . a            - The auxiliary field values at this point in space
405320f4b53cSBarry Smith . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
40540139fca9SMatthew G. Knepley . a_x          - The auxiliary field derivatives at this point in space
40550139fca9SMatthew G. Knepley . t            - The current time
40560139fca9SMatthew G. Knepley . x            - The coordinates of this point (here not used)
40570139fca9SMatthew G. Knepley . numConstants - The number of constants
40580139fca9SMatthew G. Knepley . constants    - The value of each constant
40590139fca9SMatthew G. Knepley - f            - The new coordinates at this point in space
40600139fca9SMatthew G. Knepley 
40610139fca9SMatthew G. Knepley   Level: intermediate
40620139fca9SMatthew G. Knepley 
40632fe279fdSBarry Smith .seealso: `DMPLEX`, `DMGetCoordinates()`, `DMGetCoordinatesLocal()`, `DMGetCoordinateDM()`, `DMProjectFieldLocal()`, `DMProjectFieldLabelLocal()`
40640139fca9SMatthew G. Knepley @*/
4065a4e35b19SJacob Faibussowitsch PetscErrorCode DMPlexRemapGeometry(DM dm, PetscReal time, void (*func)(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f[]))
4066d71ae5a4SJacob Faibussowitsch {
40670139fca9SMatthew G. Knepley   DM           cdm;
4068be664eb1SMatthew G. Knepley   PetscDS      cds;
40698bf1a49fSMatthew G. Knepley   DMField      cf;
4070be664eb1SMatthew G. Knepley   PetscObject  obj;
4071be664eb1SMatthew G. Knepley   PetscClassId id;
40720139fca9SMatthew G. Knepley   Vec          lCoords, tmpCoords;
40730139fca9SMatthew G. Knepley 
40740139fca9SMatthew G. Knepley   PetscFunctionBegin;
40759566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDM(dm, &cdm));
40769566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinatesLocal(dm, &lCoords));
4077be664eb1SMatthew G. Knepley   PetscCall(DMGetDS(cdm, &cds));
4078be664eb1SMatthew G. Knepley   PetscCall(PetscDSGetDiscretization(cds, 0, &obj));
4079be664eb1SMatthew G. Knepley   PetscCall(PetscObjectGetClassId(obj, &id));
4080be664eb1SMatthew G. Knepley   if (id != PETSCFE_CLASSID) {
4081be664eb1SMatthew G. Knepley     PetscSection       cSection;
4082be664eb1SMatthew G. Knepley     const PetscScalar *constants;
4083be664eb1SMatthew G. Knepley     PetscScalar       *coords, f[16];
4084be664eb1SMatthew G. Knepley     PetscInt           dim, cdim, Nc, vStart, vEnd;
4085be664eb1SMatthew G. Knepley 
4086be664eb1SMatthew G. Knepley     PetscCall(DMGetDimension(dm, &dim));
4087be664eb1SMatthew G. Knepley     PetscCall(DMGetCoordinateDim(dm, &cdim));
4088be664eb1SMatthew G. Knepley     PetscCheck(cdim <= 16, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Affine version of DMPlexRemapGeometry is currently limited to dimensions <= 16, not %" PetscInt_FMT, cdim);
4089be664eb1SMatthew G. Knepley     PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
4090be664eb1SMatthew G. Knepley     PetscCall(DMGetCoordinateSection(dm, &cSection));
4091be664eb1SMatthew G. Knepley     PetscCall(PetscDSGetConstants(cds, &Nc, &constants));
4092be664eb1SMatthew G. Knepley     PetscCall(VecGetArrayWrite(lCoords, &coords));
4093be664eb1SMatthew G. Knepley     for (PetscInt v = vStart; v < vEnd; ++v) {
4094be664eb1SMatthew G. Knepley       PetscInt uOff[2] = {0, cdim};
4095be664eb1SMatthew G. Knepley       PetscInt off, c;
4096be664eb1SMatthew G. Knepley 
4097be664eb1SMatthew G. Knepley       PetscCall(PetscSectionGetOffset(cSection, v, &off));
4098be664eb1SMatthew G. Knepley       (*func)(dim, 1, 0, uOff, NULL, &coords[off], NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0.0, NULL, Nc, constants, f);
4099be664eb1SMatthew G. Knepley       for (c = 0; c < cdim; ++c) coords[off + c] = f[c];
4100be664eb1SMatthew G. Knepley     }
4101be664eb1SMatthew G. Knepley     PetscCall(VecRestoreArrayWrite(lCoords, &coords));
4102be664eb1SMatthew G. Knepley   } else {
41039566063dSJacob Faibussowitsch     PetscCall(DMGetLocalVector(cdm, &tmpCoords));
41049566063dSJacob Faibussowitsch     PetscCall(VecCopy(lCoords, tmpCoords));
41058bf1a49fSMatthew G. Knepley     /* We have to do the coordinate field manually right now since the coordinate DM will not have its own */
41069566063dSJacob Faibussowitsch     PetscCall(DMGetCoordinateField(dm, &cf));
41076858538eSMatthew G. Knepley     cdm->coordinates[0].field = cf;
41089566063dSJacob Faibussowitsch     PetscCall(DMProjectFieldLocal(cdm, time, tmpCoords, &func, INSERT_VALUES, lCoords));
41096858538eSMatthew G. Knepley     cdm->coordinates[0].field = NULL;
41109566063dSJacob Faibussowitsch     PetscCall(DMRestoreLocalVector(cdm, &tmpCoords));
41119566063dSJacob Faibussowitsch     PetscCall(DMSetCoordinatesLocal(dm, lCoords));
41120139fca9SMatthew G. Knepley   }
4113be664eb1SMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
41140139fca9SMatthew G. Knepley }
41150139fca9SMatthew G. Knepley 
4116cc4c1da9SBarry Smith /*@
41170139fca9SMatthew G. Knepley   DMPlexShearGeometry - This shears the domain, meaning adds a multiple of the shear coordinate to all other coordinates.
41180139fca9SMatthew G. Knepley 
411920f4b53cSBarry Smith   Not Collective
41200139fca9SMatthew G. Knepley 
41210139fca9SMatthew G. Knepley   Input Parameters:
412220f4b53cSBarry Smith + dm          - The `DMPLEX`
4123a3b724e8SBarry Smith . direction   - The shear coordinate direction, e.g. `DM_X` is the x-axis
41240139fca9SMatthew G. Knepley - multipliers - The multiplier m for each direction which is not the shear direction
41250139fca9SMatthew G. Knepley 
41260139fca9SMatthew G. Knepley   Level: intermediate
41270139fca9SMatthew G. Knepley 
4128a3b724e8SBarry Smith .seealso: `DMPLEX`, `DMPlexRemapGeometry()`, `DMDirection`, `DM_X`, `DM_Y`, `DM_Z`
41290139fca9SMatthew G. Knepley @*/
4130d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexShearGeometry(DM dm, DMDirection direction, PetscReal multipliers[])
4131d71ae5a4SJacob Faibussowitsch {
41320139fca9SMatthew G. Knepley   DM             cdm;
41330139fca9SMatthew G. Knepley   PetscDS        cds;
41340139fca9SMatthew G. Knepley   PetscScalar   *moduli;
41353ee9839eSMatthew G. Knepley   const PetscInt dir = (PetscInt)direction;
41360139fca9SMatthew G. Knepley   PetscInt       dE, d, e;
41370139fca9SMatthew G. Knepley 
41380139fca9SMatthew G. Knepley   PetscFunctionBegin;
41399566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDM(dm, &cdm));
41409566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &dE));
41419566063dSJacob Faibussowitsch   PetscCall(PetscMalloc1(dE + 1, &moduli));
41420139fca9SMatthew G. Knepley   moduli[0] = dir;
4143cdaaecf7SMatthew G. Knepley   for (d = 0, e = 0; d < dE; ++d) moduli[d + 1] = d == dir ? 0.0 : (multipliers ? multipliers[e++] : 1.0);
41449566063dSJacob Faibussowitsch   PetscCall(DMGetDS(cdm, &cds));
41459566063dSJacob Faibussowitsch   PetscCall(PetscDSSetConstants(cds, dE + 1, moduli));
4146be664eb1SMatthew G. Knepley   PetscCall(DMPlexRemapGeometry(dm, 0.0, coordMap_shear));
41479566063dSJacob Faibussowitsch   PetscCall(PetscFree(moduli));
41483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
41490139fca9SMatthew G. Knepley }
4150