xref: /petsc/src/dm/impls/plex/plexgeometry.c (revision 1d27aa22b2f6148b2c4e3f06a75e0638d6493e09)
1af0996ceSBarry Smith #include <petsc/private/dmpleximpl.h>  /*I      "petscdmplex.h"   I*/
29d150b73SToby Isaac #include <petsc/private/petscfeimpl.h> /*I      "petscfe.h"       I*/
39d150b73SToby Isaac #include <petscblaslapack.h>
4af74b616SDave May #include <petsctime.h>
5ccd2543fSMatthew G Knepley 
63985bb02SVaclav Hapla /*@
73985bb02SVaclav Hapla   DMPlexFindVertices - Try to find DAG points based on their coordinates.
83985bb02SVaclav Hapla 
920f4b53cSBarry Smith   Not Collective (provided `DMGetCoordinatesLocalSetUp()` has been already called)
103985bb02SVaclav Hapla 
113985bb02SVaclav Hapla   Input Parameters:
1220f4b53cSBarry Smith + dm          - The `DMPLEX` object
1320f4b53cSBarry Smith . coordinates - The `Vec` of coordinates of the sought points
1420f4b53cSBarry Smith - eps         - The tolerance or `PETSC_DEFAULT`
153985bb02SVaclav Hapla 
162fe279fdSBarry Smith   Output Parameter:
1720f4b53cSBarry Smith . points - The `IS` of found DAG points or -1
183985bb02SVaclav Hapla 
193985bb02SVaclav Hapla   Level: intermediate
203985bb02SVaclav Hapla 
213985bb02SVaclav Hapla   Notes:
2220f4b53cSBarry 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.
233985bb02SVaclav Hapla 
2420f4b53cSBarry Smith   The output `IS` is living on `PETSC_COMM_SELF` and its length is npoints.
25d3e1f4ccSVaclav Hapla   Each rank does the search independently.
2620f4b53cSBarry 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.
273985bb02SVaclav Hapla 
2820f4b53cSBarry Smith   The output `IS` must be destroyed by user.
293985bb02SVaclav Hapla 
303985bb02SVaclav Hapla   The tolerance is interpreted as the maximum Euclidean (L2) distance of the sought point from the specified coordinates.
313985bb02SVaclav Hapla 
32d3e1f4ccSVaclav 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.
33335ef845SVaclav Hapla 
3420f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexCreate()`, `DMGetCoordinatesLocal()`
353985bb02SVaclav Hapla @*/
36d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexFindVertices(DM dm, Vec coordinates, PetscReal eps, IS *points)
37d71ae5a4SJacob Faibussowitsch {
3837900f7dSMatthew G. Knepley   PetscInt           c, cdim, i, j, o, p, vStart, vEnd;
39d3e1f4ccSVaclav Hapla   PetscInt           npoints;
40d3e1f4ccSVaclav Hapla   const PetscScalar *coord;
413985bb02SVaclav Hapla   Vec                allCoordsVec;
423985bb02SVaclav Hapla   const PetscScalar *allCoords;
43d3e1f4ccSVaclav Hapla   PetscInt          *dagPoints;
443985bb02SVaclav Hapla 
453985bb02SVaclav Hapla   PetscFunctionBegin;
463985bb02SVaclav Hapla   if (eps < 0) eps = PETSC_SQRT_MACHINE_EPSILON;
479566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &cdim));
48d3e1f4ccSVaclav Hapla   {
49d3e1f4ccSVaclav Hapla     PetscInt n;
50d3e1f4ccSVaclav Hapla 
519566063dSJacob Faibussowitsch     PetscCall(VecGetLocalSize(coordinates, &n));
5263a3b9bcSJacob 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);
53d3e1f4ccSVaclav Hapla     npoints = n / cdim;
54d3e1f4ccSVaclav Hapla   }
559566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinatesLocal(dm, &allCoordsVec));
569566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(allCoordsVec, &allCoords));
579566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(coordinates, &coord));
589566063dSJacob Faibussowitsch   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
5976bd3646SJed Brown   if (PetscDefined(USE_DEBUG)) {
60335ef845SVaclav Hapla     /* check coordinate section is consistent with DM dimension */
61335ef845SVaclav Hapla     PetscSection cs;
62335ef845SVaclav Hapla     PetscInt     ndof;
63335ef845SVaclav Hapla 
649566063dSJacob Faibussowitsch     PetscCall(DMGetCoordinateSection(dm, &cs));
653985bb02SVaclav Hapla     for (p = vStart; p < vEnd; p++) {
669566063dSJacob Faibussowitsch       PetscCall(PetscSectionGetDof(cs, p, &ndof));
6763a3b9bcSJacob Faibussowitsch       PetscCheck(ndof == cdim, PETSC_COMM_SELF, PETSC_ERR_PLIB, "point %" PetscInt_FMT ": ndof = %" PetscInt_FMT " != %" PetscInt_FMT " = cdim", p, ndof, cdim);
68335ef845SVaclav Hapla     }
69335ef845SVaclav Hapla   }
709566063dSJacob Faibussowitsch   PetscCall(PetscMalloc1(npoints, &dagPoints));
71eca9f518SVaclav Hapla   if (eps == 0.0) {
7237900f7dSMatthew G. Knepley     for (i = 0, j = 0; i < npoints; i++, j += cdim) {
73eca9f518SVaclav Hapla       dagPoints[i] = -1;
7437900f7dSMatthew G. Knepley       for (p = vStart, o = 0; p < vEnd; p++, o += cdim) {
7537900f7dSMatthew G. Knepley         for (c = 0; c < cdim; c++) {
76d3e1f4ccSVaclav Hapla           if (coord[j + c] != allCoords[o + c]) break;
77eca9f518SVaclav Hapla         }
7837900f7dSMatthew G. Knepley         if (c == cdim) {
79eca9f518SVaclav Hapla           dagPoints[i] = p;
80eca9f518SVaclav Hapla           break;
81eca9f518SVaclav Hapla         }
82eca9f518SVaclav Hapla       }
83eca9f518SVaclav Hapla     }
84d3e1f4ccSVaclav Hapla   } else {
8537900f7dSMatthew G. Knepley     for (i = 0, j = 0; i < npoints; i++, j += cdim) {
86d3e1f4ccSVaclav Hapla       PetscReal norm;
87d3e1f4ccSVaclav Hapla 
88335ef845SVaclav Hapla       dagPoints[i] = -1;
8937900f7dSMatthew G. Knepley       for (p = vStart, o = 0; p < vEnd; p++, o += cdim) {
903985bb02SVaclav Hapla         norm = 0.0;
91ad540459SPierre Jolivet         for (c = 0; c < cdim; c++) norm += PetscRealPart(PetscSqr(coord[j + c] - allCoords[o + c]));
923985bb02SVaclav Hapla         norm = PetscSqrtReal(norm);
933985bb02SVaclav Hapla         if (norm <= eps) {
943985bb02SVaclav Hapla           dagPoints[i] = p;
953985bb02SVaclav Hapla           break;
963985bb02SVaclav Hapla         }
973985bb02SVaclav Hapla       }
983985bb02SVaclav Hapla     }
99d3e1f4ccSVaclav Hapla   }
1009566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(allCoordsVec, &allCoords));
1019566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(coordinates, &coord));
1029566063dSJacob Faibussowitsch   PetscCall(ISCreateGeneral(PETSC_COMM_SELF, npoints, dagPoints, PETSC_OWN_POINTER, points));
1033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1043985bb02SVaclav Hapla }
1053985bb02SVaclav Hapla 
1066363a54bSMatthew G. Knepley #if 0
107d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexGetLineIntersection_2D_Internal(const PetscReal segmentA[], const PetscReal segmentB[], PetscReal intersection[], PetscBool *hasIntersection)
108d71ae5a4SJacob Faibussowitsch {
109fea14342SMatthew G. Knepley   const PetscReal p0_x  = segmentA[0 * 2 + 0];
110fea14342SMatthew G. Knepley   const PetscReal p0_y  = segmentA[0 * 2 + 1];
111fea14342SMatthew G. Knepley   const PetscReal p1_x  = segmentA[1 * 2 + 0];
112fea14342SMatthew G. Knepley   const PetscReal p1_y  = segmentA[1 * 2 + 1];
113fea14342SMatthew G. Knepley   const PetscReal p2_x  = segmentB[0 * 2 + 0];
114fea14342SMatthew G. Knepley   const PetscReal p2_y  = segmentB[0 * 2 + 1];
115fea14342SMatthew G. Knepley   const PetscReal p3_x  = segmentB[1 * 2 + 0];
116fea14342SMatthew G. Knepley   const PetscReal p3_y  = segmentB[1 * 2 + 1];
117fea14342SMatthew G. Knepley   const PetscReal s1_x  = p1_x - p0_x;
118fea14342SMatthew G. Knepley   const PetscReal s1_y  = p1_y - p0_y;
119fea14342SMatthew G. Knepley   const PetscReal s2_x  = p3_x - p2_x;
120fea14342SMatthew G. Knepley   const PetscReal s2_y  = p3_y - p2_y;
121fea14342SMatthew G. Knepley   const PetscReal denom = (-s2_x * s1_y + s1_x * s2_y);
122fea14342SMatthew G. Knepley 
123fea14342SMatthew G. Knepley   PetscFunctionBegin;
124fea14342SMatthew G. Knepley   *hasIntersection = PETSC_FALSE;
125fea14342SMatthew G. Knepley   /* Non-parallel lines */
126fea14342SMatthew G. Knepley   if (denom != 0.0) {
127fea14342SMatthew G. Knepley     const PetscReal s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / denom;
128fea14342SMatthew G. Knepley     const PetscReal t = (s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / denom;
129fea14342SMatthew G. Knepley 
130fea14342SMatthew G. Knepley     if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
131fea14342SMatthew G. Knepley       *hasIntersection = PETSC_TRUE;
132fea14342SMatthew G. Knepley       if (intersection) {
133fea14342SMatthew G. Knepley         intersection[0] = p0_x + (t * s1_x);
134fea14342SMatthew G. Knepley         intersection[1] = p0_y + (t * s1_y);
135fea14342SMatthew G. Knepley       }
136fea14342SMatthew G. Knepley     }
137fea14342SMatthew G. Knepley   }
1383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
139fea14342SMatthew G. Knepley }
140fea14342SMatthew G. Knepley 
141ddce0771SMatthew G. Knepley /* The plane is segmentB x segmentC: https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection */
142d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexGetLinePlaneIntersection_3D_Internal(const PetscReal segmentA[], const PetscReal segmentB[], const PetscReal segmentC[], PetscReal intersection[], PetscBool *hasIntersection)
143d71ae5a4SJacob Faibussowitsch {
144ddce0771SMatthew G. Knepley   const PetscReal p0_x  = segmentA[0 * 3 + 0];
145ddce0771SMatthew G. Knepley   const PetscReal p0_y  = segmentA[0 * 3 + 1];
146ddce0771SMatthew G. Knepley   const PetscReal p0_z  = segmentA[0 * 3 + 2];
147ddce0771SMatthew G. Knepley   const PetscReal p1_x  = segmentA[1 * 3 + 0];
148ddce0771SMatthew G. Knepley   const PetscReal p1_y  = segmentA[1 * 3 + 1];
149ddce0771SMatthew G. Knepley   const PetscReal p1_z  = segmentA[1 * 3 + 2];
150ddce0771SMatthew G. Knepley   const PetscReal q0_x  = segmentB[0 * 3 + 0];
151ddce0771SMatthew G. Knepley   const PetscReal q0_y  = segmentB[0 * 3 + 1];
152ddce0771SMatthew G. Knepley   const PetscReal q0_z  = segmentB[0 * 3 + 2];
153ddce0771SMatthew G. Knepley   const PetscReal q1_x  = segmentB[1 * 3 + 0];
154ddce0771SMatthew G. Knepley   const PetscReal q1_y  = segmentB[1 * 3 + 1];
155ddce0771SMatthew G. Knepley   const PetscReal q1_z  = segmentB[1 * 3 + 2];
156ddce0771SMatthew G. Knepley   const PetscReal r0_x  = segmentC[0 * 3 + 0];
157ddce0771SMatthew G. Knepley   const PetscReal r0_y  = segmentC[0 * 3 + 1];
158ddce0771SMatthew G. Knepley   const PetscReal r0_z  = segmentC[0 * 3 + 2];
159ddce0771SMatthew G. Knepley   const PetscReal r1_x  = segmentC[1 * 3 + 0];
160ddce0771SMatthew G. Knepley   const PetscReal r1_y  = segmentC[1 * 3 + 1];
161ddce0771SMatthew G. Knepley   const PetscReal r1_z  = segmentC[1 * 3 + 2];
162ddce0771SMatthew G. Knepley   const PetscReal s0_x  = p1_x - p0_x;
163ddce0771SMatthew G. Knepley   const PetscReal s0_y  = p1_y - p0_y;
164ddce0771SMatthew G. Knepley   const PetscReal s0_z  = p1_z - p0_z;
165ddce0771SMatthew G. Knepley   const PetscReal s1_x  = q1_x - q0_x;
166ddce0771SMatthew G. Knepley   const PetscReal s1_y  = q1_y - q0_y;
167ddce0771SMatthew G. Knepley   const PetscReal s1_z  = q1_z - q0_z;
168ddce0771SMatthew G. Knepley   const PetscReal s2_x  = r1_x - r0_x;
169ddce0771SMatthew G. Knepley   const PetscReal s2_y  = r1_y - r0_y;
170ddce0771SMatthew G. Knepley   const PetscReal s2_z  = r1_z - r0_z;
171ddce0771SMatthew G. Knepley   const PetscReal s3_x  = s1_y * s2_z - s1_z * s2_y; /* s1 x s2 */
172ddce0771SMatthew G. Knepley   const PetscReal s3_y  = s1_z * s2_x - s1_x * s2_z;
173ddce0771SMatthew G. Knepley   const PetscReal s3_z  = s1_x * s2_y - s1_y * s2_x;
174ddce0771SMatthew G. Knepley   const PetscReal s4_x  = s0_y * s2_z - s0_z * s2_y; /* s0 x s2 */
175ddce0771SMatthew G. Knepley   const PetscReal s4_y  = s0_z * s2_x - s0_x * s2_z;
176ddce0771SMatthew G. Knepley   const PetscReal s4_z  = s0_x * s2_y - s0_y * s2_x;
177ddce0771SMatthew G. Knepley   const PetscReal s5_x  = s1_y * s0_z - s1_z * s0_y; /* s1 x s0 */
178ddce0771SMatthew G. Knepley   const PetscReal s5_y  = s1_z * s0_x - s1_x * s0_z;
179ddce0771SMatthew G. Knepley   const PetscReal s5_z  = s1_x * s0_y - s1_y * s0_x;
180ddce0771SMatthew G. Knepley   const PetscReal denom = -(s0_x * s3_x + s0_y * s3_y + s0_z * s3_z); /* -s0 . (s1 x s2) */
181ddce0771SMatthew G. Knepley 
182ddce0771SMatthew G. Knepley   PetscFunctionBegin;
183ddce0771SMatthew G. Knepley   *hasIntersection = PETSC_FALSE;
184ddce0771SMatthew G. Knepley   /* Line not parallel to plane */
185ddce0771SMatthew G. Knepley   if (denom != 0.0) {
186ddce0771SMatthew G. Knepley     const PetscReal t = (s3_x * (p0_x - q0_x) + s3_y * (p0_y - q0_y) + s3_z * (p0_z - q0_z)) / denom;
187ddce0771SMatthew G. Knepley     const PetscReal u = (s4_x * (p0_x - q0_x) + s4_y * (p0_y - q0_y) + s4_z * (p0_z - q0_z)) / denom;
188ddce0771SMatthew G. Knepley     const PetscReal v = (s5_x * (p0_x - q0_x) + s5_y * (p0_y - q0_y) + s5_z * (p0_z - q0_z)) / denom;
189ddce0771SMatthew G. Knepley 
190ddce0771SMatthew G. Knepley     if (t >= 0 && t <= 1 && u >= 0 && u <= 1 && v >= 0 && v <= 1) {
191ddce0771SMatthew G. Knepley       *hasIntersection = PETSC_TRUE;
192ddce0771SMatthew G. Knepley       if (intersection) {
193ddce0771SMatthew G. Knepley         intersection[0] = p0_x + (t * s0_x);
194ddce0771SMatthew G. Knepley         intersection[1] = p0_y + (t * s0_y);
195ddce0771SMatthew G. Knepley         intersection[2] = p0_z + (t * s0_z);
196ddce0771SMatthew G. Knepley       }
197ddce0771SMatthew G. Knepley     }
198ddce0771SMatthew G. Knepley   }
1993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
200ddce0771SMatthew G. Knepley }
2016363a54bSMatthew G. Knepley #endif
2026363a54bSMatthew G. Knepley 
2036363a54bSMatthew 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[])
2046363a54bSMatthew G. Knepley {
2056363a54bSMatthew G. Knepley   PetscReal d[4]; // distance of vertices to the plane
2066363a54bSMatthew G. Knepley   PetscReal dp;   // distance from origin to the plane
2076363a54bSMatthew G. Knepley   PetscInt  n = 0;
2086363a54bSMatthew G. Knepley 
2096363a54bSMatthew G. Knepley   PetscFunctionBegin;
2106363a54bSMatthew G. Knepley   if (pos) *pos = PETSC_FALSE;
2116363a54bSMatthew G. Knepley   if (Nint) *Nint = 0;
2126363a54bSMatthew G. Knepley   if (PetscDefined(USE_DEBUG)) {
2136363a54bSMatthew G. Knepley     PetscReal mag = DMPlex_NormD_Internal(cdim, normal);
214b58dcb05SPierre Jolivet     PetscCheck(PetscAbsReal(mag - (PetscReal)1.0) < PETSC_SMALL, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Normal vector is not normalized: %g", (double)mag);
2156363a54bSMatthew G. Knepley   }
2166363a54bSMatthew G. Knepley 
2176363a54bSMatthew G. Knepley   dp = DMPlex_DotRealD_Internal(cdim, normal, p);
2186363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < dim + 1; ++v) {
2196363a54bSMatthew G. Knepley     // d[v] is positive, zero, or negative if vertex i is above, on, or below the plane
2206363a54bSMatthew G. Knepley #if defined(PETSC_USE_COMPLEX)
2216363a54bSMatthew G. Knepley     PetscReal c[4];
2226363a54bSMatthew G. Knepley     for (PetscInt i = 0; i < cdim; ++i) c[i] = PetscRealPart(coords[v * cdim + i]);
2236363a54bSMatthew G. Knepley     d[v] = DMPlex_DotRealD_Internal(cdim, normal, c);
2246363a54bSMatthew G. Knepley #else
2256363a54bSMatthew G. Knepley     d[v]           = DMPlex_DotRealD_Internal(cdim, normal, &coords[v * cdim]);
2266363a54bSMatthew G. Knepley #endif
2276363a54bSMatthew G. Knepley     d[v] -= dp;
2286363a54bSMatthew G. Knepley   }
2296363a54bSMatthew G. Knepley 
2306363a54bSMatthew G. Knepley   // If all d are positive or negative, no intersection
2316363a54bSMatthew G. Knepley   {
2326363a54bSMatthew G. Knepley     PetscInt v;
2336363a54bSMatthew G. Knepley     for (v = 0; v < dim + 1; ++v)
2346363a54bSMatthew G. Knepley       if (d[v] >= 0.) break;
2356363a54bSMatthew G. Knepley     if (v == dim + 1) PetscFunctionReturn(PETSC_SUCCESS);
2366363a54bSMatthew G. Knepley     for (v = 0; v < dim + 1; ++v)
2376363a54bSMatthew G. Knepley       if (d[v] <= 0.) break;
2386363a54bSMatthew G. Knepley     if (v == dim + 1) {
2396363a54bSMatthew G. Knepley       if (pos) *pos = PETSC_TRUE;
2406363a54bSMatthew G. Knepley       PetscFunctionReturn(PETSC_SUCCESS);
2416363a54bSMatthew G. Knepley     }
2426363a54bSMatthew G. Knepley   }
2436363a54bSMatthew G. Knepley 
2446363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < dim + 1; ++v) {
2456363a54bSMatthew G. Knepley     // Points with zero distance are automatically added to the list.
2466363a54bSMatthew G. Knepley     if (PetscAbsReal(d[v]) < PETSC_MACHINE_EPSILON) {
2476363a54bSMatthew G. Knepley       for (PetscInt i = 0; i < cdim; ++i) intPoints[n * cdim + i] = PetscRealPart(coords[v * cdim + i]);
2486363a54bSMatthew G. Knepley       ++n;
2496363a54bSMatthew G. Knepley     } else {
2506363a54bSMatthew G. Knepley       // For each point with nonzero distance, seek another point with opposite sign
2516363a54bSMatthew G. Knepley       // and higher index, and compute the intersection of the line between those
2526363a54bSMatthew G. Knepley       // points and the plane.
2536363a54bSMatthew G. Knepley       for (PetscInt w = v + 1; w < dim + 1; ++w) {
2546363a54bSMatthew G. Knepley         if (d[v] * d[w] < 0.) {
2556363a54bSMatthew G. Knepley           PetscReal inv_dist = 1. / (d[v] - d[w]);
2566363a54bSMatthew 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;
2576363a54bSMatthew G. Knepley           ++n;
2586363a54bSMatthew G. Knepley         }
2596363a54bSMatthew G. Knepley       }
2606363a54bSMatthew G. Knepley     }
2616363a54bSMatthew G. Knepley   }
2626363a54bSMatthew G. Knepley   // TODO order output points if there are 4
2636363a54bSMatthew G. Knepley   *Nint = n;
2646363a54bSMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
2656363a54bSMatthew G. Knepley }
2666363a54bSMatthew G. Knepley 
2676363a54bSMatthew G. Knepley static PetscErrorCode DMPlexGetPlaneSimplexIntersection_Internal(DM dm, PetscInt dim, PetscInt c, const PetscReal p[], const PetscReal normal[], PetscBool *pos, PetscInt *Nint, PetscReal intPoints[])
2686363a54bSMatthew G. Knepley {
2696363a54bSMatthew G. Knepley   const PetscScalar *array;
2706363a54bSMatthew G. Knepley   PetscScalar       *coords = NULL;
2716363a54bSMatthew G. Knepley   PetscInt           numCoords;
2726363a54bSMatthew G. Knepley   PetscBool          isDG;
2736363a54bSMatthew G. Knepley   PetscInt           cdim;
2746363a54bSMatthew G. Knepley 
2756363a54bSMatthew G. Knepley   PetscFunctionBegin;
2766363a54bSMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &cdim));
2776363a54bSMatthew 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);
2786363a54bSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
2796363a54bSMatthew 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);
2806363a54bSMatthew G. Knepley   PetscCall(PetscArrayzero(intPoints, dim * (dim + 1)));
2816363a54bSMatthew G. Knepley 
2826363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, coords, p, normal, pos, Nint, intPoints));
2836363a54bSMatthew G. Knepley 
2846363a54bSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
2856363a54bSMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
2866363a54bSMatthew G. Knepley }
2876363a54bSMatthew G. Knepley 
2886363a54bSMatthew G. Knepley static PetscErrorCode DMPlexGetPlaneQuadIntersection_Internal(DM dm, PetscInt dim, PetscInt c, const PetscReal p[], const PetscReal normal[], PetscBool *pos, PetscInt *Nint, PetscReal intPoints[])
2896363a54bSMatthew G. Knepley {
2906363a54bSMatthew G. Knepley   const PetscScalar *array;
2916363a54bSMatthew G. Knepley   PetscScalar       *coords = NULL;
2926363a54bSMatthew G. Knepley   PetscInt           numCoords;
2936363a54bSMatthew G. Knepley   PetscBool          isDG;
2946363a54bSMatthew G. Knepley   PetscInt           cdim;
2956363a54bSMatthew G. Knepley   PetscScalar        tcoords[6] = {0., 0., 0., 0., 0., 0.};
2966363a54bSMatthew G. Knepley   const PetscInt     vertsA[3]  = {0, 1, 3};
2976363a54bSMatthew G. Knepley   const PetscInt     vertsB[3]  = {1, 2, 3};
2986363a54bSMatthew G. Knepley   PetscInt           NintA, NintB;
2996363a54bSMatthew G. Knepley 
3006363a54bSMatthew G. Knepley   PetscFunctionBegin;
3016363a54bSMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &cdim));
3026363a54bSMatthew 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);
3036363a54bSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
3046363a54bSMatthew 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);
3056363a54bSMatthew G. Knepley   PetscCall(PetscArrayzero(intPoints, dim * 4));
3066363a54bSMatthew G. Knepley 
3076363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 3; ++v)
3086363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsA[v] * cdim + d];
3096363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintA, intPoints));
3106363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 3; ++v)
3116363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsB[v] * cdim + d];
3126363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintB, &intPoints[NintA * cdim]));
3136363a54bSMatthew G. Knepley   *Nint = NintA + NintB;
3146363a54bSMatthew G. Knepley 
3156363a54bSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
3166363a54bSMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
3176363a54bSMatthew G. Knepley }
3186363a54bSMatthew G. Knepley 
3196363a54bSMatthew G. Knepley static PetscErrorCode DMPlexGetPlaneHexIntersection_Internal(DM dm, PetscInt dim, PetscInt c, const PetscReal p[], const PetscReal normal[], PetscBool *pos, PetscInt *Nint, PetscReal intPoints[])
3206363a54bSMatthew G. Knepley {
3216363a54bSMatthew G. Knepley   const PetscScalar *array;
3226363a54bSMatthew G. Knepley   PetscScalar       *coords = NULL;
3236363a54bSMatthew G. Knepley   PetscInt           numCoords;
3246363a54bSMatthew G. Knepley   PetscBool          isDG;
3256363a54bSMatthew G. Knepley   PetscInt           cdim;
3266363a54bSMatthew G. Knepley   PetscScalar        tcoords[12] = {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.};
3276363a54bSMatthew G. Knepley   // We split using the (2, 4) main diagonal, so all tets contain those vertices
3286363a54bSMatthew G. Knepley   const PetscInt vertsA[4] = {0, 1, 2, 4};
3296363a54bSMatthew G. Knepley   const PetscInt vertsB[4] = {0, 2, 3, 4};
3306363a54bSMatthew G. Knepley   const PetscInt vertsC[4] = {1, 7, 2, 4};
3316363a54bSMatthew G. Knepley   const PetscInt vertsD[4] = {2, 7, 6, 4};
3326363a54bSMatthew G. Knepley   const PetscInt vertsE[4] = {3, 5, 4, 2};
3336363a54bSMatthew G. Knepley   const PetscInt vertsF[4] = {4, 5, 6, 2};
3346363a54bSMatthew G. Knepley   PetscInt       NintA, NintB, NintC, NintD, NintE, NintF, Nsum = 0;
3356363a54bSMatthew G. Knepley 
3366363a54bSMatthew G. Knepley   PetscFunctionBegin;
3376363a54bSMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &cdim));
3386363a54bSMatthew 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);
3396363a54bSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
3406363a54bSMatthew 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);
3416363a54bSMatthew G. Knepley   PetscCall(PetscArrayzero(intPoints, dim * 18));
3426363a54bSMatthew G. Knepley 
3436363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 4; ++v)
3446363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsA[v] * cdim + d];
3456363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintA, &intPoints[Nsum * cdim]));
3466363a54bSMatthew G. Knepley   Nsum += NintA;
3476363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 4; ++v)
3486363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsB[v] * cdim + d];
3496363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintB, &intPoints[Nsum * cdim]));
3506363a54bSMatthew G. Knepley   Nsum += NintB;
3516363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 4; ++v)
3526363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsC[v] * cdim + d];
3536363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintC, &intPoints[Nsum * cdim]));
3546363a54bSMatthew G. Knepley   Nsum += NintC;
3556363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 4; ++v)
3566363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsD[v] * cdim + d];
3576363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintD, &intPoints[Nsum * cdim]));
3586363a54bSMatthew G. Knepley   Nsum += NintD;
3596363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 4; ++v)
3606363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsE[v] * cdim + d];
3616363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintE, &intPoints[Nsum * cdim]));
3626363a54bSMatthew G. Knepley   Nsum += NintE;
3636363a54bSMatthew G. Knepley   for (PetscInt v = 0; v < 4; ++v)
3646363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) tcoords[v * cdim + d] = coords[vertsF[v] * cdim + d];
3656363a54bSMatthew G. Knepley   PetscCall(DMPlexGetPlaneSimplexIntersection_Coords_Internal(dm, dim, cdim, tcoords, p, normal, pos, &NintF, &intPoints[Nsum * cdim]));
3666363a54bSMatthew G. Knepley   Nsum += NintF;
3676363a54bSMatthew G. Knepley   *Nint = Nsum;
3686363a54bSMatthew G. Knepley 
3696363a54bSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
3706363a54bSMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
3716363a54bSMatthew G. Knepley }
3726363a54bSMatthew G. Knepley 
3736363a54bSMatthew G. Knepley /*
3746363a54bSMatthew G. Knepley   DMPlexGetPlaneCellIntersection_Internal - Finds the intersection of a plane with a cell
3756363a54bSMatthew G. Knepley 
3766363a54bSMatthew G. Knepley   Not collective
3776363a54bSMatthew G. Knepley 
3786363a54bSMatthew G. Knepley   Input Parameters:
3796363a54bSMatthew G. Knepley + dm     - the DM
3806363a54bSMatthew G. Knepley . c      - the mesh point
3816363a54bSMatthew G. Knepley . p      - a point on the plane.
3826363a54bSMatthew G. Knepley - normal - a normal vector to the plane, must be normalized
3836363a54bSMatthew G. Knepley 
3846363a54bSMatthew G. Knepley   Output Parameters:
3856363a54bSMatthew G. Knepley . pos       - `PETSC_TRUE` is the cell is on the positive side of the plane, `PETSC_FALSE` on the negative side
3866363a54bSMatthew G. Knepley + Nint      - the number of intersection points, in [0, 4]
3876363a54bSMatthew G. Knepley - intPoints - the coordinates of the intersection points, should be length at least 12
3886363a54bSMatthew G. Knepley 
389baca6076SPierre 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.
3906363a54bSMatthew G. Knepley 
3916363a54bSMatthew G. Knepley   Level: developer
3926363a54bSMatthew G. Knepley 
3936363a54bSMatthew G. Knepley .seealso:
3946363a54bSMatthew G. Knepley @*/
3956363a54bSMatthew G. Knepley static PetscErrorCode DMPlexGetPlaneCellIntersection_Internal(DM dm, PetscInt c, const PetscReal p[], const PetscReal normal[], PetscBool *pos, PetscInt *Nint, PetscReal intPoints[])
3966363a54bSMatthew G. Knepley {
3976363a54bSMatthew G. Knepley   DMPolytopeType ct;
3986363a54bSMatthew G. Knepley 
3996363a54bSMatthew G. Knepley   PetscFunctionBegin;
4006363a54bSMatthew G. Knepley   PetscCall(DMPlexGetCellType(dm, c, &ct));
4016363a54bSMatthew G. Knepley   switch (ct) {
4026363a54bSMatthew G. Knepley   case DM_POLYTOPE_SEGMENT:
4036363a54bSMatthew G. Knepley   case DM_POLYTOPE_TRIANGLE:
4046363a54bSMatthew G. Knepley   case DM_POLYTOPE_TETRAHEDRON:
4056363a54bSMatthew G. Knepley     PetscCall(DMPlexGetPlaneSimplexIntersection_Internal(dm, DMPolytopeTypeGetDim(ct), c, p, normal, pos, Nint, intPoints));
4066363a54bSMatthew G. Knepley     break;
4076363a54bSMatthew G. Knepley   case DM_POLYTOPE_QUADRILATERAL:
4086363a54bSMatthew G. Knepley     PetscCall(DMPlexGetPlaneQuadIntersection_Internal(dm, DMPolytopeTypeGetDim(ct), c, p, normal, pos, Nint, intPoints));
4096363a54bSMatthew G. Knepley     break;
4106363a54bSMatthew G. Knepley   case DM_POLYTOPE_HEXAHEDRON:
4116363a54bSMatthew G. Knepley     PetscCall(DMPlexGetPlaneHexIntersection_Internal(dm, DMPolytopeTypeGetDim(ct), c, p, normal, pos, Nint, intPoints));
4126363a54bSMatthew G. Knepley     break;
4136363a54bSMatthew G. Knepley   default:
4146363a54bSMatthew G. Knepley     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "No plane intersection for cell %" PetscInt_FMT " with type %s", c, DMPolytopeTypes[ct]);
4156363a54bSMatthew G. Knepley   }
4166363a54bSMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
4176363a54bSMatthew G. Knepley }
418ddce0771SMatthew G. Knepley 
419d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexLocatePoint_Simplex_1D_Internal(DM dm, const PetscScalar point[], PetscInt c, PetscInt *cell)
420d71ae5a4SJacob Faibussowitsch {
42114bbb9f0SLawrence Mitchell   const PetscReal eps = PETSC_SQRT_MACHINE_EPSILON;
42214bbb9f0SLawrence Mitchell   const PetscReal x   = PetscRealPart(point[0]);
42314bbb9f0SLawrence Mitchell   PetscReal       v0, J, invJ, detJ;
42414bbb9f0SLawrence Mitchell   PetscReal       xi;
42514bbb9f0SLawrence Mitchell 
42614bbb9f0SLawrence Mitchell   PetscFunctionBegin;
4279566063dSJacob Faibussowitsch   PetscCall(DMPlexComputeCellGeometryFEM(dm, c, NULL, &v0, &J, &invJ, &detJ));
42814bbb9f0SLawrence Mitchell   xi = invJ * (x - v0);
42914bbb9f0SLawrence Mitchell 
43014bbb9f0SLawrence Mitchell   if ((xi >= -eps) && (xi <= 2. + eps)) *cell = c;
43114bbb9f0SLawrence Mitchell   else *cell = DMLOCATEPOINT_POINT_NOT_FOUND;
4323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43314bbb9f0SLawrence Mitchell }
43414bbb9f0SLawrence Mitchell 
435d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexLocatePoint_Simplex_2D_Internal(DM dm, const PetscScalar point[], PetscInt c, PetscInt *cell)
436d71ae5a4SJacob Faibussowitsch {
437ccd2543fSMatthew G Knepley   const PetscInt  embedDim = 2;
438f5ebc837SMatthew G. Knepley   const PetscReal eps      = PETSC_SQRT_MACHINE_EPSILON;
439ccd2543fSMatthew G Knepley   PetscReal       x        = PetscRealPart(point[0]);
440ccd2543fSMatthew G Knepley   PetscReal       y        = PetscRealPart(point[1]);
441ccd2543fSMatthew G Knepley   PetscReal       v0[2], J[4], invJ[4], detJ;
442ccd2543fSMatthew G Knepley   PetscReal       xi, eta;
443ccd2543fSMatthew G Knepley 
444ccd2543fSMatthew G Knepley   PetscFunctionBegin;
4459566063dSJacob Faibussowitsch   PetscCall(DMPlexComputeCellGeometryFEM(dm, c, NULL, v0, J, invJ, &detJ));
446ccd2543fSMatthew G Knepley   xi  = invJ[0 * embedDim + 0] * (x - v0[0]) + invJ[0 * embedDim + 1] * (y - v0[1]);
447ccd2543fSMatthew G Knepley   eta = invJ[1 * embedDim + 0] * (x - v0[0]) + invJ[1 * embedDim + 1] * (y - v0[1]);
448ccd2543fSMatthew G Knepley 
449f5ebc837SMatthew G. Knepley   if ((xi >= -eps) && (eta >= -eps) && (xi + eta <= 2.0 + eps)) *cell = c;
450c1496c66SMatthew G. Knepley   else *cell = DMLOCATEPOINT_POINT_NOT_FOUND;
4513ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
452ccd2543fSMatthew G Knepley }
453ccd2543fSMatthew G Knepley 
454d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexClosestPoint_Simplex_2D_Internal(DM dm, const PetscScalar point[], PetscInt c, PetscReal cpoint[])
455d71ae5a4SJacob Faibussowitsch {
45662a38674SMatthew G. Knepley   const PetscInt embedDim = 2;
45762a38674SMatthew G. Knepley   PetscReal      x        = PetscRealPart(point[0]);
45862a38674SMatthew G. Knepley   PetscReal      y        = PetscRealPart(point[1]);
45962a38674SMatthew G. Knepley   PetscReal      v0[2], J[4], invJ[4], detJ;
46062a38674SMatthew G. Knepley   PetscReal      xi, eta, r;
46162a38674SMatthew G. Knepley 
46262a38674SMatthew G. Knepley   PetscFunctionBegin;
4639566063dSJacob Faibussowitsch   PetscCall(DMPlexComputeCellGeometryFEM(dm, c, NULL, v0, J, invJ, &detJ));
46462a38674SMatthew G. Knepley   xi  = invJ[0 * embedDim + 0] * (x - v0[0]) + invJ[0 * embedDim + 1] * (y - v0[1]);
46562a38674SMatthew G. Knepley   eta = invJ[1 * embedDim + 0] * (x - v0[0]) + invJ[1 * embedDim + 1] * (y - v0[1]);
46662a38674SMatthew G. Knepley 
46762a38674SMatthew G. Knepley   xi  = PetscMax(xi, 0.0);
46862a38674SMatthew G. Knepley   eta = PetscMax(eta, 0.0);
46962a38674SMatthew G. Knepley   if (xi + eta > 2.0) {
47062a38674SMatthew G. Knepley     r = (xi + eta) / 2.0;
47162a38674SMatthew G. Knepley     xi /= r;
47262a38674SMatthew G. Knepley     eta /= r;
47362a38674SMatthew G. Knepley   }
47462a38674SMatthew G. Knepley   cpoint[0] = J[0 * embedDim + 0] * xi + J[0 * embedDim + 1] * eta + v0[0];
47562a38674SMatthew G. Knepley   cpoint[1] = J[1 * embedDim + 0] * xi + J[1 * embedDim + 1] * eta + v0[1];
4763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
47762a38674SMatthew G. Knepley }
47862a38674SMatthew G. Knepley 
47961451c10SMatthew G. Knepley // This is the ray-casting, or even-odd algorithm: https://en.wikipedia.org/wiki/Even%E2%80%93odd_rule
480d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexLocatePoint_Quad_2D_Internal(DM dm, const PetscScalar point[], PetscInt c, PetscInt *cell)
481d71ae5a4SJacob Faibussowitsch {
48276b3799dSMatthew G. Knepley   const PetscScalar *array;
483a1e44745SMatthew G. Knepley   PetscScalar       *coords    = NULL;
484ccd2543fSMatthew G Knepley   const PetscInt     faces[8]  = {0, 1, 1, 2, 2, 3, 3, 0};
485ccd2543fSMatthew G Knepley   PetscReal          x         = PetscRealPart(point[0]);
486ccd2543fSMatthew G Knepley   PetscReal          y         = PetscRealPart(point[1]);
48776b3799dSMatthew G. Knepley   PetscInt           crossings = 0, numCoords, f;
48876b3799dSMatthew G. Knepley   PetscBool          isDG;
489ccd2543fSMatthew G Knepley 
490ccd2543fSMatthew G Knepley   PetscFunctionBegin;
49176b3799dSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
49276b3799dSMatthew G. Knepley   PetscCheck(numCoords == 8, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Quadrilateral should have 8 coordinates, not %" PetscInt_FMT, numCoords);
493ccd2543fSMatthew G Knepley   for (f = 0; f < 4; ++f) {
494ccd2543fSMatthew G Knepley     PetscReal x_i = PetscRealPart(coords[faces[2 * f + 0] * 2 + 0]);
495ccd2543fSMatthew G Knepley     PetscReal y_i = PetscRealPart(coords[faces[2 * f + 0] * 2 + 1]);
496ccd2543fSMatthew G Knepley     PetscReal x_j = PetscRealPart(coords[faces[2 * f + 1] * 2 + 0]);
497ccd2543fSMatthew G Knepley     PetscReal y_j = PetscRealPart(coords[faces[2 * f + 1] * 2 + 1]);
49861451c10SMatthew G. Knepley 
49961451c10SMatthew G. Knepley     if ((x == x_j) && (y == y_j)) {
50061451c10SMatthew G. Knepley       // point is a corner
50161451c10SMatthew G. Knepley       crossings = 1;
50261451c10SMatthew G. Knepley       break;
50361451c10SMatthew G. Knepley     }
50461451c10SMatthew G. Knepley     if ((y_j > y) != (y_i > y)) {
50561451c10SMatthew G. Knepley       PetscReal slope = (x - x_j) * (y_i - y_j) - (x_i - x_j) * (y - y_j);
50661451c10SMatthew G. Knepley       if (slope == 0) {
50761451c10SMatthew G. Knepley         // point is a corner
50861451c10SMatthew G. Knepley         crossings = 1;
50961451c10SMatthew G. Knepley         break;
51061451c10SMatthew G. Knepley       }
51161451c10SMatthew G. Knepley       if ((slope < 0) != (y_i < y_j)) ++crossings;
51261451c10SMatthew G. Knepley     }
513ccd2543fSMatthew G Knepley   }
514ccd2543fSMatthew G Knepley   if (crossings % 2) *cell = c;
515c1496c66SMatthew G. Knepley   else *cell = DMLOCATEPOINT_POINT_NOT_FOUND;
51676b3799dSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
5173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
518ccd2543fSMatthew G Knepley }
519ccd2543fSMatthew G Knepley 
520d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexLocatePoint_Simplex_3D_Internal(DM dm, const PetscScalar point[], PetscInt c, PetscInt *cell)
521d71ae5a4SJacob Faibussowitsch {
522ccd2543fSMatthew G Knepley   const PetscInt  embedDim = 3;
52337900f7dSMatthew G. Knepley   const PetscReal eps      = PETSC_SQRT_MACHINE_EPSILON;
524ccd2543fSMatthew G Knepley   PetscReal       v0[3], J[9], invJ[9], detJ;
525ccd2543fSMatthew G Knepley   PetscReal       x = PetscRealPart(point[0]);
526ccd2543fSMatthew G Knepley   PetscReal       y = PetscRealPart(point[1]);
527ccd2543fSMatthew G Knepley   PetscReal       z = PetscRealPart(point[2]);
528ccd2543fSMatthew G Knepley   PetscReal       xi, eta, zeta;
529ccd2543fSMatthew G Knepley 
530ccd2543fSMatthew G Knepley   PetscFunctionBegin;
5319566063dSJacob Faibussowitsch   PetscCall(DMPlexComputeCellGeometryFEM(dm, c, NULL, v0, J, invJ, &detJ));
532ccd2543fSMatthew G Knepley   xi   = invJ[0 * embedDim + 0] * (x - v0[0]) + invJ[0 * embedDim + 1] * (y - v0[1]) + invJ[0 * embedDim + 2] * (z - v0[2]);
533ccd2543fSMatthew G Knepley   eta  = invJ[1 * embedDim + 0] * (x - v0[0]) + invJ[1 * embedDim + 1] * (y - v0[1]) + invJ[1 * embedDim + 2] * (z - v0[2]);
534ccd2543fSMatthew G Knepley   zeta = invJ[2 * embedDim + 0] * (x - v0[0]) + invJ[2 * embedDim + 1] * (y - v0[1]) + invJ[2 * embedDim + 2] * (z - v0[2]);
535ccd2543fSMatthew G Knepley 
53637900f7dSMatthew G. Knepley   if ((xi >= -eps) && (eta >= -eps) && (zeta >= -eps) && (xi + eta + zeta <= 2.0 + eps)) *cell = c;
537c1496c66SMatthew G. Knepley   else *cell = DMLOCATEPOINT_POINT_NOT_FOUND;
5383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
539ccd2543fSMatthew G Knepley }
540ccd2543fSMatthew G Knepley 
541d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexLocatePoint_General_3D_Internal(DM dm, const PetscScalar point[], PetscInt c, PetscInt *cell)
542d71ae5a4SJacob Faibussowitsch {
54376b3799dSMatthew G. Knepley   const PetscScalar *array;
544872a9804SMatthew G. Knepley   PetscScalar       *coords    = NULL;
5459371c9d4SSatish 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};
546ccd2543fSMatthew G Knepley   PetscBool          found     = PETSC_TRUE;
54776b3799dSMatthew G. Knepley   PetscInt           numCoords, f;
54876b3799dSMatthew G. Knepley   PetscBool          isDG;
549ccd2543fSMatthew G Knepley 
550ccd2543fSMatthew G Knepley   PetscFunctionBegin;
55176b3799dSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
55276b3799dSMatthew G. Knepley   PetscCheck(numCoords == 24, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Quadrilateral should have 8 coordinates, not %" PetscInt_FMT, numCoords);
553ccd2543fSMatthew G Knepley   for (f = 0; f < 6; ++f) {
554ccd2543fSMatthew G Knepley     /* Check the point is under plane */
555ccd2543fSMatthew G Knepley     /*   Get face normal */
556ccd2543fSMatthew G Knepley     PetscReal v_i[3];
557ccd2543fSMatthew G Knepley     PetscReal v_j[3];
558ccd2543fSMatthew G Knepley     PetscReal normal[3];
559ccd2543fSMatthew G Knepley     PetscReal pp[3];
560ccd2543fSMatthew G Knepley     PetscReal dot;
561ccd2543fSMatthew G Knepley 
562ccd2543fSMatthew G Knepley     v_i[0]    = PetscRealPart(coords[faces[f * 4 + 3] * 3 + 0] - coords[faces[f * 4 + 0] * 3 + 0]);
563ccd2543fSMatthew G Knepley     v_i[1]    = PetscRealPart(coords[faces[f * 4 + 3] * 3 + 1] - coords[faces[f * 4 + 0] * 3 + 1]);
564ccd2543fSMatthew G Knepley     v_i[2]    = PetscRealPart(coords[faces[f * 4 + 3] * 3 + 2] - coords[faces[f * 4 + 0] * 3 + 2]);
565ccd2543fSMatthew G Knepley     v_j[0]    = PetscRealPart(coords[faces[f * 4 + 1] * 3 + 0] - coords[faces[f * 4 + 0] * 3 + 0]);
566ccd2543fSMatthew G Knepley     v_j[1]    = PetscRealPart(coords[faces[f * 4 + 1] * 3 + 1] - coords[faces[f * 4 + 0] * 3 + 1]);
567ccd2543fSMatthew G Knepley     v_j[2]    = PetscRealPart(coords[faces[f * 4 + 1] * 3 + 2] - coords[faces[f * 4 + 0] * 3 + 2]);
568ccd2543fSMatthew G Knepley     normal[0] = v_i[1] * v_j[2] - v_i[2] * v_j[1];
569ccd2543fSMatthew G Knepley     normal[1] = v_i[2] * v_j[0] - v_i[0] * v_j[2];
570ccd2543fSMatthew G Knepley     normal[2] = v_i[0] * v_j[1] - v_i[1] * v_j[0];
571ccd2543fSMatthew G Knepley     pp[0]     = PetscRealPart(coords[faces[f * 4 + 0] * 3 + 0] - point[0]);
572ccd2543fSMatthew G Knepley     pp[1]     = PetscRealPart(coords[faces[f * 4 + 0] * 3 + 1] - point[1]);
573ccd2543fSMatthew G Knepley     pp[2]     = PetscRealPart(coords[faces[f * 4 + 0] * 3 + 2] - point[2]);
574ccd2543fSMatthew G Knepley     dot       = normal[0] * pp[0] + normal[1] * pp[1] + normal[2] * pp[2];
575ccd2543fSMatthew G Knepley 
576ccd2543fSMatthew G Knepley     /* Check that projected point is in face (2D location problem) */
577ccd2543fSMatthew G Knepley     if (dot < 0.0) {
578ccd2543fSMatthew G Knepley       found = PETSC_FALSE;
579ccd2543fSMatthew G Knepley       break;
580ccd2543fSMatthew G Knepley     }
581ccd2543fSMatthew G Knepley   }
582ccd2543fSMatthew G Knepley   if (found) *cell = c;
583c1496c66SMatthew G. Knepley   else *cell = DMLOCATEPOINT_POINT_NOT_FOUND;
58476b3799dSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
5853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
586ccd2543fSMatthew G Knepley }
587ccd2543fSMatthew G Knepley 
588d71ae5a4SJacob Faibussowitsch static PetscErrorCode PetscGridHashInitialize_Internal(PetscGridHash box, PetscInt dim, const PetscScalar point[])
589d71ae5a4SJacob Faibussowitsch {
590c4eade1cSMatthew G. Knepley   PetscInt d;
591c4eade1cSMatthew G. Knepley 
592c4eade1cSMatthew G. Knepley   PetscFunctionBegin;
593c4eade1cSMatthew G. Knepley   box->dim = dim;
594378076f8SMatthew G. Knepley   for (d = 0; d < dim; ++d) box->lower[d] = box->upper[d] = point ? PetscRealPart(point[d]) : 0.;
5953ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
596c4eade1cSMatthew G. Knepley }
597c4eade1cSMatthew G. Knepley 
598d71ae5a4SJacob Faibussowitsch PetscErrorCode PetscGridHashCreate(MPI_Comm comm, PetscInt dim, const PetscScalar point[], PetscGridHash *box)
599d71ae5a4SJacob Faibussowitsch {
600c4eade1cSMatthew G. Knepley   PetscFunctionBegin;
6012b6f951bSStefano Zampini   PetscCall(PetscCalloc1(1, box));
6029566063dSJacob Faibussowitsch   PetscCall(PetscGridHashInitialize_Internal(*box, dim, point));
6033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
604c4eade1cSMatthew G. Knepley }
605c4eade1cSMatthew G. Knepley 
606d71ae5a4SJacob Faibussowitsch PetscErrorCode PetscGridHashEnlarge(PetscGridHash box, const PetscScalar point[])
607d71ae5a4SJacob Faibussowitsch {
608c4eade1cSMatthew G. Knepley   PetscInt d;
609c4eade1cSMatthew G. Knepley 
610c4eade1cSMatthew G. Knepley   PetscFunctionBegin;
611c4eade1cSMatthew G. Knepley   for (d = 0; d < box->dim; ++d) {
612c4eade1cSMatthew G. Knepley     box->lower[d] = PetscMin(box->lower[d], PetscRealPart(point[d]));
613c4eade1cSMatthew G. Knepley     box->upper[d] = PetscMax(box->upper[d], PetscRealPart(point[d]));
614c4eade1cSMatthew G. Knepley   }
6153ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
616c4eade1cSMatthew G. Knepley }
617c4eade1cSMatthew G. Knepley 
6186363a54bSMatthew G. Knepley static PetscErrorCode DMPlexCreateGridHash(DM dm, PetscGridHash *box)
6196363a54bSMatthew G. Knepley {
6206363a54bSMatthew G. Knepley   Vec                coordinates;
6216363a54bSMatthew G. Knepley   const PetscScalar *coords;
6226363a54bSMatthew G. Knepley   PetscInt           cdim, N, bs;
6236363a54bSMatthew G. Knepley 
6246363a54bSMatthew G. Knepley   PetscFunctionBegin;
6256363a54bSMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &cdim));
6266363a54bSMatthew G. Knepley   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
6276363a54bSMatthew G. Knepley   PetscCall(VecGetArrayRead(coordinates, &coords));
6286363a54bSMatthew G. Knepley   PetscCall(VecGetLocalSize(coordinates, &N));
6296363a54bSMatthew G. Knepley   PetscCall(VecGetBlockSize(coordinates, &bs));
6306363a54bSMatthew G. Knepley   PetscCheck(bs == cdim, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Coordinate block size %" PetscInt_FMT " != %" PetscInt_FMT " coordinate dimension", bs, cdim);
6316363a54bSMatthew G. Knepley 
63223f0ada9SStefano Zampini   PetscCall(PetscGridHashCreate(PetscObjectComm((PetscObject)dm), cdim, coords, box));
6336363a54bSMatthew G. Knepley   for (PetscInt i = 0; i < N; i += cdim) PetscCall(PetscGridHashEnlarge(*box, &coords[i]));
6346363a54bSMatthew G. Knepley 
6356363a54bSMatthew G. Knepley   PetscCall(VecRestoreArrayRead(coordinates, &coords));
6366363a54bSMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
6376363a54bSMatthew G. Knepley }
6386363a54bSMatthew G. Knepley 
639a4e35b19SJacob Faibussowitsch /*@C
64062a38674SMatthew G. Knepley   PetscGridHashSetGrid - Divide the grid into boxes
64162a38674SMatthew G. Knepley 
64220f4b53cSBarry Smith   Not Collective
64362a38674SMatthew G. Knepley 
64462a38674SMatthew G. Knepley   Input Parameters:
64562a38674SMatthew G. Knepley + box - The grid hash object
64620f4b53cSBarry Smith . n   - The number of boxes in each dimension, or `PETSC_DETERMINE`
64720f4b53cSBarry Smith - h   - The box size in each dimension, only used if n[d] == `PETSC_DETERMINE`
64862a38674SMatthew G. Knepley 
64962a38674SMatthew G. Knepley   Level: developer
65062a38674SMatthew G. Knepley 
6512fe279fdSBarry Smith .seealso: `DMPLEX`, `PetscGridHashCreate()`
652a4e35b19SJacob Faibussowitsch @*/
653d71ae5a4SJacob Faibussowitsch PetscErrorCode PetscGridHashSetGrid(PetscGridHash box, const PetscInt n[], const PetscReal h[])
654d71ae5a4SJacob Faibussowitsch {
655c4eade1cSMatthew G. Knepley   PetscInt d;
656c4eade1cSMatthew G. Knepley 
657c4eade1cSMatthew G. Knepley   PetscFunctionBegin;
6584f572ea9SToby Isaac   PetscAssertPointer(n, 2);
6594f572ea9SToby Isaac   if (h) PetscAssertPointer(h, 3);
660c4eade1cSMatthew G. Knepley   for (d = 0; d < box->dim; ++d) {
661c4eade1cSMatthew G. Knepley     box->extent[d] = box->upper[d] - box->lower[d];
662c4eade1cSMatthew G. Knepley     if (n[d] == PETSC_DETERMINE) {
66323f0ada9SStefano Zampini       PetscCheck(h, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Missing h");
664c4eade1cSMatthew G. Knepley       box->h[d] = h[d];
665c4eade1cSMatthew G. Knepley       box->n[d] = PetscCeilReal(box->extent[d] / h[d]);
666c4eade1cSMatthew G. Knepley     } else {
667c4eade1cSMatthew G. Knepley       box->n[d] = n[d];
668c4eade1cSMatthew G. Knepley       box->h[d] = box->extent[d] / n[d];
669c4eade1cSMatthew G. Knepley     }
670c4eade1cSMatthew G. Knepley   }
6713ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
672c4eade1cSMatthew G. Knepley }
673c4eade1cSMatthew G. Knepley 
674a4e35b19SJacob Faibussowitsch /*@C
67562a38674SMatthew G. Knepley   PetscGridHashGetEnclosingBox - Find the grid boxes containing each input point
67662a38674SMatthew G. Knepley 
67720f4b53cSBarry Smith   Not Collective
67862a38674SMatthew G. Knepley 
67962a38674SMatthew G. Knepley   Input Parameters:
68062a38674SMatthew G. Knepley + box       - The grid hash object
68162a38674SMatthew G. Knepley . numPoints - The number of input points
68262a38674SMatthew G. Knepley - points    - The input point coordinates
68362a38674SMatthew G. Knepley 
68462a38674SMatthew G. Knepley   Output Parameters:
68562a38674SMatthew G. Knepley + dboxes - An array of numPoints*dim integers expressing the enclosing box as (i_0, i_1, ..., i_dim)
68662a38674SMatthew G. Knepley - boxes  - An array of numPoints integers expressing the enclosing box as single number, or NULL
68762a38674SMatthew G. Knepley 
68862a38674SMatthew G. Knepley   Level: developer
68962a38674SMatthew G. Knepley 
690f5867de0SMatthew G. Knepley   Note:
691f5867de0SMatthew G. Knepley   This only guarantees that a box contains a point, not that a cell does.
692f5867de0SMatthew G. Knepley 
6932fe279fdSBarry Smith .seealso: `DMPLEX`, `PetscGridHashCreate()`
694a4e35b19SJacob Faibussowitsch @*/
695d71ae5a4SJacob Faibussowitsch PetscErrorCode PetscGridHashGetEnclosingBox(PetscGridHash box, PetscInt numPoints, const PetscScalar points[], PetscInt dboxes[], PetscInt boxes[])
696d71ae5a4SJacob Faibussowitsch {
697c4eade1cSMatthew G. Knepley   const PetscReal *lower = box->lower;
698c4eade1cSMatthew G. Knepley   const PetscReal *upper = box->upper;
699c4eade1cSMatthew G. Knepley   const PetscReal *h     = box->h;
700c4eade1cSMatthew G. Knepley   const PetscInt  *n     = box->n;
701c4eade1cSMatthew G. Knepley   const PetscInt   dim   = box->dim;
702c4eade1cSMatthew G. Knepley   PetscInt         d, p;
703c4eade1cSMatthew G. Knepley 
704c4eade1cSMatthew G. Knepley   PetscFunctionBegin;
705c4eade1cSMatthew G. Knepley   for (p = 0; p < numPoints; ++p) {
706c4eade1cSMatthew G. Knepley     for (d = 0; d < dim; ++d) {
7071c6dfc3eSMatthew G. Knepley       PetscInt dbox = PetscFloorReal((PetscRealPart(points[p * dim + d]) - lower[d]) / h[d]);
708c4eade1cSMatthew G. Knepley 
7091c6dfc3eSMatthew G. Knepley       if (dbox == n[d] && PetscAbsReal(PetscRealPart(points[p * dim + d]) - upper[d]) < 1.0e-9) dbox = n[d] - 1;
7102a705cacSMatthew G. Knepley       if (dbox == -1 && PetscAbsReal(PetscRealPart(points[p * dim + d]) - lower[d]) < 1.0e-9) dbox = 0;
7119371c9d4SSatish Balay       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", 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);
712c4eade1cSMatthew G. Knepley       dboxes[p * dim + d] = dbox;
713c4eade1cSMatthew G. Knepley     }
7149371c9d4SSatish Balay     if (boxes)
7159371c9d4SSatish 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];
716c4eade1cSMatthew G. Knepley   }
7173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
718c4eade1cSMatthew G. Knepley }
719c4eade1cSMatthew G. Knepley 
720af74b616SDave May /*
721af74b616SDave May   PetscGridHashGetEnclosingBoxQuery - Find the grid boxes containing each input point
722af74b616SDave May 
72320f4b53cSBarry Smith   Not Collective
724af74b616SDave May 
725af74b616SDave May   Input Parameters:
726af74b616SDave May + box         - The grid hash object
727f5867de0SMatthew G. Knepley . cellSection - The PetscSection mapping cells to boxes
728af74b616SDave May . numPoints   - The number of input points
729af74b616SDave May - points      - The input point coordinates
730af74b616SDave May 
731af74b616SDave May   Output Parameters:
73220f4b53cSBarry Smith + dboxes - An array of `numPoints`*`dim` integers expressing the enclosing box as (i_0, i_1, ..., i_dim)
73320f4b53cSBarry Smith . boxes  - An array of `numPoints` integers expressing the enclosing box as single number, or `NULL`
734af74b616SDave May - found  - Flag indicating if point was located within a box
735af74b616SDave May 
736af74b616SDave May   Level: developer
737af74b616SDave May 
738f5867de0SMatthew G. Knepley   Note:
73920f4b53cSBarry 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.
740f5867de0SMatthew G. Knepley 
7412fe279fdSBarry Smith .seealso: `DMPLEX`, `PetscGridHashGetEnclosingBox()`
742af74b616SDave May */
743a4e35b19SJacob Faibussowitsch static PetscErrorCode PetscGridHashGetEnclosingBoxQuery(PetscGridHash box, PetscSection cellSection, PetscInt numPoints, const PetscScalar points[], PetscInt dboxes[], PetscInt boxes[], PetscBool *found)
744d71ae5a4SJacob Faibussowitsch {
745af74b616SDave May   const PetscReal *lower = box->lower;
746af74b616SDave May   const PetscReal *upper = box->upper;
747af74b616SDave May   const PetscReal *h     = box->h;
748af74b616SDave May   const PetscInt  *n     = box->n;
749af74b616SDave May   const PetscInt   dim   = box->dim;
750f5867de0SMatthew G. Knepley   PetscInt         bStart, bEnd, d, p;
751af74b616SDave May 
752af74b616SDave May   PetscFunctionBegin;
753f5867de0SMatthew G. Knepley   PetscValidHeaderSpecific(cellSection, PETSC_SECTION_CLASSID, 2);
754af74b616SDave May   *found = PETSC_FALSE;
755f5867de0SMatthew G. Knepley   PetscCall(PetscSectionGetChart(box->cellSection, &bStart, &bEnd));
756af74b616SDave May   for (p = 0; p < numPoints; ++p) {
757af74b616SDave May     for (d = 0; d < dim; ++d) {
758af74b616SDave May       PetscInt dbox = PetscFloorReal((PetscRealPart(points[p * dim + d]) - lower[d]) / h[d]);
759af74b616SDave May 
760af74b616SDave May       if (dbox == n[d] && PetscAbsReal(PetscRealPart(points[p * dim + d]) - upper[d]) < 1.0e-9) dbox = n[d] - 1;
7613ba16761SJacob Faibussowitsch       if (dbox < 0 || dbox >= n[d]) PetscFunctionReturn(PETSC_SUCCESS);
762af74b616SDave May       dboxes[p * dim + d] = dbox;
763af74b616SDave May     }
7649371c9d4SSatish Balay     if (boxes)
7659371c9d4SSatish 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];
766f5867de0SMatthew G. Knepley     // It is possible for a box to overlap no grid cells
7673ba16761SJacob Faibussowitsch     if (boxes[p] < bStart || boxes[p] >= bEnd) PetscFunctionReturn(PETSC_SUCCESS);
768af74b616SDave May   }
769af74b616SDave May   *found = PETSC_TRUE;
7703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
771af74b616SDave May }
772af74b616SDave May 
773d71ae5a4SJacob Faibussowitsch PetscErrorCode PetscGridHashDestroy(PetscGridHash *box)
774d71ae5a4SJacob Faibussowitsch {
775c4eade1cSMatthew G. Knepley   PetscFunctionBegin;
776c4eade1cSMatthew G. Knepley   if (*box) {
7779566063dSJacob Faibussowitsch     PetscCall(PetscSectionDestroy(&(*box)->cellSection));
7789566063dSJacob Faibussowitsch     PetscCall(ISDestroy(&(*box)->cells));
7799566063dSJacob Faibussowitsch     PetscCall(DMLabelDestroy(&(*box)->cellsSparse));
780c4eade1cSMatthew G. Knepley   }
7819566063dSJacob Faibussowitsch   PetscCall(PetscFree(*box));
7823ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
783c4eade1cSMatthew G. Knepley }
784c4eade1cSMatthew G. Knepley 
785d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexLocatePoint_Internal(DM dm, PetscInt dim, const PetscScalar point[], PetscInt cellStart, PetscInt *cell)
786d71ae5a4SJacob Faibussowitsch {
787ba2698f1SMatthew G. Knepley   DMPolytopeType ct;
788cafe43deSMatthew G. Knepley 
789cafe43deSMatthew G. Knepley   PetscFunctionBegin;
7909566063dSJacob Faibussowitsch   PetscCall(DMPlexGetCellType(dm, cellStart, &ct));
791ba2698f1SMatthew G. Knepley   switch (ct) {
792d71ae5a4SJacob Faibussowitsch   case DM_POLYTOPE_SEGMENT:
793d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexLocatePoint_Simplex_1D_Internal(dm, point, cellStart, cell));
794d71ae5a4SJacob Faibussowitsch     break;
795d71ae5a4SJacob Faibussowitsch   case DM_POLYTOPE_TRIANGLE:
796d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexLocatePoint_Simplex_2D_Internal(dm, point, cellStart, cell));
797d71ae5a4SJacob Faibussowitsch     break;
798d71ae5a4SJacob Faibussowitsch   case DM_POLYTOPE_QUADRILATERAL:
799d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexLocatePoint_Quad_2D_Internal(dm, point, cellStart, cell));
800d71ae5a4SJacob Faibussowitsch     break;
801d71ae5a4SJacob Faibussowitsch   case DM_POLYTOPE_TETRAHEDRON:
802d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexLocatePoint_Simplex_3D_Internal(dm, point, cellStart, cell));
803d71ae5a4SJacob Faibussowitsch     break;
804d71ae5a4SJacob Faibussowitsch   case DM_POLYTOPE_HEXAHEDRON:
805d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexLocatePoint_General_3D_Internal(dm, point, cellStart, cell));
806d71ae5a4SJacob Faibussowitsch     break;
807d71ae5a4SJacob Faibussowitsch   default:
808d71ae5a4SJacob Faibussowitsch     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "No point location for cell %" PetscInt_FMT " with type %s", cellStart, DMPolytopeTypes[ct]);
809cafe43deSMatthew G. Knepley   }
8103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
811cafe43deSMatthew G. Knepley }
812cafe43deSMatthew G. Knepley 
81362a38674SMatthew G. Knepley /*
81462a38674SMatthew G. Knepley   DMPlexClosestPoint_Internal - Returns the closest point in the cell to the given point
81562a38674SMatthew G. Knepley */
816a4e35b19SJacob Faibussowitsch static PetscErrorCode DMPlexClosestPoint_Internal(DM dm, PetscInt dim, const PetscScalar point[], PetscInt cell, PetscReal cpoint[])
817d71ae5a4SJacob Faibussowitsch {
818ba2698f1SMatthew G. Knepley   DMPolytopeType ct;
81962a38674SMatthew G. Knepley 
82062a38674SMatthew G. Knepley   PetscFunctionBegin;
8219566063dSJacob Faibussowitsch   PetscCall(DMPlexGetCellType(dm, cell, &ct));
822ba2698f1SMatthew G. Knepley   switch (ct) {
823d71ae5a4SJacob Faibussowitsch   case DM_POLYTOPE_TRIANGLE:
824d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexClosestPoint_Simplex_2D_Internal(dm, point, cell, cpoint));
825d71ae5a4SJacob Faibussowitsch     break;
82662a38674SMatthew G. Knepley #if 0
827ba2698f1SMatthew G. Knepley     case DM_POLYTOPE_QUADRILATERAL:
8289566063dSJacob Faibussowitsch     PetscCall(DMPlexClosestPoint_General_2D_Internal(dm, point, cell, cpoint));break;
829ba2698f1SMatthew G. Knepley     case DM_POLYTOPE_TETRAHEDRON:
8309566063dSJacob Faibussowitsch     PetscCall(DMPlexClosestPoint_Simplex_3D_Internal(dm, point, cell, cpoint));break;
831ba2698f1SMatthew G. Knepley     case DM_POLYTOPE_HEXAHEDRON:
8329566063dSJacob Faibussowitsch     PetscCall(DMPlexClosestPoint_General_3D_Internal(dm, point, cell, cpoint));break;
83362a38674SMatthew G. Knepley #endif
834d71ae5a4SJacob Faibussowitsch   default:
835d71ae5a4SJacob Faibussowitsch     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "No closest point location for cell %" PetscInt_FMT " with type %s", cell, DMPolytopeTypes[ct]);
83662a38674SMatthew G. Knepley   }
8373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
83862a38674SMatthew G. Knepley }
83962a38674SMatthew G. Knepley 
84062a38674SMatthew G. Knepley /*
84120f4b53cSBarry Smith   DMPlexComputeGridHash_Internal - Create a grid hash structure covering the `DMPLEX`
84262a38674SMatthew G. Knepley 
84320f4b53cSBarry Smith   Collective
84462a38674SMatthew G. Knepley 
84562a38674SMatthew G. Knepley   Input Parameter:
84620f4b53cSBarry Smith . dm - The `DMPLEX`
84762a38674SMatthew G. Knepley 
84862a38674SMatthew G. Knepley   Output Parameter:
84962a38674SMatthew G. Knepley . localBox - The grid hash object
85062a38674SMatthew G. Knepley 
85162a38674SMatthew G. Knepley   Level: developer
85262a38674SMatthew G. Knepley 
8536363a54bSMatthew G. Knepley   Notes:
8546363a54bSMatthew G. Knepley   How do we determine all boxes intersecting a given cell?
8556363a54bSMatthew G. Knepley 
8566363a54bSMatthew G. Knepley   1) Get convex body enclosing cell. We will use a box called the box-hull.
8576363a54bSMatthew G. Knepley 
8586363a54bSMatthew G. Knepley   2) Get smallest brick of boxes enclosing the box-hull
8596363a54bSMatthew G. Knepley 
8606363a54bSMatthew G. Knepley   3) Each box is composed of 6 planes, 3 lower and 3 upper. We loop over dimensions, and
8616363a54bSMatthew G. Knepley      for each new plane determine whether the cell is on the negative side, positive side, or intersects it.
8626363a54bSMatthew G. Knepley 
8636363a54bSMatthew G. Knepley      a) If the cell is on the negative side of the lower planes, it is not in the box
8646363a54bSMatthew G. Knepley 
8656363a54bSMatthew G. Knepley      b) If the cell is on the positive side of the upper planes, it is not in the box
8666363a54bSMatthew G. Knepley 
8676363a54bSMatthew G. Knepley      c) If there is no intersection, it is in the box
8686363a54bSMatthew G. Knepley 
8696363a54bSMatthew G. Knepley      d) If any intersection point is within the box limits, it is in the box
8706363a54bSMatthew G. Knepley 
87120f4b53cSBarry Smith .seealso: `DMPLEX`, `PetscGridHashCreate()`, `PetscGridHashGetEnclosingBox()`
87262a38674SMatthew G. Knepley */
87366976f2fSJacob Faibussowitsch static PetscErrorCode DMPlexComputeGridHash_Internal(DM dm, PetscGridHash *localBox)
874d71ae5a4SJacob Faibussowitsch {
875f5867de0SMatthew G. Knepley   PetscInt        debug = ((DM_Plex *)dm->data)->printLocate;
876cafe43deSMatthew G. Knepley   PetscGridHash   lbox;
87796217254SMatthew G. Knepley   PetscSF         sf;
87896217254SMatthew G. Knepley   const PetscInt *leaves;
8796363a54bSMatthew G. Knepley   PetscInt       *dboxes, *boxes;
8806363a54bSMatthew G. Knepley   PetscInt        cdim, cStart, cEnd, Nl = -1;
881ddce0771SMatthew G. Knepley   PetscBool       flg;
882cafe43deSMatthew G. Knepley 
883cafe43deSMatthew G. Knepley   PetscFunctionBegin;
8846363a54bSMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &cdim));
8859566063dSJacob Faibussowitsch   PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
8866363a54bSMatthew G. Knepley   PetscCall(DMPlexCreateGridHash(dm, &lbox));
8876363a54bSMatthew G. Knepley   {
8886363a54bSMatthew G. Knepley     PetscInt n[3], d;
8896363a54bSMatthew G. Knepley 
8906363a54bSMatthew G. Knepley     PetscCall(PetscOptionsGetIntArray(NULL, ((PetscObject)dm)->prefix, "-dm_plex_hash_box_faces", n, &d, &flg));
8919371c9d4SSatish Balay     if (flg) {
8926363a54bSMatthew G. Knepley       for (PetscInt i = d; i < cdim; ++i) n[i] = n[d - 1];
8939371c9d4SSatish Balay     } else {
8946363a54bSMatthew G. Knepley       for (PetscInt i = 0; i < cdim; ++i) n[i] = PetscMax(2, PetscFloorReal(PetscPowReal((PetscReal)(cEnd - cStart), 1.0 / cdim) * 0.8));
8959371c9d4SSatish Balay     }
8969566063dSJacob Faibussowitsch     PetscCall(PetscGridHashSetGrid(lbox, n, NULL));
8979371c9d4SSatish Balay     if (debug)
8986363a54bSMatthew 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.,
8996363a54bSMatthew 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.));
9006363a54bSMatthew G. Knepley   }
9016363a54bSMatthew G. Knepley 
90296217254SMatthew G. Knepley   PetscCall(DMGetPointSF(dm, &sf));
90396217254SMatthew G. Knepley   if (sf) PetscCall(PetscSFGetGraph(sf, NULL, &Nl, &leaves, NULL));
90496217254SMatthew G. Knepley   Nl = PetscMax(Nl, 0);
9056363a54bSMatthew G. Knepley   PetscCall(PetscCalloc2(16 * cdim, &dboxes, 16, &boxes));
9066363a54bSMatthew G. Knepley 
9076363a54bSMatthew G. Knepley   PetscCall(DMLabelCreate(PETSC_COMM_SELF, "cells", &lbox->cellsSparse));
9086363a54bSMatthew G. Knepley   PetscCall(DMLabelCreateIndex(lbox->cellsSparse, cStart, cEnd));
9096363a54bSMatthew G. Knepley   for (PetscInt c = cStart; c < cEnd; ++c) {
9106363a54bSMatthew G. Knepley     PetscReal          intPoints[6 * 6 * 6 * 3];
9116363a54bSMatthew G. Knepley     const PetscScalar *array;
9126363a54bSMatthew G. Knepley     PetscScalar       *coords            = NULL;
913cafe43deSMatthew G. Knepley     const PetscReal   *h                 = lbox->h;
9146363a54bSMatthew G. Knepley     PetscReal          normal[9]         = {1., 0., 0., 0., 1., 0., 0., 0., 1.};
9156363a54bSMatthew G. Knepley     PetscReal         *lowerIntPoints[3] = {&intPoints[0 * 6 * 6 * 3], &intPoints[1 * 6 * 6 * 3], &intPoints[2 * 6 * 6 * 3]};
9166363a54bSMatthew G. Knepley     PetscReal         *upperIntPoints[3] = {&intPoints[3 * 6 * 6 * 3], &intPoints[4 * 6 * 6 * 3], &intPoints[5 * 6 * 6 * 3]};
9176363a54bSMatthew G. Knepley     PetscReal          lp[3], up[3], *tmp;
9186363a54bSMatthew G. Knepley     PetscInt           numCoords, idx, dlim[6], lowerInt[3], upperInt[3];
9196363a54bSMatthew G. Knepley     PetscBool          isDG, lower[3], upper[3];
920cafe43deSMatthew G. Knepley 
92196217254SMatthew G. Knepley     PetscCall(PetscFindInt(c, Nl, leaves, &idx));
92296217254SMatthew G. Knepley     if (idx >= 0) continue;
9236363a54bSMatthew G. Knepley     // Get grid of boxes containing the cell
9246363a54bSMatthew G. Knepley     PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
9256363a54bSMatthew G. Knepley     PetscCall(PetscGridHashGetEnclosingBox(lbox, numCoords / cdim, coords, dboxes, boxes));
9266363a54bSMatthew G. Knepley     PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &coords));
9276363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) dlim[d * 2 + 0] = dlim[d * 2 + 1] = dboxes[d];
9286363a54bSMatthew G. Knepley     for (PetscInt d = cdim; d < 3; ++d) dlim[d * 2 + 0] = dlim[d * 2 + 1] = 0;
9296363a54bSMatthew G. Knepley     for (PetscInt e = 1; e < numCoords / cdim; ++e) {
9306363a54bSMatthew G. Knepley       for (PetscInt d = 0; d < cdim; ++d) {
9316363a54bSMatthew G. Knepley         dlim[d * 2 + 0] = PetscMin(dlim[d * 2 + 0], dboxes[e * cdim + d]);
9326363a54bSMatthew G. Knepley         dlim[d * 2 + 1] = PetscMax(dlim[d * 2 + 1], dboxes[e * cdim + d]);
933ddce0771SMatthew G. Knepley       }
934ddce0771SMatthew G. Knepley     }
9356363a54bSMatthew G. Knepley     if (debug > 4) {
9366363a54bSMatthew 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]));
937ddce0771SMatthew G. Knepley     }
9386363a54bSMatthew G. Knepley     // Initialize with lower planes for first box
9396363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) {
9406363a54bSMatthew G. Knepley       lp[d] = lbox->lower[d] + dlim[d * 2 + 0] * h[d];
9416363a54bSMatthew G. Knepley       up[d] = lp[d] + h[d];
9426363a54bSMatthew G. Knepley     }
9436363a54bSMatthew G. Knepley     for (PetscInt d = 0; d < cdim; ++d) {
9446363a54bSMatthew G. Knepley       PetscCall(DMPlexGetPlaneCellIntersection_Internal(dm, c, lp, &normal[d * 3], &lower[d], &lowerInt[d], lowerIntPoints[d]));
9456363a54bSMatthew G. Knepley       if (debug > 4) {
9466363a54bSMatthew G. Knepley         if (!lowerInt[d])
9476363a54bSMatthew 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"));
9486363a54bSMatthew 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]));
949cafe43deSMatthew G. Knepley       }
950cafe43deSMatthew G. Knepley     }
9516363a54bSMatthew G. Knepley     // Loop over grid
9526363a54bSMatthew G. Knepley     for (PetscInt k = dlim[2 * 2 + 0]; k <= dlim[2 * 2 + 1]; ++k, lp[2] = up[2], up[2] += h[2]) {
9536363a54bSMatthew G. Knepley       if (cdim > 2) PetscCall(DMPlexGetPlaneCellIntersection_Internal(dm, c, up, &normal[3 * 2], &upper[2], &upperInt[2], upperIntPoints[2]));
9546363a54bSMatthew G. Knepley       if (cdim > 2 && debug > 4) {
9556363a54bSMatthew 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"));
9566363a54bSMatthew 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]));
9576363a54bSMatthew G. Knepley       }
9586363a54bSMatthew G. Knepley       for (PetscInt j = dlim[1 * 2 + 0]; j <= dlim[1 * 2 + 1]; ++j, lp[1] = up[1], up[1] += h[1]) {
9596363a54bSMatthew G. Knepley         if (cdim > 1) PetscCall(DMPlexGetPlaneCellIntersection_Internal(dm, c, up, &normal[3 * 1], &upper[1], &upperInt[1], upperIntPoints[1]));
9606363a54bSMatthew G. Knepley         if (cdim > 1 && debug > 4) {
9616363a54bSMatthew G. Knepley           if (!upperInt[1])
9626363a54bSMatthew 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"));
9636363a54bSMatthew 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]));
9646363a54bSMatthew G. Knepley         }
9656363a54bSMatthew G. Knepley         for (PetscInt i = dlim[0 * 2 + 0]; i <= dlim[0 * 2 + 1]; ++i, lp[0] = up[0], up[0] += h[0]) {
966cafe43deSMatthew G. Knepley           const PetscInt box    = (k * lbox->n[1] + j) * lbox->n[0] + i;
9676363a54bSMatthew G. Knepley           PetscBool      excNeg = PETSC_TRUE;
9686363a54bSMatthew G. Knepley           PetscBool      excPos = PETSC_TRUE;
9696363a54bSMatthew G. Knepley           PetscInt       NlInt  = 0;
9706363a54bSMatthew G. Knepley           PetscInt       NuInt  = 0;
971cafe43deSMatthew G. Knepley 
9726363a54bSMatthew G. Knepley           PetscCall(DMPlexGetPlaneCellIntersection_Internal(dm, c, up, &normal[3 * 0], &upper[0], &upperInt[0], upperIntPoints[0]));
9736363a54bSMatthew G. Knepley           if (debug > 4) {
9746363a54bSMatthew G. Knepley             if (!upperInt[0])
9756363a54bSMatthew 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"));
9766363a54bSMatthew 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]));
9776363a54bSMatthew G. Knepley           }
9786363a54bSMatthew G. Knepley           for (PetscInt d = 0; d < cdim; ++d) {
9796363a54bSMatthew G. Knepley             NlInt += lowerInt[d];
9806363a54bSMatthew G. Knepley             NuInt += upperInt[d];
9816363a54bSMatthew G. Knepley           }
9826363a54bSMatthew G. Knepley           // If there is no intersection...
9836363a54bSMatthew G. Knepley           if (!NlInt && !NuInt) {
9846363a54bSMatthew G. Knepley             // If the cell is on the negative side of the lower planes, it is not in the box
9856363a54bSMatthew G. Knepley             for (PetscInt d = 0; d < cdim; ++d)
9866363a54bSMatthew G. Knepley               if (lower[d]) {
9876363a54bSMatthew G. Knepley                 excNeg = PETSC_FALSE;
9880b6bfacdSStefano Zampini                 break;
9890b6bfacdSStefano Zampini               }
9906363a54bSMatthew G. Knepley             // If the cell is on the positive side of the upper planes, it is not in the box
9916363a54bSMatthew G. Knepley             for (PetscInt d = 0; d < cdim; ++d)
9926363a54bSMatthew G. Knepley               if (!upper[d]) {
9936363a54bSMatthew G. Knepley                 excPos = PETSC_FALSE;
9949371c9d4SSatish Balay                 break;
995ddce0771SMatthew G. Knepley               }
9966363a54bSMatthew G. Knepley             if (excNeg || excPos) {
9976363a54bSMatthew G. Knepley               if (debug && excNeg) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " is on the negative side of the lower plane\n", c));
9986363a54bSMatthew G. Knepley               if (debug && excPos) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " is on the positive side of the upper plane\n", c));
9996363a54bSMatthew G. Knepley               continue;
10006363a54bSMatthew G. Knepley             }
10016363a54bSMatthew G. Knepley             // Otherwise it is in the box
10026363a54bSMatthew G. Knepley             if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Cell %" PetscInt_FMT " is contained in box %" PetscInt_FMT "\n", c, box));
10036363a54bSMatthew G. Knepley             PetscCall(DMLabelSetValue(lbox->cellsSparse, c, box));
10046363a54bSMatthew G. Knepley             continue;
10056363a54bSMatthew G. Knepley           }
1006b3e8128dSjosephpu           /*
1007b3e8128dSjosephpu             If any intersection point is within the box limits, it is in the box
1008b3e8128dSjosephpu             We need to have tolerances here since intersection point calculations can introduce errors
1009b3e8128dSjosephpu             Initialize a count to track which planes have intersection outside the box.
1010b3e8128dSjosephpu             if two adjacent planes have intersection points upper and lower all outside the box, look
1011b3e8128dSjosephpu             first at if another plane has intersection points outside the box, if so, it is inside the cell
1012b3e8128dSjosephpu             look next if no intersection points exist on the other planes, and check if the planes are on the
1013b3e8128dSjosephpu             outside of the intersection points but on opposite ends. If so, the box cuts through the cell.
1014b3e8128dSjosephpu           */
1015b3e8128dSjosephpu           PetscInt outsideCount[6] = {0, 0, 0, 0, 0, 0};
10166363a54bSMatthew G. Knepley           for (PetscInt plane = 0; plane < cdim; ++plane) {
10176363a54bSMatthew G. Knepley             for (PetscInt ip = 0; ip < lowerInt[plane]; ++ip) {
10186363a54bSMatthew G. Knepley               PetscInt d;
10196363a54bSMatthew G. Knepley 
10206363a54bSMatthew G. Knepley               for (d = 0; d < cdim; ++d) {
1021b3e8128dSjosephpu                 if ((lowerIntPoints[plane][ip * cdim + d] < (lp[d] - PETSC_SMALL)) || (lowerIntPoints[plane][ip * cdim + d] > (up[d] + PETSC_SMALL))) {
1022b3e8128dSjosephpu                   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
1023b3e8128dSjosephpu                   break;
1024b3e8128dSjosephpu                 }
10256363a54bSMatthew G. Knepley               }
10266363a54bSMatthew G. Knepley               if (d == cdim) {
10276363a54bSMatthew 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));
10286363a54bSMatthew G. Knepley                 PetscCall(DMLabelSetValue(lbox->cellsSparse, c, box));
10296363a54bSMatthew G. Knepley                 goto end;
10306363a54bSMatthew G. Knepley               }
10316363a54bSMatthew G. Knepley             }
10326363a54bSMatthew G. Knepley             for (PetscInt ip = 0; ip < upperInt[plane]; ++ip) {
10336363a54bSMatthew G. Knepley               PetscInt d;
10346363a54bSMatthew G. Knepley 
10356363a54bSMatthew G. Knepley               for (d = 0; d < cdim; ++d) {
1036b3e8128dSjosephpu                 if ((upperIntPoints[plane][ip * cdim + d] < (lp[d] - PETSC_SMALL)) || (upperIntPoints[plane][ip * cdim + d] > (up[d] + PETSC_SMALL))) {
1037b3e8128dSjosephpu                   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
1038b3e8128dSjosephpu                   break;
1039b3e8128dSjosephpu                 }
10406363a54bSMatthew G. Knepley               }
10416363a54bSMatthew G. Knepley               if (d == cdim) {
10426363a54bSMatthew 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));
10436363a54bSMatthew G. Knepley                 PetscCall(DMLabelSetValue(lbox->cellsSparse, c, box));
10446363a54bSMatthew G. Knepley                 goto end;
1045ddce0771SMatthew G. Knepley               }
1046ddce0771SMatthew G. Knepley             }
1047cafe43deSMatthew G. Knepley           }
1048b3e8128dSjosephpu           /*
1049b3e8128dSjosephpu              Check the planes with intersections
1050b3e8128dSjosephpu              in 2D, check if the square falls in the middle of a cell
1051b3e8128dSjosephpu              ie all four planes have intersection points outside of the box
1052b3e8128dSjosephpu              You do not want to be doing this, because it means your grid hashing is finer than your grid,
1053b3e8128dSjosephpu              but we should still support it I guess
1054b3e8128dSjosephpu           */
1055b3e8128dSjosephpu           if (cdim == 2) {
1056b3e8128dSjosephpu             PetscInt nIntersects = 0;
1057b3e8128dSjosephpu             for (PetscInt d = 0; d < cdim; ++d) nIntersects += (outsideCount[d] + outsideCount[d + cdim]);
1058b3e8128dSjosephpu             // if the count adds up to 8, that means each plane has 2 external intersections and thus it is in the cell
1059b3e8128dSjosephpu             if (nIntersects == 8) {
1060b3e8128dSjosephpu               PetscCall(DMLabelSetValue(lbox->cellsSparse, c, box));
1061b3e8128dSjosephpu               goto end;
1062b3e8128dSjosephpu             }
1063b3e8128dSjosephpu           }
1064b3e8128dSjosephpu           /*
1065baca6076SPierre Jolivet              In 3 dimensions, if two adjacent planes have at least 3 intersections outside the cell in the appropriate direction,
1066b3e8128dSjosephpu              we then check the 3rd planar dimension. If a plane falls between intersection points, the cell belongs to that box.
1067b3e8128dSjosephpu              If the planes are on opposite sides of the intersection points, the cell belongs to that box and it passes through the cell.
1068b3e8128dSjosephpu           */
1069b3e8128dSjosephpu           if (cdim == 3) {
1070b3e8128dSjosephpu             PetscInt faces[3] = {0, 0, 0}, checkInternalFace = 0;
1071b3e8128dSjosephpu             // Find two adjacent planes with at least 3 intersection points in the upper and lower
1072b3e8128dSjosephpu             // if the third plane has 3 intersection points or more, a pyramid base is formed on that plane and it is in the cell
1073b3e8128dSjosephpu             for (PetscInt d = 0; d < cdim; ++d)
1074b3e8128dSjosephpu               if (outsideCount[d] >= 3 && outsideCount[cdim + d] >= 3) {
1075b3e8128dSjosephpu                 faces[d]++;
1076b3e8128dSjosephpu                 checkInternalFace++;
1077b3e8128dSjosephpu               }
1078b3e8128dSjosephpu             if (checkInternalFace == 3) {
1079b3e8128dSjosephpu               // All planes have 3 intersection points, add it.
1080b3e8128dSjosephpu               PetscCall(DMLabelSetValue(lbox->cellsSparse, c, box));
1081b3e8128dSjosephpu               goto end;
1082b3e8128dSjosephpu             }
1083b3e8128dSjosephpu             // Gross, figure out which adjacent faces have at least 3 points
1084b3e8128dSjosephpu             PetscInt nonIntersectingFace = -1;
1085b3e8128dSjosephpu             if (faces[0] == faces[1]) nonIntersectingFace = 2;
1086b3e8128dSjosephpu             if (faces[0] == faces[2]) nonIntersectingFace = 1;
1087b3e8128dSjosephpu             if (faces[1] == faces[2]) nonIntersectingFace = 0;
1088b3e8128dSjosephpu             if (nonIntersectingFace >= 0) {
1089b3e8128dSjosephpu               for (PetscInt plane = 0; plane < cdim; ++plane) {
1090b3e8128dSjosephpu                 if (!lowerInt[nonIntersectingFace] && !upperInt[nonIntersectingFace]) continue;
1091b3e8128dSjosephpu                 // 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.
1092b3e8128dSjosephpu                 for (PetscInt ip = 0; ip < lowerInt[nonIntersectingFace]; ++ip) {
1093b3e8128dSjosephpu                   if (lowerIntPoints[plane][ip * cdim + nonIntersectingFace] > lp[nonIntersectingFace] - PETSC_SMALL || lowerIntPoints[plane][ip * cdim + nonIntersectingFace] < up[nonIntersectingFace] + PETSC_SMALL) goto setpoint;
1094b3e8128dSjosephpu                 }
1095b3e8128dSjosephpu                 for (PetscInt ip = 0; ip < upperInt[nonIntersectingFace]; ++ip) {
1096b3e8128dSjosephpu                   if (upperIntPoints[plane][ip * cdim + nonIntersectingFace] > lp[nonIntersectingFace] - PETSC_SMALL || upperIntPoints[plane][ip * cdim + nonIntersectingFace] < up[nonIntersectingFace] + PETSC_SMALL) goto setpoint;
1097b3e8128dSjosephpu                 }
1098b3e8128dSjosephpu                 goto end;
1099b3e8128dSjosephpu               }
1100b3e8128dSjosephpu               // The points are within the bonds of the non intersecting planes, add it.
1101b3e8128dSjosephpu             setpoint:
1102b3e8128dSjosephpu               PetscCall(DMLabelSetValue(lbox->cellsSparse, c, box));
1103b3e8128dSjosephpu               goto end;
1104b3e8128dSjosephpu             }
1105b3e8128dSjosephpu           }
11066363a54bSMatthew G. Knepley         end:
11076363a54bSMatthew G. Knepley           lower[0]          = upper[0];
11086363a54bSMatthew G. Knepley           lowerInt[0]       = upperInt[0];
11096363a54bSMatthew G. Knepley           tmp               = lowerIntPoints[0];
11106363a54bSMatthew G. Knepley           lowerIntPoints[0] = upperIntPoints[0];
11116363a54bSMatthew G. Knepley           upperIntPoints[0] = tmp;
11126363a54bSMatthew G. Knepley         }
11136363a54bSMatthew G. Knepley         lp[0]             = lbox->lower[0] + dlim[0 * 2 + 0] * h[0];
11146363a54bSMatthew G. Knepley         up[0]             = lp[0] + h[0];
11156363a54bSMatthew G. Knepley         lower[1]          = upper[1];
11166363a54bSMatthew G. Knepley         lowerInt[1]       = upperInt[1];
11176363a54bSMatthew G. Knepley         tmp               = lowerIntPoints[1];
11186363a54bSMatthew G. Knepley         lowerIntPoints[1] = upperIntPoints[1];
11196363a54bSMatthew G. Knepley         upperIntPoints[1] = tmp;
11206363a54bSMatthew G. Knepley       }
11216363a54bSMatthew G. Knepley       lp[1]             = lbox->lower[1] + dlim[1 * 2 + 0] * h[1];
11226363a54bSMatthew G. Knepley       up[1]             = lp[1] + h[1];
11236363a54bSMatthew G. Knepley       lower[2]          = upper[2];
11246363a54bSMatthew G. Knepley       lowerInt[2]       = upperInt[2];
11256363a54bSMatthew G. Knepley       tmp               = lowerIntPoints[2];
11266363a54bSMatthew G. Knepley       lowerIntPoints[2] = upperIntPoints[2];
11276363a54bSMatthew G. Knepley       upperIntPoints[2] = tmp;
1128fea14342SMatthew G. Knepley     }
1129fea14342SMatthew G. Knepley   }
11306363a54bSMatthew G. Knepley   PetscCall(PetscFree2(dboxes, boxes));
11316363a54bSMatthew G. Knepley 
11329566063dSJacob Faibussowitsch   if (debug) PetscCall(DMLabelView(lbox->cellsSparse, PETSC_VIEWER_STDOUT_SELF));
11339566063dSJacob Faibussowitsch   PetscCall(DMLabelConvertToSection(lbox->cellsSparse, &lbox->cellSection, &lbox->cells));
11349566063dSJacob Faibussowitsch   PetscCall(DMLabelDestroy(&lbox->cellsSparse));
1135cafe43deSMatthew G. Knepley   *localBox = lbox;
11363ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1137cafe43deSMatthew G. Knepley }
1138cafe43deSMatthew G. Knepley 
1139d71ae5a4SJacob Faibussowitsch PetscErrorCode DMLocatePoints_Plex(DM dm, Vec v, DMPointLocationType ltype, PetscSF cellSF)
1140d71ae5a4SJacob Faibussowitsch {
1141f5867de0SMatthew G. Knepley   PetscInt        debug = ((DM_Plex *)dm->data)->printLocate;
1142cafe43deSMatthew G. Knepley   DM_Plex        *mesh  = (DM_Plex *)dm->data;
1143af74b616SDave May   PetscBool       hash = mesh->useHashLocation, reuse = PETSC_FALSE;
11443a93e3b7SToby Isaac   PetscInt        bs, numPoints, p, numFound, *found = NULL;
1145d8206211SMatthew G. Knepley   PetscInt        dim, Nl = 0, cStart, cEnd, numCells, c, d;
1146d8206211SMatthew G. Knepley   PetscSF         sf;
1147d8206211SMatthew G. Knepley   const PetscInt *leaves;
1148cafe43deSMatthew G. Knepley   const PetscInt *boxCells;
11493a93e3b7SToby Isaac   PetscSFNode    *cells;
1150ccd2543fSMatthew G Knepley   PetscScalar    *a;
11513a93e3b7SToby Isaac   PetscMPIInt     result;
1152af74b616SDave May   PetscLogDouble  t0, t1;
11539cb35068SDave May   PetscReal       gmin[3], gmax[3];
11549cb35068SDave May   PetscInt        terminating_query_type[] = {0, 0, 0};
11556363a54bSMatthew G. Knepley   PetscMPIInt     rank;
1156ccd2543fSMatthew G Knepley 
1157ccd2543fSMatthew G Knepley   PetscFunctionBegin;
11586363a54bSMatthew G. Knepley   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
11599566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(DMPLEX_LocatePoints, 0, 0, 0, 0));
11609566063dSJacob Faibussowitsch   PetscCall(PetscTime(&t0));
11611dca8a05SBarry 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.");
11629566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &dim));
11639566063dSJacob Faibussowitsch   PetscCall(VecGetBlockSize(v, &bs));
11649566063dSJacob Faibussowitsch   PetscCallMPI(MPI_Comm_compare(PetscObjectComm((PetscObject)cellSF), PETSC_COMM_SELF, &result));
11651dca8a05SBarry Smith   PetscCheck(result == MPI_IDENT || result == MPI_CONGRUENT, PetscObjectComm((PetscObject)cellSF), PETSC_ERR_SUP, "Trying parallel point location: only local point location supported");
116663a3b9bcSJacob Faibussowitsch   PetscCheck(bs == dim, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Block size for point vector %" PetscInt_FMT " must be the mesh coordinate dimension %" PetscInt_FMT, bs, dim);
11676858538eSMatthew G. Knepley   PetscCall(DMGetCoordinatesLocalSetUp(dm));
11689566063dSJacob Faibussowitsch   PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
1169d8206211SMatthew G. Knepley   PetscCall(DMGetPointSF(dm, &sf));
1170d8206211SMatthew G. Knepley   if (sf) PetscCall(PetscSFGetGraph(sf, NULL, &Nl, &leaves, NULL));
1171d8206211SMatthew G. Knepley   Nl = PetscMax(Nl, 0);
11729566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(v, &numPoints));
11739566063dSJacob Faibussowitsch   PetscCall(VecGetArray(v, &a));
1174ccd2543fSMatthew G Knepley   numPoints /= bs;
1175af74b616SDave May   {
1176af74b616SDave May     const PetscSFNode *sf_cells;
1177af74b616SDave May 
11789566063dSJacob Faibussowitsch     PetscCall(PetscSFGetGraph(cellSF, NULL, NULL, NULL, &sf_cells));
1179af74b616SDave May     if (sf_cells) {
11809566063dSJacob Faibussowitsch       PetscCall(PetscInfo(dm, "[DMLocatePoints_Plex] Re-using existing StarForest node list\n"));
1181af74b616SDave May       cells = (PetscSFNode *)sf_cells;
1182af74b616SDave May       reuse = PETSC_TRUE;
1183af74b616SDave May     } else {
11849566063dSJacob Faibussowitsch       PetscCall(PetscInfo(dm, "[DMLocatePoints_Plex] Creating and initializing new StarForest node list\n"));
11859566063dSJacob Faibussowitsch       PetscCall(PetscMalloc1(numPoints, &cells));
1186af74b616SDave May       /* initialize cells if created */
1187af74b616SDave May       for (p = 0; p < numPoints; p++) {
1188af74b616SDave May         cells[p].rank  = 0;
1189af74b616SDave May         cells[p].index = DMLOCATEPOINT_POINT_NOT_FOUND;
1190af74b616SDave May       }
1191af74b616SDave May     }
1192af74b616SDave May   }
119376b3799dSMatthew G. Knepley   PetscCall(DMGetBoundingBox(dm, gmin, gmax));
1194953fc75cSMatthew G. Knepley   if (hash) {
11959371c9d4SSatish Balay     if (!mesh->lbox) {
119696217254SMatthew G. Knepley       PetscCall(PetscInfo(dm, "Initializing grid hashing\n"));
11979371c9d4SSatish Balay       PetscCall(DMPlexComputeGridHash_Internal(dm, &mesh->lbox));
11989371c9d4SSatish Balay     }
1199cafe43deSMatthew G. Knepley     /* Designate the local box for each point */
1200cafe43deSMatthew G. Knepley     /* Send points to correct process */
1201cafe43deSMatthew G. Knepley     /* Search cells that lie in each subbox */
1202cafe43deSMatthew G. Knepley     /*   Should we bin points before doing search? */
12039566063dSJacob Faibussowitsch     PetscCall(ISGetIndices(mesh->lbox->cells, &boxCells));
1204953fc75cSMatthew G. Knepley   }
12053a93e3b7SToby Isaac   for (p = 0, numFound = 0; p < numPoints; ++p) {
1206ccd2543fSMatthew G Knepley     const PetscScalar *point   = &a[p * bs];
1207e56f9228SJed Brown     PetscInt           dbin[3] = {-1, -1, -1}, bin, cell = -1, cellOffset;
12089cb35068SDave May     PetscBool          point_outside_domain = PETSC_FALSE;
1209ccd2543fSMatthew G Knepley 
12109cb35068SDave May     /* check bounding box of domain */
12119cb35068SDave May     for (d = 0; d < dim; d++) {
12129371c9d4SSatish Balay       if (PetscRealPart(point[d]) < gmin[d]) {
12139371c9d4SSatish Balay         point_outside_domain = PETSC_TRUE;
12149371c9d4SSatish Balay         break;
12159371c9d4SSatish Balay       }
12169371c9d4SSatish Balay       if (PetscRealPart(point[d]) > gmax[d]) {
12179371c9d4SSatish Balay         point_outside_domain = PETSC_TRUE;
12189371c9d4SSatish Balay         break;
12199371c9d4SSatish Balay       }
12209cb35068SDave May     }
12219cb35068SDave May     if (point_outside_domain) {
1222e9b685f5SMatthew G. Knepley       cells[p].rank  = 0;
1223e9b685f5SMatthew G. Knepley       cells[p].index = DMLOCATEPOINT_POINT_NOT_FOUND;
12249cb35068SDave May       terminating_query_type[0]++;
12259cb35068SDave May       continue;
12269cb35068SDave May     }
1227ccd2543fSMatthew G Knepley 
1228af74b616SDave May     /* check initial values in cells[].index - abort early if found */
1229af74b616SDave May     if (cells[p].index != DMLOCATEPOINT_POINT_NOT_FOUND) {
1230af74b616SDave May       c              = cells[p].index;
12313a93e3b7SToby Isaac       cells[p].index = DMLOCATEPOINT_POINT_NOT_FOUND;
12329566063dSJacob Faibussowitsch       PetscCall(DMPlexLocatePoint_Internal(dm, dim, point, c, &cell));
1233af74b616SDave May       if (cell >= 0) {
1234af74b616SDave May         cells[p].rank  = 0;
1235af74b616SDave May         cells[p].index = cell;
1236af74b616SDave May         numFound++;
1237af74b616SDave May       }
1238af74b616SDave May     }
12399cb35068SDave May     if (cells[p].index != DMLOCATEPOINT_POINT_NOT_FOUND) {
12409cb35068SDave May       terminating_query_type[1]++;
12419cb35068SDave May       continue;
12429cb35068SDave May     }
1243af74b616SDave May 
1244953fc75cSMatthew G. Knepley     if (hash) {
1245af74b616SDave May       PetscBool found_box;
1246af74b616SDave May 
12476363a54bSMatthew 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]), dim > 2 ? (double)PetscRealPart(point[2]) : 0.));
1248af74b616SDave May       /* allow for case that point is outside box - abort early */
1249f5867de0SMatthew G. Knepley       PetscCall(PetscGridHashGetEnclosingBoxQuery(mesh->lbox, mesh->lbox->cellSection, 1, point, dbin, &bin, &found_box));
1250af74b616SDave May       if (found_box) {
12516363a54bSMatthew 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], dim > 2 ? dbin[2] : 0));
1252cafe43deSMatthew G. Knepley         /* TODO Lay an interface over this so we can switch between Section (dense) and Label (sparse) */
12539566063dSJacob Faibussowitsch         PetscCall(PetscSectionGetDof(mesh->lbox->cellSection, bin, &numCells));
12549566063dSJacob Faibussowitsch         PetscCall(PetscSectionGetOffset(mesh->lbox->cellSection, bin, &cellOffset));
1255cafe43deSMatthew G. Knepley         for (c = cellOffset; c < cellOffset + numCells; ++c) {
12566363a54bSMatthew G. Knepley           if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, "[%d]    Checking for point in cell %" PetscInt_FMT "\n", rank, boxCells[c]));
12579566063dSJacob Faibussowitsch           PetscCall(DMPlexLocatePoint_Internal(dm, dim, point, boxCells[c], &cell));
12583a93e3b7SToby Isaac           if (cell >= 0) {
12596363a54bSMatthew G. Knepley             if (debug) PetscCall(PetscPrintf(PETSC_COMM_SELF, "[%d]      FOUND in cell %" PetscInt_FMT "\n", rank, cell));
12603a93e3b7SToby Isaac             cells[p].rank  = 0;
12613a93e3b7SToby Isaac             cells[p].index = cell;
12623a93e3b7SToby Isaac             numFound++;
12639cb35068SDave May             terminating_query_type[2]++;
12643a93e3b7SToby Isaac             break;
1265ccd2543fSMatthew G Knepley           }
12663a93e3b7SToby Isaac         }
1267af74b616SDave May       }
1268953fc75cSMatthew G. Knepley     } else {
1269953fc75cSMatthew G. Knepley       for (c = cStart; c < cEnd; ++c) {
1270d8206211SMatthew G. Knepley         PetscInt idx;
1271d8206211SMatthew G. Knepley 
1272d8206211SMatthew G. Knepley         PetscCall(PetscFindInt(c, Nl, leaves, &idx));
1273d8206211SMatthew G. Knepley         if (idx >= 0) continue;
12749566063dSJacob Faibussowitsch         PetscCall(DMPlexLocatePoint_Internal(dm, dim, point, c, &cell));
12753a93e3b7SToby Isaac         if (cell >= 0) {
12763a93e3b7SToby Isaac           cells[p].rank  = 0;
12773a93e3b7SToby Isaac           cells[p].index = cell;
12783a93e3b7SToby Isaac           numFound++;
12799cb35068SDave May           terminating_query_type[2]++;
12803a93e3b7SToby Isaac           break;
1281953fc75cSMatthew G. Knepley         }
1282953fc75cSMatthew G. Knepley       }
12833a93e3b7SToby Isaac     }
1284ccd2543fSMatthew G Knepley   }
12859566063dSJacob Faibussowitsch   if (hash) PetscCall(ISRestoreIndices(mesh->lbox->cells, &boxCells));
128662a38674SMatthew G. Knepley   if (ltype == DM_POINTLOCATION_NEAREST && hash && numFound < numPoints) {
128762a38674SMatthew G. Knepley     for (p = 0; p < numPoints; p++) {
128862a38674SMatthew G. Knepley       const PetscScalar *point     = &a[p * bs];
1289d52e4eadSJose 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;
1290d92c4b9fSToby Isaac       PetscInt           dbin[3] = {-1, -1, -1}, bin, cellOffset, d, bestc = -1;
129162a38674SMatthew G. Knepley 
1292e9b685f5SMatthew G. Knepley       if (cells[p].index < 0) {
12939566063dSJacob Faibussowitsch         PetscCall(PetscGridHashGetEnclosingBox(mesh->lbox, 1, point, dbin, &bin));
12949566063dSJacob Faibussowitsch         PetscCall(PetscSectionGetDof(mesh->lbox->cellSection, bin, &numCells));
12959566063dSJacob Faibussowitsch         PetscCall(PetscSectionGetOffset(mesh->lbox->cellSection, bin, &cellOffset));
129662a38674SMatthew G. Knepley         for (c = cellOffset; c < cellOffset + numCells; ++c) {
12979566063dSJacob Faibussowitsch           PetscCall(DMPlexClosestPoint_Internal(dm, dim, point, boxCells[c], cpoint));
1298b716b415SMatthew G. Knepley           for (d = 0; d < dim; ++d) diff[d] = cpoint[d] - PetscRealPart(point[d]);
129962a38674SMatthew G. Knepley           dist = DMPlex_NormD_Internal(dim, diff);
130062a38674SMatthew G. Knepley           if (dist < distMax) {
1301d92c4b9fSToby Isaac             for (d = 0; d < dim; ++d) best[d] = cpoint[d];
1302d92c4b9fSToby Isaac             bestc   = boxCells[c];
130362a38674SMatthew G. Knepley             distMax = dist;
130462a38674SMatthew G. Knepley           }
130562a38674SMatthew G. Knepley         }
1306d92c4b9fSToby Isaac         if (distMax < PETSC_MAX_REAL) {
1307d92c4b9fSToby Isaac           ++numFound;
1308d92c4b9fSToby Isaac           cells[p].rank  = 0;
1309d92c4b9fSToby Isaac           cells[p].index = bestc;
1310d92c4b9fSToby Isaac           for (d = 0; d < dim; ++d) a[p * bs + d] = best[d];
1311d92c4b9fSToby Isaac         }
131262a38674SMatthew G. Knepley       }
131362a38674SMatthew G. Knepley     }
131462a38674SMatthew G. Knepley   }
131562a38674SMatthew G. Knepley   /* This code is only be relevant when interfaced to parallel point location */
1316cafe43deSMatthew G. Knepley   /* Check for highest numbered proc that claims a point (do we care?) */
13172d1fa6caSMatthew G. Knepley   if (ltype == DM_POINTLOCATION_REMOVE && numFound < numPoints) {
13189566063dSJacob Faibussowitsch     PetscCall(PetscMalloc1(numFound, &found));
13193a93e3b7SToby Isaac     for (p = 0, numFound = 0; p < numPoints; p++) {
13203a93e3b7SToby Isaac       if (cells[p].rank >= 0 && cells[p].index >= 0) {
1321ad540459SPierre Jolivet         if (numFound < p) cells[numFound] = cells[p];
13223a93e3b7SToby Isaac         found[numFound++] = p;
13233a93e3b7SToby Isaac       }
13243a93e3b7SToby Isaac     }
13253a93e3b7SToby Isaac   }
13269566063dSJacob Faibussowitsch   PetscCall(VecRestoreArray(v, &a));
132748a46eb9SPierre Jolivet   if (!reuse) PetscCall(PetscSFSetGraph(cellSF, cEnd - cStart, numFound, found, PETSC_OWN_POINTER, cells, PETSC_OWN_POINTER));
13289566063dSJacob Faibussowitsch   PetscCall(PetscTime(&t1));
13299cb35068SDave May   if (hash) {
133063a3b9bcSJacob 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]));
13319cb35068SDave May   } else {
133263a3b9bcSJacob 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]));
13339cb35068SDave May   }
133463a3b9bcSJacob Faibussowitsch   PetscCall(PetscInfo(dm, "[DMLocatePoints_Plex] npoints %" PetscInt_FMT " : time(rank0) %1.2e (sec): points/sec %1.4e\n", numPoints, t1 - t0, (double)((double)numPoints / (t1 - t0))));
13359566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(DMPLEX_LocatePoints, 0, 0, 0, 0));
13363ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1337ccd2543fSMatthew G Knepley }
1338ccd2543fSMatthew G Knepley 
1339741bfc07SMatthew G. Knepley /*@C
1340741bfc07SMatthew G. Knepley   DMPlexComputeProjection2Dto1D - Rewrite coordinates to be the 1D projection of the 2D coordinates
1341741bfc07SMatthew G. Knepley 
134220f4b53cSBarry Smith   Not Collective
1343741bfc07SMatthew G. Knepley 
13446b867d5aSJose E. Roman   Input/Output Parameter:
13456b867d5aSJose E. Roman . coords - The coordinates of a segment, on output the new y-coordinate, and 0 for x
1346741bfc07SMatthew G. Knepley 
13476b867d5aSJose E. Roman   Output Parameter:
13486b867d5aSJose E. Roman . R - The rotation which accomplishes the projection
1349741bfc07SMatthew G. Knepley 
1350741bfc07SMatthew G. Knepley   Level: developer
1351741bfc07SMatthew G. Knepley 
13522fe279fdSBarry Smith .seealso: `DMPLEX`, `DMPlexComputeProjection3Dto1D()`, `DMPlexComputeProjection3Dto2D()`
1353741bfc07SMatthew G. Knepley @*/
1354d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexComputeProjection2Dto1D(PetscScalar coords[], PetscReal R[])
1355d71ae5a4SJacob Faibussowitsch {
135617fe8556SMatthew G. Knepley   const PetscReal x = PetscRealPart(coords[2] - coords[0]);
135717fe8556SMatthew G. Knepley   const PetscReal y = PetscRealPart(coords[3] - coords[1]);
13588b49ba18SBarry Smith   const PetscReal r = PetscSqrtReal(x * x + y * y), c = x / r, s = y / r;
135917fe8556SMatthew G. Knepley 
136017fe8556SMatthew G. Knepley   PetscFunctionBegin;
13619371c9d4SSatish Balay   R[0]      = c;
13629371c9d4SSatish Balay   R[1]      = -s;
13639371c9d4SSatish Balay   R[2]      = s;
13649371c9d4SSatish Balay   R[3]      = c;
136517fe8556SMatthew G. Knepley   coords[0] = 0.0;
13667f07f362SMatthew G. Knepley   coords[1] = r;
13673ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
136817fe8556SMatthew G. Knepley }
136917fe8556SMatthew G. Knepley 
1370741bfc07SMatthew G. Knepley /*@C
1371741bfc07SMatthew G. Knepley   DMPlexComputeProjection3Dto1D - Rewrite coordinates to be the 1D projection of the 3D coordinates
137228dbe442SToby Isaac 
137320f4b53cSBarry Smith   Not Collective
137428dbe442SToby Isaac 
13756b867d5aSJose E. Roman   Input/Output Parameter:
13766b867d5aSJose E. Roman . coords - The coordinates of a segment; on output, the new y-coordinate, and 0 for x and z
1377741bfc07SMatthew G. Knepley 
13786b867d5aSJose E. Roman   Output Parameter:
13796b867d5aSJose E. Roman . R - The rotation which accomplishes the projection
1380741bfc07SMatthew G. Knepley 
1381741bfc07SMatthew G. Knepley   Level: developer
1382741bfc07SMatthew G. Knepley 
1383*1d27aa22SBarry Smith   Note:
1384*1d27aa22SBarry Smith   This uses the basis completion described by Frisvad {cite}`frisvad2012building`
1385*1d27aa22SBarry Smith 
13862fe279fdSBarry Smith .seealso: `DMPLEX`, `DMPlexComputeProjection2Dto1D()`, `DMPlexComputeProjection3Dto2D()`
1387741bfc07SMatthew G. Knepley @*/
1388d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexComputeProjection3Dto1D(PetscScalar coords[], PetscReal R[])
1389d71ae5a4SJacob Faibussowitsch {
139028dbe442SToby Isaac   PetscReal x    = PetscRealPart(coords[3] - coords[0]);
139128dbe442SToby Isaac   PetscReal y    = PetscRealPart(coords[4] - coords[1]);
139228dbe442SToby Isaac   PetscReal z    = PetscRealPart(coords[5] - coords[2]);
139328dbe442SToby Isaac   PetscReal r    = PetscSqrtReal(x * x + y * y + z * z);
139428dbe442SToby Isaac   PetscReal rinv = 1. / r;
139528dbe442SToby Isaac   PetscFunctionBegin;
139628dbe442SToby Isaac 
13979371c9d4SSatish Balay   x *= rinv;
13989371c9d4SSatish Balay   y *= rinv;
13999371c9d4SSatish Balay   z *= rinv;
140028dbe442SToby Isaac   if (x > 0.) {
140128dbe442SToby Isaac     PetscReal inv1pX = 1. / (1. + x);
140228dbe442SToby Isaac 
14039371c9d4SSatish Balay     R[0] = x;
14049371c9d4SSatish Balay     R[1] = -y;
14059371c9d4SSatish Balay     R[2] = -z;
14069371c9d4SSatish Balay     R[3] = y;
14079371c9d4SSatish Balay     R[4] = 1. - y * y * inv1pX;
14089371c9d4SSatish Balay     R[5] = -y * z * inv1pX;
14099371c9d4SSatish Balay     R[6] = z;
14109371c9d4SSatish Balay     R[7] = -y * z * inv1pX;
14119371c9d4SSatish Balay     R[8] = 1. - z * z * inv1pX;
14129371c9d4SSatish Balay   } else {
141328dbe442SToby Isaac     PetscReal inv1mX = 1. / (1. - x);
141428dbe442SToby Isaac 
14159371c9d4SSatish Balay     R[0] = x;
14169371c9d4SSatish Balay     R[1] = z;
14179371c9d4SSatish Balay     R[2] = y;
14189371c9d4SSatish Balay     R[3] = y;
14199371c9d4SSatish Balay     R[4] = -y * z * inv1mX;
14209371c9d4SSatish Balay     R[5] = 1. - y * y * inv1mX;
14219371c9d4SSatish Balay     R[6] = z;
14229371c9d4SSatish Balay     R[7] = 1. - z * z * inv1mX;
14239371c9d4SSatish Balay     R[8] = -y * z * inv1mX;
142428dbe442SToby Isaac   }
142528dbe442SToby Isaac   coords[0] = 0.0;
142628dbe442SToby Isaac   coords[1] = r;
14273ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
142828dbe442SToby Isaac }
142928dbe442SToby Isaac 
1430741bfc07SMatthew G. Knepley /*@
1431c871b86eSJed Brown   DMPlexComputeProjection3Dto2D - Rewrite coordinates of 3 or more coplanar 3D points to a common 2D basis for the
1432c871b86eSJed Brown   plane.  The normal is defined by positive orientation of the first 3 points.
1433741bfc07SMatthew G. Knepley 
143420f4b53cSBarry Smith   Not Collective
1435741bfc07SMatthew G. Knepley 
1436741bfc07SMatthew G. Knepley   Input Parameter:
14376b867d5aSJose E. Roman . coordSize - Length of coordinate array (3x number of points); must be at least 9 (3 points)
1438741bfc07SMatthew G. Knepley 
14396b867d5aSJose E. Roman   Input/Output Parameter:
14406b867d5aSJose E. Roman . coords - The interlaced coordinates of each coplanar 3D point; on output the first
14416b867d5aSJose E. Roman            2*coordSize/3 entries contain interlaced 2D points, with the rest undefined
14426b867d5aSJose E. Roman 
14436b867d5aSJose E. Roman   Output Parameter:
14446b867d5aSJose 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.
1445741bfc07SMatthew G. Knepley 
1446741bfc07SMatthew G. Knepley   Level: developer
1447741bfc07SMatthew G. Knepley 
14482fe279fdSBarry Smith .seealso: `DMPLEX`, `DMPlexComputeProjection2Dto1D()`, `DMPlexComputeProjection3Dto1D()`
1449741bfc07SMatthew G. Knepley @*/
1450d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexComputeProjection3Dto2D(PetscInt coordSize, PetscScalar coords[], PetscReal R[])
1451d71ae5a4SJacob Faibussowitsch {
1452c871b86eSJed Brown   PetscReal      x1[3], x2[3], n[3], c[3], norm;
1453ccd2543fSMatthew G Knepley   const PetscInt dim = 3;
1454c871b86eSJed Brown   PetscInt       d, p;
1455ccd2543fSMatthew G Knepley 
1456ccd2543fSMatthew G Knepley   PetscFunctionBegin;
1457ccd2543fSMatthew G Knepley   /* 0) Calculate normal vector */
1458ccd2543fSMatthew G Knepley   for (d = 0; d < dim; ++d) {
14591ee9d5ecSMatthew G. Knepley     x1[d] = PetscRealPart(coords[1 * dim + d] - coords[0 * dim + d]);
14601ee9d5ecSMatthew G. Knepley     x2[d] = PetscRealPart(coords[2 * dim + d] - coords[0 * dim + d]);
1461ccd2543fSMatthew G Knepley   }
1462c871b86eSJed Brown   // n = x1 \otimes x2
1463ccd2543fSMatthew G Knepley   n[0] = x1[1] * x2[2] - x1[2] * x2[1];
1464ccd2543fSMatthew G Knepley   n[1] = x1[2] * x2[0] - x1[0] * x2[2];
1465ccd2543fSMatthew G Knepley   n[2] = x1[0] * x2[1] - x1[1] * x2[0];
14668b49ba18SBarry Smith   norm = PetscSqrtReal(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]);
1467c871b86eSJed Brown   for (d = 0; d < dim; d++) n[d] /= norm;
1468c871b86eSJed Brown   norm = PetscSqrtReal(x1[0] * x1[0] + x1[1] * x1[1] + x1[2] * x1[2]);
1469c871b86eSJed Brown   for (d = 0; d < dim; d++) x1[d] /= norm;
1470c871b86eSJed Brown   // x2 = n \otimes x1
1471c871b86eSJed Brown   x2[0] = n[1] * x1[2] - n[2] * x1[1];
1472c871b86eSJed Brown   x2[1] = n[2] * x1[0] - n[0] * x1[2];
1473c871b86eSJed Brown   x2[2] = n[0] * x1[1] - n[1] * x1[0];
1474c871b86eSJed Brown   for (d = 0; d < dim; d++) {
1475c871b86eSJed Brown     R[d * dim + 0] = x1[d];
1476c871b86eSJed Brown     R[d * dim + 1] = x2[d];
1477c871b86eSJed Brown     R[d * dim + 2] = n[d];
1478c871b86eSJed Brown     c[d]           = PetscRealPart(coords[0 * dim + d]);
147973868372SMatthew G. Knepley   }
1480c871b86eSJed Brown   for (p = 0; p < coordSize / dim; p++) {
1481c871b86eSJed Brown     PetscReal y[3];
1482c871b86eSJed Brown     for (d = 0; d < dim; d++) y[d] = PetscRealPart(coords[p * dim + d]) - c[d];
1483c871b86eSJed 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];
14847f07f362SMatthew G. Knepley   }
14853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1486ccd2543fSMatthew G Knepley }
1487ccd2543fSMatthew G Knepley 
1488d71ae5a4SJacob Faibussowitsch PETSC_UNUSED static inline void Volume_Triangle_Internal(PetscReal *vol, PetscReal coords[])
1489d71ae5a4SJacob Faibussowitsch {
1490834e62ceSMatthew G. Knepley   /* Signed volume is 1/2 the determinant
1491834e62ceSMatthew G. Knepley 
1492834e62ceSMatthew G. Knepley    |  1  1  1 |
1493834e62ceSMatthew G. Knepley    | x0 x1 x2 |
1494834e62ceSMatthew G. Knepley    | y0 y1 y2 |
1495834e62ceSMatthew G. Knepley 
1496834e62ceSMatthew G. Knepley      but if x0,y0 is the origin, we have
1497834e62ceSMatthew G. Knepley 
1498834e62ceSMatthew G. Knepley    | x1 x2 |
1499834e62ceSMatthew G. Knepley    | y1 y2 |
1500834e62ceSMatthew G. Knepley   */
1501834e62ceSMatthew G. Knepley   const PetscReal x1 = coords[2] - coords[0], y1 = coords[3] - coords[1];
1502834e62ceSMatthew G. Knepley   const PetscReal x2 = coords[4] - coords[0], y2 = coords[5] - coords[1];
1503834e62ceSMatthew G. Knepley   PetscReal       M[4], detM;
15049371c9d4SSatish Balay   M[0] = x1;
15059371c9d4SSatish Balay   M[1] = x2;
15069371c9d4SSatish Balay   M[2] = y1;
15079371c9d4SSatish Balay   M[3] = y2;
1508923591dfSMatthew G. Knepley   DMPlex_Det2D_Internal(&detM, M);
1509834e62ceSMatthew G. Knepley   *vol = 0.5 * detM;
15103bc0b13bSBarry Smith   (void)PetscLogFlops(5.0);
1511834e62ceSMatthew G. Knepley }
1512834e62ceSMatthew G. Knepley 
1513d71ae5a4SJacob Faibussowitsch PETSC_UNUSED static inline void Volume_Tetrahedron_Internal(PetscReal *vol, PetscReal coords[])
1514d71ae5a4SJacob Faibussowitsch {
1515834e62ceSMatthew G. Knepley   /* Signed volume is 1/6th of the determinant
1516834e62ceSMatthew G. Knepley 
1517834e62ceSMatthew G. Knepley    |  1  1  1  1 |
1518834e62ceSMatthew G. Knepley    | x0 x1 x2 x3 |
1519834e62ceSMatthew G. Knepley    | y0 y1 y2 y3 |
1520834e62ceSMatthew G. Knepley    | z0 z1 z2 z3 |
1521834e62ceSMatthew G. Knepley 
1522834e62ceSMatthew G. Knepley      but if x0,y0,z0 is the origin, we have
1523834e62ceSMatthew G. Knepley 
1524834e62ceSMatthew G. Knepley    | x1 x2 x3 |
1525834e62ceSMatthew G. Knepley    | y1 y2 y3 |
1526834e62ceSMatthew G. Knepley    | z1 z2 z3 |
1527834e62ceSMatthew G. Knepley   */
1528834e62ceSMatthew G. Knepley   const PetscReal x1 = coords[3] - coords[0], y1 = coords[4] - coords[1], z1 = coords[5] - coords[2];
1529834e62ceSMatthew G. Knepley   const PetscReal x2 = coords[6] - coords[0], y2 = coords[7] - coords[1], z2 = coords[8] - coords[2];
1530834e62ceSMatthew G. Knepley   const PetscReal x3 = coords[9] - coords[0], y3 = coords[10] - coords[1], z3 = coords[11] - coords[2];
15310a3da2c2SToby Isaac   const PetscReal onesixth = ((PetscReal)1. / (PetscReal)6.);
1532834e62ceSMatthew G. Knepley   PetscReal       M[9], detM;
15339371c9d4SSatish Balay   M[0] = x1;
15349371c9d4SSatish Balay   M[1] = x2;
15359371c9d4SSatish Balay   M[2] = x3;
15369371c9d4SSatish Balay   M[3] = y1;
15379371c9d4SSatish Balay   M[4] = y2;
15389371c9d4SSatish Balay   M[5] = y3;
15399371c9d4SSatish Balay   M[6] = z1;
15409371c9d4SSatish Balay   M[7] = z2;
15419371c9d4SSatish Balay   M[8] = z3;
1542923591dfSMatthew G. Knepley   DMPlex_Det3D_Internal(&detM, M);
15430a3da2c2SToby Isaac   *vol = -onesixth * detM;
15443bc0b13bSBarry Smith   (void)PetscLogFlops(10.0);
1545834e62ceSMatthew G. Knepley }
1546834e62ceSMatthew G. Knepley 
1547d71ae5a4SJacob Faibussowitsch static inline void Volume_Tetrahedron_Origin_Internal(PetscReal *vol, PetscReal coords[])
1548d71ae5a4SJacob Faibussowitsch {
15490a3da2c2SToby Isaac   const PetscReal onesixth = ((PetscReal)1. / (PetscReal)6.);
1550923591dfSMatthew G. Knepley   DMPlex_Det3D_Internal(vol, coords);
15510a3da2c2SToby Isaac   *vol *= -onesixth;
15520ec8681fSMatthew G. Knepley }
15530ec8681fSMatthew G. Knepley 
1554d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputePointGeometry_Internal(DM dm, PetscInt e, PetscReal v0[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
1555d71ae5a4SJacob Faibussowitsch {
1556cb92db44SToby Isaac   PetscSection       coordSection;
1557cb92db44SToby Isaac   Vec                coordinates;
1558cb92db44SToby Isaac   const PetscScalar *coords;
1559cb92db44SToby Isaac   PetscInt           dim, d, off;
1560cb92db44SToby Isaac 
1561cb92db44SToby Isaac   PetscFunctionBegin;
15629566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
15639566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateSection(dm, &coordSection));
15649566063dSJacob Faibussowitsch   PetscCall(PetscSectionGetDof(coordSection, e, &dim));
15653ba16761SJacob Faibussowitsch   if (!dim) PetscFunctionReturn(PETSC_SUCCESS);
15669566063dSJacob Faibussowitsch   PetscCall(PetscSectionGetOffset(coordSection, e, &off));
15679566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(coordinates, &coords));
15689371c9d4SSatish Balay   if (v0) {
15699371c9d4SSatish Balay     for (d = 0; d < dim; d++) v0[d] = PetscRealPart(coords[off + d]);
15709371c9d4SSatish Balay   }
15719566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(coordinates, &coords));
1572cb92db44SToby Isaac   *detJ = 1.;
1573cb92db44SToby Isaac   if (J) {
1574cb92db44SToby Isaac     for (d = 0; d < dim * dim; d++) J[d] = 0.;
1575cb92db44SToby Isaac     for (d = 0; d < dim; d++) J[d * dim + d] = 1.;
1576cb92db44SToby Isaac     if (invJ) {
1577cb92db44SToby Isaac       for (d = 0; d < dim * dim; d++) invJ[d] = 0.;
1578cb92db44SToby Isaac       for (d = 0; d < dim; d++) invJ[d * dim + d] = 1.;
1579cb92db44SToby Isaac     }
1580cb92db44SToby Isaac   }
15813ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1582cb92db44SToby Isaac }
1583cb92db44SToby Isaac 
15846858538eSMatthew G. Knepley /*@C
15856858538eSMatthew G. Knepley   DMPlexGetCellCoordinates - Get coordinates for a cell, taking into account periodicity
15866858538eSMatthew G. Knepley 
158720f4b53cSBarry Smith   Not Collective
15886858538eSMatthew G. Knepley 
15896858538eSMatthew G. Knepley   Input Parameters:
159020f4b53cSBarry Smith + dm   - The `DMPLEX`
15916858538eSMatthew G. Knepley - cell - The cell number
15926858538eSMatthew G. Knepley 
15936858538eSMatthew G. Knepley   Output Parameters:
15946858538eSMatthew G. Knepley + isDG   - Using cellwise coordinates
15956858538eSMatthew G. Knepley . Nc     - The number of coordinates
15966858538eSMatthew G. Knepley . array  - The coordinate array
15976858538eSMatthew G. Knepley - coords - The cell coordinates
15986858538eSMatthew G. Knepley 
15996858538eSMatthew G. Knepley   Level: developer
16006858538eSMatthew G. Knepley 
160120f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexRestoreCellCoordinates()`, `DMGetCoordinatesLocal()`, `DMGetCellCoordinatesLocal()`
16026858538eSMatthew G. Knepley @*/
1603d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexGetCellCoordinates(DM dm, PetscInt cell, PetscBool *isDG, PetscInt *Nc, const PetscScalar *array[], PetscScalar *coords[])
1604d71ae5a4SJacob Faibussowitsch {
16056858538eSMatthew G. Knepley   DM                 cdm;
16066858538eSMatthew G. Knepley   Vec                coordinates;
16076858538eSMatthew G. Knepley   PetscSection       cs;
16086858538eSMatthew G. Knepley   const PetscScalar *ccoords;
16096858538eSMatthew G. Knepley   PetscInt           pStart, pEnd;
16106858538eSMatthew G. Knepley 
16116858538eSMatthew G. Knepley   PetscFunctionBeginHot;
16126858538eSMatthew G. Knepley   *isDG   = PETSC_FALSE;
16136858538eSMatthew G. Knepley   *Nc     = 0;
16146858538eSMatthew G. Knepley   *array  = NULL;
16156858538eSMatthew G. Knepley   *coords = NULL;
16166858538eSMatthew G. Knepley   /* Check for cellwise coordinates */
16176858538eSMatthew G. Knepley   PetscCall(DMGetCellCoordinateSection(dm, &cs));
16186858538eSMatthew G. Knepley   if (!cs) goto cg;
16196858538eSMatthew G. Knepley   /* Check that the cell exists in the cellwise section */
16206858538eSMatthew G. Knepley   PetscCall(PetscSectionGetChart(cs, &pStart, &pEnd));
16216858538eSMatthew G. Knepley   if (cell < pStart || cell >= pEnd) goto cg;
16226858538eSMatthew G. Knepley   /* Check for cellwise coordinates for this cell */
16236858538eSMatthew G. Knepley   PetscCall(PetscSectionGetDof(cs, cell, Nc));
16246858538eSMatthew G. Knepley   if (!*Nc) goto cg;
16256858538eSMatthew G. Knepley   /* Check for cellwise coordinates */
16266858538eSMatthew G. Knepley   PetscCall(DMGetCellCoordinatesLocalNoncollective(dm, &coordinates));
16276858538eSMatthew G. Knepley   if (!coordinates) goto cg;
16286858538eSMatthew G. Knepley   /* Get cellwise coordinates */
16296858538eSMatthew G. Knepley   PetscCall(DMGetCellCoordinateDM(dm, &cdm));
16306858538eSMatthew G. Knepley   PetscCall(VecGetArrayRead(coordinates, array));
16316858538eSMatthew G. Knepley   PetscCall(DMPlexPointLocalRead(cdm, cell, *array, &ccoords));
16326858538eSMatthew G. Knepley   PetscCall(DMGetWorkArray(cdm, *Nc, MPIU_SCALAR, coords));
16336858538eSMatthew G. Knepley   PetscCall(PetscArraycpy(*coords, ccoords, *Nc));
16346858538eSMatthew G. Knepley   PetscCall(VecRestoreArrayRead(coordinates, array));
16356858538eSMatthew G. Knepley   *isDG = PETSC_TRUE;
16363ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
16376858538eSMatthew G. Knepley cg:
16386858538eSMatthew G. Knepley   /* Use continuous coordinates */
16396858538eSMatthew G. Knepley   PetscCall(DMGetCoordinateDM(dm, &cdm));
16406858538eSMatthew G. Knepley   PetscCall(DMGetCoordinateSection(dm, &cs));
16416858538eSMatthew G. Knepley   PetscCall(DMGetCoordinatesLocalNoncollective(dm, &coordinates));
1642e8e188d2SZach Atkins   PetscCall(DMPlexVecGetOrientedClosure_Internal(cdm, cs, PETSC_FALSE, coordinates, cell, 0, Nc, coords));
16433ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
16446858538eSMatthew G. Knepley }
16456858538eSMatthew G. Knepley 
16466858538eSMatthew G. Knepley /*@C
16476858538eSMatthew G. Knepley   DMPlexRestoreCellCoordinates - Get coordinates for a cell, taking into account periodicity
16486858538eSMatthew G. Knepley 
164920f4b53cSBarry Smith   Not Collective
16506858538eSMatthew G. Knepley 
16516858538eSMatthew G. Knepley   Input Parameters:
165220f4b53cSBarry Smith + dm   - The `DMPLEX`
16536858538eSMatthew G. Knepley - cell - The cell number
16546858538eSMatthew G. Knepley 
16556858538eSMatthew G. Knepley   Output Parameters:
16566858538eSMatthew G. Knepley + isDG   - Using cellwise coordinates
16576858538eSMatthew G. Knepley . Nc     - The number of coordinates
16586858538eSMatthew G. Knepley . array  - The coordinate array
16596858538eSMatthew G. Knepley - coords - The cell coordinates
16606858538eSMatthew G. Knepley 
16616858538eSMatthew G. Knepley   Level: developer
16626858538eSMatthew G. Knepley 
166320f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexGetCellCoordinates()`, `DMGetCoordinatesLocal()`, `DMGetCellCoordinatesLocal()`
16646858538eSMatthew G. Knepley @*/
1665d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexRestoreCellCoordinates(DM dm, PetscInt cell, PetscBool *isDG, PetscInt *Nc, const PetscScalar *array[], PetscScalar *coords[])
1666d71ae5a4SJacob Faibussowitsch {
16676858538eSMatthew G. Knepley   DM           cdm;
16686858538eSMatthew G. Knepley   PetscSection cs;
16696858538eSMatthew G. Knepley   Vec          coordinates;
16706858538eSMatthew G. Knepley 
16716858538eSMatthew G. Knepley   PetscFunctionBeginHot;
16726858538eSMatthew G. Knepley   if (*isDG) {
16736858538eSMatthew G. Knepley     PetscCall(DMGetCellCoordinateDM(dm, &cdm));
16746858538eSMatthew G. Knepley     PetscCall(DMRestoreWorkArray(cdm, *Nc, MPIU_SCALAR, coords));
16756858538eSMatthew G. Knepley   } else {
16766858538eSMatthew G. Knepley     PetscCall(DMGetCoordinateDM(dm, &cdm));
16776858538eSMatthew G. Knepley     PetscCall(DMGetCoordinateSection(dm, &cs));
16786858538eSMatthew G. Knepley     PetscCall(DMGetCoordinatesLocalNoncollective(dm, &coordinates));
16796858538eSMatthew G. Knepley     PetscCall(DMPlexVecRestoreClosure(cdm, cs, coordinates, cell, Nc, (PetscScalar **)coords));
16806858538eSMatthew G. Knepley   }
16813ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
16826858538eSMatthew G. Knepley }
16836858538eSMatthew G. Knepley 
1684d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeLineGeometry_Internal(DM dm, PetscInt e, PetscReal v0[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
1685d71ae5a4SJacob Faibussowitsch {
16866858538eSMatthew G. Knepley   const PetscScalar *array;
1687a1e44745SMatthew G. Knepley   PetscScalar       *coords = NULL;
16886858538eSMatthew G. Knepley   PetscInt           numCoords, d;
16896858538eSMatthew G. Knepley   PetscBool          isDG;
169017fe8556SMatthew G. Knepley 
169117fe8556SMatthew G. Knepley   PetscFunctionBegin;
16926858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
169308401ef6SPierre Jolivet   PetscCheck(!invJ || J, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "In order to compute invJ, J must not be NULL");
16947f07f362SMatthew G. Knepley   *detJ = 0.0;
169528dbe442SToby Isaac   if (numCoords == 6) {
169628dbe442SToby Isaac     const PetscInt dim = 3;
169728dbe442SToby Isaac     PetscReal      R[9], J0;
169828dbe442SToby Isaac 
16999371c9d4SSatish Balay     if (v0) {
17009371c9d4SSatish Balay       for (d = 0; d < dim; d++) v0[d] = PetscRealPart(coords[d]);
17019371c9d4SSatish Balay     }
17029566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeProjection3Dto1D(coords, R));
170328dbe442SToby Isaac     if (J) {
170428dbe442SToby Isaac       J0   = 0.5 * PetscRealPart(coords[1]);
17059371c9d4SSatish Balay       J[0] = R[0] * J0;
17069371c9d4SSatish Balay       J[1] = R[1];
17079371c9d4SSatish Balay       J[2] = R[2];
17089371c9d4SSatish Balay       J[3] = R[3] * J0;
17099371c9d4SSatish Balay       J[4] = R[4];
17109371c9d4SSatish Balay       J[5] = R[5];
17119371c9d4SSatish Balay       J[6] = R[6] * J0;
17129371c9d4SSatish Balay       J[7] = R[7];
17139371c9d4SSatish Balay       J[8] = R[8];
171428dbe442SToby Isaac       DMPlex_Det3D_Internal(detJ, J);
17152b6f951bSStefano Zampini       if (invJ) DMPlex_Invert3D_Internal(invJ, J, *detJ);
1716adac9986SMatthew G. Knepley     }
171728dbe442SToby Isaac   } else if (numCoords == 4) {
17187f07f362SMatthew G. Knepley     const PetscInt dim = 2;
17197f07f362SMatthew G. Knepley     PetscReal      R[4], J0;
17207f07f362SMatthew G. Knepley 
17219371c9d4SSatish Balay     if (v0) {
17229371c9d4SSatish Balay       for (d = 0; d < dim; d++) v0[d] = PetscRealPart(coords[d]);
17239371c9d4SSatish Balay     }
17249566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeProjection2Dto1D(coords, R));
172517fe8556SMatthew G. Knepley     if (J) {
17267f07f362SMatthew G. Knepley       J0   = 0.5 * PetscRealPart(coords[1]);
17279371c9d4SSatish Balay       J[0] = R[0] * J0;
17289371c9d4SSatish Balay       J[1] = R[1];
17299371c9d4SSatish Balay       J[2] = R[2] * J0;
17309371c9d4SSatish Balay       J[3] = R[3];
1731923591dfSMatthew G. Knepley       DMPlex_Det2D_Internal(detJ, J);
1732ad540459SPierre Jolivet       if (invJ) DMPlex_Invert2D_Internal(invJ, J, *detJ);
1733adac9986SMatthew G. Knepley     }
17347f07f362SMatthew G. Knepley   } else if (numCoords == 2) {
17357f07f362SMatthew G. Knepley     const PetscInt dim = 1;
17367f07f362SMatthew G. Knepley 
17379371c9d4SSatish Balay     if (v0) {
17389371c9d4SSatish Balay       for (d = 0; d < dim; d++) v0[d] = PetscRealPart(coords[d]);
17399371c9d4SSatish Balay     }
17407f07f362SMatthew G. Knepley     if (J) {
17417f07f362SMatthew G. Knepley       J[0]  = 0.5 * (PetscRealPart(coords[1]) - PetscRealPart(coords[0]));
174217fe8556SMatthew G. Knepley       *detJ = J[0];
17439566063dSJacob Faibussowitsch       PetscCall(PetscLogFlops(2.0));
17449371c9d4SSatish Balay       if (invJ) {
17459371c9d4SSatish Balay         invJ[0] = 1.0 / J[0];
17469371c9d4SSatish Balay         PetscCall(PetscLogFlops(1.0));
17479371c9d4SSatish Balay       }
1748adac9986SMatthew G. Knepley     }
17496858538eSMatthew 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);
17506858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
17513ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
175217fe8556SMatthew G. Knepley }
175317fe8556SMatthew G. Knepley 
1754d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeTriangleGeometry_Internal(DM dm, PetscInt e, PetscReal v0[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
1755d71ae5a4SJacob Faibussowitsch {
17566858538eSMatthew G. Knepley   const PetscScalar *array;
1757a1e44745SMatthew G. Knepley   PetscScalar       *coords = NULL;
17586858538eSMatthew G. Knepley   PetscInt           numCoords, d;
17596858538eSMatthew G. Knepley   PetscBool          isDG;
1760ccd2543fSMatthew G Knepley 
1761ccd2543fSMatthew G Knepley   PetscFunctionBegin;
17626858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
17636858538eSMatthew G. Knepley   PetscCheck(!invJ || J, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "In order to compute invJ, J must not be NULL");
17647f07f362SMatthew G. Knepley   *detJ = 0.0;
1765ccd2543fSMatthew G Knepley   if (numCoords == 9) {
17667f07f362SMatthew G. Knepley     const PetscInt dim = 3;
17677f07f362SMatthew 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};
17687f07f362SMatthew G. Knepley 
17699371c9d4SSatish Balay     if (v0) {
17709371c9d4SSatish Balay       for (d = 0; d < dim; d++) v0[d] = PetscRealPart(coords[d]);
17719371c9d4SSatish Balay     }
17729566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeProjection3Dto2D(numCoords, coords, R));
17737f07f362SMatthew G. Knepley     if (J) {
1774b7ad821dSMatthew G. Knepley       const PetscInt pdim = 2;
1775b7ad821dSMatthew G. Knepley 
1776b7ad821dSMatthew G. Knepley       for (d = 0; d < pdim; d++) {
1777ad540459SPierre 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]));
17787f07f362SMatthew G. Knepley       }
17799566063dSJacob Faibussowitsch       PetscCall(PetscLogFlops(8.0));
1780923591dfSMatthew G. Knepley       DMPlex_Det3D_Internal(detJ, J0);
17817f07f362SMatthew G. Knepley       for (d = 0; d < dim; d++) {
17826858538eSMatthew G. Knepley         for (PetscInt f = 0; f < dim; f++) {
17837f07f362SMatthew G. Knepley           J[d * dim + f] = 0.0;
1784ad540459SPierre Jolivet           for (PetscInt g = 0; g < dim; g++) J[d * dim + f] += R[d * dim + g] * J0[g * dim + f];
17857f07f362SMatthew G. Knepley         }
17867f07f362SMatthew G. Knepley       }
17879566063dSJacob Faibussowitsch       PetscCall(PetscLogFlops(18.0));
17887f07f362SMatthew G. Knepley     }
1789ad540459SPierre Jolivet     if (invJ) DMPlex_Invert3D_Internal(invJ, J, *detJ);
17907f07f362SMatthew G. Knepley   } else if (numCoords == 6) {
17917f07f362SMatthew G. Knepley     const PetscInt dim = 2;
17927f07f362SMatthew G. Knepley 
17939371c9d4SSatish Balay     if (v0) {
17949371c9d4SSatish Balay       for (d = 0; d < dim; d++) v0[d] = PetscRealPart(coords[d]);
17959371c9d4SSatish Balay     }
1796ccd2543fSMatthew G Knepley     if (J) {
1797ccd2543fSMatthew G Knepley       for (d = 0; d < dim; d++) {
1798ad540459SPierre 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]));
1799ccd2543fSMatthew G Knepley       }
18009566063dSJacob Faibussowitsch       PetscCall(PetscLogFlops(8.0));
1801923591dfSMatthew G. Knepley       DMPlex_Det2D_Internal(detJ, J);
1802ccd2543fSMatthew G Knepley     }
1803ad540459SPierre Jolivet     if (invJ) DMPlex_Invert2D_Internal(invJ, J, *detJ);
180463a3b9bcSJacob Faibussowitsch   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The number of coordinates for this triangle is %" PetscInt_FMT " != 6 or 9", numCoords);
18056858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
18063ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1807ccd2543fSMatthew G Knepley }
1808ccd2543fSMatthew G Knepley 
1809d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeRectangleGeometry_Internal(DM dm, PetscInt e, PetscBool isTensor, PetscInt Nq, const PetscReal points[], PetscReal v[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
1810d71ae5a4SJacob Faibussowitsch {
18116858538eSMatthew G. Knepley   const PetscScalar *array;
1812a1e44745SMatthew G. Knepley   PetscScalar       *coords = NULL;
18136858538eSMatthew G. Knepley   PetscInt           numCoords, d;
18146858538eSMatthew G. Knepley   PetscBool          isDG;
1815ccd2543fSMatthew G Knepley 
1816ccd2543fSMatthew G Knepley   PetscFunctionBegin;
18176858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
18186858538eSMatthew G. Knepley   PetscCheck(!invJ || J, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "In order to compute invJ, J must not be NULL");
1819dfccc68fSToby Isaac   if (!Nq) {
1820412e9a14SMatthew G. Knepley     PetscInt vorder[4] = {0, 1, 2, 3};
1821412e9a14SMatthew G. Knepley 
18229371c9d4SSatish Balay     if (isTensor) {
18239371c9d4SSatish Balay       vorder[2] = 3;
18249371c9d4SSatish Balay       vorder[3] = 2;
18259371c9d4SSatish Balay     }
18267f07f362SMatthew G. Knepley     *detJ = 0.0;
182799dec3a6SMatthew G. Knepley     if (numCoords == 12) {
182899dec3a6SMatthew G. Knepley       const PetscInt dim = 3;
182999dec3a6SMatthew 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};
183099dec3a6SMatthew G. Knepley 
18319371c9d4SSatish Balay       if (v) {
18329371c9d4SSatish Balay         for (d = 0; d < dim; d++) v[d] = PetscRealPart(coords[d]);
18339371c9d4SSatish Balay       }
18349566063dSJacob Faibussowitsch       PetscCall(DMPlexComputeProjection3Dto2D(numCoords, coords, R));
183599dec3a6SMatthew G. Knepley       if (J) {
183699dec3a6SMatthew G. Knepley         const PetscInt pdim = 2;
183799dec3a6SMatthew G. Knepley 
183899dec3a6SMatthew G. Knepley         for (d = 0; d < pdim; d++) {
1839412e9a14SMatthew G. Knepley           J0[d * dim + 0] = 0.5 * (PetscRealPart(coords[vorder[1] * pdim + d]) - PetscRealPart(coords[vorder[0] * pdim + d]));
1840412e9a14SMatthew G. Knepley           J0[d * dim + 1] = 0.5 * (PetscRealPart(coords[vorder[2] * pdim + d]) - PetscRealPart(coords[vorder[1] * pdim + d]));
184199dec3a6SMatthew G. Knepley         }
18429566063dSJacob Faibussowitsch         PetscCall(PetscLogFlops(8.0));
1843923591dfSMatthew G. Knepley         DMPlex_Det3D_Internal(detJ, J0);
184499dec3a6SMatthew G. Knepley         for (d = 0; d < dim; d++) {
18456858538eSMatthew G. Knepley           for (PetscInt f = 0; f < dim; f++) {
184699dec3a6SMatthew G. Knepley             J[d * dim + f] = 0.0;
1847ad540459SPierre Jolivet             for (PetscInt g = 0; g < dim; g++) J[d * dim + f] += R[d * dim + g] * J0[g * dim + f];
184899dec3a6SMatthew G. Knepley           }
184999dec3a6SMatthew G. Knepley         }
18509566063dSJacob Faibussowitsch         PetscCall(PetscLogFlops(18.0));
185199dec3a6SMatthew G. Knepley       }
1852ad540459SPierre Jolivet       if (invJ) DMPlex_Invert3D_Internal(invJ, J, *detJ);
185371f58de1SToby Isaac     } else if (numCoords == 8) {
185499dec3a6SMatthew G. Knepley       const PetscInt dim = 2;
185599dec3a6SMatthew G. Knepley 
18569371c9d4SSatish Balay       if (v) {
18579371c9d4SSatish Balay         for (d = 0; d < dim; d++) v[d] = PetscRealPart(coords[d]);
18589371c9d4SSatish Balay       }
1859ccd2543fSMatthew G Knepley       if (J) {
1860ccd2543fSMatthew G Knepley         for (d = 0; d < dim; d++) {
1861412e9a14SMatthew G. Knepley           J[d * dim + 0] = 0.5 * (PetscRealPart(coords[vorder[1] * dim + d]) - PetscRealPart(coords[vorder[0] * dim + d]));
1862412e9a14SMatthew G. Knepley           J[d * dim + 1] = 0.5 * (PetscRealPart(coords[vorder[3] * dim + d]) - PetscRealPart(coords[vorder[0] * dim + d]));
1863ccd2543fSMatthew G Knepley         }
18649566063dSJacob Faibussowitsch         PetscCall(PetscLogFlops(8.0));
1865923591dfSMatthew G. Knepley         DMPlex_Det2D_Internal(detJ, J);
1866ccd2543fSMatthew G Knepley       }
1867ad540459SPierre Jolivet       if (invJ) DMPlex_Invert2D_Internal(invJ, J, *detJ);
186863a3b9bcSJacob Faibussowitsch     } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The number of coordinates for this quadrilateral is %" PetscInt_FMT " != 8 or 12", numCoords);
1869dfccc68fSToby Isaac   } else {
1870dfccc68fSToby Isaac     const PetscInt Nv         = 4;
1871dfccc68fSToby Isaac     const PetscInt dimR       = 2;
1872412e9a14SMatthew G. Knepley     PetscInt       zToPlex[4] = {0, 1, 3, 2};
1873dfccc68fSToby Isaac     PetscReal      zOrder[12];
1874dfccc68fSToby Isaac     PetscReal      zCoeff[12];
1875dfccc68fSToby Isaac     PetscInt       i, j, k, l, dim;
1876dfccc68fSToby Isaac 
18779371c9d4SSatish Balay     if (isTensor) {
18789371c9d4SSatish Balay       zToPlex[2] = 2;
18799371c9d4SSatish Balay       zToPlex[3] = 3;
18809371c9d4SSatish Balay     }
1881dfccc68fSToby Isaac     if (numCoords == 12) {
1882dfccc68fSToby Isaac       dim = 3;
1883dfccc68fSToby Isaac     } else if (numCoords == 8) {
1884dfccc68fSToby Isaac       dim = 2;
188563a3b9bcSJacob Faibussowitsch     } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The number of coordinates for this quadrilateral is %" PetscInt_FMT " != 8 or 12", numCoords);
1886dfccc68fSToby Isaac     for (i = 0; i < Nv; i++) {
1887dfccc68fSToby Isaac       PetscInt zi = zToPlex[i];
1888dfccc68fSToby Isaac 
1889ad540459SPierre Jolivet       for (j = 0; j < dim; j++) zOrder[dim * i + j] = PetscRealPart(coords[dim * zi + j]);
1890dfccc68fSToby Isaac     }
1891dfccc68fSToby Isaac     for (j = 0; j < dim; j++) {
18922df84da0SMatthew G. Knepley       /* Nodal basis for evaluation at the vertices: (1 \mp xi) (1 \mp eta):
18932df84da0SMatthew G. Knepley            \phi^0 = (1 - xi - eta + xi eta) --> 1      = 1/4 ( \phi^0 + \phi^1 + \phi^2 + \phi^3)
18942df84da0SMatthew G. Knepley            \phi^1 = (1 + xi - eta - xi eta) --> xi     = 1/4 (-\phi^0 + \phi^1 - \phi^2 + \phi^3)
18952df84da0SMatthew G. Knepley            \phi^2 = (1 - xi + eta - xi eta) --> eta    = 1/4 (-\phi^0 - \phi^1 + \phi^2 + \phi^3)
18962df84da0SMatthew G. Knepley            \phi^3 = (1 + xi + eta + xi eta) --> xi eta = 1/4 ( \phi^0 - \phi^1 - \phi^2 + \phi^3)
18972df84da0SMatthew G. Knepley       */
1898dfccc68fSToby Isaac       zCoeff[dim * 0 + j] = 0.25 * (zOrder[dim * 0 + j] + zOrder[dim * 1 + j] + zOrder[dim * 2 + j] + zOrder[dim * 3 + j]);
1899dfccc68fSToby Isaac       zCoeff[dim * 1 + j] = 0.25 * (-zOrder[dim * 0 + j] + zOrder[dim * 1 + j] - zOrder[dim * 2 + j] + zOrder[dim * 3 + j]);
1900dfccc68fSToby Isaac       zCoeff[dim * 2 + j] = 0.25 * (-zOrder[dim * 0 + j] - zOrder[dim * 1 + j] + zOrder[dim * 2 + j] + zOrder[dim * 3 + j]);
1901dfccc68fSToby Isaac       zCoeff[dim * 3 + j] = 0.25 * (zOrder[dim * 0 + j] - zOrder[dim * 1 + j] - zOrder[dim * 2 + j] + zOrder[dim * 3 + j]);
1902dfccc68fSToby Isaac     }
1903dfccc68fSToby Isaac     for (i = 0; i < Nq; i++) {
1904dfccc68fSToby Isaac       PetscReal xi = points[dimR * i], eta = points[dimR * i + 1];
1905dfccc68fSToby Isaac 
1906dfccc68fSToby Isaac       if (v) {
1907dfccc68fSToby Isaac         PetscReal extPoint[4];
1908dfccc68fSToby Isaac 
1909dfccc68fSToby Isaac         extPoint[0] = 1.;
1910dfccc68fSToby Isaac         extPoint[1] = xi;
1911dfccc68fSToby Isaac         extPoint[2] = eta;
1912dfccc68fSToby Isaac         extPoint[3] = xi * eta;
1913dfccc68fSToby Isaac         for (j = 0; j < dim; j++) {
1914dfccc68fSToby Isaac           PetscReal val = 0.;
1915dfccc68fSToby Isaac 
1916ad540459SPierre Jolivet           for (k = 0; k < Nv; k++) val += extPoint[k] * zCoeff[dim * k + j];
1917dfccc68fSToby Isaac           v[i * dim + j] = val;
1918dfccc68fSToby Isaac         }
1919dfccc68fSToby Isaac       }
1920dfccc68fSToby Isaac       if (J) {
1921dfccc68fSToby Isaac         PetscReal extJ[8];
1922dfccc68fSToby Isaac 
1923dfccc68fSToby Isaac         extJ[0] = 0.;
1924dfccc68fSToby Isaac         extJ[1] = 0.;
1925dfccc68fSToby Isaac         extJ[2] = 1.;
1926dfccc68fSToby Isaac         extJ[3] = 0.;
1927dfccc68fSToby Isaac         extJ[4] = 0.;
1928dfccc68fSToby Isaac         extJ[5] = 1.;
1929dfccc68fSToby Isaac         extJ[6] = eta;
1930dfccc68fSToby Isaac         extJ[7] = xi;
1931dfccc68fSToby Isaac         for (j = 0; j < dim; j++) {
1932dfccc68fSToby Isaac           for (k = 0; k < dimR; k++) {
1933dfccc68fSToby Isaac             PetscReal val = 0.;
1934dfccc68fSToby Isaac 
1935ad540459SPierre Jolivet             for (l = 0; l < Nv; l++) val += zCoeff[dim * l + j] * extJ[dimR * l + k];
1936dfccc68fSToby Isaac             J[i * dim * dim + dim * j + k] = val;
1937dfccc68fSToby Isaac           }
1938dfccc68fSToby Isaac         }
1939dfccc68fSToby Isaac         if (dim == 3) { /* put the cross product in the third component of the Jacobian */
1940dfccc68fSToby Isaac           PetscReal  x, y, z;
1941dfccc68fSToby Isaac           PetscReal *iJ = &J[i * dim * dim];
1942dfccc68fSToby Isaac           PetscReal  norm;
1943dfccc68fSToby Isaac 
1944dfccc68fSToby Isaac           x     = iJ[1 * dim + 0] * iJ[2 * dim + 1] - iJ[1 * dim + 1] * iJ[2 * dim + 0];
1945dfccc68fSToby Isaac           y     = iJ[0 * dim + 1] * iJ[2 * dim + 0] - iJ[0 * dim + 0] * iJ[2 * dim + 1];
1946dfccc68fSToby Isaac           z     = iJ[0 * dim + 0] * iJ[1 * dim + 1] - iJ[0 * dim + 1] * iJ[1 * dim + 0];
1947dfccc68fSToby Isaac           norm  = PetscSqrtReal(x * x + y * y + z * z);
1948dfccc68fSToby Isaac           iJ[2] = x / norm;
1949dfccc68fSToby Isaac           iJ[5] = y / norm;
1950dfccc68fSToby Isaac           iJ[8] = z / norm;
1951dfccc68fSToby Isaac           DMPlex_Det3D_Internal(&detJ[i], &J[i * dim * dim]);
1952ad540459SPierre Jolivet           if (invJ) DMPlex_Invert3D_Internal(&invJ[i * dim * dim], &J[i * dim * dim], detJ[i]);
1953dfccc68fSToby Isaac         } else {
1954dfccc68fSToby Isaac           DMPlex_Det2D_Internal(&detJ[i], &J[i * dim * dim]);
1955ad540459SPierre Jolivet           if (invJ) DMPlex_Invert2D_Internal(&invJ[i * dim * dim], &J[i * dim * dim], detJ[i]);
1956dfccc68fSToby Isaac         }
1957dfccc68fSToby Isaac       }
1958dfccc68fSToby Isaac     }
1959dfccc68fSToby Isaac   }
19606858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
19613ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1962ccd2543fSMatthew G Knepley }
1963ccd2543fSMatthew G Knepley 
1964d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeTetrahedronGeometry_Internal(DM dm, PetscInt e, PetscReal v0[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
1965d71ae5a4SJacob Faibussowitsch {
19666858538eSMatthew G. Knepley   const PetscScalar *array;
1967a1e44745SMatthew G. Knepley   PetscScalar       *coords = NULL;
1968ccd2543fSMatthew G Knepley   const PetscInt     dim    = 3;
19696858538eSMatthew G. Knepley   PetscInt           numCoords, d;
19706858538eSMatthew G. Knepley   PetscBool          isDG;
1971ccd2543fSMatthew G Knepley 
1972ccd2543fSMatthew G Knepley   PetscFunctionBegin;
19736858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
19746858538eSMatthew G. Knepley   PetscCheck(!invJ || J, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "In order to compute invJ, J must not be NULL");
19757f07f362SMatthew G. Knepley   *detJ = 0.0;
19769371c9d4SSatish Balay   if (v0) {
19779371c9d4SSatish Balay     for (d = 0; d < dim; d++) v0[d] = PetscRealPart(coords[d]);
19789371c9d4SSatish Balay   }
1979ccd2543fSMatthew G Knepley   if (J) {
1980ccd2543fSMatthew G Knepley     for (d = 0; d < dim; d++) {
1981f0df753eSMatthew G. Knepley       /* I orient with outward face normals */
1982f0df753eSMatthew G. Knepley       J[d * dim + 0] = 0.5 * (PetscRealPart(coords[2 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
1983f0df753eSMatthew G. Knepley       J[d * dim + 1] = 0.5 * (PetscRealPart(coords[1 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
1984f0df753eSMatthew G. Knepley       J[d * dim + 2] = 0.5 * (PetscRealPart(coords[3 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
1985ccd2543fSMatthew G Knepley     }
19869566063dSJacob Faibussowitsch     PetscCall(PetscLogFlops(18.0));
1987923591dfSMatthew G. Knepley     DMPlex_Det3D_Internal(detJ, J);
1988ccd2543fSMatthew G Knepley   }
1989ad540459SPierre Jolivet   if (invJ) DMPlex_Invert3D_Internal(invJ, J, *detJ);
19906858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
19913ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1992ccd2543fSMatthew G Knepley }
1993ccd2543fSMatthew G Knepley 
1994d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeHexahedronGeometry_Internal(DM dm, PetscInt e, PetscInt Nq, const PetscReal points[], PetscReal v[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
1995d71ae5a4SJacob Faibussowitsch {
19966858538eSMatthew G. Knepley   const PetscScalar *array;
1997a1e44745SMatthew G. Knepley   PetscScalar       *coords = NULL;
1998ccd2543fSMatthew G Knepley   const PetscInt     dim    = 3;
19996858538eSMatthew G. Knepley   PetscInt           numCoords, d;
20006858538eSMatthew G. Knepley   PetscBool          isDG;
2001ccd2543fSMatthew G Knepley 
2002ccd2543fSMatthew G Knepley   PetscFunctionBegin;
20036858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
20046858538eSMatthew G. Knepley   PetscCheck(!invJ || J, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "In order to compute invJ, J must not be NULL");
2005dfccc68fSToby Isaac   if (!Nq) {
20067f07f362SMatthew G. Knepley     *detJ = 0.0;
20079371c9d4SSatish Balay     if (v) {
20089371c9d4SSatish Balay       for (d = 0; d < dim; d++) v[d] = PetscRealPart(coords[d]);
20099371c9d4SSatish Balay     }
2010ccd2543fSMatthew G Knepley     if (J) {
2011ccd2543fSMatthew G Knepley       for (d = 0; d < dim; d++) {
2012f0df753eSMatthew G. Knepley         J[d * dim + 0] = 0.5 * (PetscRealPart(coords[3 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
2013f0df753eSMatthew G. Knepley         J[d * dim + 1] = 0.5 * (PetscRealPart(coords[1 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
2014f0df753eSMatthew G. Knepley         J[d * dim + 2] = 0.5 * (PetscRealPart(coords[4 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
2015ccd2543fSMatthew G Knepley       }
20169566063dSJacob Faibussowitsch       PetscCall(PetscLogFlops(18.0));
2017923591dfSMatthew G. Knepley       DMPlex_Det3D_Internal(detJ, J);
2018ccd2543fSMatthew G Knepley     }
2019ad540459SPierre Jolivet     if (invJ) DMPlex_Invert3D_Internal(invJ, J, *detJ);
2020dfccc68fSToby Isaac   } else {
2021dfccc68fSToby Isaac     const PetscInt Nv         = 8;
2022dfccc68fSToby Isaac     const PetscInt zToPlex[8] = {0, 3, 1, 2, 4, 5, 7, 6};
2023dfccc68fSToby Isaac     const PetscInt dim        = 3;
2024dfccc68fSToby Isaac     const PetscInt dimR       = 3;
2025dfccc68fSToby Isaac     PetscReal      zOrder[24];
2026dfccc68fSToby Isaac     PetscReal      zCoeff[24];
2027dfccc68fSToby Isaac     PetscInt       i, j, k, l;
2028dfccc68fSToby Isaac 
2029dfccc68fSToby Isaac     for (i = 0; i < Nv; i++) {
2030dfccc68fSToby Isaac       PetscInt zi = zToPlex[i];
2031dfccc68fSToby Isaac 
2032ad540459SPierre Jolivet       for (j = 0; j < dim; j++) zOrder[dim * i + j] = PetscRealPart(coords[dim * zi + j]);
2033dfccc68fSToby Isaac     }
2034dfccc68fSToby Isaac     for (j = 0; j < dim; j++) {
2035dfccc68fSToby 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]);
2036dfccc68fSToby 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]);
2037dfccc68fSToby 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]);
2038dfccc68fSToby 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]);
2039dfccc68fSToby 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]);
2040dfccc68fSToby 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]);
2041dfccc68fSToby 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]);
2042dfccc68fSToby 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]);
2043dfccc68fSToby Isaac     }
2044dfccc68fSToby Isaac     for (i = 0; i < Nq; i++) {
2045dfccc68fSToby Isaac       PetscReal xi = points[dimR * i], eta = points[dimR * i + 1], theta = points[dimR * i + 2];
2046dfccc68fSToby Isaac 
2047dfccc68fSToby Isaac       if (v) {
204891d2b7ceSToby Isaac         PetscReal extPoint[8];
2049dfccc68fSToby Isaac 
2050dfccc68fSToby Isaac         extPoint[0] = 1.;
2051dfccc68fSToby Isaac         extPoint[1] = xi;
2052dfccc68fSToby Isaac         extPoint[2] = eta;
2053dfccc68fSToby Isaac         extPoint[3] = xi * eta;
2054dfccc68fSToby Isaac         extPoint[4] = theta;
2055dfccc68fSToby Isaac         extPoint[5] = theta * xi;
2056dfccc68fSToby Isaac         extPoint[6] = theta * eta;
2057dfccc68fSToby Isaac         extPoint[7] = theta * eta * xi;
2058dfccc68fSToby Isaac         for (j = 0; j < dim; j++) {
2059dfccc68fSToby Isaac           PetscReal val = 0.;
2060dfccc68fSToby Isaac 
2061ad540459SPierre Jolivet           for (k = 0; k < Nv; k++) val += extPoint[k] * zCoeff[dim * k + j];
2062dfccc68fSToby Isaac           v[i * dim + j] = val;
2063dfccc68fSToby Isaac         }
2064dfccc68fSToby Isaac       }
2065dfccc68fSToby Isaac       if (J) {
2066dfccc68fSToby Isaac         PetscReal extJ[24];
2067dfccc68fSToby Isaac 
20689371c9d4SSatish Balay         extJ[0]  = 0.;
20699371c9d4SSatish Balay         extJ[1]  = 0.;
20709371c9d4SSatish Balay         extJ[2]  = 0.;
20719371c9d4SSatish Balay         extJ[3]  = 1.;
20729371c9d4SSatish Balay         extJ[4]  = 0.;
20739371c9d4SSatish Balay         extJ[5]  = 0.;
20749371c9d4SSatish Balay         extJ[6]  = 0.;
20759371c9d4SSatish Balay         extJ[7]  = 1.;
20769371c9d4SSatish Balay         extJ[8]  = 0.;
20779371c9d4SSatish Balay         extJ[9]  = eta;
20789371c9d4SSatish Balay         extJ[10] = xi;
20799371c9d4SSatish Balay         extJ[11] = 0.;
20809371c9d4SSatish Balay         extJ[12] = 0.;
20819371c9d4SSatish Balay         extJ[13] = 0.;
20829371c9d4SSatish Balay         extJ[14] = 1.;
20839371c9d4SSatish Balay         extJ[15] = theta;
20849371c9d4SSatish Balay         extJ[16] = 0.;
20859371c9d4SSatish Balay         extJ[17] = xi;
20869371c9d4SSatish Balay         extJ[18] = 0.;
20879371c9d4SSatish Balay         extJ[19] = theta;
20889371c9d4SSatish Balay         extJ[20] = eta;
20899371c9d4SSatish Balay         extJ[21] = theta * eta;
20909371c9d4SSatish Balay         extJ[22] = theta * xi;
20919371c9d4SSatish Balay         extJ[23] = eta * xi;
2092dfccc68fSToby Isaac 
2093dfccc68fSToby Isaac         for (j = 0; j < dim; j++) {
2094dfccc68fSToby Isaac           for (k = 0; k < dimR; k++) {
2095dfccc68fSToby Isaac             PetscReal val = 0.;
2096dfccc68fSToby Isaac 
2097ad540459SPierre Jolivet             for (l = 0; l < Nv; l++) val += zCoeff[dim * l + j] * extJ[dimR * l + k];
2098dfccc68fSToby Isaac             J[i * dim * dim + dim * j + k] = val;
2099dfccc68fSToby Isaac           }
2100dfccc68fSToby Isaac         }
2101dfccc68fSToby Isaac         DMPlex_Det3D_Internal(&detJ[i], &J[i * dim * dim]);
2102ad540459SPierre Jolivet         if (invJ) DMPlex_Invert3D_Internal(&invJ[i * dim * dim], &J[i * dim * dim], detJ[i]);
2103dfccc68fSToby Isaac       }
2104dfccc68fSToby Isaac     }
2105dfccc68fSToby Isaac   }
21066858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
21073ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2108ccd2543fSMatthew G Knepley }
2109ccd2543fSMatthew G Knepley 
2110d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeTriangularPrismGeometry_Internal(DM dm, PetscInt e, PetscInt Nq, const PetscReal points[], PetscReal v[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
2111d71ae5a4SJacob Faibussowitsch {
21126858538eSMatthew G. Knepley   const PetscScalar *array;
21132df84da0SMatthew G. Knepley   PetscScalar       *coords = NULL;
21142df84da0SMatthew G. Knepley   const PetscInt     dim    = 3;
21156858538eSMatthew G. Knepley   PetscInt           numCoords, d;
21166858538eSMatthew G. Knepley   PetscBool          isDG;
21172df84da0SMatthew G. Knepley 
21182df84da0SMatthew G. Knepley   PetscFunctionBegin;
21196858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
21206858538eSMatthew G. Knepley   PetscCheck(!invJ || J, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "In order to compute invJ, J must not be NULL");
21212df84da0SMatthew G. Knepley   if (!Nq) {
21222df84da0SMatthew G. Knepley     /* Assume that the map to the reference is affine */
21232df84da0SMatthew G. Knepley     *detJ = 0.0;
21249371c9d4SSatish Balay     if (v) {
21259371c9d4SSatish Balay       for (d = 0; d < dim; d++) v[d] = PetscRealPart(coords[d]);
21269371c9d4SSatish Balay     }
21272df84da0SMatthew G. Knepley     if (J) {
21282df84da0SMatthew G. Knepley       for (d = 0; d < dim; d++) {
21292df84da0SMatthew G. Knepley         J[d * dim + 0] = 0.5 * (PetscRealPart(coords[2 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
21302df84da0SMatthew G. Knepley         J[d * dim + 1] = 0.5 * (PetscRealPart(coords[1 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
21312df84da0SMatthew G. Knepley         J[d * dim + 2] = 0.5 * (PetscRealPart(coords[4 * dim + d]) - PetscRealPart(coords[0 * dim + d]));
21322df84da0SMatthew G. Knepley       }
21339566063dSJacob Faibussowitsch       PetscCall(PetscLogFlops(18.0));
21342df84da0SMatthew G. Knepley       DMPlex_Det3D_Internal(detJ, J);
21352df84da0SMatthew G. Knepley     }
2136ad540459SPierre Jolivet     if (invJ) DMPlex_Invert3D_Internal(invJ, J, *detJ);
21372df84da0SMatthew G. Knepley   } else {
21382df84da0SMatthew G. Knepley     const PetscInt dim  = 3;
21392df84da0SMatthew G. Knepley     const PetscInt dimR = 3;
21402df84da0SMatthew G. Knepley     const PetscInt Nv   = 6;
21412df84da0SMatthew G. Knepley     PetscReal      verts[18];
21422df84da0SMatthew G. Knepley     PetscReal      coeff[18];
21432df84da0SMatthew G. Knepley     PetscInt       i, j, k, l;
21442df84da0SMatthew G. Knepley 
21459371c9d4SSatish Balay     for (i = 0; i < Nv; ++i)
21469371c9d4SSatish Balay       for (j = 0; j < dim; ++j) verts[dim * i + j] = PetscRealPart(coords[dim * i + j]);
21472df84da0SMatthew G. Knepley     for (j = 0; j < dim; ++j) {
21482df84da0SMatthew G. Knepley       /* Check for triangle,
21492df84da0SMatthew 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)
21502df84da0SMatthew 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)
21512df84da0SMatthew G. Knepley            phi^2 =  1/2 (1 + eta)   chi^2 = delta(-1,  1)
21522df84da0SMatthew G. Knepley 
21532df84da0SMatthew G. Knepley            phi^0 + phi^1 + phi^2 = 1    coef_1   = 1/2 (         chi^1 + chi^2)
21542df84da0SMatthew G. Knepley           -phi^0 + phi^1 - phi^2 = xi   coef_xi  = 1/2 (-chi^0 + chi^1)
21552df84da0SMatthew G. Knepley           -phi^0 - phi^1 + phi^2 = eta  coef_eta = 1/2 (-chi^0         + chi^2)
21562df84da0SMatthew G. Knepley 
21572df84da0SMatthew G. Knepley           < chi_0 chi_1 chi_2> A /  1  1  1 \ / phi_0 \   <chi> I <phi>^T  so we need the inverse transpose
21582df84da0SMatthew G. Knepley                                  | -1  1 -1 | | phi_1 | =
21592df84da0SMatthew G. Knepley                                  \ -1 -1  1 / \ phi_2 /
21602df84da0SMatthew G. Knepley 
21612df84da0SMatthew 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
21622df84da0SMatthew G. Knepley       */
21632df84da0SMatthew G. Knepley       /* Nodal basis for evaluation at the vertices: {-xi - eta, 1 + xi, 1 + eta} (1 \mp zeta):
21642df84da0SMatthew G. Knepley            \phi^0 = 1/4 (   -xi - eta        + xi zeta + eta zeta) --> /  1  1  1  1  1  1 \ 1
21652df84da0SMatthew G. Knepley            \phi^1 = 1/4 (1      + eta - zeta           - eta zeta) --> | -1  1 -1 -1 -1  1 | eta
21662df84da0SMatthew G. Knepley            \phi^2 = 1/4 (1 + xi       - zeta - xi zeta)            --> | -1 -1  1 -1  1 -1 | xi
21672df84da0SMatthew G. Knepley            \phi^3 = 1/4 (   -xi - eta        - xi zeta - eta zeta) --> | -1 -1 -1  1  1  1 | zeta
21682df84da0SMatthew G. Knepley            \phi^4 = 1/4 (1 + xi       + zeta + xi zeta)            --> |  1  1 -1 -1  1 -1 | xi zeta
21692df84da0SMatthew G. Knepley            \phi^5 = 1/4 (1      + eta + zeta           + eta zeta) --> \  1 -1  1 -1 -1  1 / eta zeta
21702df84da0SMatthew G. Knepley            1/4 /  0  1  1  0  1  1 \
21712df84da0SMatthew G. Knepley                | -1  1  0 -1  0  1 |
21722df84da0SMatthew G. Knepley                | -1  0  1 -1  1  0 |
21732df84da0SMatthew G. Knepley                |  0 -1 -1  0  1  1 |
21742df84da0SMatthew G. Knepley                |  1  0 -1 -1  1  0 |
21752df84da0SMatthew G. Knepley                \  1 -1  0 -1  0  1 /
21762df84da0SMatthew G. Knepley       */
21772df84da0SMatthew G. Knepley       coeff[dim * 0 + j] = (1. / 4.) * (verts[dim * 1 + j] + verts[dim * 2 + j] + verts[dim * 4 + j] + verts[dim * 5 + j]);
21782df84da0SMatthew G. Knepley       coeff[dim * 1 + j] = (1. / 4.) * (-verts[dim * 0 + j] + verts[dim * 1 + j] - verts[dim * 3 + j] + verts[dim * 5 + j]);
21792df84da0SMatthew G. Knepley       coeff[dim * 2 + j] = (1. / 4.) * (-verts[dim * 0 + j] + verts[dim * 2 + j] - verts[dim * 3 + j] + verts[dim * 4 + j]);
21802df84da0SMatthew G. Knepley       coeff[dim * 3 + j] = (1. / 4.) * (-verts[dim * 1 + j] - verts[dim * 2 + j] + verts[dim * 4 + j] + verts[dim * 5 + j]);
21812df84da0SMatthew G. Knepley       coeff[dim * 4 + j] = (1. / 4.) * (verts[dim * 0 + j] - verts[dim * 2 + j] - verts[dim * 3 + j] + verts[dim * 4 + j]);
21822df84da0SMatthew G. Knepley       coeff[dim * 5 + j] = (1. / 4.) * (verts[dim * 0 + j] - verts[dim * 1 + j] - verts[dim * 3 + j] + verts[dim * 5 + j]);
21832df84da0SMatthew G. Knepley       /* For reference prism:
21842df84da0SMatthew G. Knepley       {0, 0, 0}
21852df84da0SMatthew G. Knepley       {0, 1, 0}
21862df84da0SMatthew G. Knepley       {1, 0, 0}
21872df84da0SMatthew G. Knepley       {0, 0, 1}
21882df84da0SMatthew G. Knepley       {0, 0, 0}
21892df84da0SMatthew G. Knepley       {0, 0, 0}
21902df84da0SMatthew G. Knepley       */
21912df84da0SMatthew G. Knepley     }
21922df84da0SMatthew G. Knepley     for (i = 0; i < Nq; ++i) {
21932df84da0SMatthew G. Knepley       const PetscReal xi = points[dimR * i], eta = points[dimR * i + 1], zeta = points[dimR * i + 2];
21942df84da0SMatthew G. Knepley 
21952df84da0SMatthew G. Knepley       if (v) {
21962df84da0SMatthew G. Knepley         PetscReal extPoint[6];
21972df84da0SMatthew G. Knepley         PetscInt  c;
21982df84da0SMatthew G. Knepley 
21992df84da0SMatthew G. Knepley         extPoint[0] = 1.;
22002df84da0SMatthew G. Knepley         extPoint[1] = eta;
22012df84da0SMatthew G. Knepley         extPoint[2] = xi;
22022df84da0SMatthew G. Knepley         extPoint[3] = zeta;
22032df84da0SMatthew G. Knepley         extPoint[4] = xi * zeta;
22042df84da0SMatthew G. Knepley         extPoint[5] = eta * zeta;
22052df84da0SMatthew G. Knepley         for (c = 0; c < dim; ++c) {
22062df84da0SMatthew G. Knepley           PetscReal val = 0.;
22072df84da0SMatthew G. Knepley 
2208ad540459SPierre Jolivet           for (k = 0; k < Nv; ++k) val += extPoint[k] * coeff[k * dim + c];
22092df84da0SMatthew G. Knepley           v[i * dim + c] = val;
22102df84da0SMatthew G. Knepley         }
22112df84da0SMatthew G. Knepley       }
22122df84da0SMatthew G. Knepley       if (J) {
22132df84da0SMatthew G. Knepley         PetscReal extJ[18];
22142df84da0SMatthew G. Knepley 
22159371c9d4SSatish Balay         extJ[0]  = 0.;
22169371c9d4SSatish Balay         extJ[1]  = 0.;
22179371c9d4SSatish Balay         extJ[2]  = 0.;
22189371c9d4SSatish Balay         extJ[3]  = 0.;
22199371c9d4SSatish Balay         extJ[4]  = 1.;
22209371c9d4SSatish Balay         extJ[5]  = 0.;
22219371c9d4SSatish Balay         extJ[6]  = 1.;
22229371c9d4SSatish Balay         extJ[7]  = 0.;
22239371c9d4SSatish Balay         extJ[8]  = 0.;
22249371c9d4SSatish Balay         extJ[9]  = 0.;
22259371c9d4SSatish Balay         extJ[10] = 0.;
22269371c9d4SSatish Balay         extJ[11] = 1.;
22279371c9d4SSatish Balay         extJ[12] = zeta;
22289371c9d4SSatish Balay         extJ[13] = 0.;
22299371c9d4SSatish Balay         extJ[14] = xi;
22309371c9d4SSatish Balay         extJ[15] = 0.;
22319371c9d4SSatish Balay         extJ[16] = zeta;
22329371c9d4SSatish Balay         extJ[17] = eta;
22332df84da0SMatthew G. Knepley 
22342df84da0SMatthew G. Knepley         for (j = 0; j < dim; j++) {
22352df84da0SMatthew G. Knepley           for (k = 0; k < dimR; k++) {
22362df84da0SMatthew G. Knepley             PetscReal val = 0.;
22372df84da0SMatthew G. Knepley 
2238ad540459SPierre Jolivet             for (l = 0; l < Nv; l++) val += coeff[dim * l + j] * extJ[dimR * l + k];
22392df84da0SMatthew G. Knepley             J[i * dim * dim + dim * j + k] = val;
22402df84da0SMatthew G. Knepley           }
22412df84da0SMatthew G. Knepley         }
22422df84da0SMatthew G. Knepley         DMPlex_Det3D_Internal(&detJ[i], &J[i * dim * dim]);
2243ad540459SPierre Jolivet         if (invJ) DMPlex_Invert3D_Internal(&invJ[i * dim * dim], &J[i * dim * dim], detJ[i]);
22442df84da0SMatthew G. Knepley       }
22452df84da0SMatthew G. Knepley     }
22462df84da0SMatthew G. Knepley   }
22476858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, e, &isDG, &numCoords, &array, &coords));
22483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
22492df84da0SMatthew G. Knepley }
22502df84da0SMatthew G. Knepley 
2251d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeCellGeometryFEM_Implicit(DM dm, PetscInt cell, PetscQuadrature quad, PetscReal *v, PetscReal *J, PetscReal *invJ, PetscReal *detJ)
2252d71ae5a4SJacob Faibussowitsch {
2253ba2698f1SMatthew G. Knepley   DMPolytopeType   ct;
2254dfccc68fSToby Isaac   PetscInt         depth, dim, coordDim, coneSize, i;
2255dfccc68fSToby Isaac   PetscInt         Nq     = 0;
2256dfccc68fSToby Isaac   const PetscReal *points = NULL;
2257dfccc68fSToby Isaac   DMLabel          depthLabel;
2258c330f8ffSToby Isaac   PetscReal        xi0[3]   = {-1., -1., -1.}, v0[3], J0[9], detJ0;
2259dfccc68fSToby Isaac   PetscBool        isAffine = PETSC_TRUE;
2260dfccc68fSToby Isaac 
2261dfccc68fSToby Isaac   PetscFunctionBegin;
22629566063dSJacob Faibussowitsch   PetscCall(DMPlexGetDepth(dm, &depth));
22639566063dSJacob Faibussowitsch   PetscCall(DMPlexGetConeSize(dm, cell, &coneSize));
22649566063dSJacob Faibussowitsch   PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
22659566063dSJacob Faibussowitsch   PetscCall(DMLabelGetValue(depthLabel, cell, &dim));
226648a46eb9SPierre Jolivet   if (depth == 1 && dim == 1) PetscCall(DMGetDimension(dm, &dim));
22679566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &coordDim));
226863a3b9bcSJacob Faibussowitsch   PetscCheck(coordDim <= 3, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Unsupported coordinate dimension %" PetscInt_FMT " > 3", coordDim);
22699566063dSJacob Faibussowitsch   if (quad) PetscCall(PetscQuadratureGetData(quad, NULL, NULL, &Nq, &points, NULL));
22709566063dSJacob Faibussowitsch   PetscCall(DMPlexGetCellType(dm, cell, &ct));
2271ba2698f1SMatthew G. Knepley   switch (ct) {
2272ba2698f1SMatthew G. Knepley   case DM_POLYTOPE_POINT:
22739566063dSJacob Faibussowitsch     PetscCall(DMPlexComputePointGeometry_Internal(dm, cell, v, J, invJ, detJ));
2274dfccc68fSToby Isaac     isAffine = PETSC_FALSE;
2275dfccc68fSToby Isaac     break;
2276ba2698f1SMatthew G. Knepley   case DM_POLYTOPE_SEGMENT:
2277412e9a14SMatthew G. Knepley   case DM_POLYTOPE_POINT_PRISM_TENSOR:
22789566063dSJacob Faibussowitsch     if (Nq) PetscCall(DMPlexComputeLineGeometry_Internal(dm, cell, v0, J0, NULL, &detJ0));
22799566063dSJacob Faibussowitsch     else PetscCall(DMPlexComputeLineGeometry_Internal(dm, cell, v, J, invJ, detJ));
2280dfccc68fSToby Isaac     break;
2281ba2698f1SMatthew G. Knepley   case DM_POLYTOPE_TRIANGLE:
22829566063dSJacob Faibussowitsch     if (Nq) PetscCall(DMPlexComputeTriangleGeometry_Internal(dm, cell, v0, J0, NULL, &detJ0));
22839566063dSJacob Faibussowitsch     else PetscCall(DMPlexComputeTriangleGeometry_Internal(dm, cell, v, J, invJ, detJ));
2284dfccc68fSToby Isaac     break;
2285ba2698f1SMatthew G. Knepley   case DM_POLYTOPE_QUADRILATERAL:
22869566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeRectangleGeometry_Internal(dm, cell, PETSC_FALSE, Nq, points, v, J, invJ, detJ));
2287412e9a14SMatthew G. Knepley     isAffine = PETSC_FALSE;
2288412e9a14SMatthew G. Knepley     break;
2289412e9a14SMatthew G. Knepley   case DM_POLYTOPE_SEG_PRISM_TENSOR:
22909566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeRectangleGeometry_Internal(dm, cell, PETSC_TRUE, Nq, points, v, J, invJ, detJ));
2291dfccc68fSToby Isaac     isAffine = PETSC_FALSE;
2292dfccc68fSToby Isaac     break;
2293ba2698f1SMatthew G. Knepley   case DM_POLYTOPE_TETRAHEDRON:
22949566063dSJacob Faibussowitsch     if (Nq) PetscCall(DMPlexComputeTetrahedronGeometry_Internal(dm, cell, v0, J0, NULL, &detJ0));
22959566063dSJacob Faibussowitsch     else PetscCall(DMPlexComputeTetrahedronGeometry_Internal(dm, cell, v, J, invJ, detJ));
2296dfccc68fSToby Isaac     break;
2297ba2698f1SMatthew G. Knepley   case DM_POLYTOPE_HEXAHEDRON:
22989566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeHexahedronGeometry_Internal(dm, cell, Nq, points, v, J, invJ, detJ));
2299dfccc68fSToby Isaac     isAffine = PETSC_FALSE;
2300dfccc68fSToby Isaac     break;
23012df84da0SMatthew G. Knepley   case DM_POLYTOPE_TRI_PRISM:
23029566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeTriangularPrismGeometry_Internal(dm, cell, Nq, points, v, J, invJ, detJ));
23032df84da0SMatthew G. Knepley     isAffine = PETSC_FALSE;
23042df84da0SMatthew G. Knepley     break;
2305d71ae5a4SJacob Faibussowitsch   default:
2306d71ae5a4SJacob 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))]);
2307dfccc68fSToby Isaac   }
23087318780aSToby Isaac   if (isAffine && Nq) {
2309dfccc68fSToby Isaac     if (v) {
2310ad540459SPierre Jolivet       for (i = 0; i < Nq; i++) CoordinatesRefToReal(coordDim, dim, xi0, v0, J0, &points[dim * i], &v[coordDim * i]);
2311dfccc68fSToby Isaac     }
23127318780aSToby Isaac     if (detJ) {
2313ad540459SPierre Jolivet       for (i = 0; i < Nq; i++) detJ[i] = detJ0;
23147318780aSToby Isaac     }
23157318780aSToby Isaac     if (J) {
23167318780aSToby Isaac       PetscInt k;
23177318780aSToby Isaac 
23187318780aSToby Isaac       for (i = 0, k = 0; i < Nq; i++) {
2319dfccc68fSToby Isaac         PetscInt j;
2320dfccc68fSToby Isaac 
2321ad540459SPierre Jolivet         for (j = 0; j < coordDim * coordDim; j++, k++) J[k] = J0[j];
23227318780aSToby Isaac       }
23237318780aSToby Isaac     }
23247318780aSToby Isaac     if (invJ) {
23257318780aSToby Isaac       PetscInt k;
23267318780aSToby Isaac       switch (coordDim) {
2327d71ae5a4SJacob Faibussowitsch       case 0:
2328d71ae5a4SJacob Faibussowitsch         break;
2329d71ae5a4SJacob Faibussowitsch       case 1:
2330d71ae5a4SJacob Faibussowitsch         invJ[0] = 1. / J0[0];
2331d71ae5a4SJacob Faibussowitsch         break;
2332d71ae5a4SJacob Faibussowitsch       case 2:
2333d71ae5a4SJacob Faibussowitsch         DMPlex_Invert2D_Internal(invJ, J0, detJ0);
2334d71ae5a4SJacob Faibussowitsch         break;
2335d71ae5a4SJacob Faibussowitsch       case 3:
2336d71ae5a4SJacob Faibussowitsch         DMPlex_Invert3D_Internal(invJ, J0, detJ0);
2337d71ae5a4SJacob Faibussowitsch         break;
23387318780aSToby Isaac       }
23397318780aSToby Isaac       for (i = 1, k = coordDim * coordDim; i < Nq; i++) {
23407318780aSToby Isaac         PetscInt j;
23417318780aSToby Isaac 
2342ad540459SPierre Jolivet         for (j = 0; j < coordDim * coordDim; j++, k++) invJ[k] = invJ[j];
2343dfccc68fSToby Isaac       }
2344dfccc68fSToby Isaac     }
2345dfccc68fSToby Isaac   }
23463ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2347dfccc68fSToby Isaac }
2348dfccc68fSToby Isaac 
2349ccd2543fSMatthew G Knepley /*@C
23508e0841e0SMatthew G. Knepley   DMPlexComputeCellGeometryAffineFEM - Assuming an affine map, compute the Jacobian, inverse Jacobian, and Jacobian determinant for a given cell
2351ccd2543fSMatthew G Knepley 
235220f4b53cSBarry Smith   Collective
2353ccd2543fSMatthew G Knepley 
23544165533cSJose E. Roman   Input Parameters:
235520f4b53cSBarry Smith + dm   - the `DMPLEX`
2356ccd2543fSMatthew G Knepley - cell - the cell
2357ccd2543fSMatthew G Knepley 
23584165533cSJose E. Roman   Output Parameters:
23599b172b3aSMatthew Knepley + v0   - the translation part of this affine transform, meaning the translation to the origin (not the first vertex of the reference cell)
2360ccd2543fSMatthew G Knepley . J    - the Jacobian of the transform from the reference element
2361ccd2543fSMatthew G Knepley . invJ - the inverse of the Jacobian
2362ccd2543fSMatthew G Knepley - detJ - the Jacobian determinant
2363ccd2543fSMatthew G Knepley 
2364ccd2543fSMatthew G Knepley   Level: advanced
2365ccd2543fSMatthew G Knepley 
236620f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexComputeCellGeometryFEM()`, `DMGetCoordinateSection()`, `DMGetCoordinates()`
2367ccd2543fSMatthew G Knepley @*/
2368d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexComputeCellGeometryAffineFEM(DM dm, PetscInt cell, PetscReal *v0, PetscReal *J, PetscReal *invJ, PetscReal *detJ)
2369d71ae5a4SJacob Faibussowitsch {
2370ccd2543fSMatthew G Knepley   PetscFunctionBegin;
23719566063dSJacob Faibussowitsch   PetscCall(DMPlexComputeCellGeometryFEM_Implicit(dm, cell, NULL, v0, J, invJ, detJ));
23723ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
23738e0841e0SMatthew G. Knepley }
23748e0841e0SMatthew G. Knepley 
2375d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeCellGeometryFEM_FE(DM dm, PetscFE fe, PetscInt point, PetscQuadrature quad, PetscReal v[], PetscReal J[], PetscReal invJ[], PetscReal *detJ)
2376d71ae5a4SJacob Faibussowitsch {
23776858538eSMatthew G. Knepley   const PetscScalar *array;
23788e0841e0SMatthew G. Knepley   PetscScalar       *coords = NULL;
23796858538eSMatthew G. Knepley   PetscInt           numCoords;
23806858538eSMatthew G. Knepley   PetscBool          isDG;
23816858538eSMatthew G. Knepley   PetscQuadrature    feQuad;
23828e0841e0SMatthew G. Knepley   const PetscReal   *quadPoints;
2383ef0bb6c7SMatthew G. Knepley   PetscTabulation    T;
23846858538eSMatthew G. Knepley   PetscInt           dim, cdim, pdim, qdim, Nq, q;
23858e0841e0SMatthew G. Knepley 
23868e0841e0SMatthew G. Knepley   PetscFunctionBegin;
23879566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dim));
23889566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &cdim));
23896858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, point, &isDG, &numCoords, &array, &coords));
2390dfccc68fSToby Isaac   if (!quad) { /* use the first point of the first functional of the dual space */
2391dfccc68fSToby Isaac     PetscDualSpace dsp;
2392dfccc68fSToby Isaac 
23939566063dSJacob Faibussowitsch     PetscCall(PetscFEGetDualSpace(fe, &dsp));
23949566063dSJacob Faibussowitsch     PetscCall(PetscDualSpaceGetFunctional(dsp, 0, &quad));
23959566063dSJacob Faibussowitsch     PetscCall(PetscQuadratureGetData(quad, &qdim, NULL, &Nq, &quadPoints, NULL));
2396dfccc68fSToby Isaac     Nq = 1;
2397dfccc68fSToby Isaac   } else {
23989566063dSJacob Faibussowitsch     PetscCall(PetscQuadratureGetData(quad, &qdim, NULL, &Nq, &quadPoints, NULL));
2399dfccc68fSToby Isaac   }
24009566063dSJacob Faibussowitsch   PetscCall(PetscFEGetDimension(fe, &pdim));
24019566063dSJacob Faibussowitsch   PetscCall(PetscFEGetQuadrature(fe, &feQuad));
2402dfccc68fSToby Isaac   if (feQuad == quad) {
24039566063dSJacob Faibussowitsch     PetscCall(PetscFEGetCellTabulation(fe, J ? 1 : 0, &T));
240463a3b9bcSJacob 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);
2405dfccc68fSToby Isaac   } else {
24069566063dSJacob Faibussowitsch     PetscCall(PetscFECreateTabulation(fe, 1, Nq, quadPoints, J ? 1 : 0, &T));
2407dfccc68fSToby Isaac   }
240863a3b9bcSJacob Faibussowitsch   PetscCheck(qdim == dim, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Point dimension %" PetscInt_FMT " != quadrature dimension %" PetscInt_FMT, dim, qdim);
2409ef0bb6c7SMatthew G. Knepley   {
2410ef0bb6c7SMatthew G. Knepley     const PetscReal *basis    = T->T[0];
2411ef0bb6c7SMatthew G. Knepley     const PetscReal *basisDer = T->T[1];
2412ef0bb6c7SMatthew G. Knepley     PetscReal        detJt;
2413ef0bb6c7SMatthew G. Knepley 
2414a2a9e04cSMatthew G. Knepley #if defined(PETSC_USE_DEBUG)
241563a3b9bcSJacob Faibussowitsch     PetscCheck(Nq == T->Np, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Np %" PetscInt_FMT " != %" PetscInt_FMT, Nq, T->Np);
241663a3b9bcSJacob Faibussowitsch     PetscCheck(pdim == T->Nb, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nb %" PetscInt_FMT " != %" PetscInt_FMT, pdim, T->Nb);
241763a3b9bcSJacob Faibussowitsch     PetscCheck(dim == T->Nc, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nc %" PetscInt_FMT " != %" PetscInt_FMT, dim, T->Nc);
241863a3b9bcSJacob Faibussowitsch     PetscCheck(cdim == T->cdim, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "cdim %" PetscInt_FMT " != %" PetscInt_FMT, cdim, T->cdim);
2419a2a9e04cSMatthew G. Knepley #endif
2420dfccc68fSToby Isaac     if (v) {
24219566063dSJacob Faibussowitsch       PetscCall(PetscArrayzero(v, Nq * cdim));
2422f960e424SToby Isaac       for (q = 0; q < Nq; ++q) {
2423f960e424SToby Isaac         PetscInt i, k;
2424f960e424SToby Isaac 
2425301b184aSMatthew G. Knepley         for (k = 0; k < pdim; ++k) {
2426301b184aSMatthew G. Knepley           const PetscInt vertex = k / cdim;
2427ad540459SPierre Jolivet           for (i = 0; i < cdim; ++i) v[q * cdim + i] += basis[(q * pdim + k) * cdim + i] * PetscRealPart(coords[vertex * cdim + i]);
2428301b184aSMatthew G. Knepley         }
24299566063dSJacob Faibussowitsch         PetscCall(PetscLogFlops(2.0 * pdim * cdim));
2430f960e424SToby Isaac       }
2431f960e424SToby Isaac     }
24328e0841e0SMatthew G. Knepley     if (J) {
24339566063dSJacob Faibussowitsch       PetscCall(PetscArrayzero(J, Nq * cdim * cdim));
24348e0841e0SMatthew G. Knepley       for (q = 0; q < Nq; ++q) {
24358e0841e0SMatthew G. Knepley         PetscInt i, j, k, c, r;
24368e0841e0SMatthew G. Knepley 
24378e0841e0SMatthew G. Knepley         /* J = dx_i/d\xi_j = sum[k=0,n-1] dN_k/d\xi_j * x_i(k) */
2438301b184aSMatthew G. Knepley         for (k = 0; k < pdim; ++k) {
2439301b184aSMatthew G. Knepley           const PetscInt vertex = k / cdim;
2440301b184aSMatthew G. Knepley           for (j = 0; j < dim; ++j) {
2441ad540459SPierre 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]);
2442301b184aSMatthew G. Knepley           }
2443301b184aSMatthew G. Knepley         }
24449566063dSJacob Faibussowitsch         PetscCall(PetscLogFlops(2.0 * pdim * dim * cdim));
24458e0841e0SMatthew G. Knepley         if (cdim > dim) {
24468e0841e0SMatthew G. Knepley           for (c = dim; c < cdim; ++c)
24479371c9d4SSatish Balay             for (r = 0; r < cdim; ++r) J[r * cdim + c] = r == c ? 1.0 : 0.0;
24488e0841e0SMatthew G. Knepley         }
2449f960e424SToby Isaac         if (!detJ && !invJ) continue;
2450a63b72c6SToby Isaac         detJt = 0.;
24518e0841e0SMatthew G. Knepley         switch (cdim) {
24528e0841e0SMatthew G. Knepley         case 3:
2453037dc194SToby Isaac           DMPlex_Det3D_Internal(&detJt, &J[q * cdim * dim]);
2454ad540459SPierre Jolivet           if (invJ) DMPlex_Invert3D_Internal(&invJ[q * cdim * dim], &J[q * cdim * dim], detJt);
245517fe8556SMatthew G. Knepley           break;
245649dc4407SMatthew G. Knepley         case 2:
24579f328543SToby Isaac           DMPlex_Det2D_Internal(&detJt, &J[q * cdim * dim]);
2458ad540459SPierre Jolivet           if (invJ) DMPlex_Invert2D_Internal(&invJ[q * cdim * dim], &J[q * cdim * dim], detJt);
245949dc4407SMatthew G. Knepley           break;
24608e0841e0SMatthew G. Knepley         case 1:
2461037dc194SToby Isaac           detJt = J[q * cdim * dim];
2462037dc194SToby Isaac           if (invJ) invJ[q * cdim * dim] = 1.0 / detJt;
246349dc4407SMatthew G. Knepley         }
2464f960e424SToby Isaac         if (detJ) detJ[q] = detJt;
246549dc4407SMatthew G. Knepley       }
246608401ef6SPierre Jolivet     } else PetscCheck(!detJ && !invJ, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Need J to compute invJ or detJ");
246749dc4407SMatthew G. Knepley   }
24689566063dSJacob Faibussowitsch   if (feQuad != quad) PetscCall(PetscTabulationDestroy(&T));
24696858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, point, &isDG, &numCoords, &array, &coords));
24703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
24718e0841e0SMatthew G. Knepley }
24728e0841e0SMatthew G. Knepley 
24738e0841e0SMatthew G. Knepley /*@C
24748e0841e0SMatthew G. Knepley   DMPlexComputeCellGeometryFEM - Compute the Jacobian, inverse Jacobian, and Jacobian determinant at each quadrature point in the given cell
24758e0841e0SMatthew G. Knepley 
247620f4b53cSBarry Smith   Collective
24778e0841e0SMatthew G. Knepley 
24784165533cSJose E. Roman   Input Parameters:
247920f4b53cSBarry Smith + dm   - the `DMPLEX`
24808e0841e0SMatthew G. Knepley . cell - the cell
248120f4b53cSBarry Smith - quad - the quadrature containing the points in the reference element where the geometry will be evaluated.  If `quad` is `NULL`, geometry will be
2482dfccc68fSToby Isaac          evaluated at the first vertex of the reference element
24838e0841e0SMatthew G. Knepley 
24844165533cSJose E. Roman   Output Parameters:
2485dfccc68fSToby Isaac + v    - the image of the transformed quadrature points, otherwise the image of the first vertex in the closure of the reference element
24868e0841e0SMatthew G. Knepley . J    - the Jacobian of the transform from the reference element at each quadrature point
24878e0841e0SMatthew G. Knepley . invJ - the inverse of the Jacobian at each quadrature point
24888e0841e0SMatthew G. Knepley - detJ - the Jacobian determinant at each quadrature point
24898e0841e0SMatthew G. Knepley 
24908e0841e0SMatthew G. Knepley   Level: advanced
24918e0841e0SMatthew G. Knepley 
249220f4b53cSBarry Smith .seealso: `DMPLEX`, `DMGetCoordinateSection()`, `DMGetCoordinates()`
24938e0841e0SMatthew G. Knepley @*/
2494d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexComputeCellGeometryFEM(DM dm, PetscInt cell, PetscQuadrature quad, PetscReal *v, PetscReal *J, PetscReal *invJ, PetscReal *detJ)
2495d71ae5a4SJacob Faibussowitsch {
2496bb4a5db5SMatthew G. Knepley   DM      cdm;
2497dfccc68fSToby Isaac   PetscFE fe = NULL;
24988e0841e0SMatthew G. Knepley 
24998e0841e0SMatthew G. Knepley   PetscFunctionBegin;
25004f572ea9SToby Isaac   PetscAssertPointer(detJ, 7);
25019566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDM(dm, &cdm));
2502bb4a5db5SMatthew G. Knepley   if (cdm) {
2503dfccc68fSToby Isaac     PetscClassId id;
2504dfccc68fSToby Isaac     PetscInt     numFields;
2505e5e52638SMatthew G. Knepley     PetscDS      prob;
2506dfccc68fSToby Isaac     PetscObject  disc;
2507dfccc68fSToby Isaac 
25089566063dSJacob Faibussowitsch     PetscCall(DMGetNumFields(cdm, &numFields));
2509dfccc68fSToby Isaac     if (numFields) {
25109566063dSJacob Faibussowitsch       PetscCall(DMGetDS(cdm, &prob));
25119566063dSJacob Faibussowitsch       PetscCall(PetscDSGetDiscretization(prob, 0, &disc));
25129566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetClassId(disc, &id));
2513ad540459SPierre Jolivet       if (id == PETSCFE_CLASSID) fe = (PetscFE)disc;
2514dfccc68fSToby Isaac     }
2515dfccc68fSToby Isaac   }
25169566063dSJacob Faibussowitsch   if (!fe) PetscCall(DMPlexComputeCellGeometryFEM_Implicit(dm, cell, quad, v, J, invJ, detJ));
25179566063dSJacob Faibussowitsch   else PetscCall(DMPlexComputeCellGeometryFEM_FE(dm, fe, cell, quad, v, J, invJ, detJ));
25183ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2519ccd2543fSMatthew G Knepley }
2520834e62ceSMatthew G. Knepley 
2521d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeGeometryFVM_0D_Internal(DM dm, PetscInt dim, PetscInt cell, PetscReal *vol, PetscReal centroid[], PetscReal normal[])
2522d71ae5a4SJacob Faibussowitsch {
25239bf2564aSMatt McGurn   PetscSection       coordSection;
25249bf2564aSMatt McGurn   Vec                coordinates;
25259bf2564aSMatt McGurn   const PetscScalar *coords = NULL;
25269bf2564aSMatt McGurn   PetscInt           d, dof, off;
25279bf2564aSMatt McGurn 
25289bf2564aSMatt McGurn   PetscFunctionBegin;
25299566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
25309566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateSection(dm, &coordSection));
25319566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(coordinates, &coords));
25329bf2564aSMatt McGurn 
25339bf2564aSMatt McGurn   /* for a point the centroid is just the coord */
25349bf2564aSMatt McGurn   if (centroid) {
25359566063dSJacob Faibussowitsch     PetscCall(PetscSectionGetDof(coordSection, cell, &dof));
25369566063dSJacob Faibussowitsch     PetscCall(PetscSectionGetOffset(coordSection, cell, &off));
2537ad540459SPierre Jolivet     for (d = 0; d < dof; d++) centroid[d] = PetscRealPart(coords[off + d]);
25389bf2564aSMatt McGurn   }
25399bf2564aSMatt McGurn   if (normal) {
25409bf2564aSMatt McGurn     const PetscInt *support, *cones;
25419bf2564aSMatt McGurn     PetscInt        supportSize;
25429bf2564aSMatt McGurn     PetscReal       norm, sign;
25439bf2564aSMatt McGurn 
25449bf2564aSMatt McGurn     /* compute the norm based upon the support centroids */
25459566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupportSize(dm, cell, &supportSize));
25469566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupport(dm, cell, &support));
25479566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeCellGeometryFVM(dm, support[0], NULL, normal, NULL));
25489bf2564aSMatt McGurn 
25499bf2564aSMatt McGurn     /* Take the normal from the centroid of the support to the vertex*/
25509566063dSJacob Faibussowitsch     PetscCall(PetscSectionGetDof(coordSection, cell, &dof));
25519566063dSJacob Faibussowitsch     PetscCall(PetscSectionGetOffset(coordSection, cell, &off));
2552ad540459SPierre Jolivet     for (d = 0; d < dof; d++) normal[d] -= PetscRealPart(coords[off + d]);
25539bf2564aSMatt McGurn 
25549bf2564aSMatt McGurn     /* Determine the sign of the normal based upon its location in the support */
25559566063dSJacob Faibussowitsch     PetscCall(DMPlexGetCone(dm, support[0], &cones));
25569bf2564aSMatt McGurn     sign = cones[0] == cell ? 1.0 : -1.0;
25579bf2564aSMatt McGurn 
25589bf2564aSMatt McGurn     norm = DMPlex_NormD_Internal(dim, normal);
25599bf2564aSMatt McGurn     for (d = 0; d < dim; ++d) normal[d] /= (norm * sign);
25609bf2564aSMatt McGurn   }
2561ad540459SPierre Jolivet   if (vol) *vol = 1.0;
25629566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(coordinates, &coords));
25633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
25649bf2564aSMatt McGurn }
25659bf2564aSMatt McGurn 
2566d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeGeometryFVM_1D_Internal(DM dm, PetscInt dim, PetscInt cell, PetscReal *vol, PetscReal centroid[], PetscReal normal[])
2567d71ae5a4SJacob Faibussowitsch {
25686858538eSMatthew G. Knepley   const PetscScalar *array;
2569a1e44745SMatthew G. Knepley   PetscScalar       *coords = NULL;
257021d6a034SMatthew G. Knepley   PetscInt           cdim, coordSize, d;
25716858538eSMatthew G. Knepley   PetscBool          isDG;
2572cc08537eSMatthew G. Knepley 
2573cc08537eSMatthew G. Knepley   PetscFunctionBegin;
257421d6a034SMatthew G. Knepley   PetscCall(DMGetCoordinateDim(dm, &cdim));
25756858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, cell, &isDG, &coordSize, &array, &coords));
257621d6a034SMatthew G. Knepley   PetscCheck(coordSize == cdim * 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Edge has %" PetscInt_FMT " coordinates != %" PetscInt_FMT, coordSize, cdim * 2);
2577cc08537eSMatthew G. Knepley   if (centroid) {
257821d6a034SMatthew G. Knepley     for (d = 0; d < cdim; ++d) centroid[d] = 0.5 * PetscRealPart(coords[d] + coords[cdim + d]);
2579cc08537eSMatthew G. Knepley   }
2580cc08537eSMatthew G. Knepley   if (normal) {
2581a60a936bSMatthew G. Knepley     PetscReal norm;
2582a60a936bSMatthew G. Knepley 
258321d6a034SMatthew G. Knepley     switch (cdim) {
258421d6a034SMatthew G. Knepley     case 3:
2585f315e28eSPierre Jolivet       normal[2] = 0.; /* fall through */
258621d6a034SMatthew G. Knepley     case 2:
258721d6a034SMatthew G. Knepley       normal[0] = -PetscRealPart(coords[1] - coords[cdim + 1]);
258821d6a034SMatthew G. Knepley       normal[1] = PetscRealPart(coords[0] - coords[cdim + 0]);
258921d6a034SMatthew G. Knepley       break;
259021d6a034SMatthew G. Knepley     case 1:
259121d6a034SMatthew G. Knepley       normal[0] = 1.0;
259221d6a034SMatthew G. Knepley       break;
259321d6a034SMatthew G. Knepley     default:
259421d6a034SMatthew G. Knepley       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Dimension %" PetscInt_FMT " not supported", cdim);
259521d6a034SMatthew G. Knepley     }
259621d6a034SMatthew G. Knepley     norm = DMPlex_NormD_Internal(cdim, normal);
259721d6a034SMatthew G. Knepley     for (d = 0; d < cdim; ++d) normal[d] /= norm;
2598cc08537eSMatthew G. Knepley   }
2599cc08537eSMatthew G. Knepley   if (vol) {
2600714b99b6SMatthew G. Knepley     *vol = 0.0;
260121d6a034SMatthew G. Knepley     for (d = 0; d < cdim; ++d) *vol += PetscSqr(PetscRealPart(coords[d] - coords[cdim + d]));
2602714b99b6SMatthew G. Knepley     *vol = PetscSqrtReal(*vol);
2603cc08537eSMatthew G. Knepley   }
26046858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, cell, &isDG, &coordSize, &array, &coords));
26053ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2606cc08537eSMatthew G. Knepley }
2607cc08537eSMatthew G. Knepley 
2608cc08537eSMatthew G. Knepley /* Centroid_i = (\sum_n A_n Cn_i) / A */
2609d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeGeometryFVM_2D_Internal(DM dm, PetscInt dim, PetscInt cell, PetscReal *vol, PetscReal centroid[], PetscReal normal[])
2610d71ae5a4SJacob Faibussowitsch {
2611412e9a14SMatthew G. Knepley   DMPolytopeType     ct;
26126858538eSMatthew G. Knepley   const PetscScalar *array;
2613cc08537eSMatthew G. Knepley   PetscScalar       *coords = NULL;
26146858538eSMatthew G. Knepley   PetscInt           coordSize;
26156858538eSMatthew G. Knepley   PetscBool          isDG;
2616793a2a13SMatthew G. Knepley   PetscInt           fv[4] = {0, 1, 2, 3};
26176858538eSMatthew G. Knepley   PetscInt           cdim, numCorners, p, d;
2618cc08537eSMatthew G. Knepley 
2619cc08537eSMatthew G. Knepley   PetscFunctionBegin;
2620793a2a13SMatthew G. Knepley   /* Must check for hybrid cells because prisms have a different orientation scheme */
26219566063dSJacob Faibussowitsch   PetscCall(DMPlexGetCellType(dm, cell, &ct));
2622412e9a14SMatthew G. Knepley   switch (ct) {
26239371c9d4SSatish Balay   case DM_POLYTOPE_SEG_PRISM_TENSOR:
26249371c9d4SSatish Balay     fv[2] = 3;
26259371c9d4SSatish Balay     fv[3] = 2;
26269371c9d4SSatish Balay     break;
2627d71ae5a4SJacob Faibussowitsch   default:
2628d71ae5a4SJacob Faibussowitsch     break;
2629412e9a14SMatthew G. Knepley   }
26309566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &cdim));
26316858538eSMatthew G. Knepley   PetscCall(DMPlexGetConeSize(dm, cell, &numCorners));
26326858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, cell, &isDG, &coordSize, &array, &coords));
26333f27a4e6SJed Brown   {
26343f27a4e6SJed Brown     PetscReal c[3] = {0., 0., 0.}, n[3] = {0., 0., 0.}, origin[3] = {0., 0., 0.}, norm;
2635793a2a13SMatthew G. Knepley 
26363f27a4e6SJed Brown     for (d = 0; d < cdim; d++) origin[d] = PetscRealPart(coords[d]);
26374f99dae5SMatthew G. Knepley     for (p = 0; p < numCorners - 2; ++p) {
26383f27a4e6SJed Brown       PetscReal e0[3] = {0., 0., 0.}, e1[3] = {0., 0., 0.};
26393f27a4e6SJed Brown       for (d = 0; d < cdim; d++) {
26403f27a4e6SJed Brown         e0[d] = PetscRealPart(coords[cdim * fv[p + 1] + d]) - origin[d];
26413f27a4e6SJed Brown         e1[d] = PetscRealPart(coords[cdim * fv[p + 2] + d]) - origin[d];
26423f27a4e6SJed Brown       }
26433f27a4e6SJed Brown       const PetscReal dx = e0[1] * e1[2] - e0[2] * e1[1];
26443f27a4e6SJed Brown       const PetscReal dy = e0[2] * e1[0] - e0[0] * e1[2];
26453f27a4e6SJed Brown       const PetscReal dz = e0[0] * e1[1] - e0[1] * e1[0];
26463f27a4e6SJed Brown       const PetscReal a  = PetscSqrtReal(dx * dx + dy * dy + dz * dz);
26474f99dae5SMatthew G. Knepley 
26484f99dae5SMatthew G. Knepley       n[0] += dx;
26494f99dae5SMatthew G. Knepley       n[1] += dy;
26504f99dae5SMatthew G. Knepley       n[2] += dz;
2651ad540459SPierre 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.;
2652ceee4971SMatthew G. Knepley     }
26534f99dae5SMatthew G. Knepley     norm = PetscSqrtReal(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]);
265461451c10SMatthew G. Knepley     // Allow zero volume cells
265561451c10SMatthew G. Knepley     if (norm != 0) {
26564f99dae5SMatthew G. Knepley       n[0] /= norm;
26574f99dae5SMatthew G. Knepley       n[1] /= norm;
26584f99dae5SMatthew G. Knepley       n[2] /= norm;
26594f99dae5SMatthew G. Knepley       c[0] /= norm;
26604f99dae5SMatthew G. Knepley       c[1] /= norm;
26614f99dae5SMatthew G. Knepley       c[2] /= norm;
266261451c10SMatthew G. Knepley     }
26634f99dae5SMatthew G. Knepley     if (vol) *vol = 0.5 * norm;
26649371c9d4SSatish Balay     if (centroid)
26659371c9d4SSatish Balay       for (d = 0; d < cdim; ++d) centroid[d] = c[d];
26669371c9d4SSatish Balay     if (normal)
26679371c9d4SSatish Balay       for (d = 0; d < cdim; ++d) normal[d] = n[d];
26680a1d6728SMatthew G. Knepley   }
26696858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, cell, &isDG, &coordSize, &array, &coords));
26703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2671cc08537eSMatthew G. Knepley }
2672cc08537eSMatthew G. Knepley 
26730ec8681fSMatthew G. Knepley /* Centroid_i = (\sum_n V_n Cn_i) / V */
2674d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexComputeGeometryFVM_3D_Internal(DM dm, PetscInt dim, PetscInt cell, PetscReal *vol, PetscReal centroid[], PetscReal normal[])
2675d71ae5a4SJacob Faibussowitsch {
2676412e9a14SMatthew G. Knepley   DMPolytopeType        ct;
26776858538eSMatthew G. Knepley   const PetscScalar    *array;
26780ec8681fSMatthew G. Knepley   PetscScalar          *coords = NULL;
26796858538eSMatthew G. Knepley   PetscInt              coordSize;
26806858538eSMatthew G. Knepley   PetscBool             isDG;
26813f27a4e6SJed Brown   PetscReal             vsum      = 0.0, vtmp, coordsTmp[3 * 3], origin[3];
26826858538eSMatthew G. Knepley   const PetscInt        order[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
26836858538eSMatthew G. Knepley   const PetscInt       *cone, *faceSizes, *faces;
26846858538eSMatthew G. Knepley   const DMPolytopeType *faceTypes;
2685793a2a13SMatthew G. Knepley   PetscBool             isHybrid = PETSC_FALSE;
26866858538eSMatthew G. Knepley   PetscInt              numFaces, f, fOff = 0, p, d;
26870ec8681fSMatthew G. Knepley 
26880ec8681fSMatthew G. Knepley   PetscFunctionBegin;
268963a3b9bcSJacob Faibussowitsch   PetscCheck(dim <= 3, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No support for dim %" PetscInt_FMT " > 3", dim);
2690793a2a13SMatthew G. Knepley   /* Must check for hybrid cells because prisms have a different orientation scheme */
26919566063dSJacob Faibussowitsch   PetscCall(DMPlexGetCellType(dm, cell, &ct));
2692412e9a14SMatthew G. Knepley   switch (ct) {
2693412e9a14SMatthew G. Knepley   case DM_POLYTOPE_POINT_PRISM_TENSOR:
2694412e9a14SMatthew G. Knepley   case DM_POLYTOPE_SEG_PRISM_TENSOR:
2695412e9a14SMatthew G. Knepley   case DM_POLYTOPE_TRI_PRISM_TENSOR:
2696d71ae5a4SJacob Faibussowitsch   case DM_POLYTOPE_QUAD_PRISM_TENSOR:
2697d71ae5a4SJacob Faibussowitsch     isHybrid = PETSC_TRUE;
2698d71ae5a4SJacob Faibussowitsch   default:
2699d71ae5a4SJacob Faibussowitsch     break;
2700412e9a14SMatthew G. Knepley   }
2701793a2a13SMatthew G. Knepley 
27029371c9d4SSatish Balay   if (centroid)
27039371c9d4SSatish Balay     for (d = 0; d < dim; ++d) centroid[d] = 0.0;
27046858538eSMatthew G. Knepley   PetscCall(DMPlexGetCone(dm, cell, &cone));
27056858538eSMatthew G. Knepley 
27066858538eSMatthew G. Knepley   // Using the closure of faces for coordinates does not work in periodic geometries, so we index into the cell coordinates
27076858538eSMatthew G. Knepley   PetscCall(DMPlexGetRawFaces_Internal(dm, ct, order, &numFaces, &faceTypes, &faceSizes, &faces));
27086858538eSMatthew G. Knepley   PetscCall(DMPlexGetCellCoordinates(dm, cell, &isDG, &coordSize, &array, &coords));
27090ec8681fSMatthew G. Knepley   for (f = 0; f < numFaces; ++f) {
2710793a2a13SMatthew G. Knepley     PetscBool flip = isHybrid && f == 0 ? PETSC_TRUE : PETSC_FALSE; /* The first hybrid face is reversed */
2711793a2a13SMatthew G. Knepley 
27123f27a4e6SJed Brown     // If using zero as the origin vertex for each tetrahedron, an element far from the origin will have positive and
27133f27a4e6SJed Brown     // negative volumes that nearly cancel, thus incurring rounding error. Here we define origin[] as the first vertex
27143f27a4e6SJed Brown     // so that all tetrahedra have positive volume.
27159371c9d4SSatish Balay     if (f == 0)
27169371c9d4SSatish Balay       for (d = 0; d < dim; d++) origin[d] = PetscRealPart(coords[d]);
27176858538eSMatthew G. Knepley     switch (faceTypes[f]) {
2718ba2698f1SMatthew G. Knepley     case DM_POLYTOPE_TRIANGLE:
27190ec8681fSMatthew G. Knepley       for (d = 0; d < dim; ++d) {
27206858538eSMatthew G. Knepley         coordsTmp[0 * dim + d] = PetscRealPart(coords[faces[fOff + 0] * dim + d]) - origin[d];
27216858538eSMatthew G. Knepley         coordsTmp[1 * dim + d] = PetscRealPart(coords[faces[fOff + 1] * dim + d]) - origin[d];
27226858538eSMatthew G. Knepley         coordsTmp[2 * dim + d] = PetscRealPart(coords[faces[fOff + 2] * dim + d]) - origin[d];
27230ec8681fSMatthew G. Knepley       }
27240ec8681fSMatthew G. Knepley       Volume_Tetrahedron_Origin_Internal(&vtmp, coordsTmp);
27256858538eSMatthew G. Knepley       if (flip) vtmp = -vtmp;
27260ec8681fSMatthew G. Knepley       vsum += vtmp;
27274f25033aSJed Brown       if (centroid) { /* Centroid of OABC = (a+b+c)/4 */
27280ec8681fSMatthew G. Knepley         for (d = 0; d < dim; ++d) {
27291ee9d5ecSMatthew G. Knepley           for (p = 0; p < 3; ++p) centroid[d] += coordsTmp[p * dim + d] * vtmp;
27300ec8681fSMatthew G. Knepley         }
27310ec8681fSMatthew G. Knepley       }
27320ec8681fSMatthew G. Knepley       break;
2733ba2698f1SMatthew G. Knepley     case DM_POLYTOPE_QUADRILATERAL:
27349371c9d4SSatish Balay     case DM_POLYTOPE_SEG_PRISM_TENSOR: {
2735793a2a13SMatthew G. Knepley       PetscInt fv[4] = {0, 1, 2, 3};
2736793a2a13SMatthew G. Knepley 
2737793a2a13SMatthew G. Knepley       /* Side faces for hybrid cells are are stored as tensor products */
27389371c9d4SSatish Balay       if (isHybrid && f > 1) {
27399371c9d4SSatish Balay         fv[2] = 3;
27409371c9d4SSatish Balay         fv[3] = 2;
27419371c9d4SSatish Balay       }
27420ec8681fSMatthew G. Knepley       /* DO FOR PYRAMID */
27430ec8681fSMatthew G. Knepley       /* First tet */
27440ec8681fSMatthew G. Knepley       for (d = 0; d < dim; ++d) {
27456858538eSMatthew G. Knepley         coordsTmp[0 * dim + d] = PetscRealPart(coords[faces[fOff + fv[0]] * dim + d]) - origin[d];
27466858538eSMatthew G. Knepley         coordsTmp[1 * dim + d] = PetscRealPart(coords[faces[fOff + fv[1]] * dim + d]) - origin[d];
27476858538eSMatthew G. Knepley         coordsTmp[2 * dim + d] = PetscRealPart(coords[faces[fOff + fv[3]] * dim + d]) - origin[d];
27480ec8681fSMatthew G. Knepley       }
27490ec8681fSMatthew G. Knepley       Volume_Tetrahedron_Origin_Internal(&vtmp, coordsTmp);
27506858538eSMatthew G. Knepley       if (flip) vtmp = -vtmp;
27510ec8681fSMatthew G. Knepley       vsum += vtmp;
27520ec8681fSMatthew G. Knepley       if (centroid) {
27530ec8681fSMatthew G. Knepley         for (d = 0; d < dim; ++d) {
27540ec8681fSMatthew G. Knepley           for (p = 0; p < 3; ++p) centroid[d] += coordsTmp[p * dim + d] * vtmp;
27550ec8681fSMatthew G. Knepley         }
27560ec8681fSMatthew G. Knepley       }
27570ec8681fSMatthew G. Knepley       /* Second tet */
27580ec8681fSMatthew G. Knepley       for (d = 0; d < dim; ++d) {
27596858538eSMatthew G. Knepley         coordsTmp[0 * dim + d] = PetscRealPart(coords[faces[fOff + fv[1]] * dim + d]) - origin[d];
27606858538eSMatthew G. Knepley         coordsTmp[1 * dim + d] = PetscRealPart(coords[faces[fOff + fv[2]] * dim + d]) - origin[d];
27616858538eSMatthew G. Knepley         coordsTmp[2 * dim + d] = PetscRealPart(coords[faces[fOff + fv[3]] * dim + d]) - origin[d];
27620ec8681fSMatthew G. Knepley       }
27630ec8681fSMatthew G. Knepley       Volume_Tetrahedron_Origin_Internal(&vtmp, coordsTmp);
27646858538eSMatthew G. Knepley       if (flip) vtmp = -vtmp;
27650ec8681fSMatthew G. Knepley       vsum += vtmp;
27660ec8681fSMatthew G. Knepley       if (centroid) {
27670ec8681fSMatthew G. Knepley         for (d = 0; d < dim; ++d) {
27680ec8681fSMatthew G. Knepley           for (p = 0; p < 3; ++p) centroid[d] += coordsTmp[p * dim + d] * vtmp;
27690ec8681fSMatthew G. Knepley         }
27700ec8681fSMatthew G. Knepley       }
27710ec8681fSMatthew G. Knepley       break;
2772793a2a13SMatthew G. Knepley     }
2773d71ae5a4SJacob Faibussowitsch     default:
2774d71ae5a4SJacob Faibussowitsch       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle face %" PetscInt_FMT " of type %s", cone[f], DMPolytopeTypes[ct]);
27750ec8681fSMatthew G. Knepley     }
27766858538eSMatthew G. Knepley     fOff += faceSizes[f];
27770ec8681fSMatthew G. Knepley   }
27786858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreRawFaces_Internal(dm, ct, order, &numFaces, &faceTypes, &faceSizes, &faces));
27796858538eSMatthew G. Knepley   PetscCall(DMPlexRestoreCellCoordinates(dm, cell, &isDG, &coordSize, &array, &coords));
27808763be8eSMatthew G. Knepley   if (vol) *vol = PetscAbsReal(vsum);
27819371c9d4SSatish Balay   if (normal)
27829371c9d4SSatish Balay     for (d = 0; d < dim; ++d) normal[d] = 0.0;
27839371c9d4SSatish Balay   if (centroid)
27849371c9d4SSatish Balay     for (d = 0; d < dim; ++d) centroid[d] = centroid[d] / (vsum * 4) + origin[d];
27853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
27860ec8681fSMatthew G. Knepley }
27870ec8681fSMatthew G. Knepley 
2788834e62ceSMatthew G. Knepley /*@C
2789834e62ceSMatthew G. Knepley   DMPlexComputeCellGeometryFVM - Compute the volume for a given cell
2790834e62ceSMatthew G. Knepley 
279120f4b53cSBarry Smith   Collective
2792834e62ceSMatthew G. Knepley 
27934165533cSJose E. Roman   Input Parameters:
279420f4b53cSBarry Smith + dm   - the `DMPLEX`
2795834e62ceSMatthew G. Knepley - cell - the cell
2796834e62ceSMatthew G. Knepley 
27974165533cSJose E. Roman   Output Parameters:
279860225df5SJacob Faibussowitsch + vol      - the cell volume
2799cc08537eSMatthew G. Knepley . centroid - the cell centroid
2800cc08537eSMatthew G. Knepley - normal   - the cell normal, if appropriate
2801834e62ceSMatthew G. Knepley 
2802834e62ceSMatthew G. Knepley   Level: advanced
2803834e62ceSMatthew G. Knepley 
280420f4b53cSBarry Smith .seealso: `DMPLEX`, `DMGetCoordinateSection()`, `DMGetCoordinates()`
2805834e62ceSMatthew G. Knepley @*/
2806d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexComputeCellGeometryFVM(DM dm, PetscInt cell, PetscReal *vol, PetscReal centroid[], PetscReal normal[])
2807d71ae5a4SJacob Faibussowitsch {
28080ec8681fSMatthew G. Knepley   PetscInt depth, dim;
2809834e62ceSMatthew G. Knepley 
2810834e62ceSMatthew G. Knepley   PetscFunctionBegin;
28119566063dSJacob Faibussowitsch   PetscCall(DMPlexGetDepth(dm, &depth));
28129566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dim));
281308401ef6SPierre Jolivet   PetscCheck(depth == dim, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh must be interpolated");
28149566063dSJacob Faibussowitsch   PetscCall(DMPlexGetPointDepth(dm, cell, &depth));
2815011ea5d8SMatthew G. Knepley   switch (depth) {
2816d71ae5a4SJacob Faibussowitsch   case 0:
2817d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexComputeGeometryFVM_0D_Internal(dm, dim, cell, vol, centroid, normal));
2818d71ae5a4SJacob Faibussowitsch     break;
2819d71ae5a4SJacob Faibussowitsch   case 1:
2820d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexComputeGeometryFVM_1D_Internal(dm, dim, cell, vol, centroid, normal));
2821d71ae5a4SJacob Faibussowitsch     break;
2822d71ae5a4SJacob Faibussowitsch   case 2:
2823d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexComputeGeometryFVM_2D_Internal(dm, dim, cell, vol, centroid, normal));
2824d71ae5a4SJacob Faibussowitsch     break;
2825d71ae5a4SJacob Faibussowitsch   case 3:
2826d71ae5a4SJacob Faibussowitsch     PetscCall(DMPlexComputeGeometryFVM_3D_Internal(dm, dim, cell, vol, centroid, normal));
2827d71ae5a4SJacob Faibussowitsch     break;
2828d71ae5a4SJacob Faibussowitsch   default:
2829d71ae5a4SJacob Faibussowitsch     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Unsupported dimension %" PetscInt_FMT " (depth %" PetscInt_FMT ") for element geometry computation", dim, depth);
2830834e62ceSMatthew G. Knepley   }
28313ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2832834e62ceSMatthew G. Knepley }
2833113c68e6SMatthew G. Knepley 
2834c501906fSMatthew G. Knepley /*@
2835891a9168SMatthew G. Knepley   DMPlexComputeGeometryFVM - Computes the cell and face geometry for a finite volume method
2836891a9168SMatthew G. Knepley 
2837891a9168SMatthew G. Knepley   Input Parameter:
283820f4b53cSBarry Smith . dm - The `DMPLEX`
2839891a9168SMatthew G. Knepley 
2840891a9168SMatthew G. Knepley   Output Parameters:
284120f4b53cSBarry Smith + cellgeom - A `Vec` of `PetscFVCellGeom` data
284220f4b53cSBarry Smith - facegeom - A `Vec` of `PetscFVFaceGeom` data
2843891a9168SMatthew G. Knepley 
2844891a9168SMatthew G. Knepley   Level: developer
2845891a9168SMatthew G. Knepley 
284620f4b53cSBarry Smith .seealso: `DMPLEX`, `PetscFVFaceGeom`, `PetscFVCellGeom`
2847891a9168SMatthew G. Knepley @*/
2848d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexComputeGeometryFVM(DM dm, Vec *cellgeom, Vec *facegeom)
2849d71ae5a4SJacob Faibussowitsch {
2850113c68e6SMatthew G. Knepley   DM           dmFace, dmCell;
2851113c68e6SMatthew G. Knepley   DMLabel      ghostLabel;
2852113c68e6SMatthew G. Knepley   PetscSection sectionFace, sectionCell;
2853113c68e6SMatthew G. Knepley   PetscSection coordSection;
2854113c68e6SMatthew G. Knepley   Vec          coordinates;
2855113c68e6SMatthew G. Knepley   PetscScalar *fgeom, *cgeom;
2856113c68e6SMatthew G. Knepley   PetscReal    minradius, gminradius;
2857113c68e6SMatthew G. Knepley   PetscInt     dim, cStart, cEnd, cEndInterior, c, fStart, fEnd, f;
2858113c68e6SMatthew G. Knepley 
2859113c68e6SMatthew G. Knepley   PetscFunctionBegin;
28609566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dim));
28619566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateSection(dm, &coordSection));
28629566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
2863113c68e6SMatthew G. Knepley   /* Make cell centroids and volumes */
28649566063dSJacob Faibussowitsch   PetscCall(DMClone(dm, &dmCell));
28659566063dSJacob Faibussowitsch   PetscCall(DMSetCoordinateSection(dmCell, PETSC_DETERMINE, coordSection));
28669566063dSJacob Faibussowitsch   PetscCall(DMSetCoordinatesLocal(dmCell, coordinates));
28679566063dSJacob Faibussowitsch   PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &sectionCell));
28689566063dSJacob Faibussowitsch   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
28692827ebadSStefano Zampini   PetscCall(DMPlexGetCellTypeStratum(dm, DM_POLYTOPE_FV_GHOST, &cEndInterior, NULL));
28709566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetChart(sectionCell, cStart, cEnd));
28719566063dSJacob Faibussowitsch   for (c = cStart; c < cEnd; ++c) PetscCall(PetscSectionSetDof(sectionCell, c, (PetscInt)PetscCeilReal(((PetscReal)sizeof(PetscFVCellGeom)) / sizeof(PetscScalar))));
28729566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetUp(sectionCell));
28739566063dSJacob Faibussowitsch   PetscCall(DMSetLocalSection(dmCell, sectionCell));
28749566063dSJacob Faibussowitsch   PetscCall(PetscSectionDestroy(&sectionCell));
28759566063dSJacob Faibussowitsch   PetscCall(DMCreateLocalVector(dmCell, cellgeom));
2876485ad865SMatthew G. Knepley   if (cEndInterior < 0) cEndInterior = cEnd;
28779566063dSJacob Faibussowitsch   PetscCall(VecGetArray(*cellgeom, &cgeom));
2878113c68e6SMatthew G. Knepley   for (c = cStart; c < cEndInterior; ++c) {
2879113c68e6SMatthew G. Knepley     PetscFVCellGeom *cg;
2880113c68e6SMatthew G. Knepley 
28819566063dSJacob Faibussowitsch     PetscCall(DMPlexPointLocalRef(dmCell, c, cgeom, &cg));
28829566063dSJacob Faibussowitsch     PetscCall(PetscArrayzero(cg, 1));
28839566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeCellGeometryFVM(dmCell, c, &cg->volume, cg->centroid, NULL));
2884113c68e6SMatthew G. Knepley   }
2885113c68e6SMatthew G. Knepley   /* Compute face normals and minimum cell radius */
28869566063dSJacob Faibussowitsch   PetscCall(DMClone(dm, &dmFace));
28879566063dSJacob Faibussowitsch   PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &sectionFace));
28889566063dSJacob Faibussowitsch   PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
28899566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetChart(sectionFace, fStart, fEnd));
28909566063dSJacob Faibussowitsch   for (f = fStart; f < fEnd; ++f) PetscCall(PetscSectionSetDof(sectionFace, f, (PetscInt)PetscCeilReal(((PetscReal)sizeof(PetscFVFaceGeom)) / sizeof(PetscScalar))));
28919566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetUp(sectionFace));
28929566063dSJacob Faibussowitsch   PetscCall(DMSetLocalSection(dmFace, sectionFace));
28939566063dSJacob Faibussowitsch   PetscCall(PetscSectionDestroy(&sectionFace));
28949566063dSJacob Faibussowitsch   PetscCall(DMCreateLocalVector(dmFace, facegeom));
28959566063dSJacob Faibussowitsch   PetscCall(VecGetArray(*facegeom, &fgeom));
28969566063dSJacob Faibussowitsch   PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
2897113c68e6SMatthew G. Knepley   minradius = PETSC_MAX_REAL;
2898113c68e6SMatthew G. Knepley   for (f = fStart; f < fEnd; ++f) {
2899113c68e6SMatthew G. Knepley     PetscFVFaceGeom *fg;
2900113c68e6SMatthew G. Knepley     PetscReal        area;
2901412e9a14SMatthew G. Knepley     const PetscInt  *cells;
2902412e9a14SMatthew G. Knepley     PetscInt         ncells, ghost = -1, d, numChildren;
2903113c68e6SMatthew G. Knepley 
29049566063dSJacob Faibussowitsch     if (ghostLabel) PetscCall(DMLabelGetValue(ghostLabel, f, &ghost));
29059566063dSJacob Faibussowitsch     PetscCall(DMPlexGetTreeChildren(dm, f, &numChildren, NULL));
29069566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupport(dm, f, &cells));
29079566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupportSize(dm, f, &ncells));
2908412e9a14SMatthew G. Knepley     /* It is possible to get a face with no support when using partition overlap */
2909412e9a14SMatthew G. Knepley     if (!ncells || ghost >= 0 || numChildren) continue;
29109566063dSJacob Faibussowitsch     PetscCall(DMPlexPointLocalRef(dmFace, f, fgeom, &fg));
29119566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeCellGeometryFVM(dm, f, &area, fg->centroid, fg->normal));
2912113c68e6SMatthew G. Knepley     for (d = 0; d < dim; ++d) fg->normal[d] *= area;
2913113c68e6SMatthew G. Knepley     /* Flip face orientation if necessary to match ordering in support, and Update minimum radius */
2914113c68e6SMatthew G. Knepley     {
2915113c68e6SMatthew G. Knepley       PetscFVCellGeom *cL, *cR;
2916113c68e6SMatthew G. Knepley       PetscReal       *lcentroid, *rcentroid;
29170453c0cdSMatthew G. Knepley       PetscReal        l[3], r[3], v[3];
2918113c68e6SMatthew G. Knepley 
29199566063dSJacob Faibussowitsch       PetscCall(DMPlexPointLocalRead(dmCell, cells[0], cgeom, &cL));
2920113c68e6SMatthew G. Knepley       lcentroid = cells[0] >= cEndInterior ? fg->centroid : cL->centroid;
292106348e87SToby Isaac       if (ncells > 1) {
29229566063dSJacob Faibussowitsch         PetscCall(DMPlexPointLocalRead(dmCell, cells[1], cgeom, &cR));
2923113c68e6SMatthew G. Knepley         rcentroid = cells[1] >= cEndInterior ? fg->centroid : cR->centroid;
29249371c9d4SSatish Balay       } else {
292506348e87SToby Isaac         rcentroid = fg->centroid;
292606348e87SToby Isaac       }
29279566063dSJacob Faibussowitsch       PetscCall(DMLocalizeCoordinateReal_Internal(dm, dim, fg->centroid, lcentroid, l));
29289566063dSJacob Faibussowitsch       PetscCall(DMLocalizeCoordinateReal_Internal(dm, dim, fg->centroid, rcentroid, r));
29290453c0cdSMatthew G. Knepley       DMPlex_WaxpyD_Internal(dim, -1, l, r, v);
2930113c68e6SMatthew G. Knepley       if (DMPlex_DotRealD_Internal(dim, fg->normal, v) < 0) {
2931113c68e6SMatthew G. Knepley         for (d = 0; d < dim; ++d) fg->normal[d] = -fg->normal[d];
2932113c68e6SMatthew G. Knepley       }
2933113c68e6SMatthew G. Knepley       if (DMPlex_DotRealD_Internal(dim, fg->normal, v) <= 0) {
293463a3b9bcSJacob 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]);
293563a3b9bcSJacob 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]);
293663a3b9bcSJacob Faibussowitsch         SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Direction for face %" PetscInt_FMT " could not be fixed", f);
2937113c68e6SMatthew G. Knepley       }
2938113c68e6SMatthew G. Knepley       if (cells[0] < cEndInterior) {
2939113c68e6SMatthew G. Knepley         DMPlex_WaxpyD_Internal(dim, -1, fg->centroid, cL->centroid, v);
2940113c68e6SMatthew G. Knepley         minradius = PetscMin(minradius, DMPlex_NormD_Internal(dim, v));
2941113c68e6SMatthew G. Knepley       }
294206348e87SToby Isaac       if (ncells > 1 && cells[1] < cEndInterior) {
2943113c68e6SMatthew G. Knepley         DMPlex_WaxpyD_Internal(dim, -1, fg->centroid, cR->centroid, v);
2944113c68e6SMatthew G. Knepley         minradius = PetscMin(minradius, DMPlex_NormD_Internal(dim, v));
2945113c68e6SMatthew G. Knepley       }
2946113c68e6SMatthew G. Knepley     }
2947113c68e6SMatthew G. Knepley   }
29481c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(&minradius, &gminradius, 1, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)dm)));
29499566063dSJacob Faibussowitsch   PetscCall(DMPlexSetMinRadius(dm, gminradius));
2950113c68e6SMatthew G. Knepley   /* Compute centroids of ghost cells */
2951113c68e6SMatthew G. Knepley   for (c = cEndInterior; c < cEnd; ++c) {
2952113c68e6SMatthew G. Knepley     PetscFVFaceGeom *fg;
2953113c68e6SMatthew G. Knepley     const PetscInt  *cone, *support;
2954113c68e6SMatthew G. Knepley     PetscInt         coneSize, supportSize, s;
2955113c68e6SMatthew G. Knepley 
29569566063dSJacob Faibussowitsch     PetscCall(DMPlexGetConeSize(dmCell, c, &coneSize));
295763a3b9bcSJacob Faibussowitsch     PetscCheck(coneSize == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Ghost cell %" PetscInt_FMT " has cone size %" PetscInt_FMT " != 1", c, coneSize);
29589566063dSJacob Faibussowitsch     PetscCall(DMPlexGetCone(dmCell, c, &cone));
29599566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupportSize(dmCell, cone[0], &supportSize));
296063a3b9bcSJacob Faibussowitsch     PetscCheck(supportSize == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " has support size %" PetscInt_FMT " != 2", cone[0], supportSize);
29619566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupport(dmCell, cone[0], &support));
29629566063dSJacob Faibussowitsch     PetscCall(DMPlexPointLocalRef(dmFace, cone[0], fgeom, &fg));
2963113c68e6SMatthew G. Knepley     for (s = 0; s < 2; ++s) {
2964113c68e6SMatthew G. Knepley       /* Reflect ghost centroid across plane of face */
2965113c68e6SMatthew G. Knepley       if (support[s] == c) {
2966640bce14SSatish Balay         PetscFVCellGeom *ci;
2967113c68e6SMatthew G. Knepley         PetscFVCellGeom *cg;
2968113c68e6SMatthew G. Knepley         PetscReal        c2f[3], a;
2969113c68e6SMatthew G. Knepley 
29709566063dSJacob Faibussowitsch         PetscCall(DMPlexPointLocalRead(dmCell, support[(s + 1) % 2], cgeom, &ci));
2971113c68e6SMatthew G. Knepley         DMPlex_WaxpyD_Internal(dim, -1, ci->centroid, fg->centroid, c2f); /* cell to face centroid */
2972113c68e6SMatthew G. Knepley         a = DMPlex_DotRealD_Internal(dim, c2f, fg->normal) / DMPlex_DotRealD_Internal(dim, fg->normal, fg->normal);
29739566063dSJacob Faibussowitsch         PetscCall(DMPlexPointLocalRef(dmCell, support[s], cgeom, &cg));
2974113c68e6SMatthew G. Knepley         DMPlex_WaxpyD_Internal(dim, 2 * a, fg->normal, ci->centroid, cg->centroid);
2975113c68e6SMatthew G. Knepley         cg->volume = ci->volume;
2976113c68e6SMatthew G. Knepley       }
2977113c68e6SMatthew G. Knepley     }
2978113c68e6SMatthew G. Knepley   }
29799566063dSJacob Faibussowitsch   PetscCall(VecRestoreArray(*facegeom, &fgeom));
29809566063dSJacob Faibussowitsch   PetscCall(VecRestoreArray(*cellgeom, &cgeom));
29819566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&dmCell));
29829566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&dmFace));
29833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2984113c68e6SMatthew G. Knepley }
2985113c68e6SMatthew G. Knepley 
2986113c68e6SMatthew G. Knepley /*@C
2987113c68e6SMatthew G. Knepley   DMPlexGetMinRadius - Returns the minimum distance from any cell centroid to a face
2988113c68e6SMatthew G. Knepley 
298920f4b53cSBarry Smith   Not Collective
2990113c68e6SMatthew G. Knepley 
29914165533cSJose E. Roman   Input Parameter:
299220f4b53cSBarry Smith . dm - the `DMPLEX`
2993113c68e6SMatthew G. Knepley 
29944165533cSJose E. Roman   Output Parameter:
2995a5b23f4aSJose E. Roman . minradius - the minimum cell radius
2996113c68e6SMatthew G. Knepley 
2997113c68e6SMatthew G. Knepley   Level: developer
2998113c68e6SMatthew G. Knepley 
299920f4b53cSBarry Smith .seealso: `DMPLEX`, `DMGetCoordinates()`
3000113c68e6SMatthew G. Knepley @*/
3001d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexGetMinRadius(DM dm, PetscReal *minradius)
3002d71ae5a4SJacob Faibussowitsch {
3003113c68e6SMatthew G. Knepley   PetscFunctionBegin;
3004113c68e6SMatthew G. Knepley   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
30054f572ea9SToby Isaac   PetscAssertPointer(minradius, 2);
3006113c68e6SMatthew G. Knepley   *minradius = ((DM_Plex *)dm->data)->minradius;
30073ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3008113c68e6SMatthew G. Knepley }
3009113c68e6SMatthew G. Knepley 
3010113c68e6SMatthew G. Knepley /*@C
3011113c68e6SMatthew G. Knepley   DMPlexSetMinRadius - Sets the minimum distance from the cell centroid to a face
3012113c68e6SMatthew G. Knepley 
301320f4b53cSBarry Smith   Logically Collective
3014113c68e6SMatthew G. Knepley 
30154165533cSJose E. Roman   Input Parameters:
301620f4b53cSBarry Smith + dm        - the `DMPLEX`
3017a5b23f4aSJose E. Roman - minradius - the minimum cell radius
3018113c68e6SMatthew G. Knepley 
3019113c68e6SMatthew G. Knepley   Level: developer
3020113c68e6SMatthew G. Knepley 
302120f4b53cSBarry Smith .seealso: `DMPLEX`, `DMSetCoordinates()`
3022113c68e6SMatthew G. Knepley @*/
3023d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexSetMinRadius(DM dm, PetscReal minradius)
3024d71ae5a4SJacob Faibussowitsch {
3025113c68e6SMatthew G. Knepley   PetscFunctionBegin;
3026113c68e6SMatthew G. Knepley   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
3027113c68e6SMatthew G. Knepley   ((DM_Plex *)dm->data)->minradius = minradius;
30283ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3029113c68e6SMatthew G. Knepley }
3030856ac710SMatthew G. Knepley 
3031d71ae5a4SJacob Faibussowitsch static PetscErrorCode BuildGradientReconstruction_Internal(DM dm, PetscFV fvm, DM dmFace, PetscScalar *fgeom, DM dmCell, PetscScalar *cgeom)
3032d71ae5a4SJacob Faibussowitsch {
3033856ac710SMatthew G. Knepley   DMLabel      ghostLabel;
3034856ac710SMatthew G. Knepley   PetscScalar *dx, *grad, **gref;
3035856ac710SMatthew G. Knepley   PetscInt     dim, cStart, cEnd, c, cEndInterior, maxNumFaces;
3036856ac710SMatthew G. Knepley 
3037856ac710SMatthew G. Knepley   PetscFunctionBegin;
30389566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dim));
30399566063dSJacob Faibussowitsch   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
30402827ebadSStefano Zampini   PetscCall(DMPlexGetCellTypeStratum(dm, DM_POLYTOPE_FV_GHOST, &cEndInterior, NULL));
3041089217ebSMatthew G. Knepley   cEndInterior = cEndInterior < 0 ? cEnd : cEndInterior;
30429566063dSJacob Faibussowitsch   PetscCall(DMPlexGetMaxSizes(dm, &maxNumFaces, NULL));
30439566063dSJacob Faibussowitsch   PetscCall(PetscFVLeastSquaresSetMaxFaces(fvm, maxNumFaces));
30449566063dSJacob Faibussowitsch   PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
30459566063dSJacob Faibussowitsch   PetscCall(PetscMalloc3(maxNumFaces * dim, &dx, maxNumFaces * dim, &grad, maxNumFaces, &gref));
3046856ac710SMatthew G. Knepley   for (c = cStart; c < cEndInterior; c++) {
3047856ac710SMatthew G. Knepley     const PetscInt  *faces;
3048856ac710SMatthew G. Knepley     PetscInt         numFaces, usedFaces, f, d;
3049640bce14SSatish Balay     PetscFVCellGeom *cg;
3050856ac710SMatthew G. Knepley     PetscBool        boundary;
3051856ac710SMatthew G. Knepley     PetscInt         ghost;
3052856ac710SMatthew G. Knepley 
3053a79418b7SMatt McGurn     // do not attempt to compute a gradient reconstruction stencil in a ghost cell.  It will never be used
3054a79418b7SMatt McGurn     PetscCall(DMLabelGetValue(ghostLabel, c, &ghost));
3055a79418b7SMatt McGurn     if (ghost >= 0) continue;
3056a79418b7SMatt McGurn 
30579566063dSJacob Faibussowitsch     PetscCall(DMPlexPointLocalRead(dmCell, c, cgeom, &cg));
30589566063dSJacob Faibussowitsch     PetscCall(DMPlexGetConeSize(dm, c, &numFaces));
30599566063dSJacob Faibussowitsch     PetscCall(DMPlexGetCone(dm, c, &faces));
306063a3b9bcSJacob 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);
3061856ac710SMatthew G. Knepley     for (f = 0, usedFaces = 0; f < numFaces; ++f) {
3062640bce14SSatish Balay       PetscFVCellGeom *cg1;
3063856ac710SMatthew G. Knepley       PetscFVFaceGeom *fg;
3064856ac710SMatthew G. Knepley       const PetscInt  *fcells;
3065856ac710SMatthew G. Knepley       PetscInt         ncell, side;
3066856ac710SMatthew G. Knepley 
30679566063dSJacob Faibussowitsch       PetscCall(DMLabelGetValue(ghostLabel, faces[f], &ghost));
30689566063dSJacob Faibussowitsch       PetscCall(DMIsBoundaryPoint(dm, faces[f], &boundary));
3069856ac710SMatthew G. Knepley       if ((ghost >= 0) || boundary) continue;
30709566063dSJacob Faibussowitsch       PetscCall(DMPlexGetSupport(dm, faces[f], &fcells));
3071856ac710SMatthew G. Knepley       side  = (c != fcells[0]); /* c is on left=0 or right=1 of face */
3072856ac710SMatthew G. Knepley       ncell = fcells[!side];    /* the neighbor */
30739566063dSJacob Faibussowitsch       PetscCall(DMPlexPointLocalRef(dmFace, faces[f], fgeom, &fg));
30749566063dSJacob Faibussowitsch       PetscCall(DMPlexPointLocalRead(dmCell, ncell, cgeom, &cg1));
3075856ac710SMatthew G. Knepley       for (d = 0; d < dim; ++d) dx[usedFaces * dim + d] = cg1->centroid[d] - cg->centroid[d];
3076856ac710SMatthew G. Knepley       gref[usedFaces++] = fg->grad[side]; /* Gradient reconstruction term will go here */
3077856ac710SMatthew G. Knepley     }
307828b400f6SJacob Faibussowitsch     PetscCheck(usedFaces, PETSC_COMM_SELF, PETSC_ERR_USER, "Mesh contains isolated cell (no neighbors). Is it intentional?");
30799566063dSJacob Faibussowitsch     PetscCall(PetscFVComputeGradient(fvm, usedFaces, dx, grad));
3080856ac710SMatthew G. Knepley     for (f = 0, usedFaces = 0; f < numFaces; ++f) {
30819566063dSJacob Faibussowitsch       PetscCall(DMLabelGetValue(ghostLabel, faces[f], &ghost));
30829566063dSJacob Faibussowitsch       PetscCall(DMIsBoundaryPoint(dm, faces[f], &boundary));
3083856ac710SMatthew G. Knepley       if ((ghost >= 0) || boundary) continue;
3084856ac710SMatthew G. Knepley       for (d = 0; d < dim; ++d) gref[usedFaces][d] = grad[usedFaces * dim + d];
3085856ac710SMatthew G. Knepley       ++usedFaces;
3086856ac710SMatthew G. Knepley     }
3087856ac710SMatthew G. Knepley   }
30889566063dSJacob Faibussowitsch   PetscCall(PetscFree3(dx, grad, gref));
30893ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3090856ac710SMatthew G. Knepley }
3091856ac710SMatthew G. Knepley 
3092d71ae5a4SJacob Faibussowitsch static PetscErrorCode BuildGradientReconstruction_Internal_Tree(DM dm, PetscFV fvm, DM dmFace, PetscScalar *fgeom, DM dmCell, PetscScalar *cgeom)
3093d71ae5a4SJacob Faibussowitsch {
3094b81db932SToby Isaac   DMLabel      ghostLabel;
3095b81db932SToby Isaac   PetscScalar *dx, *grad, **gref;
3096b81db932SToby Isaac   PetscInt     dim, cStart, cEnd, c, cEndInterior, fStart, fEnd, f, nStart, nEnd, maxNumFaces = 0;
3097b81db932SToby Isaac   PetscSection neighSec;
3098b81db932SToby Isaac   PetscInt(*neighbors)[2];
3099b81db932SToby Isaac   PetscInt *counter;
3100b81db932SToby Isaac 
3101b81db932SToby Isaac   PetscFunctionBegin;
31029566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dim));
31039566063dSJacob Faibussowitsch   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
31042827ebadSStefano Zampini   PetscCall(DMPlexGetCellTypeStratum(dm, DM_POLYTOPE_FV_GHOST, &cEndInterior, NULL));
3105485ad865SMatthew G. Knepley   if (cEndInterior < 0) cEndInterior = cEnd;
31069566063dSJacob Faibussowitsch   PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &neighSec));
31079566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetChart(neighSec, cStart, cEndInterior));
31089566063dSJacob Faibussowitsch   PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
31099566063dSJacob Faibussowitsch   PetscCall(DMGetLabel(dm, "ghost", &ghostLabel));
3110b81db932SToby Isaac   for (f = fStart; f < fEnd; f++) {
3111b81db932SToby Isaac     const PetscInt *fcells;
3112b81db932SToby Isaac     PetscBool       boundary;
31135bc680faSToby Isaac     PetscInt        ghost = -1;
3114b81db932SToby Isaac     PetscInt        numChildren, numCells, c;
3115b81db932SToby Isaac 
31169566063dSJacob Faibussowitsch     if (ghostLabel) PetscCall(DMLabelGetValue(ghostLabel, f, &ghost));
31179566063dSJacob Faibussowitsch     PetscCall(DMIsBoundaryPoint(dm, f, &boundary));
31189566063dSJacob Faibussowitsch     PetscCall(DMPlexGetTreeChildren(dm, f, &numChildren, NULL));
3119b81db932SToby Isaac     if ((ghost >= 0) || boundary || numChildren) continue;
31209566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupportSize(dm, f, &numCells));
312106348e87SToby Isaac     if (numCells == 2) {
31229566063dSJacob Faibussowitsch       PetscCall(DMPlexGetSupport(dm, f, &fcells));
3123b81db932SToby Isaac       for (c = 0; c < 2; c++) {
3124b81db932SToby Isaac         PetscInt cell = fcells[c];
3125b81db932SToby Isaac 
312648a46eb9SPierre Jolivet         if (cell >= cStart && cell < cEndInterior) PetscCall(PetscSectionAddDof(neighSec, cell, 1));
3127b81db932SToby Isaac       }
3128b81db932SToby Isaac     }
312906348e87SToby Isaac   }
31309566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetUp(neighSec));
31319566063dSJacob Faibussowitsch   PetscCall(PetscSectionGetMaxDof(neighSec, &maxNumFaces));
31329566063dSJacob Faibussowitsch   PetscCall(PetscFVLeastSquaresSetMaxFaces(fvm, maxNumFaces));
3133b81db932SToby Isaac   nStart = 0;
31349566063dSJacob Faibussowitsch   PetscCall(PetscSectionGetStorageSize(neighSec, &nEnd));
31359566063dSJacob Faibussowitsch   PetscCall(PetscMalloc1((nEnd - nStart), &neighbors));
31369566063dSJacob Faibussowitsch   PetscCall(PetscCalloc1((cEndInterior - cStart), &counter));
3137b81db932SToby Isaac   for (f = fStart; f < fEnd; f++) {
3138b81db932SToby Isaac     const PetscInt *fcells;
3139b81db932SToby Isaac     PetscBool       boundary;
31405bc680faSToby Isaac     PetscInt        ghost = -1;
3141b81db932SToby Isaac     PetscInt        numChildren, numCells, c;
3142b81db932SToby Isaac 
31439566063dSJacob Faibussowitsch     if (ghostLabel) PetscCall(DMLabelGetValue(ghostLabel, f, &ghost));
31449566063dSJacob Faibussowitsch     PetscCall(DMIsBoundaryPoint(dm, f, &boundary));
31459566063dSJacob Faibussowitsch     PetscCall(DMPlexGetTreeChildren(dm, f, &numChildren, NULL));
3146b81db932SToby Isaac     if ((ghost >= 0) || boundary || numChildren) continue;
31479566063dSJacob Faibussowitsch     PetscCall(DMPlexGetSupportSize(dm, f, &numCells));
314806348e87SToby Isaac     if (numCells == 2) {
31499566063dSJacob Faibussowitsch       PetscCall(DMPlexGetSupport(dm, f, &fcells));
3150b81db932SToby Isaac       for (c = 0; c < 2; c++) {
3151b81db932SToby Isaac         PetscInt cell = fcells[c], off;
3152b81db932SToby Isaac 
3153e6885bbbSToby Isaac         if (cell >= cStart && cell < cEndInterior) {
31549566063dSJacob Faibussowitsch           PetscCall(PetscSectionGetOffset(neighSec, cell, &off));
3155b81db932SToby Isaac           off += counter[cell - cStart]++;
3156b81db932SToby Isaac           neighbors[off][0] = f;
3157b81db932SToby Isaac           neighbors[off][1] = fcells[1 - c];
3158b81db932SToby Isaac         }
3159b81db932SToby Isaac       }
3160b81db932SToby Isaac     }
316106348e87SToby Isaac   }
31629566063dSJacob Faibussowitsch   PetscCall(PetscFree(counter));
31639566063dSJacob Faibussowitsch   PetscCall(PetscMalloc3(maxNumFaces * dim, &dx, maxNumFaces * dim, &grad, maxNumFaces, &gref));
3164b81db932SToby Isaac   for (c = cStart; c < cEndInterior; c++) {
3165317218b9SToby Isaac     PetscInt         numFaces, f, d, off, ghost = -1;
3166640bce14SSatish Balay     PetscFVCellGeom *cg;
3167b81db932SToby Isaac 
31689566063dSJacob Faibussowitsch     PetscCall(DMPlexPointLocalRead(dmCell, c, cgeom, &cg));
31699566063dSJacob Faibussowitsch     PetscCall(PetscSectionGetDof(neighSec, c, &numFaces));
31709566063dSJacob Faibussowitsch     PetscCall(PetscSectionGetOffset(neighSec, c, &off));
3171a79418b7SMatt McGurn 
3172a79418b7SMatt McGurn     // do not attempt to compute a gradient reconstruction stencil in a ghost cell.  It will never be used
31739566063dSJacob Faibussowitsch     if (ghostLabel) PetscCall(DMLabelGetValue(ghostLabel, c, &ghost));
3174a79418b7SMatt McGurn     if (ghost >= 0) continue;
3175a79418b7SMatt McGurn 
317663a3b9bcSJacob 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);
3177b81db932SToby Isaac     for (f = 0; f < numFaces; ++f) {
3178640bce14SSatish Balay       PetscFVCellGeom *cg1;
3179b81db932SToby Isaac       PetscFVFaceGeom *fg;
3180b81db932SToby Isaac       const PetscInt  *fcells;
3181b81db932SToby Isaac       PetscInt         ncell, side, nface;
3182b81db932SToby Isaac 
3183b81db932SToby Isaac       nface = neighbors[off + f][0];
3184b81db932SToby Isaac       ncell = neighbors[off + f][1];
31859566063dSJacob Faibussowitsch       PetscCall(DMPlexGetSupport(dm, nface, &fcells));
3186b81db932SToby Isaac       side = (c != fcells[0]);
31879566063dSJacob Faibussowitsch       PetscCall(DMPlexPointLocalRef(dmFace, nface, fgeom, &fg));
31889566063dSJacob Faibussowitsch       PetscCall(DMPlexPointLocalRead(dmCell, ncell, cgeom, &cg1));
3189b81db932SToby Isaac       for (d = 0; d < dim; ++d) dx[f * dim + d] = cg1->centroid[d] - cg->centroid[d];
3190b81db932SToby Isaac       gref[f] = fg->grad[side]; /* Gradient reconstruction term will go here */
3191b81db932SToby Isaac     }
31929566063dSJacob Faibussowitsch     PetscCall(PetscFVComputeGradient(fvm, numFaces, dx, grad));
3193b81db932SToby Isaac     for (f = 0; f < numFaces; ++f) {
3194b81db932SToby Isaac       for (d = 0; d < dim; ++d) gref[f][d] = grad[f * dim + d];
3195b81db932SToby Isaac     }
3196b81db932SToby Isaac   }
31979566063dSJacob Faibussowitsch   PetscCall(PetscFree3(dx, grad, gref));
31989566063dSJacob Faibussowitsch   PetscCall(PetscSectionDestroy(&neighSec));
31999566063dSJacob Faibussowitsch   PetscCall(PetscFree(neighbors));
32003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3201b81db932SToby Isaac }
3202b81db932SToby Isaac 
3203856ac710SMatthew G. Knepley /*@
3204856ac710SMatthew G. Knepley   DMPlexComputeGradientFVM - Compute geometric factors for gradient reconstruction, which are stored in the geometry data, and compute layout for gradient data
3205856ac710SMatthew G. Knepley 
320620f4b53cSBarry Smith   Collective
3207856ac710SMatthew G. Knepley 
32084165533cSJose E. Roman   Input Parameters:
320920f4b53cSBarry Smith + dm           - The `DMPLEX`
321020f4b53cSBarry Smith . fvm          - The `PetscFV`
321120f4b53cSBarry Smith - cellGeometry - The face geometry from `DMPlexComputeCellGeometryFVM()`
3212856ac710SMatthew G. Knepley 
32136b867d5aSJose E. Roman   Input/Output Parameter:
321420f4b53cSBarry Smith . faceGeometry - The face geometry from `DMPlexComputeFaceGeometryFVM()`; on output
32156b867d5aSJose E. Roman                  the geometric factors for gradient calculation are inserted
32166b867d5aSJose E. Roman 
32176b867d5aSJose E. Roman   Output Parameter:
321820f4b53cSBarry Smith . dmGrad - The `DM` describing the layout of gradient data
3219856ac710SMatthew G. Knepley 
3220856ac710SMatthew G. Knepley   Level: developer
3221856ac710SMatthew G. Knepley 
322220f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexGetFaceGeometryFVM()`, `DMPlexGetCellGeometryFVM()`
3223856ac710SMatthew G. Knepley @*/
3224d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexComputeGradientFVM(DM dm, PetscFV fvm, Vec faceGeometry, Vec cellGeometry, DM *dmGrad)
3225d71ae5a4SJacob Faibussowitsch {
3226856ac710SMatthew G. Knepley   DM           dmFace, dmCell;
3227856ac710SMatthew G. Knepley   PetscScalar *fgeom, *cgeom;
3228b81db932SToby Isaac   PetscSection sectionGrad, parentSection;
3229856ac710SMatthew G. Knepley   PetscInt     dim, pdim, cStart, cEnd, cEndInterior, c;
3230856ac710SMatthew G. Knepley 
3231856ac710SMatthew G. Knepley   PetscFunctionBegin;
32329566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dim));
32339566063dSJacob Faibussowitsch   PetscCall(PetscFVGetNumComponents(fvm, &pdim));
32349566063dSJacob Faibussowitsch   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
32352827ebadSStefano Zampini   PetscCall(DMPlexGetCellTypeStratum(dm, DM_POLYTOPE_FV_GHOST, &cEndInterior, NULL));
3236856ac710SMatthew G. Knepley   /* Construct the interpolant corresponding to each face from the least-square solution over the cell neighborhood */
32379566063dSJacob Faibussowitsch   PetscCall(VecGetDM(faceGeometry, &dmFace));
32389566063dSJacob Faibussowitsch   PetscCall(VecGetDM(cellGeometry, &dmCell));
32399566063dSJacob Faibussowitsch   PetscCall(VecGetArray(faceGeometry, &fgeom));
32409566063dSJacob Faibussowitsch   PetscCall(VecGetArray(cellGeometry, &cgeom));
32419566063dSJacob Faibussowitsch   PetscCall(DMPlexGetTree(dm, &parentSection, NULL, NULL, NULL, NULL));
3242b81db932SToby Isaac   if (!parentSection) {
32439566063dSJacob Faibussowitsch     PetscCall(BuildGradientReconstruction_Internal(dm, fvm, dmFace, fgeom, dmCell, cgeom));
3244b5a3613cSMatthew G. Knepley   } else {
32459566063dSJacob Faibussowitsch     PetscCall(BuildGradientReconstruction_Internal_Tree(dm, fvm, dmFace, fgeom, dmCell, cgeom));
3246b81db932SToby Isaac   }
32479566063dSJacob Faibussowitsch   PetscCall(VecRestoreArray(faceGeometry, &fgeom));
32489566063dSJacob Faibussowitsch   PetscCall(VecRestoreArray(cellGeometry, &cgeom));
3249856ac710SMatthew G. Knepley   /* Create storage for gradients */
32509566063dSJacob Faibussowitsch   PetscCall(DMClone(dm, dmGrad));
32519566063dSJacob Faibussowitsch   PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &sectionGrad));
32529566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetChart(sectionGrad, cStart, cEnd));
32539566063dSJacob Faibussowitsch   for (c = cStart; c < cEnd; ++c) PetscCall(PetscSectionSetDof(sectionGrad, c, pdim * dim));
32549566063dSJacob Faibussowitsch   PetscCall(PetscSectionSetUp(sectionGrad));
32559566063dSJacob Faibussowitsch   PetscCall(DMSetLocalSection(*dmGrad, sectionGrad));
32569566063dSJacob Faibussowitsch   PetscCall(PetscSectionDestroy(&sectionGrad));
32573ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3258856ac710SMatthew G. Knepley }
3259b27d5b9eSToby Isaac 
3260c501906fSMatthew G. Knepley /*@
3261c501906fSMatthew G. Knepley   DMPlexGetDataFVM - Retrieve precomputed cell geometry
3262c501906fSMatthew G. Knepley 
326320f4b53cSBarry Smith   Collective
3264c501906fSMatthew G. Knepley 
32654165533cSJose E. Roman   Input Parameters:
326620f4b53cSBarry Smith + dm - The `DM`
326720f4b53cSBarry Smith - fv - The `PetscFV`
3268c501906fSMatthew G. Knepley 
3269c501906fSMatthew G. Knepley   Output Parameters:
327060225df5SJacob Faibussowitsch + cellgeom - The cell geometry
327160225df5SJacob Faibussowitsch . facegeom - The face geometry
32726b867d5aSJose E. Roman - gradDM   - The gradient matrices
3273c501906fSMatthew G. Knepley 
3274c501906fSMatthew G. Knepley   Level: developer
3275c501906fSMatthew G. Knepley 
327620f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexComputeGeometryFVM()`
3277c501906fSMatthew G. Knepley @*/
3278d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexGetDataFVM(DM dm, PetscFV fv, Vec *cellgeom, Vec *facegeom, DM *gradDM)
3279d71ae5a4SJacob Faibussowitsch {
3280b27d5b9eSToby Isaac   PetscObject cellgeomobj, facegeomobj;
3281b27d5b9eSToby Isaac 
3282b27d5b9eSToby Isaac   PetscFunctionBegin;
32839566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject)dm, "DMPlex_cellgeom_fvm", &cellgeomobj));
3284b27d5b9eSToby Isaac   if (!cellgeomobj) {
3285b27d5b9eSToby Isaac     Vec cellgeomInt, facegeomInt;
3286b27d5b9eSToby Isaac 
32879566063dSJacob Faibussowitsch     PetscCall(DMPlexComputeGeometryFVM(dm, &cellgeomInt, &facegeomInt));
32889566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject)dm, "DMPlex_cellgeom_fvm", (PetscObject)cellgeomInt));
32899566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject)dm, "DMPlex_facegeom_fvm", (PetscObject)facegeomInt));
32909566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&cellgeomInt));
32919566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&facegeomInt));
32929566063dSJacob Faibussowitsch     PetscCall(PetscObjectQuery((PetscObject)dm, "DMPlex_cellgeom_fvm", &cellgeomobj));
3293b27d5b9eSToby Isaac   }
32949566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject)dm, "DMPlex_facegeom_fvm", &facegeomobj));
3295b27d5b9eSToby Isaac   if (cellgeom) *cellgeom = (Vec)cellgeomobj;
3296b27d5b9eSToby Isaac   if (facegeom) *facegeom = (Vec)facegeomobj;
3297b27d5b9eSToby Isaac   if (gradDM) {
3298b27d5b9eSToby Isaac     PetscObject gradobj;
3299b27d5b9eSToby Isaac     PetscBool   computeGradients;
3300b27d5b9eSToby Isaac 
33019566063dSJacob Faibussowitsch     PetscCall(PetscFVGetComputeGradients(fv, &computeGradients));
3302b27d5b9eSToby Isaac     if (!computeGradients) {
3303b27d5b9eSToby Isaac       *gradDM = NULL;
33043ba16761SJacob Faibussowitsch       PetscFunctionReturn(PETSC_SUCCESS);
3305b27d5b9eSToby Isaac     }
33069566063dSJacob Faibussowitsch     PetscCall(PetscObjectQuery((PetscObject)dm, "DMPlex_dmgrad_fvm", &gradobj));
3307b27d5b9eSToby Isaac     if (!gradobj) {
3308b27d5b9eSToby Isaac       DM dmGradInt;
3309b27d5b9eSToby Isaac 
33109566063dSJacob Faibussowitsch       PetscCall(DMPlexComputeGradientFVM(dm, fv, (Vec)facegeomobj, (Vec)cellgeomobj, &dmGradInt));
33119566063dSJacob Faibussowitsch       PetscCall(PetscObjectCompose((PetscObject)dm, "DMPlex_dmgrad_fvm", (PetscObject)dmGradInt));
33129566063dSJacob Faibussowitsch       PetscCall(DMDestroy(&dmGradInt));
33139566063dSJacob Faibussowitsch       PetscCall(PetscObjectQuery((PetscObject)dm, "DMPlex_dmgrad_fvm", &gradobj));
3314b27d5b9eSToby Isaac     }
3315b27d5b9eSToby Isaac     *gradDM = (DM)gradobj;
3316b27d5b9eSToby Isaac   }
33173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3318b27d5b9eSToby Isaac }
3319d6143a4eSToby Isaac 
3320d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexCoordinatesToReference_NewtonUpdate(PetscInt dimC, PetscInt dimR, PetscScalar *J, PetscScalar *invJ, PetscScalar *work, PetscReal *resNeg, PetscReal *guess)
3321d71ae5a4SJacob Faibussowitsch {
33229d150b73SToby Isaac   PetscInt l, m;
33239d150b73SToby Isaac 
3324cd345991SToby Isaac   PetscFunctionBeginHot;
33259d150b73SToby Isaac   if (dimC == dimR && dimR <= 3) {
33269d150b73SToby Isaac     /* invert Jacobian, multiply */
33279d150b73SToby Isaac     PetscScalar det, idet;
33289d150b73SToby Isaac 
33299d150b73SToby Isaac     switch (dimR) {
3330d71ae5a4SJacob Faibussowitsch     case 1:
3331d71ae5a4SJacob Faibussowitsch       invJ[0] = 1. / J[0];
3332d71ae5a4SJacob Faibussowitsch       break;
33339d150b73SToby Isaac     case 2:
33349d150b73SToby Isaac       det     = J[0] * J[3] - J[1] * J[2];
33359d150b73SToby Isaac       idet    = 1. / det;
33369d150b73SToby Isaac       invJ[0] = J[3] * idet;
33379d150b73SToby Isaac       invJ[1] = -J[1] * idet;
33389d150b73SToby Isaac       invJ[2] = -J[2] * idet;
33399d150b73SToby Isaac       invJ[3] = J[0] * idet;
33409d150b73SToby Isaac       break;
33419371c9d4SSatish Balay     case 3: {
33429d150b73SToby Isaac       invJ[0] = J[4] * J[8] - J[5] * J[7];
33439d150b73SToby Isaac       invJ[1] = J[2] * J[7] - J[1] * J[8];
33449d150b73SToby Isaac       invJ[2] = J[1] * J[5] - J[2] * J[4];
33459d150b73SToby Isaac       det     = invJ[0] * J[0] + invJ[1] * J[3] + invJ[2] * J[6];
33469d150b73SToby Isaac       idet    = 1. / det;
33479d150b73SToby Isaac       invJ[0] *= idet;
33489d150b73SToby Isaac       invJ[1] *= idet;
33499d150b73SToby Isaac       invJ[2] *= idet;
33509d150b73SToby Isaac       invJ[3] = idet * (J[5] * J[6] - J[3] * J[8]);
33519d150b73SToby Isaac       invJ[4] = idet * (J[0] * J[8] - J[2] * J[6]);
33529d150b73SToby Isaac       invJ[5] = idet * (J[2] * J[3] - J[0] * J[5]);
33539d150b73SToby Isaac       invJ[6] = idet * (J[3] * J[7] - J[4] * J[6]);
33549d150b73SToby Isaac       invJ[7] = idet * (J[1] * J[6] - J[0] * J[7]);
33559d150b73SToby Isaac       invJ[8] = idet * (J[0] * J[4] - J[1] * J[3]);
33569371c9d4SSatish Balay     } break;
33579d150b73SToby Isaac     }
33589d150b73SToby Isaac     for (l = 0; l < dimR; l++) {
3359ad540459SPierre Jolivet       for (m = 0; m < dimC; m++) guess[l] += PetscRealPart(invJ[l * dimC + m]) * resNeg[m];
33609d150b73SToby Isaac     }
33619d150b73SToby Isaac   } else {
33629d150b73SToby Isaac #if defined(PETSC_USE_COMPLEX)
33639d150b73SToby Isaac     char transpose = 'C';
33649d150b73SToby Isaac #else
33659d150b73SToby Isaac     char transpose = 'T';
33669d150b73SToby Isaac #endif
33679d150b73SToby Isaac     PetscBLASInt m        = dimR;
33689d150b73SToby Isaac     PetscBLASInt n        = dimC;
33699d150b73SToby Isaac     PetscBLASInt one      = 1;
33709d150b73SToby Isaac     PetscBLASInt worksize = dimR * dimC, info;
33719d150b73SToby Isaac 
3372ad540459SPierre Jolivet     for (l = 0; l < dimC; l++) invJ[l] = resNeg[l];
33739d150b73SToby Isaac 
3374792fecdfSBarry Smith     PetscCallBLAS("LAPACKgels", LAPACKgels_(&transpose, &m, &n, &one, J, &m, invJ, &n, work, &worksize, &info));
337508401ef6SPierre Jolivet     PetscCheck(info == 0, PETSC_COMM_SELF, PETSC_ERR_LIB, "Bad argument to GELS");
33769d150b73SToby Isaac 
3377ad540459SPierre Jolivet     for (l = 0; l < dimR; l++) guess[l] += PetscRealPart(invJ[l]);
33789d150b73SToby Isaac   }
33793ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
33809d150b73SToby Isaac }
33819d150b73SToby Isaac 
3382d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexCoordinatesToReference_Tensor(DM dm, PetscInt cell, PetscInt numPoints, const PetscReal realCoords[], PetscReal refCoords[], Vec coords, PetscInt dimC, PetscInt dimR)
3383d71ae5a4SJacob Faibussowitsch {
3384c0cbe899SToby Isaac   PetscInt     coordSize, i, j, k, l, m, maxIts = 7, numV = (1 << dimR);
33859d150b73SToby Isaac   PetscScalar *coordsScalar = NULL;
33869d150b73SToby Isaac   PetscReal   *cellData, *cellCoords, *cellCoeffs, *extJ, *resNeg;
33879d150b73SToby Isaac   PetscScalar *J, *invJ, *work;
33889d150b73SToby Isaac 
33899d150b73SToby Isaac   PetscFunctionBegin;
33909d150b73SToby Isaac   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
33919566063dSJacob Faibussowitsch   PetscCall(DMPlexVecGetClosure(dm, NULL, coords, cell, &coordSize, &coordsScalar));
33921dca8a05SBarry Smith   PetscCheck(coordSize >= dimC * numV, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Expecting at least %" PetscInt_FMT " coordinates, got %" PetscInt_FMT, dimC * (1 << dimR), coordSize);
33939566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, 2 * coordSize + dimR + dimC, MPIU_REAL, &cellData));
33949566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, 3 * dimR * dimC, MPIU_SCALAR, &J));
33959d150b73SToby Isaac   cellCoords = &cellData[0];
33969d150b73SToby Isaac   cellCoeffs = &cellData[coordSize];
33979d150b73SToby Isaac   extJ       = &cellData[2 * coordSize];
33989d150b73SToby Isaac   resNeg     = &cellData[2 * coordSize + dimR];
33999d150b73SToby Isaac   invJ       = &J[dimR * dimC];
34009d150b73SToby Isaac   work       = &J[2 * dimR * dimC];
34019d150b73SToby Isaac   if (dimR == 2) {
34029d150b73SToby Isaac     const PetscInt zToPlex[4] = {0, 1, 3, 2};
34039d150b73SToby Isaac 
34049d150b73SToby Isaac     for (i = 0; i < 4; i++) {
34059d150b73SToby Isaac       PetscInt plexI = zToPlex[i];
34069d150b73SToby Isaac 
3407ad540459SPierre Jolivet       for (j = 0; j < dimC; j++) cellCoords[dimC * i + j] = PetscRealPart(coordsScalar[dimC * plexI + j]);
34089d150b73SToby Isaac     }
34099d150b73SToby Isaac   } else if (dimR == 3) {
34109d150b73SToby Isaac     const PetscInt zToPlex[8] = {0, 3, 1, 2, 4, 5, 7, 6};
34119d150b73SToby Isaac 
34129d150b73SToby Isaac     for (i = 0; i < 8; i++) {
34139d150b73SToby Isaac       PetscInt plexI = zToPlex[i];
34149d150b73SToby Isaac 
3415ad540459SPierre Jolivet       for (j = 0; j < dimC; j++) cellCoords[dimC * i + j] = PetscRealPart(coordsScalar[dimC * plexI + j]);
34169d150b73SToby Isaac     }
34179d150b73SToby Isaac   } else {
3418ad540459SPierre Jolivet     for (i = 0; i < coordSize; i++) cellCoords[i] = PetscRealPart(coordsScalar[i]);
34199d150b73SToby Isaac   }
34209d150b73SToby Isaac   /* Perform the shuffling transform that converts values at the corners of [-1,1]^d to coefficients */
34219d150b73SToby Isaac   for (i = 0; i < dimR; i++) {
34229d150b73SToby Isaac     PetscReal *swap;
34239d150b73SToby Isaac 
34249d150b73SToby Isaac     for (j = 0; j < (numV / 2); j++) {
34259d150b73SToby Isaac       for (k = 0; k < dimC; k++) {
34269d150b73SToby Isaac         cellCoeffs[dimC * j + k]                = 0.5 * (cellCoords[dimC * (2 * j + 1) + k] + cellCoords[dimC * 2 * j + k]);
34279d150b73SToby Isaac         cellCoeffs[dimC * (j + (numV / 2)) + k] = 0.5 * (cellCoords[dimC * (2 * j + 1) + k] - cellCoords[dimC * 2 * j + k]);
34289d150b73SToby Isaac       }
34299d150b73SToby Isaac     }
34309d150b73SToby Isaac 
34319d150b73SToby Isaac     if (i < dimR - 1) {
34329d150b73SToby Isaac       swap       = cellCoeffs;
34339d150b73SToby Isaac       cellCoeffs = cellCoords;
34349d150b73SToby Isaac       cellCoords = swap;
34359d150b73SToby Isaac     }
34369d150b73SToby Isaac   }
34379566063dSJacob Faibussowitsch   PetscCall(PetscArrayzero(refCoords, numPoints * dimR));
34389d150b73SToby Isaac   for (j = 0; j < numPoints; j++) {
34399d150b73SToby Isaac     for (i = 0; i < maxIts; i++) {
34409d150b73SToby Isaac       PetscReal *guess = &refCoords[dimR * j];
34419d150b73SToby Isaac 
34429d150b73SToby Isaac       /* compute -residual and Jacobian */
3443ad540459SPierre Jolivet       for (k = 0; k < dimC; k++) resNeg[k] = realCoords[dimC * j + k];
3444ad540459SPierre Jolivet       for (k = 0; k < dimC * dimR; k++) J[k] = 0.;
34459d150b73SToby Isaac       for (k = 0; k < numV; k++) {
34469d150b73SToby Isaac         PetscReal extCoord = 1.;
34479d150b73SToby Isaac         for (l = 0; l < dimR; l++) {
34489d150b73SToby Isaac           PetscReal coord = guess[l];
34499d150b73SToby Isaac           PetscInt  dep   = (k & (1 << l)) >> l;
34509d150b73SToby Isaac 
34519d150b73SToby Isaac           extCoord *= dep * coord + !dep;
34529d150b73SToby Isaac           extJ[l] = dep;
34539d150b73SToby Isaac 
34549d150b73SToby Isaac           for (m = 0; m < dimR; m++) {
34559d150b73SToby Isaac             PetscReal coord = guess[m];
34569d150b73SToby Isaac             PetscInt  dep   = ((k & (1 << m)) >> m) && (m != l);
34579d150b73SToby Isaac             PetscReal mult  = dep * coord + !dep;
34589d150b73SToby Isaac 
34599d150b73SToby Isaac             extJ[l] *= mult;
34609d150b73SToby Isaac           }
34619d150b73SToby Isaac         }
34629d150b73SToby Isaac         for (l = 0; l < dimC; l++) {
34639d150b73SToby Isaac           PetscReal coeff = cellCoeffs[dimC * k + l];
34649d150b73SToby Isaac 
34659d150b73SToby Isaac           resNeg[l] -= coeff * extCoord;
3466ad540459SPierre Jolivet           for (m = 0; m < dimR; m++) J[dimR * l + m] += coeff * extJ[m];
34679d150b73SToby Isaac         }
34689d150b73SToby Isaac       }
346976bd3646SJed Brown       if (0 && PetscDefined(USE_DEBUG)) {
34700611203eSToby Isaac         PetscReal maxAbs = 0.;
34710611203eSToby Isaac 
3472ad540459SPierre Jolivet         for (l = 0; l < dimC; l++) maxAbs = PetscMax(maxAbs, PetscAbsReal(resNeg[l]));
347363a3b9bcSJacob Faibussowitsch         PetscCall(PetscInfo(dm, "cell %" PetscInt_FMT ", point %" PetscInt_FMT ", iter %" PetscInt_FMT ": res %g\n", cell, j, i, (double)maxAbs));
34740611203eSToby Isaac       }
34759d150b73SToby Isaac 
34769566063dSJacob Faibussowitsch       PetscCall(DMPlexCoordinatesToReference_NewtonUpdate(dimC, dimR, J, invJ, work, resNeg, guess));
34779d150b73SToby Isaac     }
34789d150b73SToby Isaac   }
34799566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, 3 * dimR * dimC, MPIU_SCALAR, &J));
34809566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, 2 * coordSize + dimR + dimC, MPIU_REAL, &cellData));
34819566063dSJacob Faibussowitsch   PetscCall(DMPlexVecRestoreClosure(dm, NULL, coords, cell, &coordSize, &coordsScalar));
34823ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
34839d150b73SToby Isaac }
34849d150b73SToby Isaac 
3485d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexReferenceToCoordinates_Tensor(DM dm, PetscInt cell, PetscInt numPoints, const PetscReal refCoords[], PetscReal realCoords[], Vec coords, PetscInt dimC, PetscInt dimR)
3486d71ae5a4SJacob Faibussowitsch {
34879d150b73SToby Isaac   PetscInt     coordSize, i, j, k, l, numV = (1 << dimR);
34889d150b73SToby Isaac   PetscScalar *coordsScalar = NULL;
34899d150b73SToby Isaac   PetscReal   *cellData, *cellCoords, *cellCoeffs;
34909d150b73SToby Isaac 
34919d150b73SToby Isaac   PetscFunctionBegin;
34929d150b73SToby Isaac   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
34939566063dSJacob Faibussowitsch   PetscCall(DMPlexVecGetClosure(dm, NULL, coords, cell, &coordSize, &coordsScalar));
34941dca8a05SBarry Smith   PetscCheck(coordSize >= dimC * numV, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Expecting at least %" PetscInt_FMT " coordinates, got %" PetscInt_FMT, dimC * (1 << dimR), coordSize);
34959566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, 2 * coordSize, MPIU_REAL, &cellData));
34969d150b73SToby Isaac   cellCoords = &cellData[0];
34979d150b73SToby Isaac   cellCoeffs = &cellData[coordSize];
34989d150b73SToby Isaac   if (dimR == 2) {
34999d150b73SToby Isaac     const PetscInt zToPlex[4] = {0, 1, 3, 2};
35009d150b73SToby Isaac 
35019d150b73SToby Isaac     for (i = 0; i < 4; i++) {
35029d150b73SToby Isaac       PetscInt plexI = zToPlex[i];
35039d150b73SToby Isaac 
3504ad540459SPierre Jolivet       for (j = 0; j < dimC; j++) cellCoords[dimC * i + j] = PetscRealPart(coordsScalar[dimC * plexI + j]);
35059d150b73SToby Isaac     }
35069d150b73SToby Isaac   } else if (dimR == 3) {
35079d150b73SToby Isaac     const PetscInt zToPlex[8] = {0, 3, 1, 2, 4, 5, 7, 6};
35089d150b73SToby Isaac 
35099d150b73SToby Isaac     for (i = 0; i < 8; i++) {
35109d150b73SToby Isaac       PetscInt plexI = zToPlex[i];
35119d150b73SToby Isaac 
3512ad540459SPierre Jolivet       for (j = 0; j < dimC; j++) cellCoords[dimC * i + j] = PetscRealPart(coordsScalar[dimC * plexI + j]);
35139d150b73SToby Isaac     }
35149d150b73SToby Isaac   } else {
3515ad540459SPierre Jolivet     for (i = 0; i < coordSize; i++) cellCoords[i] = PetscRealPart(coordsScalar[i]);
35169d150b73SToby Isaac   }
35179d150b73SToby Isaac   /* Perform the shuffling transform that converts values at the corners of [-1,1]^d to coefficients */
35189d150b73SToby Isaac   for (i = 0; i < dimR; i++) {
35199d150b73SToby Isaac     PetscReal *swap;
35209d150b73SToby Isaac 
35219d150b73SToby Isaac     for (j = 0; j < (numV / 2); j++) {
35229d150b73SToby Isaac       for (k = 0; k < dimC; k++) {
35239d150b73SToby Isaac         cellCoeffs[dimC * j + k]                = 0.5 * (cellCoords[dimC * (2 * j + 1) + k] + cellCoords[dimC * 2 * j + k]);
35249d150b73SToby Isaac         cellCoeffs[dimC * (j + (numV / 2)) + k] = 0.5 * (cellCoords[dimC * (2 * j + 1) + k] - cellCoords[dimC * 2 * j + k]);
35259d150b73SToby Isaac       }
35269d150b73SToby Isaac     }
35279d150b73SToby Isaac 
35289d150b73SToby Isaac     if (i < dimR - 1) {
35299d150b73SToby Isaac       swap       = cellCoeffs;
35309d150b73SToby Isaac       cellCoeffs = cellCoords;
35319d150b73SToby Isaac       cellCoords = swap;
35329d150b73SToby Isaac     }
35339d150b73SToby Isaac   }
35349566063dSJacob Faibussowitsch   PetscCall(PetscArrayzero(realCoords, numPoints * dimC));
35359d150b73SToby Isaac   for (j = 0; j < numPoints; j++) {
35369d150b73SToby Isaac     const PetscReal *guess  = &refCoords[dimR * j];
35379d150b73SToby Isaac     PetscReal       *mapped = &realCoords[dimC * j];
35389d150b73SToby Isaac 
35399d150b73SToby Isaac     for (k = 0; k < numV; k++) {
35409d150b73SToby Isaac       PetscReal extCoord = 1.;
35419d150b73SToby Isaac       for (l = 0; l < dimR; l++) {
35429d150b73SToby Isaac         PetscReal coord = guess[l];
35439d150b73SToby Isaac         PetscInt  dep   = (k & (1 << l)) >> l;
35449d150b73SToby Isaac 
35459d150b73SToby Isaac         extCoord *= dep * coord + !dep;
35469d150b73SToby Isaac       }
35479d150b73SToby Isaac       for (l = 0; l < dimC; l++) {
35489d150b73SToby Isaac         PetscReal coeff = cellCoeffs[dimC * k + l];
35499d150b73SToby Isaac 
35509d150b73SToby Isaac         mapped[l] += coeff * extCoord;
35519d150b73SToby Isaac       }
35529d150b73SToby Isaac     }
35539d150b73SToby Isaac   }
35549566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, 2 * coordSize, MPIU_REAL, &cellData));
35559566063dSJacob Faibussowitsch   PetscCall(DMPlexVecRestoreClosure(dm, NULL, coords, cell, &coordSize, &coordsScalar));
35563ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
35579d150b73SToby Isaac }
35589d150b73SToby Isaac 
35599c3cf19fSMatthew G. Knepley /* TODO: TOBY please fix this for Nc > 1 */
3560d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexCoordinatesToReference_FE(DM dm, PetscFE fe, PetscInt cell, PetscInt numPoints, const PetscReal realCoords[], PetscReal refCoords[], Vec coords, PetscInt Nc, PetscInt dimR)
3561d71ae5a4SJacob Faibussowitsch {
35629c3cf19fSMatthew G. Knepley   PetscInt     numComp, pdim, i, j, k, l, m, maxIter = 7, coordSize;
3563c6e120d1SToby Isaac   PetscScalar *nodes = NULL;
3564c6e120d1SToby Isaac   PetscReal   *invV, *modes;
3565c6e120d1SToby Isaac   PetscReal   *B, *D, *resNeg;
3566c6e120d1SToby Isaac   PetscScalar *J, *invJ, *work;
35679d150b73SToby Isaac 
35689d150b73SToby Isaac   PetscFunctionBegin;
35699566063dSJacob Faibussowitsch   PetscCall(PetscFEGetDimension(fe, &pdim));
35709566063dSJacob Faibussowitsch   PetscCall(PetscFEGetNumComponents(fe, &numComp));
357163a3b9bcSJacob 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);
35729566063dSJacob Faibussowitsch   PetscCall(DMPlexVecGetClosure(dm, NULL, coords, cell, &coordSize, &nodes));
35739d150b73SToby Isaac   /* convert nodes to values in the stable evaluation basis */
35749566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, pdim, MPIU_REAL, &modes));
35759d150b73SToby Isaac   invV = fe->invV;
3576012b7cc6SMatthew G. Knepley   for (i = 0; i < pdim; ++i) {
3577012b7cc6SMatthew G. Knepley     modes[i] = 0.;
3578ad540459SPierre Jolivet     for (j = 0; j < pdim; ++j) modes[i] += invV[i * pdim + j] * PetscRealPart(nodes[j]);
35799d150b73SToby Isaac   }
35809566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, pdim * Nc + pdim * Nc * dimR + Nc, MPIU_REAL, &B));
35819c3cf19fSMatthew G. Knepley   D      = &B[pdim * Nc];
35829c3cf19fSMatthew G. Knepley   resNeg = &D[pdim * Nc * dimR];
35839566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, 3 * Nc * dimR, MPIU_SCALAR, &J));
35849c3cf19fSMatthew G. Knepley   invJ = &J[Nc * dimR];
35859c3cf19fSMatthew G. Knepley   work = &invJ[Nc * dimR];
3586ad540459SPierre Jolivet   for (i = 0; i < numPoints * dimR; i++) refCoords[i] = 0.;
35879d150b73SToby Isaac   for (j = 0; j < numPoints; j++) {
35889b1f03cbSToby 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 */
35899d150b73SToby Isaac       PetscReal *guess = &refCoords[j * dimR];
35909566063dSJacob Faibussowitsch       PetscCall(PetscSpaceEvaluate(fe->basisSpace, 1, guess, B, D, NULL));
3591ad540459SPierre Jolivet       for (k = 0; k < Nc; k++) resNeg[k] = realCoords[j * Nc + k];
3592ad540459SPierre Jolivet       for (k = 0; k < Nc * dimR; k++) J[k] = 0.;
35939c3cf19fSMatthew G. Knepley       for (k = 0; k < pdim; k++) {
35949c3cf19fSMatthew G. Knepley         for (l = 0; l < Nc; l++) {
3595012b7cc6SMatthew G. Knepley           resNeg[l] -= modes[k] * B[k * Nc + l];
3596ad540459SPierre Jolivet           for (m = 0; m < dimR; m++) J[l * dimR + m] += modes[k] * D[(k * Nc + l) * dimR + m];
35979d150b73SToby Isaac         }
35989d150b73SToby Isaac       }
359976bd3646SJed Brown       if (0 && PetscDefined(USE_DEBUG)) {
36000611203eSToby Isaac         PetscReal maxAbs = 0.;
36010611203eSToby Isaac 
3602ad540459SPierre Jolivet         for (l = 0; l < Nc; l++) maxAbs = PetscMax(maxAbs, PetscAbsReal(resNeg[l]));
360363a3b9bcSJacob Faibussowitsch         PetscCall(PetscInfo(dm, "cell %" PetscInt_FMT ", point %" PetscInt_FMT ", iter %" PetscInt_FMT ": res %g\n", cell, j, i, (double)maxAbs));
36040611203eSToby Isaac       }
36059566063dSJacob Faibussowitsch       PetscCall(DMPlexCoordinatesToReference_NewtonUpdate(Nc, dimR, J, invJ, work, resNeg, guess));
36069d150b73SToby Isaac     }
36079d150b73SToby Isaac   }
36089566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, 3 * Nc * dimR, MPIU_SCALAR, &J));
36099566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, pdim * Nc + pdim * Nc * dimR + Nc, MPIU_REAL, &B));
36109566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, pdim, MPIU_REAL, &modes));
36119566063dSJacob Faibussowitsch   PetscCall(DMPlexVecRestoreClosure(dm, NULL, coords, cell, &coordSize, &nodes));
36123ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
36139d150b73SToby Isaac }
36149d150b73SToby Isaac 
36159c3cf19fSMatthew G. Knepley /* TODO: TOBY please fix this for Nc > 1 */
3616d71ae5a4SJacob Faibussowitsch static PetscErrorCode DMPlexReferenceToCoordinates_FE(DM dm, PetscFE fe, PetscInt cell, PetscInt numPoints, const PetscReal refCoords[], PetscReal realCoords[], Vec coords, PetscInt Nc, PetscInt dimR)
3617d71ae5a4SJacob Faibussowitsch {
36189c3cf19fSMatthew G. Knepley   PetscInt     numComp, pdim, i, j, k, l, coordSize;
3619c6e120d1SToby Isaac   PetscScalar *nodes = NULL;
3620c6e120d1SToby Isaac   PetscReal   *invV, *modes;
36219d150b73SToby Isaac   PetscReal   *B;
36229d150b73SToby Isaac 
36239d150b73SToby Isaac   PetscFunctionBegin;
36249566063dSJacob Faibussowitsch   PetscCall(PetscFEGetDimension(fe, &pdim));
36259566063dSJacob Faibussowitsch   PetscCall(PetscFEGetNumComponents(fe, &numComp));
362663a3b9bcSJacob 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);
36279566063dSJacob Faibussowitsch   PetscCall(DMPlexVecGetClosure(dm, NULL, coords, cell, &coordSize, &nodes));
36289d150b73SToby Isaac   /* convert nodes to values in the stable evaluation basis */
36299566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, pdim, MPIU_REAL, &modes));
36309d150b73SToby Isaac   invV = fe->invV;
3631012b7cc6SMatthew G. Knepley   for (i = 0; i < pdim; ++i) {
3632012b7cc6SMatthew G. Knepley     modes[i] = 0.;
3633ad540459SPierre Jolivet     for (j = 0; j < pdim; ++j) modes[i] += invV[i * pdim + j] * PetscRealPart(nodes[j]);
36349d150b73SToby Isaac   }
36359566063dSJacob Faibussowitsch   PetscCall(DMGetWorkArray(dm, numPoints * pdim * Nc, MPIU_REAL, &B));
36369566063dSJacob Faibussowitsch   PetscCall(PetscSpaceEvaluate(fe->basisSpace, numPoints, refCoords, B, NULL, NULL));
3637ad540459SPierre Jolivet   for (i = 0; i < numPoints * Nc; i++) realCoords[i] = 0.;
36389d150b73SToby Isaac   for (j = 0; j < numPoints; j++) {
36399c3cf19fSMatthew G. Knepley     PetscReal *mapped = &realCoords[j * Nc];
36409d150b73SToby Isaac 
36419c3cf19fSMatthew G. Knepley     for (k = 0; k < pdim; k++) {
3642ad540459SPierre Jolivet       for (l = 0; l < Nc; l++) mapped[l] += modes[k] * B[(j * pdim + k) * Nc + l];
36439d150b73SToby Isaac     }
36449d150b73SToby Isaac   }
36459566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, numPoints * pdim * Nc, MPIU_REAL, &B));
36469566063dSJacob Faibussowitsch   PetscCall(DMRestoreWorkArray(dm, pdim, MPIU_REAL, &modes));
36479566063dSJacob Faibussowitsch   PetscCall(DMPlexVecRestoreClosure(dm, NULL, coords, cell, &coordSize, &nodes));
36483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
36499d150b73SToby Isaac }
36509d150b73SToby Isaac 
3651d6143a4eSToby Isaac /*@
3652a4e35b19SJacob Faibussowitsch   DMPlexCoordinatesToReference - Pull coordinates back from the mesh to the reference element
3653a4e35b19SJacob Faibussowitsch   using a single element map.
3654d6143a4eSToby Isaac 
365520f4b53cSBarry Smith   Not Collective
3656d6143a4eSToby Isaac 
3657d6143a4eSToby Isaac   Input Parameters:
365820f4b53cSBarry Smith + dm         - The mesh, with coordinate maps defined either by a `PetscDS` for the coordinate `DM` (see `DMGetCoordinateDM()`) or
3659d6143a4eSToby Isaac                implicitly by the coordinates of the corner vertices of the cell: as an affine map for simplicial elements, or
3660d6143a4eSToby Isaac                as a multilinear map for tensor-product elements
3661d6143a4eSToby Isaac . cell       - the cell whose map is used.
3662d6143a4eSToby Isaac . numPoints  - the number of points to locate
366320f4b53cSBarry Smith - realCoords - (numPoints x coordinate dimension) array of coordinates (see `DMGetCoordinateDim()`)
3664d6143a4eSToby Isaac 
36652fe279fdSBarry Smith   Output Parameter:
366620f4b53cSBarry Smith . refCoords - (`numPoints` x `dimension`) array of reference coordinates (see `DMGetDimension()`)
36671b266c99SBarry Smith 
36681b266c99SBarry Smith   Level: intermediate
366973c9229bSMatthew Knepley 
3670a4e35b19SJacob Faibussowitsch   Notes:
3671a4e35b19SJacob Faibussowitsch   This inversion will be accurate inside the reference element, but may be inaccurate for
3672a4e35b19SJacob Faibussowitsch   mappings that do not extend uniquely outside the reference cell (e.g, most non-affine maps)
3673a4e35b19SJacob Faibussowitsch 
367420f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexReferenceToCoordinates()`
3675d6143a4eSToby Isaac @*/
3676d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexCoordinatesToReference(DM dm, PetscInt cell, PetscInt numPoints, const PetscReal realCoords[], PetscReal refCoords[])
3677d71ae5a4SJacob Faibussowitsch {
3678485ad865SMatthew G. Knepley   PetscInt dimC, dimR, depth, cStart, cEnd, i;
36799d150b73SToby Isaac   DM       coordDM = NULL;
36809d150b73SToby Isaac   Vec      coords;
36819d150b73SToby Isaac   PetscFE  fe = NULL;
36829d150b73SToby Isaac 
3683d6143a4eSToby Isaac   PetscFunctionBegin;
36849d150b73SToby Isaac   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
36859566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dimR));
36869566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &dimC));
36873ba16761SJacob Faibussowitsch   if (dimR <= 0 || dimC <= 0 || numPoints <= 0) PetscFunctionReturn(PETSC_SUCCESS);
36889566063dSJacob Faibussowitsch   PetscCall(DMPlexGetDepth(dm, &depth));
36899566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinatesLocal(dm, &coords));
36909566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDM(dm, &coordDM));
36919d150b73SToby Isaac   if (coordDM) {
36929d150b73SToby Isaac     PetscInt coordFields;
36939d150b73SToby Isaac 
36949566063dSJacob Faibussowitsch     PetscCall(DMGetNumFields(coordDM, &coordFields));
36959d150b73SToby Isaac     if (coordFields) {
36969d150b73SToby Isaac       PetscClassId id;
36979d150b73SToby Isaac       PetscObject  disc;
36989d150b73SToby Isaac 
36999566063dSJacob Faibussowitsch       PetscCall(DMGetField(coordDM, 0, NULL, &disc));
37009566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetClassId(disc, &id));
3701ad540459SPierre Jolivet       if (id == PETSCFE_CLASSID) fe = (PetscFE)disc;
37029d150b73SToby Isaac     }
37039d150b73SToby Isaac   }
37049566063dSJacob Faibussowitsch   PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
37051dca8a05SBarry 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);
37069d150b73SToby Isaac   if (!fe) { /* implicit discretization: affine or multilinear */
37079d150b73SToby Isaac     PetscInt  coneSize;
37089d150b73SToby Isaac     PetscBool isSimplex, isTensor;
37099d150b73SToby Isaac 
37109566063dSJacob Faibussowitsch     PetscCall(DMPlexGetConeSize(dm, cell, &coneSize));
37119d150b73SToby Isaac     isSimplex = (coneSize == (dimR + 1)) ? PETSC_TRUE : PETSC_FALSE;
37129d150b73SToby Isaac     isTensor  = (coneSize == ((depth == 1) ? (1 << dimR) : (2 * dimR))) ? PETSC_TRUE : PETSC_FALSE;
37139d150b73SToby Isaac     if (isSimplex) {
37149d150b73SToby Isaac       PetscReal detJ, *v0, *J, *invJ;
37159d150b73SToby Isaac 
37169566063dSJacob Faibussowitsch       PetscCall(DMGetWorkArray(dm, dimC + 2 * dimC * dimC, MPIU_REAL, &v0));
37179d150b73SToby Isaac       J    = &v0[dimC];
37189d150b73SToby Isaac       invJ = &J[dimC * dimC];
37199566063dSJacob Faibussowitsch       PetscCall(DMPlexComputeCellGeometryAffineFEM(dm, cell, v0, J, invJ, &detJ));
37209d150b73SToby Isaac       for (i = 0; i < numPoints; i++) { /* Apply the inverse affine transformation for each point */
3721c330f8ffSToby Isaac         const PetscReal x0[3] = {-1., -1., -1.};
3722c330f8ffSToby Isaac 
3723c330f8ffSToby Isaac         CoordinatesRealToRef(dimC, dimR, x0, v0, invJ, &realCoords[dimC * i], &refCoords[dimR * i]);
37249d150b73SToby Isaac       }
37259566063dSJacob Faibussowitsch       PetscCall(DMRestoreWorkArray(dm, dimC + 2 * dimC * dimC, MPIU_REAL, &v0));
37269d150b73SToby Isaac     } else if (isTensor) {
37279566063dSJacob Faibussowitsch       PetscCall(DMPlexCoordinatesToReference_Tensor(coordDM, cell, numPoints, realCoords, refCoords, coords, dimC, dimR));
372863a3b9bcSJacob Faibussowitsch     } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Unrecognized cone size %" PetscInt_FMT, coneSize);
37299d150b73SToby Isaac   } else {
37309566063dSJacob Faibussowitsch     PetscCall(DMPlexCoordinatesToReference_FE(coordDM, fe, cell, numPoints, realCoords, refCoords, coords, dimC, dimR));
37319d150b73SToby Isaac   }
37323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
37339d150b73SToby Isaac }
37349d150b73SToby Isaac 
37359d150b73SToby Isaac /*@
37369d150b73SToby Isaac   DMPlexReferenceToCoordinates - Map references coordinates to coordinates in the the mesh for a single element map.
37379d150b73SToby Isaac 
373820f4b53cSBarry Smith   Not Collective
37399d150b73SToby Isaac 
37409d150b73SToby Isaac   Input Parameters:
37412fe279fdSBarry Smith + dm        - The mesh, with coordinate maps defined either by a PetscDS for the coordinate `DM` (see `DMGetCoordinateDM()`) or
37429d150b73SToby Isaac                implicitly by the coordinates of the corner vertices of the cell: as an affine map for simplicial elements, or
37439d150b73SToby Isaac                as a multilinear map for tensor-product elements
37449d150b73SToby Isaac . cell      - the cell whose map is used.
37459d150b73SToby Isaac . numPoints - the number of points to locate
37462fe279fdSBarry Smith - refCoords - (numPoints x dimension) array of reference coordinates (see `DMGetDimension()`)
37479d150b73SToby Isaac 
37482fe279fdSBarry Smith   Output Parameter:
37492fe279fdSBarry Smith . realCoords - (numPoints x coordinate dimension) array of coordinates (see `DMGetCoordinateDim()`)
37501b266c99SBarry Smith 
37511b266c99SBarry Smith   Level: intermediate
375273c9229bSMatthew Knepley 
37532fe279fdSBarry Smith .seealso: `DMPLEX`, `DMPlexCoordinatesToReference()`
37549d150b73SToby Isaac @*/
3755d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexReferenceToCoordinates(DM dm, PetscInt cell, PetscInt numPoints, const PetscReal refCoords[], PetscReal realCoords[])
3756d71ae5a4SJacob Faibussowitsch {
3757485ad865SMatthew G. Knepley   PetscInt dimC, dimR, depth, cStart, cEnd, i;
37589d150b73SToby Isaac   DM       coordDM = NULL;
37599d150b73SToby Isaac   Vec      coords;
37609d150b73SToby Isaac   PetscFE  fe = NULL;
37619d150b73SToby Isaac 
37629d150b73SToby Isaac   PetscFunctionBegin;
37639d150b73SToby Isaac   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
37649566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dimR));
37659566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &dimC));
37663ba16761SJacob Faibussowitsch   if (dimR <= 0 || dimC <= 0 || numPoints <= 0) PetscFunctionReturn(PETSC_SUCCESS);
37679566063dSJacob Faibussowitsch   PetscCall(DMPlexGetDepth(dm, &depth));
37689566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinatesLocal(dm, &coords));
37699566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDM(dm, &coordDM));
37709d150b73SToby Isaac   if (coordDM) {
37719d150b73SToby Isaac     PetscInt coordFields;
37729d150b73SToby Isaac 
37739566063dSJacob Faibussowitsch     PetscCall(DMGetNumFields(coordDM, &coordFields));
37749d150b73SToby Isaac     if (coordFields) {
37759d150b73SToby Isaac       PetscClassId id;
37769d150b73SToby Isaac       PetscObject  disc;
37779d150b73SToby Isaac 
37789566063dSJacob Faibussowitsch       PetscCall(DMGetField(coordDM, 0, NULL, &disc));
37799566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetClassId(disc, &id));
3780ad540459SPierre Jolivet       if (id == PETSCFE_CLASSID) fe = (PetscFE)disc;
37819d150b73SToby Isaac     }
37829d150b73SToby Isaac   }
37839566063dSJacob Faibussowitsch   PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
37841dca8a05SBarry 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);
37859d150b73SToby Isaac   if (!fe) { /* implicit discretization: affine or multilinear */
37869d150b73SToby Isaac     PetscInt  coneSize;
37879d150b73SToby Isaac     PetscBool isSimplex, isTensor;
37889d150b73SToby Isaac 
37899566063dSJacob Faibussowitsch     PetscCall(DMPlexGetConeSize(dm, cell, &coneSize));
37909d150b73SToby Isaac     isSimplex = (coneSize == (dimR + 1)) ? PETSC_TRUE : PETSC_FALSE;
37919d150b73SToby Isaac     isTensor  = (coneSize == ((depth == 1) ? (1 << dimR) : (2 * dimR))) ? PETSC_TRUE : PETSC_FALSE;
37929d150b73SToby Isaac     if (isSimplex) {
37939d150b73SToby Isaac       PetscReal detJ, *v0, *J;
37949d150b73SToby Isaac 
37959566063dSJacob Faibussowitsch       PetscCall(DMGetWorkArray(dm, dimC + 2 * dimC * dimC, MPIU_REAL, &v0));
37969d150b73SToby Isaac       J = &v0[dimC];
37979566063dSJacob Faibussowitsch       PetscCall(DMPlexComputeCellGeometryAffineFEM(dm, cell, v0, J, NULL, &detJ));
3798c330f8ffSToby Isaac       for (i = 0; i < numPoints; i++) { /* Apply the affine transformation for each point */
3799c330f8ffSToby Isaac         const PetscReal xi0[3] = {-1., -1., -1.};
3800c330f8ffSToby Isaac 
3801c330f8ffSToby Isaac         CoordinatesRefToReal(dimC, dimR, xi0, v0, J, &refCoords[dimR * i], &realCoords[dimC * i]);
38029d150b73SToby Isaac       }
38039566063dSJacob Faibussowitsch       PetscCall(DMRestoreWorkArray(dm, dimC + 2 * dimC * dimC, MPIU_REAL, &v0));
38049d150b73SToby Isaac     } else if (isTensor) {
38059566063dSJacob Faibussowitsch       PetscCall(DMPlexReferenceToCoordinates_Tensor(coordDM, cell, numPoints, refCoords, realCoords, coords, dimC, dimR));
380663a3b9bcSJacob Faibussowitsch     } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Unrecognized cone size %" PetscInt_FMT, coneSize);
38079d150b73SToby Isaac   } else {
38089566063dSJacob Faibussowitsch     PetscCall(DMPlexReferenceToCoordinates_FE(coordDM, fe, cell, numPoints, refCoords, realCoords, coords, dimC, dimR));
38099d150b73SToby Isaac   }
38103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3811d6143a4eSToby Isaac }
38120139fca9SMatthew G. Knepley 
38130139fca9SMatthew G. Knepley /*@C
38142fe279fdSBarry Smith   DMPlexRemapGeometry - This function maps the original `DM` coordinates to new coordinates.
38150139fca9SMatthew G. Knepley 
381620f4b53cSBarry Smith   Not Collective
38170139fca9SMatthew G. Knepley 
38180139fca9SMatthew G. Knepley   Input Parameters:
38192fe279fdSBarry Smith + dm   - The `DM`
38200139fca9SMatthew G. Knepley . time - The time
3821a4e35b19SJacob Faibussowitsch - func - The function transforming current coordinates to new coordinates
38220139fca9SMatthew G. Knepley 
382320f4b53cSBarry Smith   Calling sequence of `func`:
38240139fca9SMatthew G. Knepley + dim          - The spatial dimension
38250139fca9SMatthew G. Knepley . Nf           - The number of input fields (here 1)
38260139fca9SMatthew G. Knepley . NfAux        - The number of input auxiliary fields
38270139fca9SMatthew G. Knepley . uOff         - The offset of the coordinates in u[] (here 0)
38280139fca9SMatthew G. Knepley . uOff_x       - The offset of the coordinates in u_x[] (here 0)
38290139fca9SMatthew G. Knepley . u            - The coordinate values at this point in space
383020f4b53cSBarry Smith . u_t          - The coordinate time derivative at this point in space (here `NULL`)
38310139fca9SMatthew G. Knepley . u_x          - The coordinate derivatives at this point in space
38320139fca9SMatthew G. Knepley . aOff         - The offset of each auxiliary field in u[]
38330139fca9SMatthew G. Knepley . aOff_x       - The offset of each auxiliary field in u_x[]
38340139fca9SMatthew G. Knepley . a            - The auxiliary field values at this point in space
383520f4b53cSBarry Smith . a_t          - The auxiliary field time derivative at this point in space (or `NULL`)
38360139fca9SMatthew G. Knepley . a_x          - The auxiliary field derivatives at this point in space
38370139fca9SMatthew G. Knepley . t            - The current time
38380139fca9SMatthew G. Knepley . x            - The coordinates of this point (here not used)
38390139fca9SMatthew G. Knepley . numConstants - The number of constants
38400139fca9SMatthew G. Knepley . constants    - The value of each constant
38410139fca9SMatthew G. Knepley - f            - The new coordinates at this point in space
38420139fca9SMatthew G. Knepley 
38430139fca9SMatthew G. Knepley   Level: intermediate
38440139fca9SMatthew G. Knepley 
38452fe279fdSBarry Smith .seealso: `DMPLEX`, `DMGetCoordinates()`, `DMGetCoordinatesLocal()`, `DMGetCoordinateDM()`, `DMProjectFieldLocal()`, `DMProjectFieldLabelLocal()`
38460139fca9SMatthew G. Knepley @*/
3847a4e35b19SJacob 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[]))
3848d71ae5a4SJacob Faibussowitsch {
38490139fca9SMatthew G. Knepley   DM      cdm;
38508bf1a49fSMatthew G. Knepley   DMField cf;
38510139fca9SMatthew G. Knepley   Vec     lCoords, tmpCoords;
38520139fca9SMatthew G. Knepley 
38530139fca9SMatthew G. Knepley   PetscFunctionBegin;
38549566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDM(dm, &cdm));
38559566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinatesLocal(dm, &lCoords));
38569566063dSJacob Faibussowitsch   PetscCall(DMGetLocalVector(cdm, &tmpCoords));
38579566063dSJacob Faibussowitsch   PetscCall(VecCopy(lCoords, tmpCoords));
38588bf1a49fSMatthew G. Knepley   /* We have to do the coordinate field manually right now since the coordinate DM will not have its own */
38599566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateField(dm, &cf));
38606858538eSMatthew G. Knepley   cdm->coordinates[0].field = cf;
38619566063dSJacob Faibussowitsch   PetscCall(DMProjectFieldLocal(cdm, time, tmpCoords, &func, INSERT_VALUES, lCoords));
38626858538eSMatthew G. Knepley   cdm->coordinates[0].field = NULL;
38639566063dSJacob Faibussowitsch   PetscCall(DMRestoreLocalVector(cdm, &tmpCoords));
38649566063dSJacob Faibussowitsch   PetscCall(DMSetCoordinatesLocal(dm, lCoords));
38653ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
38660139fca9SMatthew G. Knepley }
38670139fca9SMatthew G. Knepley 
38680139fca9SMatthew G. Knepley /* Shear applies the transformation, assuming we fix z,
38690139fca9SMatthew G. Knepley   / 1  0  m_0 \
38700139fca9SMatthew G. Knepley   | 0  1  m_1 |
38710139fca9SMatthew G. Knepley   \ 0  0   1  /
38720139fca9SMatthew G. Knepley */
3873d71ae5a4SJacob Faibussowitsch static void f0_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[])
3874d71ae5a4SJacob Faibussowitsch {
38750139fca9SMatthew G. Knepley   const PetscInt Nc = uOff[1] - uOff[0];
3876c1f1bd54SMatthew G. Knepley   const PetscInt ax = (PetscInt)PetscRealPart(constants[0]);
38770139fca9SMatthew G. Knepley   PetscInt       c;
38780139fca9SMatthew G. Knepley 
3879ad540459SPierre Jolivet   for (c = 0; c < Nc; ++c) coords[c] = u[c] + constants[c + 1] * u[ax];
38800139fca9SMatthew G. Knepley }
38810139fca9SMatthew G. Knepley 
38820139fca9SMatthew G. Knepley /*@C
38830139fca9SMatthew G. Knepley   DMPlexShearGeometry - This shears the domain, meaning adds a multiple of the shear coordinate to all other coordinates.
38840139fca9SMatthew G. Knepley 
388520f4b53cSBarry Smith   Not Collective
38860139fca9SMatthew G. Knepley 
38870139fca9SMatthew G. Knepley   Input Parameters:
388820f4b53cSBarry Smith + dm          - The `DMPLEX`
38893ee9839eSMatthew G. Knepley . direction   - The shear coordinate direction, e.g. 0 is the x-axis
38900139fca9SMatthew G. Knepley - multipliers - The multiplier m for each direction which is not the shear direction
38910139fca9SMatthew G. Knepley 
38920139fca9SMatthew G. Knepley   Level: intermediate
38930139fca9SMatthew G. Knepley 
389420f4b53cSBarry Smith .seealso: `DMPLEX`, `DMPlexRemapGeometry()`
38950139fca9SMatthew G. Knepley @*/
3896d71ae5a4SJacob Faibussowitsch PetscErrorCode DMPlexShearGeometry(DM dm, DMDirection direction, PetscReal multipliers[])
3897d71ae5a4SJacob Faibussowitsch {
38980139fca9SMatthew G. Knepley   DM             cdm;
38990139fca9SMatthew G. Knepley   PetscDS        cds;
39000139fca9SMatthew G. Knepley   PetscObject    obj;
39010139fca9SMatthew G. Knepley   PetscClassId   id;
39020139fca9SMatthew G. Knepley   PetscScalar   *moduli;
39033ee9839eSMatthew G. Knepley   const PetscInt dir = (PetscInt)direction;
39040139fca9SMatthew G. Knepley   PetscInt       dE, d, e;
39050139fca9SMatthew G. Knepley 
39060139fca9SMatthew G. Knepley   PetscFunctionBegin;
39079566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDM(dm, &cdm));
39089566063dSJacob Faibussowitsch   PetscCall(DMGetCoordinateDim(dm, &dE));
39099566063dSJacob Faibussowitsch   PetscCall(PetscMalloc1(dE + 1, &moduli));
39100139fca9SMatthew G. Knepley   moduli[0] = dir;
3911cdaaecf7SMatthew G. Knepley   for (d = 0, e = 0; d < dE; ++d) moduli[d + 1] = d == dir ? 0.0 : (multipliers ? multipliers[e++] : 1.0);
39129566063dSJacob Faibussowitsch   PetscCall(DMGetDS(cdm, &cds));
39139566063dSJacob Faibussowitsch   PetscCall(PetscDSGetDiscretization(cds, 0, &obj));
39149566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetClassId(obj, &id));
39150139fca9SMatthew G. Knepley   if (id != PETSCFE_CLASSID) {
39160139fca9SMatthew G. Knepley     Vec          lCoords;
39170139fca9SMatthew G. Knepley     PetscSection cSection;
39180139fca9SMatthew G. Knepley     PetscScalar *coords;
39190139fca9SMatthew G. Knepley     PetscInt     vStart, vEnd, v;
39200139fca9SMatthew G. Knepley 
39219566063dSJacob Faibussowitsch     PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
39229566063dSJacob Faibussowitsch     PetscCall(DMGetCoordinateSection(dm, &cSection));
39239566063dSJacob Faibussowitsch     PetscCall(DMGetCoordinatesLocal(dm, &lCoords));
39249566063dSJacob Faibussowitsch     PetscCall(VecGetArray(lCoords, &coords));
39250139fca9SMatthew G. Knepley     for (v = vStart; v < vEnd; ++v) {
39260139fca9SMatthew G. Knepley       PetscReal ds;
39270139fca9SMatthew G. Knepley       PetscInt  off, c;
39280139fca9SMatthew G. Knepley 
39299566063dSJacob Faibussowitsch       PetscCall(PetscSectionGetOffset(cSection, v, &off));
39300139fca9SMatthew G. Knepley       ds = PetscRealPart(coords[off + dir]);
39310139fca9SMatthew G. Knepley       for (c = 0; c < dE; ++c) coords[off + c] += moduli[c] * ds;
39320139fca9SMatthew G. Knepley     }
39339566063dSJacob Faibussowitsch     PetscCall(VecRestoreArray(lCoords, &coords));
39340139fca9SMatthew G. Knepley   } else {
39359566063dSJacob Faibussowitsch     PetscCall(PetscDSSetConstants(cds, dE + 1, moduli));
39369566063dSJacob Faibussowitsch     PetscCall(DMPlexRemapGeometry(dm, 0.0, f0_shear));
39370139fca9SMatthew G. Knepley   }
39389566063dSJacob Faibussowitsch   PetscCall(PetscFree(moduli));
39393ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
39400139fca9SMatthew G. Knepley }
3941