Actual source code: pforest.h
1: #pragma once
3: #include <petscds.h>
4: #include <petscfe.h>
5: #include <petsc/private/dmimpl.h>
6: #include <petsc/private/dmforestimpl.h>
7: #include <petsc/private/dmpleximpl.h>
8: #include <petsc/private/dmlabelimpl.h>
9: #include <petsc/private/viewerimpl.h>
10: #include <../src/sys/classes/viewer/impls/vtk/vtkvimpl.h>
11: #include "petsc_p4est_package.h"
13: #if PetscDefined(HAVE_P4EST)
15: #if !defined(P4_TO_P8)
16: #include <p4est.h>
17: #include <p4est_extended.h>
18: #include <p4est_geometry.h>
19: #include <p4est_ghost.h>
20: #include <p4est_lnodes.h>
21: #include <p4est_vtk.h>
22: #include <p4est_plex.h>
23: #include <p4est_bits.h>
24: #include <p4est_algorithms.h>
25: #else
26: #include <p8est.h>
27: #include <p8est_extended.h>
28: #include <p8est_geometry.h>
29: #include <p8est_ghost.h>
30: #include <p8est_lnodes.h>
31: #include <p8est_vtk.h>
32: #include <p8est_plex.h>
33: #include <p8est_bits.h>
34: #include <p8est_algorithms.h>
35: #endif
37: typedef enum {
38: PATTERN_HASH,
39: PATTERN_FRACTAL,
40: PATTERN_CORNER,
41: PATTERN_CENTER,
42: PATTERN_COUNT
43: } DMRefinePattern;
44: static const char *DMRefinePatternName[PATTERN_COUNT] = {"hash", "fractal", "corner", "center"};
46: typedef struct _DMRefinePatternCtx {
47: PetscInt corner;
48: PetscBool fractal[P4EST_CHILDREN];
49: PetscReal hashLikelihood;
50: PetscInt maxLevel;
51: p4est_refine_t refine_fn;
52: } DMRefinePatternCtx;
54: static int DMRefinePattern_Corner(p4est_t *p4est, p4est_topidx_t which_tree, p4est_quadrant_t *quadrant)
55: {
56: p4est_quadrant_t root, rootcorner;
57: DMRefinePatternCtx *ctx;
59: ctx = (DMRefinePatternCtx *)p4est->user_pointer;
60: if (quadrant->level >= ctx->maxLevel) return 0;
62: root.x = root.y = 0;
63: #if defined(P4_TO_P8)
64: root.z = 0;
65: #endif
66: root.level = 0;
67: p4est_quadrant_corner_descendant(&root, &rootcorner, ctx->corner, quadrant->level);
68: if (p4est_quadrant_is_equal(quadrant, &rootcorner)) return 1;
69: return 0;
70: }
72: static int DMRefinePattern_Center(p4est_t *p4est, p4est_topidx_t which_tree, p4est_quadrant_t *quadrant)
73: {
74: int cid;
75: p4est_quadrant_t ancestor, ancestorcorner;
76: DMRefinePatternCtx *ctx;
78: ctx = (DMRefinePatternCtx *)p4est->user_pointer;
79: if (quadrant->level >= ctx->maxLevel) return 0;
80: if (quadrant->level <= 1) return 1;
82: p4est_quadrant_ancestor(quadrant, 1, &ancestor);
83: cid = p4est_quadrant_child_id(&ancestor);
84: p4est_quadrant_corner_descendant(&ancestor, &ancestorcorner, P4EST_CHILDREN - 1 - cid, quadrant->level);
85: if (p4est_quadrant_is_equal(quadrant, &ancestorcorner)) return 1;
86: return 0;
87: }
89: static int DMRefinePattern_Fractal(p4est_t *p4est, p4est_topidx_t which_tree, p4est_quadrant_t *quadrant)
90: {
91: int cid;
92: DMRefinePatternCtx *ctx;
94: ctx = (DMRefinePatternCtx *)p4est->user_pointer;
95: if (quadrant->level >= ctx->maxLevel) return 0;
96: if (!quadrant->level) return 1;
97: cid = p4est_quadrant_child_id(quadrant);
98: if (ctx->fractal[cid ^ ((int)(quadrant->level % P4EST_CHILDREN))]) return 1;
99: return 0;
100: }
102: /* simplified from MurmurHash3 by Austin Appleby */
103: #define DMPROT32(x, y) (((x) << (y)) | ((x) >> (32 - (y))))
104: static uint32_t DMPforestHash(const uint32_t *blocks, uint32_t nblocks)
105: {
106: uint32_t c1 = 0xcc9e2d51;
107: uint32_t c2 = 0x1b873593;
108: uint32_t r1 = 15;
109: uint32_t r2 = 13;
110: uint32_t m = 5;
111: uint32_t n = 0xe6546b64;
112: uint32_t hash = 0;
113: int len = nblocks * 4;
114: uint32_t i;
116: for (i = 0; i < nblocks; i++) {
117: uint32_t k;
119: k = blocks[i];
120: k *= c1;
121: k = DMPROT32(k, r1);
122: k *= c2;
124: hash ^= k;
125: hash = DMPROT32(hash, r2) * m + n;
126: }
128: hash ^= len;
129: hash ^= (hash >> 16);
130: hash *= 0x85ebca6b;
131: hash ^= (hash >> 13);
132: hash *= 0xc2b2ae35;
133: hash ^= (hash >> 16);
135: return hash;
136: }
138: #if defined(UINT32_MAX)
139: #define DMP4EST_HASH_MAX UINT32_MAX
140: #else
141: #define DMP4EST_HASH_MAX ((uint32_t)0xffffffff)
142: #endif
144: static int DMRefinePattern_Hash(p4est_t *p4est, p4est_topidx_t which_tree, p4est_quadrant_t *quadrant)
145: {
146: uint32_t data[5];
147: uint32_t result;
148: DMRefinePatternCtx *ctx;
150: ctx = (DMRefinePatternCtx *)p4est->user_pointer;
151: if (quadrant->level >= ctx->maxLevel) return 0;
152: data[0] = ((uint32_t)quadrant->level) << 24;
153: data[1] = (uint32_t)which_tree;
154: data[2] = (uint32_t)quadrant->x;
155: data[3] = (uint32_t)quadrant->y;
156: #if defined(P4_TO_P8)
157: data[4] = (uint32_t)quadrant->z;
158: #endif
160: result = DMPforestHash(data, 2 + P4EST_DIM);
161: if (((double)result / (double)DMP4EST_HASH_MAX) < ctx->hashLikelihood) return 1;
162: return 0;
163: }
165: #define DMConvert_pforest_plex _infix_pforest(DMConvert, _plex)
166: static PetscErrorCode DMConvert_pforest_plex(DM, DMType, DM *);
168: #define DMFTopology_pforest _append_pforest(DMFTopology)
169: typedef struct {
170: PetscInt refct;
171: p4est_connectivity_t *conn;
172: p4est_geometry_t *geom;
173: PetscInt *tree_face_to_uniq; /* p4est does not explicitly enumerate facets, but we must to keep track of labels */
174: } DMFTopology_pforest;
176: #define DM_Forest_pforest _append_pforest(DM_Forest)
177: typedef struct {
178: DMFTopology_pforest *topo;
179: p4est_t *forest;
180: p4est_ghost_t *ghost;
181: p4est_lnodes_t *lnodes;
182: PetscBool partition_for_coarsening;
183: PetscBool coarsen_hierarchy;
184: PetscBool labelsFinalized;
185: PetscBool adaptivitySuccess;
186: PetscInt cLocalStart;
187: PetscInt cLocalEnd;
188: DM plex;
189: char *ghostName;
190: PetscSF pointAdaptToSelfSF;
191: PetscSF pointSelfToAdaptSF;
192: PetscInt *pointAdaptToSelfCids;
193: PetscInt *pointSelfToAdaptCids;
194: } DM_Forest_pforest;
196: #define DM_Forest_geometry_pforest _append_pforest(DM_Forest_geometry)
197: typedef struct {
198: DM base;
199: PetscErrorCode (*map)(DM, PetscInt, PetscInt, const PetscReal[], PetscReal[], void *);
200: void *mapCtx;
201: PetscInt coordDim;
202: p4est_geometry_t *inner;
203: } DM_Forest_geometry_pforest;
205: #define GeometryMapping_pforest _append_pforest(GeometryMapping)
206: static void GeometryMapping_pforest(p4est_geometry_t *geom, p4est_topidx_t which_tree, const double abc[3], double xyz[3])
207: {
208: DM_Forest_geometry_pforest *geom_pforest = (DM_Forest_geometry_pforest *)geom->user;
209: PetscReal PetscABC[3] = {0.};
210: PetscReal PetscXYZ[3] = {0.};
211: PetscInt i, d = PetscMin(3, geom_pforest->coordDim);
212: double ABC[3];
213: PetscErrorCode ierr;
215: (geom_pforest->inner->X)(geom_pforest->inner, which_tree, abc, ABC);
217: for (i = 0; i < d; i++) PetscABC[i] = ABC[i];
218: ierr = (geom_pforest->map)(geom_pforest->base, (PetscInt)which_tree, geom_pforest->coordDim, PetscABC, PetscXYZ, geom_pforest->mapCtx);
219: PETSC_P4EST_ASSERT(!ierr);
220: for (i = 0; i < d; i++) xyz[i] = PetscXYZ[i];
221: }
223: #define GeometryDestroy_pforest _append_pforest(GeometryDestroy)
224: static void GeometryDestroy_pforest(p4est_geometry_t *geom)
225: {
226: DM_Forest_geometry_pforest *geom_pforest = (DM_Forest_geometry_pforest *)geom->user;
227: PetscErrorCode ierr;
229: p4est_geometry_destroy(geom_pforest->inner);
230: ierr = PetscFree(geom->user);
231: PETSC_P4EST_ASSERT(!ierr);
232: ierr = PetscFree(geom);
233: PETSC_P4EST_ASSERT(!ierr);
234: }
236: #define DMFTopologyDestroy_pforest _append_pforest(DMFTopologyDestroy)
237: static PetscErrorCode DMFTopologyDestroy_pforest(DMFTopology_pforest **topo)
238: {
239: PetscFunctionBegin;
240: if (!*topo) PetscFunctionReturn(PETSC_SUCCESS);
241: if (--((*topo)->refct) > 0) {
242: *topo = NULL;
243: PetscFunctionReturn(PETSC_SUCCESS);
244: }
245: if ((*topo)->geom) PetscCallP4est(p4est_geometry_destroy, (*topo)->geom);
246: PetscCallP4est(p4est_connectivity_destroy, (*topo)->conn);
247: PetscCall(PetscFree((*topo)->tree_face_to_uniq));
248: PetscCall(PetscFree(*topo));
249: PetscFunctionReturn(PETSC_SUCCESS);
250: }
252: static PetscErrorCode PforestConnectivityEnumerateFacets(p4est_connectivity_t *, PetscInt **);
254: #define DMFTopologyCreateBrick_pforest _append_pforest(DMFTopologyCreateBrick)
255: static PetscErrorCode DMFTopologyCreateBrick_pforest(DM dm, PetscInt N[], PetscInt P[], PetscReal B[], DMFTopology_pforest **topo, PetscBool useMorton)
256: {
257: double *vertices;
258: PetscInt i, numVerts;
260: PetscFunctionBegin;
261: PetscCheck(useMorton, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Lexicographic ordering not implemented yet");
262: PetscCall(PetscNew(topo));
264: (*topo)->refct = 1;
265: #if !defined(P4_TO_P8)
266: PetscCallP4estReturn((*topo)->conn, p4est_connectivity_new_brick, (int)N[0], (int)N[1], (P[0] == DM_BOUNDARY_NONE) ? 0 : 1, (P[1] == DM_BOUNDARY_NONE) ? 0 : 1);
267: #else
268: PetscCallP4estReturn((*topo)->conn, p8est_connectivity_new_brick, (int)N[0], (int)N[1], (int)N[2], (P[0] == DM_BOUNDARY_NONE) ? 0 : 1, (P[1] == DM_BOUNDARY_NONE) ? 0 : 1, (P[2] == DM_BOUNDARY_NONE) ? 0 : 1);
269: #endif
270: numVerts = (*topo)->conn->num_vertices;
271: vertices = (*topo)->conn->vertices;
272: for (i = 0; i < 3 * numVerts; i++) {
273: PetscInt j = i % 3;
275: vertices[i] = B[2 * j] + (vertices[i] / N[j]) * (B[2 * j + 1] - B[2 * j]);
276: }
277: (*topo)->geom = NULL;
278: PetscCall(PforestConnectivityEnumerateFacets((*topo)->conn, &(*topo)->tree_face_to_uniq));
279: PetscFunctionReturn(PETSC_SUCCESS);
280: }
282: #define DMFTopologyCreate_pforest _append_pforest(DMFTopologyCreate)
283: static PetscErrorCode DMFTopologyCreate_pforest(DM dm, DMForestTopology topologyName, DMFTopology_pforest **topo)
284: {
285: const char *name = (const char *)topologyName;
286: const char *prefix;
287: PetscBool isBrick, isShell, isSphere, isMoebius;
289: PetscFunctionBegin;
291: PetscAssertPointer(name, 2);
292: PetscAssertPointer(topo, 3);
293: PetscCall(PetscStrcmp(name, "brick", &isBrick));
294: PetscCall(PetscStrcmp(name, "shell", &isShell));
295: PetscCall(PetscStrcmp(name, "sphere", &isSphere));
296: PetscCall(PetscStrcmp(name, "moebius", &isMoebius));
297: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)dm, &prefix));
298: if (isBrick) {
299: PetscBool flgN, flgP, flgM, flgB, useMorton = PETSC_TRUE, periodic = PETSC_FALSE;
300: PetscInt N[3] = {2, 2, 2}, P[3] = {0, 0, 0}, nretN = P4EST_DIM, nretP = P4EST_DIM, nretB = 2 * P4EST_DIM, i;
301: PetscReal B[6] = {0.0, 1.0, 0.0, 1.0, 0.0, 1.0}, Lstart[3] = {0., 0., 0.}, L[3] = {-1.0, -1.0, -1.0}, maxCell[3] = {-1.0, -1.0, -1.0};
303: if (dm->setfromoptionscalled) {
304: PetscCall(PetscOptionsGetIntArray(((PetscObject)dm)->options, prefix, "-dm_p4est_brick_size", N, &nretN, &flgN));
305: PetscCall(PetscOptionsGetIntArray(((PetscObject)dm)->options, prefix, "-dm_p4est_brick_periodicity", P, &nretP, &flgP));
306: PetscCall(PetscOptionsGetRealArray(((PetscObject)dm)->options, prefix, "-dm_p4est_brick_bounds", B, &nretB, &flgB));
307: PetscCall(PetscOptionsGetBool(((PetscObject)dm)->options, prefix, "-dm_p4est_brick_use_morton_curve", &useMorton, &flgM));
308: PetscCheck(!flgN || nretN == P4EST_DIM, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Need to give %d sizes in -dm_p4est_brick_size, gave %" PetscInt_FMT, P4EST_DIM, nretN);
309: PetscCheck(!flgP || nretP == P4EST_DIM, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Need to give %d periodicities in -dm_p4est_brick_periodicity, gave %" PetscInt_FMT, P4EST_DIM, nretP);
310: PetscCheck(!flgB || nretB == 2 * P4EST_DIM, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Need to give %d bounds in -dm_p4est_brick_bounds, gave %" PetscInt_FMT, P4EST_DIM, nretP);
311: }
312: for (i = 0; i < P4EST_DIM; i++) {
313: P[i] = (P[i] ? DM_BOUNDARY_PERIODIC : DM_BOUNDARY_NONE);
314: periodic = (PetscBool)(P[i] || periodic);
315: if (!flgB) B[2 * i + 1] = N[i];
316: if (P[i]) {
317: Lstart[i] = B[2 * i + 0];
318: L[i] = B[2 * i + 1] - B[2 * i + 0];
319: maxCell[i] = 1.1 * (L[i] / N[i]);
320: }
321: }
322: PetscCall(DMFTopologyCreateBrick_pforest(dm, N, P, B, topo, useMorton));
323: if (periodic) PetscCall(DMSetPeriodicity(dm, maxCell, Lstart, L));
324: } else {
325: PetscCall(PetscNew(topo));
327: (*topo)->refct = 1;
328: PetscCallP4estReturn((*topo)->conn, p4est_connectivity_new_byname, name);
329: (*topo)->geom = NULL;
330: if (isMoebius) PetscCall(DMSetCoordinateDim(dm, 3));
331: #if defined(P4_TO_P8)
332: if (isShell) {
333: PetscReal R2 = 1., R1 = .55;
335: if (dm->setfromoptionscalled) {
336: PetscCall(PetscOptionsGetReal(((PetscObject)dm)->options, prefix, "-dm_p4est_shell_outer_radius", &R2, NULL));
337: PetscCall(PetscOptionsGetReal(((PetscObject)dm)->options, prefix, "-dm_p4est_shell_inner_radius", &R1, NULL));
338: }
339: PetscCallP4estReturn((*topo)->geom, p8est_geometry_new_shell, (*topo)->conn, R2, R1);
340: } else if (isSphere) {
341: PetscReal R2 = 1., R1 = 0.191728, R0 = 0.039856;
343: if (dm->setfromoptionscalled) {
344: PetscCall(PetscOptionsGetReal(((PetscObject)dm)->options, prefix, "-dm_p4est_sphere_outer_radius", &R2, NULL));
345: PetscCall(PetscOptionsGetReal(((PetscObject)dm)->options, prefix, "-dm_p4est_sphere_inner_radius", &R1, NULL));
346: PetscCall(PetscOptionsGetReal(((PetscObject)dm)->options, prefix, "-dm_p4est_sphere_core_radius", &R0, NULL));
347: }
348: PetscCallP4estReturn((*topo)->geom, p8est_geometry_new_sphere, (*topo)->conn, R2, R1, R0);
349: }
350: #endif
351: PetscCall(PforestConnectivityEnumerateFacets((*topo)->conn, &(*topo)->tree_face_to_uniq));
352: }
353: PetscFunctionReturn(PETSC_SUCCESS);
354: }
356: #define DMConvert_plex_pforest _append_pforest(DMConvert_plex)
357: static PetscErrorCode DMConvert_plex_pforest(DM dm, DMType newtype, DM *pforest)
358: {
359: MPI_Comm comm;
360: PetscBool isPlex;
361: PetscInt dim;
362: void *ctx;
364: PetscFunctionBegin;
366: comm = PetscObjectComm((PetscObject)dm);
367: PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMPLEX, &isPlex));
368: PetscCheck(isPlex, comm, PETSC_ERR_ARG_WRONG, "Expected DM type %s, got %s", DMPLEX, ((PetscObject)dm)->type_name);
369: PetscCall(DMGetDimension(dm, &dim));
370: PetscCheck(dim == P4EST_DIM, comm, PETSC_ERR_ARG_WRONG, "Expected DM dimension %d, got %" PetscInt_FMT, P4EST_DIM, dim);
371: PetscCall(DMCreate(comm, pforest));
372: PetscCall(DMSetType(*pforest, DMPFOREST));
373: PetscCall(DMForestSetBaseDM(*pforest, dm));
374: PetscCall(DMGetApplicationContext(dm, &ctx));
375: PetscCall(DMSetApplicationContext(*pforest, ctx));
376: PetscCall(DMCopyDisc(dm, *pforest));
377: PetscFunctionReturn(PETSC_SUCCESS);
378: }
380: #define DMForestDestroy_pforest _append_pforest(DMForestDestroy)
381: static PetscErrorCode DMForestDestroy_pforest(DM dm)
382: {
383: DM_Forest *forest = (DM_Forest *)dm->data;
384: DM_Forest_pforest *pforest = (DM_Forest_pforest *)forest->data;
386: PetscFunctionBegin;
388: if (pforest->lnodes) PetscCallP4est(p4est_lnodes_destroy, pforest->lnodes);
389: pforest->lnodes = NULL;
390: if (pforest->ghost) PetscCallP4est(p4est_ghost_destroy, pforest->ghost);
391: pforest->ghost = NULL;
392: if (pforest->forest) PetscCallP4est(p4est_destroy, pforest->forest);
393: pforest->forest = NULL;
394: PetscCall(DMFTopologyDestroy_pforest(&pforest->topo));
395: PetscCall(PetscFree(pforest->ghostName));
396: PetscCall(DMDestroy(&pforest->plex));
397: PetscCall(PetscSFDestroy(&pforest->pointAdaptToSelfSF));
398: PetscCall(PetscSFDestroy(&pforest->pointSelfToAdaptSF));
399: PetscCall(PetscFree(pforest->pointAdaptToSelfCids));
400: PetscCall(PetscFree(pforest->pointSelfToAdaptCids));
401: PetscCall(PetscFree(forest->data));
402: PetscFunctionReturn(PETSC_SUCCESS);
403: }
405: #define DMForestTemplate_pforest _append_pforest(DMForestTemplate)
406: static PetscErrorCode DMForestTemplate_pforest(DM dm, DM tdm)
407: {
408: DM_Forest_pforest *pforest = (DM_Forest_pforest *)((DM_Forest *)dm->data)->data;
409: DM_Forest_pforest *tpforest = (DM_Forest_pforest *)((DM_Forest *)tdm->data)->data;
411: PetscFunctionBegin;
412: if (pforest->topo) pforest->topo->refct++;
413: PetscCall(DMFTopologyDestroy_pforest(&tpforest->topo));
414: tpforest->topo = pforest->topo;
415: PetscFunctionReturn(PETSC_SUCCESS);
416: }
418: #define DMPlexCreateConnectivity_pforest _append_pforest(DMPlexCreateConnectivity)
419: static PetscErrorCode DMPlexCreateConnectivity_pforest(DM, p4est_connectivity_t **, PetscInt **);
421: typedef struct _PforestAdaptCtx {
422: PetscInt maxLevel;
423: PetscInt minLevel;
424: PetscInt currLevel;
425: PetscBool anyChange;
426: } PforestAdaptCtx;
428: static int pforest_coarsen_currlevel(p4est_t *p4est, p4est_topidx_t which_tree, p4est_quadrant_t *quadrants[])
429: {
430: PforestAdaptCtx *ctx = (PforestAdaptCtx *)p4est->user_pointer;
431: PetscInt minLevel = ctx->minLevel;
432: PetscInt currLevel = ctx->currLevel;
434: if (quadrants[0]->level <= minLevel) return 0;
435: return (int)((PetscInt)quadrants[0]->level == currLevel);
436: }
438: static int pforest_coarsen_uniform(p4est_t *p4est, p4est_topidx_t which_tree, p4est_quadrant_t *quadrants[])
439: {
440: PforestAdaptCtx *ctx = (PforestAdaptCtx *)p4est->user_pointer;
441: PetscInt minLevel = ctx->minLevel;
443: return (int)((PetscInt)quadrants[0]->level > minLevel);
444: }
446: static int pforest_coarsen_flag_any(p4est_t *p4est, p4est_topidx_t which_tree, p4est_quadrant_t *quadrants[])
447: {
448: PetscInt i;
449: PetscBool any = PETSC_FALSE;
450: PforestAdaptCtx *ctx = (PforestAdaptCtx *)p4est->user_pointer;
451: PetscInt minLevel = ctx->minLevel;
453: if (quadrants[0]->level <= minLevel) return 0;
454: for (i = 0; i < P4EST_CHILDREN; i++) {
455: if (quadrants[i]->p.user_int == DM_ADAPT_KEEP) {
456: any = PETSC_FALSE;
457: break;
458: }
459: if (quadrants[i]->p.user_int == DM_ADAPT_COARSEN) {
460: any = PETSC_TRUE;
461: break;
462: }
463: }
464: return any ? 1 : 0;
465: }
467: static int pforest_coarsen_flag_all(p4est_t *p4est, p4est_topidx_t which_tree, p4est_quadrant_t *quadrants[])
468: {
469: PetscInt i;
470: PetscBool all = PETSC_TRUE;
471: PforestAdaptCtx *ctx = (PforestAdaptCtx *)p4est->user_pointer;
472: PetscInt minLevel = ctx->minLevel;
474: if (quadrants[0]->level <= minLevel) return 0;
475: for (i = 0; i < P4EST_CHILDREN; i++) {
476: if (quadrants[i]->p.user_int != DM_ADAPT_COARSEN) {
477: all = PETSC_FALSE;
478: break;
479: }
480: }
481: return all ? 1 : 0;
482: }
484: static void pforest_init_determine(p4est_t *p4est, p4est_topidx_t which_tree, p4est_quadrant_t *quadrant)
485: {
486: quadrant->p.user_int = DM_ADAPT_DETERMINE;
487: }
489: static int pforest_refine_uniform(p4est_t *p4est, p4est_topidx_t which_tree, p4est_quadrant_t *quadrant)
490: {
491: PforestAdaptCtx *ctx = (PforestAdaptCtx *)p4est->user_pointer;
492: PetscInt maxLevel = ctx->maxLevel;
494: return (PetscInt)quadrant->level < maxLevel;
495: }
497: static int pforest_refine_flag(p4est_t *p4est, p4est_topidx_t which_tree, p4est_quadrant_t *quadrant)
498: {
499: PforestAdaptCtx *ctx = (PforestAdaptCtx *)p4est->user_pointer;
500: PetscInt maxLevel = ctx->maxLevel;
502: if ((PetscInt)quadrant->level >= maxLevel) return 0;
504: return quadrant->p.user_int == DM_ADAPT_REFINE;
505: }
507: #if defined(__GNUC__) && !defined(__clang__)
508: #pragma GCC diagnostic push
509: #pragma GCC diagnostic ignored "-Wclobbered"
510: #endif
511: static PetscErrorCode DMPforestComputeLocalCellTransferSF_loop(p4est_t *p4estFrom, PetscInt FromOffset, p4est_t *p4estTo, PetscInt ToOffset, p4est_topidx_t flt, p4est_topidx_t llt, PetscInt *toFineLeavesCount, PetscInt *toLeaves, PetscSFNode *fromRoots, PetscInt *fromFineLeavesCount, PetscInt *fromLeaves, PetscSFNode *toRoots)
512: {
513: PetscMPIInt rank = p4estFrom->mpirank;
514: p4est_topidx_t t;
515: PetscInt toFineLeaves = 0, fromFineLeaves = 0;
517: PetscFunctionBegin;
518: /* -Wmaybe-uninitialized */
519: *toFineLeavesCount = 0;
520: *fromFineLeavesCount = 0;
521: for (t = flt; t <= llt; t++) { /* count roots and leaves */
522: p4est_tree_t *treeFrom = &(((p4est_tree_t *)p4estFrom->trees->array)[t]);
523: p4est_tree_t *treeTo = &(((p4est_tree_t *)p4estTo->trees->array)[t]);
524: p4est_quadrant_t *firstFrom = &treeFrom->first_desc;
525: p4est_quadrant_t *firstTo = &treeTo->first_desc;
526: PetscInt numFrom = (PetscInt)treeFrom->quadrants.elem_count;
527: PetscInt numTo = (PetscInt)treeTo->quadrants.elem_count;
528: p4est_quadrant_t *quadsFrom = (p4est_quadrant_t *)treeFrom->quadrants.array;
529: p4est_quadrant_t *quadsTo = (p4est_quadrant_t *)treeTo->quadrants.array;
530: PetscInt currentFrom, currentTo;
531: PetscInt treeOffsetFrom = (PetscInt)treeFrom->quadrants_offset;
532: PetscInt treeOffsetTo = (PetscInt)treeTo->quadrants_offset;
533: int comp;
535: PetscCallP4estReturn(comp, p4est_quadrant_is_equal, firstFrom, firstTo);
536: PetscCheck(comp, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "non-matching partitions");
538: for (currentFrom = 0, currentTo = 0; currentFrom < numFrom && currentTo < numTo;) {
539: p4est_quadrant_t *quadFrom = &quadsFrom[currentFrom];
540: p4est_quadrant_t *quadTo = &quadsTo[currentTo];
542: if (quadFrom->level == quadTo->level) {
543: if (toLeaves) {
544: toLeaves[toFineLeaves] = currentTo + treeOffsetTo + ToOffset;
545: fromRoots[toFineLeaves].rank = rank;
546: fromRoots[toFineLeaves].index = currentFrom + treeOffsetFrom + FromOffset;
547: }
548: toFineLeaves++;
549: currentFrom++;
550: currentTo++;
551: } else {
552: int fromIsAncestor;
554: PetscCallP4estReturn(fromIsAncestor, p4est_quadrant_is_ancestor, quadFrom, quadTo);
555: if (fromIsAncestor) {
556: p4est_quadrant_t lastDesc;
558: if (toLeaves) {
559: toLeaves[toFineLeaves] = currentTo + treeOffsetTo + ToOffset;
560: fromRoots[toFineLeaves].rank = rank;
561: fromRoots[toFineLeaves].index = currentFrom + treeOffsetFrom + FromOffset;
562: }
563: toFineLeaves++;
564: currentTo++;
565: PetscCallP4est(p4est_quadrant_last_descendant, quadFrom, &lastDesc, quadTo->level);
566: PetscCallP4estReturn(comp, p4est_quadrant_is_equal, quadTo, &lastDesc);
567: if (comp) currentFrom++;
568: } else {
569: p4est_quadrant_t lastDesc;
571: if (fromLeaves) {
572: fromLeaves[fromFineLeaves] = currentFrom + treeOffsetFrom + FromOffset;
573: toRoots[fromFineLeaves].rank = rank;
574: toRoots[fromFineLeaves].index = currentTo + treeOffsetTo + ToOffset;
575: }
576: fromFineLeaves++;
577: currentFrom++;
578: PetscCallP4est(p4est_quadrant_last_descendant, quadTo, &lastDesc, quadFrom->level);
579: PetscCallP4estReturn(comp, p4est_quadrant_is_equal, quadFrom, &lastDesc);
580: if (comp) currentTo++;
581: }
582: }
583: }
584: }
585: *toFineLeavesCount = toFineLeaves;
586: *fromFineLeavesCount = fromFineLeaves;
587: PetscFunctionReturn(PETSC_SUCCESS);
588: }
589: #if defined(__GNUC__) && !defined(__clang__)
590: #pragma GCC diagnostic pop
591: #endif
593: /* Compute the maximum level across all the trees */
594: static PetscErrorCode DMPforestGetRefinementLevel(DM dm, PetscInt *lev)
595: {
596: p4est_topidx_t t, flt, llt;
597: DM_Forest *forest = (DM_Forest *)dm->data;
598: DM_Forest_pforest *pforest = (DM_Forest_pforest *)forest->data;
599: p4est_t *p4est;
601: PetscFunctionBegin;
602: *lev = 0;
603: PetscCheck(pforest, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Missing DM_Forest_pforest");
604: PetscCheck(pforest->forest, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Missing p4est_t");
605: p4est = pforest->forest;
606: flt = p4est->first_local_tree;
607: llt = p4est->last_local_tree;
608: for (t = flt; t <= llt; t++) {
609: p4est_tree_t *tree = &(((p4est_tree_t *)p4est->trees->array)[t]);
610: *lev = PetscMax((PetscInt)tree->maxlevel, *lev);
611: }
612: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, lev, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
613: PetscFunctionReturn(PETSC_SUCCESS);
614: }
616: /* Puts identity in coarseToFine */
617: /* assumes a matching partition */
618: static PetscErrorCode DMPforestComputeLocalCellTransferSF(MPI_Comm comm, p4est_t *p4estFrom, PetscInt FromOffset, p4est_t *p4estTo, PetscInt ToOffset, PetscSF *fromCoarseToFine, PetscSF *toCoarseFromFine)
619: {
620: p4est_topidx_t flt, llt;
621: PetscSF fromCoarse, toCoarse;
622: PetscInt numRootsFrom, numRootsTo, numLeavesFrom, numLeavesTo;
623: PetscInt *fromLeaves = NULL, *toLeaves = NULL;
624: PetscSFNode *fromRoots = NULL, *toRoots = NULL;
626: PetscFunctionBegin;
627: flt = p4estFrom->first_local_tree;
628: llt = p4estFrom->last_local_tree;
629: PetscCall(PetscSFCreate(comm, &fromCoarse));
630: if (toCoarseFromFine) PetscCall(PetscSFCreate(comm, &toCoarse));
631: numRootsFrom = p4estFrom->local_num_quadrants + FromOffset;
632: numRootsTo = p4estTo->local_num_quadrants + ToOffset;
633: PetscCall(DMPforestComputeLocalCellTransferSF_loop(p4estFrom, FromOffset, p4estTo, ToOffset, flt, llt, &numLeavesTo, NULL, NULL, &numLeavesFrom, NULL, NULL));
634: PetscCall(PetscMalloc1(numLeavesTo, &toLeaves));
635: PetscCall(PetscMalloc1(numLeavesTo, &fromRoots));
636: if (toCoarseFromFine) {
637: PetscCall(PetscMalloc1(numLeavesFrom, &fromLeaves));
638: PetscCall(PetscMalloc1(numLeavesFrom, &fromRoots));
639: }
640: PetscCall(DMPforestComputeLocalCellTransferSF_loop(p4estFrom, FromOffset, p4estTo, ToOffset, flt, llt, &numLeavesTo, toLeaves, fromRoots, &numLeavesFrom, fromLeaves, toRoots));
641: if (!ToOffset && (numLeavesTo == numRootsTo)) { /* compress */
642: PetscCall(PetscFree(toLeaves));
643: PetscCall(PetscSFSetGraph(fromCoarse, numRootsFrom, numLeavesTo, NULL, PETSC_OWN_POINTER, fromRoots, PETSC_OWN_POINTER));
644: } else PetscCall(PetscSFSetGraph(fromCoarse, numRootsFrom, numLeavesTo, toLeaves, PETSC_OWN_POINTER, fromRoots, PETSC_OWN_POINTER));
645: *fromCoarseToFine = fromCoarse;
646: if (toCoarseFromFine) {
647: PetscCall(PetscSFSetGraph(toCoarse, numRootsTo, numLeavesFrom, fromLeaves, PETSC_OWN_POINTER, toRoots, PETSC_OWN_POINTER));
648: *toCoarseFromFine = toCoarse;
649: }
650: PetscFunctionReturn(PETSC_SUCCESS);
651: }
653: #if defined(__GNUC__) && !defined(__clang__)
654: #pragma GCC diagnostic push
655: #pragma GCC diagnostic ignored "-Wclobbered"
656: #endif
657: /* range of processes whose B sections overlap this ranks A section */
658: static PetscErrorCode DMPforestComputeOverlappingRanks(PetscMPIInt size, PetscMPIInt rank, p4est_t *p4estA, p4est_t *p4estB, PetscInt *startB, PetscInt *endB)
659: {
660: p4est_quadrant_t *myCoarseStart = &p4estA->global_first_position[rank];
661: p4est_quadrant_t *myCoarseEnd = &p4estA->global_first_position[rank + 1];
662: p4est_quadrant_t *globalFirstB = p4estB->global_first_position;
664: PetscFunctionBegin;
665: *startB = -1;
666: *endB = -1;
667: if (p4estA->local_num_quadrants) {
668: PetscInt lo, hi, guess;
669: /* binary search to find interval containing myCoarseStart */
670: lo = 0;
671: hi = size;
672: guess = rank;
673: while (1) {
674: int startCompMy, myCompEnd;
676: PetscCallP4estReturn(startCompMy, p4est_quadrant_compare_piggy, &globalFirstB[guess], myCoarseStart);
677: PetscCallP4estReturn(myCompEnd, p4est_quadrant_compare_piggy, myCoarseStart, &globalFirstB[guess + 1]);
678: if (startCompMy <= 0 && myCompEnd < 0) {
679: *startB = guess;
680: break;
681: } else if (startCompMy > 0) { /* guess is to high */
682: hi = guess;
683: } else { /* guess is to low */
684: lo = guess + 1;
685: }
686: guess = lo + (hi - lo) / 2;
687: }
688: /* reset bounds, but not guess */
689: lo = 0;
690: hi = size;
691: while (1) {
692: int startCompMy, myCompEnd;
694: PetscCallP4estReturn(startCompMy, p4est_quadrant_compare_piggy, &globalFirstB[guess], myCoarseEnd);
695: PetscCallP4estReturn(myCompEnd, p4est_quadrant_compare_piggy, myCoarseEnd, &globalFirstB[guess + 1]);
696: if (startCompMy < 0 && myCompEnd <= 0) { /* notice that the comparison operators are different from above */
697: *endB = guess + 1;
698: break;
699: } else if (startCompMy >= 0) { /* guess is to high */
700: hi = guess;
701: } else { /* guess is to low */
702: lo = guess + 1;
703: }
704: guess = lo + (hi - lo) / 2;
705: }
706: }
707: PetscFunctionReturn(PETSC_SUCCESS);
708: }
709: #if defined(__GNUC__) && !defined(__clang__)
710: #pragma GCC diagnostic pop
711: #endif
713: static PetscErrorCode DMPforestGetPlex(DM, DM *);
715: #define DMSetUp_pforest _append_pforest(DMSetUp)
716: #if defined(__GNUC__) && !defined(__clang__)
717: #pragma GCC diagnostic push
718: #pragma GCC diagnostic ignored "-Wclobbered"
719: #endif
720: static PetscErrorCode DMSetUp_pforest(DM dm)
721: {
722: DM_Forest *forest = (DM_Forest *)dm->data;
723: DM_Forest_pforest *pforest = (DM_Forest_pforest *)forest->data;
724: DM base, adaptFrom;
725: DMForestTopology topoName;
726: PetscSF preCoarseToFine = NULL, coarseToPreFine = NULL;
727: PforestAdaptCtx ctx;
729: PetscFunctionBegin;
730: ctx.minLevel = PETSC_INT_MAX;
731: ctx.maxLevel = 0;
732: ctx.currLevel = 0;
733: ctx.anyChange = PETSC_FALSE;
734: /* sanity check */
735: PetscCall(DMForestGetAdaptivityForest(dm, &adaptFrom));
736: PetscCall(DMForestGetBaseDM(dm, &base));
737: PetscCall(DMForestGetTopology(dm, &topoName));
738: PetscCheck(adaptFrom || base || topoName, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "A forest needs a topology, a base DM, or a DM to adapt from");
740: /* === Step 1: DMFTopology === */
741: if (adaptFrom) { /* reference already created topology */
742: PetscBool ispforest;
743: DM_Forest *aforest = (DM_Forest *)adaptFrom->data;
744: DM_Forest_pforest *apforest = (DM_Forest_pforest *)aforest->data;
746: PetscCall(PetscObjectTypeCompare((PetscObject)adaptFrom, DMPFOREST, &ispforest));
747: PetscCheck(ispforest, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_NOTSAMETYPE, "Trying to adapt from %s, which is not %s", ((PetscObject)adaptFrom)->type_name, DMPFOREST);
748: PetscCheck(apforest->topo, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "The pre-adaptation forest must have a topology");
749: PetscCall(DMSetUp(adaptFrom));
750: PetscCall(DMForestGetBaseDM(dm, &base));
751: PetscCall(DMForestGetTopology(dm, &topoName));
752: } else if (base) { /* construct a connectivity from base */
753: PetscBool isPlex, isDA;
755: PetscCall(PetscObjectGetName((PetscObject)base, &topoName));
756: PetscCall(DMForestSetTopology(dm, topoName));
757: PetscCall(PetscObjectTypeCompare((PetscObject)base, DMPLEX, &isPlex));
758: PetscCall(PetscObjectTypeCompare((PetscObject)base, DMDA, &isDA));
759: if (isPlex) {
760: MPI_Comm comm = PetscObjectComm((PetscObject)dm);
761: PetscInt depth;
762: PetscMPIInt size;
763: p4est_connectivity_t *conn = NULL;
764: DMFTopology_pforest *topo;
765: PetscInt *tree_face_to_uniq = NULL;
767: PetscCall(DMPlexGetDepth(base, &depth));
768: if (depth == 1) {
769: DM connDM;
771: PetscCall(DMPlexInterpolate(base, &connDM));
772: base = connDM;
773: PetscCall(DMForestSetBaseDM(dm, base));
774: PetscCall(DMDestroy(&connDM));
775: } else PetscCheck(depth == P4EST_DIM, comm, PETSC_ERR_ARG_WRONG, "Base plex is neither interpolated nor uninterpolated? depth %" PetscInt_FMT ", expected 2 or %d", depth, P4EST_DIM + 1);
776: PetscCallMPI(MPI_Comm_size(comm, &size));
777: if (size > 1) {
778: DM dmRedundant;
779: PetscSF sf;
781: PetscCall(DMPlexGetRedundantDM(base, &sf, &dmRedundant));
782: PetscCheck(dmRedundant, comm, PETSC_ERR_PLIB, "Could not create redundant DM");
783: PetscCall(PetscObjectCompose((PetscObject)dmRedundant, "_base_migration_sf", (PetscObject)sf));
784: PetscCall(PetscSFDestroy(&sf));
785: base = dmRedundant;
786: PetscCall(DMForestSetBaseDM(dm, base));
787: PetscCall(DMDestroy(&dmRedundant));
788: }
789: PetscCall(DMViewFromOptions(base, NULL, "-dm_p4est_base_view"));
790: PetscCall(DMPlexCreateConnectivity_pforest(base, &conn, &tree_face_to_uniq));
791: PetscCall(PetscNew(&topo));
792: topo->refct = 1;
793: topo->conn = conn;
794: topo->geom = NULL;
795: {
796: PetscErrorCode (*map)(DM, PetscInt, PetscInt, const PetscReal[], PetscReal[], void *);
797: void *mapCtx;
799: PetscCall(DMForestGetBaseCoordinateMapping(dm, &map, &mapCtx));
800: if (map) {
801: DM_Forest_geometry_pforest *geom_pforest;
802: p4est_geometry_t *geom;
804: PetscCall(PetscNew(&geom_pforest));
805: PetscCall(DMGetCoordinateDim(dm, &geom_pforest->coordDim));
806: geom_pforest->map = map;
807: geom_pforest->mapCtx = mapCtx;
808: PetscCallP4estReturn(geom_pforest->inner, p4est_geometry_new_connectivity, conn);
809: PetscCall(PetscNew(&geom));
810: geom->name = topoName;
811: geom->user = geom_pforest;
812: geom->X = GeometryMapping_pforest;
813: geom->destroy = GeometryDestroy_pforest;
814: topo->geom = geom;
815: }
816: }
817: topo->tree_face_to_uniq = tree_face_to_uniq;
818: pforest->topo = topo;
819: } else PetscCheck(!isDA, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Not implemented yet");
820: #if 0
821: PetscInt N[3], P[3];
823: /* get the sizes, periodicities */
824: /* ... */
825: /* don't use Morton order */
826: PetscCall(DMFTopologyCreateBrick_pforest(dm,N,P,&pforest->topo,PETSC_FALSE));
827: #endif
828: {
829: PetscInt numLabels, l;
831: PetscCall(DMGetNumLabels(base, &numLabels));
832: for (l = 0; l < numLabels; l++) {
833: PetscBool isDepth, isGhost, isVTK, isDim, isCellType;
834: DMLabel label, labelNew;
835: PetscInt defVal;
836: const char *name;
838: PetscCall(DMGetLabelName(base, l, &name));
839: PetscCall(DMGetLabelByNum(base, l, &label));
840: PetscCall(PetscStrcmp(name, "depth", &isDepth));
841: if (isDepth) continue;
842: PetscCall(PetscStrcmp(name, "dim", &isDim));
843: if (isDim) continue;
844: PetscCall(PetscStrcmp(name, "celltype", &isCellType));
845: if (isCellType) continue;
846: PetscCall(PetscStrcmp(name, "ghost", &isGhost));
847: if (isGhost) continue;
848: PetscCall(PetscStrcmp(name, "vtk", &isVTK));
849: if (isVTK) continue;
850: PetscCall(DMCreateLabel(dm, name));
851: PetscCall(DMGetLabel(dm, name, &labelNew));
852: PetscCall(DMLabelGetDefaultValue(label, &defVal));
853: PetscCall(DMLabelSetDefaultValue(labelNew, defVal));
854: }
855: /* map dm points (internal plex) to base
856: we currently create the subpoint_map for the entire hierarchy, starting from the finest forest
857: and propagating back to the coarsest
858: This is not an optimal approach, since we need the map only on the coarsest level
859: during DMForestTransferVecFromBase */
860: PetscCall(DMForestGetMinimumRefinement(dm, &l));
861: if (!l) PetscCall(DMCreateLabel(dm, "_forest_base_subpoint_map"));
862: }
863: } else { /* construct from topology name */
864: DMFTopology_pforest *topo;
866: PetscCall(DMFTopologyCreate_pforest(dm, topoName, &topo));
867: pforest->topo = topo;
868: /* TODO: construct base? */
869: }
871: /* === Step 2: get the leaves of the forest === */
872: if (adaptFrom) { /* start with the old forest */
873: DMLabel adaptLabel;
874: PetscInt defaultValue;
875: PetscInt numValuesGlobal, cLocalStart, count;
876: DM_Forest *aforest = (DM_Forest *)adaptFrom->data;
877: DM_Forest_pforest *apforest = (DM_Forest_pforest *)aforest->data;
878: PetscBool computeAdaptSF;
879: p4est_topidx_t flt, llt, t;
881: flt = apforest->forest->first_local_tree;
882: llt = apforest->forest->last_local_tree;
883: cLocalStart = apforest->cLocalStart;
884: PetscCall(DMForestGetComputeAdaptivitySF(dm, &computeAdaptSF));
885: PetscCallP4estReturn(pforest->forest, p4est_copy, apforest->forest, 0); /* 0 indicates no data copying */
886: PetscCall(DMForestGetAdaptivityLabel(dm, &adaptLabel));
887: if (adaptLabel) {
888: /* apply the refinement/coarsening by flags, plus minimum/maximum refinement */
889: PetscCall(DMLabelGetNumValues(adaptLabel, &numValuesGlobal));
890: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &numValuesGlobal, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)adaptFrom)));
891: PetscCall(DMLabelGetDefaultValue(adaptLabel, &defaultValue));
892: if (!numValuesGlobal && defaultValue == DM_ADAPT_COARSEN_LAST) { /* uniform coarsen of the last level only (equivalent to DM_ADAPT_COARSEN for conforming grids) */
893: PetscCall(DMForestGetMinimumRefinement(dm, &ctx.minLevel));
894: PetscCall(DMPforestGetRefinementLevel(dm, &ctx.currLevel));
895: pforest->forest->user_pointer = (void *)&ctx;
896: PetscCallP4est(p4est_coarsen, pforest->forest, 0, pforest_coarsen_currlevel, NULL);
897: pforest->forest->user_pointer = (void *)dm;
898: PetscCallP4est(p4est_balance, pforest->forest, P4EST_CONNECT_FULL, NULL);
899: /* we will have to change the offset after we compute the overlap */
900: if (computeAdaptSF) PetscCall(DMPforestComputeLocalCellTransferSF(PetscObjectComm((PetscObject)dm), pforest->forest, 0, apforest->forest, apforest->cLocalStart, &coarseToPreFine, NULL));
901: } else if (!numValuesGlobal && defaultValue == DM_ADAPT_COARSEN) { /* uniform coarsen */
902: PetscCall(DMForestGetMinimumRefinement(dm, &ctx.minLevel));
903: pforest->forest->user_pointer = (void *)&ctx;
904: PetscCallP4est(p4est_coarsen, pforest->forest, 0, pforest_coarsen_uniform, NULL);
905: pforest->forest->user_pointer = (void *)dm;
906: PetscCallP4est(p4est_balance, pforest->forest, P4EST_CONNECT_FULL, NULL);
907: /* we will have to change the offset after we compute the overlap */
908: if (computeAdaptSF) PetscCall(DMPforestComputeLocalCellTransferSF(PetscObjectComm((PetscObject)dm), pforest->forest, 0, apforest->forest, apforest->cLocalStart, &coarseToPreFine, NULL));
909: } else if (!numValuesGlobal && defaultValue == DM_ADAPT_REFINE) { /* uniform refine */
910: PetscCall(DMForestGetMaximumRefinement(dm, &ctx.maxLevel));
911: pforest->forest->user_pointer = (void *)&ctx;
912: PetscCallP4est(p4est_refine, pforest->forest, 0, pforest_refine_uniform, NULL);
913: pforest->forest->user_pointer = (void *)dm;
914: PetscCallP4est(p4est_balance, pforest->forest, P4EST_CONNECT_FULL, NULL);
915: /* we will have to change the offset after we compute the overlap */
916: if (computeAdaptSF) PetscCall(DMPforestComputeLocalCellTransferSF(PetscObjectComm((PetscObject)dm), apforest->forest, apforest->cLocalStart, pforest->forest, 0, &preCoarseToFine, NULL));
917: } else if (numValuesGlobal) {
918: p4est_t *p4est = pforest->forest;
919: PetscInt *cellFlags;
920: DMForestAdaptivityStrategy strategy;
921: PetscSF cellSF;
922: PetscInt c, cStart, cEnd;
923: PetscBool adaptAny;
925: PetscCall(DMForestGetMaximumRefinement(dm, &ctx.maxLevel));
926: PetscCall(DMForestGetMinimumRefinement(dm, &ctx.minLevel));
927: PetscCall(DMForestGetAdaptivityStrategy(dm, &strategy));
928: PetscCall(PetscStrncmp(strategy, "any", 3, &adaptAny));
929: PetscCall(DMForestGetCellChart(adaptFrom, &cStart, &cEnd));
930: PetscCall(DMForestGetCellSF(adaptFrom, &cellSF));
931: PetscCall(PetscMalloc1(cEnd - cStart, &cellFlags));
932: for (c = cStart; c < cEnd; c++) PetscCall(DMLabelGetValue(adaptLabel, c, &cellFlags[c - cStart]));
933: if (cellSF) {
934: if (adaptAny) {
935: PetscCall(PetscSFReduceBegin(cellSF, MPIU_INT, cellFlags, cellFlags, MPI_MAX));
936: PetscCall(PetscSFReduceEnd(cellSF, MPIU_INT, cellFlags, cellFlags, MPI_MAX));
937: } else {
938: PetscCall(PetscSFReduceBegin(cellSF, MPIU_INT, cellFlags, cellFlags, MPI_MIN));
939: PetscCall(PetscSFReduceEnd(cellSF, MPIU_INT, cellFlags, cellFlags, MPI_MIN));
940: }
941: }
942: for (t = flt, count = cLocalStart; t <= llt; t++) {
943: p4est_tree_t *tree = &(((p4est_tree_t *)p4est->trees->array)[t]);
944: PetscInt numQuads = (PetscInt)tree->quadrants.elem_count, i;
945: p4est_quadrant_t *quads = (p4est_quadrant_t *)tree->quadrants.array;
947: for (i = 0; i < numQuads; i++) {
948: p4est_quadrant_t *q = &quads[i];
949: q->p.user_int = cellFlags[count++];
950: }
951: }
952: PetscCall(PetscFree(cellFlags));
954: pforest->forest->user_pointer = (void *)&ctx;
955: if (adaptAny) PetscCallP4est(p4est_coarsen, pforest->forest, 0, pforest_coarsen_flag_any, pforest_init_determine);
956: else PetscCallP4est(p4est_coarsen, pforest->forest, 0, pforest_coarsen_flag_all, pforest_init_determine);
957: PetscCallP4est(p4est_refine, pforest->forest, 0, pforest_refine_flag, NULL);
958: pforest->forest->user_pointer = (void *)dm;
959: PetscCallP4est(p4est_balance, pforest->forest, P4EST_CONNECT_FULL, NULL);
960: if (computeAdaptSF) PetscCall(DMPforestComputeLocalCellTransferSF(PetscObjectComm((PetscObject)dm), apforest->forest, apforest->cLocalStart, pforest->forest, 0, &preCoarseToFine, &coarseToPreFine));
961: }
962: for (t = flt, count = cLocalStart; t <= llt; t++) {
963: p4est_tree_t *atree = &(((p4est_tree_t *)apforest->forest->trees->array)[t]);
964: p4est_tree_t *tree = &(((p4est_tree_t *)pforest->forest->trees->array)[t]);
965: PetscInt anumQuads = (PetscInt)atree->quadrants.elem_count, i;
966: PetscInt numQuads = (PetscInt)tree->quadrants.elem_count;
967: p4est_quadrant_t *aquads = (p4est_quadrant_t *)atree->quadrants.array;
968: p4est_quadrant_t *quads = (p4est_quadrant_t *)tree->quadrants.array;
970: if (anumQuads != numQuads) {
971: ctx.anyChange = PETSC_TRUE;
972: } else {
973: for (i = 0; i < numQuads; i++) {
974: p4est_quadrant_t *aq = &aquads[i];
975: p4est_quadrant_t *q = &quads[i];
977: if (aq->level != q->level) {
978: ctx.anyChange = PETSC_TRUE;
979: break;
980: }
981: }
982: }
983: if (ctx.anyChange) break;
984: }
985: }
986: {
987: PetscInt numLabels, l;
989: PetscCall(DMGetNumLabels(adaptFrom, &numLabels));
990: for (l = 0; l < numLabels; l++) {
991: PetscBool isDepth, isCellType, isGhost, isVTK;
992: DMLabel label, labelNew;
993: PetscInt defVal;
994: const char *name;
996: PetscCall(DMGetLabelName(adaptFrom, l, &name));
997: PetscCall(DMGetLabelByNum(adaptFrom, l, &label));
998: PetscCall(PetscStrcmp(name, "depth", &isDepth));
999: if (isDepth) continue;
1000: PetscCall(PetscStrcmp(name, "celltype", &isCellType));
1001: if (isCellType) continue;
1002: PetscCall(PetscStrcmp(name, "ghost", &isGhost));
1003: if (isGhost) continue;
1004: PetscCall(PetscStrcmp(name, "vtk", &isVTK));
1005: if (isVTK) continue;
1006: PetscCall(DMCreateLabel(dm, name));
1007: PetscCall(DMGetLabel(dm, name, &labelNew));
1008: PetscCall(DMLabelGetDefaultValue(label, &defVal));
1009: PetscCall(DMLabelSetDefaultValue(labelNew, defVal));
1010: }
1011: }
1012: } else { /* initial */
1013: PetscInt initLevel, minLevel;
1014: #if PetscDefined(HAVE_MPIUNI)
1015: sc_MPI_Comm comm = sc_MPI_COMM_WORLD;
1016: #else
1017: MPI_Comm comm = PetscObjectComm((PetscObject)dm);
1018: #endif
1020: PetscCall(DMForestGetInitialRefinement(dm, &initLevel));
1021: PetscCall(DMForestGetMinimumRefinement(dm, &minLevel));
1022: PetscCallP4estReturn(pforest->forest, p4est_new_ext, comm, pforest->topo->conn, 0, /* minimum number of quadrants per processor */
1023: initLevel, /* level of refinement */
1024: 1, /* uniform refinement */
1025: 0, /* we don't allocate any per quadrant data */
1026: NULL, /* there is no special quadrant initialization */
1027: (void *)dm); /* this dm is the user context */
1029: if (initLevel > minLevel) pforest->coarsen_hierarchy = PETSC_TRUE;
1030: if (dm->setfromoptionscalled) {
1031: PetscBool flgPattern, flgFractal;
1032: PetscInt corner = 0;
1033: PetscInt corners[P4EST_CHILDREN], ncorner = P4EST_CHILDREN;
1034: PetscReal likelihood = 1. / P4EST_DIM;
1035: PetscInt pattern;
1036: const char *prefix;
1038: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)dm, &prefix));
1039: PetscCall(PetscOptionsGetEList(((PetscObject)dm)->options, prefix, "-dm_p4est_refine_pattern", DMRefinePatternName, PATTERN_COUNT, &pattern, &flgPattern));
1040: PetscCall(PetscOptionsGetInt(((PetscObject)dm)->options, prefix, "-dm_p4est_refine_corner", &corner, NULL));
1041: PetscCall(PetscOptionsGetIntArray(((PetscObject)dm)->options, prefix, "-dm_p4est_refine_fractal_corners", corners, &ncorner, &flgFractal));
1042: PetscCall(PetscOptionsGetReal(((PetscObject)dm)->options, prefix, "-dm_p4est_refine_hash_likelihood", &likelihood, NULL));
1044: if (flgPattern) {
1045: DMRefinePatternCtx *ctx;
1046: PetscInt maxLevel;
1048: PetscCall(DMForestGetMaximumRefinement(dm, &maxLevel));
1049: PetscCall(PetscNew(&ctx));
1050: ctx->maxLevel = PetscMin(maxLevel, P4EST_QMAXLEVEL);
1051: if (initLevel + ctx->maxLevel > minLevel) pforest->coarsen_hierarchy = PETSC_TRUE;
1052: switch (pattern) {
1053: case PATTERN_HASH:
1054: ctx->refine_fn = DMRefinePattern_Hash;
1055: ctx->hashLikelihood = likelihood;
1056: break;
1057: case PATTERN_CORNER:
1058: ctx->corner = corner;
1059: ctx->refine_fn = DMRefinePattern_Corner;
1060: break;
1061: case PATTERN_CENTER:
1062: ctx->refine_fn = DMRefinePattern_Center;
1063: break;
1064: case PATTERN_FRACTAL:
1065: if (flgFractal) {
1066: PetscInt i;
1068: for (i = 0; i < ncorner; i++) ctx->fractal[corners[i]] = PETSC_TRUE;
1069: } else {
1070: #if !defined(P4_TO_P8)
1071: ctx->fractal[0] = ctx->fractal[1] = ctx->fractal[2] = PETSC_TRUE;
1072: #else
1073: ctx->fractal[0] = ctx->fractal[3] = ctx->fractal[5] = ctx->fractal[6] = PETSC_TRUE;
1074: #endif
1075: }
1076: ctx->refine_fn = DMRefinePattern_Fractal;
1077: break;
1078: default:
1079: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Not a valid refinement pattern");
1080: }
1082: pforest->forest->user_pointer = (void *)ctx;
1083: PetscCallP4est(p4est_refine, pforest->forest, 1, ctx->refine_fn, NULL);
1084: PetscCallP4est(p4est_balance, pforest->forest, P4EST_CONNECT_FULL, NULL);
1085: PetscCall(PetscFree(ctx));
1086: pforest->forest->user_pointer = (void *)dm;
1087: }
1088: }
1089: }
1090: if (pforest->coarsen_hierarchy) {
1091: PetscInt initLevel, currLevel, minLevel;
1093: PetscCall(DMPforestGetRefinementLevel(dm, &currLevel));
1094: PetscCall(DMForestGetInitialRefinement(dm, &initLevel));
1095: PetscCall(DMForestGetMinimumRefinement(dm, &minLevel));
1096: /* allow using PCMG and SNESFAS */
1097: PetscCall(DMSetRefineLevel(dm, currLevel - minLevel));
1098: if (currLevel > minLevel) {
1099: DM_Forest_pforest *coarse_pforest;
1100: DMLabel coarsen;
1101: DM coarseDM;
1103: PetscCall(DMForestTemplate(dm, MPI_COMM_NULL, &coarseDM));
1104: PetscCall(DMForestSetAdaptivityPurpose(coarseDM, DM_ADAPT_COARSEN));
1105: PetscCall(DMLabelCreate(PETSC_COMM_SELF, "coarsen", &coarsen));
1106: PetscCall(DMLabelSetDefaultValue(coarsen, DM_ADAPT_COARSEN));
1107: PetscCall(DMForestSetAdaptivityLabel(coarseDM, coarsen));
1108: PetscCall(DMLabelDestroy(&coarsen));
1109: PetscCall(DMSetCoarseDM(dm, coarseDM));
1110: PetscCall(PetscObjectDereference((PetscObject)coarseDM));
1111: initLevel = currLevel == initLevel ? initLevel - 1 : initLevel;
1112: PetscCall(DMForestSetInitialRefinement(coarseDM, initLevel));
1113: PetscCall(DMForestSetMinimumRefinement(coarseDM, minLevel));
1114: coarse_pforest = (DM_Forest_pforest *)((DM_Forest *)coarseDM->data)->data;
1115: coarse_pforest->coarsen_hierarchy = PETSC_TRUE;
1116: }
1117: }
1119: { /* repartitioning and overlap */
1120: PetscMPIInt size, rank;
1122: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
1123: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
1124: if (size > 1 && (pforest->partition_for_coarsening || forest->cellWeights || forest->weightCapacity != 1. || forest->weightsFactor != 1.)) {
1125: PetscBool copyForest = PETSC_FALSE;
1126: p4est_t *forest_copy = NULL;
1127: p4est_gloidx_t shipped = 0;
1129: if (preCoarseToFine || coarseToPreFine) copyForest = PETSC_TRUE;
1130: if (copyForest) PetscCallP4estReturn(forest_copy, p4est_copy, pforest->forest, 0);
1132: PetscCheck(!forest->cellWeights && forest->weightCapacity == 1. && forest->weightsFactor == 1., PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Non-uniform partition cases not implemented yet");
1133: PetscCallP4estReturn(shipped, p4est_partition_ext, pforest->forest, (int)pforest->partition_for_coarsening, NULL);
1134: if (shipped) ctx.anyChange = PETSC_TRUE;
1135: if (forest_copy) {
1136: if (preCoarseToFine || coarseToPreFine) {
1137: PetscSF repartSF; /* repartSF has roots in the old partition */
1138: PetscInt pStart = -1, pEnd = -1, p;
1139: PetscInt numRoots, numLeaves;
1140: PetscSFNode *repartRoots;
1141: p4est_gloidx_t postStart = pforest->forest->global_first_quadrant[rank];
1142: p4est_gloidx_t postEnd = pforest->forest->global_first_quadrant[rank + 1];
1143: p4est_gloidx_t partOffset = postStart;
1145: numRoots = (PetscInt)(forest_copy->global_first_quadrant[rank + 1] - forest_copy->global_first_quadrant[rank]);
1146: numLeaves = (PetscInt)(postEnd - postStart);
1147: PetscCall(DMPforestComputeOverlappingRanks(size, rank, pforest->forest, forest_copy, &pStart, &pEnd));
1148: PetscCall(PetscMalloc1((PetscInt)pforest->forest->local_num_quadrants, &repartRoots));
1149: for (p = pStart; p < pEnd; p++) {
1150: p4est_gloidx_t preStart = forest_copy->global_first_quadrant[p];
1151: p4est_gloidx_t preEnd = forest_copy->global_first_quadrant[p + 1];
1153: if (preEnd == preStart) continue;
1154: PetscCheck(preStart <= postStart, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Bad partition overlap computation");
1155: preEnd = preEnd > postEnd ? postEnd : preEnd;
1156: for (p4est_gloidx_t q = partOffset; q < preEnd; q++) {
1157: repartRoots[q - postStart].rank = p;
1158: repartRoots[q - postStart].index = (PetscInt)(partOffset - preStart);
1159: }
1160: partOffset = preEnd;
1161: }
1162: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &repartSF));
1163: PetscCall(PetscSFSetGraph(repartSF, numRoots, numLeaves, NULL, PETSC_OWN_POINTER, repartRoots, PETSC_OWN_POINTER));
1164: PetscCall(PetscSFSetUp(repartSF));
1165: if (preCoarseToFine) {
1166: PetscSF repartSFembed, preCoarseToFineNew;
1167: PetscInt nleaves;
1168: const PetscInt *leaves;
1170: PetscCall(PetscSFSetUp(preCoarseToFine));
1171: PetscCall(PetscSFGetGraph(preCoarseToFine, NULL, &nleaves, &leaves, NULL));
1172: if (leaves) {
1173: PetscCall(PetscSFCreateEmbeddedRootSF(repartSF, nleaves, leaves, &repartSFembed));
1174: } else {
1175: repartSFembed = repartSF;
1176: PetscCall(PetscObjectReference((PetscObject)repartSFembed));
1177: }
1178: PetscCall(PetscSFCompose(preCoarseToFine, repartSFembed, &preCoarseToFineNew));
1179: PetscCall(PetscSFDestroy(&preCoarseToFine));
1180: PetscCall(PetscSFDestroy(&repartSFembed));
1181: preCoarseToFine = preCoarseToFineNew;
1182: }
1183: if (coarseToPreFine) {
1184: PetscSF repartSFinv, coarseToPreFineNew;
1186: PetscCall(PetscSFCreateInverseSF(repartSF, &repartSFinv));
1187: PetscCall(PetscSFCompose(repartSFinv, coarseToPreFine, &coarseToPreFineNew));
1188: PetscCall(PetscSFDestroy(&coarseToPreFine));
1189: PetscCall(PetscSFDestroy(&repartSFinv));
1190: coarseToPreFine = coarseToPreFineNew;
1191: }
1192: PetscCall(PetscSFDestroy(&repartSF));
1193: }
1194: PetscCallP4est(p4est_destroy, forest_copy);
1195: }
1196: }
1197: if (size > 1) {
1198: PetscInt overlap;
1200: PetscCall(DMForestGetPartitionOverlap(dm, &overlap));
1202: if (adaptFrom) {
1203: PetscInt aoverlap;
1205: PetscCall(DMForestGetPartitionOverlap(adaptFrom, &aoverlap));
1206: if (aoverlap != overlap) ctx.anyChange = PETSC_TRUE;
1207: }
1209: if (overlap > 0) {
1210: PetscInt i, cLocalStart;
1211: PetscInt cEnd;
1212: PetscSF preCellSF = NULL, cellSF = NULL;
1214: PetscCallP4estReturn(pforest->ghost, p4est_ghost_new, pforest->forest, P4EST_CONNECT_FULL);
1215: PetscCallP4estReturn(pforest->lnodes, p4est_lnodes_new, pforest->forest, pforest->ghost, -P4EST_DIM);
1216: PetscCallP4est(p4est_ghost_support_lnodes, pforest->forest, pforest->lnodes, pforest->ghost);
1217: for (i = 1; i < overlap; i++) PetscCallP4est(p4est_ghost_expand_by_lnodes, pforest->forest, pforest->lnodes, pforest->ghost);
1219: cLocalStart = pforest->cLocalStart = pforest->ghost->proc_offsets[rank];
1220: cEnd = pforest->forest->local_num_quadrants + pforest->ghost->proc_offsets[size];
1222: /* shift sfs by cLocalStart, expand by cell SFs */
1223: if (preCoarseToFine || coarseToPreFine) {
1224: if (adaptFrom) PetscCall(DMForestGetCellSF(adaptFrom, &preCellSF));
1225: dm->setupcalled = PETSC_TRUE;
1226: PetscCall(DMForestGetCellSF(dm, &cellSF));
1227: }
1228: if (preCoarseToFine) {
1229: PetscSF preCoarseToFineNew;
1230: PetscInt nleaves, nroots, *leavesNew, i, nleavesNew;
1231: const PetscInt *leaves;
1232: const PetscSFNode *remotes;
1233: PetscSFNode *remotesAll;
1235: PetscCall(PetscSFSetUp(preCoarseToFine));
1236: PetscCall(PetscSFGetGraph(preCoarseToFine, &nroots, &nleaves, &leaves, &remotes));
1237: PetscCall(PetscMalloc1(cEnd, &remotesAll));
1238: for (i = 0; i < cEnd; i++) {
1239: remotesAll[i].rank = -1;
1240: remotesAll[i].index = -1;
1241: }
1242: for (i = 0; i < nleaves; i++) remotesAll[(leaves ? leaves[i] : i) + cLocalStart] = remotes[i];
1243: PetscCall(PetscSFSetUp(cellSF));
1244: PetscCall(PetscSFBcastBegin(cellSF, MPIU_SF_NODE, remotesAll, remotesAll, MPI_REPLACE));
1245: PetscCall(PetscSFBcastEnd(cellSF, MPIU_SF_NODE, remotesAll, remotesAll, MPI_REPLACE));
1246: nleavesNew = 0;
1247: for (i = 0; i < nleaves; i++) {
1248: if (remotesAll[i].rank >= 0) nleavesNew++;
1249: }
1250: PetscCall(PetscMalloc1(nleavesNew, &leavesNew));
1251: nleavesNew = 0;
1252: for (i = 0; i < nleaves; i++) {
1253: if (remotesAll[i].rank >= 0) {
1254: leavesNew[nleavesNew] = i;
1255: if (i > nleavesNew) remotesAll[nleavesNew] = remotesAll[i];
1256: nleavesNew++;
1257: }
1258: }
1259: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &preCoarseToFineNew));
1260: if (nleavesNew < cEnd) {
1261: PetscCall(PetscSFSetGraph(preCoarseToFineNew, nroots, nleavesNew, leavesNew, PETSC_OWN_POINTER, remotesAll, PETSC_COPY_VALUES));
1262: } else { /* all cells are leaves */
1263: PetscCall(PetscFree(leavesNew));
1264: PetscCall(PetscSFSetGraph(preCoarseToFineNew, nroots, nleavesNew, NULL, PETSC_OWN_POINTER, remotesAll, PETSC_COPY_VALUES));
1265: }
1266: PetscCall(PetscFree(remotesAll));
1267: PetscCall(PetscSFDestroy(&preCoarseToFine));
1268: preCoarseToFine = preCoarseToFineNew;
1269: preCoarseToFine = preCoarseToFineNew;
1270: }
1271: if (coarseToPreFine) {
1272: PetscSF coarseToPreFineNew;
1273: PetscInt nleaves, nroots, i, nleavesCellSF, nleavesExpanded, *leavesNew;
1274: const PetscInt *leaves;
1275: const PetscSFNode *remotes;
1276: PetscSFNode *remotesNew, *remotesNewRoot, *remotesExpanded;
1278: PetscCall(PetscSFSetUp(coarseToPreFine));
1279: PetscCall(PetscSFGetGraph(coarseToPreFine, &nroots, &nleaves, &leaves, &remotes));
1280: PetscCall(PetscSFGetGraph(preCellSF, NULL, &nleavesCellSF, NULL, NULL));
1281: PetscCall(PetscMalloc1(nroots, &remotesNewRoot));
1282: PetscCall(PetscMalloc1(nleaves, &remotesNew));
1283: for (i = 0; i < nroots; i++) {
1284: remotesNewRoot[i].rank = rank;
1285: remotesNewRoot[i].index = i + cLocalStart;
1286: }
1287: PetscCall(PetscSFBcastBegin(coarseToPreFine, MPIU_SF_NODE, remotesNewRoot, remotesNew, MPI_REPLACE));
1288: PetscCall(PetscSFBcastEnd(coarseToPreFine, MPIU_SF_NODE, remotesNewRoot, remotesNew, MPI_REPLACE));
1289: PetscCall(PetscFree(remotesNewRoot));
1290: PetscCall(PetscMalloc1(nleavesCellSF, &remotesExpanded));
1291: for (i = 0; i < nleavesCellSF; i++) {
1292: remotesExpanded[i].rank = -1;
1293: remotesExpanded[i].index = -1;
1294: }
1295: for (i = 0; i < nleaves; i++) remotesExpanded[leaves ? leaves[i] : i] = remotesNew[i];
1296: PetscCall(PetscFree(remotesNew));
1297: PetscCall(PetscSFBcastBegin(preCellSF, MPIU_SF_NODE, remotesExpanded, remotesExpanded, MPI_REPLACE));
1298: PetscCall(PetscSFBcastEnd(preCellSF, MPIU_SF_NODE, remotesExpanded, remotesExpanded, MPI_REPLACE));
1300: nleavesExpanded = 0;
1301: for (i = 0; i < nleavesCellSF; i++) {
1302: if (remotesExpanded[i].rank >= 0) nleavesExpanded++;
1303: }
1304: PetscCall(PetscMalloc1(nleavesExpanded, &leavesNew));
1305: nleavesExpanded = 0;
1306: for (i = 0; i < nleavesCellSF; i++) {
1307: if (remotesExpanded[i].rank >= 0) {
1308: leavesNew[nleavesExpanded] = i;
1309: if (i > nleavesExpanded) remotesExpanded[nleavesExpanded] = remotes[i];
1310: nleavesExpanded++;
1311: }
1312: }
1313: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &coarseToPreFineNew));
1314: if (nleavesExpanded < nleavesCellSF) {
1315: PetscCall(PetscSFSetGraph(coarseToPreFineNew, cEnd, nleavesExpanded, leavesNew, PETSC_OWN_POINTER, remotesExpanded, PETSC_COPY_VALUES));
1316: } else {
1317: PetscCall(PetscFree(leavesNew));
1318: PetscCall(PetscSFSetGraph(coarseToPreFineNew, cEnd, nleavesExpanded, NULL, PETSC_OWN_POINTER, remotesExpanded, PETSC_COPY_VALUES));
1319: }
1320: PetscCall(PetscFree(remotesExpanded));
1321: PetscCall(PetscSFDestroy(&coarseToPreFine));
1322: coarseToPreFine = coarseToPreFineNew;
1323: }
1324: }
1325: }
1326: }
1327: forest->preCoarseToFine = preCoarseToFine;
1328: forest->coarseToPreFine = coarseToPreFine;
1329: dm->setupcalled = PETSC_TRUE;
1330: PetscCallMPI(MPIU_Allreduce(&ctx.anyChange, &pforest->adaptivitySuccess, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)dm)));
1331: PetscCall(DMPforestGetPlex(dm, NULL));
1332: PetscFunctionReturn(PETSC_SUCCESS);
1333: }
1334: #if defined(__GNUC__) && !defined(__clang__)
1335: #pragma GCC diagnostic pop
1336: #endif
1338: #define DMForestGetAdaptivitySuccess_pforest _append_pforest(DMForestGetAdaptivitySuccess)
1339: static PetscErrorCode DMForestGetAdaptivitySuccess_pforest(DM dm, PetscBool *success)
1340: {
1341: DM_Forest *forest;
1342: DM_Forest_pforest *pforest;
1344: PetscFunctionBegin;
1345: forest = (DM_Forest *)dm->data;
1346: pforest = (DM_Forest_pforest *)forest->data;
1347: *success = pforest->adaptivitySuccess;
1348: PetscFunctionReturn(PETSC_SUCCESS);
1349: }
1351: #define DMView_ASCII_pforest _append_pforest(DMView_ASCII)
1352: static PetscErrorCode DMView_ASCII_pforest(PetscObject odm, PetscViewer viewer)
1353: {
1354: DM dm = (DM)odm;
1356: PetscFunctionBegin;
1359: PetscCall(DMSetUp(dm));
1360: switch (viewer->format) {
1361: case PETSC_VIEWER_DEFAULT:
1362: case PETSC_VIEWER_ASCII_INFO: {
1363: PetscInt dim;
1364: const char *name;
1366: PetscCall(PetscObjectGetName((PetscObject)dm, &name));
1367: PetscCall(DMGetDimension(dm, &dim));
1368: if (name) PetscCall(PetscViewerASCIIPrintf(viewer, "Forest %s in %" PetscInt_FMT " dimensions:\n", name, dim));
1369: else PetscCall(PetscViewerASCIIPrintf(viewer, "Forest in %" PetscInt_FMT " dimensions:\n", dim));
1370: } /* fall through */
1371: case PETSC_VIEWER_ASCII_INFO_DETAIL:
1372: case PETSC_VIEWER_LOAD_BALANCE: {
1373: DM plex;
1375: PetscCall(DMPforestGetPlex(dm, &plex));
1376: PetscCall(DMView(plex, viewer));
1377: } break;
1378: default:
1379: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No support for format '%s'", PetscViewerFormats[viewer->format]);
1380: }
1381: PetscFunctionReturn(PETSC_SUCCESS);
1382: }
1384: #define DMView_VTK_pforest _append_pforest(DMView_VTK)
1385: static PetscErrorCode DMView_VTK_pforest(PetscObject odm, PetscViewer viewer)
1386: {
1387: DM dm = (DM)odm;
1388: DM_Forest *forest = (DM_Forest *)dm->data;
1389: DM_Forest_pforest *pforest = (DM_Forest_pforest *)forest->data;
1390: PetscBool isvtk;
1391: PetscReal vtkScale = 1. - PETSC_MACHINE_EPSILON;
1392: PetscViewer_VTK *vtk = (PetscViewer_VTK *)viewer->data;
1393: const char *name;
1394: char *filenameStrip = NULL;
1395: PetscBool hasExt;
1396: size_t len;
1397: p4est_geometry_t *geom;
1399: PetscFunctionBegin;
1402: PetscCall(DMSetUp(dm));
1403: geom = pforest->topo->geom;
1404: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk));
1405: PetscCheck(isvtk, PetscObjectComm((PetscObject)viewer), PETSC_ERR_ARG_INCOMP, "Cannot use viewer type %s", ((PetscObject)viewer)->type_name);
1406: switch (viewer->format) {
1407: case PETSC_VIEWER_VTK_VTU:
1408: PetscCheck(pforest->forest, PetscObjectComm(odm), PETSC_ERR_ARG_WRONG, "DM has not been setup with a valid forest");
1409: name = vtk->filename;
1410: PetscCall(PetscStrlen(name, &len));
1411: PetscCall(PetscStrcasecmp(name + len - 4, ".vtu", &hasExt));
1412: if (hasExt) {
1413: PetscCall(PetscStrallocpy(name, &filenameStrip));
1414: filenameStrip[len - 4] = '\0';
1415: name = filenameStrip;
1416: }
1417: if (!pforest->topo->geom) PetscCallP4estReturn(geom, p4est_geometry_new_connectivity, pforest->topo->conn);
1418: {
1419: p4est_vtk_context_t *pvtk;
1420: int footerr;
1422: PetscCallP4estReturn(pvtk, p4est_vtk_context_new, pforest->forest, name);
1423: PetscCallP4est(p4est_vtk_context_set_geom, pvtk, geom);
1424: PetscCallP4est(p4est_vtk_context_set_scale, pvtk, (double)vtkScale);
1425: PetscCallP4estReturn(pvtk, p4est_vtk_write_header, pvtk);
1426: PetscCheck(pvtk, PetscObjectComm((PetscObject)odm), PETSC_ERR_LIB, P4EST_STRING "_vtk_write_header() failed");
1427: PetscCallP4estReturn(pvtk, p4est_vtk_write_cell_dataf, pvtk, 1, /* write tree */
1428: 1, /* write level */
1429: 1, /* write rank */
1430: 0, /* do not wrap rank */
1431: 0, /* no scalar fields */
1432: 0, /* no vector fields */
1433: pvtk);
1434: PetscCheck(pvtk, PetscObjectComm((PetscObject)odm), PETSC_ERR_LIB, P4EST_STRING "_vtk_write_cell_dataf() failed");
1435: PetscCallP4estReturn(footerr, p4est_vtk_write_footer, pvtk);
1436: PetscCheck(!footerr, PetscObjectComm((PetscObject)odm), PETSC_ERR_LIB, P4EST_STRING "_vtk_write_footer() failed");
1437: }
1438: if (!pforest->topo->geom) PetscCallP4est(p4est_geometry_destroy, geom);
1439: PetscCall(PetscFree(filenameStrip));
1440: break;
1441: default:
1442: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No support for format '%s'", PetscViewerFormats[viewer->format]);
1443: }
1444: PetscFunctionReturn(PETSC_SUCCESS);
1445: }
1447: #define DMView_HDF5_pforest _append_pforest(DMView_HDF5)
1448: static PetscErrorCode DMView_HDF5_pforest(DM dm, PetscViewer viewer)
1449: {
1450: DM plex;
1452: PetscFunctionBegin;
1453: PetscCall(DMSetUp(dm));
1454: PetscCall(DMPforestGetPlex(dm, &plex));
1455: PetscCall(DMView(plex, viewer));
1456: PetscFunctionReturn(PETSC_SUCCESS);
1457: }
1459: #define DMView_GLVis_pforest _append_pforest(DMView_GLVis)
1460: static PetscErrorCode DMView_GLVis_pforest(DM dm, PetscViewer viewer)
1461: {
1462: DM plex;
1464: PetscFunctionBegin;
1465: PetscCall(DMSetUp(dm));
1466: PetscCall(DMPforestGetPlex(dm, &plex));
1467: PetscCall(DMView(plex, viewer));
1468: PetscFunctionReturn(PETSC_SUCCESS);
1469: }
1471: #define DMView_pforest _append_pforest(DMView)
1472: static PetscErrorCode DMView_pforest(DM dm, PetscViewer viewer)
1473: {
1474: PetscBool isascii, isvtk, ishdf5, isglvis;
1476: PetscFunctionBegin;
1479: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1480: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk));
1481: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
1482: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERGLVIS, &isglvis));
1483: if (isascii) {
1484: PetscCall(DMView_ASCII_pforest((PetscObject)dm, viewer));
1485: } else if (isvtk) {
1486: PetscCall(DMView_VTK_pforest((PetscObject)dm, viewer));
1487: } else if (ishdf5) {
1488: PetscCall(DMView_HDF5_pforest(dm, viewer));
1489: } else if (isglvis) {
1490: PetscCall(DMView_GLVis_pforest(dm, viewer));
1491: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Viewer not supported (not VTK, HDF5, or GLVis)");
1492: PetscFunctionReturn(PETSC_SUCCESS);
1493: }
1495: static PetscErrorCode PforestConnectivityEnumerateFacets(p4est_connectivity_t *conn, PetscInt **tree_face_to_uniq)
1496: {
1497: PetscInt *ttf, f, t, g, count;
1498: PetscInt numFacets;
1500: PetscFunctionBegin;
1501: numFacets = conn->num_trees * P4EST_FACES;
1502: PetscCall(PetscMalloc1(numFacets, &ttf));
1503: for (f = 0; f < numFacets; f++) ttf[f] = -1;
1504: for (g = 0, count = 0, t = 0; t < conn->num_trees; t++) {
1505: for (f = 0; f < P4EST_FACES; f++, g++) {
1506: if (ttf[g] == -1) {
1507: PetscInt ng;
1509: ttf[g] = count++;
1510: ng = conn->tree_to_tree[g] * P4EST_FACES + (conn->tree_to_face[g] % P4EST_FACES);
1511: ttf[ng] = ttf[g];
1512: }
1513: }
1514: }
1515: *tree_face_to_uniq = ttf;
1516: PetscFunctionReturn(PETSC_SUCCESS);
1517: }
1519: static PetscErrorCode DMPlexCreateConnectivity_pforest(DM dm, p4est_connectivity_t **connOut, PetscInt **tree_face_to_uniq)
1520: {
1521: p4est_topidx_t numTrees, numVerts, numCorns, numCtt;
1522: PetscSection ctt;
1523: #if defined(P4_TO_P8)
1524: p4est_topidx_t numEdges, numEtt;
1525: PetscSection ett;
1526: PetscInt eStart, eEnd, e, ettSize;
1527: PetscInt vertOff = 1 + P4EST_FACES + P8EST_EDGES;
1528: PetscInt edgeOff = 1 + P4EST_FACES;
1529: #else
1530: PetscInt vertOff = 1 + P4EST_FACES;
1531: #endif
1532: p4est_connectivity_t *conn;
1533: PetscInt cStart, cEnd, c, vStart, vEnd, v, fStart, fEnd, f;
1534: PetscInt *star = NULL, *closure = NULL, closureSize, starSize, cttSize;
1535: PetscInt *ttf;
1537: PetscFunctionBegin;
1538: /* 1: count objects, allocate */
1539: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
1540: PetscCall(P4estTopidxCast(cEnd - cStart, &numTrees));
1541: numVerts = P4EST_CHILDREN * numTrees;
1542: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
1543: PetscCall(P4estTopidxCast(vEnd - vStart, &numCorns));
1544: PetscCall(PetscSectionCreate(PETSC_COMM_SELF, &ctt));
1545: PetscCall(PetscSectionSetChart(ctt, vStart, vEnd));
1546: for (v = vStart; v < vEnd; v++) {
1547: PetscInt s;
1549: PetscCall(DMPlexGetTransitiveClosure(dm, v, PETSC_FALSE, &starSize, &star));
1550: for (s = 0; s < starSize; s++) {
1551: PetscInt p = star[2 * s];
1553: if (p >= cStart && p < cEnd) {
1554: /* we want to count every time cell p references v, so we see how many times it comes up in the closure. This
1555: * only protects against periodicity problems */
1556: PetscCall(DMPlexGetTransitiveClosure(dm, p, PETSC_TRUE, &closureSize, &closure));
1557: PetscCheck(closureSize == P4EST_INSUL, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Cell %" PetscInt_FMT " with wrong closure size %" PetscInt_FMT " != %d", p, closureSize, P4EST_INSUL);
1558: for (c = 0; c < P4EST_CHILDREN; c++) {
1559: PetscInt cellVert = closure[2 * (c + vertOff)];
1561: PetscCheck(cellVert >= vStart && cellVert < vEnd, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Non-standard closure: vertices");
1562: if (cellVert == v) PetscCall(PetscSectionAddDof(ctt, v, 1));
1563: }
1564: PetscCall(DMPlexRestoreTransitiveClosure(dm, p, PETSC_TRUE, &closureSize, &closure));
1565: }
1566: }
1567: PetscCall(DMPlexRestoreTransitiveClosure(dm, v, PETSC_FALSE, &starSize, &star));
1568: }
1569: PetscCall(PetscSectionSetUp(ctt));
1570: PetscCall(PetscSectionGetStorageSize(ctt, &cttSize));
1571: PetscCall(P4estTopidxCast(cttSize, &numCtt));
1572: #if defined(P4_TO_P8)
1573: PetscCall(DMPlexGetSimplexOrBoxCells(dm, P4EST_DIM - 1, &eStart, &eEnd));
1574: PetscCall(P4estTopidxCast(eEnd - eStart, &numEdges));
1575: PetscCall(PetscSectionCreate(PETSC_COMM_SELF, &ett));
1576: PetscCall(PetscSectionSetChart(ett, eStart, eEnd));
1577: for (e = eStart; e < eEnd; e++) {
1578: PetscInt s;
1580: PetscCall(DMPlexGetTransitiveClosure(dm, e, PETSC_FALSE, &starSize, &star));
1581: for (s = 0; s < starSize; s++) {
1582: PetscInt p = star[2 * s];
1584: if (p >= cStart && p < cEnd) {
1585: /* we want to count every time cell p references e, so we see how many times it comes up in the closure. This
1586: * only protects against periodicity problems */
1587: PetscCall(DMPlexGetTransitiveClosure(dm, p, PETSC_TRUE, &closureSize, &closure));
1588: PetscCheck(closureSize == P4EST_INSUL, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Cell with wrong closure size");
1589: for (c = 0; c < P8EST_EDGES; c++) {
1590: PetscInt cellEdge = closure[2 * (c + edgeOff)];
1592: PetscCheck(cellEdge >= eStart && cellEdge < eEnd, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Non-standard closure: edges");
1593: if (cellEdge == e) PetscCall(PetscSectionAddDof(ett, e, 1));
1594: }
1595: PetscCall(DMPlexRestoreTransitiveClosure(dm, p, PETSC_TRUE, &closureSize, &closure));
1596: }
1597: }
1598: PetscCall(DMPlexRestoreTransitiveClosure(dm, e, PETSC_FALSE, &starSize, &star));
1599: }
1600: PetscCall(PetscSectionSetUp(ett));
1601: PetscCall(PetscSectionGetStorageSize(ett, &ettSize));
1602: PetscCall(P4estTopidxCast(ettSize, &numEtt));
1604: /* This routine allocates space for the arrays, which we fill below */
1605: PetscCallP4estReturn(conn, p8est_connectivity_new, numVerts, numTrees, numEdges, numEtt, numCorns, numCtt);
1606: #else
1607: PetscCallP4estReturn(conn, p4est_connectivity_new, numVerts, numTrees, numCorns, numCtt);
1608: #endif
1610: /* 2: visit every face, determine neighboring cells(trees) */
1611: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 1, &fStart, &fEnd));
1612: PetscCall(PetscMalloc1((cEnd - cStart) * P4EST_FACES, &ttf));
1613: for (f = fStart; f < fEnd; f++) {
1614: PetscInt numSupp, s;
1615: PetscInt myFace[2] = {-1, -1};
1616: PetscInt myOrnt[2] = {PETSC_INT_MIN, PETSC_INT_MIN};
1617: const PetscInt *supp;
1619: PetscCall(DMPlexGetSupportSize(dm, f, &numSupp));
1620: PetscCheck(numSupp == 1 || numSupp == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "point %" PetscInt_FMT " has facet with %" PetscInt_FMT " sides: must be 1 or 2 (boundary or conformal)", f, numSupp);
1621: PetscCall(DMPlexGetSupport(dm, f, &supp));
1623: for (s = 0; s < numSupp; s++) {
1624: PetscInt p = supp[s];
1626: if (p >= cEnd) {
1627: numSupp--;
1628: if (s) supp = &supp[1 - s];
1629: break;
1630: }
1631: }
1632: for (s = 0; s < numSupp; s++) {
1633: PetscInt p = supp[s], i;
1634: PetscInt numCone;
1635: DMPolytopeType ct;
1636: const PetscInt *cone;
1637: const PetscInt *ornt;
1638: PetscInt orient = PETSC_INT_MIN;
1640: PetscCall(DMPlexGetConeSize(dm, p, &numCone));
1641: PetscCheck(numCone == P4EST_FACES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "cell %" PetscInt_FMT " has %" PetscInt_FMT " facets, expect %d", p, numCone, P4EST_FACES);
1642: PetscCall(DMPlexGetCone(dm, p, &cone));
1643: PetscCall(DMPlexGetCellType(dm, cone[0], &ct));
1644: PetscCall(DMPlexGetConeOrientation(dm, p, &ornt));
1645: for (i = 0; i < P4EST_FACES; i++) {
1646: if (cone[i] == f) {
1647: orient = DMPolytopeConvertNewOrientation_Internal(ct, ornt[i]);
1648: break;
1649: }
1650: }
1651: PetscCheck(i < P4EST_FACES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "cell %" PetscInt_FMT " faced %" PetscInt_FMT " mismatch", p, f);
1652: if (p < cStart || p >= cEnd) {
1653: DMPolytopeType ct;
1654: PetscCall(DMPlexGetCellType(dm, p, &ct));
1655: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "cell %" PetscInt_FMT " (%s) should be in [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, DMPolytopeTypes[ct], cStart, cEnd);
1656: }
1657: ttf[P4EST_FACES * (p - cStart) + PetscFaceToP4estFace[i]] = f - fStart;
1658: if (numSupp == 1) {
1659: /* boundary faces indicated by self reference */
1660: conn->tree_to_tree[P4EST_FACES * (p - cStart) + PetscFaceToP4estFace[i]] = p - cStart;
1661: conn->tree_to_face[P4EST_FACES * (p - cStart) + PetscFaceToP4estFace[i]] = (int8_t)PetscFaceToP4estFace[i];
1662: } else {
1663: const PetscInt N = P4EST_CHILDREN / 2;
1665: conn->tree_to_tree[P4EST_FACES * (p - cStart) + PetscFaceToP4estFace[i]] = supp[1 - s] - cStart;
1666: myFace[s] = PetscFaceToP4estFace[i];
1667: /* get the orientation of cell p in p4est-type closure to facet f, by composing the p4est-closure to
1668: * petsc-closure permutation and the petsc-closure to facet orientation */
1669: myOrnt[s] = DihedralCompose(N, orient, DMPolytopeConvertNewOrientation_Internal(ct, P4estFaceToPetscOrnt[myFace[s]]));
1670: }
1671: }
1672: if (numSupp == 2) {
1673: for (s = 0; s < numSupp; s++) {
1674: PetscInt p = supp[s];
1675: PetscInt orntAtoB;
1676: PetscInt p4estOrient;
1677: const PetscInt N = P4EST_CHILDREN / 2;
1679: /* composing the forward permutation with the other cell's inverse permutation gives the self-to-neighbor
1680: * permutation of this cell-facet's cone */
1681: orntAtoB = DihedralCompose(N, DihedralInvert(N, myOrnt[1 - s]), myOrnt[s]);
1683: /* convert cone-description permutation (i.e., edges around facet) to cap-description permutation (i.e.,
1684: * vertices around facet) */
1685: #if !defined(P4_TO_P8)
1686: p4estOrient = orntAtoB < 0 ? -(orntAtoB + 1) : orntAtoB;
1687: #else
1688: {
1689: PetscInt firstVert = orntAtoB < 0 ? ((-orntAtoB) % N) : orntAtoB;
1690: PetscInt p4estFirstVert = firstVert < 2 ? firstVert : (firstVert ^ 1);
1692: /* swap bits */
1693: p4estOrient = ((myFace[s] <= myFace[1 - s]) || (orntAtoB < 0)) ? p4estFirstVert : ((p4estFirstVert >> 1) | ((p4estFirstVert & 1) << 1));
1694: }
1695: #endif
1696: /* encode neighbor face and orientation in tree_to_face per p4est_connectivity standard (see
1697: * p4est_connectivity.h, p8est_connectivity.h) */
1698: conn->tree_to_face[P4EST_FACES * (p - cStart) + myFace[s]] = (int8_t)(myFace[1 - s] + p4estOrient * P4EST_FACES);
1699: }
1700: }
1701: }
1703: #if defined(P4_TO_P8)
1704: /* 3: visit every edge */
1705: conn->ett_offset[0] = 0;
1706: for (e = eStart; e < eEnd; e++) {
1707: PetscInt off, s;
1709: PetscCall(PetscSectionGetOffset(ett, e, &off));
1710: conn->ett_offset[e - eStart] = (p4est_topidx_t)off;
1711: PetscCall(DMPlexGetTransitiveClosure(dm, e, PETSC_FALSE, &starSize, &star));
1712: for (s = 0; s < starSize; s++) {
1713: PetscInt p = star[2 * s];
1715: if (p >= cStart && p < cEnd) {
1716: PetscCall(DMPlexGetTransitiveClosure(dm, p, PETSC_TRUE, &closureSize, &closure));
1717: PetscCheck(closureSize == P4EST_INSUL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Non-standard closure");
1718: for (c = 0; c < P8EST_EDGES; c++) {
1719: PetscInt cellEdge = closure[2 * (c + edgeOff)];
1720: PetscInt cellOrnt = closure[2 * (c + edgeOff) + 1];
1721: DMPolytopeType ct;
1723: PetscCall(DMPlexGetCellType(dm, cellEdge, &ct));
1724: cellOrnt = DMPolytopeConvertNewOrientation_Internal(ct, cellOrnt);
1725: if (cellEdge == e) {
1726: PetscInt p4estEdge = PetscEdgeToP4estEdge[c];
1727: PetscInt totalOrient;
1729: /* compose p4est-closure to petsc-closure permutation and petsc-closure to edge orientation */
1730: totalOrient = DihedralCompose(2, cellOrnt, DMPolytopeConvertNewOrientation_Internal(DM_POLYTOPE_SEGMENT, P4estEdgeToPetscOrnt[p4estEdge]));
1731: /* p4est orientations are positive: -2 => 1, -1 => 0 */
1732: totalOrient = (totalOrient < 0) ? -(totalOrient + 1) : totalOrient;
1733: conn->edge_to_tree[off] = (p4est_locidx_t)(p - cStart);
1734: /* encode cell-edge and orientation in edge_to_edge per p8est_connectivity standard (see
1735: * p8est_connectivity.h) */
1736: conn->edge_to_edge[off++] = (int8_t)(p4estEdge + P8EST_EDGES * totalOrient);
1737: conn->tree_to_edge[P8EST_EDGES * (p - cStart) + p4estEdge] = e - eStart;
1738: }
1739: }
1740: PetscCall(DMPlexRestoreTransitiveClosure(dm, p, PETSC_TRUE, &closureSize, &closure));
1741: }
1742: }
1743: PetscCall(DMPlexRestoreTransitiveClosure(dm, e, PETSC_FALSE, &starSize, &star));
1744: }
1745: PetscCall(PetscSectionDestroy(&ett));
1746: #endif
1748: /* 4: visit every vertex */
1749: conn->ctt_offset[0] = 0;
1750: for (v = vStart; v < vEnd; v++) {
1751: PetscInt off, s;
1753: PetscCall(PetscSectionGetOffset(ctt, v, &off));
1754: conn->ctt_offset[v - vStart] = (p4est_topidx_t)off;
1755: PetscCall(DMPlexGetTransitiveClosure(dm, v, PETSC_FALSE, &starSize, &star));
1756: for (s = 0; s < starSize; s++) {
1757: PetscInt p = star[2 * s];
1759: if (p >= cStart && p < cEnd) {
1760: PetscCall(DMPlexGetTransitiveClosure(dm, p, PETSC_TRUE, &closureSize, &closure));
1761: PetscCheck(closureSize == P4EST_INSUL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Non-standard closure");
1762: for (c = 0; c < P4EST_CHILDREN; c++) {
1763: PetscInt cellVert = closure[2 * (c + vertOff)];
1765: if (cellVert == v) {
1766: PetscInt p4estVert = PetscVertToP4estVert[c];
1768: conn->corner_to_tree[off] = (p4est_locidx_t)(p - cStart);
1769: conn->corner_to_corner[off++] = (int8_t)p4estVert;
1770: conn->tree_to_corner[P4EST_CHILDREN * (p - cStart) + p4estVert] = v - vStart;
1771: }
1772: }
1773: PetscCall(DMPlexRestoreTransitiveClosure(dm, p, PETSC_TRUE, &closureSize, &closure));
1774: }
1775: }
1776: PetscCall(DMPlexRestoreTransitiveClosure(dm, v, PETSC_FALSE, &starSize, &star));
1777: }
1778: PetscCall(PetscSectionDestroy(&ctt));
1780: /* 5: Compute the coordinates */
1781: {
1782: PetscInt coordDim;
1784: PetscCall(DMGetCoordinateDim(dm, &coordDim));
1785: PetscCall(DMGetCoordinatesLocalSetUp(dm));
1786: for (c = cStart; c < cEnd; c++) {
1787: PetscInt dof;
1788: PetscBool isDG;
1789: PetscScalar *cellCoords = NULL;
1790: const PetscScalar *array;
1792: PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &dof, &array, &cellCoords));
1793: PetscCheck(dof == P4EST_CHILDREN * coordDim, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Need coordinates at the corners: (dof) %" PetscInt_FMT " != %d * %" PetscInt_FMT " (sdim)", dof, P4EST_CHILDREN, coordDim);
1794: for (v = 0; v < P4EST_CHILDREN; v++) {
1795: PetscInt i, lim = PetscMin(3, coordDim);
1796: PetscInt p4estVert = PetscVertToP4estVert[v];
1798: conn->tree_to_vertex[P4EST_CHILDREN * (c - cStart) + v] = P4EST_CHILDREN * (c - cStart) + v;
1799: /* p4est vertices are always embedded in R^3 */
1800: for (i = 0; i < 3; i++) conn->vertices[3 * (P4EST_CHILDREN * (c - cStart) + p4estVert) + i] = 0.;
1801: for (i = 0; i < lim; i++) conn->vertices[3 * (P4EST_CHILDREN * (c - cStart) + p4estVert) + i] = PetscRealPart(cellCoords[v * coordDim + i]);
1802: }
1803: PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &dof, &array, &cellCoords));
1804: }
1805: }
1807: #if defined(P4EST_ENABLE_DEBUG)
1808: PetscCheck(p4est_connectivity_is_valid(conn), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Plex to p4est conversion failed");
1809: #endif
1811: *connOut = conn;
1813: *tree_face_to_uniq = ttf;
1814: PetscFunctionReturn(PETSC_SUCCESS);
1815: }
1817: static PetscErrorCode locidx_to_PetscInt(sc_array_t *array)
1818: {
1819: sc_array_t *newarray;
1820: size_t zz, count = array->elem_count;
1822: PetscFunctionBegin;
1823: PetscCheck(array->elem_size == sizeof(p4est_locidx_t), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Wrong locidx size");
1825: if (sizeof(p4est_locidx_t) == sizeof(PetscInt)) PetscFunctionReturn(PETSC_SUCCESS);
1827: newarray = sc_array_new_size(sizeof(PetscInt), array->elem_count);
1828: for (zz = 0; zz < count; zz++) {
1829: p4est_locidx_t il = *((p4est_locidx_t *)sc_array_index(array, zz));
1830: PetscInt *ip = (PetscInt *)sc_array_index(newarray, zz);
1832: *ip = (PetscInt)il;
1833: }
1835: sc_array_reset(array);
1836: sc_array_init_size(array, sizeof(PetscInt), count);
1837: sc_array_copy(array, newarray);
1838: sc_array_destroy(newarray);
1839: PetscFunctionReturn(PETSC_SUCCESS);
1840: }
1842: static PetscErrorCode coords_double_to_PetscScalar(sc_array_t *array, PetscInt dim)
1843: {
1844: sc_array_t *newarray;
1845: size_t zz, count = array->elem_count;
1847: PetscFunctionBegin;
1848: PetscCheck(array->elem_size == 3 * sizeof(double), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Wrong coordinate size");
1849: #if !PetscDefined(USE_COMPLEX)
1850: if (sizeof(double) == sizeof(PetscScalar) && dim == 3) PetscFunctionReturn(PETSC_SUCCESS);
1851: #endif
1853: newarray = sc_array_new_size(dim * sizeof(PetscScalar), array->elem_count);
1854: for (zz = 0; zz < count; zz++) {
1855: int i;
1856: double *id = (double *)sc_array_index(array, zz);
1857: PetscScalar *ip = (PetscScalar *)sc_array_index(newarray, zz);
1859: for (i = 0; i < dim; i++) ip[i] = 0.;
1860: for (i = 0; i < PetscMin(dim, 3); i++) ip[i] = (PetscScalar)id[i];
1861: }
1863: sc_array_reset(array);
1864: sc_array_init_size(array, dim * sizeof(PetscScalar), count);
1865: sc_array_copy(array, newarray);
1866: sc_array_destroy(newarray);
1867: PetscFunctionReturn(PETSC_SUCCESS);
1868: }
1870: static PetscErrorCode locidx_pair_to_PetscSFNode(sc_array_t *array)
1871: {
1872: sc_array_t *newarray;
1873: size_t zz, count = array->elem_count;
1875: PetscFunctionBegin;
1876: PetscCheck(array->elem_size == 2 * sizeof(p4est_locidx_t), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Wrong locidx size");
1878: newarray = sc_array_new_size(sizeof(PetscSFNode), array->elem_count);
1879: for (zz = 0; zz < count; zz++) {
1880: p4est_locidx_t *il = (p4est_locidx_t *)sc_array_index(array, zz);
1881: PetscSFNode *ip = (PetscSFNode *)sc_array_index(newarray, zz);
1883: ip->rank = (PetscInt)il[0];
1884: ip->index = (PetscInt)il[1];
1885: }
1887: sc_array_reset(array);
1888: sc_array_init_size(array, sizeof(PetscSFNode), count);
1889: sc_array_copy(array, newarray);
1890: sc_array_destroy(newarray);
1891: PetscFunctionReturn(PETSC_SUCCESS);
1892: }
1894: static PetscErrorCode P4estToPlex_Local(p4est_t *p4est, DM *plex)
1895: {
1896: PetscFunctionBegin;
1897: {
1898: sc_array_t *points_per_dim = sc_array_new(sizeof(p4est_locidx_t));
1899: sc_array_t *cone_sizes = sc_array_new(sizeof(p4est_locidx_t));
1900: sc_array_t *cones = sc_array_new(sizeof(p4est_locidx_t));
1901: sc_array_t *cone_orientations = sc_array_new(sizeof(p4est_locidx_t));
1902: sc_array_t *coords = sc_array_new(3 * sizeof(double));
1903: sc_array_t *children = sc_array_new(sizeof(p4est_locidx_t));
1904: sc_array_t *parents = sc_array_new(sizeof(p4est_locidx_t));
1905: sc_array_t *childids = sc_array_new(sizeof(p4est_locidx_t));
1906: sc_array_t *leaves = sc_array_new(sizeof(p4est_locidx_t));
1907: sc_array_t *remotes = sc_array_new(2 * sizeof(p4est_locidx_t));
1908: p4est_locidx_t first_local_quad;
1910: PetscCallP4est(p4est_get_plex_data, p4est, P4EST_CONNECT_FULL, 0, &first_local_quad, points_per_dim, cone_sizes, cones, cone_orientations, coords, children, parents, childids, leaves, remotes);
1912: PetscCall(locidx_to_PetscInt(points_per_dim));
1913: PetscCall(locidx_to_PetscInt(cone_sizes));
1914: PetscCall(locidx_to_PetscInt(cones));
1915: PetscCall(locidx_to_PetscInt(cone_orientations));
1916: PetscCall(coords_double_to_PetscScalar(coords, P4EST_DIM));
1918: PetscCall(DMPlexCreate(PETSC_COMM_SELF, plex));
1919: PetscCall(DMSetDimension(*plex, P4EST_DIM));
1920: PetscCall(DMPlexCreateFromDAG(*plex, P4EST_DIM, (PetscInt *)points_per_dim->array, (PetscInt *)cone_sizes->array, (PetscInt *)cones->array, (PetscInt *)cone_orientations->array, (PetscScalar *)coords->array));
1921: PetscCall(DMPlexConvertOldOrientations_Internal(*plex));
1922: sc_array_destroy(points_per_dim);
1923: sc_array_destroy(cone_sizes);
1924: sc_array_destroy(cones);
1925: sc_array_destroy(cone_orientations);
1926: sc_array_destroy(coords);
1927: sc_array_destroy(children);
1928: sc_array_destroy(parents);
1929: sc_array_destroy(childids);
1930: sc_array_destroy(leaves);
1931: sc_array_destroy(remotes);
1932: }
1933: PetscFunctionReturn(PETSC_SUCCESS);
1934: }
1936: #define DMReferenceTreeGetChildSymmetry_pforest _append_pforest(DMReferenceTreeGetChildSymmetry)
1937: static PetscErrorCode DMReferenceTreeGetChildSymmetry_pforest(DM dm, PetscInt parent, PetscInt parentOrientA, PetscInt childOrientA, PetscInt childA, PetscInt parentOrientB, PetscInt *childOrientB, PetscInt *childB)
1938: {
1939: PetscInt coneSize, dStart, dEnd, vStart, vEnd, dim, ABswap, oAvert, oBvert, ABswapVert;
1941: PetscFunctionBegin;
1942: if (parentOrientA == parentOrientB) {
1943: if (childOrientB) *childOrientB = childOrientA;
1944: if (childB) *childB = childA;
1945: PetscFunctionReturn(PETSC_SUCCESS);
1946: }
1947: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
1948: if (childA >= vStart && childA < vEnd) { /* vertices (always in the middle) are invariant under rotation */
1949: if (childOrientB) *childOrientB = 0;
1950: if (childB) *childB = childA;
1951: PetscFunctionReturn(PETSC_SUCCESS);
1952: }
1953: for (dim = 0; dim < 3; dim++) {
1954: PetscCall(DMPlexGetDepthStratum(dm, dim, &dStart, &dEnd));
1955: if (parent >= dStart && parent <= dEnd) break;
1956: }
1957: PetscCheck(dim <= 2, PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot perform child symmetry for %" PetscInt_FMT "-cells", dim);
1958: PetscCheck(dim, PETSC_COMM_SELF, PETSC_ERR_PLIB, "A vertex has no children");
1959: if (childA < dStart || childA >= dEnd) { /* a 1-cell in a 2-cell */
1960: /* this is a lower-dimensional child: bootstrap */
1961: PetscInt size, i, sA = -1, sB, sOrientB, sConeSize;
1962: const PetscInt *supp, *coneA, *coneB, *oA, *oB;
1964: PetscCall(DMPlexGetSupportSize(dm, childA, &size));
1965: PetscCall(DMPlexGetSupport(dm, childA, &supp));
1967: /* find a point sA in supp(childA) that has the same parent */
1968: for (i = 0; i < size; i++) {
1969: PetscInt sParent;
1971: sA = supp[i];
1972: if (sA == parent) continue;
1973: PetscCall(DMPlexGetTreeParent(dm, sA, &sParent, NULL));
1974: if (sParent == parent) break;
1975: }
1976: PetscCheck(i != size, PETSC_COMM_SELF, PETSC_ERR_PLIB, "could not find support in children");
1977: /* find out which point sB is in an equivalent position to sA under
1978: * parentOrientB */
1979: PetscCall(DMReferenceTreeGetChildSymmetry_pforest(dm, parent, parentOrientA, 0, sA, parentOrientB, &sOrientB, &sB));
1980: PetscCall(DMPlexGetConeSize(dm, sA, &sConeSize));
1981: PetscCall(DMPlexGetCone(dm, sA, &coneA));
1982: PetscCall(DMPlexGetCone(dm, sB, &coneB));
1983: PetscCall(DMPlexGetConeOrientation(dm, sA, &oA));
1984: PetscCall(DMPlexGetConeOrientation(dm, sB, &oB));
1985: /* step through the cone of sA in natural order */
1986: for (i = 0; i < sConeSize; i++) {
1987: if (coneA[i] == childA) {
1988: /* if childA is at position i in coneA,
1989: * then we want the point that is at sOrientB*i in coneB */
1990: PetscInt j = (sOrientB >= 0) ? ((sOrientB + i) % sConeSize) : ((sConeSize - (sOrientB + 1) - i) % sConeSize);
1991: if (childB) *childB = coneB[j];
1992: if (childOrientB) {
1993: DMPolytopeType ct;
1994: PetscInt oBtrue;
1996: PetscCall(DMPlexGetConeSize(dm, childA, &coneSize));
1997: /* compose sOrientB and oB[j] */
1998: PetscCheck(coneSize == 0 || coneSize == 2, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Expected a vertex or an edge");
1999: ct = coneSize ? DM_POLYTOPE_SEGMENT : DM_POLYTOPE_POINT;
2000: /* we may have to flip an edge */
2001: oBtrue = (sOrientB >= 0) ? oB[j] : DMPolytopeTypeComposeOrientationInv(ct, -1, oB[j]);
2002: oBtrue = DMPolytopeConvertNewOrientation_Internal(ct, oBtrue);
2003: ABswap = DihedralSwap(coneSize, DMPolytopeConvertNewOrientation_Internal(ct, oA[i]), oBtrue);
2004: *childOrientB = DihedralCompose(coneSize, childOrientA, ABswap);
2005: }
2006: break;
2007: }
2008: }
2009: PetscCheck(i != sConeSize, PETSC_COMM_SELF, PETSC_ERR_PLIB, "support cone mismatch");
2010: PetscFunctionReturn(PETSC_SUCCESS);
2011: }
2012: /* get the cone size and symmetry swap */
2013: PetscCall(DMPlexGetConeSize(dm, parent, &coneSize));
2014: ABswap = DihedralSwap(coneSize, parentOrientA, parentOrientB);
2015: if (dim == 2) {
2016: /* orientations refer to cones: we want them to refer to vertices:
2017: * if it's a rotation, they are the same, but if the order is reversed, a
2018: * permutation that puts side i first does *not* put vertex i first */
2019: oAvert = (parentOrientA >= 0) ? parentOrientA : -((-parentOrientA % coneSize) + 1);
2020: oBvert = (parentOrientB >= 0) ? parentOrientB : -((-parentOrientB % coneSize) + 1);
2021: ABswapVert = DihedralSwap(coneSize, oAvert, oBvert);
2022: } else {
2023: oAvert = parentOrientA;
2024: oBvert = parentOrientB;
2025: ABswapVert = ABswap;
2026: }
2027: if (childB) {
2028: /* assume that each child corresponds to a vertex, in the same order */
2029: PetscInt p, posA = -1, numChildren, i;
2030: const PetscInt *children;
2032: /* count which position the child is in */
2033: PetscCall(DMPlexGetTreeChildren(dm, parent, &numChildren, &children));
2034: for (i = 0; i < numChildren; i++) {
2035: p = children[i];
2036: if (p == childA) {
2037: if (dim == 1) {
2038: posA = i;
2039: } else { /* 2D Morton to rotation */
2040: posA = (i & 2) ? (i ^ 1) : i;
2041: }
2042: break;
2043: }
2044: }
2045: if (posA >= coneSize) {
2046: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Could not find childA in children of parent");
2047: } else {
2048: /* figure out position B by applying ABswapVert */
2049: PetscInt posB, childIdB;
2051: posB = (ABswapVert >= 0) ? ((ABswapVert + posA) % coneSize) : ((coneSize - (ABswapVert + 1) - posA) % coneSize);
2052: if (dim == 1) {
2053: childIdB = posB;
2054: } else { /* 2D rotation to Morton */
2055: childIdB = (posB & 2) ? (posB ^ 1) : posB;
2056: }
2057: if (childB) *childB = children[childIdB];
2058: }
2059: }
2060: if (childOrientB) *childOrientB = DihedralCompose(coneSize, childOrientA, ABswap);
2061: PetscFunctionReturn(PETSC_SUCCESS);
2062: }
2064: #define DMCreateReferenceTree_pforest _append_pforest(DMCreateReferenceTree)
2065: static PetscErrorCode DMCreateReferenceTree_pforest(MPI_Comm comm, DM *dm)
2066: {
2067: p4est_connectivity_t *refcube;
2068: p4est_t *root, *refined;
2069: DM dmRoot, dmRefined;
2070: DM_Plex *mesh;
2071: PetscMPIInt rank;
2072: #if PetscDefined(HAVE_MPIUNI)
2073: sc_MPI_Comm comm_self = sc_MPI_COMM_SELF;
2074: #else
2075: MPI_Comm comm_self = PETSC_COMM_SELF;
2076: #endif
2078: PetscFunctionBegin;
2079: PetscCallP4estReturn(refcube, p4est_connectivity_new_byname, "unit");
2080: { /* [-1,1]^d geometry */
2081: PetscInt i, j;
2083: for (i = 0; i < P4EST_CHILDREN; i++) {
2084: for (j = 0; j < 3; j++) {
2085: refcube->vertices[3 * i + j] *= 2.;
2086: refcube->vertices[3 * i + j] -= 1.;
2087: }
2088: }
2089: }
2090: PetscCallP4estReturn(root, p4est_new, comm_self, refcube, 0, NULL, NULL);
2091: PetscCallP4estReturn(refined, p4est_new_ext, comm_self, refcube, 0, 1, 1, 0, NULL, NULL);
2092: PetscCall(P4estToPlex_Local(root, &dmRoot));
2093: PetscCall(P4estToPlex_Local(refined, &dmRefined));
2094: {
2095: #if !defined(P4_TO_P8)
2096: PetscInt nPoints = 25;
2097: PetscInt perm[25] = {0, 1, 2, 3, 4, 12, 8, 14, 6, 9, 15, 5, 13, 10, 7, 11, 16, 22, 20, 24, 17, 21, 18, 23, 19};
2098: PetscInt ident[25] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 0, 0, 0, 0, 5, 6, 7, 8, 1, 2, 3, 4, 0};
2099: #else
2100: PetscInt nPoints = 125;
2101: PetscInt perm[125] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 32, 16, 36, 24, 40, 12, 17, 37, 25, 41, 9, 33, 20, 26, 42, 13, 21, 27, 43, 10, 34, 18, 38, 28, 14, 19, 39, 29, 11, 35, 22, 30, 15,
2102: 23, 31, 44, 84, 76, 92, 52, 86, 68, 94, 60, 78, 70, 96, 45, 85, 77, 93, 54, 72, 62, 74, 46, 80, 53, 87, 69, 95, 64, 82, 47, 81, 55, 73, 66, 48, 88, 56, 90, 61, 79, 71,
2103: 97, 49, 89, 58, 63, 75, 50, 57, 91, 65, 83, 51, 59, 67, 98, 106, 110, 122, 114, 120, 118, 124, 99, 111, 115, 119, 100, 107, 116, 121, 101, 117, 102, 108, 112, 123, 103, 113, 104, 109, 105};
2104: PetscInt ident[125] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16,
2105: 16, 17, 17, 18, 18, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 19, 20, 21, 22, 23, 24, 25, 26, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 1, 2, 3, 4, 5, 6, 0};
2107: #endif
2108: IS permIS;
2109: DM dmPerm;
2111: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, nPoints, perm, PETSC_USE_POINTER, &permIS));
2112: PetscCall(DMPlexPermute(dmRefined, permIS, &dmPerm));
2113: if (dmPerm) {
2114: PetscCall(DMDestroy(&dmRefined));
2115: dmRefined = dmPerm;
2116: }
2117: PetscCall(ISDestroy(&permIS));
2118: {
2119: PetscInt p;
2120: PetscCall(DMCreateLabel(dmRoot, "identity"));
2121: PetscCall(DMCreateLabel(dmRefined, "identity"));
2122: for (p = 0; p < P4EST_INSUL; p++) PetscCall(DMSetLabelValue(dmRoot, "identity", p, p));
2123: for (p = 0; p < nPoints; p++) PetscCall(DMSetLabelValue(dmRefined, "identity", p, ident[p]));
2124: }
2125: }
2126: PetscCall(DMPlexCreateReferenceTree_Union(dmRoot, dmRefined, "identity", dm));
2127: mesh = (DM_Plex *)(*dm)->data;
2128: mesh->getchildsymmetry = DMReferenceTreeGetChildSymmetry_pforest;
2129: PetscCallMPI(MPI_Comm_rank(comm, &rank));
2130: if (rank == 0) {
2131: PetscCall(DMViewFromOptions(dmRoot, NULL, "-dm_p4est_ref_root_view"));
2132: PetscCall(DMViewFromOptions(dmRefined, NULL, "-dm_p4est_ref_refined_view"));
2133: PetscCall(DMViewFromOptions(dmRefined, NULL, "-dm_p4est_ref_tree_view"));
2134: }
2135: PetscCall(DMDestroy(&dmRefined));
2136: PetscCall(DMDestroy(&dmRoot));
2137: PetscCallP4est(p4est_destroy, refined);
2138: PetscCallP4est(p4est_destroy, root);
2139: PetscCallP4est(p4est_connectivity_destroy, refcube);
2140: PetscFunctionReturn(PETSC_SUCCESS);
2141: }
2143: static PetscErrorCode DMShareDiscretization(DM dmA, DM dmB)
2144: {
2145: void *ctx;
2146: PetscInt num;
2147: PetscReal val;
2149: PetscFunctionBegin;
2150: PetscCall(DMGetApplicationContext(dmA, &ctx));
2151: PetscCall(DMSetApplicationContext(dmB, ctx));
2152: PetscCall(DMCopyDisc(dmA, dmB));
2153: PetscCall(DMGetOutputSequenceNumber(dmA, &num, &val));
2154: PetscCall(DMSetOutputSequenceNumber(dmB, num, val));
2155: if (dmB->localSection != dmA->localSection || dmB->globalSection != dmA->globalSection) {
2156: PetscCall(DMClearLocalVectors(dmB));
2157: PetscCall(PetscObjectReference((PetscObject)dmA->localSection));
2158: PetscCall(PetscSectionDestroy(&dmB->localSection));
2159: dmB->localSection = dmA->localSection;
2160: PetscCall(DMClearGlobalVectors(dmB));
2161: PetscCall(PetscObjectReference((PetscObject)dmA->globalSection));
2162: PetscCall(PetscSectionDestroy(&dmB->globalSection));
2163: dmB->globalSection = dmA->globalSection;
2164: PetscCall(PetscObjectReference((PetscObject)dmA->defaultConstraint.section));
2165: PetscCall(PetscSectionDestroy(&dmB->defaultConstraint.section));
2166: dmB->defaultConstraint.section = dmA->defaultConstraint.section;
2167: PetscCall(PetscObjectReference((PetscObject)dmA->defaultConstraint.mat));
2168: PetscCall(MatDestroy(&dmB->defaultConstraint.mat));
2169: dmB->defaultConstraint.mat = dmA->defaultConstraint.mat;
2170: if (dmA->map) PetscCall(PetscLayoutReference(dmA->map, &dmB->map));
2171: /* The sections are assigned directly here, so replicate the invalidation DMSetLocalSection() and
2172: DMSetGlobalSection() do: a section-derived mapping was built from the sections being replaced */
2173: if (dmB->ltogmapFromSection) PetscCall(ISLocalToGlobalMappingDestroy(&dmB->ltogmap));
2174: }
2175: if (dmB->sectionSF != dmA->sectionSF) {
2176: PetscCall(PetscObjectReference((PetscObject)dmA->sectionSF));
2177: PetscCall(PetscSFDestroy(&dmB->sectionSF));
2178: dmB->sectionSF = dmA->sectionSF;
2179: }
2180: PetscFunctionReturn(PETSC_SUCCESS);
2181: }
2183: /* Get an SF that broadcasts a coarse-cell covering of the local fine cells */
2184: static PetscErrorCode DMPforestGetCellCoveringSF(MPI_Comm comm, p4est_t *p4estC, p4est_t *p4estF, PetscInt cStart, PetscInt cEnd, PetscSF *coveringSF)
2185: {
2186: PetscInt startF, endF, startC, endC, p, nLeaves;
2187: PetscSFNode *leaves;
2188: PetscSF sf;
2189: PetscInt *recv, *send;
2190: PetscMPIInt tag;
2191: MPI_Request *recvReqs, *sendReqs;
2192: PetscSection section;
2194: PetscFunctionBegin;
2195: PetscCall(DMPforestComputeOverlappingRanks(p4estC->mpisize, p4estC->mpirank, p4estF, p4estC, &startC, &endC));
2196: PetscCall(PetscMalloc2(2 * (endC - startC), &recv, endC - startC, &recvReqs));
2197: PetscCall(PetscCommGetNewTag(comm, &tag));
2198: for (p = startC; p < endC; p++) {
2199: recvReqs[p - startC] = MPI_REQUEST_NULL; /* just in case we don't initiate a receive */
2200: if (p4estC->global_first_quadrant[p] == p4estC->global_first_quadrant[p + 1]) { /* empty coarse partition */
2201: recv[2 * (p - startC)] = 0;
2202: recv[2 * (p - startC) + 1] = 0;
2203: continue;
2204: }
2206: PetscCallMPI(MPIU_Irecv(&recv[2 * (p - startC)], 2, MPIU_INT, p, tag, comm, &recvReqs[p - startC]));
2207: }
2208: PetscCall(DMPforestComputeOverlappingRanks(p4estC->mpisize, p4estC->mpirank, p4estC, p4estF, &startF, &endF));
2209: PetscCall(PetscMalloc2(2 * (endF - startF), &send, endF - startF, &sendReqs));
2210: /* count the quadrants rank will send to each of [startF,endF) */
2211: for (p = startF; p < endF; p++) {
2212: p4est_quadrant_t *myFineStart = &p4estF->global_first_position[p];
2213: p4est_quadrant_t *myFineEnd = &p4estF->global_first_position[p + 1];
2214: PetscInt tStart = (PetscInt)myFineStart->p.which_tree;
2215: PetscInt tEnd = (PetscInt)myFineEnd->p.which_tree;
2216: PetscInt firstCell = -1, lastCell = -1;
2217: p4est_tree_t *treeStart = &(((p4est_tree_t *)p4estC->trees->array)[tStart]);
2218: p4est_tree_t *treeEnd = (size_t)tEnd < p4estC->trees->elem_count ? &(((p4est_tree_t *)p4estC->trees->array)[tEnd]) : NULL;
2219: ssize_t overlapIndex;
2221: sendReqs[p - startF] = MPI_REQUEST_NULL; /* just in case we don't initiate a send */
2222: if (p4estF->global_first_quadrant[p] == p4estF->global_first_quadrant[p + 1]) continue;
2224: /* locate myFineStart in (or before) a cell */
2225: if (treeStart->quadrants.elem_count) {
2226: PetscCallP4estReturn(overlapIndex, sc_array_bsearch, &treeStart->quadrants, myFineStart, p4est_quadrant_disjoint);
2227: if (overlapIndex < 0) {
2228: firstCell = 0;
2229: } else {
2230: firstCell = (PetscInt)(treeStart->quadrants_offset + overlapIndex);
2231: }
2232: } else {
2233: firstCell = 0;
2234: }
2235: if (treeEnd && treeEnd->quadrants.elem_count) {
2236: PetscCallP4estReturn(overlapIndex, sc_array_bsearch, &treeEnd->quadrants, myFineEnd, p4est_quadrant_disjoint);
2237: if (overlapIndex < 0) { /* all of this local section is overlapped */
2238: lastCell = p4estC->local_num_quadrants;
2239: } else {
2240: p4est_quadrant_t *container = &(((p4est_quadrant_t *)treeEnd->quadrants.array)[overlapIndex]);
2241: p4est_quadrant_t first_desc;
2242: int equal;
2244: PetscCallP4est(p4est_quadrant_first_descendant, container, &first_desc, P4EST_QMAXLEVEL);
2245: PetscCallP4estReturn(equal, p4est_quadrant_is_equal, myFineEnd, &first_desc);
2246: if (equal) {
2247: lastCell = (PetscInt)(treeEnd->quadrants_offset + overlapIndex);
2248: } else {
2249: lastCell = (PetscInt)(treeEnd->quadrants_offset + overlapIndex + 1);
2250: }
2251: }
2252: } else {
2253: lastCell = p4estC->local_num_quadrants;
2254: }
2255: send[2 * (p - startF)] = firstCell;
2256: send[2 * (p - startF) + 1] = lastCell - firstCell;
2257: PetscCallMPI(MPIU_Isend(&send[2 * (p - startF)], 2, MPIU_INT, p, tag, comm, &sendReqs[p - startF]));
2258: }
2259: PetscCallMPI(MPI_Waitall((PetscMPIInt)(endC - startC), recvReqs, MPI_STATUSES_IGNORE));
2260: PetscCall(PetscSectionCreate(PETSC_COMM_SELF, §ion));
2261: PetscCall(PetscSectionSetChart(section, startC, endC));
2262: for (p = startC; p < endC; p++) {
2263: PetscInt numCells = recv[2 * (p - startC) + 1];
2264: PetscCall(PetscSectionSetDof(section, p, numCells));
2265: }
2266: PetscCall(PetscSectionSetUp(section));
2267: PetscCall(PetscSectionGetStorageSize(section, &nLeaves));
2268: PetscCall(PetscMalloc1(nLeaves, &leaves));
2269: for (p = startC; p < endC; p++) {
2270: PetscInt firstCell = recv[2 * (p - startC)];
2271: PetscInt numCells = recv[2 * (p - startC) + 1];
2272: PetscInt off, i;
2274: PetscCall(PetscSectionGetOffset(section, p, &off));
2275: for (i = 0; i < numCells; i++) {
2276: leaves[off + i].rank = p;
2277: leaves[off + i].index = firstCell + i;
2278: }
2279: }
2280: PetscCall(PetscSFCreate(comm, &sf));
2281: PetscCall(PetscSFSetGraph(sf, cEnd - cStart, nLeaves, NULL, PETSC_OWN_POINTER, leaves, PETSC_OWN_POINTER));
2282: PetscCall(PetscSectionDestroy(§ion));
2283: PetscCallMPI(MPI_Waitall((PetscMPIInt)(endF - startF), sendReqs, MPI_STATUSES_IGNORE));
2284: PetscCall(PetscFree2(send, sendReqs));
2285: PetscCall(PetscFree2(recv, recvReqs));
2286: *coveringSF = sf;
2287: PetscFunctionReturn(PETSC_SUCCESS);
2288: }
2290: /* closure points for locally-owned cells */
2291: static PetscErrorCode DMPforestGetCellSFNodes(DM dm, PetscInt numClosureIndices, PetscInt *numClosurePoints, PetscSFNode **closurePoints, PetscBool redirect)
2292: {
2293: PetscInt cStart, cEnd;
2294: PetscInt count, c;
2295: PetscMPIInt rank;
2296: PetscInt closureSize = -1;
2297: PetscInt *closure = NULL;
2298: PetscSF pointSF;
2299: PetscInt nleaves, nroots;
2300: const PetscInt *ilocal;
2301: const PetscSFNode *iremote;
2302: DM plex;
2303: DM_Forest *forest;
2304: DM_Forest_pforest *pforest;
2306: PetscFunctionBegin;
2307: forest = (DM_Forest *)dm->data;
2308: pforest = (DM_Forest_pforest *)forest->data;
2309: cStart = pforest->cLocalStart;
2310: cEnd = pforest->cLocalEnd;
2311: PetscCall(DMPforestGetPlex(dm, &plex));
2312: PetscCall(DMGetPointSF(dm, &pointSF));
2313: PetscCall(PetscSFGetGraph(pointSF, &nroots, &nleaves, &ilocal, &iremote));
2314: nleaves = PetscMax(0, nleaves);
2315: nroots = PetscMax(0, nroots);
2316: *numClosurePoints = numClosureIndices * (cEnd - cStart);
2317: PetscCall(PetscMalloc1(*numClosurePoints, closurePoints));
2318: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
2319: for (c = cStart, count = 0; c < cEnd; c++) {
2320: PetscInt i;
2321: PetscCall(DMPlexGetTransitiveClosure(plex, c, PETSC_TRUE, &closureSize, &closure));
2323: for (i = 0; i < numClosureIndices; i++, count++) {
2324: PetscInt p = closure[2 * i];
2325: PetscInt loc = -1;
2327: PetscCall(PetscFindInt(p, nleaves, ilocal, &loc));
2328: if (redirect && loc >= 0) {
2329: (*closurePoints)[count].rank = iremote[loc].rank;
2330: (*closurePoints)[count].index = iremote[loc].index;
2331: } else {
2332: (*closurePoints)[count].rank = rank;
2333: (*closurePoints)[count].index = p;
2334: }
2335: }
2336: PetscCall(DMPlexRestoreTransitiveClosure(plex, c, PETSC_TRUE, &closureSize, &closure));
2337: }
2338: PetscFunctionReturn(PETSC_SUCCESS);
2339: }
2341: static void MPIAPI DMPforestMaxSFNode(void *a, void *b, PetscMPIInt *len, MPI_Datatype *type)
2342: {
2343: PetscMPIInt i;
2345: for (i = 0; i < *len; i++) {
2346: PetscSFNode *A = (PetscSFNode *)a;
2347: PetscSFNode *B = (PetscSFNode *)b;
2349: if (B->rank < 0) *B = *A;
2350: }
2351: }
2353: #if defined(__GNUC__) && !defined(__clang__)
2354: #pragma GCC diagnostic push
2355: #pragma GCC diagnostic ignored "-Wclobbered"
2356: #endif
2357: static PetscErrorCode DMPforestGetTransferSF_Point(DM coarse, DM fine, PetscSF *sf, PetscBool transferIdent, PetscInt *childIds[])
2358: {
2359: MPI_Comm comm;
2360: PetscMPIInt rank, size;
2361: DM_Forest_pforest *pforestC, *pforestF;
2362: p4est_t *p4estC, *p4estF;
2363: PetscInt numClosureIndices;
2364: PetscInt numClosurePointsC, numClosurePointsF;
2365: PetscSFNode *closurePointsC, *closurePointsF;
2366: p4est_quadrant_t *coverQuads = NULL;
2367: p4est_quadrant_t **treeQuads;
2368: PetscInt *treeQuadCounts;
2369: MPI_Datatype nodeType;
2370: MPI_Datatype nodeClosureType;
2371: MPI_Op sfNodeReduce;
2372: p4est_topidx_t fltF, lltF, t;
2373: DM plexC, plexF;
2374: PetscInt pStartF, pEndF, pStartC, pEndC;
2375: PetscBool saveInCoarse = PETSC_FALSE;
2376: PetscBool saveInFine = PETSC_FALSE;
2377: PetscBool formCids = (childIds != NULL) ? PETSC_TRUE : PETSC_FALSE;
2378: PetscInt *cids = NULL;
2380: PetscFunctionBegin;
2381: pforestC = (DM_Forest_pforest *)((DM_Forest *)coarse->data)->data;
2382: pforestF = (DM_Forest_pforest *)((DM_Forest *)fine->data)->data;
2383: p4estC = pforestC->forest;
2384: p4estF = pforestF->forest;
2385: PetscCheck(pforestC->topo == pforestF->topo, PetscObjectComm((PetscObject)coarse), PETSC_ERR_ARG_INCOMP, "DM's must have the same base DM");
2386: comm = PetscObjectComm((PetscObject)coarse);
2387: PetscCallMPI(MPI_Comm_rank(comm, &rank));
2388: PetscCallMPI(MPI_Comm_size(comm, &size));
2389: PetscCall(DMPforestGetPlex(fine, &plexF));
2390: PetscCall(DMPlexGetChart(plexF, &pStartF, &pEndF));
2391: PetscCall(DMPforestGetPlex(coarse, &plexC));
2392: PetscCall(DMPlexGetChart(plexC, &pStartC, &pEndC));
2393: { /* check if the results have been cached */
2394: DM adaptCoarse, adaptFine;
2396: PetscCall(DMForestGetAdaptivityForest(coarse, &adaptCoarse));
2397: PetscCall(DMForestGetAdaptivityForest(fine, &adaptFine));
2398: if (adaptCoarse && adaptCoarse->data == fine->data) { /* coarse is adapted from fine */
2399: if (pforestC->pointSelfToAdaptSF) {
2400: PetscCall(PetscObjectReference((PetscObject)pforestC->pointSelfToAdaptSF));
2401: *sf = pforestC->pointSelfToAdaptSF;
2402: if (childIds) {
2403: PetscCall(PetscMalloc1(pEndF - pStartF, &cids));
2404: PetscCall(PetscArraycpy(cids, pforestC->pointSelfToAdaptCids, pEndF - pStartF));
2405: *childIds = cids;
2406: }
2407: PetscFunctionReturn(PETSC_SUCCESS);
2408: } else {
2409: saveInCoarse = PETSC_TRUE;
2410: formCids = PETSC_TRUE;
2411: }
2412: } else if (adaptFine && adaptFine->data == coarse->data) { /* fine is adapted from coarse */
2413: if (pforestF->pointAdaptToSelfSF) {
2414: PetscCall(PetscObjectReference((PetscObject)pforestF->pointAdaptToSelfSF));
2415: *sf = pforestF->pointAdaptToSelfSF;
2416: if (childIds) {
2417: PetscCall(PetscMalloc1(pEndF - pStartF, &cids));
2418: PetscCall(PetscArraycpy(cids, pforestF->pointAdaptToSelfCids, pEndF - pStartF));
2419: *childIds = cids;
2420: }
2421: PetscFunctionReturn(PETSC_SUCCESS);
2422: } else {
2423: saveInFine = PETSC_TRUE;
2424: formCids = PETSC_TRUE;
2425: }
2426: }
2427: }
2429: /* count the number of closure points that have dofs and create a list */
2430: numClosureIndices = P4EST_INSUL;
2431: /* create the datatype */
2432: PetscCallMPI(MPI_Type_contiguous(2, MPIU_INT, &nodeType));
2433: PetscCallMPI(MPI_Type_commit(&nodeType));
2434: PetscCallMPI(MPI_Op_create(DMPforestMaxSFNode, PETSC_FALSE, &sfNodeReduce));
2435: PetscCallMPI(MPI_Type_contiguous(numClosureIndices * 2, MPIU_INT, &nodeClosureType));
2436: PetscCallMPI(MPI_Type_commit(&nodeClosureType));
2437: /* everything has to go through cells: for each cell, create a list of the sfnodes in its closure */
2438: /* get lists of closure point SF nodes for every cell */
2439: PetscCall(DMPforestGetCellSFNodes(coarse, numClosureIndices, &numClosurePointsC, &closurePointsC, PETSC_TRUE));
2440: PetscCall(DMPforestGetCellSFNodes(fine, numClosureIndices, &numClosurePointsF, &closurePointsF, PETSC_FALSE));
2441: /* create pointers for tree lists */
2442: fltF = p4estF->first_local_tree;
2443: lltF = p4estF->last_local_tree;
2444: PetscCall(PetscCalloc2(lltF + 1 - fltF, &treeQuads, lltF + 1 - fltF, &treeQuadCounts));
2445: /* if the partitions don't match, ship the coarse to cover the fine */
2446: if (size > 1) {
2447: PetscInt p;
2449: for (p = 0; p < size; p++) {
2450: int equal;
2452: PetscCallP4estReturn(equal, p4est_quadrant_is_equal_piggy, &p4estC->global_first_position[p], &p4estF->global_first_position[p]);
2453: if (!equal) break;
2454: }
2455: if (p < size) { /* non-matching distribution: send the coarse to cover the fine */
2456: PetscInt cStartC, cEndC;
2457: PetscSF coveringSF;
2458: PetscInt nleaves;
2459: PetscInt count;
2460: PetscSFNode *newClosurePointsC;
2461: p4est_quadrant_t *coverQuadsSend;
2462: p4est_topidx_t fltC = p4estC->first_local_tree;
2463: p4est_topidx_t lltC = p4estC->last_local_tree;
2464: p4est_topidx_t t;
2465: PetscMPIInt blockSizes[4] = {P4EST_DIM, 2, 1, 1};
2466: MPI_Aint blockOffsets[4] = {offsetof(p4est_quadrant_t, x), offsetof(p4est_quadrant_t, level), offsetof(p4est_quadrant_t, pad16), offsetof(p4est_quadrant_t, p)};
2467: MPI_Datatype blockTypes[4] = {MPI_INT32_T, MPI_INT8_T, MPI_INT16_T, MPI_INT32_T /* p.which_tree */};
2468: MPI_Datatype quadStruct, quadType;
2470: PetscCall(DMPlexGetSimplexOrBoxCells(plexC, 0, &cStartC, &cEndC));
2471: PetscCall(DMPforestGetCellCoveringSF(comm, p4estC, p4estF, pforestC->cLocalStart, pforestC->cLocalEnd, &coveringSF));
2472: PetscCall(PetscSFGetGraph(coveringSF, NULL, &nleaves, NULL, NULL));
2473: PetscCall(PetscMalloc1(numClosureIndices * nleaves, &newClosurePointsC));
2474: PetscCall(PetscMalloc1(nleaves, &coverQuads));
2475: PetscCall(PetscMalloc1(cEndC - cStartC, &coverQuadsSend));
2476: count = 0;
2477: for (t = fltC; t <= lltC; t++) { /* unfortunately, we need to pack a send array, since quads are not stored packed in p4est */
2478: p4est_tree_t *tree = &(((p4est_tree_t *)p4estC->trees->array)[t]);
2479: PetscInt q;
2481: PetscCall(PetscMemcpy(&coverQuadsSend[count], tree->quadrants.array, tree->quadrants.elem_count * sizeof(p4est_quadrant_t)));
2482: for (q = 0; (size_t)q < tree->quadrants.elem_count; q++) coverQuadsSend[count + q].p.which_tree = t;
2483: count += tree->quadrants.elem_count;
2484: }
2485: /* p is of a union type p4est_quadrant_data, but only the p.which_tree field is active at this time. So, we
2486: have a simple blockTypes[] to use. Note that quadStruct does not count potential padding in array of
2487: p4est_quadrant_t. We have to call MPI_Type_create_resized() to change upper-bound of quadStruct.
2488: */
2489: PetscCallMPI(MPI_Type_create_struct(4, blockSizes, blockOffsets, blockTypes, &quadStruct));
2490: PetscCallMPI(MPI_Type_create_resized(quadStruct, 0, sizeof(p4est_quadrant_t), &quadType));
2491: PetscCallMPI(MPI_Type_commit(&quadType));
2492: PetscCall(PetscSFBcastBegin(coveringSF, nodeClosureType, closurePointsC, newClosurePointsC, MPI_REPLACE));
2493: PetscCall(PetscSFBcastBegin(coveringSF, quadType, coverQuadsSend, coverQuads, MPI_REPLACE));
2494: PetscCall(PetscSFBcastEnd(coveringSF, nodeClosureType, closurePointsC, newClosurePointsC, MPI_REPLACE));
2495: PetscCall(PetscSFBcastEnd(coveringSF, quadType, coverQuadsSend, coverQuads, MPI_REPLACE));
2496: PetscCallMPI(MPI_Type_free(&quadStruct));
2497: PetscCallMPI(MPI_Type_free(&quadType));
2498: PetscCall(PetscFree(coverQuadsSend));
2499: PetscCall(PetscFree(closurePointsC));
2500: PetscCall(PetscSFDestroy(&coveringSF));
2501: closurePointsC = newClosurePointsC;
2503: /* assign tree quads based on locations in coverQuads */
2504: {
2505: PetscInt q;
2506: for (q = 0; q < nleaves; q++) {
2507: p4est_locidx_t t = coverQuads[q].p.which_tree;
2508: if (!treeQuadCounts[t - fltF]++) treeQuads[t - fltF] = &coverQuads[q];
2509: }
2510: }
2511: }
2512: }
2513: if (!coverQuads) { /* matching partitions: assign tree quads based on locations in p4est native arrays */
2514: for (t = fltF; t <= lltF; t++) {
2515: p4est_tree_t *tree = &(((p4est_tree_t *)p4estC->trees->array)[t]);
2517: treeQuadCounts[t - fltF] = (PetscInt)tree->quadrants.elem_count;
2518: treeQuads[t - fltF] = (p4est_quadrant_t *)tree->quadrants.array;
2519: }
2520: }
2522: {
2523: PetscInt p;
2524: PetscInt cLocalStartF;
2525: PetscSF pointSF;
2526: PetscSFNode *roots;
2527: PetscInt *rootType;
2528: DM refTree = NULL;
2529: DMLabel canonical;
2530: PetscInt *childClosures[P4EST_CHILDREN] = {NULL};
2531: PetscInt *rootClosure = NULL;
2532: PetscInt coarseOffset;
2533: PetscInt numCoarseQuads;
2535: PetscCall(PetscMalloc1(pEndF - pStartF, &roots));
2536: PetscCall(PetscMalloc1(pEndF - pStartF, &rootType));
2537: PetscCall(DMGetPointSF(fine, &pointSF));
2538: for (p = pStartF; p < pEndF; p++) {
2539: roots[p - pStartF].rank = -1;
2540: roots[p - pStartF].index = -1;
2541: rootType[p - pStartF] = -1;
2542: }
2543: if (formCids) {
2544: PetscInt child;
2546: PetscCall(PetscMalloc1(pEndF - pStartF, &cids));
2547: for (p = pStartF; p < pEndF; p++) cids[p - pStartF] = -2;
2548: PetscCall(DMPlexGetReferenceTree(plexF, &refTree));
2549: PetscCall(DMPlexGetTransitiveClosure(refTree, 0, PETSC_TRUE, NULL, &rootClosure));
2550: for (child = 0; child < P4EST_CHILDREN; child++) { /* get the closures of the child cells in the reference tree */
2551: PetscCall(DMPlexGetTransitiveClosure(refTree, child + 1, PETSC_TRUE, NULL, &childClosures[child]));
2552: }
2553: PetscCall(DMGetLabel(refTree, "canonical", &canonical));
2554: }
2555: cLocalStartF = pforestF->cLocalStart;
2556: for (t = fltF, coarseOffset = 0, numCoarseQuads = 0; t <= lltF; t++, coarseOffset += numCoarseQuads) {
2557: p4est_tree_t *tree = &(((p4est_tree_t *)p4estF->trees->array)[t]);
2558: PetscInt numFineQuads = (PetscInt)tree->quadrants.elem_count;
2559: p4est_quadrant_t *coarseQuads = treeQuads[t - fltF];
2560: p4est_quadrant_t *fineQuads = (p4est_quadrant_t *)tree->quadrants.array;
2561: PetscInt i, coarseCount = 0;
2562: PetscInt offset = tree->quadrants_offset;
2563: sc_array_t coarseQuadsArray;
2565: numCoarseQuads = treeQuadCounts[t - fltF];
2566: PetscCallP4est(sc_array_init_data, &coarseQuadsArray, coarseQuads, sizeof(p4est_quadrant_t), (size_t)numCoarseQuads);
2567: for (i = 0; i < numFineQuads; i++) {
2568: PetscInt c = i + offset;
2569: p4est_quadrant_t *quad = &fineQuads[i];
2570: p4est_quadrant_t *quadCoarse = NULL;
2571: ssize_t disjoint = -1;
2573: while (disjoint < 0 && coarseCount < numCoarseQuads) {
2574: quadCoarse = &coarseQuads[coarseCount];
2575: PetscCallP4estReturn(disjoint, p4est_quadrant_disjoint, quadCoarse, quad);
2576: if (disjoint < 0) coarseCount++;
2577: }
2578: PetscCheck(disjoint == 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "did not find overlapping coarse quad");
2579: if (quadCoarse->level > quad->level || (quadCoarse->level == quad->level && !transferIdent)) { /* the "coarse" mesh is finer than the fine mesh at the point: continue */
2580: if (transferIdent) { /* find corners */
2581: PetscInt j = 0;
2583: do {
2584: if (j < P4EST_CHILDREN) {
2585: p4est_quadrant_t cornerQuad;
2586: int equal;
2588: PetscCallP4est(p4est_quadrant_corner_descendant, quad, &cornerQuad, j, quadCoarse->level);
2589: PetscCallP4estReturn(equal, p4est_quadrant_is_equal, &cornerQuad, quadCoarse);
2590: if (equal) {
2591: PetscInt petscJ = P4estVertToPetscVert[j];
2592: PetscInt p = closurePointsF[numClosureIndices * c + (P4EST_INSUL - P4EST_CHILDREN) + petscJ].index;
2593: PetscSFNode q = closurePointsC[numClosureIndices * (coarseCount + coarseOffset) + (P4EST_INSUL - P4EST_CHILDREN) + petscJ];
2595: roots[p - pStartF] = q;
2596: rootType[p - pStartF] = PETSC_INT_MAX;
2597: cids[p - pStartF] = -1;
2598: j++;
2599: }
2600: }
2601: coarseCount++;
2602: disjoint = 1;
2603: if (coarseCount < numCoarseQuads) {
2604: quadCoarse = &coarseQuads[coarseCount];
2605: PetscCallP4estReturn(disjoint, p4est_quadrant_disjoint, quadCoarse, quad);
2606: }
2607: } while (!disjoint);
2608: }
2609: continue;
2610: }
2611: if (quadCoarse->level == quad->level) { /* same quad present in coarse and fine mesh */
2612: PetscInt j;
2613: for (j = 0; j < numClosureIndices; j++) {
2614: PetscInt p = closurePointsF[numClosureIndices * c + j].index;
2616: roots[p - pStartF] = closurePointsC[numClosureIndices * (coarseCount + coarseOffset) + j];
2617: rootType[p - pStartF] = PETSC_INT_MAX; /* unconditionally accept */
2618: cids[p - pStartF] = -1;
2619: }
2620: } else {
2621: PetscInt levelDiff = quad->level - quadCoarse->level;
2622: PetscInt proposedCids[P4EST_INSUL] = {0};
2624: if (formCids) {
2625: PetscInt cl;
2626: PetscInt *pointClosure = NULL;
2627: int cid;
2629: PetscCheck(levelDiff <= 1, PETSC_COMM_SELF, PETSC_ERR_USER, "Recursive child ids not implemented");
2630: PetscCallP4estReturn(cid, p4est_quadrant_child_id, quad);
2631: PetscCall(DMPlexGetTransitiveClosure(plexF, c + cLocalStartF, PETSC_TRUE, NULL, &pointClosure));
2632: for (cl = 0; cl < P4EST_INSUL; cl++) {
2633: PetscInt p = pointClosure[2 * cl];
2634: PetscInt point = childClosures[cid][2 * cl];
2635: PetscInt ornt = childClosures[cid][2 * cl + 1];
2636: PetscInt newcid = -1;
2637: DMPolytopeType ct;
2639: if (rootType[p - pStartF] == PETSC_INT_MAX) continue;
2640: PetscCall(DMPlexGetCellType(refTree, point, &ct));
2641: ornt = DMPolytopeConvertNewOrientation_Internal(ct, ornt);
2642: if (!cl) {
2643: newcid = cid + 1;
2644: } else {
2645: PetscInt rcl, parent, parentOrnt = 0;
2647: PetscCall(DMPlexGetTreeParent(refTree, point, &parent, NULL));
2648: if (parent == point) {
2649: newcid = -1;
2650: } else if (!parent) { /* in the root */
2651: newcid = point;
2652: } else {
2653: DMPolytopeType rct = DM_POLYTOPE_UNKNOWN;
2655: for (rcl = 1; rcl < P4EST_INSUL; rcl++) {
2656: if (rootClosure[2 * rcl] == parent) {
2657: PetscCall(DMPlexGetCellType(refTree, parent, &rct));
2658: parentOrnt = DMPolytopeConvertNewOrientation_Internal(rct, rootClosure[2 * rcl + 1]);
2659: break;
2660: }
2661: }
2662: PetscCheck(rcl < P4EST_INSUL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Couldn't find parent in root closure");
2663: PetscCall(DMPlexReferenceTreeGetChildSymmetry(refTree, parent, parentOrnt, ornt, point, DMPolytopeConvertNewOrientation_Internal(rct, pointClosure[2 * rcl + 1]), NULL, &newcid));
2664: }
2665: }
2666: if (newcid >= 0) {
2667: if (canonical) PetscCall(DMLabelGetValue(canonical, newcid, &newcid));
2668: proposedCids[cl] = newcid;
2669: }
2670: }
2671: PetscCall(DMPlexRestoreTransitiveClosure(plexF, c + cLocalStartF, PETSC_TRUE, NULL, &pointClosure));
2672: }
2673: p4est_qcoord_t coarseBound[2][P4EST_DIM] = {
2674: {quadCoarse->x, quadCoarse->y,
2675: #if defined(P4_TO_P8)
2676: quadCoarse->z
2677: #endif
2678: },
2679: {0}
2680: };
2681: p4est_qcoord_t fineBound[2][P4EST_DIM] = {
2682: {quad->x, quad->y,
2683: #if defined(P4_TO_P8)
2684: quad->z
2685: #endif
2686: },
2687: {0}
2688: };
2689: PetscInt j;
2690: for (j = 0; j < P4EST_DIM; j++) { /* get the coordinates of cell boundaries in each direction */
2691: coarseBound[1][j] = coarseBound[0][j] + P4EST_QUADRANT_LEN(quadCoarse->level);
2692: fineBound[1][j] = fineBound[0][j] + P4EST_QUADRANT_LEN(quad->level);
2693: }
2694: for (j = 0; j < numClosureIndices; j++) {
2695: PetscInt l, p;
2696: PetscSFNode q;
2698: p = closurePointsF[numClosureIndices * c + j].index;
2699: if (rootType[p - pStartF] == PETSC_INT_MAX) continue;
2700: if (j == 0) { /* volume: ancestor is volume */
2701: l = 0;
2702: } else if (j < 1 + P4EST_FACES) { /* facet */
2703: PetscInt face = PetscFaceToP4estFace[j - 1];
2704: PetscInt direction = face / 2;
2705: PetscInt coarseFace = -1;
2707: if (coarseBound[face % 2][direction] == fineBound[face % 2][direction]) {
2708: coarseFace = face;
2709: l = 1 + P4estFaceToPetscFace[coarseFace];
2710: } else {
2711: l = 0;
2712: }
2713: #if defined(P4_TO_P8)
2714: } else if (j < 1 + P4EST_FACES + P8EST_EDGES) {
2715: PetscInt edge = PetscEdgeToP4estEdge[j - (1 + P4EST_FACES)];
2716: PetscInt direction = edge / 4;
2717: PetscInt mod = edge % 4;
2718: PetscInt coarseEdge = -1, coarseFace = -1;
2719: PetscInt minDir = PetscMin((direction + 1) % 3, (direction + 2) % 3);
2720: PetscInt maxDir = PetscMax((direction + 1) % 3, (direction + 2) % 3);
2721: PetscBool dirTest[2];
2723: dirTest[0] = (PetscBool)(coarseBound[mod % 2][minDir] == fineBound[mod % 2][minDir]);
2724: dirTest[1] = (PetscBool)(coarseBound[mod / 2][maxDir] == fineBound[mod / 2][maxDir]);
2726: if (dirTest[0] && dirTest[1]) { /* fine edge falls on coarse edge */
2727: coarseEdge = edge;
2728: l = 1 + P4EST_FACES + P4estEdgeToPetscEdge[coarseEdge];
2729: } else if (dirTest[0]) { /* fine edge falls on a coarse face in the minDir direction */
2730: coarseFace = 2 * minDir + (mod % 2);
2731: l = 1 + P4estFaceToPetscFace[coarseFace];
2732: } else if (dirTest[1]) { /* fine edge falls on a coarse face in the maxDir direction */
2733: coarseFace = 2 * maxDir + (mod / 2);
2734: l = 1 + P4estFaceToPetscFace[coarseFace];
2735: } else {
2736: l = 0;
2737: }
2738: #endif
2739: } else {
2740: PetscInt vertex = PetscVertToP4estVert[P4EST_CHILDREN - (P4EST_INSUL - j)];
2741: PetscBool dirTest[P4EST_DIM];
2742: PetscInt m;
2743: PetscInt numMatch = 0;
2744: PetscInt coarseVertex = -1, coarseFace = -1;
2745: #if defined(P4_TO_P8)
2746: PetscInt coarseEdge = -1;
2747: #endif
2749: for (m = 0; m < P4EST_DIM; m++) {
2750: dirTest[m] = (PetscBool)(coarseBound[(vertex >> m) & 1][m] == fineBound[(vertex >> m) & 1][m]);
2751: if (dirTest[m]) numMatch++;
2752: }
2753: if (numMatch == P4EST_DIM) { /* vertex on vertex */
2754: coarseVertex = vertex;
2755: l = P4EST_INSUL - (P4EST_CHILDREN - P4estVertToPetscVert[coarseVertex]);
2756: } else if (numMatch == 1) { /* vertex on face */
2757: for (m = 0; m < P4EST_DIM; m++) {
2758: if (dirTest[m]) {
2759: coarseFace = 2 * m + ((vertex >> m) & 1);
2760: break;
2761: }
2762: }
2763: l = 1 + P4estFaceToPetscFace[coarseFace];
2764: #if defined(P4_TO_P8)
2765: } else if (numMatch == 2) { /* vertex on edge */
2766: for (m = 0; m < P4EST_DIM; m++) {
2767: if (!dirTest[m]) {
2768: PetscInt otherDir1 = (m + 1) % 3;
2769: PetscInt otherDir2 = (m + 2) % 3;
2770: PetscInt minDir = PetscMin(otherDir1, otherDir2);
2771: PetscInt maxDir = PetscMax(otherDir1, otherDir2);
2773: coarseEdge = m * 4 + 2 * ((vertex >> maxDir) & 1) + ((vertex >> minDir) & 1);
2774: break;
2775: }
2776: }
2777: l = 1 + P4EST_FACES + P4estEdgeToPetscEdge[coarseEdge];
2778: #endif
2779: } else { /* volume */
2780: l = 0;
2781: }
2782: }
2783: q = closurePointsC[numClosureIndices * (coarseCount + coarseOffset) + l];
2784: if (l > rootType[p - pStartF]) {
2785: if (l >= P4EST_INSUL - P4EST_CHILDREN) { /* vertex on vertex: unconditional acceptance */
2786: if (transferIdent) {
2787: roots[p - pStartF] = q;
2788: rootType[p - pStartF] = PETSC_INT_MAX;
2789: if (formCids) cids[p - pStartF] = -1;
2790: }
2791: } else {
2792: PetscInt k, thisp = p, limit;
2794: roots[p - pStartF] = q;
2795: rootType[p - pStartF] = l;
2796: if (formCids) cids[p - pStartF] = proposedCids[j];
2797: limit = transferIdent ? levelDiff : (levelDiff - 1);
2798: for (k = 0; k < limit; k++) {
2799: PetscInt parent;
2801: PetscCall(DMPlexGetTreeParent(plexF, thisp, &parent, NULL));
2802: if (parent == thisp) break;
2804: roots[parent - pStartF] = q;
2805: rootType[parent - pStartF] = PETSC_INT_MAX;
2806: if (formCids) cids[parent - pStartF] = -1;
2807: thisp = parent;
2808: }
2809: }
2810: }
2811: }
2812: }
2813: }
2814: }
2816: /* now every cell has labeled the points in its closure, so we first make sure everyone agrees by reducing to roots, and the broadcast the agreements */
2817: if (size > 1) {
2818: PetscInt *rootTypeCopy, p;
2820: PetscCall(PetscMalloc1(pEndF - pStartF, &rootTypeCopy));
2821: PetscCall(PetscArraycpy(rootTypeCopy, rootType, pEndF - pStartF));
2822: PetscCall(PetscSFReduceBegin(pointSF, MPIU_INT, rootTypeCopy, rootTypeCopy, MPI_MAX));
2823: PetscCall(PetscSFReduceEnd(pointSF, MPIU_INT, rootTypeCopy, rootTypeCopy, MPI_MAX));
2824: PetscCall(PetscSFBcastBegin(pointSF, MPIU_INT, rootTypeCopy, rootTypeCopy, MPI_REPLACE));
2825: PetscCall(PetscSFBcastEnd(pointSF, MPIU_INT, rootTypeCopy, rootTypeCopy, MPI_REPLACE));
2826: for (p = pStartF; p < pEndF; p++) {
2827: if (rootTypeCopy[p - pStartF] > rootType[p - pStartF]) { /* another process found a root of higher type (e.g. vertex instead of edge), which we want to accept, so nullify this */
2828: roots[p - pStartF].rank = -1;
2829: roots[p - pStartF].index = -1;
2830: }
2831: if (formCids && rootTypeCopy[p - pStartF] == PETSC_INT_MAX) cids[p - pStartF] = -1; /* we have found an antecedent that is the same: no child id */
2832: }
2833: PetscCall(PetscFree(rootTypeCopy));
2834: PetscCall(PetscSFReduceBegin(pointSF, nodeType, roots, roots, sfNodeReduce));
2835: PetscCall(PetscSFReduceEnd(pointSF, nodeType, roots, roots, sfNodeReduce));
2836: PetscCall(PetscSFBcastBegin(pointSF, nodeType, roots, roots, MPI_REPLACE));
2837: PetscCall(PetscSFBcastEnd(pointSF, nodeType, roots, roots, MPI_REPLACE));
2838: }
2839: PetscCall(PetscFree(rootType));
2841: {
2842: PetscInt numRoots;
2843: PetscInt numLeaves;
2844: PetscInt *leaves;
2845: PetscSFNode *iremote;
2846: /* count leaves */
2848: numRoots = pEndC - pStartC;
2850: numLeaves = 0;
2851: for (p = pStartF; p < pEndF; p++) {
2852: if (roots[p - pStartF].index >= 0) numLeaves++;
2853: }
2854: PetscCall(PetscMalloc1(numLeaves, &leaves));
2855: PetscCall(PetscMalloc1(numLeaves, &iremote));
2856: numLeaves = 0;
2857: for (p = pStartF; p < pEndF; p++) {
2858: if (roots[p - pStartF].index >= 0) {
2859: leaves[numLeaves] = p - pStartF;
2860: iremote[numLeaves] = roots[p - pStartF];
2861: numLeaves++;
2862: }
2863: }
2864: PetscCall(PetscFree(roots));
2865: PetscCall(PetscSFCreate(comm, sf));
2866: if (numLeaves == (pEndF - pStartF)) {
2867: PetscCall(PetscFree(leaves));
2868: PetscCall(PetscSFSetGraph(*sf, numRoots, numLeaves, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
2869: } else {
2870: PetscCall(PetscSFSetGraph(*sf, numRoots, numLeaves, leaves, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
2871: }
2872: }
2873: if (formCids) {
2874: PetscSF pointSF;
2875: PetscInt child;
2877: PetscCall(DMPlexGetReferenceTree(plexF, &refTree));
2878: PetscCall(DMGetPointSF(plexF, &pointSF));
2879: PetscCall(PetscSFReduceBegin(pointSF, MPIU_INT, cids, cids, MPI_MAX));
2880: PetscCall(PetscSFReduceEnd(pointSF, MPIU_INT, cids, cids, MPI_MAX));
2881: if (childIds) *childIds = cids;
2882: for (child = 0; child < P4EST_CHILDREN; child++) PetscCall(DMPlexRestoreTransitiveClosure(refTree, child + 1, PETSC_TRUE, NULL, &childClosures[child]));
2883: PetscCall(DMPlexRestoreTransitiveClosure(refTree, 0, PETSC_TRUE, NULL, &rootClosure));
2884: }
2885: }
2886: if (saveInCoarse) { /* cache results */
2887: PetscCall(PetscObjectReference((PetscObject)*sf));
2888: pforestC->pointSelfToAdaptSF = *sf;
2889: if (!childIds) {
2890: pforestC->pointSelfToAdaptCids = cids;
2891: } else {
2892: PetscCall(PetscMalloc1(pEndF - pStartF, &pforestC->pointSelfToAdaptCids));
2893: PetscCall(PetscArraycpy(pforestC->pointSelfToAdaptCids, cids, pEndF - pStartF));
2894: }
2895: } else if (saveInFine) {
2896: PetscCall(PetscObjectReference((PetscObject)*sf));
2897: pforestF->pointAdaptToSelfSF = *sf;
2898: if (!childIds) {
2899: pforestF->pointAdaptToSelfCids = cids;
2900: } else {
2901: PetscCall(PetscMalloc1(pEndF - pStartF, &pforestF->pointAdaptToSelfCids));
2902: PetscCall(PetscArraycpy(pforestF->pointAdaptToSelfCids, cids, pEndF - pStartF));
2903: }
2904: }
2905: PetscCall(PetscFree2(treeQuads, treeQuadCounts));
2906: PetscCall(PetscFree(coverQuads));
2907: PetscCall(PetscFree(closurePointsC));
2908: PetscCall(PetscFree(closurePointsF));
2909: PetscCallMPI(MPI_Type_free(&nodeClosureType));
2910: PetscCallMPI(MPI_Op_free(&sfNodeReduce));
2911: PetscCallMPI(MPI_Type_free(&nodeType));
2912: PetscFunctionReturn(PETSC_SUCCESS);
2913: }
2914: #if defined(__GNUC__) && !defined(__clang__)
2915: #pragma GCC diagnostic pop
2916: #endif
2918: /* children are sf leaves of parents */
2919: static PetscErrorCode DMPforestGetTransferSF_Internal(DM coarse, DM fine, const PetscInt dofPerDim[], PetscSF *sf, PetscBool transferIdent, PetscInt *childIds[])
2920: {
2921: MPI_Comm comm;
2922: PetscMPIInt rank;
2923: DM_Forest_pforest *pforestC, *pforestF;
2924: DM plexC, plexF;
2925: PetscInt pStartC, pEndC, pStartF, pEndF;
2926: PetscSF pointTransferSF;
2927: PetscBool allOnes = PETSC_TRUE;
2929: PetscFunctionBegin;
2930: pforestC = (DM_Forest_pforest *)((DM_Forest *)coarse->data)->data;
2931: pforestF = (DM_Forest_pforest *)((DM_Forest *)fine->data)->data;
2932: PetscCheck(pforestC->topo == pforestF->topo, PetscObjectComm((PetscObject)coarse), PETSC_ERR_ARG_INCOMP, "DM's must have the same base DM");
2933: comm = PetscObjectComm((PetscObject)coarse);
2934: PetscCallMPI(MPI_Comm_rank(comm, &rank));
2936: {
2937: PetscInt i;
2938: for (i = 0; i <= P4EST_DIM; i++) {
2939: if (dofPerDim[i] != 1) {
2940: allOnes = PETSC_FALSE;
2941: break;
2942: }
2943: }
2944: }
2945: PetscCall(DMPforestGetTransferSF_Point(coarse, fine, &pointTransferSF, transferIdent, childIds));
2946: if (allOnes) {
2947: *sf = pointTransferSF;
2948: PetscFunctionReturn(PETSC_SUCCESS);
2949: }
2951: PetscCall(DMPforestGetPlex(fine, &plexF));
2952: PetscCall(DMPlexGetChart(plexF, &pStartF, &pEndF));
2953: PetscCall(DMPforestGetPlex(coarse, &plexC));
2954: PetscCall(DMPlexGetChart(plexC, &pStartC, &pEndC));
2955: {
2956: PetscInt numRoots;
2957: PetscInt numLeaves;
2958: const PetscInt *leaves;
2959: const PetscSFNode *iremote;
2960: PetscInt d;
2961: PetscSection leafSection, rootSection;
2963: /* count leaves */
2964: PetscCall(PetscSFGetGraph(pointTransferSF, &numRoots, &numLeaves, &leaves, &iremote));
2965: PetscCall(PetscSectionCreate(PETSC_COMM_SELF, &rootSection));
2966: PetscCall(PetscSectionCreate(PETSC_COMM_SELF, &leafSection));
2967: PetscCall(PetscSectionSetChart(rootSection, pStartC, pEndC));
2968: PetscCall(PetscSectionSetChart(leafSection, pStartF, pEndF));
2970: for (d = 0; d <= P4EST_DIM; d++) {
2971: PetscInt startC, endC, e;
2973: PetscCall(DMPlexGetSimplexOrBoxCells(plexC, P4EST_DIM - d, &startC, &endC));
2974: for (e = startC; e < endC; e++) PetscCall(PetscSectionSetDof(rootSection, e, dofPerDim[d]));
2975: }
2977: for (d = 0; d <= P4EST_DIM; d++) {
2978: PetscInt startF, endF, e;
2980: PetscCall(DMPlexGetSimplexOrBoxCells(plexF, P4EST_DIM - d, &startF, &endF));
2981: for (e = startF; e < endF; e++) PetscCall(PetscSectionSetDof(leafSection, e, dofPerDim[d]));
2982: }
2984: PetscCall(PetscSectionSetUp(rootSection));
2985: PetscCall(PetscSectionSetUp(leafSection));
2986: {
2987: PetscInt nroots, nleaves;
2988: PetscInt *mine, i, p;
2989: PetscInt *offsets, *offsetsRoot;
2990: PetscSFNode *remote;
2992: PetscCall(PetscMalloc1(pEndF - pStartF, &offsets));
2993: PetscCall(PetscMalloc1(pEndC - pStartC, &offsetsRoot));
2994: for (p = pStartC; p < pEndC; p++) PetscCall(PetscSectionGetOffset(rootSection, p, &offsetsRoot[p - pStartC]));
2995: PetscCall(PetscSFBcastBegin(pointTransferSF, MPIU_INT, offsetsRoot, offsets, MPI_REPLACE));
2996: PetscCall(PetscSFBcastEnd(pointTransferSF, MPIU_INT, offsetsRoot, offsets, MPI_REPLACE));
2997: PetscCall(PetscSectionGetStorageSize(rootSection, &nroots));
2998: nleaves = 0;
2999: for (i = 0; i < numLeaves; i++) {
3000: PetscInt leaf = leaves ? leaves[i] : i;
3001: PetscInt dof;
3003: PetscCall(PetscSectionGetDof(leafSection, leaf, &dof));
3004: nleaves += dof;
3005: }
3006: PetscCall(PetscMalloc1(nleaves, &mine));
3007: PetscCall(PetscMalloc1(nleaves, &remote));
3008: nleaves = 0;
3009: for (i = 0; i < numLeaves; i++) {
3010: PetscInt leaf = leaves ? leaves[i] : i;
3011: PetscInt dof;
3012: PetscInt off, j;
3014: PetscCall(PetscSectionGetDof(leafSection, leaf, &dof));
3015: PetscCall(PetscSectionGetOffset(leafSection, leaf, &off));
3016: for (j = 0; j < dof; j++) {
3017: remote[nleaves].rank = iremote[i].rank;
3018: remote[nleaves].index = offsets[leaf] + j;
3019: mine[nleaves++] = off + j;
3020: }
3021: }
3022: PetscCall(PetscFree(offsetsRoot));
3023: PetscCall(PetscFree(offsets));
3024: PetscCall(PetscSFCreate(comm, sf));
3025: PetscCall(PetscSFSetGraph(*sf, nroots, nleaves, mine, PETSC_OWN_POINTER, remote, PETSC_OWN_POINTER));
3026: }
3027: PetscCall(PetscSectionDestroy(&leafSection));
3028: PetscCall(PetscSectionDestroy(&rootSection));
3029: PetscCall(PetscSFDestroy(&pointTransferSF));
3030: }
3031: PetscFunctionReturn(PETSC_SUCCESS);
3032: }
3034: static PetscErrorCode DMPforestGetTransferSF(DM dmA, DM dmB, const PetscInt dofPerDim[], PetscSF *sfAtoB, PetscSF *sfBtoA)
3035: {
3036: DM adaptA, adaptB;
3037: DMAdaptFlag purpose;
3039: PetscFunctionBegin;
3040: PetscCall(DMForestGetAdaptivityForest(dmA, &adaptA));
3041: PetscCall(DMForestGetAdaptivityForest(dmB, &adaptB));
3042: /* it is more efficient when the coarser mesh is the first argument: reorder if we know one is coarser than the other */
3043: if (adaptA && adaptA->data == dmB->data) { /* dmA was adapted from dmB */
3044: PetscCall(DMForestGetAdaptivityPurpose(dmA, &purpose));
3045: if (purpose == DM_ADAPT_REFINE) {
3046: PetscCall(DMPforestGetTransferSF(dmB, dmA, dofPerDim, sfBtoA, sfAtoB));
3047: PetscFunctionReturn(PETSC_SUCCESS);
3048: }
3049: } else if (adaptB && adaptB->data == dmA->data) { /* dmB was adapted from dmA */
3050: PetscCall(DMForestGetAdaptivityPurpose(dmB, &purpose));
3051: if (purpose == DM_ADAPT_COARSEN) {
3052: PetscCall(DMPforestGetTransferSF(dmB, dmA, dofPerDim, sfBtoA, sfAtoB));
3053: PetscFunctionReturn(PETSC_SUCCESS);
3054: }
3055: }
3056: if (sfAtoB) PetscCall(DMPforestGetTransferSF_Internal(dmA, dmB, dofPerDim, sfAtoB, PETSC_TRUE, NULL));
3057: if (sfBtoA) PetscCall(DMPforestGetTransferSF_Internal(dmB, dmA, dofPerDim, sfBtoA, (PetscBool)(sfAtoB == NULL), NULL));
3058: PetscFunctionReturn(PETSC_SUCCESS);
3059: }
3061: #if defined(__GNUC__) && !defined(__clang__)
3062: #pragma GCC diagnostic push
3063: #pragma GCC diagnostic ignored "-Wclobbered"
3064: #endif
3065: static PetscErrorCode DMPforestLabelsInitialize(DM dm, DM plex)
3066: {
3067: DM_Forest *forest = (DM_Forest *)dm->data;
3068: DM_Forest_pforest *pforest = (DM_Forest_pforest *)forest->data;
3069: PetscInt cLocalStart, cLocalEnd, cStart, cEnd, fStart, fEnd, eStart, eEnd, vStart, vEnd;
3070: PetscInt cStartBase, cEndBase, fStartBase, fEndBase, vStartBase, vEndBase, eStartBase, eEndBase;
3071: PetscInt pStart, pEnd, pStartBase, pEndBase, p;
3072: DM base;
3073: PetscInt *star = NULL, starSize;
3074: DMLabelLink next = dm->labels;
3075: PetscInt guess = 0;
3076: p4est_topidx_t num_trees = pforest->topo->conn->num_trees;
3078: PetscFunctionBegin;
3079: pforest->labelsFinalized = PETSC_TRUE;
3080: cLocalStart = pforest->cLocalStart;
3081: cLocalEnd = pforest->cLocalEnd;
3082: PetscCall(DMForestGetBaseDM(dm, &base));
3083: if (!base) {
3084: if (pforest->ghostName) { /* insert a label to make the boundaries, with stratum values denoting which face of the element touches the boundary */
3085: p4est_connectivity_t *conn = pforest->topo->conn;
3086: p4est_t *p4est = pforest->forest;
3087: p4est_tree_t *trees = (p4est_tree_t *)p4est->trees->array;
3088: p4est_topidx_t t, flt = p4est->first_local_tree;
3089: p4est_topidx_t llt = pforest->forest->last_local_tree;
3090: DMLabel ghostLabel;
3091: PetscInt c;
3093: PetscCall(DMCreateLabel(plex, pforest->ghostName));
3094: PetscCall(DMGetLabel(plex, pforest->ghostName, &ghostLabel));
3095: for (c = cLocalStart, t = flt; t <= llt; t++) {
3096: p4est_tree_t *tree = &trees[t];
3097: p4est_quadrant_t *quads = (p4est_quadrant_t *)tree->quadrants.array;
3098: PetscInt numQuads = (PetscInt)tree->quadrants.elem_count;
3099: PetscInt q;
3101: for (q = 0; q < numQuads; q++, c++) {
3102: p4est_quadrant_t *quad = &quads[q];
3103: PetscInt f;
3105: for (f = 0; f < P4EST_FACES; f++) {
3106: p4est_quadrant_t neigh;
3107: int isOutside;
3109: PetscCallP4est(p4est_quadrant_face_neighbor, quad, f, &neigh);
3110: PetscCallP4estReturn(isOutside, p4est_quadrant_is_outside_face, &neigh);
3111: if (isOutside) {
3112: p4est_topidx_t nt;
3113: PetscInt nf;
3115: nt = conn->tree_to_tree[t * P4EST_FACES + f];
3116: nf = (PetscInt)conn->tree_to_face[t * P4EST_FACES + f];
3117: nf = nf % P4EST_FACES;
3118: if (nt == t && nf == f) {
3119: PetscInt plexF = P4estFaceToPetscFace[f];
3120: const PetscInt *cone;
3122: PetscCall(DMPlexGetCone(plex, c, &cone));
3123: PetscCall(DMLabelSetValue(ghostLabel, cone[plexF], plexF + 1));
3124: }
3125: }
3126: }
3127: }
3128: }
3129: }
3130: PetscFunctionReturn(PETSC_SUCCESS);
3131: }
3132: PetscCall(DMPlexGetSimplexOrBoxCells(base, 0, &cStartBase, &cEndBase));
3133: PetscCall(DMPlexGetSimplexOrBoxCells(base, 1, &fStartBase, &fEndBase));
3134: PetscCall(DMPlexGetSimplexOrBoxCells(base, P4EST_DIM - 1, &eStartBase, &eEndBase));
3135: PetscCall(DMPlexGetDepthStratum(base, 0, &vStartBase, &vEndBase));
3137: PetscCall(DMPlexGetSimplexOrBoxCells(plex, 0, &cStart, &cEnd));
3138: PetscCall(DMPlexGetSimplexOrBoxCells(plex, 1, &fStart, &fEnd));
3139: PetscCall(DMPlexGetSimplexOrBoxCells(plex, P4EST_DIM - 1, &eStart, &eEnd));
3140: PetscCall(DMPlexGetDepthStratum(plex, 0, &vStart, &vEnd));
3142: PetscCall(DMPlexGetChart(plex, &pStart, &pEnd));
3143: PetscCall(DMPlexGetChart(base, &pStartBase, &pEndBase));
3144: /* go through the mesh: use star to find a quadrant that borders a point. Use the closure to determine the
3145: * orientation of the quadrant relative to that point. Use that to relate the point to the numbering in the base
3146: * mesh, and extract a label value (since the base mesh is redundantly distributed, can be found locally). */
3147: while (next) {
3148: DMLabel baseLabel;
3149: DMLabel label = next->label;
3150: PetscBool isDepth, isCellType, isGhost, isVTK, isSpmap;
3151: const char *name;
3153: PetscCall(PetscObjectGetName((PetscObject)label, &name));
3154: PetscCall(PetscStrcmp(name, "depth", &isDepth));
3155: if (isDepth) {
3156: next = next->next;
3157: continue;
3158: }
3159: PetscCall(PetscStrcmp(name, "celltype", &isCellType));
3160: if (isCellType) {
3161: next = next->next;
3162: continue;
3163: }
3164: PetscCall(PetscStrcmp(name, "ghost", &isGhost));
3165: if (isGhost) {
3166: next = next->next;
3167: continue;
3168: }
3169: PetscCall(PetscStrcmp(name, "vtk", &isVTK));
3170: if (isVTK) {
3171: next = next->next;
3172: continue;
3173: }
3174: PetscCall(PetscStrcmp(name, "_forest_base_subpoint_map", &isSpmap));
3175: if (!isSpmap) {
3176: PetscCall(DMGetLabel(base, name, &baseLabel));
3177: if (!baseLabel) {
3178: next = next->next;
3179: continue;
3180: }
3181: PetscCall(DMLabelCreateIndex(baseLabel, pStartBase, pEndBase));
3182: } else baseLabel = NULL;
3184: for (p = pStart; p < pEnd; p++) {
3185: PetscInt s, c = -1, l;
3186: PetscInt *closure = NULL, closureSize;
3187: p4est_quadrant_t *ghosts = (p4est_quadrant_t *)pforest->ghost->ghosts.array;
3188: p4est_tree_t *trees = (p4est_tree_t *)pforest->forest->trees->array;
3189: p4est_quadrant_t *q;
3190: PetscInt t, val;
3191: PetscBool zerosupportpoint = PETSC_FALSE;
3193: PetscCall(DMPlexGetTransitiveClosure(plex, p, PETSC_FALSE, &starSize, &star));
3194: for (s = 0; s < starSize; s++) {
3195: PetscInt point = star[2 * s];
3197: if (cStart <= point && point < cEnd) {
3198: PetscCall(DMPlexGetTransitiveClosure(plex, point, PETSC_TRUE, &closureSize, &closure));
3199: for (l = 0; l < closureSize; l++) {
3200: PetscInt qParent = closure[2 * l], q, pp = p, pParent = p;
3201: do { /* check parents of q */
3202: q = qParent;
3203: if (q == p) {
3204: c = point;
3205: break;
3206: }
3207: PetscCall(DMPlexGetTreeParent(plex, q, &qParent, NULL));
3208: } while (qParent != q);
3209: if (c != -1) break;
3210: PetscCall(DMPlexGetTreeParent(plex, pp, &pParent, NULL));
3211: q = closure[2 * l];
3212: while (pParent != pp) { /* check parents of p */
3213: pp = pParent;
3214: if (pp == q) {
3215: c = point;
3216: break;
3217: }
3218: PetscCall(DMPlexGetTreeParent(plex, pp, &pParent, NULL));
3219: }
3220: if (c != -1) break;
3221: }
3222: PetscCall(DMPlexRestoreTransitiveClosure(plex, point, PETSC_TRUE, NULL, &closure));
3223: if (l < closureSize) break;
3224: } else {
3225: PetscInt supportSize;
3227: PetscCall(DMPlexGetSupportSize(plex, point, &supportSize));
3228: zerosupportpoint = (PetscBool)(zerosupportpoint || !supportSize);
3229: }
3230: }
3231: if (c < 0) {
3232: const char *prefix;
3233: PetscBool print = PETSC_FALSE;
3235: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)dm, &prefix));
3236: PetscCall(PetscOptionsGetBool(((PetscObject)dm)->options, prefix, "-dm_forest_print_label_error", &print, NULL));
3237: if (print) {
3238: PetscInt i;
3240: PetscCall(PetscPrintf(PETSC_COMM_SELF, "[%d] Failed to find cell with point %" PetscInt_FMT " in its closure for label %s (starSize %" PetscInt_FMT ")\n", PetscGlobalRank, p, baseLabel ? ((PetscObject)baseLabel)->name : "_forest_base_subpoint_map", starSize));
3241: for (i = 0; i < starSize; i++) PetscCall(PetscPrintf(PETSC_COMM_SELF, " star[%" PetscInt_FMT "] = %" PetscInt_FMT ",%" PetscInt_FMT "\n", i, star[2 * i], star[2 * i + 1]));
3242: }
3243: PetscCall(DMPlexRestoreTransitiveClosure(plex, p, PETSC_FALSE, NULL, &star));
3244: if (zerosupportpoint) continue;
3245: else
3246: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Failed to find cell with point %" PetscInt_FMT " in its closure for label %s. Rerun with -dm_forest_print_label_error for more information", p, baseLabel ? ((PetscObject)baseLabel)->name : "_forest_base_subpoint_map");
3247: }
3248: PetscCall(DMPlexRestoreTransitiveClosure(plex, p, PETSC_FALSE, NULL, &star));
3250: if (c < cLocalStart) {
3251: /* get from the beginning of the ghost layer */
3252: q = &ghosts[c];
3253: t = (PetscInt)q->p.which_tree;
3254: } else if (c < cLocalEnd) {
3255: PetscInt lo = 0, hi = num_trees;
3256: /* get from local quadrants: have to find the right tree */
3258: c -= cLocalStart;
3260: do {
3261: p4est_tree_t *tree;
3263: PetscCheck(guess >= lo && guess < num_trees && lo < hi, PETSC_COMM_SELF, PETSC_ERR_PLIB, "failed binary search");
3264: tree = &trees[guess];
3265: if (c < tree->quadrants_offset) {
3266: hi = guess;
3267: } else if (c < tree->quadrants_offset + (PetscInt)tree->quadrants.elem_count) {
3268: q = &((p4est_quadrant_t *)tree->quadrants.array)[c - (PetscInt)tree->quadrants_offset];
3269: t = guess;
3270: break;
3271: } else {
3272: lo = guess + 1;
3273: }
3274: guess = lo + (hi - lo) / 2;
3275: } while (1);
3276: } else {
3277: /* get from the end of the ghost layer */
3278: c -= (cLocalEnd - cLocalStart);
3280: q = &ghosts[c];
3281: t = (PetscInt)q->p.which_tree;
3282: }
3284: if (l == 0) { /* cell */
3285: if (baseLabel) {
3286: PetscCall(DMLabelGetValue(baseLabel, t + cStartBase, &val));
3287: } else {
3288: val = t + cStartBase;
3289: }
3290: PetscCall(DMLabelSetValue(label, p, val));
3291: } else if (l >= 1 && l < 1 + P4EST_FACES) { /* facet */
3292: p4est_quadrant_t nq;
3293: int isInside;
3295: l = PetscFaceToP4estFace[l - 1];
3296: PetscCallP4est(p4est_quadrant_face_neighbor, q, l, &nq);
3297: PetscCallP4estReturn(isInside, p4est_quadrant_is_inside_root, &nq);
3298: if (isInside) {
3299: /* this facet is in the interior of a tree, so it inherits the label of the tree */
3300: if (baseLabel) {
3301: PetscCall(DMLabelGetValue(baseLabel, t + cStartBase, &val));
3302: } else {
3303: val = t + cStartBase;
3304: }
3305: PetscCall(DMLabelSetValue(label, p, val));
3306: } else {
3307: PetscInt f = pforest->topo->tree_face_to_uniq[P4EST_FACES * t + l];
3309: if (baseLabel) {
3310: PetscCall(DMLabelGetValue(baseLabel, f + fStartBase, &val));
3311: } else {
3312: val = f + fStartBase;
3313: }
3314: PetscCall(DMLabelSetValue(label, p, val));
3315: }
3316: #if defined(P4_TO_P8)
3317: } else if (l >= 1 + P4EST_FACES && l < 1 + P4EST_FACES + P8EST_EDGES) { /* edge */
3318: p4est_quadrant_t nq;
3319: int isInside;
3321: l = PetscEdgeToP4estEdge[l - (1 + P4EST_FACES)];
3322: PetscCallP4est(p8est_quadrant_edge_neighbor, q, l, &nq);
3323: PetscCallP4estReturn(isInside, p4est_quadrant_is_inside_root, &nq);
3324: if (isInside) {
3325: /* this edge is in the interior of a tree, so it inherits the label of the tree */
3326: if (baseLabel) {
3327: PetscCall(DMLabelGetValue(baseLabel, t + cStartBase, &val));
3328: } else {
3329: val = t + cStartBase;
3330: }
3331: PetscCall(DMLabelSetValue(label, p, val));
3332: } else {
3333: int isOutsideFace;
3335: PetscCallP4estReturn(isOutsideFace, p4est_quadrant_is_outside_face, &nq);
3336: if (isOutsideFace) {
3337: PetscInt f;
3339: if (nq.x < 0) {
3340: f = 0;
3341: } else if (nq.x >= P4EST_ROOT_LEN) {
3342: f = 1;
3343: } else if (nq.y < 0) {
3344: f = 2;
3345: } else if (nq.y >= P4EST_ROOT_LEN) {
3346: f = 3;
3347: } else if (nq.z < 0) {
3348: f = 4;
3349: } else {
3350: f = 5;
3351: }
3352: f = pforest->topo->tree_face_to_uniq[P4EST_FACES * t + f];
3353: if (baseLabel) {
3354: PetscCall(DMLabelGetValue(baseLabel, f + fStartBase, &val));
3355: } else {
3356: val = f + fStartBase;
3357: }
3358: PetscCall(DMLabelSetValue(label, p, val));
3359: } else { /* the quadrant edge corresponds to the tree edge */
3360: PetscInt e = pforest->topo->conn->tree_to_edge[P8EST_EDGES * t + l];
3362: if (baseLabel) {
3363: PetscCall(DMLabelGetValue(baseLabel, e + eStartBase, &val));
3364: } else {
3365: val = e + eStartBase;
3366: }
3367: PetscCall(DMLabelSetValue(label, p, val));
3368: }
3369: }
3370: #endif
3371: } else { /* vertex */
3372: p4est_quadrant_t nq;
3373: int isInside;
3375: #if defined(P4_TO_P8)
3376: l = PetscVertToP4estVert[l - (1 + P4EST_FACES + P8EST_EDGES)];
3377: #else
3378: l = PetscVertToP4estVert[l - (1 + P4EST_FACES)];
3379: #endif
3380: PetscCallP4est(p4est_quadrant_corner_neighbor, q, l, &nq);
3381: PetscCallP4estReturn(isInside, p4est_quadrant_is_inside_root, &nq);
3382: if (isInside) {
3383: if (baseLabel) {
3384: PetscCall(DMLabelGetValue(baseLabel, t + cStartBase, &val));
3385: } else {
3386: val = t + cStartBase;
3387: }
3388: PetscCall(DMLabelSetValue(label, p, val));
3389: } else {
3390: int isOutside;
3392: PetscCallP4estReturn(isOutside, p4est_quadrant_is_outside_face, &nq);
3393: if (isOutside) {
3394: PetscInt f = -1;
3396: if (nq.x < 0) {
3397: f = 0;
3398: } else if (nq.x >= P4EST_ROOT_LEN) {
3399: f = 1;
3400: } else if (nq.y < 0) {
3401: f = 2;
3402: } else if (nq.y >= P4EST_ROOT_LEN) {
3403: f = 3;
3404: #if defined(P4_TO_P8)
3405: } else if (nq.z < 0) {
3406: f = 4;
3407: } else {
3408: f = 5;
3409: #endif
3410: }
3411: f = pforest->topo->tree_face_to_uniq[P4EST_FACES * t + f];
3412: if (baseLabel) {
3413: PetscCall(DMLabelGetValue(baseLabel, f + fStartBase, &val));
3414: } else {
3415: val = f + fStartBase;
3416: }
3417: PetscCall(DMLabelSetValue(label, p, val));
3418: continue;
3419: }
3420: #if defined(P4_TO_P8)
3421: PetscCallP4estReturn(isOutside, p8est_quadrant_is_outside_edge, &nq);
3422: if (isOutside) {
3423: /* outside edge */
3424: PetscInt e = -1;
3426: if (nq.x >= 0 && nq.x < P4EST_ROOT_LEN) {
3427: if (nq.z < 0) {
3428: if (nq.y < 0) {
3429: e = 0;
3430: } else {
3431: e = 1;
3432: }
3433: } else {
3434: if (nq.y < 0) {
3435: e = 2;
3436: } else {
3437: e = 3;
3438: }
3439: }
3440: } else if (nq.y >= 0 && nq.y < P4EST_ROOT_LEN) {
3441: if (nq.z < 0) {
3442: if (nq.x < 0) {
3443: e = 4;
3444: } else {
3445: e = 5;
3446: }
3447: } else {
3448: if (nq.x < 0) {
3449: e = 6;
3450: } else {
3451: e = 7;
3452: }
3453: }
3454: } else {
3455: if (nq.y < 0) {
3456: if (nq.x < 0) {
3457: e = 8;
3458: } else {
3459: e = 9;
3460: }
3461: } else {
3462: if (nq.x < 0) {
3463: e = 10;
3464: } else {
3465: e = 11;
3466: }
3467: }
3468: }
3470: e = pforest->topo->conn->tree_to_edge[P8EST_EDGES * t + e];
3471: if (baseLabel) {
3472: PetscCall(DMLabelGetValue(baseLabel, e + eStartBase, &val));
3473: } else {
3474: val = e + eStartBase;
3475: }
3476: PetscCall(DMLabelSetValue(label, p, val));
3477: continue;
3478: }
3479: #endif
3480: {
3481: /* outside vertex: same corner as quadrant corner */
3482: PetscInt v = pforest->topo->conn->tree_to_corner[P4EST_CHILDREN * t + l];
3484: if (baseLabel) {
3485: PetscCall(DMLabelGetValue(baseLabel, v + vStartBase, &val));
3486: } else {
3487: val = v + vStartBase;
3488: }
3489: PetscCall(DMLabelSetValue(label, p, val));
3490: }
3491: }
3492: }
3493: }
3494: next = next->next;
3495: }
3496: PetscFunctionReturn(PETSC_SUCCESS);
3497: }
3498: #if defined(__GNUC__) && !defined(__clang__)
3499: #pragma GCC diagnostic pop
3500: #endif
3502: static PetscErrorCode DMPforestLabelsFinalize(DM dm, DM plex)
3503: {
3504: DM_Forest_pforest *pforest = (DM_Forest_pforest *)((DM_Forest *)dm->data)->data;
3505: DM adapt;
3507: PetscFunctionBegin;
3508: if (pforest->labelsFinalized) PetscFunctionReturn(PETSC_SUCCESS);
3509: pforest->labelsFinalized = PETSC_TRUE;
3510: PetscCall(DMForestGetAdaptivityForest(dm, &adapt));
3511: if (!adapt) {
3512: /* Initialize labels from the base dm */
3513: PetscCall(DMPforestLabelsInitialize(dm, plex));
3514: } else {
3515: PetscInt dofPerDim[4] = {1, 1, 1, 1};
3516: PetscSF transferForward, transferBackward, pointSF;
3517: PetscInt pStart, pEnd, pStartA, pEndA;
3518: PetscInt *values, *adaptValues;
3519: DMLabelLink next = adapt->labels;
3520: DMLabel adaptLabel;
3521: DM adaptPlex;
3523: PetscCall(DMForestGetAdaptivityLabel(dm, &adaptLabel));
3524: PetscCall(DMPforestGetPlex(adapt, &adaptPlex));
3525: PetscCall(DMPforestGetTransferSF(adapt, dm, dofPerDim, &transferForward, &transferBackward));
3526: PetscCall(DMPlexGetChart(plex, &pStart, &pEnd));
3527: PetscCall(DMPlexGetChart(adaptPlex, &pStartA, &pEndA));
3528: PetscCall(PetscMalloc2(pEnd - pStart, &values, pEndA - pStartA, &adaptValues));
3529: PetscCall(DMGetPointSF(plex, &pointSF));
3530: if (PetscDefined(USE_DEBUG)) {
3531: PetscInt p;
3532: for (p = pStartA; p < pEndA; p++) adaptValues[p - pStartA] = -1;
3533: for (p = pStart; p < pEnd; p++) values[p - pStart] = -2;
3534: if (transferForward) {
3535: PetscCall(PetscSFBcastBegin(transferForward, MPIU_INT, adaptValues, values, MPI_REPLACE));
3536: PetscCall(PetscSFBcastEnd(transferForward, MPIU_INT, adaptValues, values, MPI_REPLACE));
3537: }
3538: if (transferBackward) {
3539: PetscCall(PetscSFReduceBegin(transferBackward, MPIU_INT, adaptValues, values, MPI_MAX));
3540: PetscCall(PetscSFReduceEnd(transferBackward, MPIU_INT, adaptValues, values, MPI_MAX));
3541: }
3542: for (p = pStart; p < pEnd; p++) {
3543: PetscInt q = p, parent;
3545: PetscCall(DMPlexGetTreeParent(plex, q, &parent, NULL));
3546: while (parent != q) {
3547: if (values[parent] == -2) values[parent] = values[q];
3548: q = parent;
3549: PetscCall(DMPlexGetTreeParent(plex, q, &parent, NULL));
3550: }
3551: }
3552: PetscCall(PetscSFReduceBegin(pointSF, MPIU_INT, values, values, MPI_MAX));
3553: PetscCall(PetscSFReduceEnd(pointSF, MPIU_INT, values, values, MPI_MAX));
3554: PetscCall(PetscSFBcastBegin(pointSF, MPIU_INT, values, values, MPI_REPLACE));
3555: PetscCall(PetscSFBcastEnd(pointSF, MPIU_INT, values, values, MPI_REPLACE));
3556: for (p = pStart; p < pEnd; p++) PetscCheck(values[p - pStart] != -2, PETSC_COMM_SELF, PETSC_ERR_PLIB, "uncovered point %" PetscInt_FMT, p);
3557: }
3558: while (next) {
3559: DMLabel nextLabel = next->label;
3560: const char *name;
3561: PetscBool isDepth, isCellType, isGhost, isVTK;
3562: DMLabel label;
3563: PetscInt p;
3565: PetscCall(PetscObjectGetName((PetscObject)nextLabel, &name));
3566: PetscCall(PetscStrcmp(name, "depth", &isDepth));
3567: if (isDepth) {
3568: next = next->next;
3569: continue;
3570: }
3571: PetscCall(PetscStrcmp(name, "celltype", &isCellType));
3572: if (isCellType) {
3573: next = next->next;
3574: continue;
3575: }
3576: PetscCall(PetscStrcmp(name, "ghost", &isGhost));
3577: if (isGhost) {
3578: next = next->next;
3579: continue;
3580: }
3581: PetscCall(PetscStrcmp(name, "vtk", &isVTK));
3582: if (isVTK) {
3583: next = next->next;
3584: continue;
3585: }
3586: if (nextLabel == adaptLabel) {
3587: next = next->next;
3588: continue;
3589: }
3590: /* label was created earlier */
3591: PetscCall(DMGetLabel(dm, name, &label));
3592: for (p = pStartA; p < pEndA; p++) PetscCall(DMLabelGetValue(nextLabel, p, &adaptValues[p]));
3593: for (p = pStart; p < pEnd; p++) values[p] = PETSC_INT_MIN;
3595: if (transferForward) PetscCall(PetscSFBcastBegin(transferForward, MPIU_INT, adaptValues, values, MPI_REPLACE));
3596: if (transferBackward) PetscCall(PetscSFReduceBegin(transferBackward, MPIU_INT, adaptValues, values, MPI_MAX));
3597: if (transferForward) PetscCall(PetscSFBcastEnd(transferForward, MPIU_INT, adaptValues, values, MPI_REPLACE));
3598: if (transferBackward) PetscCall(PetscSFReduceEnd(transferBackward, MPIU_INT, adaptValues, values, MPI_MAX));
3599: for (p = pStart; p < pEnd; p++) {
3600: PetscInt q = p, parent;
3602: PetscCall(DMPlexGetTreeParent(plex, q, &parent, NULL));
3603: while (parent != q) {
3604: if (values[parent] == PETSC_INT_MIN) values[parent] = values[q];
3605: q = parent;
3606: PetscCall(DMPlexGetTreeParent(plex, q, &parent, NULL));
3607: }
3608: }
3609: PetscCall(PetscSFReduceBegin(pointSF, MPIU_INT, values, values, MPI_MAX));
3610: PetscCall(PetscSFReduceEnd(pointSF, MPIU_INT, values, values, MPI_MAX));
3611: PetscCall(PetscSFBcastBegin(pointSF, MPIU_INT, values, values, MPI_REPLACE));
3612: PetscCall(PetscSFBcastEnd(pointSF, MPIU_INT, values, values, MPI_REPLACE));
3614: for (p = pStart; p < pEnd; p++) PetscCall(DMLabelSetValue(label, p, values[p]));
3615: next = next->next;
3616: }
3617: PetscCall(PetscFree2(values, adaptValues));
3618: PetscCall(PetscSFDestroy(&transferForward));
3619: PetscCall(PetscSFDestroy(&transferBackward));
3620: pforest->labelsFinalized = PETSC_TRUE;
3621: }
3622: PetscFunctionReturn(PETSC_SUCCESS);
3623: }
3625: static PetscErrorCode DMPforestMapCoordinates_Cell(DM plex, p4est_geometry_t *geom, PetscInt cell, p4est_quadrant_t *q, p4est_topidx_t t, p4est_connectivity_t *conn, PetscScalar *coords)
3626: {
3627: PetscInt closureSize, c, coordStart, coordEnd, coordDim;
3628: PetscInt *closure = NULL;
3629: PetscSection coordSec;
3631: PetscFunctionBegin;
3632: PetscCall(DMGetCoordinateSection(plex, &coordSec));
3633: PetscCall(PetscSectionGetChart(coordSec, &coordStart, &coordEnd));
3634: PetscCall(DMGetCoordinateDim(plex, &coordDim));
3635: PetscCall(DMPlexGetTransitiveClosure(plex, cell, PETSC_TRUE, &closureSize, &closure));
3636: for (c = 0; c < closureSize; c++) {
3637: PetscInt point = closure[2 * c];
3639: if (point >= coordStart && point < coordEnd) {
3640: PetscInt dof, off;
3641: PetscInt nCoords, i;
3642: PetscCall(PetscSectionGetDof(coordSec, point, &dof));
3643: PetscCheck(dof % coordDim == 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Did not understand coordinate layout");
3644: nCoords = dof / coordDim;
3645: PetscCall(PetscSectionGetOffset(coordSec, point, &off));
3646: for (i = 0; i < nCoords; i++) {
3647: PetscScalar *coord = &coords[off + i * coordDim];
3648: double coordP4est[3] = {0.};
3649: double coordP4estMapped[3] = {0.};
3650: PetscInt j;
3651: PetscReal treeCoords[P4EST_CHILDREN][3] = {{0.}};
3652: PetscReal eta[3] = {0.};
3653: PetscInt numRounds = 10;
3654: PetscReal coordGuess[3] = {0.};
3656: eta[0] = (PetscReal)q->x / (PetscReal)P4EST_ROOT_LEN;
3657: eta[1] = (PetscReal)q->y / (PetscReal)P4EST_ROOT_LEN;
3658: #if defined(P4_TO_P8)
3659: eta[2] = (PetscReal)q->z / (PetscReal)P4EST_ROOT_LEN;
3660: #endif
3662: for (j = 0; j < P4EST_CHILDREN; j++) {
3663: PetscInt k;
3665: for (k = 0; k < 3; k++) treeCoords[j][k] = conn->vertices[3 * conn->tree_to_vertex[P4EST_CHILDREN * t + j] + k];
3666: }
3668: for (j = 0; j < P4EST_CHILDREN; j++) {
3669: PetscInt k;
3670: PetscReal prod = 1.;
3672: for (k = 0; k < P4EST_DIM; k++) prod *= (j & (1 << k)) ? eta[k] : (1. - eta[k]);
3673: for (k = 0; k < 3; k++) coordGuess[k] += prod * treeCoords[j][k];
3674: }
3676: for (j = 0; j < numRounds; j++) {
3677: PetscInt dir;
3679: for (dir = 0; dir < P4EST_DIM; dir++) {
3680: PetscInt k;
3681: PetscReal diff[3];
3682: PetscReal dXdeta[3] = {0.};
3683: PetscReal rhs, scale, update;
3685: for (k = 0; k < 3; k++) diff[k] = coordP4est[k] - coordGuess[k];
3686: for (k = 0; k < P4EST_CHILDREN; k++) {
3687: PetscInt l;
3688: PetscReal prod = 1.;
3690: for (l = 0; l < P4EST_DIM; l++) {
3691: if (l == dir) {
3692: prod *= (k & (1 << l)) ? 1. : -1.;
3693: } else {
3694: prod *= (k & (1 << l)) ? eta[l] : (1. - eta[l]);
3695: }
3696: }
3697: for (l = 0; l < 3; l++) dXdeta[l] += prod * treeCoords[k][l];
3698: }
3699: rhs = 0.;
3700: scale = 0;
3701: for (k = 0; k < 3; k++) {
3702: rhs += diff[k] * dXdeta[k];
3703: scale += dXdeta[k] * dXdeta[k];
3704: }
3705: update = rhs / scale;
3706: eta[dir] += update;
3707: eta[dir] = PetscMin(eta[dir], 1.);
3708: eta[dir] = PetscMax(eta[dir], 0.);
3710: coordGuess[0] = coordGuess[1] = coordGuess[2] = 0.;
3711: for (k = 0; k < P4EST_CHILDREN; k++) {
3712: PetscInt l;
3713: PetscReal prod = 1.;
3715: for (l = 0; l < P4EST_DIM; l++) prod *= (k & (1 << l)) ? eta[l] : (1. - eta[l]);
3716: for (l = 0; l < 3; l++) coordGuess[l] += prod * treeCoords[k][l];
3717: }
3718: }
3719: }
3720: for (j = 0; j < 3; j++) coordP4est[j] = (double)eta[j];
3722: PetscCheck(geom, PETSC_COMM_SELF, PETSC_ERR_SUP, "Not coded");
3723: (geom->X)(geom, t, coordP4est, coordP4estMapped);
3724: for (j = 0; j < coordDim; j++) coord[j] = (PetscScalar)coordP4estMapped[j];
3725: }
3726: }
3727: }
3728: PetscCall(DMPlexRestoreTransitiveClosure(plex, cell, PETSC_TRUE, &closureSize, &closure));
3729: PetscFunctionReturn(PETSC_SUCCESS);
3730: }
3732: static PetscErrorCode DMPforestMapCoordinates(DM dm, DM plex)
3733: {
3734: DM_Forest *forest;
3735: DM_Forest_pforest *pforest;
3736: p4est_geometry_t *geom;
3737: PetscInt cLocalStart, cLocalEnd;
3738: Vec coordLocalVec;
3739: PetscScalar *coords;
3740: p4est_topidx_t flt, llt, t;
3741: p4est_tree_t *trees;
3742: PetscErrorCode (*map)(DM, PetscInt, PetscInt, const PetscReal[], PetscReal[], void *);
3743: void *mapCtx;
3745: PetscFunctionBegin;
3746: forest = (DM_Forest *)dm->data;
3747: pforest = (DM_Forest_pforest *)forest->data;
3748: geom = pforest->topo->geom;
3749: PetscCall(DMForestGetBaseCoordinateMapping(dm, &map, &mapCtx));
3750: if (!geom && !map) PetscFunctionReturn(PETSC_SUCCESS);
3751: PetscCall(DMGetCoordinatesLocal(plex, &coordLocalVec));
3752: PetscCall(VecGetArray(coordLocalVec, &coords));
3753: cLocalStart = pforest->cLocalStart;
3754: cLocalEnd = pforest->cLocalEnd;
3755: flt = pforest->forest->first_local_tree;
3756: llt = pforest->forest->last_local_tree;
3757: trees = (p4est_tree_t *)pforest->forest->trees->array;
3758: if (map) { /* apply the map directly to the existing coordinates */
3759: PetscSection coordSec;
3760: PetscInt coordStart, coordEnd, p, coordDim, p4estCoordDim, cStart, cEnd, cEndInterior;
3761: DM base;
3763: PetscCall(DMPlexGetHeightStratum(plex, 0, &cStart, &cEnd));
3764: PetscCall(DMPlexGetCellTypeStratum(plex, DM_POLYTOPE_FV_GHOST, &cEndInterior, NULL));
3765: cEnd = cEndInterior < 0 ? cEnd : cEndInterior;
3766: PetscCall(DMForestGetBaseDM(dm, &base));
3767: PetscCall(DMGetCoordinateSection(plex, &coordSec));
3768: PetscCall(PetscSectionGetChart(coordSec, &coordStart, &coordEnd));
3769: PetscCall(DMGetCoordinateDim(plex, &coordDim));
3770: p4estCoordDim = PetscMin(coordDim, 3);
3771: for (p = coordStart; p < coordEnd; p++) {
3772: PetscInt *star = NULL, starSize;
3773: PetscInt dof, off, cell = -1, coarsePoint = -1;
3774: PetscInt nCoords, i;
3775: PetscCall(PetscSectionGetDof(coordSec, p, &dof));
3776: PetscCheck(dof % coordDim == 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Did not understand coordinate layout");
3777: nCoords = dof / coordDim;
3778: PetscCall(PetscSectionGetOffset(coordSec, p, &off));
3779: PetscCall(DMPlexGetTransitiveClosure(plex, p, PETSC_FALSE, &starSize, &star));
3780: for (i = 0; i < starSize; i++) {
3781: PetscInt point = star[2 * i];
3783: if (cStart <= point && point < cEnd) {
3784: cell = point;
3785: break;
3786: }
3787: }
3788: PetscCall(DMPlexRestoreTransitiveClosure(plex, p, PETSC_FALSE, &starSize, &star));
3789: if (cell >= 0) {
3790: if (cell < cLocalStart) {
3791: p4est_quadrant_t *ghosts = (p4est_quadrant_t *)pforest->ghost->ghosts.array;
3793: coarsePoint = ghosts[cell].p.which_tree;
3794: } else if (cell < cLocalEnd) {
3795: cell -= cLocalStart;
3796: for (t = flt; t <= llt; t++) {
3797: p4est_tree_t *tree = &trees[t];
3799: if (cell >= tree->quadrants_offset && (size_t)cell < tree->quadrants_offset + tree->quadrants.elem_count) {
3800: coarsePoint = t;
3801: break;
3802: }
3803: }
3804: } else {
3805: p4est_quadrant_t *ghosts = (p4est_quadrant_t *)pforest->ghost->ghosts.array;
3807: coarsePoint = ghosts[cell - cLocalEnd].p.which_tree;
3808: }
3809: }
3810: for (i = 0; i < nCoords; i++) {
3811: PetscScalar *coord = &coords[off + i * coordDim];
3812: PetscReal coordP4est[3] = {0.};
3813: PetscReal coordP4estMapped[3] = {0.};
3814: PetscInt j;
3816: for (j = 0; j < p4estCoordDim; j++) coordP4est[j] = PetscRealPart(coord[j]);
3817: PetscCall((map)(base, coarsePoint, p4estCoordDim, coordP4est, coordP4estMapped, mapCtx));
3818: for (j = 0; j < p4estCoordDim; j++) coord[j] = (PetscScalar)coordP4estMapped[j];
3819: }
3820: }
3821: } else { /* we have to transform coordinates back to the unit cube (where geom is defined), and then apply geom */
3822: PetscInt cStart, cEnd, cEndInterior;
3824: PetscCall(DMPlexGetHeightStratum(plex, 0, &cStart, &cEnd));
3825: PetscCall(DMPlexGetCellTypeStratum(plex, DM_POLYTOPE_FV_GHOST, &cEndInterior, NULL));
3826: cEnd = cEndInterior < 0 ? cEnd : cEndInterior;
3827: if (cLocalStart > 0) {
3828: p4est_quadrant_t *ghosts = (p4est_quadrant_t *)pforest->ghost->ghosts.array;
3829: PetscInt count;
3831: for (count = 0; count < cLocalStart; count++) {
3832: p4est_quadrant_t *quad = &ghosts[count];
3833: p4est_topidx_t t = quad->p.which_tree;
3835: PetscCall(DMPforestMapCoordinates_Cell(plex, geom, count, quad, t, pforest->topo->conn, coords));
3836: }
3837: }
3838: for (t = flt; t <= llt; t++) {
3839: p4est_tree_t *tree = &trees[t];
3840: PetscInt offset = cLocalStart + tree->quadrants_offset, i;
3841: PetscInt numQuads = (PetscInt)tree->quadrants.elem_count;
3842: p4est_quadrant_t *quads = (p4est_quadrant_t *)tree->quadrants.array;
3844: for (i = 0; i < numQuads; i++) {
3845: PetscInt count = i + offset;
3847: PetscCall(DMPforestMapCoordinates_Cell(plex, geom, count, &quads[i], t, pforest->topo->conn, coords));
3848: }
3849: }
3850: if (cLocalEnd - cLocalStart < cEnd - cStart) {
3851: p4est_quadrant_t *ghosts = (p4est_quadrant_t *)pforest->ghost->ghosts.array;
3852: PetscInt numGhosts = (PetscInt)pforest->ghost->ghosts.elem_count;
3853: PetscInt count;
3855: for (count = 0; count < numGhosts - cLocalStart; count++) {
3856: p4est_quadrant_t *quad = &ghosts[count + cLocalStart];
3857: p4est_topidx_t t = quad->p.which_tree;
3859: PetscCall(DMPforestMapCoordinates_Cell(plex, geom, count + cLocalEnd, quad, t, pforest->topo->conn, coords));
3860: }
3861: }
3862: }
3863: PetscCall(VecRestoreArray(coordLocalVec, &coords));
3864: PetscFunctionReturn(PETSC_SUCCESS);
3865: }
3867: static PetscErrorCode PforestQuadrantIsInterior(p4est_quadrant_t *quad, PetscBool *is_interior)
3868: {
3869: PetscFunctionBegin;
3870: p4est_qcoord_t h = P4EST_QUADRANT_LEN(quad->level);
3871: if (quad->x > 0 && quad->x + h < P4EST_ROOT_LEN
3872: #if defined(P4_TO_P8)
3873: && quad->z > 0 && quad->z + h < P4EST_ROOT_LEN
3874: #endif
3875: && quad->y > 0 && quad->y + h < P4EST_ROOT_LEN) {
3876: *is_interior = PETSC_TRUE;
3877: } else {
3878: *is_interior = PETSC_FALSE;
3879: }
3880: PetscFunctionReturn(PETSC_SUCCESS);
3881: }
3883: /* We always use DG coordinates with p4est: if they do not match the vertex
3884: coordinates, add space for them in the section */
3885: static PetscErrorCode PforestCheckLocalizeCell(DM plex, PetscInt cDim, Vec cVecOld, DM_Forest_pforest *pforest, PetscSection oldSection, PetscSection newSection, PetscInt cell, PetscInt coarsePoint, p4est_quadrant_t *quad)
3886: {
3887: PetscBool is_interior;
3889: PetscFunctionBegin;
3890: PetscCall(PforestQuadrantIsInterior(quad, &is_interior));
3891: if (is_interior) { // quads in the interior of a coarse cell can't touch periodic interfaces
3892: PetscCall(PetscSectionSetDof(newSection, cell, 0));
3893: PetscCall(PetscSectionSetFieldDof(newSection, cell, 0, 0));
3894: } else {
3895: PetscInt cSize;
3896: PetscScalar *values = NULL;
3897: PetscBool same_coords = PETSC_TRUE;
3899: PetscCall(DMPlexVecGetClosure(plex, oldSection, cVecOld, cell, &cSize, &values));
3900: PetscAssert(cSize == cDim * P4EST_CHILDREN, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Unexpected closure size");
3901: for (int c = 0; c < P4EST_CHILDREN; c++) {
3902: p4est_qcoord_t quad_coords[3];
3903: p4est_qcoord_t h = P4EST_QUADRANT_LEN(quad->level);
3904: double corner_coords[3];
3905: double vert_coords[3];
3906: PetscInt corner = PetscVertToP4estVert[c];
3908: for (PetscInt d = 0; d < PetscMin(cDim, 3); d++) vert_coords[d] = PetscRealPart(values[c * cDim + d]);
3910: quad_coords[0] = quad->x;
3911: quad_coords[1] = quad->y;
3912: #if defined(P4_TO_P8)
3913: quad_coords[2] = quad->z;
3914: #endif
3915: for (int d = 0; d < 3; d++) quad_coords[d] += (corner & (1 << d)) ? h : 0;
3916: #if !defined(P4_TO_P8)
3917: PetscCallP4est(p4est_qcoord_to_vertex, pforest->forest->connectivity, coarsePoint, quad_coords[0], quad_coords[1], corner_coords);
3918: #else
3919: PetscCallP4est(p4est_qcoord_to_vertex, pforest->forest->connectivity, coarsePoint, quad_coords[0], quad_coords[1], quad_coords[2], corner_coords);
3920: #endif
3921: for (PetscInt d = 0; d < PetscMin(cDim, 3); d++) {
3922: if (fabs(vert_coords[d] - corner_coords[d]) > PETSC_SMALL) {
3923: same_coords = PETSC_FALSE;
3924: break;
3925: }
3926: }
3927: }
3928: if (same_coords) {
3929: PetscCall(PetscSectionSetDof(newSection, cell, 0));
3930: PetscCall(PetscSectionSetFieldDof(newSection, cell, 0, 0));
3931: } else {
3932: PetscCall(PetscSectionSetDof(newSection, cell, cSize));
3933: PetscCall(PetscSectionSetFieldDof(newSection, cell, 0, cSize));
3934: }
3935: PetscCall(DMPlexVecRestoreClosure(plex, oldSection, cVecOld, cell, &cSize, &values));
3936: }
3937: PetscFunctionReturn(PETSC_SUCCESS);
3938: }
3940: static PetscErrorCode PforestLocalizeCell(DM plex, PetscInt cDim, DM_Forest_pforest *pforest, PetscSection newSection, PetscInt cell, PetscInt coarsePoint, p4est_quadrant_t *quad, PetscScalar coords[])
3941: {
3942: PetscInt cdof, off;
3944: PetscFunctionBegin;
3945: PetscCall(PetscSectionGetDof(newSection, cell, &cdof));
3946: if (!cdof) PetscFunctionReturn(PETSC_SUCCESS);
3948: PetscCall(PetscSectionGetOffset(newSection, cell, &off));
3949: for (PetscInt c = 0, pos = off; c < P4EST_CHILDREN; c++) {
3950: p4est_qcoord_t quad_coords[3];
3951: p4est_qcoord_t h = P4EST_QUADRANT_LEN(quad->level);
3952: double corner_coords[3];
3953: PetscInt corner = PetscVertToP4estVert[c];
3955: quad_coords[0] = quad->x;
3956: quad_coords[1] = quad->y;
3957: #if defined(P4_TO_P8)
3958: quad_coords[2] = quad->z;
3959: #endif
3960: for (int d = 0; d < 3; d++) quad_coords[d] += (corner & (1 << d)) ? h : 0;
3961: #if !defined(P4_TO_P8)
3962: PetscCallP4est(p4est_qcoord_to_vertex, pforest->forest->connectivity, coarsePoint, quad_coords[0], quad_coords[1], corner_coords);
3963: #else
3964: PetscCallP4est(p4est_qcoord_to_vertex, pforest->forest->connectivity, coarsePoint, quad_coords[0], quad_coords[1], quad_coords[2], corner_coords);
3965: #endif
3966: for (PetscInt d = 0; d < PetscMin(cDim, 3); d++) coords[pos++] = corner_coords[d];
3967: for (PetscInt d = PetscMin(cDim, 3); d < cDim; d++) coords[pos++] = 0.;
3968: }
3969: PetscFunctionReturn(PETSC_SUCCESS);
3970: }
3972: static PetscErrorCode DMPforestLocalizeCoordinates(DM dm, DM plex)
3973: {
3974: DM_Forest *forest;
3975: DM_Forest_pforest *pforest;
3976: DM base, cdm, cdmCell;
3977: Vec cVec, cVecOld;
3978: PetscSection oldSection, newSection;
3979: PetscScalar *coords2;
3980: const PetscReal *L;
3981: PetscInt cLocalStart, cLocalEnd, coarsePoint;
3982: PetscInt cDim, newStart, newEnd;
3983: PetscInt v, vStart, vEnd, cp, cStart, cEnd, cEndInterior;
3984: p4est_topidx_t flt, llt, t;
3985: p4est_tree_t *trees;
3986: PetscBool baseLocalized = PETSC_FALSE;
3988: PetscFunctionBegin;
3989: PetscCall(DMGetPeriodicity(dm, NULL, NULL, &L));
3990: /* we localize on all cells if we don't have a base DM or the base DM coordinates have not been localized */
3991: PetscCall(DMGetCoordinateDim(dm, &cDim));
3992: PetscCall(DMForestGetBaseDM(dm, &base));
3993: if (base) PetscCall(DMGetCoordinatesLocalized(base, &baseLocalized));
3994: if (!baseLocalized) base = NULL;
3995: if (!baseLocalized && !L) PetscFunctionReturn(PETSC_SUCCESS);
3996: PetscCall(DMPlexGetChart(plex, &newStart, &newEnd));
3998: PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &newSection));
3999: PetscCall(PetscSectionSetNumFields(newSection, 1));
4000: PetscCall(PetscSectionSetFieldComponents(newSection, 0, cDim));
4001: PetscCall(PetscSectionSetChart(newSection, newStart, newEnd));
4003: PetscCall(DMGetCoordinateSection(plex, &oldSection));
4004: PetscCall(DMPlexGetDepthStratum(plex, 0, &vStart, &vEnd));
4005: PetscCall(DMGetCoordinatesLocal(plex, &cVecOld));
4007: forest = (DM_Forest *)dm->data;
4008: pforest = (DM_Forest_pforest *)forest->data;
4009: cLocalStart = pforest->cLocalStart;
4010: cLocalEnd = pforest->cLocalEnd;
4011: flt = pforest->forest->first_local_tree;
4012: llt = pforest->forest->last_local_tree;
4013: trees = (p4est_tree_t *)pforest->forest->trees->array;
4015: PetscCall(DMPlexGetHeightStratum(plex, 0, &cStart, &cEnd));
4016: PetscCall(DMPlexGetCellTypeStratum(plex, DM_POLYTOPE_FV_GHOST, &cEndInterior, NULL));
4017: cEnd = cEndInterior < 0 ? cEnd : cEndInterior;
4018: cp = 0;
4019: if (cLocalStart > 0) {
4020: p4est_quadrant_t *ghosts = (p4est_quadrant_t *)pforest->ghost->ghosts.array;
4021: PetscInt cell;
4023: for (cell = 0; cell < cLocalStart; ++cell, cp++) {
4024: p4est_quadrant_t *quad = &ghosts[cell];
4026: coarsePoint = quad->p.which_tree;
4027: PetscCall(PforestCheckLocalizeCell(plex, cDim, cVecOld, pforest, oldSection, newSection, cell, coarsePoint, quad));
4028: }
4029: }
4030: for (t = flt; t <= llt; t++) {
4031: p4est_tree_t *tree = &trees[t];
4032: PetscInt offset = cLocalStart + tree->quadrants_offset;
4033: PetscInt numQuads = (PetscInt)tree->quadrants.elem_count;
4034: p4est_quadrant_t *quads = (p4est_quadrant_t *)tree->quadrants.array;
4035: PetscInt i;
4037: if (!numQuads) continue;
4038: coarsePoint = t;
4039: for (i = 0; i < numQuads; i++, cp++) {
4040: PetscInt cell = i + offset;
4041: p4est_quadrant_t *quad = &quads[i];
4043: PetscCall(PforestCheckLocalizeCell(plex, cDim, cVecOld, pforest, oldSection, newSection, cell, coarsePoint, quad));
4044: }
4045: }
4046: if (cLocalEnd - cLocalStart < cEnd - cStart) {
4047: p4est_quadrant_t *ghosts = (p4est_quadrant_t *)pforest->ghost->ghosts.array;
4048: PetscInt numGhosts = (PetscInt)pforest->ghost->ghosts.elem_count;
4049: PetscInt count;
4051: for (count = 0; count < numGhosts - cLocalStart; count++, cp++) {
4052: p4est_quadrant_t *quad = &ghosts[count + cLocalStart];
4053: coarsePoint = quad->p.which_tree;
4054: PetscInt cell = count + cLocalEnd;
4056: PetscCall(PforestCheckLocalizeCell(plex, cDim, cVecOld, pforest, oldSection, newSection, cell, coarsePoint, quad));
4057: }
4058: }
4059: PetscAssert(cp == cEnd - cStart, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Unexpected number of fine cells %" PetscInt_FMT " != %" PetscInt_FMT, cp, cEnd - cStart);
4061: PetscCall(PetscSectionSetUp(newSection));
4062: PetscCall(DMGetCoordinateDM(plex, &cdm));
4063: PetscCall(DMClone(cdm, &cdmCell));
4064: PetscCall(DMSetCellCoordinateDM(plex, cdmCell));
4065: PetscCall(DMDestroy(&cdmCell));
4066: PetscCall(DMSetCellCoordinateSection(plex, cDim, newSection));
4067: PetscCall(PetscSectionGetStorageSize(newSection, &v));
4068: PetscCall(VecCreate(PETSC_COMM_SELF, &cVec));
4069: PetscCall(PetscObjectSetName((PetscObject)cVec, "coordinates"));
4070: PetscCall(VecSetBlockSize(cVec, cDim));
4071: PetscCall(VecSetSizes(cVec, v, PETSC_DETERMINE));
4072: PetscCall(VecSetType(cVec, VECSTANDARD));
4073: PetscCall(VecSet(cVec, PETSC_MIN_REAL));
4075: /* Localize coordinates on cells if needed */
4076: PetscCall(VecGetArray(cVec, &coords2));
4077: cp = 0;
4078: if (cLocalStart > 0) {
4079: p4est_quadrant_t *ghosts = (p4est_quadrant_t *)pforest->ghost->ghosts.array;
4080: PetscInt cell;
4082: for (cell = 0; cell < cLocalStart; ++cell, cp++) {
4083: p4est_quadrant_t *quad = &ghosts[cell];
4085: coarsePoint = quad->p.which_tree;
4086: PetscCall(PforestLocalizeCell(plex, cDim, pforest, newSection, cell, coarsePoint, quad, coords2));
4087: }
4088: }
4089: for (t = flt; t <= llt; t++) {
4090: p4est_tree_t *tree = &trees[t];
4091: PetscInt offset = cLocalStart + tree->quadrants_offset;
4092: PetscInt numQuads = (PetscInt)tree->quadrants.elem_count;
4093: p4est_quadrant_t *quads = (p4est_quadrant_t *)tree->quadrants.array;
4094: PetscInt i;
4096: if (!numQuads) continue;
4097: coarsePoint = t;
4098: for (i = 0; i < numQuads; i++, cp++) {
4099: PetscInt cell = i + offset;
4100: p4est_quadrant_t *quad = &quads[i];
4102: PetscCall(PforestLocalizeCell(plex, cDim, pforest, newSection, cell, coarsePoint, quad, coords2));
4103: }
4104: }
4105: if (cLocalEnd - cLocalStart < cEnd - cStart) {
4106: p4est_quadrant_t *ghosts = (p4est_quadrant_t *)pforest->ghost->ghosts.array;
4107: PetscInt numGhosts = (PetscInt)pforest->ghost->ghosts.elem_count;
4108: PetscInt count;
4110: for (count = 0; count < numGhosts - cLocalStart; count++, cp++) {
4111: p4est_quadrant_t *quad = &ghosts[count + cLocalStart];
4112: coarsePoint = quad->p.which_tree;
4113: PetscInt cell = count + cLocalEnd;
4115: PetscCall(PforestLocalizeCell(plex, cDim, pforest, newSection, cell, coarsePoint, quad, coords2));
4116: }
4117: }
4118: PetscCall(VecRestoreArray(cVec, &coords2));
4119: PetscCall(DMSetCellCoordinatesLocal(plex, cVec));
4120: PetscCall(VecDestroy(&cVec));
4121: PetscCall(PetscSectionDestroy(&newSection));
4122: PetscFunctionReturn(PETSC_SUCCESS);
4123: }
4125: #define DMForestClearAdaptivityForest_pforest _append_pforest(DMForestClearAdaptivityForest)
4126: static PetscErrorCode DMForestClearAdaptivityForest_pforest(DM dm)
4127: {
4128: DM_Forest *forest;
4129: DM_Forest_pforest *pforest;
4131: PetscFunctionBegin;
4132: forest = (DM_Forest *)dm->data;
4133: pforest = (DM_Forest_pforest *)forest->data;
4134: PetscCall(PetscSFDestroy(&pforest->pointAdaptToSelfSF));
4135: PetscCall(PetscSFDestroy(&pforest->pointSelfToAdaptSF));
4136: PetscCall(PetscFree(pforest->pointAdaptToSelfCids));
4137: PetscCall(PetscFree(pforest->pointSelfToAdaptCids));
4138: PetscFunctionReturn(PETSC_SUCCESS);
4139: }
4141: static PetscErrorCode DMConvert_pforest_plex(DM dm, DMType newtype, DM *plex)
4142: {
4143: DM_Forest *forest;
4144: DM_Forest_pforest *pforest;
4145: DM refTree, newPlex, base;
4146: PetscInt adjDim, adjCodim, coordDim;
4147: MPI_Comm comm;
4148: PetscBool isPforest;
4149: PetscInt dim;
4150: PetscInt overlap;
4151: p4est_connect_type_t ctype;
4152: p4est_locidx_t first_local_quad = -1;
4153: sc_array_t *points_per_dim, *cone_sizes, *cones, *cone_orientations, *coords, *children, *parents, *childids, *leaves, *remotes;
4154: PetscSection parentSection;
4155: PetscSF pointSF;
4156: size_t zz, count;
4157: PetscInt pStart, pEnd;
4158: DMLabel ghostLabelBase = NULL;
4160: PetscFunctionBegin;
4162: comm = PetscObjectComm((PetscObject)dm);
4163: PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMPFOREST, &isPforest));
4164: PetscCheck(isPforest, comm, PETSC_ERR_ARG_WRONG, "Expected DM type %s, got %s", DMPFOREST, ((PetscObject)dm)->type_name);
4165: PetscCall(DMSetUp(dm));
4166: PetscCall(DMGetDimension(dm, &dim));
4167: PetscCheck(dim == P4EST_DIM, comm, PETSC_ERR_ARG_WRONG, "Expected DM dimension %d, got %" PetscInt_FMT, P4EST_DIM, dim);
4168: forest = (DM_Forest *)dm->data;
4169: pforest = (DM_Forest_pforest *)forest->data;
4170: PetscCall(DMForestGetBaseDM(dm, &base));
4171: if (base) PetscCall(DMGetLabel(base, "ghost", &ghostLabelBase));
4172: if (!pforest->plex) {
4173: PetscMPIInt size;
4174: const char *name;
4176: PetscCallMPI(MPI_Comm_size(comm, &size));
4177: PetscCall(DMCreate(comm, &newPlex));
4178: PetscCall(PetscObjectGetName((PetscObject)dm, &name));
4179: PetscCall(PetscObjectSetName((PetscObject)newPlex, name));
4180: PetscCall(DMSetType(newPlex, DMPLEX));
4181: PetscCall(DMSetMatType(newPlex, dm->mattype));
4182: /* share labels */
4183: PetscCall(DMCopyLabels(dm, newPlex, PETSC_OWN_POINTER, PETSC_TRUE, DM_COPY_LABELS_FAIL));
4184: PetscCall(DMForestGetAdjacencyDimension(dm, &adjDim));
4185: PetscCall(DMForestGetAdjacencyCodimension(dm, &adjCodim));
4186: PetscCall(DMGetCoordinateDim(dm, &coordDim));
4187: if (adjDim == 0) {
4188: ctype = P4EST_CONNECT_FULL;
4189: } else if (adjCodim == 1) {
4190: ctype = P4EST_CONNECT_FACE;
4191: #if defined(P4_TO_P8)
4192: } else if (adjDim == 1) {
4193: ctype = P8EST_CONNECT_EDGE;
4194: #endif
4195: } else {
4196: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Invalid adjacency dimension %" PetscInt_FMT, adjDim);
4197: }
4198: PetscCheck(ctype == P4EST_CONNECT_FULL, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Adjacency dimension %" PetscInt_FMT " / codimension %" PetscInt_FMT " not supported yet", adjDim, adjCodim);
4199: PetscCall(DMForestGetPartitionOverlap(dm, &overlap));
4200: PetscCall(DMPlexSetOverlap_Plex(newPlex, NULL, overlap));
4202: points_per_dim = sc_array_new(sizeof(p4est_locidx_t));
4203: cone_sizes = sc_array_new(sizeof(p4est_locidx_t));
4204: cones = sc_array_new(sizeof(p4est_locidx_t));
4205: cone_orientations = sc_array_new(sizeof(p4est_locidx_t));
4206: coords = sc_array_new(3 * sizeof(double));
4207: children = sc_array_new(sizeof(p4est_locidx_t));
4208: parents = sc_array_new(sizeof(p4est_locidx_t));
4209: childids = sc_array_new(sizeof(p4est_locidx_t));
4210: leaves = sc_array_new(sizeof(p4est_locidx_t));
4211: remotes = sc_array_new(2 * sizeof(p4est_locidx_t));
4213: PetscCallP4est(p4est_get_plex_data_ext, pforest->forest, &pforest->ghost, &pforest->lnodes, ctype, (int)((size > 1) ? overlap : 0), &first_local_quad, points_per_dim, cone_sizes, cones, cone_orientations, coords, children, parents, childids, leaves, remotes, 1);
4215: pforest->cLocalStart = (PetscInt)first_local_quad;
4216: pforest->cLocalEnd = pforest->cLocalStart + (PetscInt)pforest->forest->local_num_quadrants;
4217: PetscCall(locidx_to_PetscInt(points_per_dim));
4218: PetscCall(locidx_to_PetscInt(cone_sizes));
4219: PetscCall(locidx_to_PetscInt(cones));
4220: PetscCall(locidx_to_PetscInt(cone_orientations));
4221: PetscCall(coords_double_to_PetscScalar(coords, coordDim));
4222: PetscCall(locidx_to_PetscInt(children));
4223: PetscCall(locidx_to_PetscInt(parents));
4224: PetscCall(locidx_to_PetscInt(childids));
4225: PetscCall(locidx_to_PetscInt(leaves));
4226: PetscCall(locidx_pair_to_PetscSFNode(remotes));
4228: PetscCall(DMSetDimension(newPlex, P4EST_DIM));
4229: PetscCall(DMSetCoordinateDim(newPlex, coordDim));
4230: PetscCall(DMPlexSetMaxProjectionHeight(newPlex, P4EST_DIM - 1));
4231: PetscCall(DMPlexCreateFromDAG(newPlex, P4EST_DIM, (PetscInt *)points_per_dim->array, (PetscInt *)cone_sizes->array, (PetscInt *)cones->array, (PetscInt *)cone_orientations->array, (PetscScalar *)coords->array));
4232: PetscCall(DMPlexConvertOldOrientations_Internal(newPlex));
4233: PetscCall(DMCreateReferenceTree_pforest(comm, &refTree));
4234: PetscCall(DMPlexSetReferenceTree(newPlex, refTree));
4235: PetscCall(PetscSectionCreate(comm, &parentSection));
4236: PetscCall(DMPlexGetChart(newPlex, &pStart, &pEnd));
4237: PetscCall(PetscSectionSetChart(parentSection, pStart, pEnd));
4238: count = children->elem_count;
4239: for (zz = 0; zz < count; zz++) {
4240: PetscInt child = *((PetscInt *)sc_array_index(children, zz));
4242: PetscCall(PetscSectionSetDof(parentSection, child, 1));
4243: }
4244: PetscCall(PetscSectionSetUp(parentSection));
4245: PetscCall(DMPlexSetTree(newPlex, parentSection, (PetscInt *)parents->array, (PetscInt *)childids->array));
4246: PetscCall(PetscSectionDestroy(&parentSection));
4247: PetscCall(PetscSFCreate(comm, &pointSF));
4248: /*
4249: These arrays defining the sf are from the p4est library, but the code there shows the leaves being populated in increasing order.
4250: https://gitlab.com/petsc/petsc/merge_requests/2248#note_240186391
4251: */
4252: PetscCall(PetscSFSetGraph(pointSF, pEnd - pStart, (PetscInt)leaves->elem_count, (PetscInt *)leaves->array, PETSC_COPY_VALUES, (PetscSFNode *)remotes->array, PETSC_COPY_VALUES));
4253: PetscCall(DMSetPointSF(newPlex, pointSF));
4254: PetscCall(DMSetPointSF(dm, pointSF));
4255: {
4256: DM coordDM;
4258: PetscCall(DMGetCoordinateDM(newPlex, &coordDM));
4259: PetscCall(DMSetPointSF(coordDM, pointSF));
4260: }
4261: PetscCall(PetscSFDestroy(&pointSF));
4262: sc_array_destroy(points_per_dim);
4263: sc_array_destroy(cone_sizes);
4264: sc_array_destroy(cones);
4265: sc_array_destroy(cone_orientations);
4266: sc_array_destroy(coords);
4267: sc_array_destroy(children);
4268: sc_array_destroy(parents);
4269: sc_array_destroy(childids);
4270: sc_array_destroy(leaves);
4271: sc_array_destroy(remotes);
4273: {
4274: const PetscReal *maxCell, *Lstart, *L;
4276: PetscCall(DMGetPeriodicity(dm, &maxCell, &Lstart, &L));
4277: PetscCall(DMSetPeriodicity(newPlex, maxCell, Lstart, L));
4278: PetscCall(DMPforestLocalizeCoordinates(dm, newPlex));
4279: }
4281: if (overlap > 0) { /* the p4est routine can't set all of the coordinates in its routine if there is overlap */
4282: Vec coordsGlobal, coordsLocal;
4283: const PetscScalar *globalArray;
4284: PetscScalar *localArray;
4285: PetscSF coordSF;
4286: DM coordDM;
4288: PetscCall(DMGetCoordinateDM(newPlex, &coordDM));
4289: PetscCall(DMGetSectionSF(coordDM, &coordSF));
4290: PetscCall(DMGetCoordinates(newPlex, &coordsGlobal));
4291: PetscCall(DMGetCoordinatesLocal(newPlex, &coordsLocal));
4292: PetscCall(VecGetArrayRead(coordsGlobal, &globalArray));
4293: PetscCall(VecGetArray(coordsLocal, &localArray));
4294: PetscCall(PetscSFBcastBegin(coordSF, MPIU_SCALAR, globalArray, localArray, MPI_REPLACE));
4295: PetscCall(PetscSFBcastEnd(coordSF, MPIU_SCALAR, globalArray, localArray, MPI_REPLACE));
4296: PetscCall(VecRestoreArray(coordsLocal, &localArray));
4297: PetscCall(VecRestoreArrayRead(coordsGlobal, &globalArray));
4298: PetscCall(DMSetCoordinatesLocal(newPlex, coordsLocal));
4299: }
4300: PetscCall(DMPforestMapCoordinates(dm, newPlex));
4302: pforest->plex = newPlex;
4304: /* copy labels */
4305: PetscCall(DMPforestLabelsFinalize(dm, newPlex));
4307: if (ghostLabelBase || pforest->ghostName) { /* we have to do this after copying labels because the labels drive the construction of ghost cells */
4308: PetscInt numAdded;
4309: DM newPlexGhosted;
4310: void *ctx;
4312: PetscCall(DMPlexConstructGhostCells(newPlex, pforest->ghostName, &numAdded, &newPlexGhosted));
4313: PetscCall(DMGetApplicationContext(newPlex, &ctx));
4314: PetscCall(DMSetApplicationContext(newPlexGhosted, ctx));
4315: /* we want the sf for the ghost dm to be the one for the p4est dm as well */
4316: PetscCall(DMGetPointSF(newPlexGhosted, &pointSF));
4317: PetscCall(DMSetPointSF(dm, pointSF));
4318: PetscCall(DMDestroy(&newPlex));
4319: PetscCall(DMPlexSetReferenceTree(newPlexGhosted, refTree));
4320: PetscCall(DMForestClearAdaptivityForest_pforest(dm));
4321: newPlex = newPlexGhosted;
4323: /* share the labels back */
4324: PetscCall(DMDestroyLabelLinkList_Internal(dm));
4325: PetscCall(DMCopyLabels(newPlex, dm, PETSC_OWN_POINTER, PETSC_TRUE, DM_COPY_LABELS_FAIL));
4326: pforest->plex = newPlex;
4327: }
4328: PetscCall(DMDestroy(&refTree));
4329: if (dm->setfromoptionscalled) {
4330: PetscObjectOptionsBegin((PetscObject)newPlex);
4331: PetscCall(DMSetFromOptions_NonRefinement_Plex(newPlex, PetscOptionsObject));
4332: PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)newPlex, PetscOptionsObject));
4333: PetscOptionsEnd();
4334: }
4335: PetscCall(DMViewFromOptions(newPlex, NULL, "-dm_p4est_plex_view"));
4336: {
4337: DM cdm;
4338: PetscSection coordsSec;
4339: Vec coords;
4340: PetscInt cDim;
4342: PetscCall(DMGetCoordinateDim(newPlex, &cDim));
4343: PetscCall(DMGetCoordinateSection(newPlex, &coordsSec));
4344: PetscCall(DMSetCoordinateSection(dm, cDim, coordsSec));
4345: PetscCall(DMGetCoordinatesLocal(newPlex, &coords));
4346: PetscCall(DMSetCoordinatesLocal(dm, coords));
4347: PetscCall(DMGetCoordinateDM(newPlex, &cdm));
4348: if (cdm) {
4349: PetscFE fe;
4350: #if !defined(P4_TO_P8)
4351: DMPolytopeType celltype = DM_POLYTOPE_QUADRILATERAL;
4352: #else
4353: DMPolytopeType celltype = DM_POLYTOPE_HEXAHEDRON;
4354: #endif
4356: PetscCall(PetscFECreateLagrangeByCell(PETSC_COMM_SELF, dim, dim, celltype, 1, PETSC_DEFAULT, &fe));
4357: PetscCall(DMSetField(cdm, 0, NULL, (PetscObject)fe));
4358: PetscCall(PetscFEDestroy(&fe));
4359: PetscCall(DMCreateDS(cdm));
4360: }
4361: PetscCall(DMGetCellCoordinateDM(newPlex, &cdm));
4362: if (cdm) PetscCall(DMSetCellCoordinateDM(dm, cdm));
4363: PetscCall(DMGetCellCoordinateSection(newPlex, &coordsSec));
4364: if (coordsSec) PetscCall(DMSetCellCoordinateSection(dm, cDim, coordsSec));
4365: PetscCall(DMGetCellCoordinatesLocal(newPlex, &coords));
4366: if (coords) PetscCall(DMSetCellCoordinatesLocal(dm, coords));
4367: }
4368: } else {
4369: PetscCall(DMCopyLabels(dm, pforest->plex, PETSC_OWN_POINTER, PETSC_FALSE, DM_COPY_LABELS_REPLACE));
4370: }
4371: newPlex = pforest->plex;
4372: if (plex) {
4373: PetscCall(DMClone(newPlex, plex));
4374: #if 0
4375: PetscCall(DMGetCoordinateDM(newPlex,&coordDM));
4376: PetscCall(DMSetCoordinateDM(*plex,coordDM));
4377: PetscCall(DMGetCellCoordinateDM(newPlex,&coordDM));
4378: PetscCall(DMSetCellCoordinateDM(*plex,coordDM));
4379: #endif
4380: PetscCall(DMShareDiscretization(dm, *plex));
4381: }
4382: PetscFunctionReturn(PETSC_SUCCESS);
4383: }
4385: static PetscErrorCode DMSetFromOptions_pforest(DM dm, PetscOptionItems PetscOptionsObject)
4386: {
4387: DM_Forest_pforest *pforest = (DM_Forest_pforest *)((DM_Forest *)dm->data)->data;
4388: char stringBuffer[256];
4389: PetscBool flg;
4391: PetscFunctionBegin;
4392: PetscCall(DMSetFromOptions_Forest(dm, PetscOptionsObject));
4393: PetscOptionsHeadBegin(PetscOptionsObject, "DM" P4EST_STRING " options");
4394: PetscCall(PetscOptionsBool("-dm_p4est_partition_for_coarsening", "partition forest to allow for coarsening", "DMP4estSetPartitionForCoarsening", pforest->partition_for_coarsening, &pforest->partition_for_coarsening, NULL));
4395: PetscCall(PetscOptionsString("-dm_p4est_ghost_label_name", "the name of the ghost label when converting from a DMPlex", NULL, NULL, stringBuffer, sizeof(stringBuffer), &flg));
4396: PetscOptionsHeadEnd();
4397: if (flg) {
4398: PetscCall(PetscFree(pforest->ghostName));
4399: PetscCall(PetscStrallocpy(stringBuffer, &pforest->ghostName));
4400: }
4401: PetscFunctionReturn(PETSC_SUCCESS);
4402: }
4404: #if !defined(P4_TO_P8)
4405: #define DMPforestGetPartitionForCoarsening DMP4estGetPartitionForCoarsening
4406: #define DMPforestSetPartitionForCoarsening DMP4estSetPartitionForCoarsening
4407: #else
4408: #define DMPforestGetPartitionForCoarsening DMP8estGetPartitionForCoarsening
4409: #define DMPforestSetPartitionForCoarsening DMP8estSetPartitionForCoarsening
4410: #endif
4412: PETSC_EXTERN PetscErrorCode DMPforestGetPartitionForCoarsening(DM dm, PetscBool *flg)
4413: {
4414: DM_Forest_pforest *pforest;
4416: PetscFunctionBegin;
4418: pforest = (DM_Forest_pforest *)((DM_Forest *)dm->data)->data;
4419: *flg = pforest->partition_for_coarsening;
4420: PetscFunctionReturn(PETSC_SUCCESS);
4421: }
4423: PETSC_EXTERN PetscErrorCode DMPforestSetPartitionForCoarsening(DM dm, PetscBool flg)
4424: {
4425: DM_Forest_pforest *pforest;
4427: PetscFunctionBegin;
4429: pforest = (DM_Forest_pforest *)((DM_Forest *)dm->data)->data;
4430: pforest->partition_for_coarsening = flg;
4431: PetscFunctionReturn(PETSC_SUCCESS);
4432: }
4434: static PetscErrorCode DMPforestGetPlex(DM dm, DM *plex)
4435: {
4436: DM_Forest_pforest *pforest;
4438: PetscFunctionBegin;
4439: if (plex) *plex = NULL;
4440: PetscCall(DMSetUp(dm));
4441: pforest = (DM_Forest_pforest *)((DM_Forest *)dm->data)->data;
4442: if (!pforest->plex) PetscCall(DMConvert_pforest_plex(dm, DMPLEX, NULL));
4443: PetscCall(DMShareDiscretization(dm, pforest->plex));
4444: if (plex) *plex = pforest->plex;
4445: PetscFunctionReturn(PETSC_SUCCESS);
4446: }
4448: #define DMCreateInterpolation_pforest _append_pforest(DMCreateInterpolation)
4449: static PetscErrorCode DMCreateInterpolation_pforest(DM dmCoarse, DM dmFine, Mat *interpolation, Vec *scaling)
4450: {
4451: PetscSection gsc, gsf;
4452: PetscInt m, n;
4453: DM cdm;
4455: PetscFunctionBegin;
4456: PetscCall(DMGetGlobalSection(dmFine, &gsf));
4457: PetscCall(PetscSectionGetConstrainedStorageSize(gsf, &m));
4458: PetscCall(DMGetGlobalSection(dmCoarse, &gsc));
4459: PetscCall(PetscSectionGetConstrainedStorageSize(gsc, &n));
4461: PetscCall(MatCreate(PetscObjectComm((PetscObject)dmFine), interpolation));
4462: PetscCall(MatSetSizes(*interpolation, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
4463: PetscCall(MatSetType(*interpolation, MATAIJ));
4465: PetscCall(DMGetCoarseDM(dmFine, &cdm));
4466: PetscCheck(cdm == dmCoarse, PetscObjectComm((PetscObject)dmFine), PETSC_ERR_SUP, "Only interpolation from coarse DM for now");
4468: {
4469: DM plexF, plexC;
4470: PetscSF sf;
4471: PetscInt *cids;
4472: PetscInt dofPerDim[4] = {1, 1, 1, 1};
4474: PetscCall(DMPforestGetPlex(dmCoarse, &plexC));
4475: PetscCall(DMPforestGetPlex(dmFine, &plexF));
4476: PetscCall(DMPforestGetTransferSF_Internal(dmCoarse, dmFine, dofPerDim, &sf, PETSC_TRUE, &cids));
4477: PetscCall(PetscSFSetUp(sf));
4478: PetscCall(DMPlexComputeInterpolatorTree(plexC, plexF, sf, cids, *interpolation));
4479: PetscCall(PetscSFDestroy(&sf));
4480: PetscCall(PetscFree(cids));
4481: }
4482: PetscCall(MatViewFromOptions(*interpolation, NULL, "-interp_mat_view"));
4483: /* Use naive scaling */
4484: PetscCall(DMCreateInterpolationScale(dmCoarse, dmFine, *interpolation, scaling));
4485: PetscFunctionReturn(PETSC_SUCCESS);
4486: }
4488: #define DMCreateInjection_pforest _append_pforest(DMCreateInjection)
4489: static PetscErrorCode DMCreateInjection_pforest(DM dmCoarse, DM dmFine, Mat *injection)
4490: {
4491: PetscSection gsc, gsf;
4492: PetscInt m, n;
4493: DM cdm;
4495: PetscFunctionBegin;
4496: PetscCall(DMGetGlobalSection(dmFine, &gsf));
4497: PetscCall(PetscSectionGetConstrainedStorageSize(gsf, &n));
4498: PetscCall(DMGetGlobalSection(dmCoarse, &gsc));
4499: PetscCall(PetscSectionGetConstrainedStorageSize(gsc, &m));
4501: PetscCall(MatCreate(PetscObjectComm((PetscObject)dmFine), injection));
4502: PetscCall(MatSetSizes(*injection, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
4503: PetscCall(MatSetType(*injection, MATAIJ));
4505: PetscCall(DMGetCoarseDM(dmFine, &cdm));
4506: PetscCheck(cdm == dmCoarse, PetscObjectComm((PetscObject)dmFine), PETSC_ERR_SUP, "Only injection to coarse DM for now");
4508: {
4509: DM plexF, plexC;
4510: PetscSF sf;
4511: PetscInt *cids;
4512: PetscInt dofPerDim[4] = {1, 1, 1, 1};
4514: PetscCall(DMPforestGetPlex(dmCoarse, &plexC));
4515: PetscCall(DMPforestGetPlex(dmFine, &plexF));
4516: PetscCall(DMPforestGetTransferSF_Internal(dmCoarse, dmFine, dofPerDim, &sf, PETSC_TRUE, &cids));
4517: PetscCall(PetscSFSetUp(sf));
4518: PetscCall(DMPlexComputeInjectorTree(plexC, plexF, sf, cids, *injection));
4519: PetscCall(PetscSFDestroy(&sf));
4520: PetscCall(PetscFree(cids));
4521: }
4522: PetscCall(MatViewFromOptions(*injection, NULL, "-inject_mat_view"));
4523: /* Use naive scaling */
4524: PetscFunctionReturn(PETSC_SUCCESS);
4525: }
4527: #define DMForestTransferVecFromBase_pforest _append_pforest(DMForestTransferVecFromBase)
4528: static PetscErrorCode DMForestTransferVecFromBase_pforest(DM dm, Vec vecIn, Vec vecOut)
4529: {
4530: DM dmIn, dmVecIn, base, basec, plex, coarseDM;
4531: DM *hierarchy;
4532: PetscSF sfRed = NULL;
4533: PetscDS ds;
4534: Vec vecInLocal, vecOutLocal;
4535: DMLabel subpointMap;
4536: PetscInt minLevel, mh, n_hi, i;
4537: PetscBool hiforest, *hierarchy_forest;
4539: PetscFunctionBegin;
4540: PetscCall(VecGetDM(vecIn, &dmVecIn));
4541: PetscCall(DMGetDS(dmVecIn, &ds));
4542: PetscCheck(ds, PetscObjectComm((PetscObject)dmVecIn), PETSC_ERR_SUP, "Cannot transfer without a PetscDS object");
4543: { /* we cannot stick user contexts into function callbacks for DMProjectFieldLocal! */
4544: PetscSection section;
4545: PetscInt Nf;
4547: PetscCall(DMGetLocalSection(dmVecIn, §ion));
4548: PetscCall(PetscSectionGetNumFields(section, &Nf));
4549: PetscCheck(Nf <= 3, PetscObjectComm((PetscObject)dmVecIn), PETSC_ERR_SUP, "Number of fields %" PetscInt_FMT " are currently not supported! Send an email at petsc-dev@mcs.anl.gov", Nf);
4550: }
4551: PetscCall(DMForestGetMinimumRefinement(dm, &minLevel));
4552: PetscCheck(!minLevel, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Cannot transfer with minimum refinement set to %" PetscInt_FMT ". Rerun with DMForestSetMinimumRefinement(dm,0)", minLevel);
4553: PetscCall(DMForestGetBaseDM(dm, &base));
4554: PetscCheck(base, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Missing base DM");
4556: PetscCall(VecSet(vecOut, 0.0));
4557: if (dmVecIn == base) { /* sequential runs */
4558: PetscCall(PetscObjectReference((PetscObject)vecIn));
4559: } else {
4560: PetscSection secIn, secInRed;
4561: Vec vecInRed, vecInLocal;
4563: PetscCall(PetscObjectQuery((PetscObject)base, "_base_migration_sf", (PetscObject *)&sfRed));
4564: PetscCheck(sfRed, PETSC_COMM_SELF, PETSC_ERR_SUP, "Not the DM set with DMForestSetBaseDM()");
4565: PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dmVecIn), &secInRed));
4566: PetscCall(VecCreate(PETSC_COMM_SELF, &vecInRed));
4567: PetscCall(DMGetLocalSection(dmVecIn, &secIn));
4568: PetscCall(DMGetLocalVector(dmVecIn, &vecInLocal));
4569: PetscCall(DMGlobalToLocalBegin(dmVecIn, vecIn, INSERT_VALUES, vecInLocal));
4570: PetscCall(DMGlobalToLocalEnd(dmVecIn, vecIn, INSERT_VALUES, vecInLocal));
4571: PetscCall(DMPlexDistributeField(dmVecIn, sfRed, secIn, vecInLocal, secInRed, vecInRed));
4572: PetscCall(DMRestoreLocalVector(dmVecIn, &vecInLocal));
4573: PetscCall(PetscSectionDestroy(&secInRed));
4574: vecIn = vecInRed;
4575: }
4577: /* we first search through the AdaptivityForest hierarchy
4578: once we found the first disconnected forest, we upsweep the DM hierarchy */
4579: hiforest = PETSC_TRUE;
4581: /* upsweep to the coarsest DM */
4582: n_hi = 0;
4583: coarseDM = dm;
4584: do {
4585: PetscBool isforest;
4587: dmIn = coarseDM;
4588: /* need to call DMSetUp to have the hierarchy recursively setup */
4589: PetscCall(DMSetUp(dmIn));
4590: PetscCall(DMIsForest(dmIn, &isforest));
4591: PetscCheck(isforest, PetscObjectComm((PetscObject)dmIn), PETSC_ERR_SUP, "Cannot currently transfer through a mixed hierarchy! Found DM type %s", ((PetscObject)dmIn)->type_name);
4592: coarseDM = NULL;
4593: if (hiforest) PetscCall(DMForestGetAdaptivityForest(dmIn, &coarseDM));
4594: if (!coarseDM) { /* DMForest hierarchy ended, we keep upsweeping through the DM hierarchy */
4595: hiforest = PETSC_FALSE;
4596: PetscCall(DMGetCoarseDM(dmIn, &coarseDM));
4597: }
4598: n_hi++;
4599: } while (coarseDM);
4601: PetscCall(PetscMalloc2(n_hi, &hierarchy, n_hi, &hierarchy_forest));
4603: i = 0;
4604: hiforest = PETSC_TRUE;
4605: coarseDM = dm;
4606: do {
4607: dmIn = coarseDM;
4608: coarseDM = NULL;
4609: if (hiforest) PetscCall(DMForestGetAdaptivityForest(dmIn, &coarseDM));
4610: if (!coarseDM) { /* DMForest hierarchy ended, we keep upsweeping through the DM hierarchy */
4611: hiforest = PETSC_FALSE;
4612: PetscCall(DMGetCoarseDM(dmIn, &coarseDM));
4613: }
4614: i++;
4615: hierarchy[n_hi - i] = dmIn;
4616: } while (coarseDM);
4618: /* project base vector on the coarsest forest (minimum refinement = 0) */
4619: PetscCall(DMPforestGetPlex(dmIn, &plex));
4621: /* Check this plex is compatible with the base */
4622: {
4623: IS gnum[2];
4624: PetscInt gncells[2];
4626: PetscCall(DMPlexGetCellNumbering(base, &gnum[0]));
4627: PetscCall(DMPlexGetCellNumbering(plex, &gnum[1]));
4628: PetscCall(ISGetMinMax(gnum[0], NULL, &gncells[0]));
4629: PetscCall(ISGetMinMax(gnum[1], NULL, &gncells[1]));
4630: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, gncells, 2, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
4631: PetscCheck(gncells[0] == gncells[1], PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Invalid number of base cells! Expected %" PetscInt_FMT ", found %" PetscInt_FMT, gncells[0] + 1, gncells[1] + 1);
4632: }
4634: PetscCall(DMGetLabel(dmIn, "_forest_base_subpoint_map", &subpointMap));
4635: PetscCheck(subpointMap, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Missing _forest_base_subpoint_map label");
4637: PetscCall(DMPlexGetMaxProjectionHeight(base, &mh));
4638: PetscCall(DMPlexSetMaxProjectionHeight(plex, mh));
4640: PetscCall(DMClone(base, &basec));
4641: PetscCall(DMCopyDisc(dmVecIn, basec));
4642: if (sfRed) {
4643: PetscCall(PetscObjectReference((PetscObject)vecIn));
4644: vecInLocal = vecIn;
4645: } else {
4646: PetscCall(DMCreateLocalVector(basec, &vecInLocal));
4647: PetscCall(DMGlobalToLocalBegin(basec, vecIn, INSERT_VALUES, vecInLocal));
4648: PetscCall(DMGlobalToLocalEnd(basec, vecIn, INSERT_VALUES, vecInLocal));
4649: }
4651: PetscCall(DMGetLocalVector(dmIn, &vecOutLocal));
4652: { /* get degrees of freedom ordered onto dmIn */
4653: PetscSF basetocoarse;
4654: PetscInt bStart, bEnd, nroots;
4655: PetscInt iStart, iEnd, nleaves, leaf;
4656: PetscMPIInt rank;
4657: PetscSFNode *remotes;
4658: PetscSection secIn, secOut;
4659: PetscInt *remoteOffsets;
4660: PetscSF transferSF;
4661: const PetscScalar *inArray;
4662: PetscScalar *outArray;
4664: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)basec), &rank));
4665: PetscCall(DMPlexGetChart(basec, &bStart, &bEnd));
4666: nroots = PetscMax(bEnd - bStart, 0);
4667: PetscCall(DMPlexGetChart(plex, &iStart, &iEnd));
4668: nleaves = PetscMax(iEnd - iStart, 0);
4670: PetscCall(PetscMalloc1(nleaves, &remotes));
4671: for (leaf = iStart; leaf < iEnd; leaf++) {
4672: PetscInt index;
4674: remotes[leaf - iStart].rank = rank;
4675: PetscCall(DMLabelGetValue(subpointMap, leaf, &index));
4676: remotes[leaf - iStart].index = index;
4677: }
4679: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)basec), &basetocoarse));
4680: PetscCall(PetscSFSetGraph(basetocoarse, nroots, nleaves, NULL, PETSC_OWN_POINTER, remotes, PETSC_OWN_POINTER));
4681: PetscCall(PetscSFSetUp(basetocoarse));
4682: PetscCall(DMGetLocalSection(basec, &secIn));
4683: PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dmIn), &secOut));
4684: PetscCall(PetscSFDistributeSection(basetocoarse, secIn, &remoteOffsets, secOut));
4685: PetscCall(PetscSFCreateSectionSF(basetocoarse, secIn, remoteOffsets, secOut, &transferSF));
4686: PetscCall(PetscFree(remoteOffsets));
4687: PetscCall(VecGetArrayWrite(vecOutLocal, &outArray));
4688: PetscCall(VecGetArrayRead(vecInLocal, &inArray));
4689: PetscCall(PetscSFBcastBegin(transferSF, MPIU_SCALAR, inArray, outArray, MPI_REPLACE));
4690: PetscCall(PetscSFBcastEnd(transferSF, MPIU_SCALAR, inArray, outArray, MPI_REPLACE));
4691: PetscCall(VecRestoreArrayRead(vecInLocal, &inArray));
4692: PetscCall(VecRestoreArrayWrite(vecOutLocal, &outArray));
4693: PetscCall(PetscSFDestroy(&transferSF));
4694: PetscCall(PetscSectionDestroy(&secOut));
4695: PetscCall(PetscSFDestroy(&basetocoarse));
4696: }
4697: PetscCall(VecDestroy(&vecInLocal));
4698: PetscCall(DMDestroy(&basec));
4699: PetscCall(VecDestroy(&vecIn));
4701: /* output */
4702: if (n_hi > 1) { /* downsweep the stored hierarchy */
4703: Vec vecOut1, vecOut2;
4704: DM fineDM;
4706: PetscCall(DMGetGlobalVector(dmIn, &vecOut1));
4707: PetscCall(DMLocalToGlobal(dmIn, vecOutLocal, INSERT_VALUES, vecOut1));
4708: PetscCall(DMRestoreLocalVector(dmIn, &vecOutLocal));
4709: for (i = 1; i < n_hi - 1; i++) {
4710: fineDM = hierarchy[i];
4711: PetscCall(DMGetGlobalVector(fineDM, &vecOut2));
4712: PetscCall(DMForestTransferVec(dmIn, vecOut1, fineDM, vecOut2, PETSC_TRUE, 0.0));
4713: PetscCall(DMRestoreGlobalVector(dmIn, &vecOut1));
4714: vecOut1 = vecOut2;
4715: dmIn = fineDM;
4716: }
4717: PetscCall(DMForestTransferVec(dmIn, vecOut1, dm, vecOut, PETSC_TRUE, 0.0));
4718: PetscCall(DMRestoreGlobalVector(dmIn, &vecOut1));
4719: } else {
4720: PetscCall(DMLocalToGlobal(dmIn, vecOutLocal, INSERT_VALUES, vecOut));
4721: PetscCall(DMRestoreLocalVector(dmIn, &vecOutLocal));
4722: }
4723: PetscCall(PetscFree2(hierarchy, hierarchy_forest));
4724: PetscFunctionReturn(PETSC_SUCCESS);
4725: }
4727: #define DMForestTransferVec_pforest _append_pforest(DMForestTransferVec)
4728: static PetscErrorCode DMForestTransferVec_pforest(DM dmIn, Vec vecIn, DM dmOut, Vec vecOut, PetscBool useBCs, PetscReal time)
4729: {
4730: DM adaptIn, adaptOut, plexIn, plexOut;
4731: DM_Forest *forestIn, *forestOut, *forestAdaptIn, *forestAdaptOut;
4732: PetscInt dofPerDim[] = {1, 1, 1, 1};
4733: PetscSF inSF = NULL, outSF = NULL;
4734: PetscInt *inCids = NULL, *outCids = NULL;
4735: DMAdaptFlag purposeIn, purposeOut;
4737: PetscFunctionBegin;
4738: forestOut = (DM_Forest *)dmOut->data;
4739: forestIn = (DM_Forest *)dmIn->data;
4741: PetscCall(DMForestGetAdaptivityForest(dmOut, &adaptOut));
4742: PetscCall(DMForestGetAdaptivityPurpose(dmOut, &purposeOut));
4743: forestAdaptOut = adaptOut ? (DM_Forest *)adaptOut->data : NULL;
4745: PetscCall(DMForestGetAdaptivityForest(dmIn, &adaptIn));
4746: PetscCall(DMForestGetAdaptivityPurpose(dmIn, &purposeIn));
4747: forestAdaptIn = adaptIn ? (DM_Forest *)adaptIn->data : NULL;
4749: if (forestAdaptOut == forestIn) {
4750: switch (purposeOut) {
4751: case DM_ADAPT_REFINE:
4752: PetscCall(DMPforestGetTransferSF_Internal(dmIn, dmOut, dofPerDim, &inSF, PETSC_TRUE, &inCids));
4753: PetscCall(PetscSFSetUp(inSF));
4754: break;
4755: case DM_ADAPT_COARSEN:
4756: case DM_ADAPT_COARSEN_LAST:
4757: PetscCall(DMPforestGetTransferSF_Internal(dmOut, dmIn, dofPerDim, &outSF, PETSC_TRUE, &outCids));
4758: PetscCall(PetscSFSetUp(outSF));
4759: break;
4760: default:
4761: PetscCall(DMPforestGetTransferSF_Internal(dmIn, dmOut, dofPerDim, &inSF, PETSC_TRUE, &inCids));
4762: PetscCall(DMPforestGetTransferSF_Internal(dmOut, dmIn, dofPerDim, &outSF, PETSC_FALSE, &outCids));
4763: PetscCall(PetscSFSetUp(inSF));
4764: PetscCall(PetscSFSetUp(outSF));
4765: }
4766: } else if (forestAdaptIn == forestOut) {
4767: switch (purposeIn) {
4768: case DM_ADAPT_REFINE:
4769: PetscCall(DMPforestGetTransferSF_Internal(dmOut, dmIn, dofPerDim, &outSF, PETSC_TRUE, &inCids));
4770: PetscCall(PetscSFSetUp(outSF));
4771: break;
4772: case DM_ADAPT_COARSEN:
4773: case DM_ADAPT_COARSEN_LAST:
4774: PetscCall(DMPforestGetTransferSF_Internal(dmIn, dmOut, dofPerDim, &inSF, PETSC_TRUE, &inCids));
4775: PetscCall(PetscSFSetUp(inSF));
4776: break;
4777: default:
4778: PetscCall(DMPforestGetTransferSF_Internal(dmIn, dmOut, dofPerDim, &inSF, PETSC_TRUE, &inCids));
4779: PetscCall(DMPforestGetTransferSF_Internal(dmOut, dmIn, dofPerDim, &outSF, PETSC_FALSE, &outCids));
4780: PetscCall(PetscSFSetUp(inSF));
4781: PetscCall(PetscSFSetUp(outSF));
4782: }
4783: } else SETERRQ(PetscObjectComm((PetscObject)dmIn), PETSC_ERR_SUP, "Only support transfer from pre-adaptivity to post-adaptivity right now");
4784: PetscCall(DMPforestGetPlex(dmIn, &plexIn));
4785: PetscCall(DMPforestGetPlex(dmOut, &plexOut));
4787: PetscCall(DMPlexTransferVecTree(plexIn, vecIn, plexOut, vecOut, inSF, outSF, inCids, outCids, useBCs, time));
4788: PetscCall(PetscFree(inCids));
4789: PetscCall(PetscFree(outCids));
4790: PetscCall(PetscSFDestroy(&inSF));
4791: PetscCall(PetscSFDestroy(&outSF));
4792: PetscCall(PetscFree(inCids));
4793: PetscCall(PetscFree(outCids));
4794: PetscFunctionReturn(PETSC_SUCCESS);
4795: }
4797: #define DMCreateCoordinateDM_pforest _append_pforest(DMCreateCoordinateDM)
4798: static PetscErrorCode DMCreateCoordinateDM_pforest(DM dm, DM *cdm)
4799: {
4800: DM plex;
4802: PetscFunctionBegin;
4804: PetscCall(DMPforestGetPlex(dm, &plex));
4805: PetscCall(DMGetCoordinateDM(plex, cdm));
4806: PetscCall(PetscObjectReference((PetscObject)*cdm));
4807: PetscFunctionReturn(PETSC_SUCCESS);
4808: }
4810: #define VecViewLocal_pforest _append_pforest(VecViewLocal)
4811: static PetscErrorCode VecViewLocal_pforest(Vec vec, PetscViewer viewer)
4812: {
4813: DM dm, plex;
4815: PetscFunctionBegin;
4816: PetscCall(VecGetDM(vec, &dm));
4817: PetscCall(PetscObjectReference((PetscObject)dm));
4818: PetscCall(DMPforestGetPlex(dm, &plex));
4819: PetscCall(VecSetDM(vec, plex));
4820: PetscCall(VecView_Plex_Local(vec, viewer));
4821: PetscCall(VecSetDM(vec, dm));
4822: PetscCall(DMDestroy(&dm));
4823: PetscFunctionReturn(PETSC_SUCCESS);
4824: }
4826: #define VecView_pforest _append_pforest(VecView)
4827: static PetscErrorCode VecView_pforest(Vec vec, PetscViewer viewer)
4828: {
4829: DM dm, plex;
4831: PetscFunctionBegin;
4832: PetscCall(VecGetDM(vec, &dm));
4833: PetscCall(PetscObjectReference((PetscObject)dm));
4834: PetscCall(DMPforestGetPlex(dm, &plex));
4835: PetscCall(VecSetDM(vec, plex));
4836: PetscCall(VecView_Plex(vec, viewer));
4837: PetscCall(VecSetDM(vec, dm));
4838: PetscCall(DMDestroy(&dm));
4839: PetscFunctionReturn(PETSC_SUCCESS);
4840: }
4842: #define VecView_pforest_Native _infix_pforest(VecView, _Native)
4843: static PetscErrorCode VecView_pforest_Native(Vec vec, PetscViewer viewer)
4844: {
4845: DM dm, plex;
4847: PetscFunctionBegin;
4848: PetscCall(VecGetDM(vec, &dm));
4849: PetscCall(PetscObjectReference((PetscObject)dm));
4850: PetscCall(DMPforestGetPlex(dm, &plex));
4851: PetscCall(VecSetDM(vec, plex));
4852: PetscCall(VecView_Plex_Native(vec, viewer));
4853: PetscCall(VecSetDM(vec, dm));
4854: PetscCall(DMDestroy(&dm));
4855: PetscFunctionReturn(PETSC_SUCCESS);
4856: }
4858: #define VecLoad_pforest _append_pforest(VecLoad)
4859: static PetscErrorCode VecLoad_pforest(Vec vec, PetscViewer viewer)
4860: {
4861: DM dm, plex;
4863: PetscFunctionBegin;
4864: PetscCall(VecGetDM(vec, &dm));
4865: PetscCall(PetscObjectReference((PetscObject)dm));
4866: PetscCall(DMPforestGetPlex(dm, &plex));
4867: PetscCall(VecSetDM(vec, plex));
4868: PetscCall(VecLoad_Plex(vec, viewer));
4869: PetscCall(VecSetDM(vec, dm));
4870: PetscCall(DMDestroy(&dm));
4871: PetscFunctionReturn(PETSC_SUCCESS);
4872: }
4874: #define VecLoad_pforest_Native _infix_pforest(VecLoad, _Native)
4875: static PetscErrorCode VecLoad_pforest_Native(Vec vec, PetscViewer viewer)
4876: {
4877: DM dm, plex;
4879: PetscFunctionBegin;
4880: PetscCall(VecGetDM(vec, &dm));
4881: PetscCall(PetscObjectReference((PetscObject)dm));
4882: PetscCall(DMPforestGetPlex(dm, &plex));
4883: PetscCall(VecSetDM(vec, plex));
4884: PetscCall(VecLoad_Plex_Native(vec, viewer));
4885: PetscCall(VecSetDM(vec, dm));
4886: PetscCall(DMDestroy(&dm));
4887: PetscFunctionReturn(PETSC_SUCCESS);
4888: }
4890: #define DMCreateGlobalVector_pforest _append_pforest(DMCreateGlobalVector)
4891: static PetscErrorCode DMCreateGlobalVector_pforest(DM dm, Vec *vec)
4892: {
4893: PetscFunctionBegin;
4894: PetscCall(DMCreateGlobalVector_Section_Private(dm, vec));
4895: /* PetscCall(VecSetOperation(*vec, VECOP_DUPLICATE, (void(*)(void)) VecDuplicate_MPI_DM)); */
4896: PetscCall(VecSetOperation(*vec, VECOP_VIEW, (PetscErrorCodeFn *)VecView_pforest));
4897: PetscCall(VecSetOperation(*vec, VECOP_VIEWNATIVE, (PetscErrorCodeFn *)VecView_pforest_Native));
4898: PetscCall(VecSetOperation(*vec, VECOP_LOAD, (PetscErrorCodeFn *)VecLoad_pforest));
4899: PetscCall(VecSetOperation(*vec, VECOP_LOADNATIVE, (PetscErrorCodeFn *)VecLoad_pforest_Native));
4900: PetscFunctionReturn(PETSC_SUCCESS);
4901: }
4903: #define DMCreateLocalVector_pforest _append_pforest(DMCreateLocalVector)
4904: static PetscErrorCode DMCreateLocalVector_pforest(DM dm, Vec *vec)
4905: {
4906: PetscFunctionBegin;
4907: PetscCall(DMCreateLocalVector_Section_Private(dm, vec));
4908: PetscCall(VecSetOperation(*vec, VECOP_VIEW, (PetscErrorCodeFn *)VecViewLocal_pforest));
4909: PetscFunctionReturn(PETSC_SUCCESS);
4910: }
4912: #define DMCreateMatrix_pforest _append_pforest(DMCreateMatrix)
4913: static PetscErrorCode DMCreateMatrix_pforest(DM dm, Mat *mat)
4914: {
4915: DM plex;
4917: PetscFunctionBegin;
4919: PetscCall(DMPforestGetPlex(dm, &plex));
4920: if (plex->prealloc_only != dm->prealloc_only) plex->prealloc_only = dm->prealloc_only; /* maybe this should go into forest->plex */
4921: PetscCall(DMSetMatType(plex, dm->mattype));
4922: PetscCall(DMCreateMatrix(plex, mat));
4923: PetscCall(MatSetDM(*mat, dm));
4924: PetscFunctionReturn(PETSC_SUCCESS);
4925: }
4927: #define DMProjectFunctionLocal_pforest _append_pforest(DMProjectFunctionLocal)
4928: static PetscErrorCode DMProjectFunctionLocal_pforest(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, InsertMode mode, Vec localX)
4929: {
4930: DM plex;
4932: PetscFunctionBegin;
4934: PetscCall(DMPforestGetPlex(dm, &plex));
4935: PetscCall(DMProjectFunctionLocal(plex, time, funcs, ctxs, mode, localX));
4936: PetscFunctionReturn(PETSC_SUCCESS);
4937: }
4939: #define DMProjectFunctionLabelLocal_pforest _append_pforest(DMProjectFunctionLabelLocal)
4940: static PetscErrorCode DMProjectFunctionLabelLocal_pforest(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscInt Ncc, const PetscInt comps[], PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, InsertMode mode, Vec localX)
4941: {
4942: DM plex;
4944: PetscFunctionBegin;
4946: PetscCall(DMPforestGetPlex(dm, &plex));
4947: PetscCall(DMProjectFunctionLabelLocal(plex, time, label, numIds, ids, Ncc, comps, funcs, ctxs, mode, localX));
4948: PetscFunctionReturn(PETSC_SUCCESS);
4949: }
4951: #define DMProjectFieldLocal_pforest _append_pforest(DMProjectFieldLocal)
4952: PetscErrorCode DMProjectFieldLocal_pforest(DM dm, PetscReal time, Vec localU, void (**funcs)(PetscInt, PetscInt, PetscInt, const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[], const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[], PetscReal, const PetscReal[], PetscInt, const PetscScalar[], PetscScalar[]), InsertMode mode, Vec localX)
4953: {
4954: DM plex;
4956: PetscFunctionBegin;
4958: PetscCall(DMPforestGetPlex(dm, &plex));
4959: PetscCall(DMProjectFieldLocal(plex, time, localU, funcs, mode, localX));
4960: PetscFunctionReturn(PETSC_SUCCESS);
4961: }
4963: #define DMComputeL2Diff_pforest _append_pforest(DMComputeL2Diff)
4964: PetscErrorCode DMComputeL2Diff_pforest(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
4965: {
4966: DM plex;
4968: PetscFunctionBegin;
4970: PetscCall(DMPforestGetPlex(dm, &plex));
4971: PetscCall(DMComputeL2Diff(plex, time, funcs, ctxs, X, diff));
4972: PetscFunctionReturn(PETSC_SUCCESS);
4973: }
4975: #define DMComputeL2FieldDiff_pforest _append_pforest(DMComputeL2FieldDiff)
4976: PetscErrorCode DMComputeL2FieldDiff_pforest(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
4977: {
4978: DM plex;
4980: PetscFunctionBegin;
4982: PetscCall(DMPforestGetPlex(dm, &plex));
4983: PetscCall(DMComputeL2FieldDiff(plex, time, funcs, ctxs, X, diff));
4984: PetscFunctionReturn(PETSC_SUCCESS);
4985: }
4987: #define DMCreatelocalsection_pforest _append_pforest(DMCreatelocalsection)
4988: static PetscErrorCode DMCreatelocalsection_pforest(DM dm)
4989: {
4990: DM plex;
4991: PetscSection section;
4993: PetscFunctionBegin;
4995: PetscCall(DMPforestGetPlex(dm, &plex));
4996: PetscCall(DMGetLocalSection(plex, §ion));
4997: PetscCall(DMSetLocalSection(dm, section));
4998: PetscFunctionReturn(PETSC_SUCCESS);
4999: }
5001: #define DMCreateDefaultConstraints_pforest _append_pforest(DMCreateDefaultConstraints)
5002: static PetscErrorCode DMCreateDefaultConstraints_pforest(DM dm)
5003: {
5004: DM plex;
5005: Mat mat;
5006: Vec bias;
5007: PetscSection section;
5009: PetscFunctionBegin;
5011: PetscCall(DMPforestGetPlex(dm, &plex));
5012: PetscCall(DMGetDefaultConstraints(plex, §ion, &mat, &bias));
5013: PetscCall(DMSetDefaultConstraints(dm, section, mat, bias));
5014: PetscFunctionReturn(PETSC_SUCCESS);
5015: }
5017: #define DMGetDimPoints_pforest _append_pforest(DMGetDimPoints)
5018: static PetscErrorCode DMGetDimPoints_pforest(DM dm, PetscInt dim, PetscInt *cStart, PetscInt *cEnd)
5019: {
5020: DM plex;
5022: PetscFunctionBegin;
5024: PetscCall(DMPforestGetPlex(dm, &plex));
5025: PetscCall(DMGetDimPoints(plex, dim, cStart, cEnd));
5026: PetscFunctionReturn(PETSC_SUCCESS);
5027: }
5029: /* Need to forward declare */
5030: #define DMInitialize_pforest _append_pforest(DMInitialize)
5031: static PetscErrorCode DMInitialize_pforest(DM dm);
5033: #define DMClone_pforest _append_pforest(DMClone)
5034: static PetscErrorCode DMClone_pforest(DM dm, DM *newdm)
5035: {
5036: PetscFunctionBegin;
5037: PetscCall(DMClone_Forest(dm, newdm));
5038: PetscCall(DMInitialize_pforest(*newdm));
5039: PetscFunctionReturn(PETSC_SUCCESS);
5040: }
5042: #define DMForestCreateCellChart_pforest _append_pforest(DMForestCreateCellChart)
5043: static PetscErrorCode DMForestCreateCellChart_pforest(DM dm, PetscInt *cStart, PetscInt *cEnd)
5044: {
5045: DM_Forest *forest;
5046: DM_Forest_pforest *pforest;
5047: PetscInt overlap;
5049: PetscFunctionBegin;
5050: PetscCall(DMSetUp(dm));
5051: forest = (DM_Forest *)dm->data;
5052: pforest = (DM_Forest_pforest *)forest->data;
5053: *cStart = 0;
5054: PetscCall(DMForestGetPartitionOverlap(dm, &overlap));
5055: if (overlap && pforest->ghost) {
5056: *cEnd = pforest->forest->local_num_quadrants + pforest->ghost->proc_offsets[pforest->forest->mpisize];
5057: } else {
5058: *cEnd = pforest->forest->local_num_quadrants;
5059: }
5060: PetscFunctionReturn(PETSC_SUCCESS);
5061: }
5063: #define DMForestCreateCellSF_pforest _append_pforest(DMForestCreateCellSF)
5064: static PetscErrorCode DMForestCreateCellSF_pforest(DM dm, PetscSF *cellSF)
5065: {
5066: DM_Forest *forest;
5067: DM_Forest_pforest *pforest;
5068: PetscMPIInt rank;
5069: PetscInt overlap;
5070: PetscInt cStart, cEnd, cLocalStart, cLocalEnd;
5071: PetscInt nRoots, nLeaves, *mine = NULL;
5072: PetscSFNode *remote = NULL;
5073: PetscSF sf;
5075: PetscFunctionBegin;
5076: PetscCall(DMForestGetCellChart(dm, &cStart, &cEnd));
5077: forest = (DM_Forest *)dm->data;
5078: pforest = (DM_Forest_pforest *)forest->data;
5079: nRoots = cEnd - cStart;
5080: cLocalStart = pforest->cLocalStart;
5081: cLocalEnd = pforest->cLocalEnd;
5082: nLeaves = 0;
5083: PetscCall(DMForestGetPartitionOverlap(dm, &overlap));
5084: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
5085: if (overlap && pforest->ghost) {
5086: PetscSFNode *mirror;
5087: p4est_quadrant_t *mirror_array;
5088: PetscInt nMirror, nGhostPre, nSelf, q;
5089: void **mirrorPtrs;
5091: nMirror = (PetscInt)pforest->ghost->mirrors.elem_count;
5092: nSelf = cLocalEnd - cLocalStart;
5093: nLeaves = nRoots - nSelf;
5094: nGhostPre = (PetscInt)pforest->ghost->proc_offsets[rank];
5095: PetscCall(PetscMalloc1(nLeaves, &mine));
5096: PetscCall(PetscMalloc1(nLeaves, &remote));
5097: PetscCall(PetscMalloc2(nMirror, &mirror, nMirror, &mirrorPtrs));
5098: mirror_array = (p4est_quadrant_t *)pforest->ghost->mirrors.array;
5099: for (q = 0; q < nMirror; q++) {
5100: p4est_quadrant_t *mir = &mirror_array[q];
5102: mirror[q].rank = rank;
5103: mirror[q].index = (PetscInt)mir->p.piggy3.local_num + cLocalStart;
5104: mirrorPtrs[q] = (void *)&mirror[q];
5105: }
5106: PetscCallP4est(p4est_ghost_exchange_custom, pforest->forest, pforest->ghost, sizeof(PetscSFNode), mirrorPtrs, remote);
5107: PetscCall(PetscFree2(mirror, mirrorPtrs));
5108: for (q = 0; q < nGhostPre; q++) mine[q] = q;
5109: for (; q < nLeaves; q++) mine[q] = (q - nGhostPre) + cLocalEnd;
5110: }
5111: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)dm), &sf));
5112: PetscCall(PetscSFSetGraph(sf, nRoots, nLeaves, mine, PETSC_OWN_POINTER, remote, PETSC_OWN_POINTER));
5113: *cellSF = sf;
5114: PetscFunctionReturn(PETSC_SUCCESS);
5115: }
5117: static PetscErrorCode DMCreateNeumannOverlap_pforest(DM dm, IS *ovl, Mat *J, PetscErrorCode (**setup)(Mat, PetscReal, Vec, Vec, PetscReal, IS, void *), void **setup_ctx)
5118: {
5119: DM plex;
5121: PetscFunctionBegin;
5122: PetscCall(DMPforestGetPlex(dm, &plex));
5123: PetscCall(DMCopyAuxiliaryVec(dm, plex));
5124: PetscCall(DMCreateNeumannOverlap_Plex(plex, ovl, J, setup, setup_ctx));
5125: PetscCall(DMClearAuxiliaryVec(plex));
5126: if (!*setup) {
5127: PetscCall(PetscObjectQueryFunction((PetscObject)dm, "MatComputeNeumannOverlap_C", setup));
5128: if (*setup) PetscCall(PetscObjectCompose((PetscObject)*ovl, "_DM_Original_HPDDM", (PetscObject)dm));
5129: }
5130: PetscFunctionReturn(PETSC_SUCCESS);
5131: }
5133: #define DMCreateDomainDecomposition_pforest _append_pforest(DMCreateDomainDecomposition)
5134: static PetscErrorCode DMCreateDomainDecomposition_pforest(DM dm, PetscInt *nsub, char ***names, IS **innerises, IS **outerises, DM **dms)
5135: {
5136: DM plex;
5138: PetscFunctionBegin;
5139: PetscCall(DMPforestGetPlex(dm, &plex));
5140: PetscCall(DMCopyAuxiliaryVec(dm, plex));
5141: PetscCall(DMCreateDomainDecomposition(plex, nsub, names, innerises, outerises, dms));
5142: PetscCall(DMClearAuxiliaryVec(plex));
5143: PetscFunctionReturn(PETSC_SUCCESS);
5144: }
5146: #define DMCreateDomainDecompositionScatters_pforest _append_pforest(DMCreateDomainDecompositionScatters)
5147: static PetscErrorCode DMCreateDomainDecompositionScatters_pforest(DM dm, PetscInt n, DM *subdms, VecScatter **iscat, VecScatter **oscat, VecScatter **lscat)
5148: {
5149: DM plex;
5151: PetscFunctionBegin;
5152: PetscCall(DMPforestGetPlex(dm, &plex));
5153: PetscCall(DMCopyAuxiliaryVec(dm, plex));
5154: PetscCall(DMCreateDomainDecompositionScatters(plex, n, subdms, iscat, oscat, lscat));
5155: PetscFunctionReturn(PETSC_SUCCESS);
5156: }
5158: static PetscErrorCode DMInitialize_pforest(DM dm)
5159: {
5160: PetscFunctionBegin;
5161: dm->ops->setup = DMSetUp_pforest;
5162: dm->ops->view = DMView_pforest;
5163: dm->ops->clone = DMClone_pforest;
5164: dm->ops->createinterpolation = DMCreateInterpolation_pforest;
5165: dm->ops->createinjection = DMCreateInjection_pforest;
5166: dm->ops->setfromoptions = DMSetFromOptions_pforest;
5167: dm->ops->createcoordinatedm = DMCreateCoordinateDM_pforest;
5168: dm->ops->createglobalvector = DMCreateGlobalVector_pforest;
5169: dm->ops->createlocalvector = DMCreateLocalVector_pforest;
5170: dm->ops->creatematrix = DMCreateMatrix_pforest;
5171: dm->ops->projectfunctionlocal = DMProjectFunctionLocal_pforest;
5172: dm->ops->projectfunctionlabellocal = DMProjectFunctionLabelLocal_pforest;
5173: dm->ops->projectfieldlocal = DMProjectFieldLocal_pforest;
5174: dm->ops->createlocalsection = DMCreatelocalsection_pforest;
5175: dm->ops->createdefaultconstraints = DMCreateDefaultConstraints_pforest;
5176: dm->ops->computel2diff = DMComputeL2Diff_pforest;
5177: dm->ops->computel2fielddiff = DMComputeL2FieldDiff_pforest;
5178: dm->ops->getdimpoints = DMGetDimPoints_pforest;
5179: dm->ops->createdomaindecomposition = DMCreateDomainDecomposition_pforest;
5180: dm->ops->createddscatters = DMCreateDomainDecompositionScatters_pforest;
5182: PetscCall(PetscObjectComposeFunction((PetscObject)dm, PetscStringize(DMConvert_plex_pforest) "_C", DMConvert_plex_pforest));
5183: PetscCall(PetscObjectComposeFunction((PetscObject)dm, PetscStringize(DMConvert_pforest_plex) "_C", DMConvert_pforest_plex));
5184: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMCreateNeumannOverlap_C", DMCreateNeumannOverlap_pforest));
5185: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexGetOverlap_C", DMForestGetPartitionOverlap));
5186: PetscFunctionReturn(PETSC_SUCCESS);
5187: }
5189: #define DMCreate_pforest _append_pforest(DMCreate)
5190: PETSC_EXTERN PetscErrorCode DMCreate_pforest(DM dm)
5191: {
5192: DM_Forest *forest;
5193: DM_Forest_pforest *pforest;
5195: PetscFunctionBegin;
5196: PetscCall(PetscP4estInitialize());
5197: PetscCall(DMCreate_Forest(dm));
5198: PetscCall(DMInitialize_pforest(dm));
5199: PetscCall(DMSetDimension(dm, P4EST_DIM));
5201: /* set forest defaults */
5202: PetscCall(DMForestSetTopology(dm, "unit"));
5203: PetscCall(DMForestSetMinimumRefinement(dm, 0));
5204: PetscCall(DMForestSetInitialRefinement(dm, 0));
5205: PetscCall(DMForestSetMaximumRefinement(dm, P4EST_QMAXLEVEL));
5206: PetscCall(DMForestSetGradeFactor(dm, 2));
5207: PetscCall(DMForestSetAdjacencyDimension(dm, 0));
5208: PetscCall(DMForestSetPartitionOverlap(dm, 0));
5210: /* create p4est data */
5211: PetscCall(PetscNew(&pforest));
5213: forest = (DM_Forest *)dm->data;
5214: forest->data = pforest;
5215: forest->destroy = DMForestDestroy_pforest;
5216: forest->ftemplate = DMForestTemplate_pforest;
5217: forest->transfervec = DMForestTransferVec_pforest;
5218: forest->transfervecfrombase = DMForestTransferVecFromBase_pforest;
5219: forest->createcellchart = DMForestCreateCellChart_pforest;
5220: forest->createcellsf = DMForestCreateCellSF_pforest;
5221: forest->clearadaptivityforest = DMForestClearAdaptivityForest_pforest;
5222: forest->getadaptivitysuccess = DMForestGetAdaptivitySuccess_pforest;
5223: pforest->topo = NULL;
5224: pforest->forest = NULL;
5225: pforest->ghost = NULL;
5226: pforest->lnodes = NULL;
5227: pforest->partition_for_coarsening = PETSC_TRUE;
5228: pforest->coarsen_hierarchy = PETSC_FALSE;
5229: pforest->cLocalStart = -1;
5230: pforest->cLocalEnd = -1;
5231: pforest->labelsFinalized = PETSC_FALSE;
5232: pforest->ghostName = NULL;
5233: PetscFunctionReturn(PETSC_SUCCESS);
5234: }
5236: #endif /* PetscDefined(HAVE_P4EST) */