Actual source code: plexrefsbr.c

  1: #include <petsc/private/dmplextransformimpl.h>
  2: #include <petscsf.h>

  4: PetscBool  SBRcite       = PETSC_FALSE;
  5: const char SBRCitation[] = "@article{PlazaCarey2000,\n"
  6:                            "  title   = {Local refinement of simplicial grids based on the skeleton},\n"
  7:                            "  journal = {Applied Numerical Mathematics},\n"
  8:                            "  author  = {A. Plaza and Graham F. Carey},\n"
  9:                            "  volume  = {32},\n"
 10:                            "  number  = {3},\n"
 11:                            "  pages   = {195--218},\n"
 12:                            "  doi     = {10.1016/S0168-9274(99)00022-7},\n"
 13:                            "  year    = {2000}\n}\n";

 15: /*
 16:   Tetrahedron combinatorics, in the canonical local numbering used throughout this file (matching
 17:   the convention documented in DMPlexTransformCellRefine_Regular() for DM_POLYTOPE_TETRAHEDRON):

 19:     e0 = (v0,v1), e1 = (v1,v2), e2 = (v2,v0), e3 = (v0,v3), e4 = (v1,v3), e5 = (v2,v3)
 20:     f0 = (v0,v1,v2), f1 = (v0,v3,v1), f2 = (v0,v2,v3), f3 = (v2,v1,v3)

 22:   tetEdgeVert[e]    - the 2 vertices of edge e, in its canonical direction
 23:   tetFaceVert[f]    - the 3 vertices of face f, in its canonical order
 24:   tetFaceEdge[f]    - the edges of face f, at local indices 0,1,2 (i.e. (v_0,v_1),(v_1,v_2),(v_2,v_0) of that face)
 25:   tetEdgeFaceLoc[e] - a (face, local edge index) path that reaches edge e in its canonical direction
 26:   tetVertPath[v]    - a (face, local edge index, local vertex index) path that reaches vertex v
 27:   tetOppFace[x]     - the 3 local vertex positions (not values) of the face opposite position x, i.e. f[3-x]
 28: */
 29: static const PetscInt tetEdgeVert[6][2] = {
 30:   {0, 1},
 31:   {1, 2},
 32:   {2, 0},
 33:   {0, 3},
 34:   {1, 3},
 35:   {2, 3}
 36: };
 37: static const PetscInt tetFaceVert[4][3] = {
 38:   {0, 1, 2},
 39:   {0, 3, 1},
 40:   {0, 2, 3},
 41:   {2, 1, 3}
 42: };
 43: static const PetscInt tetFaceEdge[4][3] = {
 44:   {0, 1, 2},
 45:   {3, 4, 0},
 46:   {2, 5, 3},
 47:   {1, 4, 5}
 48: };
 49: static const PetscInt tetEdgeFaceLoc[6][2] = {
 50:   {0, 0},
 51:   {0, 1},
 52:   {0, 2},
 53:   {1, 0},
 54:   {3, 1},
 55:   {2, 1}
 56: };
 57: static const PetscInt tetVertPath[4][3] = {
 58:   {0, 0, 0},
 59:   {0, 0, 1},
 60:   {0, 2, 0},
 61:   {1, 0, 1}
 62: };
 63: static const PetscInt tetOppFace[4][3] = {
 64:   {2, 1, 3},
 65:   {0, 2, 3},
 66:   {0, 3, 1},
 67:   {0, 1, 2}
 68: };
 69: /* tetVertFaces[v], tetEdgeFaces[e] - bitmasks over f0..f3 of the faces containing vertex v or edge e */
 70: static const PetscInt tetVertFaces[4] = {7, 11, 13, 14};
 71: static const PetscInt tetEdgeFaces[6] = {3, 9, 5, 6, 10, 12};
 72: /* The edges of the triangle, triEdgeVert[e] = (v_e, v_{e+1}) */
 73: static const PetscInt triEdgeVert[3][2] = {
 74:   {0, 1},
 75:   {1, 2},
 76:   {2, 0}
 77: };

 79: /* Find the tetrahedron edge index (0-5) connecting the two given (unordered) vertices */
 80: static PetscInt SBREdgeIndexFromVerts_Private(PetscInt v0, PetscInt v1)
 81: {
 82:   for (PetscInt k = 0; k < 6; ++k) {
 83:     if ((tetEdgeVert[k][0] == v0 && tetEdgeVert[k][1] == v1) || (tetEdgeVert[k][0] == v1 && tetEdgeVert[k][1] == v0)) return k;
 84:   }
 85:   return -1;
 86: }

 88: static PetscErrorCode SBRGetEdgeLen_Private(DMPlexTransform tr, PetscInt edge, PetscReal *len)
 89: {
 90:   DMPlexRefine_SBR *sbr = (DMPlexRefine_SBR *)tr->data;
 91:   DM                dm;
 92:   PetscInt          off;

 94:   PetscFunctionBeginHot;
 95:   PetscCall(DMPlexTransformGetDM(tr, &dm));
 96:   PetscCall(PetscSectionGetOffset(sbr->secEdgeLen, edge, &off));
 97:   if (sbr->edgeLen[off] <= 0.0) {
 98:     DM                 cdm;
 99:     Vec                coordsLocal;
100:     const PetscScalar *coords;
101:     const PetscInt    *cone;
102:     PetscScalar       *cA, *cB;
103:     PetscInt           coneSize, cdim;

105:     PetscCall(DMGetCoordinateDM(dm, &cdm));
106:     PetscCall(DMPlexGetCone(dm, edge, &cone));
107:     PetscCall(DMPlexGetConeSize(dm, edge, &coneSize));
108:     PetscCheck(coneSize == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Edge %" PetscInt_FMT " cone size must be 2, not %" PetscInt_FMT, edge, coneSize);
109:     PetscCall(DMGetCoordinateDim(dm, &cdim));
110:     PetscCall(DMGetCoordinatesLocalNoncollective(dm, &coordsLocal));
111:     PetscCall(VecGetArrayRead(coordsLocal, &coords));
112:     PetscCall(DMPlexPointLocalRead(cdm, cone[0], coords, &cA));
113:     PetscCall(DMPlexPointLocalRead(cdm, cone[1], coords, &cB));
114:     sbr->edgeLen[off] = DMPlex_DistD_Internal(cdim, cA, cB);
115:     PetscCall(VecRestoreArrayRead(coordsLocal, &coords));
116:   }
117:   *len = sbr->edgeLen[off];
118:   PetscFunctionReturn(PETSC_SUCCESS);
119: }

121: static PetscErrorCode SBRGetEdgeMid_Private(DMPlexTransform tr, PetscInt edge, PetscReal mid[3])
122: {
123:   DM                 dm, cdm;
124:   Vec                coordsLocal;
125:   const PetscScalar *coords;
126:   const PetscInt    *cone;
127:   PetscScalar       *cA, *cB;
128:   PetscInt           cdim;

130:   PetscFunctionBeginHot;
131:   PetscCall(DMPlexTransformGetDM(tr, &dm));
132:   PetscCall(DMGetCoordinateDM(dm, &cdm));
133:   PetscCall(DMPlexGetCone(dm, edge, &cone));
134:   PetscCall(DMGetCoordinateDim(dm, &cdim));
135:   PetscCall(DMGetCoordinatesLocalNoncollective(dm, &coordsLocal));
136:   PetscCall(VecGetArrayRead(coordsLocal, &coords));
137:   PetscCall(DMPlexPointLocalRead(cdm, cone[0], coords, &cA));
138:   PetscCall(DMPlexPointLocalRead(cdm, cone[1], coords, &cB));
139:   for (PetscInt d = 0; d < 3; ++d) mid[d] = d < cdim ? 0.5 * PetscRealPart(cA[d] + cB[d]) : 0.0;
140:   PetscCall(VecRestoreArrayRead(coordsLocal, &coords));
141:   PetscFunctionReturn(PETSC_SUCCESS);
142: }

144: /*
145:   Determine whether edge eA is bisected before edge eB: longer edges come first, and exact length
146:   ties are broken in favor of the lexicographically greater edge midpoint. The tie-breaker depends
147:   only on the geometry, not on mesh point numbers or cone traversal order, so every face and every
148:   cell containing the two edges resolves the tie the same way, on every process. This keeps the
149:   subdivision each face chooses for itself consistent with the subdivision induced on that face by
150:   the bisection of the cells above it (see the discussion at RefinementType).
151: */
152: static PetscErrorCode SBREdgePrecedes_Private(DMPlexTransform tr, PetscInt eA, PetscInt eB, PetscBool *precedes)
153: {
154:   PetscReal lenA, lenB, midA[3], midB[3];

156:   PetscFunctionBeginHot;
157:   PetscCall(SBRGetEdgeLen_Private(tr, eA, &lenA));
158:   PetscCall(SBRGetEdgeLen_Private(tr, eB, &lenB));
159:   if (lenA != lenB) {
160:     *precedes = lenA > lenB ? PETSC_TRUE : PETSC_FALSE;
161:     PetscFunctionReturn(PETSC_SUCCESS);
162:   }
163:   PetscCall(SBRGetEdgeMid_Private(tr, eA, midA));
164:   PetscCall(SBRGetEdgeMid_Private(tr, eB, midB));
165:   *precedes = PETSC_FALSE;
166:   for (PetscInt d = 0; d < 3; ++d) {
167:     if (midA[d] != midB[d]) {
168:       *precedes = midA[d] > midB[d] ? PETSC_TRUE : PETSC_FALSE;
169:       break;
170:     }
171:   }
172:   PetscFunctionReturn(PETSC_SUCCESS);
173: }

175: /*
176:   Get the 6 edges of a tetrahedron, in the canonical local order used throughout this file:
177:   e0 = (v0,v1), e1 = (v1,v2), e2 = (v2,v0), e3 = (v0,v3), e4 = (v1,v3), e5 = (v2,v3), where
178:   v0..v3 are the tetrahedron's vertices in the order given by its own transitive closure. This
179:   matches the convention documented in DMPlexTransformCellRefine_Regular() for DM_POLYTOPE_TETRAHEDRON.
180:   The faces of the tetrahedron, in DMPlexGetCone() order, are f0 = (v0,v1,v2), f1 = (v0,v3,v1),
181:   f2 = (v0,v2,v3), f3 = (v2,v1,v3), so each e_k below is read off face fIdx[k] at local edge index
182:   lIdx[k], reoriented for that face's actual orientation as seen from the tetrahedron.
183: */
184: static PetscErrorCode SBRGetTetEdges_Private(DM dm, PetscInt tet, PetscInt edges[6])
185: {
186:   const PetscInt *fcone, *forient;

188:   PetscFunctionBeginHot;
189:   PetscCall(DMPlexGetCone(dm, tet, &fcone));
190:   PetscCall(DMPlexGetConeOrientation(dm, tet, &forient));
191:   for (PetscInt k = 0; k < 6; ++k) {
192:     const PetscInt  floc = tetEdgeFaceLoc[k][0];
193:     const PetscInt  face = fcone[floc];
194:     const PetscInt *arr  = DMPolytopeTypeGetArrangement(DM_POLYTOPE_TRIANGLE, forient[floc]);
195:     const PetscInt  li   = arr[tetEdgeFaceLoc[k][1] * 2];
196:     const PetscInt *econe;

198:     PetscCall(DMPlexGetCone(dm, face, &econe));
199:     edges[k] = econe[li];
200:   }
201:   PetscFunctionReturn(PETSC_SUCCESS);
202: }

204: /* Find the first edge of a tetrahedron in the bisection order, that is its longest edge */
205: static PetscErrorCode SBRGetTetMaxEdge_Private(DMPlexTransform tr, PetscInt tet, PetscInt *maxedge)
206: {
207:   DM        dm;
208:   PetscInt  edges[6];
209:   PetscBool prec;

211:   PetscFunctionBeginHot;
212:   PetscCall(DMPlexTransformGetDM(tr, &dm));
213:   PetscCall(SBRGetTetEdges_Private(dm, tet, edges));
214:   *maxedge = edges[0];
215:   for (PetscInt k = 1; k < 6; ++k) {
216:     PetscCall(SBREdgePrecedes_Private(tr, edges[k], *maxedge, &prec));
217:     if (prec) *maxedge = edges[k];
218:   }
219:   PetscFunctionReturn(PETSC_SUCCESS);
220: }

222: /*
223:   Mark the longest edge of a face-level cell (a triangle of a 3D mesh, or a maximal cell of a 2D
224:   mesh), and the longest edge of every unprocessed cell above it. This is idempotent, so it is
225:   safe to process a face again when it was marked both locally and on another process.
226: */
227: static PetscErrorCode SBRSplitFace_Private(DMPlexTransform tr, DMPlexPointQueue queue, PetscInt cell)
228: {
229:   DMPlexRefine_SBR *sbr = (DMPlexRefine_SBR *)tr->data;
230:   DM                dm;
231:   const PetscInt   *cone, *tsupport;
232:   PetscInt          coneSize, tsupportSize, c, eval, maxedge;
233:   PetscBool         prec;

235:   PetscFunctionBegin;
236:   PetscCall(DMPlexTransformGetDM(tr, &dm));
237:   PetscCall(DMPlexGetCone(dm, cell, &cone));
238:   PetscCall(DMPlexGetConeSize(dm, cell, &coneSize));
239:   maxedge = cone[0];
240:   for (c = 1; c < coneSize; ++c) {
241:     PetscCall(SBREdgePrecedes_Private(tr, cone[c], maxedge, &prec));
242:     if (prec) maxedge = cone[c];
243:   }
244:   PetscCall(DMLabelGetValue(sbr->splitPoints, maxedge, &eval));
245:   if (eval != 1) {
246:     PetscCall(DMLabelSetValue(sbr->splitPoints, maxedge, 1));
247:     PetscCall(DMPlexPointQueueEnqueue(queue, maxedge));
248:   }
249:   PetscCall(DMLabelSetValue(sbr->splitPoints, cell, 2));
250:   /* Propagate to the tetrahedra above this face, if any (empty in a 2D mesh) */
251:   PetscCall(DMPlexGetSupport(dm, cell, &tsupport));
252:   PetscCall(DMPlexGetSupportSize(dm, cell, &tsupportSize));
253:   for (PetscInt ts = 0; ts < tsupportSize; ++ts) {
254:     const PetscInt tet = tsupport[ts];
255:     PetscInt       tval, tmaxedge = -1, teval;

257:     PetscCall(DMLabelGetValue(sbr->splitPoints, tet, &tval));
258:     if (tval == 3) continue;
259:     PetscCall(SBRGetTetMaxEdge_Private(tr, tet, &tmaxedge));
260:     PetscCall(DMLabelGetValue(sbr->splitPoints, tmaxedge, &teval));
261:     if (teval != 1) {
262:       PetscCall(DMLabelSetValue(sbr->splitPoints, tmaxedge, 1));
263:       PetscCall(DMPlexPointQueueEnqueue(queue, tmaxedge));
264:     }
265:     PetscCall(DMLabelSetValue(sbr->splitPoints, tet, 3));
266:   }
267:   PetscFunctionReturn(PETSC_SUCCESS);
268: }

270: /*
271:   Mark local edges that should be split, ensuring conformity of the mesh skeleton.

273:   This implements the closure step of Plaza & Carey, Section 3.1, generalized from 2D to 3D:
274:   whenever an edge is marked, every non-conforming face containing it has its own longest edge
275:   marked (as in the original 2D algorithm), and every tetrahedron touching such a face has its
276:   own longest edge marked in turn (the "2.1/2.2" steps of the paper's 3D outline). In a 2D mesh,
277:   the tetrahedron support of a face is empty and this reduces exactly to the original algorithm.

279:   The queue also receives the points marked on other processes from the label propagation. A
280:   face-level cell arriving this way is processed directly: the process that marked it has no
281:   access to the cells above it on this process, so the local closure must be completed here.
282:   Points of any other depth are ignored: vertices are never marked, and a cell arriving through
283:   an overlapped point SF already had its closure ensured by its owner, whose edge marks arrive
284:   through the same propagation.
285: */
286: static PetscErrorCode SBRSplitLocalEdges_Private(DMPlexTransform tr, DMPlexPointQueue queue)
287: {
288:   DMPlexRefine_SBR *sbr = (DMPlexRefine_SBR *)tr->data;
289:   DM                dm;
290:   PetscInt          eStart, eEnd, fStart, fEnd;

292:   PetscFunctionBegin;
293:   PetscCall(DMPlexTransformGetDM(tr, &dm));
294:   PetscCall(DMPlexGetDepthStratum(dm, 1, &eStart, &eEnd));
295:   PetscCall(DMPlexGetDepthStratum(dm, 2, &fStart, &fEnd));
296:   while (!DMPlexPointQueueEmpty(queue)) {
297:     PetscInt p = -1;

299:     PetscCall(DMPlexPointQueueDequeue(queue, &p));
300:     if (p >= eStart && p < eEnd) {
301:       const PetscInt *support;
302:       PetscInt        supportSize;

304:       PetscCall(DMPlexGetSupport(dm, p, &support));
305:       PetscCall(DMPlexGetSupportSize(dm, p, &supportSize));
306:       for (PetscInt s = 0; s < supportSize; ++s) {
307:         PetscInt cval;

309:         PetscCall(DMLabelGetValue(sbr->splitPoints, support[s], &cval));
310:         if (cval == 2) continue;
311:         PetscCall(SBRSplitFace_Private(tr, queue, support[s]));
312:       }
313:     } else if (p >= fStart && p < fEnd) PetscCall(SBRSplitFace_Private(tr, queue, p));
314:   }
315:   PetscFunctionReturn(PETSC_SUCCESS);
316: }

318: static PetscErrorCode splitPoint(PETSC_UNUSED DMLabel label, PetscInt p, PETSC_UNUSED PetscInt val, PetscCtx ctx)
319: {
320:   DMPlexPointQueue queue = (DMPlexPointQueue)ctx;

322:   PetscFunctionBegin;
323:   PetscCall(DMPlexPointQueueEnqueue(queue, p));
324:   PetscFunctionReturn(PETSC_SUCCESS);
325: }

327: /*
328:   The 'splitPoints' label marks mesh points to be divided. It marks edges with 1, triangles with 2, and tetrahedra with 3.
329:   Then the refinement type is calculated as follows:

331:     RT_VERTEX:                  vertex
332:     RT_EDGE:                    edge unsplit
333:     RT_EDGE_SPLIT:              edge split
334:     RT_TRIANGLE:                triangle unsplit
335:     RT_TRIANGLE_SPLIT:          maximal (2D) triangle with all edges split, subdivided regularly
336:     RT_TRIANGLE_SPLIT_ij:       triangle with edges i and j split, i bisected first
337:     RT_TRIANGLE_SPLIT_k:        triangle with only edge k split
338:     RT_TRIANGLE_SPLIT_FAN_k:    triangle with all edges split under a 3D cell, fanned around the midpoint of edge k
339:     RT_TET:                     tetrahedron unsplit
340:     RT_TET_SPLIT_BASE + code:   tetrahedron with marked edges bisected in a given order

342:   Following Plaza & Carey (2000), a marked cell is subdivided by bisecting its marked edges one at a
343:   time, longest first: each bisection splits every subsimplex containing that edge, so the ordered
344:   list of marked edges determines the whole subdivision, and the subdivision it induces on a face is
345:   the bisection of the face's own marked edges in the same relative order. The classification below
346:   therefore records the bisection order: for a pair of split triangle edges as the type
347:   RT_TRIANGLE_SPLIT_ij, and for a tetrahedron as code = sum_i (e_i + 1) 7^i, the little-endian
348:   base-7 encoding of its marked edges e_0 > e_1 > ... in bisection order, with edges e0..e5 numbered
349:   as documented at SBRGetTetEdges_Private(). All length comparisons use SBREdgePrecedes_Private(),
350:   whose geometric tie-breaking makes the order consistent between each face and the cells above it.

352:   A fully marked triangle under a tetrahedron is fanned around the midpoint of its first-bisected
353:   edge, matching the bisection cascade (the 4T partition of Rivara, Fig. 3 of the paper), and a
354:   fully marked tetrahedron is bisected 6 times like any other marked tetrahedron. The regular
355:   subdivisions are kept only for maximal (2D) triangles, where no compatibility with higher cells
356:   constrains the interior of the subdivision, preserving the original 2D behavior of this transform.
357: */
358: typedef enum {
359:   RT_VERTEX,
360:   RT_EDGE,
361:   RT_EDGE_SPLIT,
362:   RT_TRIANGLE,
363:   RT_TRIANGLE_SPLIT,
364:   RT_TRIANGLE_SPLIT_01,
365:   RT_TRIANGLE_SPLIT_10,
366:   RT_TRIANGLE_SPLIT_12,
367:   RT_TRIANGLE_SPLIT_21,
368:   RT_TRIANGLE_SPLIT_20,
369:   RT_TRIANGLE_SPLIT_02,
370:   RT_TRIANGLE_SPLIT_0,
371:   RT_TRIANGLE_SPLIT_1,
372:   RT_TRIANGLE_SPLIT_2,
373:   RT_TRIANGLE_SPLIT_FAN_0,
374:   RT_TRIANGLE_SPLIT_FAN_1,
375:   RT_TRIANGLE_SPLIT_FAN_2,
376:   RT_TET,
377:   RT_TET_SPLIT_BASE
378: } RefinementType;

380: static PetscErrorCode DMPlexTransformSetUp_SBR(DMPlexTransform tr)
381: {
382:   DMPlexRefine_SBR *sbr = (DMPlexRefine_SBR *)tr->data;
383:   DM                dm;
384:   DMLabel           active;
385:   PetscSF           pointSF;
386:   DMPlexPointQueue  queue = NULL;
387:   IS                refineIS;
388:   const PetscInt   *refineCells;
389:   PetscInt          pStart, pEnd, p, eStart, eEnd, e, edgeLenSize, Nc, c;
390:   PetscBool         empty;

392:   PetscFunctionBegin;
393:   PetscCall(DMPlexTransformGetDM(tr, &dm));
394:   PetscCall(DMLabelCreate(PETSC_COMM_SELF, "Split Points", &sbr->splitPoints));
395:   /* Create edge lengths */
396:   PetscCall(DMGetCoordinatesLocalSetUp(dm));
397:   PetscCall(DMPlexGetDepthStratum(dm, 1, &eStart, &eEnd));
398:   PetscCall(PetscSectionCreate(PETSC_COMM_SELF, &sbr->secEdgeLen));
399:   PetscCall(PetscSectionSetChart(sbr->secEdgeLen, eStart, eEnd));
400:   for (e = eStart; e < eEnd; ++e) PetscCall(PetscSectionSetDof(sbr->secEdgeLen, e, 1));
401:   PetscCall(PetscSectionSetUp(sbr->secEdgeLen));
402:   PetscCall(PetscSectionGetStorageSize(sbr->secEdgeLen, &edgeLenSize));
403:   PetscCall(PetscCalloc1(edgeLenSize, &sbr->edgeLen));
404:   /* Add edges of cells that are marked for refinement to edge queue */
405:   PetscCall(DMPlexTransformGetActive(tr, &active));
406:   PetscCheck(active, PetscObjectComm((PetscObject)tr), PETSC_ERR_ARG_WRONGSTATE, "DMPlexTransform must have an adaptation label in order to use SBR algorithm");
407:   PetscCall(DMPlexPointQueueCreate(1024, &queue));
408:   PetscCall(DMLabelGetStratumIS(active, DM_ADAPT_REFINE, &refineIS));
409:   PetscCall(DMLabelGetStratumSize(active, DM_ADAPT_REFINE, &Nc));
410:   if (refineIS) PetscCall(ISGetIndices(refineIS, &refineCells));
411:   for (c = 0; c < Nc; ++c) {
412:     const PetscInt cell = refineCells[c];
413:     PetscInt       depth;

415:     PetscCall(DMPlexGetPointDepth(dm, cell, &depth));
416:     if (depth == 1) {
417:       PetscCall(DMLabelSetValue(sbr->splitPoints, cell, 1));
418:       PetscCall(DMPlexPointQueueEnqueue(queue, cell));
419:     } else {
420:       PetscInt *closure = NULL;
421:       PetscInt  Ncl;

423:       PetscCall(DMLabelSetValue(sbr->splitPoints, cell, depth));
424:       PetscCall(DMPlexGetTransitiveClosure(dm, cell, PETSC_TRUE, &Ncl, &closure));
425:       for (PetscInt cl = 0; cl < 2 * Ncl; cl += 2) {
426:         const PetscInt edge = closure[cl];

428:         if (edge >= eStart && edge < eEnd) {
429:           PetscCall(DMLabelSetValue(sbr->splitPoints, edge, 1));
430:           PetscCall(DMPlexPointQueueEnqueue(queue, edge));
431:         }
432:       }
433:       PetscCall(DMPlexRestoreTransitiveClosure(dm, cell, PETSC_TRUE, &Ncl, &closure));
434:     }
435:   }
436:   if (refineIS) PetscCall(ISRestoreIndices(refineIS, &refineCells));
437:   PetscCall(ISDestroy(&refineIS));
438:   /* Setup communication */
439:   PetscCall(DMGetPointSF(dm, &pointSF));
440:   PetscCall(DMLabelPropagateBegin(sbr->splitPoints, pointSF));
441:   /* While edge queue is not empty: */
442:   PetscCall(DMPlexPointQueueEmptyCollective((PetscObject)dm, queue, &empty));
443:   while (!empty) {
444:     PetscCall(SBRSplitLocalEdges_Private(tr, queue));
445:     /* Communicate marked edges
446:          An easy implementation is to allocate an array the size of the number of points. We put the splitPoints marks into the
447:          array, and then call PetscSFReduce()+PetscSFBcast() to make the marks consistent.

449:          TODO: We could use in-place communication with a different SF
450:            We use MPI_SUM for the Reduce, and check the result against the rootdegree. If sum >= rootdegree+1, then the edge has
451:            already been marked. If not, it might have been handled on the process in this round, but we add it anyway.

453:            In order to update the queue with the new edges from the label communication, we use BcastAnOp(MPI_SUM), so that new
454:            values will have 1+0=1 and old values will have 1+1=2. Loop over these, resetting the values to 1, and adding any new
455:            edge to the queue.
456:     */
457:     PetscCall(DMLabelPropagatePush(sbr->splitPoints, pointSF, MPI_MAX, splitPoint, queue));
458:     PetscCall(DMPlexPointQueueEmptyCollective((PetscObject)dm, queue, &empty));
459:   }
460:   PetscCall(DMLabelPropagateEnd(sbr->splitPoints, pointSF));
461:   /* Calculate refineType for each cell */
462:   PetscCall(DMLabelCreate(PETSC_COMM_SELF, "Refine Type", &tr->trType));
463:   PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
464:   for (p = pStart; p < pEnd; ++p) {
465:     DMLabel        trType = tr->trType;
466:     DMPolytopeType ct;
467:     PetscInt       val;

469:     PetscCall(DMPlexGetCellType(dm, p, &ct));
470:     switch (ct) {
471:     case DM_POLYTOPE_POINT:
472:       PetscCall(DMLabelSetValue(trType, p, RT_VERTEX));
473:       break;
474:     case DM_POLYTOPE_SEGMENT:
475:       PetscCall(DMLabelGetValue(sbr->splitPoints, p, &val));
476:       if (val == 1) PetscCall(DMLabelSetValue(trType, p, RT_EDGE_SPLIT));
477:       else PetscCall(DMLabelSetValue(trType, p, RT_EDGE));
478:       break;
479:     case DM_POLYTOPE_TRIANGLE:
480:       PetscCall(DMLabelGetValue(sbr->splitPoints, p, &val));
481:       if (val == 2) {
482:         const PetscInt *cone;
483:         PetscInt        vals[3], i;
484:         PetscBool       prec;

486:         PetscCall(DMPlexGetCone(dm, p, &cone));
487:         for (i = 0; i < 3; ++i) {
488:           PetscCall(DMLabelGetValue(sbr->splitPoints, cone[i], &vals[i]));
489:           vals[i] = vals[i] < 0 ? 0 : vals[i];
490:         }
491:         if (vals[0] && vals[1] && vals[2]) {
492:           PetscInt suppSize, k = 0;

494:           /* A triangle below a 3D cell must be subdivided compatibly with the bisection cascade of
495:              the cells above it, fanning around the midpoint of its first-bisected edge; a maximal
496:              (2D) triangle keeps the regular subdivision used since the original 2D implementation */
497:           PetscCall(DMPlexGetSupportSize(dm, p, &suppSize));
498:           if (suppSize) {
499:             for (i = 1; i < 3; ++i) {
500:               PetscCall(SBREdgePrecedes_Private(tr, cone[i], cone[k], &prec));
501:               if (prec) k = i;
502:             }
503:             PetscCall(DMLabelSetValue(trType, p, RT_TRIANGLE_SPLIT_FAN_0 + k));
504:           } else PetscCall(DMLabelSetValue(trType, p, RT_TRIANGLE_SPLIT));
505:         } else if (vals[0] && vals[1]) {
506:           PetscCall(SBREdgePrecedes_Private(tr, cone[0], cone[1], &prec));
507:           PetscCall(DMLabelSetValue(trType, p, prec ? RT_TRIANGLE_SPLIT_01 : RT_TRIANGLE_SPLIT_10));
508:         } else if (vals[1] && vals[2]) {
509:           PetscCall(SBREdgePrecedes_Private(tr, cone[1], cone[2], &prec));
510:           PetscCall(DMLabelSetValue(trType, p, prec ? RT_TRIANGLE_SPLIT_12 : RT_TRIANGLE_SPLIT_21));
511:         } else if (vals[2] && vals[0]) {
512:           PetscCall(SBREdgePrecedes_Private(tr, cone[2], cone[0], &prec));
513:           PetscCall(DMLabelSetValue(trType, p, prec ? RT_TRIANGLE_SPLIT_20 : RT_TRIANGLE_SPLIT_02));
514:         } else if (vals[0]) PetscCall(DMLabelSetValue(trType, p, RT_TRIANGLE_SPLIT_0));
515:         else if (vals[1]) PetscCall(DMLabelSetValue(trType, p, RT_TRIANGLE_SPLIT_1));
516:         else if (vals[2]) PetscCall(DMLabelSetValue(trType, p, RT_TRIANGLE_SPLIT_2));
517:         else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cell %" PetscInt_FMT " does not fit any refinement type (%" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ")", p, vals[0], vals[1], vals[2]);
518:       } else PetscCall(DMLabelSetValue(trType, p, RT_TRIANGLE));
519:       break;
520:     case DM_POLYTOPE_TETRAHEDRON:
521:       PetscCall(DMLabelGetValue(sbr->splitPoints, p, &val));
522:       if (val == 3) {
523:         PetscInt edges[6], ord[6], na = 0, code = 0;

525:         PetscCall(SBRGetTetEdges_Private(dm, p, edges));
526:         for (PetscInt k = 0; k < 6; ++k) {
527:           PetscInt eval;

529:           PetscCall(DMLabelGetValue(sbr->splitPoints, edges[k], &eval));
530:           if (eval == 1) ord[na++] = k;
531:         }
532:         PetscCheck(na, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cell %" PetscInt_FMT " is marked for subdivision but has no marked edges", p);
533:         /* Insertion sort of the marked edges into bisection order */
534:         for (PetscInt i = 1; i < na; ++i) {
535:           const PetscInt ei = ord[i];
536:           PetscInt       j;

538:           for (j = i - 1; j >= 0; --j) {
539:             PetscBool prec;

541:             PetscCall(SBREdgePrecedes_Private(tr, edges[ei], edges[ord[j]], &prec));
542:             if (!prec) break;
543:             ord[j + 1] = ord[j];
544:           }
545:           ord[j + 1] = ei;
546:         }
547:         for (PetscInt i = na - 1; i >= 0; --i) code = code * 7 + (ord[i] + 1);
548:         PetscCall(DMLabelSetValue(trType, p, RT_TET_SPLIT_BASE + code));
549:       } else PetscCall(DMLabelSetValue(trType, p, RT_TET));
550:       break;
551:     default:
552:       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot handle points of type %s", DMPolytopeTypes[ct]);
553:     }
554:     PetscCall(DMLabelGetValue(sbr->splitPoints, p, &val));
555:   }
556:   /* Store the refine type of each point, read stratum by stratum in O(number of points) */
557:   {
558:     IS              valueIS;
559:     const PetscInt *values;
560:     PetscInt        Nv, defVal;

562:     PetscCall(PetscMalloc1(pEnd - pStart, &sbr->rt));
563:     PetscCall(DMLabelGetDefaultValue(tr->trType, &defVal));
564:     for (p = pStart; p < pEnd; ++p) sbr->rt[p - pStart] = defVal;
565:     PetscCall(DMLabelGetNumValues(tr->trType, &Nv));
566:     PetscCall(DMLabelGetValueIS(tr->trType, &valueIS));
567:     PetscCall(ISGetIndices(valueIS, &values));
568:     for (PetscInt v = 0; v < Nv; ++v) {
569:       IS              pointIS;
570:       const PetscInt *points;
571:       PetscInt        Np;

573:       PetscCall(DMLabelGetStratumIS(tr->trType, values[v], &pointIS));
574:       if (!pointIS) continue;
575:       PetscCall(ISGetLocalSize(pointIS, &Np));
576:       PetscCall(ISGetIndices(pointIS, &points));
577:       for (PetscInt i = 0; i < Np; ++i) sbr->rt[points[i] - pStart] = values[v];
578:       PetscCall(ISRestoreIndices(pointIS, &points));
579:       PetscCall(ISDestroy(&pointIS));
580:     }
581:     PetscCall(ISRestoreIndices(valueIS, &values));
582:     PetscCall(ISDestroy(&valueIS));
583:     sbr->rtStart = pStart;
584:     sbr->rtEnd   = pEnd;
585:   }
586:   /* Cleanup */
587:   PetscCall(DMPlexPointQueueDestroy(&queue));
588:   PetscFunctionReturn(PETSC_SUCCESS);
589: }

591: /* Append one cone entry {ft, fn, acp[0..fn-1], r} plus its matching ornt entry o */
592: static PetscErrorCode SBRAppendCone_Private(PetscInt cone[], PetscInt *coff, PetscInt maxCone, PetscInt ornt[], PetscInt *ooff, PetscInt maxOrnt, DMPolytopeType ft, PetscInt fn, const PetscInt acp[], PetscInt r, PetscInt o)
593: {
594:   PetscFunctionBeginHot;
595:   PetscCheck(*coff + 3 + fn <= maxCone && *ooff + 1 <= maxOrnt, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Cone buffer of size (%" PetscInt_FMT ", %" PetscInt_FMT ") is too small", maxCone, maxOrnt);
596:   cone[(*coff)++] = (PetscInt)ft;
597:   cone[(*coff)++] = fn;
598:   for (PetscInt i = 0; i < fn; ++i) cone[(*coff)++] = acp[i];
599:   cone[(*coff)++] = r;
600:   ornt[(*ooff)++] = o;
601:   PetscFunctionReturn(PETSC_SUCCESS);
602: }

604: /*
605:   Symbolic subdivision machinery

607:   Subdivisions are worked out on a canonical reference cell, in terms of symbols: for a triangle,
608:   0-2 denote its vertices and 3+e the midpoint of its edge e; for a tetrahedron, 0-3 denote its
609:   vertices and 4+e the midpoint of its edge e. Everything is purely combinatorial, so the results
610:   depend only on the refinement type, never on mesh coordinates.
611: */

613: typedef struct {
614:   PetscInt nseg;      /* Number of segments added inside the triangle */
615:   PetscInt ntri;      /* Number of subtriangles */
616:   PetscInt seg[3][2]; /* The endpoints of each added segment, in its canonical direction */
617:   PetscInt tri[4][3]; /* The vertices of each subtriangle, in canonical cone order */
618: } SBRTriSubdiv;

620: /* Map a triangle symbol authored against arrangement o of the triangle to the actual cone numbering */
621: static PetscInt SBRTriRelabel_Private(PetscInt o, PetscInt s)
622: {
623:   const PetscInt *arr = DMPolytopeTypeGetArrangement(DM_POLYTOPE_TRIANGLE, o);

625:   if (s < 3) return triEdgeVert[arr[s * 2]][arr[s * 2 + 1] ? 1 : 0];
626:   return 3 + arr[(s - 3) * 2];
627: }

629: /*
630:   Compute the symbolic subdivision of a triangle: nsplit = 0 leaves it whole, nsplit = 1 bisects
631:   edge 'first', nsplit = 2 bisects edge 'first' and then edge 'second', and nsplit = 3 bisects all
632:   three edges starting with edge 'first' (the fan, where the order of the remaining two does not
633:   affect the result). The subcells are listed exactly as produced, in replica order, by the identity
634:   transform, SBRGetTriangleSplitSingle(), SBRGetTriangleSplitDouble(), and
635:   SBRGetTriangleSplitFan_Private(): each case is authored here for the canonical arrangement and
636:   relabeled through the same arrangement its template is dispatched with.
637: */
638: static PetscErrorCode SBRTriangleSubdiv_Private(PetscInt nsplit, PetscInt first, PetscInt second, SBRTriSubdiv *sub)
639: {
640:   static const SBRTriSubdiv unsplitS = {0, 1, {{0, 0}}, {{0, 1, 2}}};
641:   static const SBRTriSubdiv singleS  = {
642:     1, 2, {{0, 4}},
643:       {{0, 1, 4}, {4, 2, 0}}
644:   };
645:   static const SBRTriSubdiv doubleS = {
646:     2, 3, {{0, 4}, {4, 5}},
647:       {{0, 1, 4}, {4, 2, 5}, {5, 0, 4}}
648:   };
649:   /* The reflected double split (second = first - 1), authored for first = 2, second = 1: the
650:      template emits its subtriangle cones starting from different corners than a plain reflection
651:      of the rotated instances, so it gets its own canonical tuples */
652:   static const SBRTriSubdiv doubleRS = {
653:     2, 3, {{1, 5}, {5, 4}},
654:       {{5, 0, 1}, {4, 2, 5}, {1, 4, 5}}
655:   };
656:   static const SBRTriSubdiv fanS = {
657:     3, 4, {{0, 4}, {4, 3}, {4, 5}},
658:       {{0, 3, 4}, {3, 1, 4}, {5, 4, 2}, {0, 4, 5}}
659:   };
660:   const SBRTriSubdiv *canon;
661:   PetscInt            o;

663:   PetscFunctionBeginHot;
664:   switch (nsplit) {
665:   case 0:
666:     canon = &unsplitS;
667:     o     = 0;
668:     break;
669:   case 1:
670:   case 3:
671:     canon = nsplit == 1 ? &singleS : &fanS;
672:     o     = (first + 2) % 3;
673:     break;
674:   case 2:
675:     if (second == (first + 1) % 3) {
676:       canon = &doubleS;
677:       o     = (first + 2) % 3;
678:     } else {
679:       canon = &doubleRS;
680:       o     = (first + 1) % 3;
681:     }
682:     break;
683:   default:
684:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid number of split edges %" PetscInt_FMT, nsplit);
685:   }
686:   sub->nseg = canon->nseg;
687:   sub->ntri = canon->ntri;
688:   for (PetscInt s = 0; s < canon->nseg; ++s)
689:     for (PetscInt i = 0; i < 2; ++i) sub->seg[s][i] = SBRTriRelabel_Private(o, canon->seg[s][i]);
690:   for (PetscInt t = 0; t < canon->ntri; ++t)
691:     for (PetscInt i = 0; i < 3; ++i) sub->tri[t][i] = SBRTriRelabel_Private(o, canon->tri[t][i]);
692:   PetscFunctionReturn(PETSC_SUCCESS);
693: }

695: #define SBR_TET_MAX_SEGS   16
696: #define SBR_TET_MAX_TRIS   32
697: #define SBR_TET_MAX_LEAVES 16
698: #define SBR_TET_MAX_CONE   2048
699: #define SBR_TET_MAX_ORNT   512

701: typedef struct {
702:   PetscInt nseg, ntri, nleaf;
703:   PetscInt seg[SBR_TET_MAX_SEGS][2];    /* Interior segments, in their canonical direction */
704:   PetscInt tri[SBR_TET_MAX_TRIS][3];    /* Interior triangles, in canonical cone order */
705:   PetscInt leaf[SBR_TET_MAX_LEAVES][4]; /* Subtetrahedra, in canonical vertex order */
706: } SBRTetSubdiv;

708: /* The faces of the tetrahedron containing a given symbol, as a bitmask over f0..f3 */
709: static PetscInt SBRTetSymbolFaces_Private(PetscInt s)
710: {
711:   return s < 4 ? tetVertFaces[s] : tetEdgeFaces[s - 4];
712: }

714: static PetscInt SBRTupleCompare_Private(PetscInt n, const PetscInt a[], const PetscInt b[])
715: {
716:   for (PetscInt i = 0; i < n; ++i)
717:     if (a[i] != b[i]) return a[i] < b[i] ? -1 : 1;
718:   return 0;
719: }

721: static PetscBool SBRTupleMatch_Private(PetscInt n, const PetscInt a[], const PetscInt b[])
722: {
723:   for (PetscInt i = 0; i < n; ++i) {
724:     PetscInt j;

726:     for (j = 0; j < n; ++j)
727:       if (a[i] == b[j]) break;
728:     if (j == n) return PETSC_FALSE;
729:   }
730:   return PETSC_TRUE;
731: }

733: static void SBRTetDecodeOrder_Private(PetscInt code, PetscInt ord[6], PetscInt *na)
734: {
735:   *na = 0;
736:   while (code) {
737:     ord[(*na)++] = code % 7 - 1;
738:     code /= 7;
739:   }
740: }

742: /* Add the interior segment (P, Q) if it is not already present */
743: static PetscErrorCode SBRTetAddSeg_Private(SBRTetSubdiv *sub, PetscInt P, PetscInt Q)
744: {
745:   PetscFunctionBeginHot;
746:   for (PetscInt s = 0; s < sub->nseg; ++s)
747:     if ((sub->seg[s][0] == P && sub->seg[s][1] == Q) || (sub->seg[s][0] == Q && sub->seg[s][1] == P)) PetscFunctionReturn(PETSC_SUCCESS);
748:   PetscCheck(sub->nseg < SBR_TET_MAX_SEGS, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Too many interior segments");
749:   sub->seg[sub->nseg][0] = P;
750:   sub->seg[sub->nseg][1] = Q;
751:   ++sub->nseg;
752:   PetscFunctionReturn(PETSC_SUCCESS);
753: }

755: /*
756:   Subdivide the reference tetrahedron by bisecting the given edges in the given order. Each
757:   bisection splits every current subsimplex containing the edge (Lemma 1.1 of Plaza & Carey (2000)):
758:   the leaf subtetrahedra, the interior triangles created by earlier bisections, and implicitly the
759:   faces of the tetrahedron, whose subdivision is not tracked here because each face is subdivided by
760:   its own transform, consistently, since its refinement type orders its marked edges with the same
761:   comparison (see RefinementType). Only the segments and triangles strictly interior to the
762:   tetrahedron are recorded as its own subcells; everything on the boundary belongs to a face.
763: */
764: static PetscErrorCode SBRTetSubdivide_Private(const PetscInt ord[], PetscInt na, SBRTetSubdiv *sub)
765: {
766:   PetscFunctionBegin;
767:   sub->nseg  = 0;
768:   sub->ntri  = 0;
769:   sub->nleaf = 1;
770:   for (PetscInt i = 0; i < 4; ++i) sub->leaf[0][i] = i;
771:   for (PetscInt s = 0; s < na; ++s) {
772:     const PetscInt e = ord[s], a = tetEdgeVert[e][0], b = tetEdgeVert[e][1], m = 4 + e;

774:     for (PetscInt t = 0; t < sub->ntri; ++t) {
775:       PetscInt pa = -1, pb = -1;

777:       for (PetscInt i = 0; i < 3; ++i) {
778:         if (sub->tri[t][i] == a) pa = i;
779:         else if (sub->tri[t][i] == b) pb = i;
780:       }
781:       if (pa < 0 || pb < 0) continue;
782:       PetscCheck(sub->ntri < SBR_TET_MAX_TRIS, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Too many interior triangles");
783:       PetscCall(PetscArraymove(&sub->tri[t + 2][0], &sub->tri[t + 1][0], 3 * (sub->ntri - t - 1)));
784:       PetscCall(PetscArraycpy(sub->tri[t + 1], sub->tri[t], 3));
785:       PetscCall(SBRTetAddSeg_Private(sub, sub->tri[t][3 - pa - pb], m));
786:       sub->tri[t][pb]     = m;
787:       sub->tri[t + 1][pa] = m;
788:       ++sub->ntri;
789:       ++t;
790:     }
791:     for (PetscInt l = 0; l < sub->nleaf; ++l) {
792:       PetscInt pa = -1, pb = -1, *newtri;

794:       for (PetscInt i = 0; i < 4; ++i) {
795:         if (sub->leaf[l][i] == a) pa = i;
796:         else if (sub->leaf[l][i] == b) pb = i;
797:       }
798:       if (pa < 0 || pb < 0) continue;
799:       PetscCheck(sub->nleaf < SBR_TET_MAX_LEAVES && sub->ntri < SBR_TET_MAX_TRIS, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Too many subcells");
800:       PetscCall(PetscArraymove(&sub->leaf[l + 2][0], &sub->leaf[l + 1][0], 4 * (sub->nleaf - l - 1)));
801:       PetscCall(PetscArraycpy(sub->leaf[l + 1], sub->leaf[l], 4));
802:       sub->leaf[l][pb]     = m;
803:       sub->leaf[l + 1][pa] = m;
804:       ++sub->nleaf;
805:       /* Record the interior triangle separating the two children, and its interior median edges */
806:       newtri = sub->tri[sub->ntri++];
807:       for (PetscInt i = 0; i < 3; ++i) newtri[i] = sub->leaf[l + 1][tetOppFace[pb][i]];
808:       for (PetscInt i = 0; i < 3; ++i) {
809:         const PetscInt P = newtri[i], Q = newtri[(i + 1) % 3], other = P == m ? Q : P;

811:         if (P != m && Q != m) continue;
812:         if (SBRTetSymbolFaces_Private(m) & SBRTetSymbolFaces_Private(other)) continue;
813:         PetscCall(SBRTetAddSeg_Private(sub, other, m));
814:       }
815:       ++l;
816:     }
817:   }
818:   PetscFunctionReturn(PETSC_SUCCESS);
819: }

821: /* The subdivision of face f of the tetrahedron, relabeled from face symbols into tetrahedron symbols */
822: static PetscErrorCode SBRTetFaceSubdiv_Private(const PetscInt ord[], PetscInt na, PetscInt f, SBRTriSubdiv *sub)
823: {
824:   PetscInt fl[3], nfm = 0;

826:   PetscFunctionBeginHot;
827:   for (PetscInt s = 0; s < na; ++s)
828:     for (PetscInt l = 0; l < 3; ++l)
829:       if (tetFaceEdge[f][l] == ord[s]) fl[nfm++] = l;
830:   PetscCall(SBRTriangleSubdiv_Private(nfm, nfm > 0 ? fl[0] : -1, nfm > 1 ? fl[1] : -1, sub));
831:   for (PetscInt s = 0; s < sub->nseg; ++s)
832:     for (PetscInt i = 0; i < 2; ++i) sub->seg[s][i] = sub->seg[s][i] < 3 ? tetFaceVert[f][sub->seg[s][i]] : 4 + tetFaceEdge[f][sub->seg[s][i] - 3];
833:   for (PetscInt t = 0; t < sub->ntri; ++t)
834:     for (PetscInt i = 0; i < 3; ++i) sub->tri[t][i] = sub->tri[t][i] < 3 ? tetFaceVert[f][sub->tri[t][i]] : 4 + tetFaceEdge[f][sub->tri[t][i] - 3];
835:   PetscFunctionReturn(PETSC_SUCCESS);
836: }

838: /* Emit the cone entry for the segment (P, Q): a whole original edge, half of a split edge, a
839:    segment added inside a face, or a segment interior to the tetrahedron */
840: static PetscErrorCode SBRTetEmitSegRef_Private(const SBRTetSubdiv *sub, const SBRTriSubdiv fsub[], PetscInt P, PetscInt Q, PetscInt cone[], PetscInt *coff, PetscInt ornt[], PetscInt *ooff)
841: {
842:   PetscFunctionBeginHot;
843:   if (P < 4 && Q < 4) {
844:     const PetscInt e = SBREdgeIndexFromVerts_Private(P, Q);

846:     PetscCall(SBRAppendCone_Private(cone, coff, SBR_TET_MAX_CONE, ornt, ooff, SBR_TET_MAX_ORNT, DM_POLYTOPE_SEGMENT, 2, tetEdgeFaceLoc[e], 0, tetEdgeVert[e][0] == P ? 0 : -1));
847:     PetscFunctionReturn(PETSC_SUCCESS);
848:   }
849:   if (P < 4 || Q < 4) {
850:     const PetscInt v = P < 4 ? P : Q, e = (P < 4 ? Q : P) - 4;

852:     if (tetEdgeVert[e][0] == v || tetEdgeVert[e][1] == v) {
853:       const PetscInt r = tetEdgeVert[e][0] == v ? 0 : 1;

855:       /* Half of split edge e: replica 0 runs from the edge tail to the midpoint, replica 1 from the midpoint to the head */
856:       PetscCall(SBRAppendCone_Private(cone, coff, SBR_TET_MAX_CONE, ornt, ooff, SBR_TET_MAX_ORNT, DM_POLYTOPE_SEGMENT, 2, tetEdgeFaceLoc[e], r, (r == 0) == (P == v) ? 0 : -1));
857:       PetscFunctionReturn(PETSC_SUCCESS);
858:     }
859:   }
860:   {
861:     const PetscInt mask = SBRTetSymbolFaces_Private(P) & SBRTetSymbolFaces_Private(Q);

863:     if (mask) {
864:       PetscInt f = 0;

866:       while (!(mask & (1 << f))) ++f;
867:       for (PetscInt r = 0; r < fsub[f].nseg; ++r) {
868:         if ((fsub[f].seg[r][0] == P && fsub[f].seg[r][1] == Q) || (fsub[f].seg[r][0] == Q && fsub[f].seg[r][1] == P)) {
869:           const PetscInt acp[1] = {f};

871:           PetscCall(SBRAppendCone_Private(cone, coff, SBR_TET_MAX_CONE, ornt, ooff, SBR_TET_MAX_ORNT, DM_POLYTOPE_SEGMENT, 1, acp, r, fsub[f].seg[r][0] == P ? 0 : -1));
872:           PetscFunctionReturn(PETSC_SUCCESS);
873:         }
874:       }
875:       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Segment (%" PetscInt_FMT ", %" PetscInt_FMT ") not found in the subdivision of face %" PetscInt_FMT, P, Q, f);
876:     }
877:     for (PetscInt r = 0; r < sub->nseg; ++r) {
878:       if ((sub->seg[r][0] == P && sub->seg[r][1] == Q) || (sub->seg[r][0] == Q && sub->seg[r][1] == P)) {
879:         PetscCall(SBRAppendCone_Private(cone, coff, SBR_TET_MAX_CONE, ornt, ooff, SBR_TET_MAX_ORNT, DM_POLYTOPE_SEGMENT, 0, NULL, r, sub->seg[r][0] == P ? 0 : -1));
880:         PetscFunctionReturn(PETSC_SUCCESS);
881:       }
882:     }
883:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Interior segment (%" PetscInt_FMT ", %" PetscInt_FMT ") not found", P, Q);
884:   }
885: }

887: /* Emit the cone entry for the triangle with vertex cycle C: a subtriangle of a face, or a triangle
888:    interior to the tetrahedron */
889: static PetscErrorCode SBRTetEmitTriRef_Private(const SBRTetSubdiv *sub, const SBRTriSubdiv fsub[], const PetscInt C[3], PetscInt cone[], PetscInt *coff, PetscInt ornt[], PetscInt *ooff)
890: {
891:   const PetscInt mask = SBRTetSymbolFaces_Private(C[0]) & SBRTetSymbolFaces_Private(C[1]) & SBRTetSymbolFaces_Private(C[2]);
892:   PetscInt       o;

894:   PetscFunctionBeginHot;
895:   if (mask) {
896:     PetscInt f = 0;

898:     while (!(mask & (1 << f))) ++f;
899:     for (PetscInt r = 0; r < fsub[f].ntri; ++r) {
900:       if (SBRTupleMatch_Private(3, fsub[f].tri[r], C)) {
901:         const PetscInt acp[1] = {f};

903:         PetscCall(DMPolytopeGetVertexOrientation(DM_POLYTOPE_TRIANGLE, fsub[f].tri[r], C, &o));
904:         PetscCall(SBRAppendCone_Private(cone, coff, SBR_TET_MAX_CONE, ornt, ooff, SBR_TET_MAX_ORNT, DM_POLYTOPE_TRIANGLE, 1, acp, r, o));
905:         PetscFunctionReturn(PETSC_SUCCESS);
906:       }
907:     }
908:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Triangle (%" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ") not found in the subdivision of face %" PetscInt_FMT, C[0], C[1], C[2], f);
909:   }
910:   for (PetscInt r = 0; r < sub->ntri; ++r) {
911:     if (SBRTupleMatch_Private(3, sub->tri[r], C)) {
912:       PetscCall(DMPolytopeGetVertexOrientation(DM_POLYTOPE_TRIANGLE, sub->tri[r], C, &o));
913:       PetscCall(SBRAppendCone_Private(cone, coff, SBR_TET_MAX_CONE, ornt, ooff, SBR_TET_MAX_ORNT, DM_POLYTOPE_TRIANGLE, 0, NULL, r, o));
914:       PetscFunctionReturn(PETSC_SUCCESS);
915:     }
916:   }
917:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Interior triangle (%" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ") not found", C[0], C[1], C[2]);
918: }

920: /* Emit the cone and orientation data for the subdivision of a tetrahedron */
921: static PetscErrorCode SBRTetEmit_Private(const PetscInt ord[], PetscInt na, const SBRTetSubdiv *sub, PetscInt *Nt, DMPolytopeType target[], PetscInt size[], PetscInt cone[], PetscInt *Ncone, PetscInt ornt[], PetscInt *Nornt)
922: {
923:   SBRTriSubdiv fsub[4];
924:   PetscInt     coff = 0, ooff = 0, n = 0;

926:   PetscFunctionBegin;
927:   for (PetscInt f = 0; f < 4; ++f) PetscCall(SBRTetFaceSubdiv_Private(ord, na, f, &fsub[f]));
928:   for (PetscInt s = 0; s < sub->nseg; ++s) {
929:     for (PetscInt i = 0; i < 2; ++i) {
930:       const PetscInt sym = sub->seg[s][i];

932:       if (sym < 4) PetscCall(SBRAppendCone_Private(cone, &coff, SBR_TET_MAX_CONE, ornt, &ooff, SBR_TET_MAX_ORNT, DM_POLYTOPE_POINT, 3, tetVertPath[sym], 0, 0));
933:       else PetscCall(SBRAppendCone_Private(cone, &coff, SBR_TET_MAX_CONE, ornt, &ooff, SBR_TET_MAX_ORNT, DM_POLYTOPE_POINT, 2, tetEdgeFaceLoc[sym - 4], 0, 0));
934:     }
935:   }
936:   for (PetscInt t = 0; t < sub->ntri; ++t)
937:     for (PetscInt i = 0; i < 3; ++i) PetscCall(SBRTetEmitSegRef_Private(sub, fsub, sub->tri[t][i], sub->tri[t][(i + 1) % 3], cone, &coff, ornt, &ooff));
938:   for (PetscInt l = 0; l < sub->nleaf; ++l) {
939:     for (PetscInt f = 0; f < 4; ++f) {
940:       /* The face f of the child tetrahedron is the face opposite its vertex 3 - f */
941:       const PetscInt mp = 3 - f;
942:       PetscInt       C[3];

944:       for (PetscInt i = 0; i < 3; ++i) C[i] = sub->leaf[l][tetOppFace[mp][i]];
945:       PetscCall(SBRTetEmitTriRef_Private(sub, fsub, C, cone, &coff, ornt, &ooff));
946:     }
947:   }
948:   if (sub->nseg) {
949:     target[n] = DM_POLYTOPE_SEGMENT;
950:     size[n]   = sub->nseg;
951:     ++n;
952:   }
953:   target[n] = DM_POLYTOPE_TRIANGLE;
954:   size[n]   = sub->ntri;
955:   ++n;
956:   target[n] = DM_POLYTOPE_TETRAHEDRON;
957:   size[n]   = sub->nleaf;
958:   ++n;
959:   *Nt    = n;
960:   *Ncone = coff;
961:   *Nornt = ooff;
962:   PetscFunctionReturn(PETSC_SUCCESS);
963: }

965: /* Get the subdivision data for the encoded bisection order, generating and caching it on first use */
966: static PetscErrorCode SBRGetTetSplit_Private(DMPlexTransform tr, PetscInt code, PetscInt *Nt, DMPolytopeType *target[], PetscInt *size[], PetscInt *cone[], PetscInt *ornt[])
967: {
968:   DMPlexRefine_SBR *sbr = (DMPlexRefine_SBR *)tr->data;
969:   PetscInt          i;

971:   PetscFunctionBeginHot;
972:   PetscCall(PetscHMapIGetWithDefault(sbr->cacheMap, code, sbr->Ncache, &i));
973:   if (i == sbr->Ncache) {
974:     SBRTetSubdiv   sub;
975:     DMPolytopeType targetTmp[3];
976:     PetscInt       sizeTmp[3], coneTmp[SBR_TET_MAX_CONE], orntTmp[SBR_TET_MAX_ORNT];
977:     PetscInt       ord[6], na, NtTmp, Ncone, Nornt;

979:     SBRTetDecodeOrder_Private(code, ord, &na);
980:     PetscCall(SBRTetSubdivide_Private(ord, na, &sub));
981:     PetscCall(SBRTetEmit_Private(ord, na, &sub, &NtTmp, targetTmp, sizeTmp, coneTmp, &Ncone, orntTmp, &Nornt));
982:     if (sbr->Ncache == sbr->maxCache) {
983:       const PetscInt   newmax = PetscMax(2 * sbr->maxCache, 16);
984:       PetscInt        *newCode, *newNt, **newSize, **newCone, **newOrnt;
985:       DMPolytopeType **newTarget;

987:       PetscCall(PetscMalloc6(newmax, &newCode, newmax, &newNt, newmax, &newTarget, newmax, &newSize, newmax, &newCone, newmax, &newOrnt));
988:       PetscCall(PetscArraycpy(newCode, sbr->cacheCode, sbr->Ncache));
989:       PetscCall(PetscArraycpy(newNt, sbr->cacheNt, sbr->Ncache));
990:       PetscCall(PetscArraycpy(newTarget, sbr->cacheTarget, sbr->Ncache));
991:       PetscCall(PetscArraycpy(newSize, sbr->cacheSize, sbr->Ncache));
992:       PetscCall(PetscArraycpy(newCone, sbr->cacheCone, sbr->Ncache));
993:       PetscCall(PetscArraycpy(newOrnt, sbr->cacheOrnt, sbr->Ncache));
994:       PetscCall(PetscFree6(sbr->cacheCode, sbr->cacheNt, sbr->cacheTarget, sbr->cacheSize, sbr->cacheCone, sbr->cacheOrnt));
995:       sbr->cacheCode   = newCode;
996:       sbr->cacheNt     = newNt;
997:       sbr->cacheTarget = newTarget;
998:       sbr->cacheSize   = newSize;
999:       sbr->cacheCone   = newCone;
1000:       sbr->cacheOrnt   = newOrnt;
1001:       sbr->maxCache    = newmax;
1002:     }
1003:     PetscCall(PetscMalloc1(NtTmp, &sbr->cacheTarget[i]));
1004:     PetscCall(PetscMalloc1(NtTmp, &sbr->cacheSize[i]));
1005:     PetscCall(PetscMalloc1(Ncone, &sbr->cacheCone[i]));
1006:     PetscCall(PetscMalloc1(Nornt, &sbr->cacheOrnt[i]));
1007:     PetscCall(PetscArraycpy(sbr->cacheTarget[i], targetTmp, NtTmp));
1008:     PetscCall(PetscArraycpy(sbr->cacheSize[i], sizeTmp, NtTmp));
1009:     PetscCall(PetscArraycpy(sbr->cacheCone[i], coneTmp, Ncone));
1010:     PetscCall(PetscArraycpy(sbr->cacheOrnt[i], orntTmp, Nornt));
1011:     sbr->cacheCode[i] = code;
1012:     sbr->cacheNt[i]   = NtTmp;
1013:     ++sbr->Ncache;
1014:     PetscCall(PetscHMapISet(sbr->cacheMap, code, i));
1015:   }
1016:   *Nt     = sbr->cacheNt[i];
1017:   *target = sbr->cacheTarget[i];
1018:   *size   = sbr->cacheSize[i];
1019:   *cone   = sbr->cacheCone[i];
1020:   *ornt   = sbr->cacheOrnt[i];
1021:   PetscFunctionReturn(PETSC_SUCCESS);
1022: }

1024: /*
1025:   Map the subcell (r, o) of a split triangle, authored against arrangement so of the triangle, to
1026:   the matching subcell of the triangle's own production: both subdivisions are reconstructed
1027:   symbolically, the authored subcell is relabeled through the arrangement, and matched against the
1028:   actual subcells
1029: */
1030: static PetscErrorCode SBRTriangleOrient_Private(PetscInt rt, PetscInt so, DMPolytopeType tct, PetscInt r, PetscInt o, PetscInt *rnew, PetscInt *onew)
1031: {
1032:   const PetscInt *arr = DMPolytopeTypeGetArrangement(DM_POLYTOPE_TRIANGLE, so);
1033:   SBRTriSubdiv    subT, subV;
1034:   const PetscInt *tupleV, *canonT;
1035:   PetscInt        inv[3], tuple[3], n, nlist, nsplit, first, second = -1, r2, dO;

1037:   PetscFunctionBeginHot;
1038:   switch (rt) {
1039:   case RT_TRIANGLE_SPLIT_0:
1040:   case RT_TRIANGLE_SPLIT_1:
1041:   case RT_TRIANGLE_SPLIT_2:
1042:     nsplit = 1;
1043:     first  = rt - RT_TRIANGLE_SPLIT_0;
1044:     break;
1045:   case RT_TRIANGLE_SPLIT_FAN_0:
1046:   case RT_TRIANGLE_SPLIT_FAN_1:
1047:   case RT_TRIANGLE_SPLIT_FAN_2:
1048:     nsplit = 3;
1049:     first  = rt - RT_TRIANGLE_SPLIT_FAN_0;
1050:     break;
1051:   case RT_TRIANGLE_SPLIT_01:
1052:   case RT_TRIANGLE_SPLIT_10:
1053:   case RT_TRIANGLE_SPLIT_12:
1054:   case RT_TRIANGLE_SPLIT_21:
1055:   case RT_TRIANGLE_SPLIT_20:
1056:   case RT_TRIANGLE_SPLIT_02: {
1057:     static const PetscInt pairs[6][2] = {
1058:       {0, 1},
1059:       {1, 0},
1060:       {1, 2},
1061:       {2, 1},
1062:       {2, 0},
1063:       {0, 2}
1064:     };

1066:     nsplit = 2;
1067:     first  = pairs[rt - RT_TRIANGLE_SPLIT_01][0];
1068:     second = pairs[rt - RT_TRIANGLE_SPLIT_01][1];
1069:   } break;
1070:   default:
1071:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid refinement type %" PetscInt_FMT, rt);
1072:   }
1073:   for (PetscInt l = 0; l < 3; ++l) inv[arr[l * 2]] = l;
1074:   PetscCall(SBRTriangleSubdiv_Private(nsplit, first, second, &subT));
1075:   PetscCall(SBRTriangleSubdiv_Private(nsplit, inv[first], second < 0 ? -1 : inv[second], &subV));
1076:   if (tct == DM_POLYTOPE_SEGMENT) {
1077:     n      = 2;
1078:     nlist  = subT.nseg;
1079:     tupleV = subV.seg[r];
1080:   } else {
1081:     n      = 3;
1082:     nlist  = subT.ntri;
1083:     tupleV = subV.tri[r];
1084:   }
1085:   for (PetscInt i = 0; i < n; ++i) tuple[i] = SBRTriRelabel_Private(so, tupleV[i]);
1086:   for (r2 = 0; r2 < nlist; ++r2) {
1087:     canonT = tct == DM_POLYTOPE_SEGMENT ? subT.seg[r2] : subT.tri[r2];
1088:     if (SBRTupleMatch_Private(n, canonT, tuple)) break;
1089:   }
1090:   PetscCheck(r2 < nlist, PETSC_COMM_SELF, PETSC_ERR_PLIB, "No matching %s subcell for replica %" PetscInt_FMT " at orientation %" PetscInt_FMT, DMPolytopeTypes[tct], r, so);
1091:   PetscCall(DMPolytopeGetVertexOrientation(tct, canonT, tuple, &dO));
1092:   *rnew = r2;
1093:   *onew = DMPolytopeTypeComposeOrientation(tct, o, dO);
1094:   PetscFunctionReturn(PETSC_SUCCESS);
1095: }

1097: /* The images of the tetrahedron edges under the vertex permutation varr */
1098: static void SBRTetEdgeImage_Private(const PetscInt varr[], PetscInt medge[6])
1099: {
1100:   for (PetscInt e = 0; e < 6; ++e) medge[e] = SBREdgeIndexFromVerts_Private(varr[tetEdgeVert[e][0]], varr[tetEdgeVert[e][1]]);
1101: }

1103: /* The tetrahedron analogue of SBRTriangleOrient_Private() */
1104: static PetscErrorCode SBRTetOrient_Private(PetscInt code, PetscInt so, DMPolytopeType tct, PetscInt r, PetscInt o, PetscInt *rnew, PetscInt *onew)
1105: {
1106:   const PetscInt *varr = DMPolytopeTypeGetVertexArrangement(DM_POLYTOPE_TETRAHEDRON, so);
1107:   SBRTetSubdiv    subT, subV;
1108:   const PetscInt *tupleV, *canonT = NULL;
1109:   PetscInt        medge[6], minv[6], ordT[6], ordV[6], na, tuple[4], n, nlist, r2, dO;

1111:   PetscFunctionBeginHot;
1112:   SBRTetDecodeOrder_Private(code, ordT, &na);
1113:   SBRTetEdgeImage_Private(varr, medge);
1114:   for (PetscInt e = 0; e < 6; ++e) minv[medge[e]] = e;
1115:   for (PetscInt i = 0; i < na; ++i) ordV[i] = minv[ordT[i]];
1116:   PetscCall(SBRTetSubdivide_Private(ordT, na, &subT));
1117:   PetscCall(SBRTetSubdivide_Private(ordV, na, &subV));
1118:   switch (tct) {
1119:   case DM_POLYTOPE_SEGMENT:
1120:     n      = 2;
1121:     nlist  = subT.nseg;
1122:     tupleV = subV.seg[r];
1123:     break;
1124:   case DM_POLYTOPE_TRIANGLE:
1125:     n      = 3;
1126:     nlist  = subT.ntri;
1127:     tupleV = subV.tri[r];
1128:     break;
1129:   case DM_POLYTOPE_TETRAHEDRON:
1130:     n      = 4;
1131:     nlist  = subT.nleaf;
1132:     tupleV = subV.leaf[r];
1133:     break;
1134:   default:
1135:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid target type %s", DMPolytopeTypes[tct]);
1136:   }
1137:   for (PetscInt i = 0; i < n; ++i) tuple[i] = tupleV[i] < 4 ? varr[tupleV[i]] : 4 + medge[tupleV[i] - 4];
1138:   for (r2 = 0; r2 < nlist; ++r2) {
1139:     canonT = tct == DM_POLYTOPE_SEGMENT ? subT.seg[r2] : (tct == DM_POLYTOPE_TRIANGLE ? subT.tri[r2] : subT.leaf[r2]);
1140:     if (SBRTupleMatch_Private(n, canonT, tuple)) break;
1141:   }
1142:   PetscCheck(r2 < nlist, PETSC_COMM_SELF, PETSC_ERR_PLIB, "No matching %s subcell for replica %" PetscInt_FMT " at orientation %" PetscInt_FMT, DMPolytopeTypes[tct], r, so);
1143:   PetscCall(DMPolytopeGetVertexOrientation(tct, canonT, tuple, &dO));
1144:   *rnew = r2;
1145:   *onew = DMPolytopeTypeComposeOrientation(tct, o, dO);
1146:   PetscFunctionReturn(PETSC_SUCCESS);
1147: }

1149: /*
1150:   Validate the subdivision generator against the enumeration of Plaza & Carey (2000): over all
1151:   possible edge length orders and all conforming sets of marked edges, there are exactly 51
1152:   subdivision classes up to rotation, distributed over the number of marked edges na = 1..6 as
1153:   1, 3, 9, 17, 15, 6 (Table 4 of the paper). This runs the generator on every configuration, which
1154:   also exercises all internal consistency checks in the emission of the subdivision data.
1155: */
1156: static PetscErrorCode DMPlexTransformSBRValidate_Private(DMPlexTransform tr)
1157: {
1158:   const PetscInt expected[6] = {1, 3, 9, 17, 15, 6};
1159:   const PetscInt fact[6]     = {120, 24, 6, 2, 1, 1};
1160:   const PetscInt keyLen      = 2 + 4 * SBR_TET_MAX_LEAVES;
1161:   PetscBT        btCode;
1162:   PetscInt      *codes, *keys, *nas, counts[6] = {0, 0, 0, 0, 0, 0};
1163:   PetscInt       Ncodes = 0, maxCodes = 4096;

1165:   PetscFunctionBegin;
1166:   PetscCall(PetscBTCreate(117649, &btCode)); /* 7^6 possible codes */
1167:   PetscCall(PetscMalloc3(maxCodes, &codes, maxCodes * keyLen, &keys, maxCodes, &nas));
1168:   for (PetscInt idx = 0; idx < 720; ++idx) {
1169:     PetscInt avail[6] = {0, 1, 2, 3, 4, 5}, perm[6], prio[6], k = idx;

1171:     for (PetscInt i = 0; i < 6; ++i) {
1172:       const PetscInt pos = k / fact[i];

1174:       k %= fact[i];
1175:       perm[i] = avail[pos];
1176:       for (PetscInt j = pos; j < 5 - i; ++j) avail[j] = avail[j + 1];
1177:     }
1178:     for (PetscInt i = 0; i < 6; ++i) prio[perm[i]] = i;
1179:     for (PetscInt mask = 1; mask < 64; ++mask) {
1180:       PetscInt  ord[6], na = 0, code = 0;
1181:       PetscBool stable = (mask & (1 << perm[0])) ? PETSC_TRUE : PETSC_FALSE;

1183:       /* The set is conforming when the longest edge overall and of each affected face is marked */
1184:       for (PetscInt f = 0; f < 4 && stable; ++f) {
1185:         PetscInt fmax = tetFaceEdge[f][0], nm = 0;

1187:         for (PetscInt l = 0; l < 3; ++l) {
1188:           if (mask & (1 << tetFaceEdge[f][l])) ++nm;
1189:           if (prio[tetFaceEdge[f][l]] < prio[fmax]) fmax = tetFaceEdge[f][l];
1190:         }
1191:         if (nm && !(mask & (1 << fmax))) stable = PETSC_FALSE;
1192:       }
1193:       if (!stable) continue;
1194:       for (PetscInt i = 0; i < 6; ++i)
1195:         if (mask & (1 << perm[i])) ord[na++] = perm[i];
1196:       for (PetscInt i = na - 1; i >= 0; --i) code = code * 7 + (ord[i] + 1);
1197:       if (!PetscBTLookupSet(btCode, code)) {
1198:         PetscCheck(Ncodes < maxCodes, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Too many configurations");
1199:         codes[Ncodes] = code;
1200:         nas[Ncodes]   = na;
1201:         ++Ncodes;
1202:       }
1203:     }
1204:   }
1205:   for (PetscInt c = 0; c < Ncodes; ++c) {
1206:     SBRTetSubdiv   sub;
1207:     DMPolytopeType targetTmp[3];
1208:     PetscInt       sizeTmp[3], coneTmp[SBR_TET_MAX_CONE], orntTmp[SBR_TET_MAX_ORNT];
1209:     PetscInt       ord[6], na, NtTmp, Ncone, Nornt;
1210:     PetscInt      *key = &keys[c * keyLen];

1212:     SBRTetDecodeOrder_Private(codes[c], ord, &na);
1213:     PetscCall(SBRTetSubdivide_Private(ord, na, &sub));
1214:     PetscCall(SBRTetEmit_Private(ord, na, &sub, &NtTmp, targetTmp, sizeTmp, coneTmp, &Ncone, orntTmp, &Nornt));
1215:     /* The class key is the smallest relabeling, over all 12 rotations, of the leaf set together
1216:        with the first bisected edge: the paper counts length configurations, which distinguish two
1217:        marked sets producing the same subdivision when their longest edges do not correspond */
1218:     for (PetscInt so = 0; so < 12; ++so) {
1219:       const PetscInt *varr = DMPolytopeTypeGetVertexArrangement(DM_POLYTOPE_TETRAHEDRON, so);
1220:       PetscInt        medge[6], cand[2 + 4 * SBR_TET_MAX_LEAVES];

1222:       SBRTetEdgeImage_Private(varr, medge);
1223:       for (PetscInt i = 0; i < keyLen; ++i) cand[i] = -1;
1224:       cand[0] = sub.nleaf;
1225:       cand[1] = medge[ord[0]];
1226:       for (PetscInt l = 0; l < sub.nleaf; ++l) {
1227:         PetscInt *t = &cand[2 + 4 * l];

1229:         for (PetscInt i = 0; i < 4; ++i) t[i] = sub.leaf[l][i] < 4 ? varr[sub.leaf[l][i]] : 4 + medge[sub.leaf[l][i] - 4];
1230:         PetscCall(PetscSortInt(4, t));
1231:       }
1232:       /* Insertion sort of the leaf records, then keep the smallest candidate */
1233:       for (PetscInt l = 1; l < sub.nleaf; ++l) {
1234:         PetscInt t[4], j;

1236:         PetscCall(PetscArraycpy(t, &cand[2 + 4 * l], 4));
1237:         for (j = l - 1; j >= 0 && SBRTupleCompare_Private(4, &cand[2 + 4 * j], t) > 0; --j) PetscCall(PetscArraycpy(&cand[2 + 4 * (j + 1)], &cand[2 + 4 * j], 4));
1238:         PetscCall(PetscArraycpy(&cand[2 + 4 * (j + 1)], t, 4));
1239:       }
1240:       if (so == 0 || SBRTupleCompare_Private(keyLen, cand, key) < 0) PetscCall(PetscArraycpy(key, cand, keyLen));
1241:     }
1242:   }
1243:   for (PetscInt c = 0; c < Ncodes; ++c) {
1244:     PetscInt d;

1246:     for (d = 0; d < c; ++d) {
1247:       PetscBool same;

1249:       if (nas[d] != nas[c]) continue;
1250:       PetscCall(PetscMemcmp(&keys[d * keyLen], &keys[c * keyLen], keyLen * sizeof(PetscInt), &same));
1251:       if (same) break;
1252:     }
1253:     if (d == c) ++counts[nas[c] - 1];
1254:   }
1255:   for (PetscInt na = 1; na <= 6; ++na)
1256:     PetscCheck(counts[na - 1] == expected[na - 1], PetscObjectComm((PetscObject)tr), PETSC_ERR_PLIB, "Found %" PetscInt_FMT " subdivision classes with %" PetscInt_FMT " marked edges, expected %" PetscInt_FMT, counts[na - 1], na, expected[na - 1]);
1257:   PetscCall(PetscPrintf(PetscObjectComm((PetscObject)tr), "SBR: validated %" PetscInt_FMT " conforming configurations covering 51 subdivision classes (1 3 9 17 15 6 for 1-6 bisected edges)\n", Ncodes));
1258:   PetscCall(PetscFree3(codes, keys, nas));
1259:   PetscCall(PetscBTDestroy(&btCode));
1260:   PetscFunctionReturn(PETSC_SUCCESS);
1261: }

1263: /* The refine type of point p, from the array filled in DMPlexTransformSetUp_SBR() */
1264: static inline PetscErrorCode SBRGetRefineType_Private(DMPlexTransform tr, PetscInt p, PetscInt *rt)
1265: {
1266:   DMPlexRefine_SBR *sbr = (DMPlexRefine_SBR *)tr->data;

1268:   PetscFunctionBeginHot;
1269:   if (p >= sbr->rtStart && p < sbr->rtEnd) *rt = sbr->rt[p - sbr->rtStart];
1270:   else PetscCall(DMLabelGetValue(tr->trType, p, rt));
1271:   PetscFunctionReturn(PETSC_SUCCESS);
1272: }

1274: static PetscErrorCode DMPlexTransformGetSubcellOrientation_SBR(DMPlexTransform tr, DMPolytopeType sct, PetscInt sp, PetscInt so, DMPolytopeType tct, PetscInt r, PetscInt o, PetscInt *rnew, PetscInt *onew)
1275: {
1276:   PetscInt rt;

1278:   PetscFunctionBeginHot;
1279:   PetscCall(SBRGetRefineType_Private(tr, sp, &rt));
1280:   *rnew = r;
1281:   *onew = o;
1282:   switch (rt) {
1283:   case RT_TRIANGLE_SPLIT_01:
1284:   case RT_TRIANGLE_SPLIT_10:
1285:   case RT_TRIANGLE_SPLIT_12:
1286:   case RT_TRIANGLE_SPLIT_21:
1287:   case RT_TRIANGLE_SPLIT_20:
1288:   case RT_TRIANGLE_SPLIT_02:
1289:   case RT_TRIANGLE_SPLIT_0:
1290:   case RT_TRIANGLE_SPLIT_1:
1291:   case RT_TRIANGLE_SPLIT_2:
1292:   case RT_TRIANGLE_SPLIT_FAN_0:
1293:   case RT_TRIANGLE_SPLIT_FAN_1:
1294:   case RT_TRIANGLE_SPLIT_FAN_2:
1295:     if (so) PetscCall(SBRTriangleOrient_Private(rt, so, tct, r, o, rnew, onew));
1296:     break;
1297:   case RT_EDGE_SPLIT:
1298:   case RT_TRIANGLE_SPLIT:
1299:     PetscCall(DMPlexTransformGetSubcellOrientation_Regular(tr, sct, sp, so, tct, r, o, rnew, onew));
1300:     break;
1301:   default:
1302:     if (rt >= RT_TET_SPLIT_BASE) {
1303:       if (so) PetscCall(SBRTetOrient_Private(rt - RT_TET_SPLIT_BASE, so, tct, r, o, rnew, onew));
1304:     } else PetscCall(DMPlexTransformGetSubcellOrientationIdentity(tr, sct, sp, so, tct, r, o, rnew, onew));
1305:   }
1306:   PetscFunctionReturn(PETSC_SUCCESS);
1307: }

1309: /* Add 1 edge inside this triangle, making 2 new triangles.
1310:  2
1311:  |\
1312:  | \
1313:  |  \
1314:  |   \
1315:  |    1
1316:  |     \
1317:  |  B   \
1318:  2       1
1319:  |      / \
1320:  | ____/   0
1321:  |/    A    \
1322:  0-----0-----1
1323: */
1324: static PetscErrorCode SBRGetTriangleSplitSingle(PetscInt o, PetscInt *Nt, DMPolytopeType *target[], PetscInt *size[], PetscInt *cone[], PetscInt *ornt[])
1325: {
1326:   const PetscInt       *arr     = DMPolytopeTypeGetArrangement(DM_POLYTOPE_TRIANGLE, o);
1327:   static DMPolytopeType triT1[] = {DM_POLYTOPE_SEGMENT, DM_POLYTOPE_TRIANGLE};
1328:   static PetscInt       triS1[] = {1, 2};
1329:   static PetscInt       triC1[] = {DM_POLYTOPE_POINT,   2, 0, 0, 0, DM_POLYTOPE_POINT, 1, 1, 0, DM_POLYTOPE_SEGMENT, 1, 0, 0, DM_POLYTOPE_SEGMENT, 1, 1, 0, DM_POLYTOPE_SEGMENT, 0, 0, DM_POLYTOPE_SEGMENT, 1, 1, 1, DM_POLYTOPE_SEGMENT, 1, 2, 0,
1330:                                    DM_POLYTOPE_SEGMENT, 0, 0};
1331:   static PetscInt       triO1[] = {0, 0, 0, 0, -1, 0, 0, 0};

1333:   PetscFunctionBeginHot;
1334:   /* To get the other divisions, we reorient the triangle */
1335:   triC1[2]  = arr[0 * 2];
1336:   triC1[7]  = arr[1 * 2];
1337:   triC1[11] = arr[0 * 2];
1338:   triC1[15] = arr[1 * 2];
1339:   triC1[22] = arr[1 * 2];
1340:   triC1[26] = arr[2 * 2];
1341:   *Nt       = 2;
1342:   *target   = triT1;
1343:   *size     = triS1;
1344:   *cone     = triC1;
1345:   *ornt     = triO1;
1346:   PetscFunctionReturn(PETSC_SUCCESS);
1347: }

1349: /* Add 2 edges inside this triangle, making 3 new triangles.
1350:  RT_TRIANGLE_SPLIT_12
1351:  2
1352:  |\
1353:  | \
1354:  |  \
1355:  0   \
1356:  |    1
1357:  |     \
1358:  |  B   \
1359:  2-------1
1360:  |   C  / \
1361:  1 ____/   0
1362:  |/    A    \
1363:  0-----0-----1
1364:  RT_TRIANGLE_SPLIT_10
1365:  2
1366:  |\
1367:  | \
1368:  |  \
1369:  0   \
1370:  |    1
1371:  |     \
1372:  |  A   \
1373:  2       1
1374:  |      /|\
1375:  1 ____/ / 0
1376:  |/ C   / B \
1377:  0-----0-----1
1378:  RT_TRIANGLE_SPLIT_20
1379:  2
1380:  |\
1381:  | \
1382:  |  \
1383:  0   \
1384:  |    \
1385:  |     \
1386:  |      \
1387:  2   A   1
1388:  |\       \
1389:  1 ---\    \
1390:  |B \_C----\\
1391:  0-----0-----1
1392:  RT_TRIANGLE_SPLIT_21
1393:  2
1394:  |\
1395:  | \
1396:  |  \
1397:  0   \
1398:  |    \
1399:  |  B  \
1400:  |      \
1401:  2-------1
1402:  |\     C \
1403:  1 ---\    \
1404:  |  A  ----\\
1405:  0-----0-----1
1406:  RT_TRIANGLE_SPLIT_01
1407:  2
1408:  |\
1409:  |\\
1410:  || \
1411:  | \ \
1412:  |  | \
1413:  |  |  \
1414:  |  |   \
1415:  2   \ C 1
1416:  |  A | / \
1417:  |    | |B \
1418:  |     \/   \
1419:  0-----0-----1
1420:  RT_TRIANGLE_SPLIT_02
1421:  2
1422:  |\
1423:  |\\
1424:  || \
1425:  | \ \
1426:  |  | \
1427:  |  |  \
1428:  |  |   \
1429:  2 C \   1
1430:  |\   |   \
1431:  | \__|  A \
1432:  | B  \\    \
1433:  0-----0-----1
1434: */
1435: static PetscErrorCode SBRGetTriangleSplitDouble(PetscInt o, PetscInt *Nt, DMPolytopeType *target[], PetscInt *size[], PetscInt *cone[], PetscInt *ornt[])
1436: {
1437:   PetscInt              e0, e1;
1438:   const PetscInt       *arr     = DMPolytopeTypeGetArrangement(DM_POLYTOPE_TRIANGLE, o);
1439:   static DMPolytopeType triT2[] = {DM_POLYTOPE_SEGMENT, DM_POLYTOPE_TRIANGLE};
1440:   static PetscInt       triS2[] = {2, 3};
1441:   static PetscInt triC2[] = {DM_POLYTOPE_POINT, 2, 0, 0, 0, DM_POLYTOPE_POINT, 1, 1, 0, DM_POLYTOPE_POINT, 1, 1, 0, DM_POLYTOPE_POINT, 1, 2, 0, DM_POLYTOPE_SEGMENT, 1, 0, 0, DM_POLYTOPE_SEGMENT, 1, 1, 0, DM_POLYTOPE_SEGMENT, 0, 0, DM_POLYTOPE_SEGMENT, 1, 1, 1, DM_POLYTOPE_SEGMENT, 1, 2, 0, DM_POLYTOPE_SEGMENT, 0, 1, DM_POLYTOPE_SEGMENT, 1, 2, 1, DM_POLYTOPE_SEGMENT, 0, 0, DM_POLYTOPE_SEGMENT, 0, 1};
1442:   static PetscInt triO2[] = {0, 0, 0, 0, 0, 0, -1, 0, 0, -1, 0, 0, 0};

1444:   PetscFunctionBeginHot;
1445:   /* To get the other divisions, we reorient the triangle */
1446:   triC2[2]  = arr[0 * 2];
1447:   triC2[3]  = arr[0 * 2 + 1] ? 1 : 0;
1448:   triC2[7]  = arr[1 * 2];
1449:   triC2[11] = arr[1 * 2];
1450:   triC2[15] = arr[2 * 2];
1451:   /* Swap the first two edges if the triangle is reversed */
1452:   e0            = o < 0 ? 23 : 19;
1453:   e1            = o < 0 ? 19 : 23;
1454:   triC2[e0]     = arr[0 * 2];
1455:   triC2[e0 + 1] = 0;
1456:   triC2[e1]     = arr[1 * 2];
1457:   triC2[e1 + 1] = o < 0 ? 1 : 0;
1458:   triO2[6]      = DMPolytopeTypeComposeOrientation(DM_POLYTOPE_SEGMENT, -1, arr[2 * 2 + 1]);
1459:   /* Swap the first two edges if the triangle is reversed */
1460:   e0            = o < 0 ? 34 : 30;
1461:   e1            = o < 0 ? 30 : 34;
1462:   triC2[e0]     = arr[1 * 2];
1463:   triC2[e0 + 1] = o < 0 ? 0 : 1;
1464:   triC2[e1]     = arr[2 * 2];
1465:   triC2[e1 + 1] = o < 0 ? 1 : 0;
1466:   triO2[9]      = DMPolytopeTypeComposeOrientation(DM_POLYTOPE_SEGMENT, -1, arr[2 * 2 + 1]);
1467:   /* Swap the last two edges if the triangle is reversed */
1468:   triC2[41] = arr[2 * 2];
1469:   triC2[42] = o < 0 ? 0 : 1;
1470:   triC2[45] = o < 0 ? 1 : 0;
1471:   triC2[48] = o < 0 ? 0 : 1;
1472:   triO2[11] = DMPolytopeTypeComposeOrientation(DM_POLYTOPE_SEGMENT, 0, arr[1 * 2 + 1]);
1473:   triO2[12] = DMPolytopeTypeComposeOrientation(DM_POLYTOPE_SEGMENT, 0, arr[2 * 2 + 1]);
1474:   *Nt       = 2;
1475:   *target   = triT2;
1476:   *size     = triS2;
1477:   *cone     = triC2;
1478:   *ornt     = triO2;
1479:   PetscFunctionReturn(PETSC_SUCCESS);
1480: }

1482: /* Add 3 edges inside this triangle, making 4 new triangles fanned around the midpoint of the
1483:    first-bisected edge (the 4T partition of Rivara), e.g. for first = 1:
1484:  2
1485:  |\
1486:  | \
1487:  2   1
1488:  | \  \
1489:  |  \  \
1490:  |   \  \
1491:  2 D  \ B 1
1492:  |\    \  |\
1493:  | \  C \ | 0
1494:  |  2--__\|A \
1495:  0-----0-----1
1496:    This subdivision is used for a fully marked triangle below a 3D cell, where it matches the
1497:    subdivision induced on the triangle by bisecting the cells above it (Lemma 1.2 of Plaza & Carey
1498:    (2000)); a fully marked maximal (2D) triangle is subdivided regularly instead. */
1499: static PetscErrorCode SBRGetTriangleSplitFan_Private(PetscInt first, PetscInt *Nt, DMPolytopeType *target[], PetscInt *size[], PetscInt *cone[], PetscInt *ornt[])
1500: {
1501:   static DMPolytopeType fanT[] = {DM_POLYTOPE_SEGMENT, DM_POLYTOPE_TRIANGLE};
1502:   static PetscInt       fanS[] = {3, 4};
1503:   static PetscInt       fanC[96];
1504:   static PetscInt       fanO[24];
1505:   SBRTriSubdiv          sub;
1506:   PetscInt              coff = 0, ooff = 0;

1508:   PetscFunctionBeginHot;
1509:   PetscCall(SBRTriangleSubdiv_Private(3, first, -1, &sub));
1510:   for (PetscInt s = 0; s < sub.nseg; ++s) {
1511:     for (PetscInt i = 0; i < 2; ++i) {
1512:       const PetscInt sym = sub.seg[s][i];

1514:       if (sym < 3) {
1515:         const PetscInt acp[2] = {sym, 0}; /* vertex v is the first vertex of edge v */

1517:         PetscCall(SBRAppendCone_Private(fanC, &coff, 96, fanO, &ooff, 24, DM_POLYTOPE_POINT, 2, acp, 0, 0));
1518:       } else {
1519:         const PetscInt acp[1] = {sym - 3};

1521:         PetscCall(SBRAppendCone_Private(fanC, &coff, 96, fanO, &ooff, 24, DM_POLYTOPE_POINT, 1, acp, 0, 0));
1522:       }
1523:     }
1524:   }
1525:   for (PetscInt t = 0; t < sub.ntri; ++t) {
1526:     for (PetscInt i = 0; i < 3; ++i) {
1527:       const PetscInt P = sub.tri[t][i], Q = sub.tri[t][(i + 1) % 3];
1528:       const PetscInt v = P < 3 ? P : Q, e = (P < 3 ? Q : P) - 3;
1529:       PetscInt       r;

1531:       if ((P < 3 || Q < 3) && (triEdgeVert[e][0] == v || triEdgeVert[e][1] == v)) {
1532:         /* Half of a split edge: replica 0 runs from the edge tail to the midpoint, replica 1 from the midpoint to the head */
1533:         const PetscInt acp[1] = {e};

1535:         r = triEdgeVert[e][0] == v ? 0 : 1;
1536:         PetscCall(SBRAppendCone_Private(fanC, &coff, 96, fanO, &ooff, 24, DM_POLYTOPE_SEGMENT, 1, acp, r, (r == 0) == (P == v) ? 0 : -1));
1537:       } else {
1538:         for (r = 0; r < sub.nseg; ++r)
1539:           if ((sub.seg[r][0] == P && sub.seg[r][1] == Q) || (sub.seg[r][0] == Q && sub.seg[r][1] == P)) break;
1540:         PetscCheck(r < sub.nseg, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Interior segment (%" PetscInt_FMT ", %" PetscInt_FMT ") not found", P, Q);
1541:         PetscCall(SBRAppendCone_Private(fanC, &coff, 96, fanO, &ooff, 24, DM_POLYTOPE_SEGMENT, 0, NULL, r, sub.seg[r][0] == P ? 0 : -1));
1542:       }
1543:     }
1544:   }
1545:   *Nt     = 2;
1546:   *target = fanT;
1547:   *size   = fanS;
1548:   *cone   = fanC;
1549:   *ornt   = fanO;
1550:   PetscFunctionReturn(PETSC_SUCCESS);
1551: }

1553: static PetscErrorCode DMPlexTransformCellTransform_SBR(DMPlexTransform tr, DMPolytopeType source, PetscInt p, PetscInt *rt, PetscInt *Nt, DMPolytopeType *target[], PetscInt *size[], PetscInt *cone[], PetscInt *ornt[])
1554: {
1555:   PetscInt val;

1557:   PetscFunctionBeginHot;
1558:   PetscCheck(p >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Point argument is invalid");
1559:   PetscCall(SBRGetRefineType_Private(tr, p, &val));
1560:   if (rt) *rt = val;
1561:   switch (source) {
1562:   case DM_POLYTOPE_POINT:
1563:   case DM_POLYTOPE_POINT_PRISM_TENSOR:
1564:   case DM_POLYTOPE_QUADRILATERAL:
1565:   case DM_POLYTOPE_SEG_PRISM_TENSOR:
1566:   case DM_POLYTOPE_HEXAHEDRON:
1567:   case DM_POLYTOPE_TRI_PRISM:
1568:   case DM_POLYTOPE_TRI_PRISM_TENSOR:
1569:   case DM_POLYTOPE_QUAD_PRISM_TENSOR:
1570:   case DM_POLYTOPE_PYRAMID:
1571:     PetscCall(DMPlexTransformCellTransformIdentity(tr, source, p, NULL, Nt, target, size, cone, ornt));
1572:     break;
1573:   case DM_POLYTOPE_SEGMENT:
1574:     if (val == RT_EDGE) PetscCall(DMPlexTransformCellTransformIdentity(tr, source, p, NULL, Nt, target, size, cone, ornt));
1575:     else PetscCall(DMPlexTransformCellRefine_Regular(tr, source, p, NULL, Nt, target, size, cone, ornt));
1576:     break;
1577:   case DM_POLYTOPE_TRIANGLE:
1578:     switch (val) {
1579:     case RT_TRIANGLE_SPLIT_0:
1580:       PetscCall(SBRGetTriangleSplitSingle(2, Nt, target, size, cone, ornt));
1581:       break;
1582:     case RT_TRIANGLE_SPLIT_1:
1583:       PetscCall(SBRGetTriangleSplitSingle(0, Nt, target, size, cone, ornt));
1584:       break;
1585:     case RT_TRIANGLE_SPLIT_2:
1586:       PetscCall(SBRGetTriangleSplitSingle(1, Nt, target, size, cone, ornt));
1587:       break;
1588:     case RT_TRIANGLE_SPLIT_21:
1589:       PetscCall(SBRGetTriangleSplitDouble(-3, Nt, target, size, cone, ornt));
1590:       break;
1591:     case RT_TRIANGLE_SPLIT_10:
1592:       PetscCall(SBRGetTriangleSplitDouble(-2, Nt, target, size, cone, ornt));
1593:       break;
1594:     case RT_TRIANGLE_SPLIT_02:
1595:       PetscCall(SBRGetTriangleSplitDouble(-1, Nt, target, size, cone, ornt));
1596:       break;
1597:     case RT_TRIANGLE_SPLIT_12:
1598:       PetscCall(SBRGetTriangleSplitDouble(0, Nt, target, size, cone, ornt));
1599:       break;
1600:     case RT_TRIANGLE_SPLIT_20:
1601:       PetscCall(SBRGetTriangleSplitDouble(1, Nt, target, size, cone, ornt));
1602:       break;
1603:     case RT_TRIANGLE_SPLIT_01:
1604:       PetscCall(SBRGetTriangleSplitDouble(2, Nt, target, size, cone, ornt));
1605:       break;
1606:     case RT_TRIANGLE_SPLIT_FAN_0:
1607:     case RT_TRIANGLE_SPLIT_FAN_1:
1608:     case RT_TRIANGLE_SPLIT_FAN_2:
1609:       PetscCall(SBRGetTriangleSplitFan_Private(val - RT_TRIANGLE_SPLIT_FAN_0, Nt, target, size, cone, ornt));
1610:       break;
1611:     case RT_TRIANGLE_SPLIT:
1612:       PetscCall(DMPlexTransformCellRefine_Regular(tr, source, p, NULL, Nt, target, size, cone, ornt));
1613:       break;
1614:     default:
1615:       PetscCall(DMPlexTransformCellTransformIdentity(tr, source, p, NULL, Nt, target, size, cone, ornt));
1616:     }
1617:     break;
1618:   case DM_POLYTOPE_TETRAHEDRON:
1619:     if (val == RT_TET) PetscCall(DMPlexTransformCellTransformIdentity(tr, source, p, NULL, Nt, target, size, cone, ornt));
1620:     else {
1621:       PetscCheck(val >= RT_TET_SPLIT_BASE, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid refinement type %" PetscInt_FMT " for tetrahedron %" PetscInt_FMT, val, p);
1622:       PetscCall(SBRGetTetSplit_Private(tr, val - RT_TET_SPLIT_BASE, Nt, target, size, cone, ornt));
1623:     }
1624:     break;
1625:   default:
1626:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No refinement strategy for %s", DMPolytopeTypes[source]);
1627:   }
1628:   PetscFunctionReturn(PETSC_SUCCESS);
1629: }

1631: static PetscErrorCode DMPlexTransformSetFromOptions_SBR(DMPlexTransform tr, PetscOptionItems PetscOptionsObject)
1632: {
1633:   PetscInt  cells[256], n = 256, i;
1634:   PetscBool flg, validate = PETSC_FALSE;

1636:   PetscFunctionBegin;
1637:   PetscOptionsHeadBegin(PetscOptionsObject, "DMPlex Options");
1638:   PetscCall(PetscOptionsIntArray("-dm_plex_transform_sbr_ref_cell", "Mark cells for refinement", "", cells, &n, &flg));
1639:   if (flg) {
1640:     DMLabel active;

1642:     PetscCall(DMLabelCreate(PETSC_COMM_SELF, "Adaptation Label", &active));
1643:     for (i = 0; i < n; ++i) PetscCall(DMLabelSetValue(active, cells[i], DM_ADAPT_REFINE));
1644:     PetscCall(DMPlexTransformSetActive(tr, active));
1645:     PetscCall(DMLabelDestroy(&active));
1646:   }
1647:   PetscCall(PetscOptionsBool("-dm_plex_transform_sbr_validate", "Validate the tetrahedron subdivision generator against Plaza & Carey (2000), Table 4", "", validate, &validate, NULL));
1648:   PetscOptionsHeadEnd();
1649:   if (validate) PetscCall(DMPlexTransformSBRValidate_Private(tr));
1650:   PetscFunctionReturn(PETSC_SUCCESS);
1651: }

1653: static PetscErrorCode DMPlexTransformView_SBR(DMPlexTransform tr, PetscViewer viewer)
1654: {
1655:   PetscBool isascii;

1657:   PetscFunctionBegin;
1660:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1661:   if (isascii) {
1662:     PetscViewerFormat format;
1663:     const char       *name;

1665:     PetscCall(PetscObjectGetName((PetscObject)tr, &name));
1666:     PetscCall(PetscViewerASCIIPrintf(viewer, "SBR refinement %s\n", name ? name : ""));
1667:     PetscCall(PetscViewerGetFormat(viewer, &format));
1668:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) PetscCall(DMLabelView(tr->trType, viewer));
1669:   } else {
1670:     SETERRQ(PetscObjectComm((PetscObject)tr), PETSC_ERR_SUP, "Viewer type %s not yet supported for DMPlexTransform writing", ((PetscObject)viewer)->type_name);
1671:   }
1672:   PetscFunctionReturn(PETSC_SUCCESS);
1673: }

1675: static PetscErrorCode DMPlexTransformDestroy_SBR(DMPlexTransform tr)
1676: {
1677:   DMPlexRefine_SBR *sbr = (DMPlexRefine_SBR *)tr->data;

1679:   PetscFunctionBegin;
1680:   for (PetscInt i = 0; i < sbr->Ncache; ++i) {
1681:     PetscCall(PetscFree(sbr->cacheTarget[i]));
1682:     PetscCall(PetscFree(sbr->cacheSize[i]));
1683:     PetscCall(PetscFree(sbr->cacheCone[i]));
1684:     PetscCall(PetscFree(sbr->cacheOrnt[i]));
1685:   }
1686:   PetscCall(PetscFree6(sbr->cacheCode, sbr->cacheNt, sbr->cacheTarget, sbr->cacheSize, sbr->cacheCone, sbr->cacheOrnt));
1687:   PetscCall(PetscHMapIDestroy(&sbr->cacheMap));
1688:   PetscCall(PetscFree(sbr->edgeLen));
1689:   PetscCall(PetscFree(sbr->rt));
1690:   PetscCall(PetscSectionDestroy(&sbr->secEdgeLen));
1691:   PetscCall(DMLabelDestroy(&sbr->splitPoints));
1692:   PetscCall(PetscFree(tr->data));
1693:   PetscFunctionReturn(PETSC_SUCCESS);
1694: }

1696: static PetscErrorCode DMPlexTransformInitialize_SBR(DMPlexTransform tr)
1697: {
1698:   PetscFunctionBegin;
1699:   tr->ops->view                  = DMPlexTransformView_SBR;
1700:   tr->ops->setfromoptions        = DMPlexTransformSetFromOptions_SBR;
1701:   tr->ops->setup                 = DMPlexTransformSetUp_SBR;
1702:   tr->ops->destroy               = DMPlexTransformDestroy_SBR;
1703:   tr->ops->setdimensions         = DMPlexTransformSetDimensions_Internal;
1704:   tr->ops->celltransform         = DMPlexTransformCellTransform_SBR;
1705:   tr->ops->getsubcellorientation = DMPlexTransformGetSubcellOrientation_SBR;
1706:   tr->ops->mapcoordinates        = DMPlexTransformMapCoordinatesBarycenter_Internal;
1707:   PetscFunctionReturn(PETSC_SUCCESS);
1708: }

1710: PETSC_EXTERN PetscErrorCode DMPlexTransformCreate_SBR(DMPlexTransform tr)
1711: {
1712:   DMPlexRefine_SBR *f;

1714:   PetscFunctionBegin;
1716:   PetscCall(PetscNew(&f));
1717:   PetscCall(PetscHMapICreate(&f->cacheMap));
1718:   tr->data = f;

1720:   PetscCall(DMPlexTransformInitialize_SBR(tr));
1721:   PetscCall(PetscCitationsRegister(SBRCitation, &SBRcite));
1722:   PetscFunctionReturn(PETSC_SUCCESS);
1723: }