Actual source code: plex.c
1: #include <petsc/private/dmpleximpl.h>
2: #include <petsc/private/dmlabelimpl.h>
3: #include <petsc/private/isimpl.h>
4: #include <petsc/private/vecimpl.h>
5: #include <petsc/private/glvisvecimpl.h>
6: #include <petscsf.h>
7: #include <petscds.h>
8: #include <petscdraw.h>
9: #include <petscdmfield.h>
10: #include <petscdmplextransform.h>
11: #include <petscblaslapack.h>
13: /* Logging support */
14: PetscLogEvent DMPLEX_Interpolate, DMPLEX_Partition, DMPLEX_Distribute, DMPLEX_DistributeMultistage, DMPLEX_DistributeCones, DMPLEX_DistributeLabels, DMPLEX_DistributeSF, DMPLEX_DistributeOverlap, DMPLEX_DistributeField, DMPLEX_DistributeData, DMPLEX_Migrate, DMPLEX_InterpolateSF, DMPLEX_GlobalToNaturalBegin, DMPLEX_GlobalToNaturalEnd, DMPLEX_NaturalToGlobalBegin, DMPLEX_NaturalToGlobalEnd, DMPLEX_Stratify, DMPLEX_Symmetrize, DMPLEX_Preallocate, DMPLEX_ResidualFEM, DMPLEX_JacobianFEM, DMPLEX_InterpolatorFEM, DMPLEX_InjectorFEM, DMPLEX_IntegralFEM, DMPLEX_CreateGmsh, DMPLEX_CreateBoxSFC, DMPLEX_RebalanceSharedPoints, DMPLEX_PartSelf, DMPLEX_PartLabelInvert, DMPLEX_PartLabelCreateSF, DMPLEX_PartStratSF, DMPLEX_CreatePointSF, DMPLEX_LocatePoints, DMPLEX_TopologyView, DMPLEX_LabelsView, DMPLEX_CoordinatesView, DMPLEX_SectionView, DMPLEX_GlobalVectorView, DMPLEX_LocalVectorView, DMPLEX_TopologyLoad, DMPLEX_LabelsLoad, DMPLEX_CoordinatesLoad, DMPLEX_SectionLoad, DMPLEX_GlobalVectorLoad, DMPLEX_LocalVectorLoad;
15: PetscLogEvent DMPLEX_RebalBuildGraph, DMPLEX_RebalRewriteSF, DMPLEX_RebalGatherGraph, DMPLEX_RebalPartition, DMPLEX_RebalScatterPart, DMPLEX_Generate, DMPLEX_GetLocalOffsets, DMPLEX_Uninterpolate;
16: PetscLogEvent DMPLEX_DistributionView, DMPLEX_DistributionLoad;
18: PetscBool Plexcite = PETSC_FALSE;
19: const char PlexCitation[] = "@article{LangeMitchellKnepleyGorman2015,\n"
20: "title = {Efficient mesh management in {Firedrake} using {PETSc-DMPlex}},\n"
21: "author = {Michael Lange and Lawrence Mitchell and Matthew G. Knepley and Gerard J. Gorman},\n"
22: "journal = {SIAM Journal on Scientific Computing},\n"
23: "volume = {38},\n"
24: "number = {5},\n"
25: "pages = {S143--S155},\n"
26: "eprint = {http://arxiv.org/abs/1506.07749},\n"
27: "doi = {10.1137/15M1026092},\n"
28: "year = {2016},\n"
29: "petsc_uses={DMPlex},\n}\n";
31: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode VecView_MPI(Vec, PetscViewer);
33: /*@
34: DMPlexIsSimplex - Is the first cell in this mesh a simplex?
36: Input Parameter:
37: . dm - The `DMPLEX` object
39: Output Parameter:
40: . simplex - Flag checking for a simplex
42: Level: intermediate
44: Note:
45: This just gives the first range of cells found. If the mesh has several cell types, it will only give the first.
46: If the mesh has no cells, this returns `PETSC_FALSE`.
48: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetSimplexOrBoxCells()`, `DMPlexGetCellType()`, `DMPlexGetHeightStratum()`, `DMPolytopeTypeGetNumVertices()`
49: @*/
50: PetscErrorCode DMPlexIsSimplex(DM dm, PetscBool *simplex)
51: {
52: DMPolytopeType ct;
53: PetscInt cStart, cEnd;
55: PetscFunctionBegin;
56: PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
57: if (cEnd <= cStart) {
58: *simplex = PETSC_FALSE;
59: PetscFunctionReturn(PETSC_SUCCESS);
60: }
61: PetscCall(DMPlexGetCellType(dm, cStart, &ct));
62: *simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
63: PetscFunctionReturn(PETSC_SUCCESS);
64: }
66: /*@
67: DMPlexGetSimplexOrBoxCells - Get the range of cells which are neither prisms nor ghost FV cells
69: Input Parameters:
70: + dm - The `DMPLEX` object
71: - height - The cell height in the Plex, 0 is the default
73: Output Parameters:
74: + cStart - The first "normal" cell, pass `NULL` if not needed
75: - cEnd - The upper bound on "normal" cells, pass `NULL` if not needed
77: Level: developer
79: Note:
80: This function requires that tensor cells are ordered last.
82: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexConstructGhostCells()`, `DMPlexGetCellTypeStratum()`
83: @*/
84: PetscErrorCode DMPlexGetSimplexOrBoxCells(DM dm, PetscInt height, PeOp PetscInt *cStart, PeOp PetscInt *cEnd)
85: {
86: DMLabel ctLabel;
87: IS valueIS;
88: const PetscInt *ctypes;
89: PetscBool found = PETSC_FALSE;
90: PetscInt Nct, cS = PETSC_INT_MAX, cE = 0;
92: PetscFunctionBegin;
93: PetscCall(DMPlexGetCellTypeLabel(dm, &ctLabel));
94: PetscCall(DMLabelGetValueIS(ctLabel, &valueIS));
95: PetscCall(ISGetLocalSize(valueIS, &Nct));
96: PetscCall(ISGetIndices(valueIS, &ctypes));
97: for (PetscInt t = 0; t < Nct; ++t) {
98: const DMPolytopeType ct = (DMPolytopeType)ctypes[t];
99: PetscInt ctS, ctE, ht;
101: if (ct == DM_POLYTOPE_UNKNOWN) {
102: // If any cells are not typed, just use all cells
103: PetscCall(DMPlexGetHeightStratum(dm, PetscMax(height, 0), cStart, cEnd));
104: break;
105: }
106: if (DMPolytopeTypeIsHybrid(ct) || ct == DM_POLYTOPE_FV_GHOST) continue;
107: PetscCall(DMLabelGetStratumBounds(ctLabel, ct, &ctS, &ctE));
108: if (ctS >= ctE) continue;
109: // Check that a point has the right height
110: PetscCall(DMPlexGetPointHeight(dm, ctS, &ht));
111: if (ht != height) continue;
112: cS = PetscMin(cS, ctS);
113: cE = PetscMax(cE, ctE);
114: found = PETSC_TRUE;
115: }
116: if (!Nct || !found) cS = cE = 0;
117: PetscCall(ISDestroy(&valueIS));
118: // Reset label for fast lookup
119: PetscCall(DMLabelMakeAllInvalid_Internal(ctLabel));
120: if (cStart) *cStart = cS;
121: if (cEnd) *cEnd = cE;
122: PetscFunctionReturn(PETSC_SUCCESS);
123: }
125: PetscErrorCode DMPlexGetFieldTypes_Internal(DM dm, PetscSection section, PetscInt field, PetscInt *types, PetscInt **ssStart, PetscInt **ssEnd, PetscViewerVTKFieldType **sft)
126: {
127: PetscInt cdim, pStart, pEnd, vStart, vEnd, cStart, cEnd, c, depth, cellHeight, t;
128: PetscInt *sStart, *sEnd;
129: PetscViewerVTKFieldType *ft;
130: PetscInt vcdof[DM_NUM_POLYTOPES + 1], globalvcdof[DM_NUM_POLYTOPES + 1];
131: DMLabel depthLabel, ctLabel;
133: PetscFunctionBegin;
134: /* the vcdof and globalvcdof are sized to allow every polytope type and simple vertex at DM_NUM_POLYTOPES */
135: PetscCall(PetscArrayzero(vcdof, DM_NUM_POLYTOPES + 1));
136: PetscCall(DMGetCoordinateDim(dm, &cdim));
137: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
138: PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
139: if (field >= 0) {
140: if ((vStart >= pStart) && (vStart < pEnd)) PetscCall(PetscSectionGetFieldDof(section, vStart, field, &vcdof[DM_NUM_POLYTOPES]));
141: } else {
142: if ((vStart >= pStart) && (vStart < pEnd)) PetscCall(PetscSectionGetDof(section, vStart, &vcdof[DM_NUM_POLYTOPES]));
143: }
145: PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
146: PetscCall(DMPlexGetDepth(dm, &depth));
147: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
148: PetscCall(DMPlexGetCellTypeLabel(dm, &ctLabel));
149: for (c = 0; c < DM_NUM_POLYTOPES; ++c) {
150: const DMPolytopeType ict = (DMPolytopeType)c;
151: PetscInt dep;
153: if (ict == DM_POLYTOPE_FV_GHOST) continue;
154: PetscCall(DMLabelGetStratumBounds(ctLabel, ict, &cStart, &cEnd));
155: if (pStart >= 0) {
156: PetscCall(DMLabelGetValue(depthLabel, cStart, &dep));
157: if (dep != depth - cellHeight) continue;
158: }
159: if (field >= 0) {
160: if ((cStart >= pStart) && (cStart < pEnd)) PetscCall(PetscSectionGetFieldDof(section, cStart, field, &vcdof[c]));
161: } else {
162: if ((cStart >= pStart) && (cStart < pEnd)) PetscCall(PetscSectionGetDof(section, cStart, &vcdof[c]));
163: }
164: }
166: PetscCallMPI(MPIU_Allreduce(vcdof, globalvcdof, DM_NUM_POLYTOPES + 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
167: *types = 0;
169: for (c = 0; c < DM_NUM_POLYTOPES + 1; ++c) {
170: if (globalvcdof[c]) ++(*types);
171: }
173: PetscCall(PetscMalloc3(*types, &sStart, *types, &sEnd, *types, &ft));
174: t = 0;
175: if (globalvcdof[DM_NUM_POLYTOPES]) {
176: sStart[t] = vStart;
177: sEnd[t] = vEnd;
178: ft[t] = (globalvcdof[t] == cdim) ? PETSC_VTK_POINT_VECTOR_FIELD : PETSC_VTK_POINT_FIELD;
179: ++t;
180: }
182: for (c = 0; c < DM_NUM_POLYTOPES; ++c) {
183: if (globalvcdof[c]) {
184: const DMPolytopeType ict = (DMPolytopeType)c;
186: PetscCall(DMLabelGetStratumBounds(ctLabel, ict, &cStart, &cEnd));
187: sStart[t] = cStart;
188: sEnd[t] = cEnd;
189: ft[t] = (globalvcdof[c] == cdim) ? PETSC_VTK_CELL_VECTOR_FIELD : PETSC_VTK_CELL_FIELD;
190: ++t;
191: }
192: }
194: if (!*types) {
195: if (field >= 0) {
196: const char *fieldname;
198: PetscCall(PetscSectionGetFieldName(section, field, &fieldname));
199: PetscCall(PetscInfo((PetscObject)dm, "Could not classify VTK output type of section field %" PetscInt_FMT " \"%s\"\n", field, fieldname));
200: } else {
201: PetscCall(PetscInfo((PetscObject)dm, "Could not classify VTK output type of section\n"));
202: }
203: }
205: *ssStart = sStart;
206: *ssEnd = sEnd;
207: *sft = ft;
208: PetscFunctionReturn(PETSC_SUCCESS);
209: }
211: PetscErrorCode DMPlexRestoreFieldTypes_Internal(DM dm, PetscSection section, PetscInt field, PetscInt *types, PetscInt **sStart, PetscInt **sEnd, PetscViewerVTKFieldType **ft)
212: {
213: PetscFunctionBegin;
214: PetscCall(PetscFree3(*sStart, *sEnd, *ft));
215: PetscFunctionReturn(PETSC_SUCCESS);
216: }
218: PetscErrorCode DMPlexGetFieldType_Internal(DM dm, PetscSection section, PetscInt field, PetscInt *sStart, PetscInt *sEnd, PetscViewerVTKFieldType *ft)
219: {
220: PetscInt cdim, pStart, pEnd, vStart, vEnd, cStart, cEnd;
221: PetscInt vcdof[2] = {0, 0}, globalvcdof[2];
223: PetscFunctionBegin;
224: *ft = PETSC_VTK_INVALID;
225: PetscCall(DMGetCoordinateDim(dm, &cdim));
226: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
227: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
228: PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
229: if (field >= 0) {
230: if ((vStart >= pStart) && (vStart < pEnd)) PetscCall(PetscSectionGetFieldDof(section, vStart, field, &vcdof[0]));
231: if ((cStart >= pStart) && (cStart < pEnd)) PetscCall(PetscSectionGetFieldDof(section, cStart, field, &vcdof[1]));
232: } else {
233: if ((vStart >= pStart) && (vStart < pEnd)) PetscCall(PetscSectionGetDof(section, vStart, &vcdof[0]));
234: if ((cStart >= pStart) && (cStart < pEnd)) PetscCall(PetscSectionGetDof(section, cStart, &vcdof[1]));
235: }
236: PetscCallMPI(MPIU_Allreduce(vcdof, globalvcdof, 2, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
237: if (globalvcdof[0]) {
238: *sStart = vStart;
239: *sEnd = vEnd;
240: if (globalvcdof[0] == cdim) *ft = PETSC_VTK_POINT_VECTOR_FIELD;
241: else *ft = PETSC_VTK_POINT_FIELD;
242: } else if (globalvcdof[1]) {
243: *sStart = cStart;
244: *sEnd = cEnd;
245: if (globalvcdof[1] == cdim) *ft = PETSC_VTK_CELL_VECTOR_FIELD;
246: else *ft = PETSC_VTK_CELL_FIELD;
247: } else {
248: if (field >= 0) {
249: const char *fieldname;
251: PetscCall(PetscSectionGetFieldName(section, field, &fieldname));
252: PetscCall(PetscInfo(dm, "Could not classify VTK output type of section field %" PetscInt_FMT " \"%s\"\n", field, fieldname));
253: } else {
254: PetscCall(PetscInfo(dm, "Could not classify VTK output type of section\n"));
255: }
256: }
257: PetscFunctionReturn(PETSC_SUCCESS);
258: }
260: static PetscErrorCode DMPlexVecFFT1D_Internal(DM dm, PetscBool removeDC, PetscInt n, Vec u, Vec uhat)
261: {
262: Mat FT;
263: Vec fftX, fftY;
264: IS fftReal;
265: PetscInt N;
267: PetscFunctionBegin;
268: PetscCall(VecDuplicate(u, &uhat));
269: PetscCall(VecGetSize(u, &N));
270: PetscCall(MatCreateFFT(PetscObjectComm((PetscObject)dm), 1, &N, MATFFTW, &FT));
271: PetscCall(MatCreateVecs(FT, &fftX, &fftY));
272: PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &fftReal));
274: PetscCall(VecISCopy(fftX, fftReal, SCATTER_FORWARD, u));
275: PetscCall(MatMult(FT, fftX, fftY));
276: PetscCall(VecFilter(fftY, PETSC_SMALL));
277: PetscCall(VecISCopy(fftY, fftReal, SCATTER_REVERSE, uhat));
278: if (removeDC) PetscCall(VecSetValue(uhat, 0, 0., INSERT_VALUES)); // Remove DC component
280: PetscCall(MatDestroy(&FT));
281: PetscCall(VecDestroy(&fftX));
282: PetscCall(VecDestroy(&fftY));
283: PetscCall(ISDestroy(&fftReal));
284: PetscFunctionReturn(PETSC_SUCCESS);
285: }
287: /*@
288: DMPlexVecView1D - Plot many 1D solutions on the same line graph
290: Collective
292: Input Parameters:
293: + dm - The `DMPLEX` object
294: . n - The number of vectors
295: . u - The array of local vectors
296: - viewer - The `PetscViewer`
298: Level: advanced
300: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `VecViewFromOptions()`, `VecView()`
301: @*/
302: PetscErrorCode DMPlexVecView1D(DM dm, PetscInt n, Vec u[], PetscViewer viewer)
303: {
304: DM cdm;
305: PetscDS ds;
306: PetscSection s;
307: Vec *uhat; // Fourier transform of each vector u[i]
308: Vec coordinates; // Local vector of mesh coordinate
309: const PetscScalar *coords; // Coordinate values
310: const PetscScalar **sol; // Arrays from each vector u[i]
311: char **names; // Names for each component of each vector
312: PetscReal *vals; // Values at a point for each component of each vector
313: PetscInt *Nc; // Number of components for each field
314: PetscInt Ntc; // Total number of components across all fields
315: PetscInt Nw; // Number of plots
316: PetscInt cdof; // Total number of cell dofs
317: PetscInt vdof; // Total number of vertex dofs
318: PetscInt k; // The Lagrange degree, and drawing mode
319: PetscInt Nf, vStart, vEnd, eStart, eEnd;
320: PetscBool separateCmp = PETSC_TRUE; // Plot components of fields
321: PetscBool fft = PETSC_FALSE; // Fourier Transform the field before plotting
322: PetscBool removeDC = PETSC_FALSE; // Remove DC component before plotting
324: PetscFunctionBegin;
325: PetscCall(PetscOptionsGetBool(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_plex_view_1d_fft", &fft, NULL));
326: PetscCall(PetscOptionsGetBool(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_plex_view_1d_components", &separateCmp, NULL));
327: PetscCall(PetscOptionsGetBool(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_plex_view_1d_remove_dc", &removeDC, NULL));
328: if (!n) fft = PETSC_FALSE;
329: if (fft) {
330: PetscCall(PetscMalloc1(n, &uhat));
331: for (PetscInt i = 0; i < n; ++i) {
332: PetscCall(VecDuplicate(u[i], &uhat[i]));
333: PetscCall(DMPlexVecFFT1D_Internal(dm, removeDC, 1, u[i], uhat[i]));
334: }
335: }
336: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
337: PetscCall(DMPlexGetDepthStratum(dm, 1, &eStart, &eEnd));
338: PetscCall(DMGetCoordinateDM(dm, &cdm));
339: PetscCall(DMGetDS(dm, &ds));
340: PetscCall(PetscDSGetNumFields(ds, &Nf));
341: PetscCall(PetscDSGetTotalComponents(ds, &Ntc));
342: PetscCall(PetscDSGetComponents(ds, &Nc));
344: PetscCall(DMGetLocalSection(dm, &s));
345: PetscCall(PetscSectionGetDof(s, eStart, &cdof));
346: PetscCall(PetscSectionGetDof(s, vStart, &vdof));
347: PetscCheck(cdof || vdof, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Unsupported discretization");
348: if (cdof && vdof) k = 2;
349: else if (vdof) k = 1;
350: else if (cdof) k = 0;
352: PetscCall(PetscMalloc3(n, &sol, n * Ntc, &names, n * Ntc, &vals));
353: for (PetscInt i = 0, l = 0; i < n; ++i) {
354: const char *vname;
356: PetscCall(PetscObjectGetName((PetscObject)u[i], &vname));
357: for (PetscInt f = 0; f < Nf; ++f) {
358: PetscObject disc;
359: const char *fname;
360: char tmpname[PETSC_MAX_PATH_LEN];
362: PetscCall(PetscDSGetDiscretization(ds, f, &disc));
363: /* TODO Create names for components */
364: for (PetscInt c = 0; c < Nc[f]; ++c, ++l) {
365: PetscCall(PetscObjectGetName(disc, &fname));
366: PetscCall(PetscStrncpy(tmpname, vname, sizeof(tmpname)));
367: PetscCall(PetscStrlcat(tmpname, ":", sizeof(tmpname)));
368: PetscCall(PetscStrlcat(tmpname, fname, sizeof(tmpname)));
369: PetscCall(PetscStrallocpy(tmpname, &names[l]));
370: }
371: }
372: }
374: PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
375: PetscCall(VecGetArrayRead(coordinates, &coords));
376: for (PetscInt i = 0; i < n; ++i) PetscCall(VecGetArrayRead(fft ? uhat[i] : u[i], &sol[i]));
378: PetscDrawLG *lg;
380: Nw = separateCmp ? Ntc : 1;
381: PetscCall(PetscMalloc1(Nw, &lg));
382: for (PetscInt w = 0; w < Nw; ++w) {
383: PetscDraw draw = NULL;
384: const PetscInt Nl = separateCmp ? 1 : Ntc;
385: PetscInt vFirst = -1;
386: PetscInt field = 0;
387: PetscInt cmp = 0;
388: PetscInt tcmp = 0;
390: if (separateCmp) {
391: for (PetscInt f = 0; f < Nf; ++f) {
392: PetscInt c;
394: for (c = 0; c < Nc[f]; ++c, ++tcmp) {
395: if (tcmp == w) {
396: cmp = c;
397: break;
398: }
399: }
400: if (c < Nc[f]) {
401: field = f;
402: break;
403: }
404: }
405: }
406: PetscCall(PetscViewerDrawGetDraw(viewer, w, &draw));
407: if (!draw) PetscFunctionReturn(PETSC_SUCCESS);
408: PetscCall(PetscDrawLGCreate(draw, n * Nl, &lg[w]));
410: PetscCall(PetscDrawLGSetLegend(lg[w], (const char *const *)&names[w]));
411: switch (k) {
412: case 0:
413: for (PetscInt e = eStart; e < eEnd; ++e) {
414: PetscScalar *xa, *xb, *svals;
415: const PetscInt *cone;
417: PetscCall(DMPlexGetCone(dm, e, &cone));
418: PetscCall(DMPlexPointLocalRead(cdm, cone[0], coords, &xa));
419: PetscCall(DMPlexPointLocalRead(cdm, cone[1], coords, &xb));
420: for (PetscInt i = 0; i < n; ++i) {
421: if (separateCmp) {
422: PetscCall(DMPlexPointLocalFieldRead(dm, e, field, sol[i], &svals));
423: vals[i] = PetscRealPart(svals[cmp]);
424: } else {
425: PetscCall(DMPlexPointLocalRead(dm, e, sol[i], &svals));
426: for (PetscInt l = 0; l < Nl; ++l) vals[i * Nl + l] = PetscRealPart(svals[l]);
427: }
428: }
429: PetscCall(PetscDrawLGAddCommonPoint(lg[w], 0.5 * (PetscRealPart(xa[0]) + PetscRealPart(xb[0])), vals));
430: }
431: break;
432: case 1:
433: for (PetscInt v = vStart; v < vEnd; ++v) {
434: PetscScalar *x, *svals;
436: PetscCall(DMPlexPointLocalRead(cdm, v, coords, &x));
437: for (PetscInt i = 0; i < n; ++i) {
438: if (separateCmp) {
439: PetscCall(DMPlexPointLocalFieldRead(dm, v, field, sol[i], &svals));
440: vals[i] = PetscRealPart(svals[cmp]);
441: } else {
442: PetscCall(DMPlexPointLocalRead(dm, v, sol[i], &svals));
443: for (PetscInt l = 0; l < Nl; ++l) vals[i * Nl + l] = PetscRealPart(svals[l]);
444: }
445: }
446: PetscCall(PetscDrawLGAddCommonPoint(lg[w], PetscRealPart(x[0]), vals));
447: }
448: break;
449: case 2:
450: for (PetscInt e = eStart; e < eEnd; ++e) {
451: PetscScalar *xa, *xb, *svals;
452: const PetscInt *cone;
454: PetscCall(DMPlexGetCone(dm, e, &cone));
455: PetscCall(DMPlexPointLocalRead(cdm, cone[0], coords, &xa));
456: PetscCall(DMPlexPointLocalRead(cdm, cone[1], coords, &xb));
457: if (e == eStart) vFirst = cone[0];
458: for (PetscInt i = 0; i < n; ++i) {
459: if (separateCmp) {
460: PetscCall(DMPlexPointLocalFieldRead(dm, cone[0], field, sol[i], &svals));
461: vals[i] = PetscRealPart(svals[cmp]);
462: } else {
463: PetscCall(DMPlexPointLocalRead(dm, cone[0], sol[i], &svals));
464: for (PetscInt l = 0; l < Nl; ++l) vals[i * Nl + l] = PetscRealPart(svals[l]);
465: }
466: }
467: PetscCall(PetscDrawLGAddCommonPoint(lg[w], PetscRealPart(xa[0]), vals));
468: if (e == eEnd - 1 && cone[1] != vFirst) {
469: for (PetscInt i = 0; i < n; ++i) {
470: if (separateCmp) {
471: PetscCall(DMPlexPointLocalFieldRead(dm, e, field, sol[i], &svals));
472: vals[i] = PetscRealPart(svals[cmp]);
473: } else {
474: PetscCall(DMPlexPointLocalRead(dm, e, sol[i], &svals));
475: for (PetscInt l = 0; l < Nl; ++l) vals[i * Nl + l] = PetscRealPart(svals[l]);
476: }
477: }
478: PetscCall(PetscDrawLGAddCommonPoint(lg[w], 0.5 * (PetscRealPart(xa[0]) + PetscRealPart(xb[0])), vals));
479: for (PetscInt i = 0; i < n; ++i) {
480: if (separateCmp) {
481: PetscCall(DMPlexPointLocalFieldRead(dm, cone[1], field, sol[i], &svals));
482: vals[i] = PetscRealPart(svals[cmp]);
483: } else {
484: PetscCall(DMPlexPointLocalRead(dm, cone[1], sol[i], &svals));
485: for (PetscInt l = 0; l < Nl; ++l) vals[i * Nl + l] = PetscRealPart(svals[l]);
486: }
487: }
488: PetscCall(PetscDrawLGAddCommonPoint(lg[w], PetscRealPart(xb[0]), vals));
489: }
490: }
491: break;
492: default:
493: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Invalid value of k: %" PetscInt_FMT, k);
494: }
495: }
496: PetscCall(VecRestoreArrayRead(coordinates, &coords));
497: for (PetscInt i = 0; i < n; ++i) PetscCall(VecRestoreArrayRead(fft ? uhat[i] : u[i], &sol[i]));
498: if (fft) {
499: for (PetscInt i = 0; i < n; ++i) PetscCall(VecDestroy(&uhat[i]));
500: PetscCall(PetscFree(uhat));
501: }
502: for (PetscInt l = 0; l < n * Ntc; ++l) PetscCall(PetscFree(names[l]));
503: PetscCall(PetscFree3(sol, names, vals));
504: for (PetscInt w = 0; w < Nw; ++w) {
505: PetscCall(PetscDrawLGDraw(lg[w]));
506: PetscCall(PetscDrawLGDestroy(&lg[w]));
507: }
508: PetscCall(PetscFree(lg));
509: PetscFunctionReturn(PETSC_SUCCESS);
510: }
512: static PetscErrorCode VecView_Plex_Local_Draw_1D(Vec u, PetscViewer viewer)
513: {
514: DM dm;
516: PetscFunctionBegin;
517: PetscCall(VecGetDM(u, &dm));
518: PetscCall(DMPlexVecView1D(dm, 1, &u, viewer));
519: PetscFunctionReturn(PETSC_SUCCESS);
520: }
522: static PetscErrorCode VecView_Plex_Local_Draw_2D(Vec v, PetscViewer viewer)
523: {
524: DM dm;
525: PetscSection s;
526: PetscDraw draw, popup;
527: DM cdm;
528: PetscSection coordSection;
529: Vec coordinates;
530: const PetscScalar *array;
531: PetscReal lbound[3], ubound[3];
532: PetscReal vbound[2], time;
533: PetscBool flg;
534: PetscInt dim, Nf, f, Nc, comp, vStart, vEnd, cStart, cEnd, c, N, level, step, w = 0;
535: const char *name;
536: char title[PETSC_MAX_PATH_LEN];
538: PetscFunctionBegin;
539: PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
540: PetscCall(VecGetDM(v, &dm));
541: PetscCall(DMGetCoordinateDim(dm, &dim));
542: PetscCall(DMGetLocalSection(dm, &s));
543: PetscCall(PetscSectionGetNumFields(s, &Nf));
544: PetscCall(DMGetCoarsenLevel(dm, &level));
545: PetscCall(DMGetCoordinateDM(dm, &cdm));
546: PetscCall(DMGetLocalSection(cdm, &coordSection));
547: PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
548: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
549: PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
551: PetscCall(PetscObjectGetName((PetscObject)v, &name));
552: PetscCall(DMGetOutputSequenceNumber(dm, &step, &time));
554: PetscCall(VecGetLocalSize(coordinates, &N));
555: PetscCall(DMGetBoundingBox(dm, lbound, ubound));
556: PetscCall(PetscDrawClear(draw));
558: /* Could implement something like DMDASelectFields() */
559: for (f = 0; f < Nf; ++f) {
560: DM fdm = dm;
561: Vec fv = v;
562: IS fis;
563: char prefix[PETSC_MAX_PATH_LEN];
564: const char *fname;
566: PetscCall(PetscSectionGetFieldComponents(s, f, &Nc));
567: PetscCall(PetscSectionGetFieldName(s, f, &fname));
569: if (v->hdr.prefix) PetscCall(PetscStrncpy(prefix, v->hdr.prefix, sizeof(prefix)));
570: else prefix[0] = '\0';
571: if (Nf > 1) {
572: PetscCall(DMCreateSubDM(dm, 1, &f, &fis, &fdm));
573: PetscCall(VecGetSubVector(v, fis, &fv));
574: PetscCall(PetscStrlcat(prefix, fname, sizeof(prefix)));
575: PetscCall(PetscStrlcat(prefix, "_", sizeof(prefix)));
576: }
577: for (comp = 0; comp < Nc; ++comp, ++w) {
578: PetscInt nmax = 2;
580: PetscCall(PetscViewerDrawGetDraw(viewer, w, &draw));
581: if (Nc > 1) PetscCall(PetscSNPrintf(title, sizeof(title), "%s:%s_%" PetscInt_FMT " Step: %" PetscInt_FMT " Time: %.4g", name, fname, comp, step, (double)time));
582: else PetscCall(PetscSNPrintf(title, sizeof(title), "%s:%s Step: %" PetscInt_FMT " Time: %.4g", name, fname, step, (double)time));
583: PetscCall(PetscDrawSetTitle(draw, title));
585: /* TODO Get max and min only for this component */
586: PetscCall(PetscOptionsGetRealArray(NULL, prefix, "-vec_view_bounds", vbound, &nmax, &flg));
587: if (!flg) {
588: PetscCall(VecMin(fv, NULL, &vbound[0]));
589: PetscCall(VecMax(fv, NULL, &vbound[1]));
590: if (vbound[1] <= vbound[0]) vbound[1] = vbound[0] + 1.0;
591: }
593: PetscCall(PetscDrawGetPopup(draw, &popup));
594: PetscCall(PetscDrawScalePopup(popup, vbound[0], vbound[1]));
595: PetscCall(PetscDrawSetCoordinates(draw, lbound[0], lbound[1], ubound[0], ubound[1]));
596: PetscCall(VecGetArrayRead(fv, &array));
597: for (c = cStart; c < cEnd; ++c) {
598: DMPolytopeType ct;
599: PetscScalar *coords = NULL, *a = NULL;
600: const PetscScalar *coords_arr;
601: PetscBool isDG;
602: PetscInt numCoords;
603: int color[4] = {-1, -1, -1, -1};
605: PetscCall(DMPlexGetCellType(dm, c, &ct));
606: PetscCall(DMPlexPointLocalRead(fdm, c, array, &a));
607: if (a) {
608: color[0] = PetscDrawRealToColor(PetscRealPart(a[comp]), vbound[0], vbound[1]);
609: color[1] = color[2] = color[3] = color[0];
610: } else {
611: PetscScalar *vals = NULL;
612: PetscInt numVals;
614: PetscCall(DMPlexVecGetClosure(fdm, NULL, fv, c, &numVals, &vals));
615: if (!numVals) {
616: PetscCall(DMPlexVecRestoreClosure(fdm, NULL, fv, c, &numVals, &vals));
617: continue;
618: }
619: PetscCheck(numVals % Nc == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The number of components %" PetscInt_FMT " does not divide the number of values in the closure %" PetscInt_FMT, Nc, numVals);
620: switch (numVals / Nc) {
621: case 1: /* P1 Clamped Segment Prism */
622: case 2: /* P1 Segment Prism, P2 Clamped Segment Prism */
623: PetscCheck(ct == DM_POLYTOPE_SEG_PRISM_TENSOR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell should be a tensor segment, but it is a %s", DMPolytopeTypes[ct]);
624: for (PetscInt va = 0; va < numVals / Nc; ++va) color[va] = PetscDrawRealToColor(PetscRealPart(vals[va * Nc + comp]), vbound[0], vbound[1]);
625: break;
626: case 3: /* P1 Triangle */
627: case 4: /* P1 Quadrangle */
628: PetscCheck(ct == DM_POLYTOPE_TRIANGLE || ct == DM_POLYTOPE_QUADRILATERAL || ct == DM_POLYTOPE_SEG_PRISM_TENSOR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell should be a triangle or quad, but it is a %s", DMPolytopeTypes[ct]);
629: for (PetscInt va = 0; va < numVals / Nc; ++va) color[va] = PetscDrawRealToColor(PetscRealPart(vals[va * Nc + comp]), vbound[0], vbound[1]);
630: break;
631: case 6: /* P2 Triangle */
632: case 8: /* P2 Quadrangle */
633: PetscCheck(ct == DM_POLYTOPE_TRIANGLE || ct == DM_POLYTOPE_QUADRILATERAL || ct == DM_POLYTOPE_SEG_PRISM_TENSOR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell should be a triangle or quad, but it is a %s", DMPolytopeTypes[ct]);
634: for (PetscInt va = 0; va < numVals / (Nc * 2); ++va) color[va] = PetscDrawRealToColor(PetscRealPart(vals[va * Nc + comp + numVals / (Nc * 2)]), vbound[0], vbound[1]);
635: break;
636: default:
637: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of values for cell closure %" PetscInt_FMT " cannot be handled", numVals / Nc);
638: }
639: PetscCall(DMPlexVecRestoreClosure(fdm, NULL, fv, c, &numVals, &vals));
640: }
641: PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &coords_arr, &coords));
642: switch (numCoords) {
643: case 6:
644: case 12: /* Localized triangle */
645: PetscCall(PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), color[0], color[1], color[2]));
646: break;
647: case 8:
648: case 16: /* Localized quadrilateral */
649: if (ct == DM_POLYTOPE_SEG_PRISM_TENSOR) {
650: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscMax(color[0], color[1])));
651: } else {
652: PetscCall(PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), color[0], color[1], color[2]));
653: PetscCall(PetscDrawTriangle(draw, PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[6]), PetscRealPart(coords[7]), PetscRealPart(coords[0]), PetscRealPart(coords[1]), color[2], color[3], color[0]));
654: }
655: break;
656: default:
657: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells with %" PetscInt_FMT " coordinates", numCoords);
658: }
659: PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &coords_arr, &coords));
660: }
661: PetscCall(VecRestoreArrayRead(fv, &array));
662: PetscCall(PetscDrawFlush(draw));
663: PetscCall(PetscDrawPause(draw));
664: PetscCall(PetscDrawSave(draw));
665: }
666: if (Nf > 1) {
667: PetscCall(VecRestoreSubVector(v, fis, &fv));
668: PetscCall(ISDestroy(&fis));
669: PetscCall(DMDestroy(&fdm));
670: }
671: }
672: PetscFunctionReturn(PETSC_SUCCESS);
673: }
675: static PetscErrorCode VecView_Plex_Local_Draw(Vec v, PetscViewer viewer)
676: {
677: DM dm;
678: PetscDraw draw;
679: PetscInt dim;
680: PetscBool isnull;
682: PetscFunctionBegin;
683: PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
684: PetscCall(PetscDrawIsNull(draw, &isnull));
685: if (isnull) PetscFunctionReturn(PETSC_SUCCESS);
687: PetscCall(VecGetDM(v, &dm));
688: PetscCall(DMGetCoordinateDim(dm, &dim));
689: switch (dim) {
690: case 1:
691: PetscCall(VecView_Plex_Local_Draw_1D(v, viewer));
692: break;
693: case 2:
694: PetscCall(VecView_Plex_Local_Draw_2D(v, viewer));
695: break;
696: default:
697: SETERRQ(PetscObjectComm((PetscObject)v), PETSC_ERR_SUP, "Cannot draw meshes of dimension %" PetscInt_FMT ". Try PETSCVIEWERGLVIS", dim);
698: }
699: PetscFunctionReturn(PETSC_SUCCESS);
700: }
702: static PetscErrorCode VecView_Plex_Local_VTK(Vec v, PetscViewer viewer)
703: {
704: DM dm;
705: Vec locv;
706: const char *name;
707: PetscSection section;
708: PetscInt pStart, pEnd;
709: PetscInt numFields;
710: PetscViewerVTKFieldType ft;
712: PetscFunctionBegin;
713: PetscCall(VecGetDM(v, &dm));
714: PetscCall(DMCreateLocalVector(dm, &locv)); /* VTK viewer requires exclusive ownership of the vector */
715: PetscCall(PetscObjectGetName((PetscObject)v, &name));
716: PetscCall(PetscObjectSetName((PetscObject)locv, name));
717: PetscCall(VecCopy(v, locv));
718: PetscCall(DMGetLocalSection(dm, §ion));
719: PetscCall(PetscSectionGetNumFields(section, &numFields));
720: if (!numFields) {
721: PetscCall(DMPlexGetFieldType_Internal(dm, section, PETSC_DETERMINE, &pStart, &pEnd, &ft));
722: PetscCall(PetscViewerVTKAddField(viewer, (PetscObject)dm, DMPlexVTKWriteAll, PETSC_DEFAULT, ft, PETSC_TRUE, (PetscObject)locv));
723: } else {
724: for (PetscInt f = 0; f < numFields; f++) {
725: PetscCall(DMPlexGetFieldType_Internal(dm, section, f, &pStart, &pEnd, &ft));
726: if (ft == PETSC_VTK_INVALID) continue;
727: PetscCall(PetscObjectReference((PetscObject)locv));
728: PetscCall(PetscViewerVTKAddField(viewer, (PetscObject)dm, DMPlexVTKWriteAll, f, ft, PETSC_TRUE, (PetscObject)locv));
729: }
730: PetscCall(VecDestroy(&locv));
731: }
732: PetscFunctionReturn(PETSC_SUCCESS);
733: }
735: PetscErrorCode VecView_Plex_Local(Vec v, PetscViewer viewer)
736: {
737: DM dm;
738: PetscBool isvtk, ishdf5, isdraw, isglvis, iscgns, ispython;
740: PetscFunctionBegin;
741: PetscCall(VecGetDM(v, &dm));
742: PetscCheck(dm, PetscObjectComm((PetscObject)v), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
743: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk));
744: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
745: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
746: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERGLVIS, &isglvis));
747: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERCGNS, &iscgns));
748: PetscCall(PetscObjectHasFunction((PetscObject)viewer, "PetscViewerPythonViewObject_C", &ispython));
749: if (isvtk || ishdf5 || isdraw || isglvis || iscgns || ispython) {
750: PetscInt numFields;
751: PetscObject fe;
752: PetscBool fem = PETSC_FALSE;
753: Vec locv = v;
754: const char *name;
755: PetscInt step;
756: PetscReal time;
758: PetscCall(DMGetNumFields(dm, &numFields));
759: for (PetscInt i = 0; i < numFields; i++) {
760: PetscCall(DMGetField(dm, i, NULL, &fe));
761: if (fe->classid == PETSCFE_CLASSID) {
762: fem = PETSC_TRUE;
763: break;
764: }
765: }
766: if (fem) {
767: PetscObject isZero;
769: PetscCall(DMGetLocalVector(dm, &locv));
770: PetscCall(PetscObjectGetName((PetscObject)v, &name));
771: PetscCall(PetscObjectSetName((PetscObject)locv, name));
772: PetscCall(PetscObjectQuery((PetscObject)v, "__Vec_bc_zero__", &isZero));
773: PetscCall(PetscObjectCompose((PetscObject)locv, "__Vec_bc_zero__", isZero));
774: PetscCall(VecCopy(v, locv));
775: PetscCall(DMGetOutputSequenceNumber(dm, NULL, &time));
776: PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_TRUE, locv, time, NULL, NULL, NULL));
777: }
778: if (isvtk) {
779: PetscCall(VecView_Plex_Local_VTK(locv, viewer));
780: } else if (ishdf5) {
781: #if defined(PETSC_HAVE_HDF5)
782: PetscCall(VecView_Plex_Local_HDF5_Internal(locv, viewer));
783: #else
784: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
785: #endif
786: } else if (isdraw) {
787: PetscCall(VecView_Plex_Local_Draw(locv, viewer));
788: } else if (ispython) {
789: PetscCall(PetscViewerPythonViewObject(viewer, (PetscObject)locv));
790: } else if (isglvis) {
791: PetscCall(DMGetOutputSequenceNumber(dm, &step, NULL));
792: PetscCall(PetscViewerGLVisSetSnapId(viewer, step));
793: PetscCall(VecView_GLVis(locv, viewer));
794: } else if (iscgns) {
795: #if defined(PETSC_HAVE_CGNS)
796: PetscCall(VecView_Plex_Local_CGNS(locv, viewer));
797: #else
798: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "CGNS not supported in this build.\nPlease reconfigure using --download-cgns");
799: #endif
800: }
801: if (fem) {
802: PetscCall(PetscObjectCompose((PetscObject)locv, "__Vec_bc_zero__", NULL));
803: PetscCall(DMRestoreLocalVector(dm, &locv));
804: }
805: } else {
806: PetscBool isseq;
808: PetscCall(PetscObjectTypeCompare((PetscObject)v, VECSEQ, &isseq));
809: if (isseq) PetscCall(VecView_Seq(v, viewer));
810: else PetscCall(VecView_MPI(v, viewer));
811: }
812: PetscFunctionReturn(PETSC_SUCCESS);
813: }
815: PetscErrorCode VecView_Plex(Vec v, PetscViewer viewer)
816: {
817: DM dm;
818: PetscBool isvtk, ishdf5, isdraw, isglvis, isexodusii, iscgns, ispython;
820: PetscFunctionBegin;
821: PetscCall(VecGetDM(v, &dm));
822: PetscCheck(dm, PetscObjectComm((PetscObject)v), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
823: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk));
824: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
825: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
826: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERGLVIS, &isglvis));
827: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERCGNS, &iscgns));
828: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWEREXODUSII, &isexodusii));
829: PetscCall(PetscObjectHasFunction((PetscObject)viewer, "PetscViewerPythonViewObject_C", &ispython));
830: if (isvtk || isdraw || isglvis || iscgns || ispython) {
831: Vec locv;
832: PetscObject isZero;
833: const char *name;
835: PetscCall(DMGetLocalVector(dm, &locv));
836: PetscCall(PetscObjectGetName((PetscObject)v, &name));
837: PetscCall(PetscObjectSetName((PetscObject)locv, name));
838: PetscCall(DMGlobalToLocalBegin(dm, v, INSERT_VALUES, locv));
839: PetscCall(DMGlobalToLocalEnd(dm, v, INSERT_VALUES, locv));
840: PetscCall(PetscObjectQuery((PetscObject)v, "__Vec_bc_zero__", &isZero));
841: PetscCall(PetscObjectCompose((PetscObject)locv, "__Vec_bc_zero__", isZero));
842: PetscCall(VecView_Plex_Local(locv, viewer));
843: PetscCall(PetscObjectCompose((PetscObject)locv, "__Vec_bc_zero__", NULL));
844: PetscCall(DMRestoreLocalVector(dm, &locv));
845: } else if (ishdf5) {
846: #if defined(PETSC_HAVE_HDF5)
847: PetscCall(VecView_Plex_HDF5_Internal(v, viewer));
848: #else
849: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
850: #endif
851: } else if (isexodusii) {
852: #if defined(PETSC_HAVE_EXODUSII)
853: PetscCall(VecView_PlexExodusII_Internal(v, viewer));
854: #else
855: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "ExodusII not supported in this build.\nPlease reconfigure using --download-exodusii");
856: #endif
857: } else {
858: PetscBool isseq;
860: PetscCall(PetscObjectTypeCompare((PetscObject)v, VECSEQ, &isseq));
861: if (isseq) PetscCall(VecView_Seq(v, viewer));
862: else PetscCall(VecView_MPI(v, viewer));
863: }
864: PetscFunctionReturn(PETSC_SUCCESS);
865: }
867: PetscErrorCode VecView_Plex_Native(Vec originalv, PetscViewer viewer)
868: {
869: DM dm;
870: MPI_Comm comm;
871: PetscViewerFormat format;
872: Vec v;
873: PetscBool isvtk, ishdf5;
875: PetscFunctionBegin;
876: PetscCall(VecGetDM(originalv, &dm));
877: PetscCall(PetscObjectGetComm((PetscObject)originalv, &comm));
878: PetscCheck(dm, comm, PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
879: PetscCall(PetscViewerGetFormat(viewer, &format));
880: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
881: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk));
882: if (format == PETSC_VIEWER_NATIVE) {
883: /* Natural ordering is the common case for DMDA, NATIVE means plain vector, for PLEX is the opposite */
884: /* this need a better fix */
885: if (dm->useNatural) {
886: const char *vecname;
887: PetscInt n, nroots;
889: PetscCheck(dm->sfNatural, comm, PETSC_ERR_ARG_WRONGSTATE, "DM global to natural SF was not created");
890: PetscCall(VecGetLocalSize(originalv, &n));
891: PetscCall(PetscSFGetGraph(dm->sfNatural, &nroots, NULL, NULL, NULL));
892: PetscCheck(n == nroots, comm, PETSC_ERR_ARG_WRONG, "DM global to natural SF only handles global vectors");
893: PetscCall(DMPlexCreateNaturalVector(dm, &v));
894: PetscCall(DMPlexGlobalToNaturalBegin(dm, originalv, v));
895: PetscCall(DMPlexGlobalToNaturalEnd(dm, originalv, v));
896: PetscCall(PetscObjectGetName((PetscObject)originalv, &vecname));
897: PetscCall(PetscObjectSetName((PetscObject)v, vecname));
898: } else v = originalv;
899: } else v = originalv;
901: if (ishdf5) {
902: #if defined(PETSC_HAVE_HDF5)
903: PetscCall(VecView_Plex_HDF5_Native_Internal(v, viewer));
904: #else
905: SETERRQ(comm, PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
906: #endif
907: } else if (isvtk) {
908: SETERRQ(comm, PETSC_ERR_SUP, "VTK format does not support viewing in natural order. Please switch to HDF5.");
909: } else {
910: PetscBool isseq;
912: PetscCall(PetscObjectTypeCompare((PetscObject)v, VECSEQ, &isseq));
913: if (isseq) PetscCall(VecView_Seq(v, viewer));
914: else PetscCall(VecView_MPI(v, viewer));
915: }
916: if (v != originalv) PetscCall(VecDestroy(&v));
917: PetscFunctionReturn(PETSC_SUCCESS);
918: }
920: PetscErrorCode VecLoad_Plex_Local(Vec v, PetscViewer viewer)
921: {
922: DM dm;
923: PetscBool ishdf5;
925: PetscFunctionBegin;
926: PetscCall(VecGetDM(v, &dm));
927: PetscCheck(dm, PetscObjectComm((PetscObject)v), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
928: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
929: if (ishdf5) {
930: DM dmBC;
931: Vec gv;
932: const char *name;
934: PetscCall(DMGetOutputDM(dm, &dmBC));
935: PetscCall(DMGetGlobalVector(dmBC, &gv));
936: PetscCall(PetscObjectGetName((PetscObject)v, &name));
937: PetscCall(PetscObjectSetName((PetscObject)gv, name));
938: PetscCall(VecLoad_Default(gv, viewer));
939: PetscCall(DMGlobalToLocalBegin(dmBC, gv, INSERT_VALUES, v));
940: PetscCall(DMGlobalToLocalEnd(dmBC, gv, INSERT_VALUES, v));
941: PetscCall(DMRestoreGlobalVector(dmBC, &gv));
942: } else PetscCall(VecLoad_Default(v, viewer));
943: PetscFunctionReturn(PETSC_SUCCESS);
944: }
946: PetscErrorCode VecLoad_Plex(Vec v, PetscViewer viewer)
947: {
948: DM dm;
949: PetscBool ishdf5, isexodusii, iscgns;
951: PetscFunctionBegin;
952: PetscCall(VecGetDM(v, &dm));
953: PetscCheck(dm, PetscObjectComm((PetscObject)v), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
954: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
955: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWEREXODUSII, &isexodusii));
956: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERCGNS, &iscgns));
957: if (ishdf5) {
958: #if defined(PETSC_HAVE_HDF5)
959: PetscCall(VecLoad_Plex_HDF5_Internal(v, viewer));
960: #else
961: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
962: #endif
963: } else if (isexodusii) {
964: #if defined(PETSC_HAVE_EXODUSII)
965: PetscCall(VecLoad_PlexExodusII_Internal(v, viewer));
966: #else
967: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "ExodusII not supported in this build.\nPlease reconfigure using --download-exodusii");
968: #endif
969: } else if (iscgns) {
970: #if defined(PETSC_HAVE_CGNS)
971: PetscCall(VecLoad_Plex_CGNS_Internal(v, viewer));
972: #else
973: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "CGNS not supported in this build.\nPlease reconfigure using --download-cgns");
974: #endif
975: } else PetscCall(VecLoad_Default(v, viewer));
976: PetscFunctionReturn(PETSC_SUCCESS);
977: }
979: PetscErrorCode VecLoad_Plex_Native(Vec originalv, PetscViewer viewer)
980: {
981: DM dm;
982: PetscViewerFormat format;
983: PetscBool ishdf5;
985: PetscFunctionBegin;
986: PetscCall(VecGetDM(originalv, &dm));
987: PetscCheck(dm, PetscObjectComm((PetscObject)originalv), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
988: PetscCall(PetscViewerGetFormat(viewer, &format));
989: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
990: if (format == PETSC_VIEWER_NATIVE) {
991: if (dm->useNatural) {
992: if (dm->sfNatural) {
993: if (ishdf5) {
994: #if defined(PETSC_HAVE_HDF5)
995: Vec v;
996: const char *vecname;
998: PetscCall(DMPlexCreateNaturalVector(dm, &v));
999: PetscCall(PetscObjectGetName((PetscObject)originalv, &vecname));
1000: PetscCall(PetscObjectSetName((PetscObject)v, vecname));
1001: PetscCall(VecLoad_Plex_HDF5_Native_Internal(v, viewer));
1002: PetscCall(DMPlexNaturalToGlobalBegin(dm, v, originalv));
1003: PetscCall(DMPlexNaturalToGlobalEnd(dm, v, originalv));
1004: PetscCall(VecDestroy(&v));
1005: #else
1006: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
1007: #endif
1008: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Reading in natural order is not supported for anything but HDF5.");
1009: }
1010: } else PetscCall(VecLoad_Default(originalv, viewer));
1011: }
1012: PetscFunctionReturn(PETSC_SUCCESS);
1013: }
1015: PETSC_UNUSED static PetscErrorCode DMPlexView_Ascii_Geometry(DM dm, PetscViewer viewer)
1016: {
1017: PetscSection coordSection;
1018: Vec coordinates;
1019: DMLabel depthLabel, celltypeLabel;
1020: const char *name[4];
1021: const PetscScalar *a;
1022: PetscInt dim, pStart, pEnd, cStart, cEnd, c;
1024: PetscFunctionBegin;
1025: PetscCall(DMGetDimension(dm, &dim));
1026: PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
1027: PetscCall(DMGetCoordinateSection(dm, &coordSection));
1028: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
1029: PetscCall(DMPlexGetCellTypeLabel(dm, &celltypeLabel));
1030: PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
1031: PetscCall(PetscSectionGetChart(coordSection, &pStart, &pEnd));
1032: PetscCall(VecGetArrayRead(coordinates, &a));
1033: name[0] = "vertex";
1034: name[1] = "edge";
1035: name[dim - 1] = "face";
1036: name[dim] = "cell";
1037: for (c = cStart; c < cEnd; ++c) {
1038: PetscInt *closure = NULL;
1039: PetscInt closureSize, cl, ct;
1041: PetscCall(DMLabelGetValue(celltypeLabel, c, &ct));
1042: PetscCall(PetscViewerASCIIPrintf(viewer, "Geometry for cell %" PetscInt_FMT " polytope type %s:\n", c, DMPolytopeTypes[ct]));
1043: PetscCall(DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
1044: PetscCall(PetscViewerASCIIPushTab(viewer));
1045: for (cl = 0; cl < closureSize * 2; cl += 2) {
1046: PetscInt point = closure[cl], depth, dof, off, d, p;
1048: if ((point < pStart) || (point >= pEnd)) continue;
1049: PetscCall(PetscSectionGetDof(coordSection, point, &dof));
1050: if (!dof) continue;
1051: PetscCall(DMLabelGetValue(depthLabel, point, &depth));
1052: PetscCall(PetscSectionGetOffset(coordSection, point, &off));
1053: PetscCall(PetscViewerASCIIPrintf(viewer, "%s %" PetscInt_FMT " coords:", name[depth], point));
1054: for (p = 0; p < dof / dim; ++p) {
1055: PetscCall(PetscViewerASCIIPrintf(viewer, " ("));
1056: for (d = 0; d < dim; ++d) {
1057: if (d > 0) PetscCall(PetscViewerASCIIPrintf(viewer, ", "));
1058: PetscCall(PetscViewerASCIIPrintf(viewer, "%g", (double)PetscRealPart(a[off + p * dim + d])));
1059: }
1060: PetscCall(PetscViewerASCIIPrintf(viewer, ")"));
1061: }
1062: PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
1063: }
1064: PetscCall(DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
1065: PetscCall(PetscViewerASCIIPopTab(viewer));
1066: }
1067: PetscCall(VecRestoreArrayRead(coordinates, &a));
1068: PetscFunctionReturn(PETSC_SUCCESS);
1069: }
1071: typedef enum {
1072: CS_CARTESIAN,
1073: CS_POLAR,
1074: CS_CYLINDRICAL,
1075: CS_SPHERICAL
1076: } CoordSystem;
1077: const char *CoordSystems[] = {"cartesian", "polar", "cylindrical", "spherical", "CoordSystem", "CS_", NULL};
1079: static PetscErrorCode DMPlexView_Ascii_Coordinates(PetscViewer viewer, CoordSystem cs, PetscInt dim, const PetscScalar x[])
1080: {
1081: PetscFunctionBegin;
1082: if (dim > 3) {
1083: for (PetscInt i = 0; i < dim; ++i) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " %g", (double)PetscRealPart(x[i])));
1084: } else {
1085: PetscReal coords[3], trcoords[3] = {0., 0., 0.};
1087: for (PetscInt i = 0; i < dim; ++i) coords[i] = PetscRealPart(x[i]);
1088: switch (cs) {
1089: case CS_CARTESIAN:
1090: for (PetscInt i = 0; i < dim; ++i) trcoords[i] = coords[i];
1091: break;
1092: case CS_POLAR:
1093: PetscCheck(dim == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Polar coordinates are for 2 dimension, not %" PetscInt_FMT, dim);
1094: trcoords[0] = PetscSqrtReal(PetscSqr(coords[0]) + PetscSqr(coords[1]));
1095: trcoords[1] = PetscAtan2Real(coords[1], coords[0]);
1096: break;
1097: case CS_CYLINDRICAL:
1098: PetscCheck(dim == 3, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cylindrical coordinates are for 3 dimension, not %" PetscInt_FMT, dim);
1099: trcoords[0] = PetscSqrtReal(PetscSqr(coords[0]) + PetscSqr(coords[1]));
1100: trcoords[1] = PetscAtan2Real(coords[1], coords[0]);
1101: trcoords[2] = coords[2];
1102: break;
1103: case CS_SPHERICAL:
1104: PetscCheck(dim == 3, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Spherical coordinates are for 3 dimension, not %" PetscInt_FMT, dim);
1105: trcoords[0] = PetscSqrtReal(PetscSqr(coords[0]) + PetscSqr(coords[1]) + PetscSqr(coords[2]));
1106: trcoords[1] = PetscAtan2Real(PetscSqrtReal(PetscSqr(coords[0]) + PetscSqr(coords[1])), coords[2]);
1107: trcoords[2] = PetscAtan2Real(coords[1], coords[0]);
1108: break;
1109: }
1110: for (PetscInt i = 0; i < dim; ++i) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " %g", (double)trcoords[i]));
1111: }
1112: PetscFunctionReturn(PETSC_SUCCESS);
1113: }
1115: static PetscErrorCode DMPlexView_Ascii(DM dm, PetscViewer viewer)
1116: {
1117: DM_Plex *mesh = (DM_Plex *)dm->data;
1118: DM cdm, cdmCell;
1119: PetscSection coordSection, coordSectionCell;
1120: Vec coordinates, coordinatesCell;
1121: PetscViewerFormat format;
1123: PetscFunctionBegin;
1124: PetscCall(PetscViewerGetFormat(viewer, &format));
1125: if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1126: const char *name;
1127: PetscInt dim, cellHeight, maxConeSize, maxSupportSize;
1128: PetscInt pStart, pEnd, p, numLabels, l;
1129: PetscMPIInt rank, size;
1131: PetscCall(DMGetCoordinateDM(dm, &cdm));
1132: PetscCall(DMGetCoordinateSection(dm, &coordSection));
1133: PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
1134: PetscCall(DMGetCellCoordinateDM(dm, &cdmCell));
1135: PetscCall(DMGetCellCoordinateSection(dm, &coordSectionCell));
1136: PetscCall(DMGetCellCoordinatesLocal(dm, &coordinatesCell));
1137: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
1138: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
1139: PetscCall(PetscObjectGetName((PetscObject)dm, &name));
1140: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
1141: PetscCall(DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize));
1142: PetscCall(DMGetDimension(dm, &dim));
1143: PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
1144: if (name) PetscCall(PetscViewerASCIIPrintf(viewer, "%s in %" PetscInt_FMT " dimension%s:\n", name, dim, dim == 1 ? "" : "s"));
1145: else PetscCall(PetscViewerASCIIPrintf(viewer, "Mesh in %" PetscInt_FMT " dimension%s:\n", dim, dim == 1 ? "" : "s"));
1146: if (cellHeight) PetscCall(PetscViewerASCIIPrintf(viewer, " Cells are at height %" PetscInt_FMT "\n", cellHeight));
1147: PetscCall(PetscViewerASCIIPrintf(viewer, "Supports:\n"));
1148: PetscCall(PetscViewerASCIIPushSynchronized(viewer));
1149: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Max support size: %" PetscInt_FMT "\n", rank, maxSupportSize));
1150: for (p = pStart; p < pEnd; ++p) {
1151: PetscInt dof, off, s;
1153: PetscCall(PetscSectionGetDof(mesh->supportSection, p, &dof));
1154: PetscCall(PetscSectionGetOffset(mesh->supportSection, p, &off));
1155: for (s = off; s < off + dof; ++s) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d]: %" PetscInt_FMT " ----> %" PetscInt_FMT "\n", rank, p, mesh->supports[s]));
1156: }
1157: PetscCall(PetscViewerFlush(viewer));
1158: PetscCall(PetscViewerASCIIPrintf(viewer, "Cones:\n"));
1159: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Max cone size: %" PetscInt_FMT "\n", rank, maxConeSize));
1160: for (p = pStart; p < pEnd; ++p) {
1161: PetscInt dof, off, c;
1163: PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
1164: PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
1165: for (c = off; c < off + dof; ++c) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d]: %" PetscInt_FMT " <---- %" PetscInt_FMT " (%" PetscInt_FMT ")\n", rank, p, mesh->cones[c], mesh->coneOrientations[c]));
1166: }
1167: PetscCall(PetscViewerFlush(viewer));
1168: PetscCall(PetscViewerASCIIPopSynchronized(viewer));
1169: if (coordSection && coordinates) {
1170: CoordSystem cs = CS_CARTESIAN;
1171: const PetscScalar *array, *arrayCell = NULL;
1172: PetscInt Nf, Nc, pvStart, pvEnd, pcStart = PETSC_INT_MAX, pcEnd = PETSC_INT_MIN, pStart, pEnd, p;
1173: PetscMPIInt rank;
1174: const char *name;
1176: PetscCall(PetscOptionsGetEnum(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_coord_system", CoordSystems, (PetscEnum *)&cs, NULL));
1177: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)viewer), &rank));
1178: PetscCall(PetscSectionGetNumFields(coordSection, &Nf));
1179: PetscCheck(Nf == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Coordinate section should have 1 field, not %" PetscInt_FMT, Nf);
1180: PetscCall(PetscSectionGetFieldComponents(coordSection, 0, &Nc));
1181: PetscCall(PetscSectionGetChart(coordSection, &pvStart, &pvEnd));
1182: if (coordSectionCell) PetscCall(PetscSectionGetChart(coordSectionCell, &pcStart, &pcEnd));
1183: pStart = PetscMin(pvStart, pcStart);
1184: pEnd = PetscMax(pvEnd, pcEnd);
1185: PetscCall(PetscObjectGetName((PetscObject)coordinates, &name));
1186: PetscCall(PetscViewerASCIIPrintf(viewer, "%s with %" PetscInt_FMT " fields\n", name, Nf));
1187: PetscCall(PetscViewerASCIIPrintf(viewer, " field 0 with %" PetscInt_FMT " components\n", Nc));
1188: if (cs != CS_CARTESIAN) PetscCall(PetscViewerASCIIPrintf(viewer, " output coordinate system: %s\n", CoordSystems[cs]));
1190: PetscCall(VecGetArrayRead(coordinates, &array));
1191: if (coordinatesCell) PetscCall(VecGetArrayRead(coordinatesCell, &arrayCell));
1192: PetscCall(PetscViewerASCIIPushSynchronized(viewer));
1193: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "Process %d:\n", rank));
1194: for (p = pStart; p < pEnd; ++p) {
1195: PetscInt dof, off;
1197: if (p >= pvStart && p < pvEnd) {
1198: PetscCall(PetscSectionGetDof(coordSection, p, &dof));
1199: PetscCall(PetscSectionGetOffset(coordSection, p, &off));
1200: if (dof) {
1201: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " (%4" PetscInt_FMT ") dof %2" PetscInt_FMT " offset %3" PetscInt_FMT, p, dof, off));
1202: PetscCall(DMPlexView_Ascii_Coordinates(viewer, cs, dof, &array[off]));
1203: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\n"));
1204: }
1205: }
1206: if (cdmCell && p >= pcStart && p < pcEnd) {
1207: PetscCall(PetscSectionGetDof(coordSectionCell, p, &dof));
1208: PetscCall(PetscSectionGetOffset(coordSectionCell, p, &off));
1209: if (dof) {
1210: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " (%4" PetscInt_FMT ") dof %2" PetscInt_FMT " offset %3" PetscInt_FMT, p, dof, off));
1211: PetscCall(DMPlexView_Ascii_Coordinates(viewer, cs, dof, &arrayCell[off]));
1212: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\n"));
1213: }
1214: }
1215: }
1216: PetscCall(PetscViewerFlush(viewer));
1217: PetscCall(PetscViewerASCIIPopSynchronized(viewer));
1218: PetscCall(VecRestoreArrayRead(coordinates, &array));
1219: if (coordinatesCell) PetscCall(VecRestoreArrayRead(coordinatesCell, &arrayCell));
1220: }
1221: PetscCall(DMGetNumLabels(dm, &numLabels));
1222: if (numLabels) PetscCall(PetscViewerASCIIPrintf(viewer, "Labels:\n"));
1223: for (l = 0; l < numLabels; ++l) {
1224: DMLabel label;
1225: PetscBool isdepth;
1226: const char *name;
1228: PetscCall(DMGetLabelName(dm, l, &name));
1229: PetscCall(PetscStrcmp(name, "depth", &isdepth));
1230: if (isdepth) continue;
1231: PetscCall(DMGetLabel(dm, name, &label));
1232: PetscCall(DMLabelView(label, viewer));
1233: }
1234: if (size > 1) {
1235: PetscSF sf;
1237: PetscCall(DMGetPointSF(dm, &sf));
1238: PetscCall(PetscSFView(sf, viewer));
1239: }
1240: if (mesh->periodic.face_sfs)
1241: for (PetscInt i = 0; i < mesh->periodic.num_face_sfs; i++) PetscCall(PetscSFView(mesh->periodic.face_sfs[i], viewer));
1242: PetscCall(PetscViewerFlush(viewer));
1243: } else if (format == PETSC_VIEWER_ASCII_LATEX) {
1244: const char *name, *color;
1245: const char *defcolors[3] = {"gray", "orange", "green"};
1246: const char *deflcolors[4] = {"blue", "cyan", "red", "magenta"};
1247: char lname[PETSC_MAX_PATH_LEN];
1248: PetscReal scale = 2.0;
1249: PetscReal tikzscale = 1.0;
1250: PetscBool useNumbers = PETSC_TRUE, drawNumbers[4], drawColors[4], useLabels, useColors, plotEdges, drawHasse = PETSC_FALSE;
1251: double tcoords[3];
1252: PetscScalar *coords;
1253: PetscInt numLabels, l, numColors, numLColors, dim, d, depth, cStart, cEnd, c, vStart, vEnd, v, eStart = 0, eEnd = 0, fStart = 0, fEnd = 0, e, p, n;
1254: PetscMPIInt rank, size;
1255: char **names, **colors, **lcolors;
1256: PetscBool flg, lflg;
1257: PetscBT wp = NULL;
1258: PetscInt pEnd, pStart;
1260: PetscCall(DMGetCoordinateDM(dm, &cdm));
1261: PetscCall(DMGetCoordinateSection(dm, &coordSection));
1262: PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
1263: PetscCall(DMGetCellCoordinateDM(dm, &cdmCell));
1264: PetscCall(DMGetCellCoordinateSection(dm, &coordSectionCell));
1265: PetscCall(DMGetCellCoordinatesLocal(dm, &coordinatesCell));
1266: PetscCall(DMGetDimension(dm, &dim));
1267: PetscCall(DMPlexGetDepth(dm, &depth));
1268: PetscCall(DMGetNumLabels(dm, &numLabels));
1269: numLabels = PetscMax(numLabels, 10);
1270: numColors = 10;
1271: numLColors = 10;
1272: PetscCall(PetscCalloc3(numLabels, &names, numColors, &colors, numLColors, &lcolors));
1273: PetscCall(PetscOptionsGetReal(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_scale", &scale, NULL));
1274: PetscCall(PetscOptionsGetReal(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_tikzscale", &tikzscale, NULL));
1275: PetscCall(PetscOptionsGetBool(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_numbers", &useNumbers, NULL));
1276: for (d = 0; d < 4; ++d) drawNumbers[d] = useNumbers;
1277: for (d = 0; d < 4; ++d) drawColors[d] = PETSC_TRUE;
1278: n = 4;
1279: PetscCall(PetscOptionsGetBoolArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_numbers_depth", drawNumbers, &n, &flg));
1280: PetscCheck(!flg || n == dim + 1, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Number of flags %" PetscInt_FMT " != %" PetscInt_FMT " dim+1", n, dim + 1);
1281: n = 4;
1282: PetscCall(PetscOptionsGetBoolArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_colors_depth", drawColors, &n, &flg));
1283: PetscCheck(!flg || n == dim + 1, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Number of flags %" PetscInt_FMT " != %" PetscInt_FMT " dim+1", n, dim + 1);
1284: PetscCall(PetscOptionsGetStringArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_labels", names, &numLabels, &useLabels));
1285: if (!useLabels) numLabels = 0;
1286: PetscCall(PetscOptionsGetStringArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_colors", colors, &numColors, &useColors));
1287: if (!useColors) {
1288: numColors = 3;
1289: for (c = 0; c < numColors; ++c) PetscCall(PetscStrallocpy(defcolors[c], &colors[c]));
1290: }
1291: PetscCall(PetscOptionsGetStringArray(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_lcolors", lcolors, &numLColors, &useColors));
1292: if (!useColors) {
1293: numLColors = 4;
1294: for (c = 0; c < numLColors; ++c) PetscCall(PetscStrallocpy(deflcolors[c], &lcolors[c]));
1295: }
1296: PetscCall(PetscOptionsGetString(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_label_filter", lname, sizeof(lname), &lflg));
1297: plotEdges = (PetscBool)(depth > 1 && drawNumbers[1] && dim < 3);
1298: PetscCall(PetscOptionsGetBool(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_edges", &plotEdges, &flg));
1299: PetscCheck(!flg || !plotEdges || depth >= dim, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Mesh must be interpolated");
1300: if (depth < dim) plotEdges = PETSC_FALSE;
1301: PetscCall(PetscOptionsGetBool(((PetscObject)viewer)->options, ((PetscObject)viewer)->prefix, "-dm_plex_view_hasse", &drawHasse, NULL));
1303: /* filter points with labelvalue != labeldefaultvalue */
1304: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
1305: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
1306: PetscCall(DMPlexGetDepthStratum(dm, 1, &eStart, &eEnd));
1307: PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
1308: PetscCall(DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd));
1309: if (lflg) {
1310: DMLabel lbl;
1312: PetscCall(DMGetLabel(dm, lname, &lbl));
1313: if (lbl) {
1314: PetscInt val, defval;
1316: PetscCall(DMLabelGetDefaultValue(lbl, &defval));
1317: PetscCall(PetscBTCreate(pEnd - pStart, &wp));
1318: for (c = pStart; c < pEnd; c++) {
1319: PetscInt *closure = NULL;
1320: PetscInt closureSize;
1322: PetscCall(DMLabelGetValue(lbl, c, &val));
1323: if (val == defval) continue;
1325: PetscCall(DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
1326: for (p = 0; p < closureSize * 2; p += 2) PetscCall(PetscBTSet(wp, closure[p] - pStart));
1327: PetscCall(DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
1328: }
1329: }
1330: }
1332: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
1333: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)dm), &size));
1334: PetscCall(PetscObjectGetName((PetscObject)dm, &name));
1335: PetscCall(PetscViewerASCIIPrintf(viewer, "\
1336: \\documentclass[tikz]{standalone}\n\n\
1337: \\usepackage{pgflibraryshapes}\n\
1338: \\usetikzlibrary{backgrounds}\n\
1339: \\usetikzlibrary{arrows}\n\
1340: \\begin{document}\n"));
1341: if (size > 1) {
1342: PetscCall(PetscViewerASCIIPrintf(viewer, "%s for process ", name));
1343: for (p = 0; p < size; ++p) {
1344: if (p) PetscCall(PetscViewerASCIIPrintf(viewer, (p == size - 1) ? ", and " : ", "));
1345: PetscCall(PetscViewerASCIIPrintf(viewer, "{\\textcolor{%s}%" PetscInt_FMT "}", colors[p % numColors], p));
1346: }
1347: PetscCall(PetscViewerASCIIPrintf(viewer, ".\n\n\n"));
1348: }
1349: if (drawHasse) {
1350: PetscInt maxStratum = PetscMax(vEnd - vStart, PetscMax(eEnd - eStart, PetscMax(fEnd - fStart, cEnd - cStart)));
1352: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\vStart}{%" PetscInt_FMT "}\n", vStart));
1353: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\vEnd}{%" PetscInt_FMT "}\n", vEnd - 1));
1354: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\numVertices}{%" PetscInt_FMT "}\n", vEnd - vStart));
1355: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\vShift}{%.2f}\n", 3 + (maxStratum - (vEnd - vStart)) / 2.));
1356: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\eStart}{%" PetscInt_FMT "}\n", eStart));
1357: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\eEnd}{%" PetscInt_FMT "}\n", eEnd - 1));
1358: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\eShift}{%.2f}\n", 3 + (maxStratum - (eEnd - eStart)) / 2.));
1359: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\numEdges}{%" PetscInt_FMT "}\n", eEnd - eStart));
1360: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\fStart}{%" PetscInt_FMT "}\n", fStart));
1361: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\fEnd}{%" PetscInt_FMT "}\n", fEnd - 1));
1362: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\fShift}{%.2f}\n", 3 + (maxStratum - (fEnd - fStart)) / 2.));
1363: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\numFaces}{%" PetscInt_FMT "}\n", fEnd - fStart));
1364: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\cStart}{%" PetscInt_FMT "}\n", cStart));
1365: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\cEnd}{%" PetscInt_FMT "}\n", cEnd - 1));
1366: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\numCells}{%" PetscInt_FMT "}\n", cEnd - cStart));
1367: PetscCall(PetscViewerASCIIPrintf(viewer, "\\newcommand{\\cShift}{%.2f}\n", 3 + (maxStratum - (cEnd - cStart)) / 2.));
1368: }
1369: PetscCall(PetscViewerASCIIPrintf(viewer, "\\begin{tikzpicture}[scale = %g,font=\\fontsize{8}{8}\\selectfont]\n", (double)tikzscale));
1371: /* Plot vertices */
1372: PetscCall(VecGetArray(coordinates, &coords));
1373: PetscCall(PetscViewerASCIIPushSynchronized(viewer));
1374: for (v = vStart; v < vEnd; ++v) {
1375: PetscInt off, dof, d;
1376: PetscBool isLabeled = PETSC_FALSE;
1378: if (wp && !PetscBTLookup(wp, v - pStart)) continue;
1379: PetscCall(PetscSectionGetDof(coordSection, v, &dof));
1380: PetscCall(PetscSectionGetOffset(coordSection, v, &off));
1381: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\\path ("));
1382: PetscCheck(dof <= 3, PETSC_COMM_SELF, PETSC_ERR_PLIB, "coordSection vertex %" PetscInt_FMT " has dof %" PetscInt_FMT " > 3", v, dof);
1383: for (d = 0; d < dof; ++d) {
1384: tcoords[d] = (double)(scale * PetscRealPart(coords[off + d]));
1385: tcoords[d] = PetscAbs(tcoords[d]) < 1e-10 ? 0.0 : tcoords[d];
1386: }
1387: /* Rotate coordinates since PGF makes z point out of the page instead of up */
1388: if (dim == 3) {
1389: PetscReal tmp = tcoords[1];
1390: tcoords[1] = tcoords[2];
1391: tcoords[2] = -tmp;
1392: }
1393: for (d = 0; d < dof; ++d) {
1394: if (d > 0) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ","));
1395: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%g", tcoords[d]));
1396: }
1397: if (drawHasse) color = colors[0 % numColors];
1398: else color = colors[rank % numColors];
1399: for (l = 0; l < numLabels; ++l) {
1400: PetscInt val;
1401: PetscCall(DMGetLabelValue(dm, names[l], v, &val));
1402: if (val >= 0) {
1403: color = lcolors[l % numLColors];
1404: isLabeled = PETSC_TRUE;
1405: break;
1406: }
1407: }
1408: if (drawNumbers[0]) {
1409: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [draw,shape=circle,color=%s] {%" PetscInt_FMT "};\n", v, rank, color, v));
1410: } else if (drawColors[0]) {
1411: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [fill,inner sep=%dpt,shape=circle,color=%s] {};\n", v, rank, !isLabeled ? 1 : 2, color));
1412: } else PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [] {};\n", v, rank));
1413: }
1414: PetscCall(VecRestoreArray(coordinates, &coords));
1415: PetscCall(PetscViewerFlush(viewer));
1416: /* Plot edges */
1417: if (plotEdges) {
1418: PetscCall(VecGetArray(coordinates, &coords));
1419: PetscCall(PetscViewerASCIIPrintf(viewer, "\\path\n"));
1420: for (e = eStart; e < eEnd; ++e) {
1421: const PetscInt *cone;
1422: PetscInt coneSize, offA, offB, dof, d;
1424: if (wp && !PetscBTLookup(wp, e - pStart)) continue;
1425: PetscCall(DMPlexGetConeSize(dm, e, &coneSize));
1426: PetscCheck(coneSize == 2, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Edge %" PetscInt_FMT " cone should have two vertices, not %" PetscInt_FMT, e, coneSize);
1427: PetscCall(DMPlexGetCone(dm, e, &cone));
1428: PetscCall(PetscSectionGetDof(coordSection, cone[0], &dof));
1429: PetscCall(PetscSectionGetOffset(coordSection, cone[0], &offA));
1430: PetscCall(PetscSectionGetOffset(coordSection, cone[1], &offB));
1431: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "("));
1432: for (d = 0; d < dof; ++d) {
1433: tcoords[d] = (double)(scale * PetscRealPart(coords[offA + d] + coords[offB + d]) / 2);
1434: tcoords[d] = PetscAbs(tcoords[d]) < 1e-10 ? 0.0 : tcoords[d];
1435: }
1436: /* Rotate coordinates since PGF makes z point out of the page instead of up */
1437: if (dim == 3) {
1438: PetscReal tmp = tcoords[1];
1439: tcoords[1] = tcoords[2];
1440: tcoords[2] = -tmp;
1441: }
1442: for (d = 0; d < dof; ++d) {
1443: if (d > 0) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ","));
1444: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%g", tcoords[d]));
1445: }
1446: if (drawHasse) color = colors[1 % numColors];
1447: else color = colors[rank % numColors];
1448: for (l = 0; l < numLabels; ++l) {
1449: PetscInt val;
1450: PetscCall(DMGetLabelValue(dm, names[l], e, &val));
1451: if (val >= 0) {
1452: color = lcolors[l % numLColors];
1453: break;
1454: }
1455: }
1456: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [draw,shape=circle,color=%s] {%" PetscInt_FMT "} --\n", e, rank, color, e));
1457: }
1458: PetscCall(VecRestoreArray(coordinates, &coords));
1459: PetscCall(PetscViewerFlush(viewer));
1460: PetscCall(PetscViewerASCIIPrintf(viewer, "(0,0);\n"));
1461: }
1462: /* Plot cells */
1463: if (dim == 3 || !drawNumbers[1]) {
1464: for (e = eStart; e < eEnd; ++e) {
1465: const PetscInt *cone;
1467: if (wp && !PetscBTLookup(wp, e - pStart)) continue;
1468: color = colors[rank % numColors];
1469: for (l = 0; l < numLabels; ++l) {
1470: PetscInt val;
1471: PetscCall(DMGetLabelValue(dm, names[l], e, &val));
1472: if (val >= 0) {
1473: color = lcolors[l % numLColors];
1474: break;
1475: }
1476: }
1477: PetscCall(DMPlexGetCone(dm, e, &cone));
1478: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\\draw[color=%s] (%" PetscInt_FMT "_%d) -- (%" PetscInt_FMT "_%d);\n", color, cone[0], rank, cone[1], rank));
1479: }
1480: } else {
1481: DMPolytopeType ct;
1483: /* Drawing a 2D polygon */
1484: for (c = cStart; c < cEnd; ++c) {
1485: if (wp && !PetscBTLookup(wp, c - pStart)) continue;
1486: PetscCall(DMPlexGetCellType(dm, c, &ct));
1487: if (DMPolytopeTypeIsHybrid(ct)) {
1488: const PetscInt *cone;
1489: PetscInt coneSize;
1491: PetscCall(DMPlexGetCone(dm, c, &cone));
1492: PetscCall(DMPlexGetConeSize(dm, c, &coneSize));
1493: for (PetscInt e = 0; e < coneSize; ++e) {
1494: const PetscInt *econe;
1496: PetscCall(DMPlexGetCone(dm, cone[e], &econe));
1497: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\\draw[color=%s] (%" PetscInt_FMT "_%d) -- (%" PetscInt_FMT "_%d) -- (%" PetscInt_FMT "_%d);\n", colors[rank % numColors], econe[0], rank, cone[e], rank, econe[1], rank));
1498: }
1499: } else {
1500: PetscInt *closure = NULL;
1501: PetscInt closureSize, Nv = 0, v;
1503: PetscCall(DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
1504: for (p = 0; p < closureSize * 2; p += 2) {
1505: const PetscInt point = closure[p];
1507: if ((point >= vStart) && (point < vEnd)) closure[Nv++] = point;
1508: }
1509: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\\draw[color=%s] ", colors[rank % numColors]));
1510: for (v = 0; v <= Nv; ++v) {
1511: const PetscInt vertex = closure[v % Nv];
1513: if (v > 0) {
1514: if (plotEdges) {
1515: const PetscInt *edge;
1516: PetscInt endpoints[2], ne;
1518: endpoints[0] = closure[v - 1];
1519: endpoints[1] = vertex;
1520: PetscCall(DMPlexGetJoin(dm, 2, endpoints, &ne, &edge));
1521: PetscCheck(ne == 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Could not find edge for vertices %" PetscInt_FMT ", %" PetscInt_FMT, endpoints[0], endpoints[1]);
1522: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " -- (%" PetscInt_FMT "_%d) -- ", edge[0], rank));
1523: PetscCall(DMPlexRestoreJoin(dm, 2, endpoints, &ne, &edge));
1524: } else PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " -- "));
1525: }
1526: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "(%" PetscInt_FMT "_%d)", vertex, rank));
1527: }
1528: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ";\n"));
1529: PetscCall(DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
1530: }
1531: }
1532: }
1533: for (c = cStart; c < cEnd; ++c) {
1534: double ccoords[3] = {0.0, 0.0, 0.0};
1535: PetscBool isLabeled = PETSC_FALSE;
1536: PetscScalar *cellCoords = NULL;
1537: const PetscScalar *array;
1538: PetscInt numCoords, cdim, d;
1539: PetscBool isDG;
1541: if (wp && !PetscBTLookup(wp, c - pStart)) continue;
1542: PetscCall(DMGetCoordinateDim(dm, &cdim));
1543: PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &array, &cellCoords));
1544: PetscCheck(!(numCoords % cdim), PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "coordinate dim %" PetscInt_FMT " does not divide numCoords %" PetscInt_FMT, cdim, numCoords);
1545: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\\path ("));
1546: for (p = 0; p < numCoords / cdim; ++p) {
1547: for (d = 0; d < cdim; ++d) {
1548: tcoords[d] = (double)(scale * PetscRealPart(cellCoords[p * cdim + d]));
1549: tcoords[d] = PetscAbs(tcoords[d]) < 1e-10 ? 0.0 : tcoords[d];
1550: }
1551: /* Rotate coordinates since PGF makes z point out of the page instead of up */
1552: if (cdim == 3) {
1553: PetscReal tmp = tcoords[1];
1554: tcoords[1] = tcoords[2];
1555: tcoords[2] = -tmp;
1556: }
1557: for (d = 0; d < dim; ++d) ccoords[d] += tcoords[d];
1558: }
1559: for (d = 0; d < cdim; ++d) ccoords[d] /= (numCoords / cdim);
1560: PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &array, &cellCoords));
1561: for (d = 0; d < cdim; ++d) {
1562: if (d > 0) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ","));
1563: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%g", ccoords[d]));
1564: }
1565: if (drawHasse) color = colors[depth % numColors];
1566: else color = colors[rank % numColors];
1567: for (l = 0; l < numLabels; ++l) {
1568: PetscInt val;
1569: PetscCall(DMGetLabelValue(dm, names[l], c, &val));
1570: if (val >= 0) {
1571: color = lcolors[l % numLColors];
1572: isLabeled = PETSC_TRUE;
1573: break;
1574: }
1575: }
1576: if (drawNumbers[dim]) {
1577: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [draw,shape=circle,color=%s] {%" PetscInt_FMT "};\n", c, rank, color, c));
1578: } else if (drawColors[dim]) {
1579: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [fill,inner sep=%dpt,shape=circle,color=%s] {};\n", c, rank, !isLabeled ? 1 : 2, color));
1580: } else PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ") node(%" PetscInt_FMT "_%d) [] {};\n", c, rank));
1581: }
1582: if (drawHasse) {
1583: int height = 0;
1585: color = colors[depth % numColors];
1586: PetscCall(PetscViewerASCIIPrintf(viewer, "%% Cells\n"));
1587: PetscCall(PetscViewerASCIIPrintf(viewer, "\\foreach \\c in {\\cStart,...,\\cEnd}\n"));
1588: PetscCall(PetscViewerASCIIPrintf(viewer, "{\n"));
1589: PetscCall(PetscViewerASCIIPrintf(viewer, " \\node(\\c_%d) [draw,shape=circle,color=%s,minimum size = 6mm] at (\\cShift+\\c-\\cStart,%d) {\\c};\n", rank, color, height++));
1590: PetscCall(PetscViewerASCIIPrintf(viewer, "}\n"));
1592: if (depth > 2) {
1593: color = colors[1 % numColors];
1594: PetscCall(PetscViewerASCIIPrintf(viewer, "%% Faces\n"));
1595: PetscCall(PetscViewerASCIIPrintf(viewer, "\\foreach \\f in {\\fStart,...,\\fEnd}\n"));
1596: PetscCall(PetscViewerASCIIPrintf(viewer, "{\n"));
1597: PetscCall(PetscViewerASCIIPrintf(viewer, " \\node(\\f_%d) [draw,shape=circle,color=%s,minimum size = 6mm] at (\\fShift+\\f-\\fStart,%d) {\\f};\n", rank, color, height++));
1598: PetscCall(PetscViewerASCIIPrintf(viewer, "}\n"));
1599: }
1601: color = colors[1 % numColors];
1602: PetscCall(PetscViewerASCIIPrintf(viewer, "%% Edges\n"));
1603: PetscCall(PetscViewerASCIIPrintf(viewer, "\\foreach \\e in {\\eStart,...,\\eEnd}\n"));
1604: PetscCall(PetscViewerASCIIPrintf(viewer, "{\n"));
1605: PetscCall(PetscViewerASCIIPrintf(viewer, " \\node(\\e_%d) [draw,shape=circle,color=%s,minimum size = 6mm] at (\\eShift+\\e-\\eStart,%d) {\\e};\n", rank, color, height++));
1606: PetscCall(PetscViewerASCIIPrintf(viewer, "}\n"));
1608: color = colors[0 % numColors];
1609: PetscCall(PetscViewerASCIIPrintf(viewer, "%% Vertices\n"));
1610: PetscCall(PetscViewerASCIIPrintf(viewer, "\\foreach \\v in {\\vStart,...,\\vEnd}\n"));
1611: PetscCall(PetscViewerASCIIPrintf(viewer, "{\n"));
1612: PetscCall(PetscViewerASCIIPrintf(viewer, " \\node(\\v_%d) [draw,shape=circle,color=%s,minimum size = 6mm] at (\\vShift+\\v-\\vStart,%d) {\\v};\n", rank, color, height++));
1613: PetscCall(PetscViewerASCIIPrintf(viewer, "}\n"));
1615: for (p = pStart; p < pEnd; ++p) {
1616: const PetscInt *cone;
1617: PetscInt coneSize;
1619: PetscCall(DMPlexGetCone(dm, p, &cone));
1620: PetscCall(DMPlexGetConeSize(dm, p, &coneSize));
1621: for (PetscInt cp = 0; cp < coneSize; ++cp) PetscCall(PetscViewerASCIIPrintf(viewer, "\\draw[->, shorten >=1pt] (%" PetscInt_FMT "_%d) -- (%" PetscInt_FMT "_%d);\n", cone[cp], rank, p, rank));
1622: }
1623: }
1624: PetscCall(PetscViewerFlush(viewer));
1625: PetscCall(PetscViewerASCIIPopSynchronized(viewer));
1626: PetscCall(PetscViewerASCIIPrintf(viewer, "\\end{tikzpicture}\n"));
1627: PetscCall(PetscViewerASCIIPrintf(viewer, "\\end{document}\n"));
1628: for (l = 0; l < numLabels; ++l) PetscCall(PetscFree(names[l]));
1629: for (c = 0; c < numColors; ++c) PetscCall(PetscFree(colors[c]));
1630: for (c = 0; c < numLColors; ++c) PetscCall(PetscFree(lcolors[c]));
1631: PetscCall(PetscFree3(names, colors, lcolors));
1632: PetscCall(PetscBTDestroy(&wp));
1633: } else if (format == PETSC_VIEWER_LOAD_BALANCE) {
1634: Vec cown, acown;
1635: VecScatter sct;
1636: ISLocalToGlobalMapping g2l;
1637: IS gid, acis;
1638: MPI_Comm comm, ncomm = MPI_COMM_NULL;
1639: MPI_Group ggroup, ngroup;
1640: PetscScalar *array, nid;
1641: const PetscInt *idxs;
1642: PetscInt *idxs2, *start, *adjacency, *work;
1643: PetscInt64 lm[3], gm[3];
1644: PetscInt i, c, cStart, cEnd, cum, numVertices, ect, ectn, cellHeight;
1645: PetscMPIInt d1, d2, rank;
1647: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
1648: PetscCallMPI(MPI_Comm_rank(comm, &rank));
1649: #if defined(PETSC_HAVE_MPI_PROCESS_SHARED_MEMORY)
1650: PetscCallMPI(MPI_Comm_split_type(comm, MPI_COMM_TYPE_SHARED, rank, MPI_INFO_NULL, &ncomm));
1651: #endif
1652: if (ncomm != MPI_COMM_NULL) {
1653: PetscCallMPI(MPI_Comm_group(comm, &ggroup));
1654: PetscCallMPI(MPI_Comm_group(ncomm, &ngroup));
1655: d1 = 0;
1656: PetscCallMPI(MPI_Group_translate_ranks(ngroup, 1, &d1, ggroup, &d2));
1657: nid = d2;
1658: PetscCallMPI(MPI_Group_free(&ggroup));
1659: PetscCallMPI(MPI_Group_free(&ngroup));
1660: PetscCallMPI(MPI_Comm_free(&ncomm));
1661: } else nid = 0.0;
1663: /* Get connectivity */
1664: PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
1665: PetscCall(DMPlexCreatePartitionerGraph(dm, cellHeight, &numVertices, &start, &adjacency, &gid));
1667: /* filter overlapped local cells */
1668: PetscCall(DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd));
1669: PetscCall(ISGetIndices(gid, &idxs));
1670: PetscCall(ISGetLocalSize(gid, &cum));
1671: PetscCall(PetscMalloc1(cum, &idxs2));
1672: for (c = cStart, cum = 0; c < cEnd; c++) {
1673: if (idxs[c - cStart] < 0) continue;
1674: idxs2[cum++] = idxs[c - cStart];
1675: }
1676: PetscCall(ISRestoreIndices(gid, &idxs));
1677: PetscCheck(numVertices == cum, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Unexpected %" PetscInt_FMT " != %" PetscInt_FMT, numVertices, cum);
1678: PetscCall(ISDestroy(&gid));
1679: PetscCall(ISCreateGeneral(comm, numVertices, idxs2, PETSC_OWN_POINTER, &gid));
1681: /* support for node-aware cell locality */
1682: PetscCall(ISCreateGeneral(comm, start[numVertices], adjacency, PETSC_USE_POINTER, &acis));
1683: PetscCall(VecCreateSeq(PETSC_COMM_SELF, start[numVertices], &acown));
1684: PetscCall(VecCreateMPI(comm, numVertices, PETSC_DECIDE, &cown));
1685: PetscCall(VecGetArray(cown, &array));
1686: for (c = 0; c < numVertices; c++) array[c] = nid;
1687: PetscCall(VecRestoreArray(cown, &array));
1688: PetscCall(VecScatterCreate(cown, acis, acown, NULL, &sct));
1689: PetscCall(VecScatterBegin(sct, cown, acown, INSERT_VALUES, SCATTER_FORWARD));
1690: PetscCall(VecScatterEnd(sct, cown, acown, INSERT_VALUES, SCATTER_FORWARD));
1691: PetscCall(ISDestroy(&acis));
1692: PetscCall(VecScatterDestroy(&sct));
1693: PetscCall(VecDestroy(&cown));
1695: /* compute edgeCut */
1696: for (c = 0, cum = 0; c < numVertices; c++) cum = PetscMax(cum, start[c + 1] - start[c]);
1697: PetscCall(PetscMalloc1(cum, &work));
1698: PetscCall(ISLocalToGlobalMappingCreateIS(gid, &g2l));
1699: PetscCall(ISLocalToGlobalMappingSetType(g2l, ISLOCALTOGLOBALMAPPINGHASH));
1700: PetscCall(ISDestroy(&gid));
1701: PetscCall(VecGetArray(acown, &array));
1702: for (c = 0, ect = 0, ectn = 0; c < numVertices; c++) {
1703: PetscInt totl;
1705: totl = start[c + 1] - start[c];
1706: PetscCall(ISGlobalToLocalMappingApply(g2l, IS_GTOLM_MASK, totl, adjacency + start[c], NULL, work));
1707: for (i = 0; i < totl; i++) {
1708: if (work[i] < 0) {
1709: ect += 1;
1710: ectn += (array[i + start[c]] != nid) ? 0 : 1;
1711: }
1712: }
1713: }
1714: PetscCall(PetscFree(work));
1715: PetscCall(VecRestoreArray(acown, &array));
1716: lm[0] = numVertices > 0 ? numVertices : PETSC_INT_MAX;
1717: lm[1] = -numVertices;
1718: PetscCallMPI(MPIU_Allreduce(lm, gm, 2, MPIU_INT64, MPI_MIN, comm));
1719: PetscCall(PetscViewerASCIIPrintf(viewer, " Cell balance: %.2f (max %" PetscInt64_FMT ", min %" PetscInt64_FMT, -((double)gm[1]) / ((double)gm[0]), -gm[1], gm[0]));
1720: lm[0] = ect; /* edgeCut */
1721: lm[1] = ectn; /* node-aware edgeCut */
1722: lm[2] = numVertices > 0 ? 0 : 1; /* empty processes */
1723: PetscCallMPI(MPIU_Allreduce(lm, gm, 3, MPIU_INT64, MPI_SUM, comm));
1724: PetscCall(PetscViewerASCIIPrintf(viewer, ", empty %" PetscInt64_FMT ")\n", gm[2]));
1725: #if defined(PETSC_HAVE_MPI_PROCESS_SHARED_MEMORY)
1726: PetscCall(PetscViewerASCIIPrintf(viewer, " Edge Cut: %" PetscInt64_FMT " (on node %.3f)\n", gm[0] / 2, gm[0] ? ((double)gm[1]) / ((double)gm[0]) : 1.));
1727: #else
1728: PetscCall(PetscViewerASCIIPrintf(viewer, " Edge Cut: %" PetscInt64_FMT " (on node %.3f)\n", gm[0] / 2, 0.0));
1729: #endif
1730: PetscCall(ISLocalToGlobalMappingDestroy(&g2l));
1731: PetscCall(PetscFree(start));
1732: PetscCall(PetscFree(adjacency));
1733: PetscCall(VecDestroy(&acown));
1734: } else {
1735: const char *name;
1736: PetscInt *sizes, *hybsizes, *ghostsizes;
1737: PetscInt locDepth, depth, cellHeight, dim, d;
1738: PetscInt pStart, pEnd, p, gcStart, gcEnd, gcNum;
1739: PetscInt numLabels, l, maxSize = 17;
1740: DMPolytopeType ct0 = DM_POLYTOPE_UNKNOWN;
1741: MPI_Comm comm;
1742: PetscMPIInt size, rank;
1744: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
1745: PetscCallMPI(MPI_Comm_size(comm, &size));
1746: PetscCallMPI(MPI_Comm_rank(comm, &rank));
1747: PetscCall(DMGetDimension(dm, &dim));
1748: PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
1749: PetscCall(PetscObjectGetName((PetscObject)dm, &name));
1750: if (name) PetscCall(PetscViewerASCIIPrintf(viewer, "%s in %" PetscInt_FMT " dimension%s:\n", name, dim, dim == 1 ? "" : "s"));
1751: else PetscCall(PetscViewerASCIIPrintf(viewer, "Mesh in %" PetscInt_FMT " dimension%s:\n", dim, dim == 1 ? "" : "s"));
1752: if (cellHeight) PetscCall(PetscViewerASCIIPrintf(viewer, " Cells are at height %" PetscInt_FMT "\n", cellHeight));
1753: PetscCall(DMPlexGetDepth(dm, &locDepth));
1754: PetscCallMPI(MPIU_Allreduce(&locDepth, &depth, 1, MPIU_INT, MPI_MAX, comm));
1755: PetscCall(DMPlexGetCellTypeStratum(dm, DM_POLYTOPE_FV_GHOST, &gcStart, &gcEnd));
1756: gcNum = gcEnd - gcStart;
1757: if (size < maxSize) PetscCall(PetscCalloc3(size, &sizes, size, &hybsizes, size, &ghostsizes));
1758: else PetscCall(PetscCalloc3(3, &sizes, 3, &hybsizes, 3, &ghostsizes));
1759: for (d = 0; d <= depth; d++) {
1760: PetscInt Nc[2] = {0, 0}, ict;
1762: PetscCall(DMPlexGetDepthStratum(dm, d, &pStart, &pEnd));
1763: if (pStart < pEnd) PetscCall(DMPlexGetCellType(dm, pStart, &ct0));
1764: ict = ct0;
1765: PetscCallMPI(MPI_Bcast(&ict, 1, MPIU_INT, 0, comm));
1766: ct0 = (DMPolytopeType)ict;
1767: for (p = pStart; p < pEnd; ++p) {
1768: DMPolytopeType ct;
1770: PetscCall(DMPlexGetCellType(dm, p, &ct));
1771: if (ct == ct0) ++Nc[0];
1772: else ++Nc[1];
1773: }
1774: if (size < maxSize) {
1775: PetscCallMPI(MPI_Gather(&Nc[0], 1, MPIU_INT, sizes, 1, MPIU_INT, 0, comm));
1776: PetscCallMPI(MPI_Gather(&Nc[1], 1, MPIU_INT, hybsizes, 1, MPIU_INT, 0, comm));
1777: if (d == depth) PetscCallMPI(MPI_Gather(&gcNum, 1, MPIU_INT, ghostsizes, 1, MPIU_INT, 0, comm));
1778: PetscCall(PetscViewerASCIIPrintf(viewer, " Number of %" PetscInt_FMT "-cells per rank:", (depth == 1) && d ? dim : d));
1779: for (p = 0; p < size; ++p) {
1780: if (rank == 0) {
1781: PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT, sizes[p] + hybsizes[p]));
1782: if (hybsizes[p] > 0) PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ")", hybsizes[p]));
1783: if (ghostsizes[p] > 0) PetscCall(PetscViewerASCIIPrintf(viewer, " [%" PetscInt_FMT "]", ghostsizes[p]));
1784: }
1785: }
1786: } else {
1787: sizes[0] = Nc[0] + Nc[1];
1788: sizes[1] = Nc[0] + Nc[1];
1789: PetscCall(PetscGlobalMinMaxInt(comm, sizes, sizes));
1790: hybsizes[0] = Nc[1];
1791: hybsizes[1] = Nc[1];
1792: PetscCall(PetscGlobalMinMaxInt(comm, hybsizes, hybsizes));
1793: if (d == depth) {
1794: ghostsizes[0] = gcNum;
1795: ghostsizes[1] = gcNum;
1796: PetscCall(PetscGlobalMinMaxInt(comm, ghostsizes, ghostsizes));
1797: }
1798: PetscCall(PetscViewerASCIIPrintf(viewer, " Min/Max of %" PetscInt_FMT "-cells per rank:", (depth == 1) && d ? dim : d));
1799: PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT "/%" PetscInt_FMT, sizes[0], sizes[1]));
1800: if (hybsizes[0] > 0) PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT "/%" PetscInt_FMT ")", hybsizes[0], hybsizes[1]));
1801: if (ghostsizes[0] > 0) PetscCall(PetscViewerASCIIPrintf(viewer, " [%" PetscInt_FMT "/%" PetscInt_FMT "]", ghostsizes[0], ghostsizes[1]));
1802: }
1803: PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
1804: }
1805: PetscCall(PetscFree3(sizes, hybsizes, ghostsizes));
1806: {
1807: DM cdm;
1808: const PetscReal *maxCell;
1809: const PetscReal *L;
1810: PetscBool localized;
1812: PetscCall(DMGetCoordinateDM(dm, &cdm));
1813: PetscCall(DMViewDSFromOptions_Internal(cdm, "-plex_view_ds"));
1814: PetscCall(DMViewSectionFromOptions_Internal(cdm, "-plex_view_section"));
1815: PetscCall(DMGetPeriodicity(dm, &maxCell, NULL, &L));
1816: PetscCall(DMGetCoordinatesLocalized(dm, &localized));
1817: if (L || localized) {
1818: PetscCall(PetscViewerASCIIPrintf(viewer, "Periodic mesh"));
1819: PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
1820: if (L) {
1821: PetscCall(PetscViewerASCIIPrintf(viewer, " ("));
1822: for (d = 0; d < dim; ++d) {
1823: if (d > 0) PetscCall(PetscViewerASCIIPrintf(viewer, ", "));
1824: PetscCall(PetscViewerASCIIPrintf(viewer, "%s", L[d] > 0.0 ? "PERIODIC" : "NONE"));
1825: }
1826: PetscCall(PetscViewerASCIIPrintf(viewer, ")"));
1827: }
1828: PetscCall(PetscViewerASCIIPrintf(viewer, " coordinates %s\n", localized ? "localized" : "not localized"));
1829: PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
1830: }
1831: }
1832: PetscCall(DMGetNumLabels(dm, &numLabels));
1833: if (numLabels) PetscCall(PetscViewerASCIIPrintf(viewer, "Labels:\n"));
1834: for (l = 0; l < numLabels; ++l) {
1835: DMLabel label;
1836: const char *name;
1837: PetscInt *values;
1838: PetscInt numValues;
1840: PetscCall(DMGetLabelName(dm, l, &name));
1841: PetscCall(DMGetLabel(dm, name, &label));
1842: PetscCall(DMLabelGetNumValues(label, &numValues));
1843: PetscCall(PetscViewerASCIIPrintf(viewer, " %s: %" PetscInt_FMT " strata with value/size (", name, numValues));
1845: { // Extract array of DMLabel values so it can be sorted
1846: IS is_values;
1847: const PetscInt *is_values_local = NULL;
1849: PetscCall(DMLabelGetValueIS(label, &is_values));
1850: PetscCall(ISGetIndices(is_values, &is_values_local));
1851: PetscCall(PetscMalloc1(numValues, &values));
1852: PetscCall(PetscArraycpy(values, is_values_local, numValues));
1853: PetscCall(PetscSortInt(numValues, values));
1854: PetscCall(ISRestoreIndices(is_values, &is_values_local));
1855: PetscCall(ISDestroy(&is_values));
1856: }
1857: PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
1858: for (PetscInt v = 0; v < numValues; ++v) {
1859: PetscInt size;
1861: PetscCall(DMLabelGetStratumSize(label, values[v], &size));
1862: if (v > 0) PetscCall(PetscViewerASCIIPrintf(viewer, ", "));
1863: PetscCall(PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " (%" PetscInt_FMT ")", values[v], size));
1864: }
1865: PetscCall(PetscViewerASCIIPrintf(viewer, ")\n"));
1866: PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
1867: PetscCall(PetscFree(values));
1868: }
1869: {
1870: char **labelNames;
1871: PetscInt Nl = numLabels;
1872: PetscBool flg;
1874: PetscCall(PetscMalloc1(Nl, &labelNames));
1875: PetscCall(PetscOptionsGetStringArray(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_plex_view_labels", labelNames, &Nl, &flg));
1876: for (l = 0; l < Nl; ++l) {
1877: DMLabel label;
1879: PetscCall(DMHasLabel(dm, labelNames[l], &flg));
1880: if (flg) {
1881: PetscCall(DMGetLabel(dm, labelNames[l], &label));
1882: PetscCall(DMLabelView(label, viewer));
1883: }
1884: PetscCall(PetscFree(labelNames[l]));
1885: }
1886: PetscCall(PetscFree(labelNames));
1887: }
1888: /* If no fields are specified, people do not want to see adjacency */
1889: if (dm->Nf) {
1890: for (PetscInt f = 0; f < dm->Nf; ++f) {
1891: const char *name;
1893: PetscCall(PetscObjectGetName(dm->fields[f].disc, &name));
1894: if (numLabels) PetscCall(PetscViewerASCIIPrintf(viewer, "Field %s:\n", name));
1895: PetscCall(PetscViewerASCIIPushTab(viewer));
1896: if (dm->fields[f].label) PetscCall(DMLabelView(dm->fields[f].label, viewer));
1897: if (dm->fields[f].adjacency[0]) {
1898: if (dm->fields[f].adjacency[1]) PetscCall(PetscViewerASCIIPrintf(viewer, "adjacency FVM++\n"));
1899: else PetscCall(PetscViewerASCIIPrintf(viewer, "adjacency FVM\n"));
1900: } else {
1901: if (dm->fields[f].adjacency[1]) PetscCall(PetscViewerASCIIPrintf(viewer, "adjacency FEM\n"));
1902: else PetscCall(PetscViewerASCIIPrintf(viewer, "adjacency FUNKY\n"));
1903: }
1904: PetscCall(PetscViewerASCIIPopTab(viewer));
1905: }
1906: }
1907: DMPlexTransform tr;
1909: PetscCall(DMPlexGetTransform(dm, &tr));
1910: if (tr) {
1911: PetscCall(PetscViewerASCIIPushTab(viewer));
1912: PetscCall(PetscViewerASCIIPrintf(viewer, "Created using transform:\n"));
1913: PetscCall(DMPlexTransformView(tr, viewer));
1914: PetscCall(PetscViewerASCIIPopTab(viewer));
1915: }
1916: PetscCall(DMGetCoarseDM(dm, &cdm));
1917: if (cdm) {
1918: PetscCall(PetscViewerASCIIPushTab(viewer));
1919: PetscCall(PetscViewerASCIIPrintf(viewer, "Defined by transform from:\n"));
1920: PetscCall(DMPlexView_Ascii(cdm, viewer));
1921: PetscCall(PetscViewerASCIIPopTab(viewer));
1922: }
1923: }
1924: PetscFunctionReturn(PETSC_SUCCESS);
1925: }
1927: /*@
1928: DMPlexDrawCell - Draw the given cell on the `PetscDraw` object.
1930: Not collective
1932: Input Parameters:
1933: + dm - The `DMPLEX` object
1934: . draw - The `PetscDraw` object
1935: . lC - The line color, or `PETSC_DETERMINE` to use the default
1936: . cC - The cell color, or `PETSC_DETERMINE` to use the default
1937: . cell - The cell to draw
1938: - coords - The vertex coordinates for the cell
1940: Level: developer
1942: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMView()`
1943: @*/
1944: PetscErrorCode DMPlexDrawCell(DM dm, PetscDraw draw, PetscInt lC, PetscInt cC, PetscInt cell, const PetscScalar coords[])
1945: {
1946: DMPolytopeType ct;
1947: PetscMPIInt rank;
1948: PetscInt cdim;
1949: int lineColor, cellColor;
1951: PetscFunctionBegin;
1954: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
1955: PetscCall(DMPlexGetCellType(dm, cell, &ct));
1956: PetscCall(DMGetCoordinateDim(dm, &cdim));
1957: lineColor = (int)(lC == PETSC_DETERMINE ? PETSC_DRAW_BLACK : lC);
1958: cellColor = (int)(cC == PETSC_DETERMINE ? PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS - 2) + 2 : cC);
1959: switch (ct) {
1960: case DM_POLYTOPE_SEGMENT:
1961: case DM_POLYTOPE_POINT_PRISM_TENSOR:
1962: switch (cdim) {
1963: case 1: {
1964: const PetscReal y = 0.5; /* TODO Put it in the middle of the viewport */
1965: const PetscReal dy = 0.05; /* TODO Make it a fraction of the total length */
1967: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]), y, PetscRealPart(coords[1]), y, lineColor));
1968: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]), y + dy, PetscRealPart(coords[0]), y - dy, lineColor));
1969: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[1]), y + dy, PetscRealPart(coords[1]), y - dy, lineColor));
1970: } break;
1971: case 2: {
1972: const PetscReal dx = (PetscRealPart(coords[3]) - PetscRealPart(coords[1]));
1973: const PetscReal dy = (PetscRealPart(coords[2]) - PetscRealPart(coords[0]));
1974: const PetscReal l = 0.1 / PetscSqrtReal(dx * dx + dy * dy);
1976: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), lineColor));
1977: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]) + l * dx, PetscRealPart(coords[1]) + l * dy, PetscRealPart(coords[0]) - l * dx, PetscRealPart(coords[1]) - l * dy, lineColor));
1978: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[2]) + l * dx, PetscRealPart(coords[3]) + l * dy, PetscRealPart(coords[2]) - l * dx, PetscRealPart(coords[3]) - l * dy, lineColor));
1979: } break;
1980: default:
1981: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells of dimension %" PetscInt_FMT, cdim);
1982: }
1983: break;
1984: case DM_POLYTOPE_TRIANGLE:
1985: if (cellColor >= 0) PetscCall(PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), cellColor, cellColor, cellColor));
1986: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), lineColor));
1987: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), lineColor));
1988: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[0]), PetscRealPart(coords[1]), lineColor));
1989: break;
1990: case DM_POLYTOPE_QUADRILATERAL:
1991: if (cellColor >= 0) {
1992: PetscCall(PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), cellColor, cellColor, cellColor));
1993: PetscCall(PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[6]), PetscRealPart(coords[7]), cellColor, cellColor, cellColor));
1994: }
1995: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), lineColor));
1996: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), lineColor));
1997: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[6]), PetscRealPart(coords[7]), lineColor));
1998: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[6]), PetscRealPart(coords[7]), PetscRealPart(coords[0]), PetscRealPart(coords[1]), lineColor));
1999: break;
2000: case DM_POLYTOPE_SEG_PRISM_TENSOR:
2001: if (cellColor >= 0) {
2002: PetscCall(PetscDrawTriangle(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), cellColor, cellColor, cellColor));
2003: PetscCall(PetscDrawTriangle(draw, PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[6]), PetscRealPart(coords[7]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), cellColor, cellColor, cellColor));
2004: }
2005: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[0]), PetscRealPart(coords[1]), PetscRealPart(coords[2]), PetscRealPart(coords[3]), lineColor));
2006: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[2]), PetscRealPart(coords[3]), PetscRealPart(coords[6]), PetscRealPart(coords[7]), lineColor));
2007: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[6]), PetscRealPart(coords[7]), PetscRealPart(coords[4]), PetscRealPart(coords[5]), lineColor));
2008: PetscCall(PetscDrawLine(draw, PetscRealPart(coords[4]), PetscRealPart(coords[5]), PetscRealPart(coords[0]), PetscRealPart(coords[1]), lineColor));
2009: break;
2010: case DM_POLYTOPE_FV_GHOST:
2011: break;
2012: default:
2013: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells of type %s", DMPolytopeTypes[ct]);
2014: }
2015: PetscFunctionReturn(PETSC_SUCCESS);
2016: }
2018: static PetscErrorCode DrawPolygon_Private(DM dm, PetscDraw draw, PetscInt cell, PetscInt Nv, const PetscReal refVertices[], const PetscScalar coords[], PetscInt edgeDiv, PetscReal refCoords[], PetscReal edgeCoords[])
2019: {
2020: PetscReal centroid[2] = {0., 0.};
2021: PetscMPIInt rank;
2022: PetscMPIInt fillColor;
2024: PetscFunctionBegin;
2025: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
2026: fillColor = PETSC_DRAW_WHITE + rank % (PETSC_DRAW_BASIC_COLORS - 2) + 2;
2027: for (PetscInt v = 0; v < Nv; ++v) {
2028: centroid[0] += PetscRealPart(coords[v * 2 + 0]) / Nv;
2029: centroid[1] += PetscRealPart(coords[v * 2 + 1]) / Nv;
2030: }
2031: for (PetscInt e = 0; e < Nv; ++e) {
2032: refCoords[0] = refVertices[e * 2 + 0];
2033: refCoords[1] = refVertices[e * 2 + 1];
2034: for (PetscInt d = 1; d <= edgeDiv; ++d) {
2035: refCoords[d * 2 + 0] = refCoords[0] + (refVertices[(e + 1) % Nv * 2 + 0] - refCoords[0]) * d / edgeDiv;
2036: refCoords[d * 2 + 1] = refCoords[1] + (refVertices[(e + 1) % Nv * 2 + 1] - refCoords[1]) * d / edgeDiv;
2037: }
2038: PetscCall(DMPlexReferenceToCoordinates(dm, cell, edgeDiv + 1, refCoords, edgeCoords));
2039: for (PetscInt d = 0; d < edgeDiv; ++d) {
2040: PetscCall(PetscDrawTriangle(draw, centroid[0], centroid[1], edgeCoords[d * 2 + 0], edgeCoords[d * 2 + 1], edgeCoords[(d + 1) * 2 + 0], edgeCoords[(d + 1) * 2 + 1], fillColor, fillColor, fillColor));
2041: PetscCall(PetscDrawLine(draw, edgeCoords[d * 2 + 0], edgeCoords[d * 2 + 1], edgeCoords[(d + 1) * 2 + 0], edgeCoords[(d + 1) * 2 + 1], PETSC_DRAW_BLACK));
2042: }
2043: }
2044: PetscFunctionReturn(PETSC_SUCCESS);
2045: }
2047: static PetscErrorCode DMPlexDrawCellHighOrder(DM dm, PetscDraw draw, PetscInt cell, const PetscScalar coords[], PetscInt edgeDiv, PetscReal refCoords[], PetscReal edgeCoords[])
2048: {
2049: DMPolytopeType ct;
2051: PetscFunctionBegin;
2052: PetscCall(DMPlexGetCellType(dm, cell, &ct));
2053: switch (ct) {
2054: case DM_POLYTOPE_TRIANGLE: {
2055: PetscReal refVertices[6] = {-1., -1., 1., -1., -1., 1.};
2057: PetscCall(DrawPolygon_Private(dm, draw, cell, 3, refVertices, coords, edgeDiv, refCoords, edgeCoords));
2058: } break;
2059: case DM_POLYTOPE_QUADRILATERAL: {
2060: PetscReal refVertices[8] = {-1., -1., 1., -1., 1., 1., -1., 1.};
2062: PetscCall(DrawPolygon_Private(dm, draw, cell, 4, refVertices, coords, edgeDiv, refCoords, edgeCoords));
2063: } break;
2064: default:
2065: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot draw cells of type %s", DMPolytopeTypes[ct]);
2066: }
2067: PetscFunctionReturn(PETSC_SUCCESS);
2068: }
2070: static PetscErrorCode DMPlexView_Draw(DM dm, PetscViewer viewer)
2071: {
2072: PetscDraw draw;
2073: DM cdm;
2074: PetscSection coordSection;
2075: Vec coordinates;
2076: PetscReal xyl[3], xyr[3];
2077: PetscReal *refCoords, *edgeCoords;
2078: PetscBool isnull, drawAffine;
2079: PetscInt dim, vStart, vEnd, cStart, cEnd, c, cDegree, edgeDiv, lineColor = PETSC_DETERMINE, cellColor = PETSC_DETERMINE;
2081: PetscFunctionBegin;
2082: PetscCall(DMGetCoordinateDim(dm, &dim));
2083: PetscCheck(dim <= 2, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Cannot draw meshes of dimension %" PetscInt_FMT, dim);
2084: PetscCall(DMGetCoordinateDegree_Internal(dm, &cDegree));
2085: drawAffine = cDegree > 1 ? PETSC_FALSE : PETSC_TRUE;
2086: edgeDiv = cDegree + 1;
2087: PetscCall(PetscOptionsGetInt(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_view_draw_line_color", &lineColor, NULL));
2088: PetscCall(PetscOptionsGetInt(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_view_draw_cell_color", &cellColor, NULL));
2089: PetscCall(PetscOptionsGetBool(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_view_draw_affine", &drawAffine, NULL));
2090: if (!drawAffine) PetscCall(PetscMalloc2((edgeDiv + 1) * dim, &refCoords, (edgeDiv + 1) * dim, &edgeCoords));
2091: PetscCall(DMGetCoordinateDM(dm, &cdm));
2092: PetscCall(DMGetLocalSection(cdm, &coordSection));
2093: PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
2094: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
2095: PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
2097: PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
2098: PetscCall(PetscDrawIsNull(draw, &isnull));
2099: if (isnull) PetscFunctionReturn(PETSC_SUCCESS);
2100: PetscCall(PetscDrawSetTitle(draw, "Mesh"));
2102: PetscCall(DMGetBoundingBox(dm, xyl, xyr));
2103: PetscCall(PetscDrawSetCoordinates(draw, xyl[0], xyl[1], xyr[0], xyr[1]));
2104: PetscCall(PetscDrawClear(draw));
2106: for (c = cStart; c < cEnd; ++c) {
2107: PetscScalar *coords = NULL;
2108: const PetscScalar *coords_arr;
2109: PetscInt numCoords;
2110: PetscBool isDG;
2112: PetscCall(DMPlexGetCellCoordinates(dm, c, &isDG, &numCoords, &coords_arr, &coords));
2113: if (drawAffine) PetscCall(DMPlexDrawCell(dm, draw, lineColor, cellColor, c, coords));
2114: else PetscCall(DMPlexDrawCellHighOrder(dm, draw, c, coords, edgeDiv, refCoords, edgeCoords));
2115: PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDG, &numCoords, &coords_arr, &coords));
2116: }
2117: if (!drawAffine) PetscCall(PetscFree2(refCoords, edgeCoords));
2118: PetscCall(PetscDrawFlush(draw));
2119: PetscCall(PetscDrawPause(draw));
2120: PetscCall(PetscDrawSave(draw));
2121: PetscFunctionReturn(PETSC_SUCCESS);
2122: }
2124: static PetscErrorCode DMPlexCreateHighOrderSurrogate_Internal(DM dm, DM *hdm)
2125: {
2126: DM odm = dm, rdm = dm, cdm;
2127: PetscFE fe;
2128: PetscSpace sp;
2129: PetscClassId id;
2130: PetscInt degree;
2131: PetscBool hoView = PETSC_TRUE;
2133: PetscFunctionBegin;
2134: PetscObjectOptionsBegin((PetscObject)dm);
2135: PetscCall(PetscOptionsBool("-dm_plex_high_order_view", "Subsample to view meshes with high order coordinates", "DMPlexCreateHighOrderSurrogate_Internal", hoView, &hoView, NULL));
2136: PetscOptionsEnd();
2137: PetscCall(PetscObjectReference((PetscObject)dm));
2138: *hdm = dm;
2139: if (!hoView) PetscFunctionReturn(PETSC_SUCCESS);
2140: PetscCall(DMGetCoordinateDM(dm, &cdm));
2141: PetscCall(DMGetField(cdm, 0, NULL, (PetscObject *)&fe));
2142: PetscCall(PetscObjectGetClassId((PetscObject)fe, &id));
2143: if (id != PETSCFE_CLASSID) PetscFunctionReturn(PETSC_SUCCESS);
2144: PetscCall(PetscFEGetBasisSpace(fe, &sp));
2145: PetscCall(PetscSpaceGetDegree(sp, °ree, NULL));
2146: for (PetscInt r = 0, rd = PetscCeilReal(((PetscReal)degree) / 2.); r < (PetscInt)PetscCeilReal(PetscLog2Real(degree)); ++r, rd = PetscCeilReal(((PetscReal)rd) / 2.)) {
2147: DM cdm, rcdm;
2148: Mat In;
2149: Vec cl, rcl;
2151: PetscCall(DMRefine(odm, PetscObjectComm((PetscObject)odm), &rdm));
2152: PetscCall(DMPlexCreateCoordinateSpace(rdm, rd, PETSC_FALSE, PETSC_FALSE));
2153: PetscCall(PetscObjectSetName((PetscObject)rdm, "Refined Mesh with Linear Coordinates"));
2154: PetscCall(DMGetCoordinateDM(odm, &cdm));
2155: PetscCall(DMGetCoordinateDM(rdm, &rcdm));
2156: PetscCall(DMGetCoordinatesLocal(odm, &cl));
2157: PetscCall(DMGetCoordinatesLocal(rdm, &rcl));
2158: PetscCall(DMSetCoarseDM(rcdm, cdm));
2159: PetscCall(DMCreateInterpolation(cdm, rcdm, &In, NULL));
2160: PetscCall(MatMult(In, cl, rcl));
2161: PetscCall(MatDestroy(&In));
2162: PetscCall(DMSetCoordinatesLocal(rdm, rcl));
2163: PetscCall(DMDestroy(&odm));
2164: odm = rdm;
2165: }
2166: *hdm = rdm;
2167: PetscFunctionReturn(PETSC_SUCCESS);
2168: }
2170: #if defined(PETSC_HAVE_EXODUSII)
2171: #include <exodusII.h>
2172: #endif
2174: PetscErrorCode DMView_Plex(DM dm, PetscViewer viewer)
2175: {
2176: PetscBool isascii, ishdf5, isvtk, isdraw, flg, isglvis, isexodus, iscgns, ispython;
2177: char name[PETSC_MAX_PATH_LEN];
2179: PetscFunctionBegin;
2182: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
2183: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk));
2184: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2185: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
2186: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERGLVIS, &isglvis));
2187: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWEREXODUSII, &isexodus));
2188: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERCGNS, &iscgns));
2189: PetscCall(PetscObjectHasFunction((PetscObject)viewer, "PetscViewerPythonViewObject_C", &ispython));
2190: if (isascii) {
2191: PetscViewerFormat format;
2192: PetscCall(PetscViewerGetFormat(viewer, &format));
2193: if (format == PETSC_VIEWER_ASCII_GLVIS) PetscCall(DMPlexView_GLVis(dm, viewer));
2194: else PetscCall(DMPlexView_Ascii(dm, viewer));
2195: } else if (ishdf5) {
2196: #if defined(PETSC_HAVE_HDF5)
2197: PetscCall(DMPlexView_HDF5_Internal(dm, viewer));
2198: #else
2199: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2200: #endif
2201: } else if (isvtk) {
2202: PetscCall(DMPlexVTKWriteAll((PetscObject)dm, viewer));
2203: } else if (isdraw) {
2204: DM hdm;
2206: PetscCall(DMPlexCreateHighOrderSurrogate_Internal(dm, &hdm));
2207: PetscCall(DMPlexView_Draw(hdm, viewer));
2208: PetscCall(DMDestroy(&hdm));
2209: } else if (isglvis) {
2210: PetscCall(DMPlexView_GLVis(dm, viewer));
2211: #if defined(PETSC_HAVE_EXODUSII)
2212: } else if (isexodus) {
2213: /*
2214: ExodusII requires that all sets be part of exactly one cell set.
2215: If the dm does not have a "Cell Sets" label defined, we create one
2216: with ID 1, containing all cells.
2217: Note that if the Cell Sets label is defined but does not cover all cells,
2218: we may still have a problem. This should probably be checked here or in the viewer;
2219: */
2220: PetscInt numCS;
2221: PetscCall(DMGetLabelSize(dm, "Cell Sets", &numCS));
2222: if (!numCS) {
2223: PetscInt cStart, cEnd, c;
2224: PetscCall(DMCreateLabel(dm, "Cell Sets"));
2225: PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
2226: for (c = cStart; c < cEnd; ++c) PetscCall(DMSetLabelValue(dm, "Cell Sets", c, 1));
2227: }
2228: PetscCall(DMView_PlexExodusII(dm, viewer));
2229: #endif
2230: #if defined(PETSC_HAVE_CGNS)
2231: } else if (iscgns) {
2232: PetscCall(DMView_PlexCGNS(dm, viewer));
2233: #endif
2234: } else if (ispython) {
2235: PetscCall(PetscViewerPythonViewObject(viewer, (PetscObject)dm));
2236: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Viewer type %s not yet supported for DMPlex writing", ((PetscObject)viewer)->type_name);
2237: /* Optionally view the partition */
2238: PetscCall(PetscOptionsHasName(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_partition_view", &flg));
2239: if (flg) {
2240: Vec ranks;
2241: PetscCall(DMPlexCreateRankField(dm, &ranks));
2242: PetscCall(VecView(ranks, viewer));
2243: PetscCall(VecDestroy(&ranks));
2244: }
2245: /* Optionally view a label */
2246: PetscCall(PetscOptionsGetString(((PetscObject)dm)->options, ((PetscObject)dm)->prefix, "-dm_label_view", name, sizeof(name), &flg));
2247: if (flg) {
2248: DMLabel label;
2249: Vec val;
2251: PetscCall(DMGetLabel(dm, name, &label));
2252: PetscCheck(label, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Label %s provided to -dm_label_view does not exist in this DM", name);
2253: PetscCall(DMPlexCreateLabelField(dm, label, &val));
2254: PetscCall(VecView(val, viewer));
2255: PetscCall(VecDestroy(&val));
2256: }
2257: PetscFunctionReturn(PETSC_SUCCESS);
2258: }
2260: /*@
2261: DMPlexTopologyView - Saves a `DMPLEX` topology into a file
2263: Collective
2265: Input Parameters:
2266: + dm - The `DM` whose topology is to be saved
2267: - viewer - The `PetscViewer` to save it in
2269: Level: advanced
2271: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMView()`, `DMPlexCoordinatesView()`, `DMPlexLabelsView()`, `DMPlexTopologyLoad()`, `PetscViewer`
2272: @*/
2273: PetscErrorCode DMPlexTopologyView(DM dm, PetscViewer viewer)
2274: {
2275: PetscBool ishdf5;
2277: PetscFunctionBegin;
2280: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2281: PetscCall(PetscLogEventBegin(DMPLEX_TopologyView, viewer, 0, 0, 0));
2282: if (ishdf5) {
2283: #if defined(PETSC_HAVE_HDF5)
2284: IS globalPointNumbering;
2285: PetscViewerFormat format;
2287: PetscCall(PetscViewerGetFormat(viewer, &format));
2288: PetscCheck(format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 output.", PetscViewerFormats[format]);
2289: PetscCall(DMPlexCreatePointNumbering(dm, &globalPointNumbering));
2290: PetscCall(DMPlexTopologyView_HDF5_Internal(dm, globalPointNumbering, viewer));
2291: PetscCall(ISDestroy(&globalPointNumbering));
2292: #else
2293: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2294: #endif
2295: }
2296: PetscCall(PetscLogEventEnd(DMPLEX_TopologyView, viewer, 0, 0, 0));
2297: PetscFunctionReturn(PETSC_SUCCESS);
2298: }
2300: /*@
2301: DMPlexCoordinatesView - Saves `DMPLEX` coordinates into a file
2303: Collective
2305: Input Parameters:
2306: + dm - The `DM` whose coordinates are to be saved
2307: - viewer - The `PetscViewer` for saving
2309: Level: advanced
2311: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMView()`, `DMPlexTopologyView()`, `DMPlexLabelsView()`, `DMPlexCoordinatesLoad()`, `PetscViewer`
2312: @*/
2313: PetscErrorCode DMPlexCoordinatesView(DM dm, PetscViewer viewer)
2314: {
2315: PetscBool ishdf5;
2317: PetscFunctionBegin;
2320: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2321: PetscCall(PetscLogEventBegin(DMPLEX_CoordinatesView, viewer, 0, 0, 0));
2322: if (ishdf5) {
2323: #if defined(PETSC_HAVE_HDF5)
2324: PetscViewerFormat format;
2326: PetscCall(PetscViewerGetFormat(viewer, &format));
2327: PetscCheck(format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 output.", PetscViewerFormats[format]);
2328: PetscCall(DMPlexCoordinatesView_HDF5_Internal(dm, viewer));
2329: #else
2330: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2331: #endif
2332: }
2333: PetscCall(PetscLogEventEnd(DMPLEX_CoordinatesView, viewer, 0, 0, 0));
2334: PetscFunctionReturn(PETSC_SUCCESS);
2335: }
2337: /*@
2338: DMPlexLabelsView - Saves `DMPLEX` labels into a file
2340: Collective
2342: Input Parameters:
2343: + dm - The `DM` whose labels are to be saved
2344: - viewer - The `PetscViewer` for saving
2346: Level: advanced
2348: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMView()`, `DMPlexTopologyView()`, `DMPlexCoordinatesView()`, `DMPlexLabelsLoad()`, `PetscViewer`
2349: @*/
2350: PetscErrorCode DMPlexLabelsView(DM dm, PetscViewer viewer)
2351: {
2352: PetscBool ishdf5;
2354: PetscFunctionBegin;
2357: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2358: PetscCall(PetscLogEventBegin(DMPLEX_LabelsView, viewer, 0, 0, 0));
2359: if (ishdf5) {
2360: #if defined(PETSC_HAVE_HDF5)
2361: IS globalPointNumbering;
2362: PetscViewerFormat format;
2364: PetscCall(PetscViewerGetFormat(viewer, &format));
2365: PetscCheck(format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
2366: PetscCall(DMPlexCreatePointNumbering(dm, &globalPointNumbering));
2367: PetscCall(DMPlexLabelsView_HDF5_Internal(dm, globalPointNumbering, viewer));
2368: PetscCall(ISDestroy(&globalPointNumbering));
2369: #else
2370: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2371: #endif
2372: }
2373: PetscCall(PetscLogEventEnd(DMPLEX_LabelsView, viewer, 0, 0, 0));
2374: PetscFunctionReturn(PETSC_SUCCESS);
2375: }
2377: /*@
2378: DMPlexSectionView - Saves a section associated with a `DMPLEX`
2380: Collective
2382: Input Parameters:
2383: + dm - The `DM` that contains the topology on which the section to be saved is defined
2384: . viewer - The `PetscViewer` for saving
2385: - sectiondm - The `DM` that contains the section to be saved, can be `NULL`
2387: Level: advanced
2389: Notes:
2390: This function is a wrapper around `PetscSectionView()`; in addition to the raw section, it saves information that associates the section points to the topology (`dm`) points. When the topology (`dm`) and the section are later loaded with `DMPlexTopologyLoad()` and `DMPlexSectionLoad()`, respectively, this information is used to match section points with topology points.
2392: In general `dm` and `sectiondm` are two different objects, the former carrying the topology and the latter carrying the section, and have been given a topology name and a section name, respectively, with `PetscObjectSetName()`. In practice, however, they can be the same object (or in case `sectiondm` is `NULL`) if it carries both topology and section; in that case the name of the object is used as both the topology name and the section name.
2394: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMView()`, `DMPlexTopologyView()`, `DMPlexCoordinatesView()`, `DMPlexLabelsView()`, `DMPlexGlobalVectorView()`, `DMPlexLocalVectorView()`, `PetscSectionView()`, `DMPlexSectionLoad()`, `PetscViewer`
2395: @*/
2396: PetscErrorCode DMPlexSectionView(DM dm, PetscViewer viewer, DM sectiondm)
2397: {
2398: PetscBool ishdf5;
2400: PetscFunctionBegin;
2403: if (!sectiondm) sectiondm = dm;
2405: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2406: PetscCall(PetscLogEventBegin(DMPLEX_SectionView, viewer, 0, 0, 0));
2407: if (ishdf5) {
2408: #if defined(PETSC_HAVE_HDF5)
2409: PetscCall(DMPlexSectionView_HDF5_Internal(dm, viewer, sectiondm));
2410: #else
2411: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2412: #endif
2413: }
2414: PetscCall(PetscLogEventEnd(DMPLEX_SectionView, viewer, 0, 0, 0));
2415: PetscFunctionReturn(PETSC_SUCCESS);
2416: }
2418: /*@
2419: DMPlexGlobalVectorView - Saves a global vector
2421: Collective
2423: Input Parameters:
2424: + dm - The `DM` that represents the topology
2425: . viewer - The `PetscViewer` to save data with
2426: . sectiondm - The `DM` that contains the global section on which vec is defined, can be `NULL`
2427: - vec - The global vector to be saved
2429: Level: advanced
2431: Notes:
2432: In general `dm` and `sectiondm` are two different objects, the former carrying the topology and the latter carrying the section, and have been given a topology name and a section name, respectively, with `PetscObjectSetName()`. In practice, however, they can be the same object (or in case `sectiondm` is `NULL`) if it carries both topology and section; in that case the name of the object is used as both the topology name and the section name.
2434: Calling sequence:
2435: .vb
2436: DMCreate(PETSC_COMM_WORLD, &dm);
2437: DMSetType(dm, DMPLEX);
2438: PetscObjectSetName((PetscObject)dm, "topologydm_name");
2439: DMClone(dm, §iondm);
2440: PetscObjectSetName((PetscObject)sectiondm, "sectiondm_name");
2441: PetscSectionCreate(PETSC_COMM_WORLD, §ion);
2442: DMPlexGetChart(sectiondm, &pStart, &pEnd);
2443: PetscSectionSetChart(section, pStart, pEnd);
2444: PetscSectionSetUp(section);
2445: DMSetLocalSection(sectiondm, section);
2446: PetscSectionDestroy(§ion);
2447: DMGetGlobalVector(sectiondm, &vec);
2448: PetscObjectSetName((PetscObject)vec, "vec_name");
2449: DMPlexTopologyView(dm, viewer);
2450: DMPlexSectionView(dm, viewer, sectiondm);
2451: DMPlexGlobalVectorView(dm, viewer, sectiondm, vec);
2452: DMRestoreGlobalVector(sectiondm, &vec);
2453: DMDestroy(§iondm);
2454: DMDestroy(&dm);
2455: .ve
2457: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexTopologyView()`, `DMPlexSectionView()`, `DMPlexLocalVectorView()`, `DMPlexGlobalVectorLoad()`, `DMPlexLocalVectorLoad()`
2458: @*/
2459: PetscErrorCode DMPlexGlobalVectorView(DM dm, PetscViewer viewer, DM sectiondm, Vec vec)
2460: {
2461: PetscBool ishdf5;
2463: PetscFunctionBegin;
2466: if (!sectiondm) sectiondm = dm;
2469: /* Check consistency */
2470: {
2471: PetscSection section;
2472: PetscBool includesConstraints;
2473: PetscInt m, m1;
2475: PetscCall(VecGetLocalSize(vec, &m1));
2476: PetscCall(DMGetGlobalSection(sectiondm, §ion));
2477: PetscCall(PetscSectionGetIncludesConstraints(section, &includesConstraints));
2478: if (includesConstraints) PetscCall(PetscSectionGetStorageSize(section, &m));
2479: else PetscCall(PetscSectionGetConstrainedStorageSize(section, &m));
2480: PetscCheck(m1 == m, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Global vector size (%" PetscInt_FMT ") != global section storage size (%" PetscInt_FMT ")", m1, m);
2481: }
2482: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2483: PetscCall(PetscLogEventBegin(DMPLEX_GlobalVectorView, viewer, 0, 0, 0));
2484: if (ishdf5) {
2485: #if defined(PETSC_HAVE_HDF5)
2486: PetscCall(DMPlexGlobalVectorView_HDF5_Internal(dm, viewer, sectiondm, vec));
2487: #else
2488: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2489: #endif
2490: }
2491: PetscCall(PetscLogEventEnd(DMPLEX_GlobalVectorView, viewer, 0, 0, 0));
2492: PetscFunctionReturn(PETSC_SUCCESS);
2493: }
2495: /*@
2496: DMPlexLocalVectorView - Saves a local vector
2498: Collective
2500: Input Parameters:
2501: + dm - The `DM` that represents the topology
2502: . viewer - The `PetscViewer` to save data with
2503: . sectiondm - The `DM` that contains the local section on which `vec` is defined, can be `NULL`
2504: - vec - The local vector to be saved
2506: Level: advanced
2508: Note:
2509: In general `dm` and `sectiondm` are two different objects, the former carrying the topology and the latter carrying the section, and have been given a topology name and a section name, respectively, with `PetscObjectSetName()`. In practice, however, they can be the same object (or in case `sectiondm` is `NULL`) if it carries both topology and section; in that case the name of the object is used as both the topology name and the section name.
2511: Calling sequence:
2512: .vb
2513: DMCreate(PETSC_COMM_WORLD, &dm);
2514: DMSetType(dm, DMPLEX);
2515: PetscObjectSetName((PetscObject)dm, "topologydm_name");
2516: DMClone(dm, §iondm);
2517: PetscObjectSetName((PetscObject)sectiondm, "sectiondm_name");
2518: PetscSectionCreate(PETSC_COMM_WORLD, §ion);
2519: DMPlexGetChart(sectiondm, &pStart, &pEnd);
2520: PetscSectionSetChart(section, pStart, pEnd);
2521: PetscSectionSetUp(section);
2522: DMSetLocalSection(sectiondm, section);
2523: DMGetLocalVector(sectiondm, &vec);
2524: PetscObjectSetName((PetscObject)vec, "vec_name");
2525: DMPlexTopologyView(dm, viewer);
2526: DMPlexSectionView(dm, viewer, sectiondm);
2527: DMPlexLocalVectorView(dm, viewer, sectiondm, vec);
2528: DMRestoreLocalVector(sectiondm, &vec);
2529: DMDestroy(§iondm);
2530: DMDestroy(&dm);
2531: .ve
2533: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexTopologyView()`, `DMPlexSectionView()`, `DMPlexGlobalVectorView()`, `DMPlexGlobalVectorLoad()`, `DMPlexLocalVectorLoad()`
2534: @*/
2535: PetscErrorCode DMPlexLocalVectorView(DM dm, PetscViewer viewer, DM sectiondm, Vec vec)
2536: {
2537: PetscBool ishdf5;
2539: PetscFunctionBegin;
2542: if (!sectiondm) sectiondm = dm;
2545: /* Check consistency */
2546: {
2547: PetscSection section;
2548: PetscBool includesConstraints;
2549: PetscInt m, m1;
2551: PetscCall(VecGetLocalSize(vec, &m1));
2552: PetscCall(DMGetLocalSection(sectiondm, §ion));
2553: PetscCall(PetscSectionGetIncludesConstraints(section, &includesConstraints));
2554: if (includesConstraints) PetscCall(PetscSectionGetStorageSize(section, &m));
2555: else PetscCall(PetscSectionGetConstrainedStorageSize(section, &m));
2556: PetscCheck(m1 == m, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Local vector size (%" PetscInt_FMT ") != local section storage size (%" PetscInt_FMT ")", m1, m);
2557: }
2558: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2559: PetscCall(PetscLogEventBegin(DMPLEX_LocalVectorView, viewer, 0, 0, 0));
2560: if (ishdf5) {
2561: #if defined(PETSC_HAVE_HDF5)
2562: PetscCall(DMPlexLocalVectorView_HDF5_Internal(dm, viewer, sectiondm, vec));
2563: #else
2564: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2565: #endif
2566: }
2567: PetscCall(PetscLogEventEnd(DMPLEX_LocalVectorView, viewer, 0, 0, 0));
2568: PetscFunctionReturn(PETSC_SUCCESS);
2569: }
2571: PetscErrorCode DMLoad_Plex(DM dm, PetscViewer viewer)
2572: {
2573: PetscBool ishdf5;
2575: PetscFunctionBegin;
2578: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2579: if (ishdf5) {
2580: #if defined(PETSC_HAVE_HDF5)
2581: PetscViewerFormat format;
2582: PetscCall(PetscViewerGetFormat(viewer, &format));
2583: if (format == PETSC_VIEWER_HDF5_XDMF || format == PETSC_VIEWER_HDF5_VIZ) {
2584: PetscCall(DMPlexLoad_HDF5_Xdmf_Internal(dm, viewer));
2585: } else if (format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE) {
2586: PetscCall(DMPlexLoad_HDF5_Internal(dm, viewer));
2587: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
2588: PetscFunctionReturn(PETSC_SUCCESS);
2589: #else
2590: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2591: #endif
2592: } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Viewer type %s not yet supported for DMPlex loading", ((PetscObject)viewer)->type_name);
2593: }
2595: /*@
2596: DMPlexTopologyLoad - Loads a topology into a `DMPLEX`
2598: Collective
2600: Input Parameters:
2601: + dm - The `DM` into which the topology is loaded
2602: - viewer - The `PetscViewer` for the saved topology
2604: Output Parameter:
2605: . globalToLocalPointSF - The `PetscSF` that pushes points in [0, N) to the associated points in the loaded `DMPLEX`, where N is the global number of points;
2606: `NULL` if unneeded
2608: Level: advanced
2610: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMLoad()`, `DMPlexCoordinatesLoad()`, `DMPlexLabelsLoad()`, `DMView()`, `PetscViewerHDF5Open()`, `PetscViewerPushFormat()`,
2611: `PetscViewer`, `PetscSF`
2612: @*/
2613: PetscErrorCode DMPlexTopologyLoad(DM dm, PetscViewer viewer, PetscSF *globalToLocalPointSF)
2614: {
2615: PetscBool ishdf5;
2617: PetscFunctionBegin;
2620: if (globalToLocalPointSF) PetscAssertPointer(globalToLocalPointSF, 3);
2621: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2622: PetscCall(PetscLogEventBegin(DMPLEX_TopologyLoad, viewer, 0, 0, 0));
2623: if (ishdf5) {
2624: #if defined(PETSC_HAVE_HDF5)
2625: PetscViewerFormat format;
2627: PetscCall(PetscViewerGetFormat(viewer, &format));
2628: PetscCheck(format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
2629: PetscCall(DMPlexTopologyLoad_HDF5_Internal(dm, viewer, globalToLocalPointSF));
2630: #else
2631: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2632: #endif
2633: }
2634: PetscCall(PetscLogEventEnd(DMPLEX_TopologyLoad, viewer, 0, 0, 0));
2635: PetscFunctionReturn(PETSC_SUCCESS);
2636: }
2638: /*@
2639: DMPlexCoordinatesLoad - Loads coordinates into a `DMPLEX`
2641: Collective
2643: Input Parameters:
2644: + dm - The `DM` into which the coordinates are loaded
2645: . viewer - The `PetscViewer` for the saved coordinates
2646: - globalToLocalPointSF - The `PetscSF` returned by `DMPlexTopologyLoad()` when loading dm from viewer
2648: Level: advanced
2650: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMLoad()`, `DMPlexTopologyLoad()`, `DMPlexLabelsLoad()`, `DMView()`, `PetscViewerHDF5Open()`, `PetscViewerPushFormat()`,
2651: `PetscSF`, `PetscViewer`
2652: @*/
2653: PetscErrorCode DMPlexCoordinatesLoad(DM dm, PetscViewer viewer, PetscSF globalToLocalPointSF)
2654: {
2655: PetscBool ishdf5;
2657: PetscFunctionBegin;
2661: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2662: PetscCall(PetscLogEventBegin(DMPLEX_CoordinatesLoad, viewer, 0, 0, 0));
2663: if (ishdf5) {
2664: #if defined(PETSC_HAVE_HDF5)
2665: PetscViewerFormat format;
2667: PetscCall(PetscViewerGetFormat(viewer, &format));
2668: PetscCheck(format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
2669: PetscCall(DMPlexCoordinatesLoad_HDF5_Internal(dm, viewer, globalToLocalPointSF));
2670: #else
2671: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2672: #endif
2673: }
2674: PetscCall(PetscLogEventEnd(DMPLEX_CoordinatesLoad, viewer, 0, 0, 0));
2675: PetscFunctionReturn(PETSC_SUCCESS);
2676: }
2678: /*@
2679: DMPlexLabelsLoad - Loads labels into a `DMPLEX`
2681: Collective
2683: Input Parameters:
2684: + dm - The `DM` into which the labels are loaded
2685: . viewer - The `PetscViewer` for the saved labels
2686: - globalToLocalPointSF - The `PetscSF` returned by `DMPlexTopologyLoad()` when loading `dm` from viewer
2688: Level: advanced
2690: Note:
2691: The `PetscSF` argument must not be `NULL` if the `DM` is distributed, otherwise an error occurs.
2693: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMLoad()`, `DMPlexTopologyLoad()`, `DMPlexCoordinatesLoad()`, `DMView()`, `PetscViewerHDF5Open()`, `PetscViewerPushFormat()`,
2694: `PetscSF`, `PetscViewer`
2695: @*/
2696: PetscErrorCode DMPlexLabelsLoad(DM dm, PetscViewer viewer, PetscSF globalToLocalPointSF)
2697: {
2698: PetscBool ishdf5;
2700: PetscFunctionBegin;
2704: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2705: PetscCall(PetscLogEventBegin(DMPLEX_LabelsLoad, viewer, 0, 0, 0));
2706: if (ishdf5) {
2707: #if defined(PETSC_HAVE_HDF5)
2708: PetscViewerFormat format;
2710: PetscCall(PetscViewerGetFormat(viewer, &format));
2711: PetscCheck(format == PETSC_VIEWER_HDF5_PETSC || format == PETSC_VIEWER_DEFAULT || format == PETSC_VIEWER_NATIVE, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "PetscViewerFormat %s not supported for HDF5 input.", PetscViewerFormats[format]);
2712: PetscCall(DMPlexLabelsLoad_HDF5_Internal(dm, viewer, globalToLocalPointSF));
2713: #else
2714: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2715: #endif
2716: }
2717: PetscCall(PetscLogEventEnd(DMPLEX_LabelsLoad, viewer, 0, 0, 0));
2718: PetscFunctionReturn(PETSC_SUCCESS);
2719: }
2721: /*@
2722: DMPlexSectionLoad - Loads section into a `DMPLEX`
2724: Collective
2726: Input Parameters:
2727: + dm - The `DM` that represents the topology
2728: . viewer - The `PetscViewer` that represents the on-disk section (sectionA)
2729: . sectiondm - The `DM` into which the on-disk section (sectionA) is migrated, can be `NULL`
2730: - globalToLocalPointSF - The `PetscSF` returned by `DMPlexTopologyLoad(`) when loading dm from viewer
2732: Output Parameters:
2733: + globalDofSF - The `PetscSF` that migrates any on-disk `Vec` data associated with sectionA into a global `Vec` associated with the `sectiondm`'s global section (`NULL` if not needed)
2734: - localDofSF - The `PetscSF` that migrates any on-disk `Vec` data associated with sectionA into a local `Vec` associated with the `sectiondm`'s local section (`NULL` if not needed)
2736: Level: advanced
2738: Notes:
2739: This function is a wrapper around `PetscSectionLoad()`; it loads, in addition to the raw section, a list of global point numbers that associates each on-disk section point with a global point number in [0, NX), where NX is the number of topology points in `dm`. Noting that globalToLocalPointSF associates each topology point in dm with a global number in [0, NX), one can readily establish an association of the on-disk section points with the topology points.
2741: In general `dm` and `sectiondm` are two different objects, the former carrying the topology and the latter carrying the section, and have been given a topology name and a section name, respectively, with `PetscObjectSetName()`. In practice, however, they can be the same object (or in case `sectiondm` is `NULL`) if it carries both topology and section; in that case the name of the object is used as both the topology name and the section name.
2743: The output parameter, `globalDofSF` (`localDofSF`), can later be used with `DMPlexGlobalVectorLoad()` (`DMPlexLocalVectorLoad()`) to load on-disk vectors into global (local) vectors associated with sectiondm's global (local) section.
2745: Example using 2 processes:
2746: .vb
2747: NX (number of points on dm): 4
2748: sectionA : the on-disk section
2749: vecA : a vector associated with sectionA
2750: sectionB : sectiondm's local section constructed in this function
2751: vecB (local) : a vector associated with sectiondm's local section
2752: vecB (global) : a vector associated with sectiondm's global section
2754: rank 0 rank 1
2755: vecA (global) : [.0 .4 .1 | .2 .3] <- to be loaded in DMPlexGlobalVectorLoad() or DMPlexLocalVectorLoad()
2756: sectionA->atlasOff : 0 2 | 1 <- loaded in PetscSectionLoad()
2757: sectionA->atlasDof : 1 3 | 1 <- loaded in PetscSectionLoad()
2758: sectionA's global point numbers: 0 2 | 3 <- loaded in DMPlexSectionLoad()
2759: [0, NX) : 0 1 | 2 3 <- conceptual partition used in globalToLocalPointSF
2760: sectionB's global point numbers: 0 1 3 | 3 2 <- associated with [0, NX) by globalToLocalPointSF
2761: sectionB->atlasDof : 1 0 1 | 1 3
2762: sectionB->atlasOff (no perm) : 0 1 1 | 0 1
2763: vecB (local) : [.0 .4] | [.4 .1 .2 .3] <- to be constructed by calling DMPlexLocalVectorLoad() with localDofSF
2764: vecB (global) : [.0 .4 | .1 .2 .3] <- to be constructed by calling DMPlexGlobalVectorLoad() with globalDofSF
2765: .ve
2766: where "|" represents a partition of loaded data, and global point 3 is assumed to be owned by rank 0.
2768: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMLoad()`, `DMPlexTopologyLoad()`, `DMPlexCoordinatesLoad()`, `DMPlexLabelsLoad()`, `DMPlexGlobalVectorLoad()`, `DMPlexLocalVectorLoad()`, `PetscSectionLoad()`, `DMPlexSectionView()`, `PetscSF`, `PetscViewer`
2769: @*/
2770: PetscErrorCode DMPlexSectionLoad(DM dm, PetscViewer viewer, PeOp DM sectiondm, PetscSF globalToLocalPointSF, PeOp PetscSF *globalDofSF, PeOp PetscSF *localDofSF)
2771: {
2772: PetscBool ishdf5;
2774: PetscFunctionBegin;
2777: if (!sectiondm) sectiondm = dm;
2780: if (globalDofSF) PetscAssertPointer(globalDofSF, 5);
2781: if (localDofSF) PetscAssertPointer(localDofSF, 6);
2782: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2783: PetscCall(PetscLogEventBegin(DMPLEX_SectionLoad, viewer, 0, 0, 0));
2784: if (ishdf5) {
2785: #if defined(PETSC_HAVE_HDF5)
2786: PetscCall(DMPlexSectionLoad_HDF5_Internal(dm, viewer, sectiondm, globalToLocalPointSF, globalDofSF, localDofSF));
2787: #else
2788: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2789: #endif
2790: }
2791: PetscCall(PetscLogEventEnd(DMPLEX_SectionLoad, viewer, 0, 0, 0));
2792: PetscFunctionReturn(PETSC_SUCCESS);
2793: }
2795: /*@
2796: DMPlexGlobalVectorLoad - Loads on-disk vector data into a global vector
2798: Collective
2800: Input Parameters:
2801: + dm - The `DM` that represents the topology
2802: . viewer - The `PetscViewer` that represents the on-disk vector data
2803: . sectiondm - The `DM` that contains the global section on which vec is defined, can be `NULL`
2804: . sf - The `PetscSF` that migrates the on-disk vector data into vec
2805: - vec - The global vector to set values of
2807: Level: advanced
2809: Notes:
2810: In general dm and sectiondm are two different objects, the former carrying the topology and the latter carrying the section, and have been given a topology name and a section name, respectively, with `PetscObjectSetName()`. In practice, however, they can be the same object (or in case `sectiondm` is `NULL`) if it carries both topology and section; in that case the name of the object is used as both the topology name and the section name.
2812: Calling sequence:
2813: .vb
2814: DMCreate(PETSC_COMM_WORLD, &dm);
2815: DMSetType(dm, DMPLEX);
2816: PetscObjectSetName((PetscObject)dm, "topologydm_name");
2817: DMPlexTopologyLoad(dm, viewer, &sfX);
2818: DMClone(dm, §iondm);
2819: PetscObjectSetName((PetscObject)sectiondm, "sectiondm_name");
2820: DMPlexSectionLoad(dm, viewer, sectiondm, sfX, &gsf, NULL);
2821: DMGetGlobalVector(sectiondm, &vec);
2822: PetscObjectSetName((PetscObject)vec, "vec_name");
2823: DMPlexGlobalVectorLoad(dm, viewer, sectiondm, gsf, vec);
2824: DMRestoreGlobalVector(sectiondm, &vec);
2825: PetscSFDestroy(&gsf);
2826: PetscSFDestroy(&sfX);
2827: DMDestroy(§iondm);
2828: DMDestroy(&dm);
2829: .ve
2831: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexTopologyLoad()`, `DMPlexSectionLoad()`, `DMPlexLocalVectorLoad()`, `DMPlexGlobalVectorView()`, `DMPlexLocalVectorView()`,
2832: `PetscSF`, `PetscViewer`
2833: @*/
2834: PetscErrorCode DMPlexGlobalVectorLoad(DM dm, PetscViewer viewer, DM sectiondm, PetscSF sf, Vec vec)
2835: {
2836: PetscBool ishdf5;
2838: PetscFunctionBegin;
2841: if (!sectiondm) sectiondm = dm;
2845: /* Check consistency */
2846: {
2847: PetscSection section;
2848: PetscBool includesConstraints;
2849: PetscInt m, m1;
2851: PetscCall(VecGetLocalSize(vec, &m1));
2852: PetscCall(DMGetGlobalSection(sectiondm, §ion));
2853: PetscCall(PetscSectionGetIncludesConstraints(section, &includesConstraints));
2854: if (includesConstraints) PetscCall(PetscSectionGetStorageSize(section, &m));
2855: else PetscCall(PetscSectionGetConstrainedStorageSize(section, &m));
2856: PetscCheck(m1 == m, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Global vector size (%" PetscInt_FMT ") != global section storage size (%" PetscInt_FMT ")", m1, m);
2857: }
2858: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2859: PetscCall(PetscLogEventBegin(DMPLEX_GlobalVectorLoad, viewer, 0, 0, 0));
2860: if (ishdf5) {
2861: #if defined(PETSC_HAVE_HDF5)
2862: PetscCall(DMPlexVecLoad_HDF5_Internal(dm, viewer, sectiondm, sf, vec));
2863: #else
2864: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2865: #endif
2866: }
2867: PetscCall(PetscLogEventEnd(DMPLEX_GlobalVectorLoad, viewer, 0, 0, 0));
2868: PetscFunctionReturn(PETSC_SUCCESS);
2869: }
2871: /*@
2872: DMPlexLocalVectorLoad - Loads on-disk vector data into a local vector
2874: Collective
2876: Input Parameters:
2877: + dm - The `DM` that represents the topology
2878: . viewer - The `PetscViewer` that represents the on-disk vector data
2879: . sectiondm - The `DM` that contains the local section on which vec is defined, can be `NULL`
2880: . sf - The `PetscSF` that migrates the on-disk vector data into vec
2881: - vec - The local vector to set values of
2883: Level: advanced
2885: Notes:
2886: In general `dm` and `sectiondm` are two different objects, the former carrying the topology and the latter carrying the section, and have been given a topology name and a section name, respectively, with `PetscObjectSetName()`. In practice, however, they can be the same object (or in case `sectiondm` is `NULL`) if it carries both topology and section; in that case the name of the object is used as both the topology name and the section name.
2888: Calling sequence:
2889: .vb
2890: DMCreate(PETSC_COMM_WORLD, &dm);
2891: DMSetType(dm, DMPLEX);
2892: PetscObjectSetName((PetscObject)dm, "topologydm_name");
2893: DMPlexTopologyLoad(dm, viewer, &sfX);
2894: DMClone(dm, §iondm);
2895: PetscObjectSetName((PetscObject)sectiondm, "sectiondm_name");
2896: DMPlexSectionLoad(dm, viewer, sectiondm, sfX, NULL, &lsf);
2897: DMGetLocalVector(sectiondm, &vec);
2898: PetscObjectSetName((PetscObject)vec, "vec_name");
2899: DMPlexLocalVectorLoad(dm, viewer, sectiondm, lsf, vec);
2900: DMRestoreLocalVector(sectiondm, &vec);
2901: PetscSFDestroy(&lsf);
2902: PetscSFDestroy(&sfX);
2903: DMDestroy(§iondm);
2904: DMDestroy(&dm);
2905: .ve
2907: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexTopologyLoad()`, `DMPlexSectionLoad()`, `DMPlexGlobalVectorLoad()`, `DMPlexGlobalVectorView()`, `DMPlexLocalVectorView()`,
2908: `PetscSF`, `PetscViewer`
2909: @*/
2910: PetscErrorCode DMPlexLocalVectorLoad(DM dm, PetscViewer viewer, DM sectiondm, PetscSF sf, Vec vec)
2911: {
2912: PetscBool ishdf5;
2914: PetscFunctionBegin;
2917: if (!sectiondm) sectiondm = dm;
2921: /* Check consistency */
2922: {
2923: PetscSection section;
2924: PetscBool includesConstraints;
2925: PetscInt m, m1;
2927: PetscCall(VecGetLocalSize(vec, &m1));
2928: PetscCall(DMGetLocalSection(sectiondm, §ion));
2929: PetscCall(PetscSectionGetIncludesConstraints(section, &includesConstraints));
2930: if (includesConstraints) PetscCall(PetscSectionGetStorageSize(section, &m));
2931: else PetscCall(PetscSectionGetConstrainedStorageSize(section, &m));
2932: PetscCheck(m1 == m, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Local vector size (%" PetscInt_FMT ") != local section storage size (%" PetscInt_FMT ")", m1, m);
2933: }
2934: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2935: PetscCall(PetscLogEventBegin(DMPLEX_LocalVectorLoad, viewer, 0, 0, 0));
2936: if (ishdf5) {
2937: #if defined(PETSC_HAVE_HDF5)
2938: PetscCall(DMPlexVecLoad_HDF5_Internal(dm, viewer, sectiondm, sf, vec));
2939: #else
2940: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2941: #endif
2942: }
2943: PetscCall(PetscLogEventEnd(DMPLEX_LocalVectorLoad, viewer, 0, 0, 0));
2944: PetscFunctionReturn(PETSC_SUCCESS);
2945: }
2947: PetscErrorCode DMDestroy_Plex(DM dm)
2948: {
2949: DM_Plex *mesh = (DM_Plex *)dm->data;
2951: PetscFunctionBegin;
2952: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMSetUpGLVisViewer_C", NULL));
2953: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexInsertBoundaryValues_C", NULL));
2954: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexInsertTimeDerivativeBoundaryValues_C", NULL));
2955: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexInsertBounds_C", NULL));
2956: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMCreateNeumannOverlap_C", NULL));
2957: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMInterpolateSolution_C", NULL));
2958: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexGetOverlap_C", NULL));
2959: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexDistributeGetDefault_C", NULL));
2960: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexDistributeSetDefault_C", NULL));
2961: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "MatComputeNeumannOverlap_C", NULL));
2962: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexReorderGetDefault_C", NULL));
2963: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexReorderSetDefault_C", NULL));
2964: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMReorderSectionGetDefault_C", NULL));
2965: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMReorderSectionSetDefault_C", NULL));
2966: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMReorderSectionGetType_C", NULL));
2967: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMReorderSectionSetType_C", NULL));
2968: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexGetOverlap_C", NULL));
2969: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexSetOverlap_C", NULL));
2970: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexGetUseCeed_C", NULL));
2971: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexSetUseCeed_C", NULL));
2972: PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMGetIsoperiodicPointSF_C", NULL));
2973: if (--mesh->refct > 0) PetscFunctionReturn(PETSC_SUCCESS);
2974: PetscCall(PetscSectionDestroy(&mesh->coneSection));
2975: PetscCall(PetscFree(mesh->cones));
2976: PetscCall(PetscFree(mesh->coneOrientations));
2977: PetscCall(PetscSectionDestroy(&mesh->supportSection));
2978: PetscCall(PetscSectionDestroy(&mesh->subdomainSection));
2979: PetscCall(PetscFree(mesh->supports));
2980: PetscCall(PetscFree(mesh->cellTypes));
2981: PetscCall(DMPlexTransformDestroy(&mesh->tr));
2982: PetscCall(PetscFree(mesh->tetgenOpts));
2983: PetscCall(PetscFree(mesh->triangleOpts));
2984: PetscCall(PetscFree(mesh->transformType));
2985: PetscCall(PetscFree(mesh->distributionName));
2986: PetscCall(PetscPartitionerDestroy(&mesh->partitioner));
2987: PetscCall(DMLabelDestroy(&mesh->subpointMap));
2988: PetscCall(ISDestroy(&mesh->subpointIS));
2989: PetscCall(ISDestroy(&mesh->globalVertexNumbers));
2990: PetscCall(ISDestroy(&mesh->globalCellNumbers));
2991: if (mesh->periodic.face_sfs) {
2992: for (PetscInt i = 0; i < mesh->periodic.num_face_sfs; i++) PetscCall(PetscSFDestroy(&mesh->periodic.face_sfs[i]));
2993: PetscCall(PetscFree(mesh->periodic.face_sfs));
2994: }
2995: PetscCall(PetscSFDestroy(&mesh->periodic.composed_sf));
2996: if (mesh->periodic.periodic_points) {
2997: for (PetscInt i = 0; i < mesh->periodic.num_face_sfs; i++) PetscCall(ISDestroy(&mesh->periodic.periodic_points[i]));
2998: PetscCall(PetscFree(mesh->periodic.periodic_points));
2999: }
3000: PetscCall(PetscFree(mesh->periodic.transform));
3001: PetscCall(PetscSectionDestroy(&mesh->anchorSection));
3002: PetscCall(ISDestroy(&mesh->anchorIS));
3003: PetscCall(PetscSectionDestroy(&mesh->parentSection));
3004: PetscCall(PetscFree(mesh->parents));
3005: PetscCall(PetscFree(mesh->childIDs));
3006: PetscCall(PetscSectionDestroy(&mesh->childSection));
3007: PetscCall(PetscFree(mesh->children));
3008: PetscCall(DMDestroy(&mesh->referenceTree));
3009: PetscCall(PetscGridHashDestroy(&mesh->lbox));
3010: PetscCall(PetscFree(mesh->neighbors));
3011: PetscCall(PetscFree(mesh->metricCtx));
3012: if (mesh->nonempty_comm != MPI_COMM_NULL && mesh->nonempty_comm != MPI_COMM_SELF) PetscCallMPI(MPI_Comm_free(&mesh->nonempty_comm));
3013: PetscCall(DMPlexTransformDestroy(&mesh->transform));
3014: /* This was originally freed in DMDestroy(), but that prevents reference counting of backend objects */
3015: PetscCall(PetscFree(mesh));
3016: PetscFunctionReturn(PETSC_SUCCESS);
3017: }
3019: PetscErrorCode DMCreateMatrix_Plex(DM dm, Mat *J)
3020: {
3021: PetscSection sectionGlobal, sectionLocal;
3022: PetscInt bs = -1, mbs;
3023: PetscInt localSize, localStart = 0;
3024: PetscBool isShell, isBlock, isSeqBlock, isMPIBlock, isSymBlock, isSymSeqBlock, isSymMPIBlock, isMatIS;
3025: MatType mtype;
3026: ISLocalToGlobalMapping ltog;
3028: PetscFunctionBegin;
3029: PetscCall(MatInitializePackage());
3030: mtype = dm->mattype;
3031: PetscCall(DMGetLocalSection(dm, §ionLocal));
3032: PetscCall(DMGetGlobalSection(dm, §ionGlobal));
3033: /* PetscCall(PetscSectionGetStorageSize(sectionGlobal, &localSize)); */
3034: PetscCall(PetscSectionGetConstrainedStorageSize(sectionGlobal, &localSize));
3035: PetscCallMPI(MPI_Exscan(&localSize, &localStart, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)dm)));
3036: PetscCall(MatCreate(PetscObjectComm((PetscObject)dm), J));
3037: PetscCall(MatSetSizes(*J, localSize, localSize, PETSC_DETERMINE, PETSC_DETERMINE));
3038: PetscCall(MatSetType(*J, mtype));
3039: PetscCall(MatSetFromOptions(*J));
3040: PetscCall(MatGetBlockSize(*J, &mbs));
3041: if (mbs > 1) bs = mbs;
3042: PetscCall(PetscStrcmp(mtype, MATSHELL, &isShell));
3043: PetscCall(PetscStrcmp(mtype, MATBAIJ, &isBlock));
3044: PetscCall(PetscStrcmp(mtype, MATSEQBAIJ, &isSeqBlock));
3045: PetscCall(PetscStrcmp(mtype, MATMPIBAIJ, &isMPIBlock));
3046: PetscCall(PetscStrcmp(mtype, MATSBAIJ, &isSymBlock));
3047: PetscCall(PetscStrcmp(mtype, MATSEQSBAIJ, &isSymSeqBlock));
3048: PetscCall(PetscStrcmp(mtype, MATMPISBAIJ, &isSymMPIBlock));
3049: PetscCall(PetscStrcmp(mtype, MATIS, &isMatIS));
3050: if (!isShell) {
3051: // There are three states with pblocks, since block starts can have no dofs:
3052: // UNKNOWN) New Block: An open block has been signalled by pblocks[p] == 1
3053: // TRUE) Block Start: The first entry in a block has been added
3054: // FALSE) Block Add: An additional block entry has been added, since pblocks[p] == 0
3055: PetscBT blst;
3056: PetscBool3 bstate = PETSC_BOOL3_UNKNOWN;
3057: PetscBool fillMatrix = (PetscBool)(!dm->prealloc_only && !isMatIS);
3058: const PetscInt *perm = NULL;
3059: PetscInt *dnz, *onz, *dnzu, *onzu, bsLocal[2], bsMinMax[2], *pblocks;
3060: PetscInt pStart, pEnd, dof, cdof, num_fields;
3062: PetscCall(DMGetLocalToGlobalMapping(dm, <og));
3063: PetscCall(PetscSectionGetBlockStarts(sectionLocal, &blst));
3064: if (sectionLocal->perm) PetscCall(ISGetIndices(sectionLocal->perm, &perm));
3066: PetscCall(PetscCalloc1(localSize, &pblocks));
3067: PetscCall(PetscSectionGetChart(sectionGlobal, &pStart, &pEnd));
3068: PetscCall(PetscSectionGetNumFields(sectionGlobal, &num_fields));
3069: // We need to process in the permuted order to get block sizes right
3070: for (PetscInt point = pStart; point < pEnd; ++point) {
3071: const PetscInt p = perm ? perm[point] : point;
3073: switch (dm->blocking_type) {
3074: case DM_BLOCKING_TOPOLOGICAL_POINT: { // One block per topological point
3075: PetscInt bdof, offset;
3077: PetscCall(PetscSectionGetDof(sectionGlobal, p, &dof));
3078: PetscCall(PetscSectionGetOffset(sectionGlobal, p, &offset));
3079: PetscCall(PetscSectionGetConstraintDof(sectionGlobal, p, &cdof));
3080: if (blst && PetscBTLookup(blst, p)) bstate = PETSC_BOOL3_UNKNOWN;
3081: if (dof > 0) {
3082: // State change
3083: if (bstate == PETSC_BOOL3_UNKNOWN) bstate = PETSC_BOOL3_TRUE;
3084: else if (bstate == PETSC_BOOL3_TRUE && blst && !PetscBTLookup(blst, p)) bstate = PETSC_BOOL3_FALSE;
3086: for (PetscInt i = 0; i < dof - cdof; ++i) pblocks[offset - localStart + i] = dof - cdof;
3087: // Signal block concatenation
3088: if (bstate == PETSC_BOOL3_FALSE && dof - cdof) pblocks[offset - localStart] = -(dof - cdof);
3089: }
3090: dof = dof < 0 ? -(dof + 1) : dof;
3091: bdof = cdof && (dof - cdof) ? 1 : dof;
3092: if (dof) {
3093: if (bs < 0) {
3094: bs = bdof;
3095: } else if (bs != bdof) {
3096: bs = 1;
3097: }
3098: }
3099: } break;
3100: case DM_BLOCKING_FIELD_NODE: {
3101: for (PetscInt field = 0; field < num_fields; field++) {
3102: PetscInt num_comp, bdof, offset;
3103: PetscCall(PetscSectionGetFieldComponents(sectionGlobal, field, &num_comp));
3104: PetscCall(PetscSectionGetFieldDof(sectionGlobal, p, field, &dof));
3105: if (dof < 0) continue;
3106: PetscCall(PetscSectionGetFieldOffset(sectionGlobal, p, field, &offset));
3107: PetscCall(PetscSectionGetFieldConstraintDof(sectionGlobal, p, field, &cdof));
3108: PetscAssert(dof % num_comp == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Point %" PetscInt_FMT " field %" PetscInt_FMT " has %" PetscInt_FMT " dof, not divisible by %" PetscInt_FMT " component ", p, field, dof, num_comp);
3109: PetscInt num_nodes = dof / num_comp;
3110: for (PetscInt i = 0; i < dof - cdof; i++) pblocks[offset - localStart + i] = (dof - cdof) / num_nodes;
3111: // Handle possibly constant block size (unlikely)
3112: bdof = cdof && (dof - cdof) ? 1 : dof;
3113: if (dof) {
3114: if (bs < 0) {
3115: bs = bdof;
3116: } else if (bs != bdof) {
3117: bs = 1;
3118: }
3119: }
3120: }
3121: } break;
3122: }
3123: }
3124: if (sectionLocal->perm) PetscCall(ISRestoreIndices(sectionLocal->perm, &perm));
3125: /* Must have same blocksize on all procs (some might have no points) */
3126: bsLocal[0] = bs < 0 ? PETSC_INT_MAX : bs;
3127: bsLocal[1] = bs;
3128: PetscCall(PetscGlobalMinMaxInt(PetscObjectComm((PetscObject)dm), bsLocal, bsMinMax));
3129: if (bsMinMax[0] != bsMinMax[1]) bs = 1;
3130: else bs = bsMinMax[0];
3131: bs = PetscMax(1, bs);
3132: PetscCall(MatSetLocalToGlobalMapping(*J, ltog, ltog));
3133: if (dm->prealloc_skip) { // User will likely use MatSetPreallocationCOO(), but still set structural parameters
3134: PetscCall(MatSetBlockSize(*J, bs));
3135: PetscCall(MatSetUp(*J));
3136: } else {
3137: PetscCall(PetscCalloc4(localSize / bs, &dnz, localSize / bs, &onz, localSize / bs, &dnzu, localSize / bs, &onzu));
3138: PetscCall(DMPlexPreallocateOperator(dm, bs, dnz, onz, dnzu, onzu, *J, fillMatrix));
3139: PetscCall(PetscFree4(dnz, onz, dnzu, onzu));
3140: }
3141: if (pblocks) { // Consolidate blocks
3142: PetscInt nblocks = 0;
3143: pblocks[0] = PetscAbs(pblocks[0]);
3144: for (PetscInt i = 0; i < localSize; i += PetscMax(1, pblocks[i])) {
3145: if (pblocks[i] == 0) continue;
3146: // Negative block size indicates the blocks should be concatenated
3147: if (pblocks[i] < 0) {
3148: pblocks[i] = -pblocks[i];
3149: pblocks[nblocks - 1] += pblocks[i];
3150: } else {
3151: pblocks[nblocks++] = pblocks[i]; // nblocks always <= i
3152: }
3153: for (PetscInt j = 1; j < pblocks[i]; j++)
3154: PetscCheck(pblocks[i + j] == pblocks[i], PETSC_COMM_SELF, PETSC_ERR_PLIB, "Block of size %" PetscInt_FMT " at %" PetscInt_FMT " mismatches entry %" PetscInt_FMT " at %" PetscInt_FMT, pblocks[i], i, pblocks[i + j], i + j);
3155: }
3156: PetscCall(MatSetVariableBlockSizes(*J, nblocks, pblocks));
3157: }
3158: PetscCall(PetscFree(pblocks));
3159: }
3160: PetscCall(MatSetDM(*J, dm));
3161: PetscFunctionReturn(PETSC_SUCCESS);
3162: }
3164: /*@
3165: DMPlexGetSubdomainSection - Returns the section associated with the subdomain
3167: Not Collective
3169: Input Parameter:
3170: . dm - The `DMPLEX`
3172: Output Parameter:
3173: . subsection - The subdomain section
3175: Level: developer
3177: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `PetscSection`
3178: @*/
3179: PetscErrorCode DMPlexGetSubdomainSection(DM dm, PetscSection *subsection)
3180: {
3181: DM_Plex *mesh = (DM_Plex *)dm->data;
3183: PetscFunctionBegin;
3185: if (!mesh->subdomainSection) {
3186: PetscSection section;
3187: PetscSF sf;
3189: PetscCall(PetscSFCreate(PETSC_COMM_SELF, &sf));
3190: PetscCall(DMGetLocalSection(dm, §ion));
3191: PetscCall(PetscSectionCreateGlobalSection(section, sf, PETSC_TRUE, PETSC_FALSE, PETSC_TRUE, &mesh->subdomainSection));
3192: PetscCall(PetscSFDestroy(&sf));
3193: }
3194: *subsection = mesh->subdomainSection;
3195: PetscFunctionReturn(PETSC_SUCCESS);
3196: }
3198: /*@
3199: DMPlexGetChart - Return the interval for all mesh points [`pStart`, `pEnd`)
3201: Not Collective
3203: Input Parameter:
3204: . dm - The `DMPLEX`
3206: Output Parameters:
3207: + pStart - The first mesh point
3208: - pEnd - The upper bound for mesh points
3210: Level: beginner
3212: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexSetChart()`
3213: @*/
3214: PetscErrorCode DMPlexGetChart(DM dm, PetscInt *pStart, PetscInt *pEnd)
3215: {
3216: DM_Plex *mesh = (DM_Plex *)dm->data;
3218: PetscFunctionBegin;
3220: if (mesh->tr) PetscCall(DMPlexTransformGetChart(mesh->tr, pStart, pEnd));
3221: else PetscCall(PetscSectionGetChart(mesh->coneSection, pStart, pEnd));
3222: PetscFunctionReturn(PETSC_SUCCESS);
3223: }
3225: /*@
3226: DMPlexSetChart - Set the interval for all mesh points [`pStart`, `pEnd`)
3228: Not Collective
3230: Input Parameters:
3231: + dm - The `DMPLEX`
3232: . pStart - The first mesh point
3233: - pEnd - The upper bound for mesh points
3235: Level: beginner
3237: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetChart()`
3238: @*/
3239: PetscErrorCode DMPlexSetChart(DM dm, PetscInt pStart, PetscInt pEnd)
3240: {
3241: DM_Plex *mesh = (DM_Plex *)dm->data;
3243: PetscFunctionBegin;
3245: PetscCall(PetscSectionSetChart(mesh->coneSection, pStart, pEnd));
3246: PetscCall(PetscSectionSetChart(mesh->supportSection, pStart, pEnd));
3247: PetscCall(PetscFree(mesh->cellTypes));
3248: PetscFunctionReturn(PETSC_SUCCESS);
3249: }
3251: /*@
3252: DMPlexGetConeSize - Return the number of in-edges for this point in the DAG
3254: Not Collective
3256: Input Parameters:
3257: + dm - The `DMPLEX`
3258: - p - The point, which must lie in the chart set with `DMPlexSetChart()`
3260: Output Parameter:
3261: . size - The cone size for point `p`
3263: Level: beginner
3265: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexSetConeSize()`, `DMPlexSetChart()`
3266: @*/
3267: PetscErrorCode DMPlexGetConeSize(DM dm, PetscInt p, PetscInt *size)
3268: {
3269: DM_Plex *mesh = (DM_Plex *)dm->data;
3271: PetscFunctionBegin;
3273: PetscAssertPointer(size, 3);
3274: if (mesh->tr) PetscCall(DMPlexTransformGetConeSize(mesh->tr, p, size));
3275: else PetscCall(PetscSectionGetDof(mesh->coneSection, p, size));
3276: PetscFunctionReturn(PETSC_SUCCESS);
3277: }
3279: /*@
3280: DMPlexSetConeSize - Set the number of in-edges for this point in the DAG
3282: Not Collective
3284: Input Parameters:
3285: + dm - The `DMPLEX`
3286: . p - The point, which must lie in the chart set with `DMPlexSetChart()`
3287: - size - The cone size for point `p`
3289: Level: beginner
3291: Note:
3292: This should be called after `DMPlexSetChart()`.
3294: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSetCone()`, `DMPlexCreate()`, `DMPlexGetConeSize()`, `DMPlexSetChart()`
3295: @*/
3296: PetscErrorCode DMPlexSetConeSize(DM dm, PetscInt p, PetscInt size)
3297: {
3298: DM_Plex *mesh = (DM_Plex *)dm->data;
3300: PetscFunctionBegin;
3302: PetscCheck(!mesh->tr, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Cannot call DMPlexSetConeSize() on a mesh with a transform defined.");
3303: PetscCall(PetscSectionSetDof(mesh->coneSection, p, size));
3304: PetscFunctionReturn(PETSC_SUCCESS);
3305: }
3307: /*@C
3308: DMPlexGetCone - Return the points on the in-edges for this point in the DAG
3310: Not Collective
3312: Input Parameters:
3313: + dm - The `DMPLEX`
3314: - p - The point, which must lie in the chart set with `DMPlexSetChart()`
3316: Output Parameter:
3317: . cone - An array of points which are on the in-edges for point `p`, the length of `cone` is the result of `DMPlexGetConeSize()`
3319: Level: beginner
3321: Fortran Notes:
3322: `cone` must be declared with
3323: .vb
3324: PetscInt, pointer :: cone(:)
3325: .ve
3327: You must call `DMPlexRestoreCone()` after you finish using the array.
3328: `DMPlexRestoreCone()` is not needed/available in C.
3330: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetConeSize()`, `DMPlexSetCone()`, `DMPlexGetConeTuple()`, `DMPlexSetChart()`, `DMPlexRestoreCone()`
3331: @*/
3332: PetscErrorCode DMPlexGetCone(DM dm, PetscInt p, const PetscInt *cone[])
3333: {
3334: DM_Plex *mesh = (DM_Plex *)dm->data;
3335: PetscInt off;
3337: PetscFunctionBegin;
3339: PetscAssertPointer(cone, 3);
3340: PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
3341: *cone = PetscSafePointerPlusOffset(mesh->cones, off);
3342: PetscFunctionReturn(PETSC_SUCCESS);
3343: }
3345: /*@
3346: DMPlexGetConeTuple - Return the points on the in-edges of several points in the DAG
3348: Not Collective
3350: Input Parameters:
3351: + dm - The `DMPLEX`
3352: - p - The `IS` of points, which must lie in the chart set with `DMPlexSetChart()`
3354: Output Parameters:
3355: + pConesSection - `PetscSection` describing the layout of `pCones`
3356: - pCones - An `IS` containing the points which are on the in-edges for the point set `p`
3358: Level: intermediate
3360: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexGetConeRecursive()`, `DMPlexSetChart()`, `PetscSection`, `IS`
3361: @*/
3362: PetscErrorCode DMPlexGetConeTuple(DM dm, IS p, PeOp PetscSection *pConesSection, PeOp IS *pCones)
3363: {
3364: PetscSection cs, newcs;
3365: PetscInt *cones;
3366: PetscInt *newarr = NULL;
3367: PetscInt n;
3369: PetscFunctionBegin;
3370: PetscCall(DMPlexGetCones(dm, &cones));
3371: PetscCall(DMPlexGetConeSection(dm, &cs));
3372: PetscCall(PetscSectionExtractDofsFromArray(cs, MPIU_INT, cones, p, &newcs, pCones ? ((void **)&newarr) : NULL));
3373: if (pConesSection) *pConesSection = newcs;
3374: if (pCones) {
3375: PetscCall(PetscSectionGetStorageSize(newcs, &n));
3376: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)p), n, newarr, PETSC_OWN_POINTER, pCones));
3377: }
3378: PetscFunctionReturn(PETSC_SUCCESS);
3379: }
3381: /*@
3382: DMPlexGetConeRecursiveVertices - Expand each given point into its cone points and do that recursively until we end up just with vertices.
3384: Not Collective
3386: Input Parameters:
3387: + dm - The `DMPLEX`
3388: - points - The `IS` of points, which must lie in the chart set with `DMPlexSetChart()`
3390: Output Parameter:
3391: . expandedPoints - An `IS` containing the of vertices recursively expanded from input points
3393: Level: advanced
3395: Notes:
3396: Like `DMPlexGetConeRecursive()` but returns only the 0-depth `IS` (i.e. vertices only) and no sections.
3398: There is no corresponding Restore function, just call `ISDestroy()` on the returned `IS` to deallocate.
3400: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexGetConeTuple()`, `DMPlexGetConeRecursive()`, `DMPlexRestoreConeRecursive()`,
3401: `DMPlexGetDepth()`, `IS`
3402: @*/
3403: PetscErrorCode DMPlexGetConeRecursiveVertices(DM dm, IS points, IS *expandedPoints)
3404: {
3405: IS *expandedPointsAll;
3406: PetscInt depth;
3408: PetscFunctionBegin;
3411: PetscAssertPointer(expandedPoints, 3);
3412: PetscCall(DMPlexGetConeRecursive(dm, points, &depth, &expandedPointsAll, NULL));
3413: *expandedPoints = expandedPointsAll[0];
3414: PetscCall(PetscObjectReference((PetscObject)expandedPointsAll[0]));
3415: PetscCall(DMPlexRestoreConeRecursive(dm, points, &depth, &expandedPointsAll, NULL));
3416: PetscFunctionReturn(PETSC_SUCCESS);
3417: }
3419: /*@
3420: DMPlexGetConeRecursive - Expand each given point into its cone points and do that recursively until we end up just with vertices
3421: (DAG points of depth 0, i.e., without cones).
3423: Not Collective
3425: Input Parameters:
3426: + dm - The `DMPLEX`
3427: - points - The `IS` of points, which must lie in the chart set with `DMPlexSetChart()`
3429: Output Parameters:
3430: + depth - (optional) Size of the output arrays, equal to `DMPLEX` depth, returned by `DMPlexGetDepth()`
3431: . expandedPoints - (optional) An array of index sets with recursively expanded cones
3432: - sections - (optional) An array of sections which describe mappings from points to their cone points
3434: Level: advanced
3436: Notes:
3437: Like `DMPlexGetConeTuple()` but recursive.
3439: Array `expandedPoints` has size equal to `depth`. Each `expandedPoints`[d] contains DAG points with maximum depth d, recursively cone-wise expanded from the input points.
3440: For example, for d=0 it contains only vertices, for d=1 it can contain vertices and edges, etc.
3442: Array section has size equal to `depth`. Each `PetscSection` `sections`[d] realizes mapping from `expandedPoints`[d+1] (section points) to `expandedPoints`[d] (section dofs) as follows\:
3443: (1) DAG points in `expandedPoints`[d+1] with `depth` d+1 to their cone points in `expandedPoints`[d];
3444: (2) DAG points in `expandedPoints`[d+1] with `depth` in [0,d] to the same points in `expandedPoints`[d].
3446: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexGetConeTuple()`, `DMPlexRestoreConeRecursive()`, `DMPlexGetConeRecursiveVertices()`,
3447: `DMPlexGetDepth()`, `PetscSection`, `IS`
3448: @*/
3449: PetscErrorCode DMPlexGetConeRecursive(DM dm, IS points, PeOp PetscInt *depth, PeOp IS *expandedPoints[], PeOp PetscSection *sections[])
3450: {
3451: const PetscInt *arr0 = NULL, *cone = NULL;
3452: PetscInt *arr = NULL, *newarr = NULL;
3453: PetscInt d, depth_, i, n, newn, cn, co, start, end;
3454: IS *expandedPoints_;
3455: PetscSection *sections_;
3457: PetscFunctionBegin;
3460: if (depth) PetscAssertPointer(depth, 3);
3461: if (expandedPoints) PetscAssertPointer(expandedPoints, 4);
3462: if (sections) PetscAssertPointer(sections, 5);
3463: PetscCall(ISGetLocalSize(points, &n));
3464: PetscCall(ISGetIndices(points, &arr0));
3465: PetscCall(DMPlexGetDepth(dm, &depth_));
3466: PetscCall(PetscCalloc1(depth_, &expandedPoints_));
3467: PetscCall(PetscCalloc1(depth_, §ions_));
3468: arr = (PetscInt *)arr0; /* this is ok because first generation of arr is not modified */
3469: for (d = depth_ - 1; d >= 0; d--) {
3470: PetscCall(PetscSectionCreate(PETSC_COMM_SELF, §ions_[d]));
3471: PetscCall(PetscSectionSetChart(sections_[d], 0, n));
3472: for (i = 0; i < n; i++) {
3473: PetscCall(DMPlexGetDepthStratum(dm, d + 1, &start, &end));
3474: if (arr[i] >= start && arr[i] < end) {
3475: PetscCall(DMPlexGetConeSize(dm, arr[i], &cn));
3476: PetscCall(PetscSectionSetDof(sections_[d], i, cn));
3477: } else {
3478: PetscCall(PetscSectionSetDof(sections_[d], i, 1));
3479: }
3480: }
3481: PetscCall(PetscSectionSetUp(sections_[d]));
3482: PetscCall(PetscSectionGetStorageSize(sections_[d], &newn));
3483: PetscCall(PetscMalloc1(newn, &newarr));
3484: for (i = 0; i < n; i++) {
3485: PetscCall(PetscSectionGetDof(sections_[d], i, &cn));
3486: PetscCall(PetscSectionGetOffset(sections_[d], i, &co));
3487: if (cn > 1) {
3488: PetscCall(DMPlexGetCone(dm, arr[i], &cone));
3489: PetscCall(PetscArraycpy(&newarr[co], cone, cn));
3490: } else {
3491: newarr[co] = arr[i];
3492: }
3493: }
3494: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, newn, newarr, PETSC_OWN_POINTER, &expandedPoints_[d]));
3495: arr = newarr;
3496: n = newn;
3497: }
3498: PetscCall(ISRestoreIndices(points, &arr0));
3499: *depth = depth_;
3500: if (expandedPoints) *expandedPoints = expandedPoints_;
3501: else {
3502: for (d = 0; d < depth_; d++) PetscCall(ISDestroy(&expandedPoints_[d]));
3503: PetscCall(PetscFree(expandedPoints_));
3504: }
3505: if (sections) *sections = sections_;
3506: else {
3507: for (d = 0; d < depth_; d++) PetscCall(PetscSectionDestroy(§ions_[d]));
3508: PetscCall(PetscFree(sections_));
3509: }
3510: PetscFunctionReturn(PETSC_SUCCESS);
3511: }
3513: /*@
3514: DMPlexRestoreConeRecursive - Deallocates arrays created by `DMPlexGetConeRecursive()`
3516: Not Collective
3518: Input Parameters:
3519: + dm - The `DMPLEX`
3520: - points - The `IS` of points, which must lie in the chart set with `DMPlexSetChart()`
3522: Output Parameters:
3523: + depth - (optional) Size of the output arrays, equal to `DMPLEX` depth, returned by `DMPlexGetDepth()`
3524: . expandedPoints - (optional) An array of recursively expanded cones
3525: - sections - (optional) An array of sections which describe mappings from points to their cone points
3527: Level: advanced
3529: Note:
3530: See `DMPlexGetConeRecursive()`
3532: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexGetConeTuple()`, `DMPlexGetConeRecursive()`, `DMPlexGetConeRecursiveVertices()`,
3533: `DMPlexGetDepth()`, `IS`, `PetscSection`
3534: @*/
3535: PetscErrorCode DMPlexRestoreConeRecursive(DM dm, IS points, PeOp PetscInt *depth, PeOp IS *expandedPoints[], PeOp PetscSection *sections[])
3536: {
3537: PetscInt depth_;
3539: PetscFunctionBegin;
3540: PetscCall(DMPlexGetDepth(dm, &depth_));
3541: PetscCheck(!depth || *depth == depth_, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "depth changed since last call to DMPlexGetConeRecursive");
3542: if (depth) *depth = 0;
3543: if (expandedPoints) {
3544: for (PetscInt d = 0; d < depth_; d++) PetscCall(ISDestroy(&(*expandedPoints)[d]));
3545: PetscCall(PetscFree(*expandedPoints));
3546: }
3547: if (sections) {
3548: for (PetscInt d = 0; d < depth_; d++) PetscCall(PetscSectionDestroy(&(*sections)[d]));
3549: PetscCall(PetscFree(*sections));
3550: }
3551: PetscFunctionReturn(PETSC_SUCCESS);
3552: }
3554: /*@
3555: DMPlexSetCone - Set the points on the in-edges for this point in the DAG; that is these are the points that cover the specific point
3557: Not Collective
3559: Input Parameters:
3560: + dm - The `DMPLEX`
3561: . p - The point, which must lie in the chart set with `DMPlexSetChart()`
3562: - cone - An array of points which are on the in-edges for point `p`, its length must have been previously provided with `DMPlexSetConeSize()`
3564: Level: beginner
3566: Note:
3567: This should be called after all calls to `DMPlexSetConeSize()` and `DMSetUp()`.
3569: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`, `DMPlexSetSupport()`, `DMPlexSetSupportSize()`
3570: @*/
3571: PetscErrorCode DMPlexSetCone(DM dm, PetscInt p, const PetscInt cone[])
3572: {
3573: DM_Plex *mesh = (DM_Plex *)dm->data;
3574: PetscInt dof, off, c;
3576: PetscFunctionBegin;
3578: PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
3579: if (dof) PetscAssertPointer(cone, 3);
3580: PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
3581: if (PetscDefined(USE_DEBUG)) {
3582: PetscInt pStart, pEnd;
3583: PetscCall(PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd));
3584: PetscCheck(!(p < pStart) && !(p >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, pStart, pEnd);
3585: for (c = 0; c < dof; ++c) {
3586: PetscCheck(!(cone[c] < pStart) && !(cone[c] >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", cone[c], pStart, pEnd);
3587: mesh->cones[off + c] = cone[c];
3588: }
3589: } else {
3590: for (c = 0; c < dof; ++c) mesh->cones[off + c] = cone[c];
3591: }
3592: PetscFunctionReturn(PETSC_SUCCESS);
3593: }
3595: /*@C
3596: DMPlexGetConeOrientation - Return the orientations on the in-edges for this point in the DAG
3598: Not Collective
3600: Input Parameters:
3601: + dm - The `DMPLEX`
3602: - p - The point, which must lie in the chart set with `DMPlexSetChart()`
3604: Output Parameter:
3605: . coneOrientation - An array of orientations which are on the in-edges for point `p`. An orientation is an
3606: integer giving the prescription for cone traversal. Its length is given by the result of `DMPlexSetConeSize()`
3608: Level: beginner
3610: Note:
3611: The number indexes the symmetry transformations for the cell type (see manual). Orientation 0 is always
3612: the identity transformation. Negative orientation indicates reflection so that -(o+1) is the reflection
3613: of o, however it is not necessarily the inverse. To get the inverse, use `DMPolytopeTypeComposeOrientationInv()`
3614: with the identity.
3616: Fortran Notes:
3617: You must call `DMPlexRestoreConeOrientation()` after you finish using the returned array.
3618: `DMPlexRestoreConeOrientation()` is not needed/available in C.
3620: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSetConeSize()`, `DMPolytopeTypeComposeOrientation()`, `DMPolytopeTypeComposeOrientationInv()`,
3621: `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetCone()`, `DMPlexSetChart()`
3622: @*/
3623: PetscErrorCode DMPlexGetConeOrientation(DM dm, PetscInt p, const PetscInt *coneOrientation[])
3624: {
3625: DM_Plex *mesh = (DM_Plex *)dm->data;
3626: PetscInt off;
3628: PetscFunctionBegin;
3630: if (PetscDefined(USE_DEBUG)) {
3631: PetscInt dof;
3632: PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
3633: if (dof) PetscAssertPointer(coneOrientation, 3);
3634: }
3635: PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
3637: *coneOrientation = &mesh->coneOrientations[off];
3638: PetscFunctionReturn(PETSC_SUCCESS);
3639: }
3641: /*@
3642: DMPlexSetConeOrientation - Set the orientations on the in-edges for this point in the DAG
3644: Not Collective
3646: Input Parameters:
3647: + dm - The `DMPLEX`
3648: . p - The point, which must lie in the chart set with `DMPlexSetChart()`
3649: - coneOrientation - An array of orientations. Its length is given by the result of `DMPlexSetConeSize()`
3651: Level: beginner
3653: Notes:
3654: This should be called after all calls to `DMPlexSetConeSize()` and `DMSetUp()`.
3656: The meaning of coneOrientation is detailed in `DMPlexGetConeOrientation()`.
3658: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetConeOrientation()`, `DMPlexSetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`
3659: @*/
3660: PetscErrorCode DMPlexSetConeOrientation(DM dm, PetscInt p, const PetscInt coneOrientation[])
3661: {
3662: DM_Plex *mesh = (DM_Plex *)dm->data;
3663: PetscInt pStart, pEnd;
3664: PetscInt dof, off, c;
3666: PetscFunctionBegin;
3668: PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
3669: if (dof) PetscAssertPointer(coneOrientation, 3);
3670: PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
3671: if (PetscDefined(USE_DEBUG)) {
3672: PetscCall(PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd));
3673: PetscCheck(!(p < pStart) && !(p >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, pStart, pEnd);
3674: for (c = 0; c < dof; ++c) {
3675: PetscInt cdof, o = coneOrientation[c];
3677: PetscCall(PetscSectionGetDof(mesh->coneSection, mesh->cones[off + c], &cdof));
3678: PetscCheck(!o || (o >= -(cdof + 1) && o < cdof), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone orientation %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ". %" PetscInt_FMT ")", o, -(cdof + 1), cdof);
3679: mesh->coneOrientations[off + c] = o;
3680: }
3681: } else {
3682: for (c = 0; c < dof; ++c) mesh->coneOrientations[off + c] = coneOrientation[c];
3683: }
3684: PetscFunctionReturn(PETSC_SUCCESS);
3685: }
3687: /*@
3688: DMPlexInsertCone - Insert a point into the in-edges for the point p in the DAG
3690: Not Collective
3692: Input Parameters:
3693: + dm - The `DMPLEX`
3694: . p - The point, which must lie in the chart set with `DMPlexSetChart()`
3695: . conePos - The local index in the cone where the point should be put
3696: - conePoint - The mesh point to insert
3698: Level: beginner
3700: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`
3701: @*/
3702: PetscErrorCode DMPlexInsertCone(DM dm, PetscInt p, PetscInt conePos, PetscInt conePoint)
3703: {
3704: DM_Plex *mesh = (DM_Plex *)dm->data;
3705: PetscInt pStart, pEnd;
3706: PetscInt dof, off;
3708: PetscFunctionBegin;
3710: if (PetscDefined(USE_DEBUG)) {
3711: PetscCall(PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd));
3712: PetscCheck(!(p < pStart) && !(p >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, pStart, pEnd);
3713: PetscCheck(!(conePoint < pStart) && !(conePoint >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", conePoint, pStart, pEnd);
3714: PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
3715: PetscCheck(!(conePos < 0) && !(conePos >= dof), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone position %" PetscInt_FMT " of point %" PetscInt_FMT " is not in the valid range [0, %" PetscInt_FMT ")", conePos, p, dof);
3716: }
3717: PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
3718: mesh->cones[off + conePos] = conePoint;
3719: PetscFunctionReturn(PETSC_SUCCESS);
3720: }
3722: /*@
3723: DMPlexInsertConeOrientation - Insert a point orientation for the in-edge for the point p in the DAG
3725: Not Collective
3727: Input Parameters:
3728: + dm - The `DMPLEX`
3729: . p - The point, which must lie in the chart set with `DMPlexSetChart()`
3730: . conePos - The local index in the cone where the point should be put
3731: - coneOrientation - The point orientation to insert
3733: Level: beginner
3735: Note:
3736: The meaning of coneOrientation values is detailed in `DMPlexGetConeOrientation()`.
3738: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`
3739: @*/
3740: PetscErrorCode DMPlexInsertConeOrientation(DM dm, PetscInt p, PetscInt conePos, PetscInt coneOrientation)
3741: {
3742: DM_Plex *mesh = (DM_Plex *)dm->data;
3743: PetscInt pStart, pEnd;
3744: PetscInt dof, off;
3746: PetscFunctionBegin;
3748: if (PetscDefined(USE_DEBUG)) {
3749: PetscCall(PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd));
3750: PetscCheck(!(p < pStart) && !(p >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, pStart, pEnd);
3751: PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
3752: PetscCheck(!(conePos < 0) && !(conePos >= dof), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cone position %" PetscInt_FMT " of point %" PetscInt_FMT " is not in the valid range [0, %" PetscInt_FMT ")", conePos, p, dof);
3753: }
3754: PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
3755: mesh->coneOrientations[off + conePos] = coneOrientation;
3756: PetscFunctionReturn(PETSC_SUCCESS);
3757: }
3759: /*@C
3760: DMPlexGetOrientedCone - Return the points and orientations on the in-edges for this point in the DAG
3762: Not collective
3764: Input Parameters:
3765: + dm - The DMPlex
3766: - p - The point, which must lie in the chart set with DMPlexSetChart()
3768: Output Parameters:
3769: + cone - An array of points which are on the in-edges for point `p`
3770: - ornt - An array of orientations which are on the in-edges for point `p`. An orientation is an
3771: integer giving the prescription for cone traversal.
3773: Level: beginner
3775: Notes:
3776: The number indexes the symmetry transformations for the cell type (see manual). Orientation 0 is always
3777: the identity transformation. Negative orientation indicates reflection so that -(o+1) is the reflection
3778: of o, however it is not necessarily the inverse. To get the inverse, use `DMPolytopeTypeComposeOrientationInv()`
3779: with the identity.
3781: You must also call `DMPlexRestoreOrientedCone()` after you finish using the returned array.
3783: Fortran Notes:
3784: `cone` and `ornt` must be declared with
3785: .vb
3786: PetscInt, pointer :: cone(:)
3787: PetscInt, pointer :: ornt(:)
3788: .ve
3790: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexRestoreOrientedCone()`, `DMPlexGetConeSize()`, `DMPlexGetCone()`, `DMPlexGetChart()`
3791: @*/
3792: PetscErrorCode DMPlexGetOrientedCone(DM dm, PetscInt p, PeOp const PetscInt *cone[], PeOp const PetscInt *ornt[])
3793: {
3794: DM_Plex *mesh = (DM_Plex *)dm->data;
3796: PetscFunctionBegin;
3798: if (mesh->tr) {
3799: PetscCall(DMPlexTransformGetCone(mesh->tr, p, cone, ornt));
3800: } else {
3801: PetscInt off;
3802: if (PetscDefined(USE_DEBUG)) {
3803: PetscInt dof;
3804: PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
3805: if (dof) {
3806: if (cone) PetscAssertPointer(cone, 3);
3807: if (ornt) PetscAssertPointer(ornt, 4);
3808: }
3809: }
3810: PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
3811: if (cone) *cone = PetscSafePointerPlusOffset(mesh->cones, off);
3812: if (ornt) *ornt = PetscSafePointerPlusOffset(mesh->coneOrientations, off);
3813: }
3814: PetscFunctionReturn(PETSC_SUCCESS);
3815: }
3817: /*@C
3818: DMPlexRestoreOrientedCone - Restore the points and orientations on the in-edges for this point in the DAG obtained with `DMPlexGetOrientedCone()`
3820: Not Collective
3822: Input Parameters:
3823: + dm - The DMPlex
3824: . p - The point, which must lie in the chart set with `DMPlexSetChart()`
3825: . cone - An array of points which are on the in-edges for point p
3826: - ornt - An array of orientations which are on the in-edges for point `p`. An orientation is an
3827: integer giving the prescription for cone traversal.
3829: Level: beginner
3831: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetOrientedCone()`, `DMPlexGetConeSize()`, `DMPlexGetCone()`, `DMPlexGetChart()`
3832: @*/
3833: PetscErrorCode DMPlexRestoreOrientedCone(DM dm, PetscInt p, const PetscInt *cone[], const PetscInt *ornt[])
3834: {
3835: DM_Plex *mesh = (DM_Plex *)dm->data;
3837: PetscFunctionBegin;
3839: if (mesh->tr) PetscCall(DMPlexTransformRestoreCone(mesh->tr, p, cone, ornt));
3840: PetscFunctionReturn(PETSC_SUCCESS);
3841: }
3843: /*@
3844: DMPlexGetSupportSize - Return the number of out-edges for this point in the DAG
3846: Not Collective
3848: Input Parameters:
3849: + dm - The `DMPLEX`
3850: - p - The point, which must lie in the chart set with `DMPlexSetChart()`
3852: Output Parameter:
3853: . size - The support size for point `p`
3855: Level: beginner
3857: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexSetConeSize()`, `DMPlexSetChart()`, `DMPlexGetConeSize()`
3858: @*/
3859: PetscErrorCode DMPlexGetSupportSize(DM dm, PetscInt p, PetscInt *size)
3860: {
3861: DM_Plex *mesh = (DM_Plex *)dm->data;
3863: PetscFunctionBegin;
3865: PetscAssertPointer(size, 3);
3866: PetscCall(PetscSectionGetDof(mesh->supportSection, p, size));
3867: PetscFunctionReturn(PETSC_SUCCESS);
3868: }
3870: /*@
3871: DMPlexSetSupportSize - Set the number of out-edges for this point in the DAG
3873: Not Collective
3875: Input Parameters:
3876: + dm - The `DMPLEX`
3877: . p - The point, which must lie in the chart set with `DMPlexSetChart()`
3878: - size - The support size for point `p`
3880: Level: beginner
3882: Note:
3883: This should be called after `DMPlexSetChart()`.
3885: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetSupportSize()`, `DMPlexSetChart()`
3886: @*/
3887: PetscErrorCode DMPlexSetSupportSize(DM dm, PetscInt p, PetscInt size)
3888: {
3889: DM_Plex *mesh = (DM_Plex *)dm->data;
3891: PetscFunctionBegin;
3893: PetscCall(PetscSectionSetDof(mesh->supportSection, p, size));
3894: PetscFunctionReturn(PETSC_SUCCESS);
3895: }
3897: /*@C
3898: DMPlexGetSupport - Return the points on the out-edges for this point in the DAG
3900: Not Collective
3902: Input Parameters:
3903: + dm - The `DMPLEX`
3904: - p - The point, which must lie in the chart set with `DMPlexSetChart()`
3906: Output Parameter:
3907: . support - An array of points which are on the out-edges for point `p`, its length is that obtained from `DMPlexGetSupportSize()`
3909: Level: beginner
3911: Fortran Notes:
3912: `support` must be declared with
3913: .vb
3914: PetscInt, pointer :: support(:)
3915: .ve
3917: You must also call `DMPlexRestoreSupport()` after you finish using the returned array.
3918: `DMPlexRestoreSupport()` is not needed/available in C.
3920: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetSupportSize()`, `DMPlexSetSupport()`, `DMPlexGetCone()`, `DMPlexSetChart()`
3921: @*/
3922: PetscErrorCode DMPlexGetSupport(DM dm, PetscInt p, const PetscInt *support[])
3923: {
3924: DM_Plex *mesh = (DM_Plex *)dm->data;
3925: PetscInt off;
3927: PetscFunctionBegin;
3929: PetscAssertPointer(support, 3);
3930: PetscCall(PetscSectionGetOffset(mesh->supportSection, p, &off));
3931: *support = PetscSafePointerPlusOffset(mesh->supports, off);
3932: PetscFunctionReturn(PETSC_SUCCESS);
3933: }
3935: /*@
3936: DMPlexSetSupport - Set the points on the out-edges for this point in the DAG, that is the list of points that this point covers
3938: Not Collective
3940: Input Parameters:
3941: + dm - The `DMPLEX`
3942: . p - The point, which must lie in the chart set with `DMPlexSetChart()`
3943: - support - An array of points which are on the out-edges for point `p`, its length is that obtained from `DMPlexGetSupportSize()`
3945: Level: beginner
3947: Note:
3948: This should be called after all calls to `DMPlexSetSupportSize()` and `DMSetUp()`.
3950: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSetCone()`, `DMPlexSetConeSize()`, `DMPlexCreate()`, `DMPlexGetSupport()`, `DMPlexSetChart()`, `DMPlexSetSupportSize()`, `DMSetUp()`
3951: @*/
3952: PetscErrorCode DMPlexSetSupport(DM dm, PetscInt p, const PetscInt support[])
3953: {
3954: DM_Plex *mesh = (DM_Plex *)dm->data;
3955: PetscInt pStart, pEnd;
3956: PetscInt dof, off, c;
3958: PetscFunctionBegin;
3960: PetscCall(PetscSectionGetChart(mesh->supportSection, &pStart, &pEnd));
3961: PetscCall(PetscSectionGetDof(mesh->supportSection, p, &dof));
3962: if (dof) PetscAssertPointer(support, 3);
3963: PetscCall(PetscSectionGetOffset(mesh->supportSection, p, &off));
3964: PetscCheck(!(p < pStart) && !(p >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, pStart, pEnd);
3965: for (c = 0; c < dof; ++c) {
3966: PetscCheck(!(support[c] < pStart) && !(support[c] >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Support point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", support[c], pStart, pEnd);
3967: mesh->supports[off + c] = support[c];
3968: }
3969: PetscFunctionReturn(PETSC_SUCCESS);
3970: }
3972: /*@
3973: DMPlexInsertSupport - Insert a point into the out-edges for the point p in the DAG
3975: Not Collective
3977: Input Parameters:
3978: + dm - The `DMPLEX`
3979: . p - The point, which must lie in the chart set with `DMPlexSetChart()`
3980: . supportPos - The local index in the cone where the point should be put
3981: - supportPoint - The mesh point to insert
3983: Level: beginner
3985: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexGetCone()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMSetUp()`
3986: @*/
3987: PetscErrorCode DMPlexInsertSupport(DM dm, PetscInt p, PetscInt supportPos, PetscInt supportPoint)
3988: {
3989: DM_Plex *mesh = (DM_Plex *)dm->data;
3990: PetscInt pStart, pEnd;
3991: PetscInt dof, off;
3993: PetscFunctionBegin;
3995: PetscCall(PetscSectionGetChart(mesh->supportSection, &pStart, &pEnd));
3996: PetscCall(PetscSectionGetDof(mesh->supportSection, p, &dof));
3997: PetscCall(PetscSectionGetOffset(mesh->supportSection, p, &off));
3998: PetscCheck(!(p < pStart) && !(p >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, pStart, pEnd);
3999: PetscCheck(!(supportPoint < pStart) && !(supportPoint >= pEnd), PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Support point %" PetscInt_FMT " is not in the valid range [%" PetscInt_FMT ", %" PetscInt_FMT ")", supportPoint, pStart, pEnd);
4000: PetscCheck(supportPos < dof, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Support position %" PetscInt_FMT " of point %" PetscInt_FMT " is not in the valid range [0, %" PetscInt_FMT ")", supportPos, p, dof);
4001: mesh->supports[off + supportPos] = supportPoint;
4002: PetscFunctionReturn(PETSC_SUCCESS);
4003: }
4005: /* Converts an orientation o in the current numbering to the previous scheme used in Plex */
4006: PetscInt DMPolytopeConvertNewOrientation_Internal(DMPolytopeType ct, PetscInt o)
4007: {
4008: switch (ct) {
4009: case DM_POLYTOPE_SEGMENT:
4010: if (o == -1) return -2;
4011: break;
4012: case DM_POLYTOPE_TRIANGLE:
4013: if (o == -3) return -1;
4014: if (o == -2) return -3;
4015: if (o == -1) return -2;
4016: break;
4017: case DM_POLYTOPE_QUADRILATERAL:
4018: if (o == -4) return -2;
4019: if (o == -3) return -1;
4020: if (o == -2) return -4;
4021: if (o == -1) return -3;
4022: break;
4023: default:
4024: return o;
4025: }
4026: return o;
4027: }
4029: /* Converts an orientation o in the previous scheme used in Plex to the current numbering */
4030: PetscInt DMPolytopeConvertOldOrientation_Internal(DMPolytopeType ct, PetscInt o)
4031: {
4032: switch (ct) {
4033: case DM_POLYTOPE_SEGMENT:
4034: if ((o == -2) || (o == 1)) return -1;
4035: if (o == -1) return 0;
4036: break;
4037: case DM_POLYTOPE_TRIANGLE:
4038: if (o == -3) return -2;
4039: if (o == -2) return -1;
4040: if (o == -1) return -3;
4041: break;
4042: case DM_POLYTOPE_QUADRILATERAL:
4043: if (o == -4) return -2;
4044: if (o == -3) return -1;
4045: if (o == -2) return -4;
4046: if (o == -1) return -3;
4047: break;
4048: default:
4049: return o;
4050: }
4051: return o;
4052: }
4054: /* Takes in a mesh whose orientations are in the previous scheme and converts them all to the current numbering */
4055: PetscErrorCode DMPlexConvertOldOrientations_Internal(DM dm)
4056: {
4057: PetscInt pStart, pEnd, p;
4059: PetscFunctionBegin;
4060: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
4061: for (p = pStart; p < pEnd; ++p) {
4062: const PetscInt *cone, *ornt;
4063: PetscInt coneSize, c;
4065: PetscCall(DMPlexGetConeSize(dm, p, &coneSize));
4066: PetscCall(DMPlexGetCone(dm, p, &cone));
4067: PetscCall(DMPlexGetConeOrientation(dm, p, &ornt));
4068: for (c = 0; c < coneSize; ++c) {
4069: DMPolytopeType ct;
4070: const PetscInt o = ornt[c];
4072: PetscCall(DMPlexGetCellType(dm, cone[c], &ct));
4073: switch (ct) {
4074: case DM_POLYTOPE_SEGMENT:
4075: if ((o == -2) || (o == 1)) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -1));
4076: if (o == -1) PetscCall(DMPlexInsertConeOrientation(dm, p, c, 0));
4077: break;
4078: case DM_POLYTOPE_TRIANGLE:
4079: if (o == -3) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -2));
4080: if (o == -2) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -1));
4081: if (o == -1) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -3));
4082: break;
4083: case DM_POLYTOPE_QUADRILATERAL:
4084: if (o == -4) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -2));
4085: if (o == -3) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -1));
4086: if (o == -2) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -4));
4087: if (o == -1) PetscCall(DMPlexInsertConeOrientation(dm, p, c, -3));
4088: break;
4089: default:
4090: break;
4091: }
4092: }
4093: }
4094: PetscFunctionReturn(PETSC_SUCCESS);
4095: }
4097: static inline PetscErrorCode DMPlexGetTransitiveClosure_Hot_Private(DM dm, PetscInt p, PetscBool useCone, PetscInt *size, const PetscInt *arr[], const PetscInt *ornt[])
4098: {
4099: DM_Plex *mesh = (DM_Plex *)dm->data;
4101: PetscFunctionBeginHot;
4102: if (PetscDefined(USE_DEBUG) || mesh->tr) {
4103: if (useCone) {
4104: PetscCall(DMPlexGetConeSize(dm, p, size));
4105: PetscCall(DMPlexGetOrientedCone(dm, p, arr, ornt));
4106: } else {
4107: PetscCall(DMPlexGetSupportSize(dm, p, size));
4108: PetscCall(DMPlexGetSupport(dm, p, arr));
4109: }
4110: } else {
4111: if (useCone) {
4112: const PetscSection s = mesh->coneSection;
4113: const PetscInt ps = p - s->pStart;
4114: const PetscInt off = s->atlasOff[ps];
4116: *size = s->atlasDof[ps];
4117: *arr = mesh->cones + off;
4118: *ornt = mesh->coneOrientations + off;
4119: } else {
4120: const PetscSection s = mesh->supportSection;
4121: const PetscInt ps = p - s->pStart;
4122: const PetscInt off = s->atlasOff[ps];
4124: *size = s->atlasDof[ps];
4125: *arr = mesh->supports + off;
4126: }
4127: }
4128: PetscFunctionReturn(PETSC_SUCCESS);
4129: }
4131: static inline PetscErrorCode DMPlexRestoreTransitiveClosure_Hot_Private(DM dm, PetscInt p, PetscBool useCone, PetscInt *size, const PetscInt *arr[], const PetscInt *ornt[])
4132: {
4133: DM_Plex *mesh = (DM_Plex *)dm->data;
4135: PetscFunctionBeginHot;
4136: if (PetscDefined(USE_DEBUG) || mesh->tr) {
4137: if (useCone) PetscCall(DMPlexRestoreOrientedCone(dm, p, arr, ornt));
4138: }
4139: PetscFunctionReturn(PETSC_SUCCESS);
4140: }
4142: static PetscErrorCode DMPlexGetTransitiveClosure_Depth1_Private(DM dm, PetscInt p, PetscInt ornt, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
4143: {
4144: DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
4145: PetscInt *closure;
4146: const PetscInt *tmp = NULL, *tmpO = NULL;
4147: PetscInt off = 0, tmpSize, t;
4149: PetscFunctionBeginHot;
4150: if (ornt) {
4151: PetscCall(DMPlexGetCellType(dm, p, &ct));
4152: if (ct == DM_POLYTOPE_FV_GHOST || ct == DM_POLYTOPE_INTERIOR_GHOST || ct == DM_POLYTOPE_UNKNOWN || ct == DM_POLYTOPE_UNKNOWN_CELL || ct == DM_POLYTOPE_UNKNOWN_FACE) ct = DM_POLYTOPE_UNKNOWN;
4153: }
4154: if (*points) {
4155: closure = *points;
4156: } else {
4157: PetscInt maxConeSize, maxSupportSize;
4158: PetscCall(DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize));
4159: PetscCall(DMGetWorkArray(dm, 2 * (PetscMax(maxConeSize, maxSupportSize) + 1), MPIU_INT, &closure));
4160: }
4161: PetscCall(DMPlexGetTransitiveClosure_Hot_Private(dm, p, useCone, &tmpSize, &tmp, &tmpO));
4162: if (ct == DM_POLYTOPE_UNKNOWN) {
4163: closure[off++] = p;
4164: closure[off++] = 0;
4165: for (t = 0; t < tmpSize; ++t) {
4166: closure[off++] = tmp[t];
4167: closure[off++] = tmpO ? tmpO[t] : 0;
4168: }
4169: } else {
4170: const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, ornt);
4172: /* We assume that cells with a valid type have faces with a valid type */
4173: closure[off++] = p;
4174: closure[off++] = ornt;
4175: for (t = 0; t < tmpSize; ++t) {
4176: DMPolytopeType ft;
4178: PetscCall(DMPlexGetCellType(dm, tmp[t], &ft));
4179: closure[off++] = tmp[arr[t]];
4180: closure[off++] = tmpO ? DMPolytopeTypeComposeOrientation(ft, ornt, tmpO[t]) : 0;
4181: }
4182: }
4183: PetscCall(DMPlexRestoreTransitiveClosure_Hot_Private(dm, p, useCone, &tmpSize, &tmp, &tmpO));
4184: if (numPoints) *numPoints = tmpSize + 1;
4185: if (points) *points = closure;
4186: PetscFunctionReturn(PETSC_SUCCESS);
4187: }
4189: /* We need a special tensor version because we want to allow duplicate points in the endcaps for hybrid cells */
4190: static PetscErrorCode DMPlexTransitiveClosure_Tensor_Internal(DM dm, PetscInt point, DMPolytopeType ct, PetscInt o, PetscBool useCone, PetscInt *numPoints, PetscInt **points)
4191: {
4192: const PetscInt *arr = DMPolytopeTypeGetArrangement(ct, o);
4193: const PetscInt *cone, *ornt;
4194: PetscInt *pts, *closure = NULL;
4195: DMPolytopeType ft;
4196: PetscInt maxConeSize, maxSupportSize, coneSeries, supportSeries, maxSize;
4197: PetscInt dim, coneSize, c, d, clSize, cl;
4199: PetscFunctionBeginHot;
4200: PetscCall(DMGetDimension(dm, &dim));
4201: PetscCall(DMPlexGetTransitiveClosure_Hot_Private(dm, point, PETSC_TRUE, &coneSize, &cone, &ornt));
4202: PetscCall(DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize));
4203: coneSeries = (maxConeSize > 1) ? ((PetscPowInt(maxConeSize, dim + 1) - 1) / (maxConeSize - 1)) : dim + 1;
4204: supportSeries = (maxSupportSize > 1) ? ((PetscPowInt(maxSupportSize, dim + 1) - 1) / (maxSupportSize - 1)) : dim + 1;
4205: maxSize = PetscMax(coneSeries, supportSeries);
4206: if (*points) {
4207: pts = *points;
4208: } else PetscCall(DMGetWorkArray(dm, 2 * maxSize, MPIU_INT, &pts));
4209: c = 0;
4210: pts[c++] = point;
4211: pts[c++] = o;
4212: PetscCall(DMPlexGetCellType(dm, cone[arr[0 * 2 + 0]], &ft));
4213: PetscCall(DMPlexGetTransitiveClosure_Internal(dm, cone[arr[0 * 2 + 0]], DMPolytopeTypeComposeOrientation(ft, arr[0 * 2 + 1], ornt[0]), useCone, &clSize, &closure));
4214: for (cl = 0; cl < clSize * 2; cl += 2) {
4215: pts[c++] = closure[cl];
4216: pts[c++] = closure[cl + 1];
4217: }
4218: PetscCall(DMPlexGetTransitiveClosure_Internal(dm, cone[arr[1 * 2 + 0]], DMPolytopeTypeComposeOrientation(ft, arr[1 * 2 + 1], ornt[1]), useCone, &clSize, &closure));
4219: for (cl = 0; cl < clSize * 2; cl += 2) {
4220: pts[c++] = closure[cl];
4221: pts[c++] = closure[cl + 1];
4222: }
4223: PetscCall(DMPlexRestoreTransitiveClosure(dm, cone[0], useCone, &clSize, &closure));
4224: for (d = 2; d < coneSize; ++d) {
4225: PetscCall(DMPlexGetCellType(dm, cone[arr[d * 2 + 0]], &ft));
4226: pts[c++] = cone[arr[d * 2 + 0]];
4227: pts[c++] = DMPolytopeTypeComposeOrientation(ft, arr[d * 2 + 1], ornt[d]);
4228: }
4229: PetscCall(DMPlexRestoreTransitiveClosure_Hot_Private(dm, point, PETSC_TRUE, &coneSize, &cone, &ornt));
4230: if (dim >= 3) {
4231: for (d = 2; d < coneSize; ++d) {
4232: const PetscInt fpoint = cone[arr[d * 2 + 0]];
4233: const PetscInt *fcone, *fornt;
4234: PetscInt fconeSize, fc, i;
4236: PetscCall(DMPlexGetCellType(dm, fpoint, &ft));
4237: const PetscInt *farr = DMPolytopeTypeGetArrangement(ft, DMPolytopeTypeComposeOrientation(ft, arr[d * 2 + 1], ornt[d]));
4238: PetscCall(DMPlexGetTransitiveClosure_Hot_Private(dm, fpoint, PETSC_TRUE, &fconeSize, &fcone, &fornt));
4239: for (fc = 0; fc < fconeSize; ++fc) {
4240: const PetscInt cp = fcone[farr[fc * 2 + 0]];
4241: const PetscInt co = farr[fc * 2 + 1];
4243: for (i = 0; i < c; i += 2)
4244: if (pts[i] == cp) break;
4245: if (i == c) {
4246: PetscCall(DMPlexGetCellType(dm, cp, &ft));
4247: pts[c++] = cp;
4248: pts[c++] = DMPolytopeTypeComposeOrientation(ft, co, fornt[farr[fc * 2 + 0]]);
4249: }
4250: }
4251: PetscCall(DMPlexRestoreTransitiveClosure_Hot_Private(dm, fpoint, PETSC_TRUE, &fconeSize, &fcone, &fornt));
4252: }
4253: }
4254: *numPoints = c / 2;
4255: *points = pts;
4256: PetscFunctionReturn(PETSC_SUCCESS);
4257: }
4259: PetscErrorCode DMPlexGetTransitiveClosure_Internal(DM dm, PetscInt p, PetscInt ornt, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
4260: {
4261: DMPolytopeType ct;
4262: PetscInt *closure, *fifo;
4263: PetscInt closureSize = 0, fifoStart = 0, fifoSize = 0;
4264: PetscInt maxConeSize, maxSupportSize, coneSeries, supportSeries;
4265: PetscInt depth, maxSize;
4267: PetscFunctionBeginHot;
4268: PetscCall(DMPlexGetDepth(dm, &depth));
4269: if (depth == 1) {
4270: PetscCall(DMPlexGetTransitiveClosure_Depth1_Private(dm, p, ornt, useCone, numPoints, points));
4271: PetscFunctionReturn(PETSC_SUCCESS);
4272: }
4273: PetscCall(DMPlexGetCellType(dm, p, &ct));
4274: if (ct == DM_POLYTOPE_FV_GHOST || ct == DM_POLYTOPE_INTERIOR_GHOST || ct == DM_POLYTOPE_UNKNOWN || ct == DM_POLYTOPE_UNKNOWN_CELL || ct == DM_POLYTOPE_UNKNOWN_FACE) ct = DM_POLYTOPE_UNKNOWN;
4275: if (DMPolytopeTypeIsHybrid(ct) && ct != DM_POLYTOPE_POINT_PRISM_TENSOR) {
4276: PetscCall(DMPlexTransitiveClosure_Tensor_Internal(dm, p, ct, ornt, useCone, numPoints, points));
4277: PetscFunctionReturn(PETSC_SUCCESS);
4278: }
4279: PetscCall(DMPlexGetMaxSizes(dm, &maxConeSize, &maxSupportSize));
4280: coneSeries = (maxConeSize > 1) ? ((PetscPowInt(maxConeSize, depth + 1) - 1) / (maxConeSize - 1)) : depth + 1;
4281: supportSeries = (maxSupportSize > 1) ? ((PetscPowInt(maxSupportSize, depth + 1) - 1) / (maxSupportSize - 1)) : depth + 1;
4282: maxSize = PetscMax(coneSeries, supportSeries);
4283: PetscCall(DMGetWorkArray(dm, 3 * maxSize, MPIU_INT, &fifo));
4284: if (*points) {
4285: closure = *points;
4286: } else PetscCall(DMGetWorkArray(dm, 2 * maxSize, MPIU_INT, &closure));
4287: closure[closureSize++] = p;
4288: closure[closureSize++] = ornt;
4289: fifo[fifoSize++] = p;
4290: fifo[fifoSize++] = ornt;
4291: fifo[fifoSize++] = ct;
4292: /* Should kick out early when depth is reached, rather than checking all vertices for empty cones */
4293: while (fifoSize - fifoStart) {
4294: const PetscInt q = fifo[fifoStart++];
4295: const PetscInt o = fifo[fifoStart++];
4296: const DMPolytopeType qt = (DMPolytopeType)fifo[fifoStart++];
4297: const PetscInt *qarr = DMPolytopeTypeGetArrangement(qt, o);
4298: const PetscInt *tmp, *tmpO = NULL;
4299: PetscInt tmpSize;
4301: if (PetscDefined(USE_DEBUG)) {
4302: PetscInt nO = DMPolytopeTypeGetNumArrangements(qt) / 2;
4303: PetscCheck(!o || !(o >= nO || o < -nO), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid orientation %" PetscInt_FMT " not in [%" PetscInt_FMT ",%" PetscInt_FMT ") for %s %" PetscInt_FMT, o, -nO, nO, DMPolytopeTypes[qt], q);
4304: }
4305: PetscCall(DMPlexGetTransitiveClosure_Hot_Private(dm, q, useCone, &tmpSize, &tmp, &tmpO));
4306: for (PetscInt t = 0; t < tmpSize; ++t) {
4307: const PetscInt ip = useCone && qarr ? qarr[t * 2] : t;
4308: const PetscInt io = useCone && qarr ? qarr[t * 2 + 1] : 0;
4309: const PetscInt cp = tmp[ip];
4310: PetscCall(DMPlexGetCellType(dm, cp, &ct));
4311: const PetscInt co = tmpO ? DMPolytopeTypeComposeOrientation(ct, io, tmpO[ip]) : 0;
4312: PetscInt c;
4314: /* Check for duplicate */
4315: for (c = 0; c < closureSize; c += 2) {
4316: if (closure[c] == cp) break;
4317: }
4318: if (c == closureSize) {
4319: closure[closureSize++] = cp;
4320: closure[closureSize++] = co;
4321: fifo[fifoSize++] = cp;
4322: fifo[fifoSize++] = co;
4323: fifo[fifoSize++] = ct;
4324: }
4325: }
4326: PetscCall(DMPlexRestoreTransitiveClosure_Hot_Private(dm, q, useCone, &tmpSize, &tmp, &tmpO));
4327: }
4328: PetscCall(DMRestoreWorkArray(dm, 3 * maxSize, MPIU_INT, &fifo));
4329: if (numPoints) *numPoints = closureSize / 2;
4330: if (points) *points = closure;
4331: PetscFunctionReturn(PETSC_SUCCESS);
4332: }
4334: /*@C
4335: DMPlexGetTransitiveClosure - Return the points on the transitive closure of the in-edges or out-edges for this point in the DAG
4337: Not Collective
4339: Input Parameters:
4340: + dm - The `DMPLEX`
4341: . p - The mesh point
4342: - useCone - `PETSC_TRUE` for the closure, otherwise return the support
4344: Input/Output Parameter:
4345: . points - The points and point orientations, interleaved as pairs [p0, o0, p1, o1, ...];
4346: if *points is `NULL` on input, internal storage will be returned, use `DMPlexRestoreTransitiveClosure()`,
4347: otherwise the provided array is used to hold the values
4349: Output Parameter:
4350: . numPoints - The number of points in the closure, so `points` is of size 2*`numPoints`
4352: Level: beginner
4354: Note:
4355: If using internal storage (points is `NULL` on input), each call overwrites the last output.
4357: Fortran Notes:
4358: `points` must be declared with
4359: .vb
4360: PetscInt, pointer :: points(:)
4361: .ve
4362: and is always allocated by the function.
4364: Pass `PETSC_NULL_INTEGER` for `numPoints` if it is not needed
4366: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexRestoreTransitiveClosure()`, `DMPlexCreate()`, `DMPlexSetCone()`, `DMPlexSetChart()`, `DMPlexGetCone()`
4367: @*/
4368: PetscErrorCode DMPlexGetTransitiveClosure(DM dm, PetscInt p, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
4369: {
4370: PetscFunctionBeginHot;
4372: if (numPoints) PetscAssertPointer(numPoints, 4);
4373: if (points) PetscAssertPointer(points, 5);
4374: if (PetscDefined(USE_DEBUG)) {
4375: PetscInt pStart, pEnd;
4376: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
4377: PetscCheck(p >= pStart && p < pEnd, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Point %" PetscInt_FMT " is not in [%" PetscInt_FMT ", %" PetscInt_FMT ")", p, pStart, pEnd);
4378: }
4379: PetscCall(DMPlexGetTransitiveClosure_Internal(dm, p, 0, useCone, numPoints, points));
4380: PetscFunctionReturn(PETSC_SUCCESS);
4381: }
4383: /*@C
4384: DMPlexRestoreTransitiveClosure - Restore the array of points on the transitive closure of the in-edges or out-edges for this point in the DAG
4386: Not Collective
4388: Input Parameters:
4389: + dm - The `DMPLEX`
4390: . p - The mesh point
4391: . useCone - `PETSC_TRUE` for the closure, otherwise return the star
4392: . numPoints - The number of points in the closure, so points[] is of size 2*`numPoints`
4393: - points - The points and point orientations, interleaved as pairs [p0, o0, p1, o1, ...]
4395: Level: beginner
4397: Note:
4398: If not using internal storage (points is not `NULL` on input), this call is unnecessary
4400: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetTransitiveClosure()`, `DMPlexCreate()`, `DMPlexSetCone()`, `DMPlexSetChart()`, `DMPlexGetCone()`
4401: @*/
4402: PetscErrorCode DMPlexRestoreTransitiveClosure(DM dm, PetscInt p, PetscBool useCone, PetscInt *numPoints, PetscInt *points[])
4403: {
4404: PetscFunctionBeginHot;
4406: if (numPoints) *numPoints = 0;
4407: PetscCall(DMRestoreWorkArray(dm, 0, MPIU_INT, points));
4408: PetscFunctionReturn(PETSC_SUCCESS);
4409: }
4411: /*@
4412: DMPlexGetMaxSizes - Return the maximum number of in-edges (cone) and out-edges (support) for any point in the DAG
4414: Not Collective
4416: Input Parameter:
4417: . dm - The `DMPLEX`
4419: Output Parameters:
4420: + maxConeSize - The maximum number of in-edges
4421: - maxSupportSize - The maximum number of out-edges
4423: Level: beginner
4425: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexSetConeSize()`, `DMPlexSetChart()`
4426: @*/
4427: PetscErrorCode DMPlexGetMaxSizes(DM dm, PeOp PetscInt *maxConeSize, PeOp PetscInt *maxSupportSize)
4428: {
4429: DM_Plex *mesh = (DM_Plex *)dm->data;
4431: PetscFunctionBegin;
4433: if (maxConeSize) PetscCall(PetscSectionGetMaxDof(mesh->coneSection, maxConeSize));
4434: if (maxSupportSize) PetscCall(PetscSectionGetMaxDof(mesh->supportSection, maxSupportSize));
4435: PetscFunctionReturn(PETSC_SUCCESS);
4436: }
4438: PetscErrorCode DMSetUp_Plex(DM dm)
4439: {
4440: DM_Plex *mesh = (DM_Plex *)dm->data;
4441: PetscInt size, maxSupportSize;
4443: PetscFunctionBegin;
4445: PetscCall(PetscSectionSetUp(mesh->coneSection));
4446: PetscCall(PetscSectionGetStorageSize(mesh->coneSection, &size));
4447: PetscCall(PetscMalloc1(size, &mesh->cones));
4448: PetscCall(PetscCalloc1(size, &mesh->coneOrientations));
4449: PetscCall(PetscSectionGetMaxDof(mesh->supportSection, &maxSupportSize));
4450: if (maxSupportSize) {
4451: PetscCall(PetscSectionSetUp(mesh->supportSection));
4452: PetscCall(PetscSectionGetStorageSize(mesh->supportSection, &size));
4453: PetscCall(PetscMalloc1(size, &mesh->supports));
4454: }
4455: PetscFunctionReturn(PETSC_SUCCESS);
4456: }
4458: PetscErrorCode DMCreateSubDM_Plex(DM dm, PetscInt numFields, const PetscInt fields[], IS *is, DM *subdm)
4459: {
4460: PetscFunctionBegin;
4461: if (subdm) PetscCall(DMClone(dm, subdm));
4462: PetscCall(DMCreateSectionSubDM(dm, numFields, fields, NULL, NULL, is, subdm));
4463: if (subdm) (*subdm)->useNatural = dm->useNatural;
4464: if (dm->useNatural && dm->sfMigration) {
4465: PetscSF sfNatural;
4467: (*subdm)->sfMigration = dm->sfMigration;
4468: PetscCall(PetscObjectReference((PetscObject)dm->sfMigration));
4469: PetscCall(DMPlexCreateGlobalToNaturalSF(*subdm, NULL, (*subdm)->sfMigration, &sfNatural));
4470: (*subdm)->sfNatural = sfNatural;
4471: }
4472: PetscFunctionReturn(PETSC_SUCCESS);
4473: }
4475: PetscErrorCode DMCreateSuperDM_Plex(DM dms[], PetscInt len, IS **is, DM *superdm)
4476: {
4477: PetscInt i = 0;
4479: PetscFunctionBegin;
4480: PetscCall(DMClone(dms[0], superdm));
4481: PetscCall(DMCreateSectionSuperDM(dms, len, is, superdm));
4482: (*superdm)->useNatural = PETSC_FALSE;
4483: for (i = 0; i < len; i++) {
4484: if (dms[i]->useNatural && dms[i]->sfMigration) {
4485: PetscSF sfNatural;
4487: (*superdm)->sfMigration = dms[i]->sfMigration;
4488: PetscCall(PetscObjectReference((PetscObject)dms[i]->sfMigration));
4489: (*superdm)->useNatural = PETSC_TRUE;
4490: PetscCall(DMPlexCreateGlobalToNaturalSF(*superdm, NULL, (*superdm)->sfMigration, &sfNatural));
4491: (*superdm)->sfNatural = sfNatural;
4492: break;
4493: }
4494: }
4495: PetscFunctionReturn(PETSC_SUCCESS);
4496: }
4498: /*@
4499: DMPlexSymmetrize - Create support (out-edge) information from cone (in-edge) information
4501: Not Collective
4503: Input Parameter:
4504: . dm - The `DMPLEX`
4506: Level: beginner
4508: Note:
4509: This should be called after all calls to `DMPlexSetCone()`
4511: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexSetChart()`, `DMPlexSetConeSize()`, `DMPlexSetCone()`
4512: @*/
4513: PetscErrorCode DMPlexSymmetrize(DM dm)
4514: {
4515: DM_Plex *mesh = (DM_Plex *)dm->data;
4516: PetscInt *offsets;
4517: PetscInt supportSize;
4518: PetscInt pStart, pEnd, p;
4520: PetscFunctionBegin;
4522: PetscCheck(!mesh->supports, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "Supports were already setup in this DMPlex");
4523: PetscCall(PetscLogEventBegin(DMPLEX_Symmetrize, dm, 0, 0, 0));
4524: /* Calculate support sizes */
4525: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
4526: for (p = pStart; p < pEnd; ++p) {
4527: PetscInt dof, off, c;
4529: PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
4530: PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
4531: for (c = off; c < off + dof; ++c) PetscCall(PetscSectionAddDof(mesh->supportSection, mesh->cones[c], 1));
4532: }
4533: PetscCall(PetscSectionSetUp(mesh->supportSection));
4534: /* Calculate supports */
4535: PetscCall(PetscSectionGetStorageSize(mesh->supportSection, &supportSize));
4536: PetscCall(PetscMalloc1(supportSize, &mesh->supports));
4537: PetscCall(PetscCalloc1(pEnd - pStart, &offsets));
4538: for (p = pStart; p < pEnd; ++p) {
4539: PetscInt dof, off, c;
4541: PetscCall(PetscSectionGetDof(mesh->coneSection, p, &dof));
4542: PetscCall(PetscSectionGetOffset(mesh->coneSection, p, &off));
4543: for (c = off; c < off + dof; ++c) {
4544: const PetscInt q = mesh->cones[c];
4545: PetscInt offS;
4547: PetscCall(PetscSectionGetOffset(mesh->supportSection, q, &offS));
4549: mesh->supports[offS + offsets[q]] = p;
4550: ++offsets[q];
4551: }
4552: }
4553: PetscCall(PetscFree(offsets));
4554: PetscCall(PetscLogEventEnd(DMPLEX_Symmetrize, dm, 0, 0, 0));
4555: PetscFunctionReturn(PETSC_SUCCESS);
4556: }
4558: static PetscErrorCode DMPlexCreateDepthStratum(DM dm, DMLabel label, PetscInt depth, PetscInt pStart, PetscInt pEnd)
4559: {
4560: IS stratumIS;
4562: PetscFunctionBegin;
4563: if (pStart >= pEnd) PetscFunctionReturn(PETSC_SUCCESS);
4564: if (PetscDefined(USE_DEBUG)) {
4565: PetscInt qStart, qEnd, numLevels, level;
4566: PetscBool overlap = PETSC_FALSE;
4567: PetscCall(DMLabelGetNumValues(label, &numLevels));
4568: for (level = 0; level < numLevels; level++) {
4569: PetscCall(DMLabelGetStratumBounds(label, level, &qStart, &qEnd));
4570: if ((pStart >= qStart && pStart < qEnd) || (pEnd > qStart && pEnd <= qEnd)) {
4571: overlap = PETSC_TRUE;
4572: break;
4573: }
4574: }
4575: PetscCheck(!overlap, PETSC_COMM_SELF, PETSC_ERR_PLIB, "New depth %" PetscInt_FMT " range [%" PetscInt_FMT ",%" PetscInt_FMT ") overlaps with depth %" PetscInt_FMT " range [%" PetscInt_FMT ",%" PetscInt_FMT ")", depth, pStart, pEnd, level, qStart, qEnd);
4576: }
4577: PetscCall(ISCreateStride(PETSC_COMM_SELF, pEnd - pStart, pStart, 1, &stratumIS));
4578: PetscCall(DMLabelSetStratumIS(label, depth, stratumIS));
4579: PetscCall(ISDestroy(&stratumIS));
4580: PetscFunctionReturn(PETSC_SUCCESS);
4581: }
4583: static PetscErrorCode DMPlexStratify_CellType_Private(DM dm, DMLabel label)
4584: {
4585: PetscInt *pMin, *pMax;
4586: PetscInt pStart, pEnd;
4587: PetscInt dmin = PETSC_INT_MAX, dmax = PETSC_INT_MIN;
4589: PetscFunctionBegin;
4590: {
4591: DMLabel label2;
4593: PetscCall(DMPlexGetCellTypeLabel(dm, &label2));
4594: PetscCall(PetscObjectViewFromOptions((PetscObject)label2, NULL, "-ct_view"));
4595: }
4596: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
4597: for (PetscInt p = pStart; p < pEnd; ++p) {
4598: DMPolytopeType ct;
4600: PetscCall(DMPlexGetCellType(dm, p, &ct));
4601: dmin = PetscMin(DMPolytopeTypeGetDim(ct), dmin);
4602: dmax = PetscMax(DMPolytopeTypeGetDim(ct), dmax);
4603: }
4604: PetscCall(PetscMalloc2(dmax + 1, &pMin, dmax + 1, &pMax));
4605: for (PetscInt d = dmin; d <= dmax; ++d) {
4606: pMin[d] = PETSC_INT_MAX;
4607: pMax[d] = PETSC_INT_MIN;
4608: }
4609: for (PetscInt p = pStart; p < pEnd; ++p) {
4610: DMPolytopeType ct;
4611: PetscInt d;
4613: PetscCall(DMPlexGetCellType(dm, p, &ct));
4614: d = DMPolytopeTypeGetDim(ct);
4615: pMin[d] = PetscMin(p, pMin[d]);
4616: pMax[d] = PetscMax(p, pMax[d]);
4617: }
4618: for (PetscInt d = dmin; d <= dmax; ++d) {
4619: if (pMin[d] > pMax[d]) continue;
4620: PetscCall(DMPlexCreateDepthStratum(dm, label, d, pMin[d], pMax[d] + 1));
4621: }
4622: PetscCall(PetscFree2(pMin, pMax));
4623: PetscFunctionReturn(PETSC_SUCCESS);
4624: }
4626: static PetscErrorCode DMPlexStratify_Topological_Private(DM dm, DMLabel label)
4627: {
4628: PetscInt pStart, pEnd;
4629: PetscInt numRoots = 0, numLeaves = 0;
4631: PetscFunctionBegin;
4632: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
4633: {
4634: /* Initialize roots and count leaves */
4635: PetscInt sMin = PETSC_INT_MAX;
4636: PetscInt sMax = PETSC_INT_MIN;
4637: PetscInt coneSize, supportSize;
4639: for (PetscInt p = pStart; p < pEnd; ++p) {
4640: PetscCall(DMPlexGetConeSize(dm, p, &coneSize));
4641: PetscCall(DMPlexGetSupportSize(dm, p, &supportSize));
4642: if (!coneSize && supportSize) {
4643: sMin = PetscMin(p, sMin);
4644: sMax = PetscMax(p, sMax);
4645: ++numRoots;
4646: } else if (!supportSize && coneSize) {
4647: ++numLeaves;
4648: } else if (!supportSize && !coneSize) {
4649: /* Isolated points */
4650: sMin = PetscMin(p, sMin);
4651: sMax = PetscMax(p, sMax);
4652: }
4653: }
4654: PetscCall(DMPlexCreateDepthStratum(dm, label, 0, sMin, sMax + 1));
4655: }
4657: if (numRoots + numLeaves == (pEnd - pStart)) {
4658: PetscInt sMin = PETSC_INT_MAX;
4659: PetscInt sMax = PETSC_INT_MIN;
4660: PetscInt coneSize, supportSize;
4662: for (PetscInt p = pStart; p < pEnd; ++p) {
4663: PetscCall(DMPlexGetConeSize(dm, p, &coneSize));
4664: PetscCall(DMPlexGetSupportSize(dm, p, &supportSize));
4665: if (!supportSize && coneSize) {
4666: sMin = PetscMin(p, sMin);
4667: sMax = PetscMax(p, sMax);
4668: }
4669: }
4670: PetscCall(DMPlexCreateDepthStratum(dm, label, 1, sMin, sMax + 1));
4671: } else {
4672: PetscInt level = 0;
4673: PetscInt qStart, qEnd;
4675: PetscCall(DMLabelGetStratumBounds(label, level, &qStart, &qEnd));
4676: while (qEnd > qStart) {
4677: PetscInt sMin = PETSC_INT_MAX;
4678: PetscInt sMax = PETSC_INT_MIN;
4680: for (PetscInt q = qStart; q < qEnd; ++q) {
4681: const PetscInt *support;
4682: PetscInt supportSize;
4684: PetscCall(DMPlexGetSupportSize(dm, q, &supportSize));
4685: PetscCall(DMPlexGetSupport(dm, q, &support));
4686: for (PetscInt s = 0; s < supportSize; ++s) {
4687: sMin = PetscMin(support[s], sMin);
4688: sMax = PetscMax(support[s], sMax);
4689: }
4690: }
4691: PetscCall(DMLabelGetNumValues(label, &level));
4692: PetscCall(DMPlexCreateDepthStratum(dm, label, level, sMin, sMax + 1));
4693: PetscCall(DMLabelGetStratumBounds(label, level, &qStart, &qEnd));
4694: }
4695: }
4696: PetscFunctionReturn(PETSC_SUCCESS);
4697: }
4699: /*@
4700: DMPlexStratify - Computes the strata for all points in the `DMPLEX`
4702: Collective
4704: Input Parameter:
4705: . dm - The `DMPLEX`
4707: Level: beginner
4709: Notes:
4710: The strata group all points of the same grade, and this function calculates the strata. This
4711: grade can be seen as the height (or depth) of the point in the DAG.
4713: The DAG for most topologies is a graded poset (https://en.wikipedia.org/wiki/Graded_poset), and
4714: can be illustrated by a Hasse Diagram (https://en.wikipedia.org/wiki/Hasse_diagram).
4715: Concretely, `DMPlexStratify()` creates a new label named "depth" containing the depth in the DAG of each point. For cell-vertex
4716: meshes, vertices are depth 0 and cells are depth 1. For fully interpolated meshes, depth 0 for vertices, 1 for edges, and so on
4717: until cells have depth equal to the dimension of the mesh. The depth label can be accessed through `DMPlexGetDepthLabel()` or `DMPlexGetDepthStratum()`, or
4718: manually via `DMGetLabel()`. The height is defined implicitly by height = maxDimension - depth, and can be accessed
4719: via `DMPlexGetHeightStratum()`. For example, cells have height 0 and faces have height 1.
4721: The depth of a point is calculated by executing a breadth-first search (BFS) on the DAG. This could produce surprising results
4722: if run on a partially interpolated mesh, meaning one that had some edges and faces, but not others. For example, suppose that
4723: we had a mesh consisting of one triangle (c0) and three vertices (v0, v1, v2), and only one edge is on the boundary so we choose
4724: to interpolate only that one (e0), so that
4725: .vb
4726: cone(c0) = {e0, v2}
4727: cone(e0) = {v0, v1}
4728: .ve
4729: If `DMPlexStratify()` is run on this mesh, it will give depths
4730: .vb
4731: depth 0 = {v0, v1, v2}
4732: depth 1 = {e0, c0}
4733: .ve
4734: where the triangle has been given depth 1, instead of 2, because it is reachable from vertex v2.
4736: `DMPlexStratify()` should be called after all calls to `DMPlexSymmetrize()`
4738: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexSymmetrize()`, `DMPlexComputeCellTypes()`
4739: @*/
4740: PetscErrorCode DMPlexStratify(DM dm)
4741: {
4742: DM_Plex *mesh = (DM_Plex *)dm->data;
4743: DMLabel label;
4744: PetscBool flg = PETSC_FALSE;
4746: PetscFunctionBegin;
4748: PetscCall(PetscLogEventBegin(DMPLEX_Stratify, dm, 0, 0, 0));
4750: // Create depth label
4751: PetscCall(DMRemoveLabel(dm, "depth", NULL));
4752: PetscCall(DMCreateLabel(dm, "depth"));
4753: PetscCall(DMPlexGetDepthLabel(dm, &label));
4755: PetscCall(PetscOptionsGetBool(NULL, dm->hdr.prefix, "-dm_plex_stratify_celltype", &flg, NULL));
4756: if (flg) PetscCall(DMPlexStratify_CellType_Private(dm, label));
4757: else PetscCall(DMPlexStratify_Topological_Private(dm, label));
4759: { /* just in case there is an empty process */
4760: PetscInt numValues, maxValues = 0, v;
4762: PetscCall(DMLabelGetNumValues(label, &numValues));
4763: PetscCallMPI(MPIU_Allreduce(&numValues, &maxValues, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
4764: for (v = numValues; v < maxValues; v++) PetscCall(DMLabelAddStratum(label, v));
4765: }
4766: PetscCall(PetscObjectStateGet((PetscObject)label, &mesh->depthState));
4767: PetscCall(PetscLogEventEnd(DMPLEX_Stratify, dm, 0, 0, 0));
4768: PetscFunctionReturn(PETSC_SUCCESS);
4769: }
4771: PetscErrorCode DMPlexComputeCellType_Internal(DM dm, PetscInt p, PetscInt pdepth, DMPolytopeType *pt)
4772: {
4773: DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
4774: PetscInt dim, depth, pheight, coneSize;
4775: PetscBool preferTensor;
4777: PetscFunctionBeginHot;
4778: PetscCall(DMGetDimension(dm, &dim));
4779: PetscCall(DMPlexGetDepth(dm, &depth));
4780: PetscCall(DMPlexGetConeSize(dm, p, &coneSize));
4781: PetscCall(DMPlexGetInterpolatePreferTensor(dm, &preferTensor));
4782: pheight = depth - pdepth;
4783: if (depth <= 1) {
4784: switch (pdepth) {
4785: case 0:
4786: ct = DM_POLYTOPE_POINT;
4787: break;
4788: case 1:
4789: switch (coneSize) {
4790: case 2:
4791: ct = DM_POLYTOPE_SEGMENT;
4792: break;
4793: case 3:
4794: ct = DM_POLYTOPE_TRIANGLE;
4795: break;
4796: case 4:
4797: switch (dim) {
4798: case 2:
4799: ct = DM_POLYTOPE_QUADRILATERAL;
4800: break;
4801: case 3:
4802: ct = DM_POLYTOPE_TETRAHEDRON;
4803: break;
4804: default:
4805: break;
4806: }
4807: break;
4808: case 5:
4809: ct = DM_POLYTOPE_PYRAMID;
4810: break;
4811: case 6:
4812: ct = preferTensor ? DM_POLYTOPE_TRI_PRISM_TENSOR : DM_POLYTOPE_TRI_PRISM;
4813: break;
4814: case 8:
4815: ct = DM_POLYTOPE_HEXAHEDRON;
4816: break;
4817: default:
4818: break;
4819: }
4820: }
4821: } else {
4822: if (pdepth == 0) {
4823: ct = DM_POLYTOPE_POINT;
4824: } else if (pheight == 0) {
4825: switch (dim) {
4826: case 1:
4827: switch (coneSize) {
4828: case 2:
4829: ct = DM_POLYTOPE_SEGMENT;
4830: break;
4831: default:
4832: break;
4833: }
4834: break;
4835: case 2:
4836: switch (coneSize) {
4837: case 3:
4838: ct = DM_POLYTOPE_TRIANGLE;
4839: break;
4840: case 4:
4841: ct = DM_POLYTOPE_QUADRILATERAL;
4842: break;
4843: default:
4844: break;
4845: }
4846: break;
4847: case 3:
4848: switch (coneSize) {
4849: case 4:
4850: ct = DM_POLYTOPE_TETRAHEDRON;
4851: break;
4852: case 5: {
4853: const PetscInt *cone;
4854: PetscInt faceConeSize;
4856: PetscCall(DMPlexGetCone(dm, p, &cone));
4857: PetscCall(DMPlexGetConeSize(dm, cone[0], &faceConeSize));
4858: switch (faceConeSize) {
4859: case 3:
4860: ct = preferTensor ? DM_POLYTOPE_TRI_PRISM_TENSOR : DM_POLYTOPE_TRI_PRISM;
4861: break;
4862: case 4:
4863: ct = DM_POLYTOPE_PYRAMID;
4864: break;
4865: }
4866: } break;
4867: case 6:
4868: ct = DM_POLYTOPE_HEXAHEDRON;
4869: break;
4870: default:
4871: break;
4872: }
4873: break;
4874: default:
4875: break;
4876: }
4877: } else if (pheight > 0) {
4878: switch (coneSize) {
4879: case 2:
4880: ct = DM_POLYTOPE_SEGMENT;
4881: break;
4882: case 3:
4883: ct = DM_POLYTOPE_TRIANGLE;
4884: break;
4885: case 4:
4886: ct = DM_POLYTOPE_QUADRILATERAL;
4887: break;
4888: default:
4889: break;
4890: }
4891: }
4892: }
4893: *pt = ct;
4894: PetscFunctionReturn(PETSC_SUCCESS);
4895: }
4897: /*@
4898: DMPlexComputeCellTypes - Infer the polytope type of every cell using its dimension and cone size.
4900: Collective
4902: Input Parameter:
4903: . dm - The `DMPLEX`
4905: Level: developer
4907: Note:
4908: This function is normally called automatically when a cell type is requested. It creates an
4909: internal `DMLabel` named "celltype" which can be directly accessed using `DMGetLabel()`. A user may disable
4910: automatic creation by creating the label manually, using `DMCreateLabel`(dm, "celltype").
4912: `DMPlexComputeCellTypes()` should be called after all calls to `DMPlexSymmetrize()` and `DMPlexStratify()`
4914: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreate()`, `DMPlexSymmetrize()`, `DMPlexStratify()`, `DMGetLabel()`, `DMCreateLabel()`
4915: @*/
4916: PetscErrorCode DMPlexComputeCellTypes(DM dm)
4917: {
4918: DM_Plex *mesh;
4919: DMLabel ctLabel;
4920: PetscInt pStart, pEnd, p;
4922: PetscFunctionBegin;
4924: mesh = (DM_Plex *)dm->data;
4925: PetscCall(DMCreateLabel(dm, "celltype"));
4926: PetscCall(DMPlexGetCellTypeLabel(dm, &ctLabel));
4927: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
4928: PetscCall(PetscFree(mesh->cellTypes));
4929: PetscCall(PetscMalloc1(pEnd - pStart, &mesh->cellTypes));
4930: for (p = pStart; p < pEnd; ++p) {
4931: DMPolytopeType ct = DM_POLYTOPE_UNKNOWN;
4932: PetscInt pdepth;
4934: PetscCall(DMPlexGetPointDepth(dm, p, &pdepth));
4935: PetscCall(DMPlexComputeCellType_Internal(dm, p, pdepth, &ct));
4936: PetscCheck(ct != DM_POLYTOPE_UNKNOWN && ct != DM_POLYTOPE_UNKNOWN_CELL && ct != DM_POLYTOPE_UNKNOWN_FACE, PETSC_COMM_SELF, PETSC_ERR_SUP, "Point %" PetscInt_FMT " has invalid celltype (%s)", p, DMPolytopeTypes[ct]);
4937: PetscCall(DMLabelSetValue(ctLabel, p, ct));
4938: mesh->cellTypes[p - pStart].value_as_uint8 = (uint8_t)ct;
4939: }
4940: PetscCall(PetscObjectStateGet((PetscObject)ctLabel, &mesh->celltypeState));
4941: PetscCall(PetscObjectViewFromOptions((PetscObject)ctLabel, NULL, "-dm_plex_celltypes_view"));
4942: PetscFunctionReturn(PETSC_SUCCESS);
4943: }
4945: /*@C
4946: DMPlexGetJoin - Get an array for the join of the set of points
4948: Not Collective
4950: Input Parameters:
4951: + dm - The `DMPLEX` object
4952: . numPoints - The number of input points for the join
4953: - points - The input points
4955: Output Parameters:
4956: + numCoveredPoints - The number of points in the join
4957: - coveredPoints - The points in the join
4959: Level: intermediate
4961: Note:
4962: Currently, this is restricted to a single level join
4964: Fortran Notes:
4965: `converedPoints` must be declared with
4966: .vb
4967: PetscInt, pointer :: coveredPints(:)
4968: .ve
4970: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexRestoreJoin()`, `DMPlexGetMeet()`
4971: @*/
4972: PetscErrorCode DMPlexGetJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt *coveredPoints[])
4973: {
4974: DM_Plex *mesh = (DM_Plex *)dm->data;
4975: PetscInt *join[2];
4976: PetscInt joinSize, i = 0;
4977: PetscInt dof, off, p, c, m;
4978: PetscInt maxSupportSize;
4980: PetscFunctionBegin;
4982: PetscAssertPointer(points, 3);
4983: PetscAssertPointer(numCoveredPoints, 4);
4984: PetscAssertPointer(coveredPoints, 5);
4985: PetscCall(PetscSectionGetMaxDof(mesh->supportSection, &maxSupportSize));
4986: PetscCall(DMGetWorkArray(dm, maxSupportSize, MPIU_INT, &join[0]));
4987: PetscCall(DMGetWorkArray(dm, maxSupportSize, MPIU_INT, &join[1]));
4988: /* Copy in support of first point */
4989: PetscCall(PetscSectionGetDof(mesh->supportSection, points[0], &dof));
4990: PetscCall(PetscSectionGetOffset(mesh->supportSection, points[0], &off));
4991: for (joinSize = 0; joinSize < dof; ++joinSize) join[i][joinSize] = mesh->supports[off + joinSize];
4992: /* Check each successive support */
4993: for (p = 1; p < numPoints; ++p) {
4994: PetscInt newJoinSize = 0;
4996: PetscCall(PetscSectionGetDof(mesh->supportSection, points[p], &dof));
4997: PetscCall(PetscSectionGetOffset(mesh->supportSection, points[p], &off));
4998: for (c = 0; c < dof; ++c) {
4999: const PetscInt point = mesh->supports[off + c];
5001: for (m = 0; m < joinSize; ++m) {
5002: if (point == join[i][m]) {
5003: join[1 - i][newJoinSize++] = point;
5004: break;
5005: }
5006: }
5007: }
5008: joinSize = newJoinSize;
5009: i = 1 - i;
5010: }
5011: *numCoveredPoints = joinSize;
5012: *coveredPoints = join[i];
5013: PetscCall(DMRestoreWorkArray(dm, maxSupportSize, MPIU_INT, &join[1 - i]));
5014: PetscFunctionReturn(PETSC_SUCCESS);
5015: }
5017: /*@C
5018: DMPlexRestoreJoin - Restore an array for the join of the set of points obtained with `DMPlexGetJoin()`
5020: Not Collective
5022: Input Parameters:
5023: + dm - The `DMPLEX` object
5024: . numPoints - The number of input points for the join
5025: - points - The input points
5027: Output Parameters:
5028: + numCoveredPoints - The number of points in the join
5029: - coveredPoints - The points in the join
5031: Level: intermediate
5033: Fortran Notes:
5034: `converedPoints` must be declared with
5035: .vb
5036: PetscInt, pointer :: coveredPoints(:)
5037: .ve
5039: Pass `PETSC_NULL_INTEGER` for `numCoveredPoints` if it is not needed
5041: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetJoin()`, `DMPlexGetFullJoin()`, `DMPlexGetMeet()`
5042: @*/
5043: PetscErrorCode DMPlexRestoreJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt *coveredPoints[])
5044: {
5045: PetscFunctionBegin;
5047: if (points) PetscAssertPointer(points, 3);
5048: if (numCoveredPoints) PetscAssertPointer(numCoveredPoints, 4);
5049: PetscAssertPointer(coveredPoints, 5);
5050: PetscCall(DMRestoreWorkArray(dm, 0, MPIU_INT, (void *)coveredPoints));
5051: if (numCoveredPoints) *numCoveredPoints = 0;
5052: PetscFunctionReturn(PETSC_SUCCESS);
5053: }
5055: /*@C
5056: DMPlexGetFullJoin - Get an array for the join of the set of points
5058: Not Collective
5060: Input Parameters:
5061: + dm - The `DMPLEX` object
5062: . numPoints - The number of input points for the join
5063: - points - The input points, its length is `numPoints`
5065: Output Parameters:
5066: + numCoveredPoints - The number of points in the join
5067: - coveredPoints - The points in the join, its length is `numCoveredPoints`
5069: Level: intermediate
5071: Fortran Notes:
5072: .vb
5073: PetscInt, pointer :: coveredPints(:)
5074: .ve
5076: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetJoin()`, `DMPlexRestoreJoin()`, `DMPlexGetMeet()`
5077: @*/
5078: PetscErrorCode DMPlexGetFullJoin(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt *coveredPoints[])
5079: {
5080: PetscInt *offsets, **closures;
5081: PetscInt *join[2];
5082: PetscInt depth = 0, maxSize, joinSize = 0, i = 0;
5083: PetscInt p, d, c, m, ms;
5085: PetscFunctionBegin;
5087: PetscAssertPointer(points, 3);
5088: PetscAssertPointer(numCoveredPoints, 4);
5089: PetscAssertPointer(coveredPoints, 5);
5091: PetscCall(DMPlexGetDepth(dm, &depth));
5092: PetscCall(PetscCalloc1(numPoints, &closures));
5093: PetscCall(DMGetWorkArray(dm, numPoints * (depth + 2), MPIU_INT, &offsets));
5094: PetscCall(DMPlexGetMaxSizes(dm, NULL, &ms));
5095: maxSize = (ms > 1) ? ((PetscPowInt(ms, depth + 1) - 1) / (ms - 1)) : depth + 1;
5096: PetscCall(DMGetWorkArray(dm, maxSize, MPIU_INT, &join[0]));
5097: PetscCall(DMGetWorkArray(dm, maxSize, MPIU_INT, &join[1]));
5099: for (p = 0; p < numPoints; ++p) {
5100: PetscInt closureSize;
5102: PetscCall(DMPlexGetTransitiveClosure(dm, points[p], PETSC_FALSE, &closureSize, &closures[p]));
5104: offsets[p * (depth + 2) + 0] = 0;
5105: for (d = 0; d < depth + 1; ++d) {
5106: PetscInt pStart, pEnd, i;
5108: PetscCall(DMPlexGetDepthStratum(dm, d, &pStart, &pEnd));
5109: for (i = offsets[p * (depth + 2) + d]; i < closureSize; ++i) {
5110: if ((pStart > closures[p][i * 2]) || (pEnd <= closures[p][i * 2])) {
5111: offsets[p * (depth + 2) + d + 1] = i;
5112: break;
5113: }
5114: }
5115: if (i == closureSize) offsets[p * (depth + 2) + d + 1] = i;
5116: }
5117: PetscCheck(offsets[p * (depth + 2) + depth + 1] == closureSize, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Total size of closure %" PetscInt_FMT " should be %" PetscInt_FMT, offsets[p * (depth + 2) + depth + 1], closureSize);
5118: }
5119: for (d = 0; d < depth + 1; ++d) {
5120: PetscInt dof;
5122: /* Copy in support of first point */
5123: dof = offsets[d + 1] - offsets[d];
5124: for (joinSize = 0; joinSize < dof; ++joinSize) join[i][joinSize] = closures[0][(offsets[d] + joinSize) * 2];
5125: /* Check each successive cone */
5126: for (p = 1; p < numPoints && joinSize; ++p) {
5127: PetscInt newJoinSize = 0;
5129: dof = offsets[p * (depth + 2) + d + 1] - offsets[p * (depth + 2) + d];
5130: for (c = 0; c < dof; ++c) {
5131: const PetscInt point = closures[p][(offsets[p * (depth + 2) + d] + c) * 2];
5133: for (m = 0; m < joinSize; ++m) {
5134: if (point == join[i][m]) {
5135: join[1 - i][newJoinSize++] = point;
5136: break;
5137: }
5138: }
5139: }
5140: joinSize = newJoinSize;
5141: i = 1 - i;
5142: }
5143: if (joinSize) break;
5144: }
5145: *numCoveredPoints = joinSize;
5146: *coveredPoints = join[i];
5147: for (p = 0; p < numPoints; ++p) PetscCall(DMPlexRestoreTransitiveClosure(dm, points[p], PETSC_FALSE, NULL, &closures[p]));
5148: PetscCall(PetscFree(closures));
5149: PetscCall(DMRestoreWorkArray(dm, numPoints * (depth + 2), MPIU_INT, &offsets));
5150: PetscCall(DMRestoreWorkArray(dm, ms, MPIU_INT, &join[1 - i]));
5151: PetscFunctionReturn(PETSC_SUCCESS);
5152: }
5154: /*@C
5155: DMPlexGetMeet - Get an array for the meet of the set of points
5157: Not Collective
5159: Input Parameters:
5160: + dm - The `DMPLEX` object
5161: . numPoints - The number of input points for the meet
5162: - points - The input points, of length `numPoints`
5164: Output Parameters:
5165: + numCoveringPoints - The number of points in the meet
5166: - coveringPoints - The points in the meet, of length `numCoveringPoints`
5168: Level: intermediate
5170: Note:
5171: Currently, this is restricted to a single level meet
5173: Fortran Note:
5174: `coveringPoints` must be declared with
5175: .vb
5176: PetscInt, pointer :: coveringPoints(:)
5177: .ve
5179: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexRestoreMeet()`, `DMPlexGetJoin()`
5180: @*/
5181: PetscErrorCode DMPlexGetMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveringPoints, const PetscInt *coveringPoints[])
5182: {
5183: DM_Plex *mesh = (DM_Plex *)dm->data;
5184: PetscInt *meet[2];
5185: PetscInt meetSize, i = 0;
5186: PetscInt dof, off, p, c, m;
5187: PetscInt maxConeSize;
5189: PetscFunctionBegin;
5191: PetscAssertPointer(points, 3);
5192: PetscAssertPointer(numCoveringPoints, 4);
5193: PetscAssertPointer(coveringPoints, 5);
5194: PetscCall(PetscSectionGetMaxDof(mesh->coneSection, &maxConeSize));
5195: PetscCall(DMGetWorkArray(dm, maxConeSize, MPIU_INT, &meet[0]));
5196: PetscCall(DMGetWorkArray(dm, maxConeSize, MPIU_INT, &meet[1]));
5197: /* Copy in cone of first point */
5198: PetscCall(PetscSectionGetDof(mesh->coneSection, points[0], &dof));
5199: PetscCall(PetscSectionGetOffset(mesh->coneSection, points[0], &off));
5200: for (meetSize = 0; meetSize < dof; ++meetSize) meet[i][meetSize] = mesh->cones[off + meetSize];
5201: /* Check each successive cone */
5202: for (p = 1; p < numPoints; ++p) {
5203: PetscInt newMeetSize = 0;
5205: PetscCall(PetscSectionGetDof(mesh->coneSection, points[p], &dof));
5206: PetscCall(PetscSectionGetOffset(mesh->coneSection, points[p], &off));
5207: for (c = 0; c < dof; ++c) {
5208: const PetscInt point = mesh->cones[off + c];
5210: for (m = 0; m < meetSize; ++m) {
5211: if (point == meet[i][m]) {
5212: meet[1 - i][newMeetSize++] = point;
5213: break;
5214: }
5215: }
5216: }
5217: meetSize = newMeetSize;
5218: i = 1 - i;
5219: }
5220: *numCoveringPoints = meetSize;
5221: *coveringPoints = meet[i];
5222: PetscCall(DMRestoreWorkArray(dm, maxConeSize, MPIU_INT, &meet[1 - i]));
5223: PetscFunctionReturn(PETSC_SUCCESS);
5224: }
5226: /*@C
5227: DMPlexRestoreMeet - Restore an array for the meet of the set of points obtained with `DMPlexGetMeet()`
5229: Not Collective
5231: Input Parameters:
5232: + dm - The `DMPLEX` object
5233: . numPoints - The number of input points for the meet
5234: - points - The input points
5236: Output Parameters:
5237: + numCoveredPoints - The number of points in the meet
5238: - coveredPoints - The points in the meet
5240: Level: intermediate
5242: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetMeet()`, `DMPlexGetFullMeet()`, `DMPlexGetJoin()`
5243: @*/
5244: PetscErrorCode DMPlexRestoreMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt *coveredPoints[])
5245: {
5246: PetscFunctionBegin;
5248: if (points) PetscAssertPointer(points, 3);
5249: if (numCoveredPoints) PetscAssertPointer(numCoveredPoints, 4);
5250: PetscAssertPointer(coveredPoints, 5);
5251: PetscCall(DMRestoreWorkArray(dm, 0, MPIU_INT, (void *)coveredPoints));
5252: if (numCoveredPoints) *numCoveredPoints = 0;
5253: PetscFunctionReturn(PETSC_SUCCESS);
5254: }
5256: /*@C
5257: DMPlexGetFullMeet - Get an array for the meet of the set of points
5259: Not Collective
5261: Input Parameters:
5262: + dm - The `DMPLEX` object
5263: . numPoints - The number of input points for the meet
5264: - points - The input points, of length `numPoints`
5266: Output Parameters:
5267: + numCoveredPoints - The number of points in the meet
5268: - coveredPoints - The points in the meet, of length `numCoveredPoints`
5270: Level: intermediate
5272: Fortran Notes:
5273: `coveredPoints` must be declared with
5274: .vb
5275: PetscInt, pointer :: coveredPoints(:)
5276: .ve
5278: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetMeet()`, `DMPlexRestoreMeet()`, `DMPlexGetJoin()`
5279: @*/
5280: PetscErrorCode DMPlexGetFullMeet(DM dm, PetscInt numPoints, const PetscInt points[], PetscInt *numCoveredPoints, const PetscInt *coveredPoints[])
5281: {
5282: PetscInt *offsets, **closures;
5283: PetscInt *meet[2];
5284: PetscInt height = 0, maxSize, meetSize = 0, i = 0;
5285: PetscInt p, h, c, m, mc;
5287: PetscFunctionBegin;
5289: PetscAssertPointer(points, 3);
5290: PetscAssertPointer(numCoveredPoints, 4);
5291: PetscAssertPointer(coveredPoints, 5);
5293: PetscCall(DMPlexGetDepth(dm, &height));
5294: PetscCall(PetscMalloc1(numPoints, &closures));
5295: PetscCall(DMGetWorkArray(dm, numPoints * (height + 2), MPIU_INT, &offsets));
5296: PetscCall(DMPlexGetMaxSizes(dm, &mc, NULL));
5297: maxSize = (mc > 1) ? ((PetscPowInt(mc, height + 1) - 1) / (mc - 1)) : height + 1;
5298: PetscCall(DMGetWorkArray(dm, maxSize, MPIU_INT, &meet[0]));
5299: PetscCall(DMGetWorkArray(dm, maxSize, MPIU_INT, &meet[1]));
5301: for (p = 0; p < numPoints; ++p) {
5302: PetscInt closureSize;
5304: PetscCall(DMPlexGetTransitiveClosure(dm, points[p], PETSC_TRUE, &closureSize, &closures[p]));
5306: offsets[p * (height + 2) + 0] = 0;
5307: for (h = 0; h < height + 1; ++h) {
5308: PetscInt pStart, pEnd, i;
5310: PetscCall(DMPlexGetHeightStratum(dm, h, &pStart, &pEnd));
5311: for (i = offsets[p * (height + 2) + h]; i < closureSize; ++i) {
5312: if ((pStart > closures[p][i * 2]) || (pEnd <= closures[p][i * 2])) {
5313: offsets[p * (height + 2) + h + 1] = i;
5314: break;
5315: }
5316: }
5317: if (i == closureSize) offsets[p * (height + 2) + h + 1] = i;
5318: }
5319: PetscCheck(offsets[p * (height + 2) + height + 1] == closureSize, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Total size of closure %" PetscInt_FMT " should be %" PetscInt_FMT, offsets[p * (height + 2) + height + 1], closureSize);
5320: }
5321: for (h = 0; h < height + 1; ++h) {
5322: PetscInt dof;
5324: /* Copy in cone of first point */
5325: dof = offsets[h + 1] - offsets[h];
5326: for (meetSize = 0; meetSize < dof; ++meetSize) meet[i][meetSize] = closures[0][(offsets[h] + meetSize) * 2];
5327: /* Check each successive cone */
5328: for (p = 1; p < numPoints && meetSize; ++p) {
5329: PetscInt newMeetSize = 0;
5331: dof = offsets[p * (height + 2) + h + 1] - offsets[p * (height + 2) + h];
5332: for (c = 0; c < dof; ++c) {
5333: const PetscInt point = closures[p][(offsets[p * (height + 2) + h] + c) * 2];
5335: for (m = 0; m < meetSize; ++m) {
5336: if (point == meet[i][m]) {
5337: meet[1 - i][newMeetSize++] = point;
5338: break;
5339: }
5340: }
5341: }
5342: meetSize = newMeetSize;
5343: i = 1 - i;
5344: }
5345: if (meetSize) break;
5346: }
5347: *numCoveredPoints = meetSize;
5348: *coveredPoints = meet[i];
5349: for (p = 0; p < numPoints; ++p) PetscCall(DMPlexRestoreTransitiveClosure(dm, points[p], PETSC_TRUE, NULL, &closures[p]));
5350: PetscCall(PetscFree(closures));
5351: PetscCall(DMRestoreWorkArray(dm, numPoints * (height + 2), MPIU_INT, &offsets));
5352: PetscCall(DMRestoreWorkArray(dm, mc, MPIU_INT, &meet[1 - i]));
5353: PetscFunctionReturn(PETSC_SUCCESS);
5354: }
5356: /*@
5357: DMPlexEqual - Determine if two `DM` have the same topology
5359: Not Collective
5361: Input Parameters:
5362: + dmA - A `DMPLEX` object
5363: - dmB - A `DMPLEX` object
5365: Output Parameter:
5366: . equal - `PETSC_TRUE` if the topologies are identical
5368: Level: intermediate
5370: Note:
5371: We are not solving graph isomorphism, so we do not permute.
5373: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCone()`
5374: @*/
5375: PetscErrorCode DMPlexEqual(DM dmA, DM dmB, PetscBool *equal)
5376: {
5377: PetscInt depth, depthB, pStart, pEnd, pStartB, pEndB, p;
5379: PetscFunctionBegin;
5382: PetscAssertPointer(equal, 3);
5384: *equal = PETSC_FALSE;
5385: PetscCall(DMPlexGetDepth(dmA, &depth));
5386: PetscCall(DMPlexGetDepth(dmB, &depthB));
5387: if (depth != depthB) PetscFunctionReturn(PETSC_SUCCESS);
5388: PetscCall(DMPlexGetChart(dmA, &pStart, &pEnd));
5389: PetscCall(DMPlexGetChart(dmB, &pStartB, &pEndB));
5390: if ((pStart != pStartB) || (pEnd != pEndB)) PetscFunctionReturn(PETSC_SUCCESS);
5391: for (p = pStart; p < pEnd; ++p) {
5392: const PetscInt *cone, *coneB, *ornt, *orntB, *support, *supportB;
5393: PetscInt coneSize, coneSizeB, c, supportSize, supportSizeB, s;
5395: PetscCall(DMPlexGetConeSize(dmA, p, &coneSize));
5396: PetscCall(DMPlexGetCone(dmA, p, &cone));
5397: PetscCall(DMPlexGetConeOrientation(dmA, p, &ornt));
5398: PetscCall(DMPlexGetConeSize(dmB, p, &coneSizeB));
5399: PetscCall(DMPlexGetCone(dmB, p, &coneB));
5400: PetscCall(DMPlexGetConeOrientation(dmB, p, &orntB));
5401: if (coneSize != coneSizeB) PetscFunctionReturn(PETSC_SUCCESS);
5402: for (c = 0; c < coneSize; ++c) {
5403: if (cone[c] != coneB[c]) PetscFunctionReturn(PETSC_SUCCESS);
5404: if (ornt[c] != orntB[c]) PetscFunctionReturn(PETSC_SUCCESS);
5405: }
5406: PetscCall(DMPlexGetSupportSize(dmA, p, &supportSize));
5407: PetscCall(DMPlexGetSupport(dmA, p, &support));
5408: PetscCall(DMPlexGetSupportSize(dmB, p, &supportSizeB));
5409: PetscCall(DMPlexGetSupport(dmB, p, &supportB));
5410: if (supportSize != supportSizeB) PetscFunctionReturn(PETSC_SUCCESS);
5411: for (s = 0; s < supportSize; ++s) {
5412: if (support[s] != supportB[s]) PetscFunctionReturn(PETSC_SUCCESS);
5413: }
5414: }
5415: *equal = PETSC_TRUE;
5416: PetscFunctionReturn(PETSC_SUCCESS);
5417: }
5419: /*@
5420: DMPlexGetNumFaceVertices - Returns the number of vertices on a face
5422: Not Collective
5424: Input Parameters:
5425: + dm - The `DMPLEX`
5426: . cellDim - The cell dimension
5427: - numCorners - The number of vertices on a cell
5429: Output Parameter:
5430: . numFaceVertices - The number of vertices on a face
5432: Level: developer
5434: Note:
5435: Of course this can only work for a restricted set of symmetric shapes
5437: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCone()`
5438: @*/
5439: PetscErrorCode DMPlexGetNumFaceVertices(DM dm, PetscInt cellDim, PetscInt numCorners, PetscInt *numFaceVertices)
5440: {
5441: MPI_Comm comm;
5443: PetscFunctionBegin;
5444: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
5445: PetscAssertPointer(numFaceVertices, 4);
5446: switch (cellDim) {
5447: case 0:
5448: *numFaceVertices = 0;
5449: break;
5450: case 1:
5451: *numFaceVertices = 1;
5452: break;
5453: case 2:
5454: switch (numCorners) {
5455: case 3: /* triangle */
5456: *numFaceVertices = 2; /* Edge has 2 vertices */
5457: break;
5458: case 4: /* quadrilateral */
5459: *numFaceVertices = 2; /* Edge has 2 vertices */
5460: break;
5461: case 6: /* quadratic triangle, tri and quad cohesive Lagrange cells */
5462: *numFaceVertices = 3; /* Edge has 3 vertices */
5463: break;
5464: case 9: /* quadratic quadrilateral, quadratic quad cohesive Lagrange cells */
5465: *numFaceVertices = 3; /* Edge has 3 vertices */
5466: break;
5467: default:
5468: SETERRQ(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid number of face corners %" PetscInt_FMT " for dimension %" PetscInt_FMT, numCorners, cellDim);
5469: }
5470: break;
5471: case 3:
5472: switch (numCorners) {
5473: case 4: /* tetradehdron */
5474: *numFaceVertices = 3; /* Face has 3 vertices */
5475: break;
5476: case 6: /* tet cohesive cells */
5477: *numFaceVertices = 4; /* Face has 4 vertices */
5478: break;
5479: case 8: /* hexahedron */
5480: *numFaceVertices = 4; /* Face has 4 vertices */
5481: break;
5482: case 9: /* tet cohesive Lagrange cells */
5483: *numFaceVertices = 6; /* Face has 6 vertices */
5484: break;
5485: case 10: /* quadratic tetrahedron */
5486: *numFaceVertices = 6; /* Face has 6 vertices */
5487: break;
5488: case 12: /* hex cohesive Lagrange cells */
5489: *numFaceVertices = 6; /* Face has 6 vertices */
5490: break;
5491: case 18: /* quadratic tet cohesive Lagrange cells */
5492: *numFaceVertices = 6; /* Face has 6 vertices */
5493: break;
5494: case 27: /* quadratic hexahedron, quadratic hex cohesive Lagrange cells */
5495: *numFaceVertices = 9; /* Face has 9 vertices */
5496: break;
5497: default:
5498: SETERRQ(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid number of face corners %" PetscInt_FMT " for dimension %" PetscInt_FMT, numCorners, cellDim);
5499: }
5500: break;
5501: default:
5502: SETERRQ(comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid cell dimension %" PetscInt_FMT, cellDim);
5503: }
5504: PetscFunctionReturn(PETSC_SUCCESS);
5505: }
5507: /*@
5508: DMPlexGetDepthLabel - Get the `DMLabel` recording the depth of each point
5510: Not Collective
5512: Input Parameter:
5513: . dm - The `DMPLEX` object
5515: Output Parameter:
5516: . depthLabel - The `DMLabel` recording point depth
5518: Level: developer
5520: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetDepth()`, `DMPlexGetHeightStratum()`, `DMPlexGetDepthStratum()`, `DMPlexGetPointDepth()`
5521: @*/
5522: PetscErrorCode DMPlexGetDepthLabel(DM dm, DMLabel *depthLabel)
5523: {
5524: PetscFunctionBegin;
5526: PetscAssertPointer(depthLabel, 2);
5527: *depthLabel = dm->depthLabel;
5528: PetscFunctionReturn(PETSC_SUCCESS);
5529: }
5531: /*@
5532: DMPlexGetDepth - Get the depth of the DAG representing this mesh
5534: Not Collective
5536: Input Parameter:
5537: . dm - The `DMPLEX` object
5539: Output Parameter:
5540: . depth - The number of strata (breadth first levels) in the DAG
5542: Level: developer
5544: Notes:
5545: This returns maximum of point depths over all points, i.e. maximum value of the label returned by `DMPlexGetDepthLabel()`.
5547: The point depth is described more in detail in `DMPlexGetDepthStratum()`.
5549: An empty mesh gives -1.
5551: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetDepthLabel()`, `DMPlexGetDepthStratum()`, `DMPlexGetPointDepth()`, `DMPlexSymmetrize()`
5552: @*/
5553: PetscErrorCode DMPlexGetDepth(DM dm, PetscInt *depth)
5554: {
5555: DM_Plex *mesh = (DM_Plex *)dm->data;
5556: DMLabel label;
5557: PetscInt d = -1;
5559: PetscFunctionBegin;
5561: PetscAssertPointer(depth, 2);
5562: if (mesh->tr) {
5563: PetscCall(DMPlexTransformGetDepth(mesh->tr, depth));
5564: } else {
5565: PetscCall(DMPlexGetDepthLabel(dm, &label));
5566: // Allow missing depths
5567: if (label) PetscCall(DMLabelGetValueBounds(label, NULL, &d));
5568: *depth = d;
5569: }
5570: PetscFunctionReturn(PETSC_SUCCESS);
5571: }
5573: /*@
5574: DMPlexGetDepthStratum - Get the bounds [`start`, `end`) for all points at a certain depth.
5576: Not Collective
5578: Input Parameters:
5579: + dm - The `DMPLEX` object
5580: - depth - The requested depth
5582: Output Parameters:
5583: + start - The first point at this `depth`
5584: - end - One beyond the last point at this `depth`
5586: Level: developer
5588: Notes:
5589: Depth indexing is related to topological dimension. Depth stratum 0 contains the lowest topological dimension points,
5590: often "vertices". If the mesh is "interpolated" (see `DMPlexInterpolate()`), then depth stratum 1 contains the next
5591: higher dimension, e.g., "edges".
5593: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetHeightStratum()`, `DMPlexGetCellTypeStratum()`, `DMPlexGetDepth()`, `DMPlexGetDepthLabel()`, `DMPlexGetPointDepth()`, `DMPlexSymmetrize()`, `DMPlexInterpolate()`
5594: @*/
5595: PetscErrorCode DMPlexGetDepthStratum(DM dm, PetscInt depth, PeOp PetscInt *start, PeOp PetscInt *end)
5596: {
5597: DM_Plex *mesh = (DM_Plex *)dm->data;
5598: DMLabel label;
5599: PetscInt pStart, pEnd;
5601: PetscFunctionBegin;
5603: if (start) {
5604: PetscAssertPointer(start, 3);
5605: *start = 0;
5606: }
5607: if (end) {
5608: PetscAssertPointer(end, 4);
5609: *end = 0;
5610: }
5611: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
5612: if (pStart == pEnd) PetscFunctionReturn(PETSC_SUCCESS);
5613: if (depth < 0) {
5614: if (start) *start = pStart;
5615: if (end) *end = pEnd;
5616: PetscFunctionReturn(PETSC_SUCCESS);
5617: }
5618: if (mesh->tr) {
5619: PetscCall(DMPlexTransformGetDepthStratum(mesh->tr, depth, start, end));
5620: } else {
5621: PetscCall(DMPlexGetDepthLabel(dm, &label));
5622: PetscCheck(label, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "No label named depth was found");
5623: PetscCall(DMLabelGetStratumBounds(label, depth, start, end));
5624: }
5625: PetscFunctionReturn(PETSC_SUCCESS);
5626: }
5628: /*@
5629: DMPlexGetHeightStratum - Get the bounds [`start`, `end`) for all points at a certain height.
5631: Not Collective
5633: Input Parameters:
5634: + dm - The `DMPLEX` object
5635: - height - The requested height
5637: Output Parameters:
5638: + start - The first point at this `height`
5639: - end - One beyond the last point at this `height`
5641: Level: developer
5643: Notes:
5644: Height indexing is related to topological codimension. Height stratum 0 contains the highest topological dimension
5645: points, often called "cells" or "elements". If the mesh is "interpolated" (see `DMPlexInterpolate()`), then height
5646: stratum 1 contains the boundary of these "cells", often called "faces" or "facets".
5648: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetDepthStratum()`, `DMPlexGetCellTypeStratum()`, `DMPlexGetDepth()`, `DMPlexGetPointHeight()`
5649: @*/
5650: PetscErrorCode DMPlexGetHeightStratum(DM dm, PetscInt height, PeOp PetscInt *start, PeOp PetscInt *end)
5651: {
5652: DMLabel label;
5653: PetscInt depth, pStart, pEnd;
5655: PetscFunctionBegin;
5657: if (start) {
5658: PetscAssertPointer(start, 3);
5659: *start = 0;
5660: }
5661: if (end) {
5662: PetscAssertPointer(end, 4);
5663: *end = 0;
5664: }
5665: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
5666: if (pStart == pEnd) PetscFunctionReturn(PETSC_SUCCESS);
5667: if (height < 0) {
5668: if (start) *start = pStart;
5669: if (end) *end = pEnd;
5670: PetscFunctionReturn(PETSC_SUCCESS);
5671: }
5672: PetscCall(DMPlexGetDepthLabel(dm, &label));
5673: if (label) PetscCall(DMLabelGetNumValues(label, &depth));
5674: else PetscCall(DMGetDimension(dm, &depth));
5675: PetscCheck(depth >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Depth not yet computed");
5676: PetscCall(DMPlexGetDepthStratum(dm, depth - 1 - height, start, end));
5677: PetscFunctionReturn(PETSC_SUCCESS);
5678: }
5680: /*@
5681: DMPlexGetPointDepth - Get the `depth` of a given point
5683: Not Collective
5685: Input Parameters:
5686: + dm - The `DMPLEX` object
5687: - point - The point
5689: Output Parameter:
5690: . depth - The depth of the `point`
5692: Level: intermediate
5694: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellType()`, `DMPlexGetDepthLabel()`, `DMPlexGetDepth()`, `DMPlexGetPointHeight()`
5695: @*/
5696: PetscErrorCode DMPlexGetPointDepth(DM dm, PetscInt point, PetscInt *depth)
5697: {
5698: PetscFunctionBegin;
5700: PetscAssertPointer(depth, 3);
5701: PetscCall(DMLabelGetValue(dm->depthLabel, point, depth));
5702: PetscFunctionReturn(PETSC_SUCCESS);
5703: }
5705: /*@
5706: DMPlexGetPointHeight - Get the `height` of a given point
5708: Not Collective
5710: Input Parameters:
5711: + dm - The `DMPLEX` object
5712: - point - The point
5714: Output Parameter:
5715: . height - The height of the `point`
5717: Level: intermediate
5719: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellType()`, `DMPlexGetDepthLabel()`, `DMPlexGetDepth()`, `DMPlexGetPointDepth()`
5720: @*/
5721: PetscErrorCode DMPlexGetPointHeight(DM dm, PetscInt point, PetscInt *height)
5722: {
5723: PetscInt n, pDepth;
5725: PetscFunctionBegin;
5727: PetscAssertPointer(height, 3);
5728: PetscCall(DMLabelGetNumValues(dm->depthLabel, &n));
5729: PetscCall(DMLabelGetValue(dm->depthLabel, point, &pDepth));
5730: *height = n - 1 - pDepth; /* DAG depth is n-1 */
5731: PetscFunctionReturn(PETSC_SUCCESS);
5732: }
5734: /*@
5735: DMPlexGetCellTypeLabel - Get the `DMLabel` recording the polytope type of each cell
5737: Not Collective
5739: Input Parameter:
5740: . dm - The `DMPLEX` object
5742: Output Parameter:
5743: . celltypeLabel - The `DMLabel` recording cell polytope type
5745: Level: developer
5747: Note:
5748: This function will trigger automatica computation of cell types. This can be disabled by calling
5749: `DMCreateLabel`(dm, "celltype") beforehand.
5751: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellType()`, `DMPlexGetDepthLabel()`, `DMCreateLabel()`
5752: @*/
5753: PetscErrorCode DMPlexGetCellTypeLabel(DM dm, DMLabel *celltypeLabel)
5754: {
5755: PetscFunctionBegin;
5757: PetscAssertPointer(celltypeLabel, 2);
5758: if (!dm->celltypeLabel) PetscCall(DMPlexComputeCellTypes(dm));
5759: *celltypeLabel = dm->celltypeLabel;
5760: PetscFunctionReturn(PETSC_SUCCESS);
5761: }
5763: /*@
5764: DMPlexGetCellType - Get the polytope type of a given cell
5766: Not Collective
5768: Input Parameters:
5769: + dm - The `DMPLEX` object
5770: - cell - The cell
5772: Output Parameter:
5773: . celltype - The polytope type of the cell
5775: Level: intermediate
5777: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPolytopeType`, `DMPlexGetCellTypeLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetDepth()`
5778: @*/
5779: PetscErrorCode DMPlexGetCellType(DM dm, PetscInt cell, DMPolytopeType *celltype)
5780: {
5781: DM_Plex *mesh = (DM_Plex *)dm->data;
5782: DMLabel label;
5783: PetscInt ct;
5785: PetscFunctionBegin;
5787: PetscAssertPointer(celltype, 3);
5788: if (mesh->tr) {
5789: PetscCall(DMPlexTransformGetCellType(mesh->tr, cell, celltype));
5790: } else {
5791: PetscInt pStart, pEnd;
5793: PetscCall(PetscSectionGetChart(mesh->coneSection, &pStart, NULL));
5794: if (!mesh->cellTypes) { /* XXX remove? optimize? */
5795: PetscCall(PetscSectionGetChart(mesh->coneSection, NULL, &pEnd));
5796: if (pEnd <= pStart) {
5797: *celltype = DM_POLYTOPE_UNKNOWN;
5798: PetscFunctionReturn(PETSC_SUCCESS);
5799: }
5800: PetscCall(PetscMalloc1(pEnd - pStart, &mesh->cellTypes));
5801: PetscCall(DMPlexGetCellTypeLabel(dm, &label));
5802: for (PetscInt p = pStart; p < pEnd; p++) {
5803: PetscCall(DMLabelGetValue(label, p, &ct));
5804: mesh->cellTypes[p - pStart].value_as_uint8 = (uint8_t)ct;
5805: }
5806: }
5807: *celltype = (DMPolytopeType)mesh->cellTypes[cell - pStart].value_as_uint8;
5808: if (PetscDefined(USE_DEBUG)) {
5809: PetscCall(DMPlexGetCellTypeLabel(dm, &label));
5810: PetscCall(DMLabelGetValue(label, cell, &ct));
5811: PetscCheck(ct >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Cell %" PetscInt_FMT " has not been assigned a cell type", cell);
5812: PetscCheck(ct == (PetscInt)*celltype, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid cellType for %" PetscInt_FMT ": %d != %" PetscInt_FMT, cell, (int)*celltype, ct);
5813: }
5814: }
5815: PetscFunctionReturn(PETSC_SUCCESS);
5816: }
5818: /*@
5819: DMPlexSetCellType - Set the polytope type of a given cell
5821: Not Collective
5823: Input Parameters:
5824: + dm - The `DMPLEX` object
5825: . cell - The cell
5826: - celltype - The polytope type of the cell
5828: Level: advanced
5830: Note:
5831: By default, cell types will be automatically computed using `DMPlexComputeCellTypes()` before this function
5832: is executed. This function will override the computed type. However, if automatic classification will not succeed
5833: and a user wants to manually specify all types, the classification must be disabled by calling
5834: DMCreateLabel(dm, "celltype") before getting or setting any cell types.
5836: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellTypeLabel()`, `DMPlexGetDepthLabel()`, `DMPlexGetDepth()`, `DMPlexComputeCellTypes()`, `DMCreateLabel()`
5837: @*/
5838: PetscErrorCode DMPlexSetCellType(DM dm, PetscInt cell, DMPolytopeType celltype)
5839: {
5840: DM_Plex *mesh = (DM_Plex *)dm->data;
5841: DMLabel label;
5842: PetscInt pStart, pEnd;
5844: PetscFunctionBegin;
5846: PetscCall(PetscSectionGetChart(mesh->coneSection, &pStart, &pEnd));
5847: PetscCall(DMPlexGetCellTypeLabel(dm, &label));
5848: PetscCall(DMLabelSetValue(label, cell, celltype));
5849: if (!mesh->cellTypes) PetscCall(PetscMalloc1(pEnd - pStart, &mesh->cellTypes));
5850: mesh->cellTypes[cell - pStart].value_as_uint8 = (uint8_t)celltype;
5851: PetscFunctionReturn(PETSC_SUCCESS);
5852: }
5854: PetscErrorCode DMCreateCoordinateDM_Plex(DM dm, DM *cdm)
5855: {
5856: PetscSection section;
5857: PetscInt maxHeight;
5858: const char *prefix;
5860: PetscFunctionBegin;
5861: PetscCall(DMClone(dm, cdm));
5862: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)dm, &prefix));
5863: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)*cdm, prefix));
5864: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)*cdm, "cdm_"));
5865: PetscCall(DMPlexGetMaxProjectionHeight(dm, &maxHeight));
5866: PetscCall(DMPlexSetMaxProjectionHeight(*cdm, maxHeight));
5867: PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), §ion));
5868: PetscCall(DMSetLocalSection(*cdm, section));
5869: PetscCall(PetscSectionDestroy(§ion));
5871: PetscCall(DMSetNumFields(*cdm, 1));
5872: PetscCall(DMCreateDS(*cdm));
5873: (*cdm)->cloneOpts = PETSC_TRUE;
5874: if (dm->setfromoptionscalled) PetscCall(DMSetFromOptions(*cdm));
5875: PetscFunctionReturn(PETSC_SUCCESS);
5876: }
5878: PetscErrorCode DMCreateCellCoordinateDM_Plex(DM dm, DM *cdm)
5879: {
5880: DM cgcdm;
5881: PetscSection section;
5882: const char *prefix;
5884: PetscFunctionBegin;
5885: PetscCall(DMGetCoordinateDM(dm, &cgcdm));
5886: PetscCall(DMClone(cgcdm, cdm));
5887: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)dm, &prefix));
5888: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)*cdm, prefix));
5889: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)*cdm, "cellcdm_"));
5890: PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), §ion));
5891: PetscCall(DMSetLocalSection(*cdm, section));
5892: PetscCall(PetscSectionDestroy(§ion));
5893: PetscCall(DMSetNumFields(*cdm, 1));
5894: PetscCall(DMCreateDS(*cdm));
5895: (*cdm)->cloneOpts = PETSC_TRUE;
5896: if (dm->setfromoptionscalled) PetscCall(DMSetFromOptions(*cdm));
5897: PetscFunctionReturn(PETSC_SUCCESS);
5898: }
5900: PetscErrorCode DMCreateCoordinateField_Plex(DM dm, DMField *field)
5901: {
5902: Vec coordsLocal, cellCoordsLocal;
5903: DM coordsDM, cellCoordsDM;
5905: PetscFunctionBegin;
5906: *field = NULL;
5907: PetscCall(DMGetCoordinatesLocal(dm, &coordsLocal));
5908: PetscCall(DMGetCoordinateDM(dm, &coordsDM));
5909: PetscCall(DMGetCellCoordinatesLocal(dm, &cellCoordsLocal));
5910: PetscCall(DMGetCellCoordinateDM(dm, &cellCoordsDM));
5911: if (coordsLocal && coordsDM) {
5912: if (cellCoordsLocal && cellCoordsDM) PetscCall(DMFieldCreateDSWithDG(coordsDM, cellCoordsDM, 0, coordsLocal, cellCoordsLocal, field));
5913: else PetscCall(DMFieldCreateDS(coordsDM, 0, coordsLocal, field));
5914: }
5915: PetscFunctionReturn(PETSC_SUCCESS);
5916: }
5918: /*@
5919: DMPlexGetConeSection - Return a section which describes the layout of cone data
5921: Not Collective
5923: Input Parameter:
5924: . dm - The `DMPLEX` object
5926: Output Parameter:
5927: . section - The `PetscSection` object
5929: Level: developer
5931: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetSupportSection()`, `DMPlexGetCones()`, `DMPlexGetConeOrientations()`, `PetscSection`
5932: @*/
5933: PetscErrorCode DMPlexGetConeSection(DM dm, PetscSection *section)
5934: {
5935: DM_Plex *mesh = (DM_Plex *)dm->data;
5937: PetscFunctionBegin;
5939: if (section) *section = mesh->coneSection;
5940: PetscFunctionReturn(PETSC_SUCCESS);
5941: }
5943: /*@
5944: DMPlexGetSupportSection - Return a section which describes the layout of support data
5946: Not Collective
5948: Input Parameter:
5949: . dm - The `DMPLEX` object
5951: Output Parameter:
5952: . section - The `PetscSection` object
5954: Level: developer
5956: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetConeSection()`, `PetscSection`
5957: @*/
5958: PetscErrorCode DMPlexGetSupportSection(DM dm, PetscSection *section)
5959: {
5960: DM_Plex *mesh = (DM_Plex *)dm->data;
5962: PetscFunctionBegin;
5964: if (section) *section = mesh->supportSection;
5965: PetscFunctionReturn(PETSC_SUCCESS);
5966: }
5968: /*@C
5969: DMPlexGetCones - Return cone data
5971: Not Collective
5973: Input Parameter:
5974: . dm - The `DMPLEX` object
5976: Output Parameter:
5977: . cones - The cone for each point
5979: Level: developer
5981: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetConeSection()`
5982: @*/
5983: PetscErrorCode DMPlexGetCones(DM dm, PetscInt *cones[])
5984: {
5985: DM_Plex *mesh = (DM_Plex *)dm->data;
5987: PetscFunctionBegin;
5989: if (cones) *cones = mesh->cones;
5990: PetscFunctionReturn(PETSC_SUCCESS);
5991: }
5993: /*@C
5994: DMPlexGetConeOrientations - Return cone orientation data
5996: Not Collective
5998: Input Parameter:
5999: . dm - The `DMPLEX` object
6001: Output Parameter:
6002: . coneOrientations - The array of cone orientations for all points
6004: Level: developer
6006: Notes:
6007: The `PetscSection` returned by `DMPlexGetConeSection()` partitions coneOrientations into cone orientations of particular points
6008: as returned by `DMPlexGetConeOrientation()`.
6010: The meaning of coneOrientations values is detailed in `DMPlexGetConeOrientation()`.
6012: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetConeSection()`, `DMPlexGetConeOrientation()`, `PetscSection`
6013: @*/
6014: PetscErrorCode DMPlexGetConeOrientations(DM dm, PetscInt *coneOrientations[])
6015: {
6016: DM_Plex *mesh = (DM_Plex *)dm->data;
6018: PetscFunctionBegin;
6020: if (coneOrientations) *coneOrientations = mesh->coneOrientations;
6021: PetscFunctionReturn(PETSC_SUCCESS);
6022: }
6024: /* FEM Support */
6026: PetscErrorCode DMPlexGetAllCells_Internal(DM plex, IS *cellIS)
6027: {
6028: PetscInt depth;
6030: PetscFunctionBegin;
6031: PetscCall(DMPlexGetDepth(plex, &depth));
6032: PetscCall(DMGetStratumIS(plex, "dim", depth, cellIS));
6033: if (!*cellIS) PetscCall(DMGetStratumIS(plex, "depth", depth, cellIS));
6034: PetscFunctionReturn(PETSC_SUCCESS);
6035: }
6037: PetscErrorCode DMPlexGetAllFaces_Internal(DM plex, IS *faceIS)
6038: {
6039: PetscInt depth;
6041: PetscFunctionBegin;
6042: PetscCall(DMPlexGetDepth(plex, &depth));
6043: PetscCall(DMGetStratumIS(plex, "dim", depth - 1, faceIS));
6044: if (!*faceIS) PetscCall(DMGetStratumIS(plex, "depth", depth - 1, faceIS));
6045: PetscFunctionReturn(PETSC_SUCCESS);
6046: }
6048: /*
6049: Returns number of components and tensor degree for the field. For interpolated meshes, line should be a point
6050: representing a line in the section.
6051: */
6052: static PetscErrorCode PetscSectionFieldGetTensorDegree_Private(DM dm, PetscSection section, PetscInt field, PetscInt line, PetscInt *Nc, PetscInt *k, PetscBool *continuous, PetscBool *tensor)
6053: {
6054: PetscObject obj;
6055: PetscClassId id;
6056: PetscFE fe = NULL;
6058: PetscFunctionBeginHot;
6059: PetscCall(PetscSectionGetFieldComponents(section, field, Nc));
6060: PetscCall(DMGetField(dm, field, NULL, &obj));
6061: PetscCall(PetscObjectGetClassId(obj, &id));
6062: if (id == PETSCFE_CLASSID) fe = (PetscFE)obj;
6064: if (!fe) {
6065: /* Assume the full interpolated mesh is in the chart; lines in particular */
6066: /* An order k SEM disc has k-1 dofs on an edge */
6067: PetscCall(PetscSectionGetFieldDof(section, line, field, k));
6068: *k = *k / *Nc + 1;
6069: } else {
6070: PetscInt dual_space_size, dim;
6071: PetscDualSpace dsp;
6073: PetscCall(DMGetDimension(dm, &dim));
6074: PetscCall(PetscFEGetDualSpace(fe, &dsp));
6075: PetscCall(PetscDualSpaceGetDimension(dsp, &dual_space_size));
6076: PetscCall(PetscDualSpaceLagrangeGetContinuity(dsp, continuous));
6077: PetscCall(PetscDualSpaceLagrangeGetTensor(dsp, tensor));
6078: if (*tensor) {
6079: *k = (PetscInt)PetscCeilReal(PetscPowReal(dual_space_size / *Nc, 1.0 / dim)) - 1;
6080: } else {
6081: switch (dim) {
6082: case 1:
6083: *k = (dual_space_size / *Nc) - 1;
6084: break;
6085: case 2:
6086: // N = (k + 1) (k + 2) / 2, k^2 + 3 k - 2 (N - 1) = 0, k = (sqrt(8 N + 1) - 3) / 2
6087: *k = (PetscInt)PetscCeilReal((PetscSqrtReal(8 * dual_space_size / *Nc + 1) - 3) / 2);
6088: break;
6089: case 3: {
6090: // N = (k + 1) (k + 2) (k + 3) / 6, k = (sqrt(3) sqrt(243 N^2 - 1) + 27 N)^(1/3)/3^(2/3) + 1/(3^(1/3) (sqrt(3) sqrt(243 N^2 - 1) + 27 N)^(1/3)) - 2
6091: PetscInt N = dual_space_size / *Nc;
6092: *k = (PetscInt)PetscCeilReal(PetscPowReal((PetscSqrtReal(3 * (243 * N * N - 1)) + 27 * N) / 9, 1.0 / 3.0) + 1 / PetscPowReal(3 * (PetscSqrtReal(3 * (243 * N * N - 1)) + 27 * N), 1.0 / 3.0)) - 2;
6093: } break;
6094: default:
6095: *k = -1;
6096: }
6097: }
6098: }
6099: PetscFunctionReturn(PETSC_SUCCESS);
6100: }
6102: static PetscErrorCode GetFieldSize_Private(PetscInt dim, PetscInt k, PetscBool tensor, PetscInt *dof)
6103: {
6104: PetscFunctionBeginHot;
6105: if (tensor) {
6106: *dof = PetscPowInt(k + 1, dim);
6107: } else {
6108: switch (dim) {
6109: case 1:
6110: *dof = k + 1;
6111: break;
6112: case 2:
6113: *dof = ((k + 1) * (k + 2)) / 2;
6114: break;
6115: case 3:
6116: *dof = ((k + 1) * (k + 2) * (k + 3)) / 6;
6117: break;
6118: default:
6119: *dof = 0;
6120: }
6121: }
6122: PetscFunctionReturn(PETSC_SUCCESS);
6123: }
6125: /*@
6126: DMPlexSetClosurePermutationTensor - Create a permutation from the default (BFS) point ordering in the closure, to a
6127: lexicographic ordering over the tensor product cell (i.e., line, quad, hex, etc.), and set this permutation in the
6128: section provided (or the section of the `DM`).
6130: Not Collective
6132: Input Parameters:
6133: + dm - The `DM`
6134: . point - Either a cell (highest dim point) or an edge (dim 1 point), or `PETSC_DETERMINE`
6135: - section - The `PetscSection` to reorder, or `NULL` for the default section
6137: Example:
6138: A typical interpolated single-quad mesh might order points as
6139: .vb
6140: [c0, v1, v2, v3, v4, e5, e6, e7, e8]
6142: v4 -- e6 -- v3
6143: | |
6144: e7 c0 e8
6145: | |
6146: v1 -- e5 -- v2
6147: .ve
6149: (There is no significance to the ordering described here.) The default section for a Q3 quad might typically assign
6150: dofs in the order of points, e.g.,
6151: .vb
6152: c0 -> [0,1,2,3]
6153: v1 -> [4]
6154: ...
6155: e5 -> [8, 9]
6156: .ve
6158: which corresponds to the dofs
6159: .vb
6160: 6 10 11 7
6161: 13 2 3 15
6162: 12 0 1 14
6163: 4 8 9 5
6164: .ve
6166: The closure in BFS ordering works through height strata (cells, edges, vertices) to produce the ordering
6167: .vb
6168: 0 1 2 3 8 9 14 15 11 10 13 12 4 5 7 6
6169: .ve
6171: After calling DMPlexSetClosurePermutationTensor(), the closure will be ordered lexicographically,
6172: .vb
6173: 4 8 9 5 12 0 1 14 13 2 3 15 6 10 11 7
6174: .ve
6176: Level: developer
6178: Notes:
6179: The point is used to determine the number of dofs/field on an edge. For SEM, this is related to the polynomial
6180: degree of the basis.
6182: This is required to run with libCEED.
6184: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMGetLocalSection()`, `PetscSectionSetClosurePermutation()`, `DMPlexSetClosurePermutationLexicographic()`, `DMSetGlobalSection()`
6185: @*/
6186: PetscErrorCode DMPlexSetClosurePermutationTensor(DM dm, PetscInt point, PetscSection section)
6187: {
6188: DMLabel label;
6189: PetscInt dim, depth = -1, eStart = -1, Nf;
6190: PetscBool continuous = PETSC_TRUE, tensor = PETSC_TRUE;
6192: PetscFunctionBegin;
6195: PetscCall(DMGetDimension(dm, &dim));
6196: if (dim < 1) PetscFunctionReturn(PETSC_SUCCESS);
6197: if (point < 0) {
6198: PetscInt sStart, sEnd;
6200: PetscCall(DMPlexGetDepthStratum(dm, 1, &sStart, &sEnd));
6201: point = sEnd - sStart ? sStart : point;
6202: }
6203: PetscCall(DMPlexGetDepthLabel(dm, &label));
6204: if (point >= 0) PetscCall(DMLabelGetValue(label, point, &depth));
6205: if (!section) PetscCall(DMGetLocalSection(dm, §ion));
6206: if (depth == 1) {
6207: eStart = point;
6208: } else if (depth == dim) {
6209: const PetscInt *cone;
6211: PetscCall(DMPlexGetCone(dm, point, &cone));
6212: if (dim == 2) eStart = cone[0];
6213: else if (dim == 3) {
6214: const PetscInt *cone2;
6215: PetscCall(DMPlexGetCone(dm, cone[0], &cone2));
6216: eStart = cone2[0];
6217: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Point %" PetscInt_FMT " of depth %" PetscInt_FMT " cannot be used to bootstrap spectral ordering for dim %" PetscInt_FMT, point, depth, dim);
6218: } else PetscCheck(depth < 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Point %" PetscInt_FMT " of depth %" PetscInt_FMT " cannot be used to bootstrap spectral ordering for dim %" PetscInt_FMT, point, depth, dim);
6220: PetscCall(PetscSectionGetNumFields(section, &Nf));
6221: for (PetscInt d = 1; d <= dim; d++) {
6222: PetscInt k, f, Nc, c, i, j, size = 0, offset = 0, foffset = 0;
6223: PetscInt *perm;
6225: for (f = 0; f < Nf; ++f) {
6226: PetscInt dof;
6228: PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6229: PetscCheck(dim == 1 || tensor || !continuous, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Continuous field %" PetscInt_FMT " must have a tensor product discretization", f);
6230: if (!continuous && d < dim) continue;
6231: PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6232: size += dof * Nc;
6233: }
6234: PetscCall(PetscMalloc1(size, &perm));
6235: for (f = 0; f < Nf; ++f) {
6236: switch (d) {
6237: case 1:
6238: PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6239: if (!continuous && d < dim) continue;
6240: /*
6241: Original ordering is [ edge of length k-1; vtx0; vtx1 ]
6242: We want [ vtx0; edge of length k-1; vtx1 ]
6243: */
6244: if (continuous) {
6245: for (c = 0; c < Nc; c++, offset++) perm[offset] = (k - 1) * Nc + c + foffset;
6246: for (i = 0; i < k - 1; i++)
6247: for (c = 0; c < Nc; c++, offset++) perm[offset] = i * Nc + c + foffset;
6248: for (c = 0; c < Nc; c++, offset++) perm[offset] = k * Nc + c + foffset;
6249: foffset = offset;
6250: } else {
6251: PetscInt dof;
6253: PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6254: for (i = 0; i < dof * Nc; ++i, ++offset) perm[offset] = i + foffset;
6255: foffset = offset;
6256: }
6257: break;
6258: case 2:
6259: /* The original quad closure is oriented clockwise, {f, e_b, e_r, e_t, e_l, v_lb, v_rb, v_tr, v_tl} */
6260: PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6261: if (!continuous && d < dim) continue;
6262: /* The SEM order is
6264: v_lb, {e_b}, v_rb,
6265: e^{(k-1)-i}_l, {f^{i*(k-1)}}, e^i_r,
6266: v_lt, reverse {e_t}, v_rt
6267: */
6268: if (continuous) {
6269: const PetscInt of = 0;
6270: const PetscInt oeb = of + PetscSqr(k - 1);
6271: const PetscInt oer = oeb + (k - 1);
6272: const PetscInt oet = oer + (k - 1);
6273: const PetscInt oel = oet + (k - 1);
6274: const PetscInt ovlb = oel + (k - 1);
6275: const PetscInt ovrb = ovlb + 1;
6276: const PetscInt ovrt = ovrb + 1;
6277: const PetscInt ovlt = ovrt + 1;
6278: PetscInt o;
6280: /* bottom */
6281: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlb * Nc + c + foffset;
6282: for (o = oeb; o < oer; ++o)
6283: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6284: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovrb * Nc + c + foffset;
6285: /* middle */
6286: for (i = 0; i < k - 1; ++i) {
6287: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oel + (k - 2) - i) * Nc + c + foffset;
6288: for (o = of + (k - 1) * i; o < of + (k - 1) * (i + 1); ++o)
6289: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6290: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oer + i) * Nc + c + foffset;
6291: }
6292: /* top */
6293: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlt * Nc + c + foffset;
6294: for (o = oel - 1; o >= oet; --o)
6295: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6296: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovrt * Nc + c + foffset;
6297: foffset = offset;
6298: } else {
6299: PetscInt dof;
6301: PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6302: for (i = 0; i < dof * Nc; ++i, ++offset) perm[offset] = i + foffset;
6303: foffset = offset;
6304: }
6305: break;
6306: case 3:
6307: /* The original hex closure is
6309: {c,
6310: f_b, f_t, f_f, f_b, f_r, f_l,
6311: e_bl, e_bb, e_br, e_bf, e_tf, e_tr, e_tb, e_tl, e_rf, e_lf, e_lb, e_rb,
6312: v_blf, v_blb, v_brb, v_brf, v_tlf, v_trf, v_trb, v_tlb}
6313: */
6314: PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6315: if (!continuous && d < dim) continue;
6316: /* The SEM order is
6317: Bottom Slice
6318: v_blf, {e^{(k-1)-n}_bf}, v_brf,
6319: e^{i}_bl, f^{n*(k-1)+(k-1)-i}_b, e^{(k-1)-i}_br,
6320: v_blb, {e_bb}, v_brb,
6322: Middle Slice (j)
6323: {e^{(k-1)-j}_lf}, {f^{j*(k-1)+n}_f}, e^j_rf,
6324: f^{i*(k-1)+j}_l, {c^{(j*(k-1) + i)*(k-1)+n}_t}, f^{j*(k-1)+i}_r,
6325: e^j_lb, {f^{j*(k-1)+(k-1)-n}_b}, e^{(k-1)-j}_rb,
6327: Top Slice
6328: v_tlf, {e_tf}, v_trf,
6329: e^{(k-1)-i}_tl, {f^{i*(k-1)}_t}, e^{i}_tr,
6330: v_tlb, {e^{(k-1)-n}_tb}, v_trb,
6331: */
6332: if (continuous) {
6333: const PetscInt oc = 0;
6334: const PetscInt ofb = oc + PetscSqr(k - 1) * (k - 1);
6335: const PetscInt oft = ofb + PetscSqr(k - 1);
6336: const PetscInt off = oft + PetscSqr(k - 1);
6337: const PetscInt ofk = off + PetscSqr(k - 1);
6338: const PetscInt ofr = ofk + PetscSqr(k - 1);
6339: const PetscInt ofl = ofr + PetscSqr(k - 1);
6340: const PetscInt oebl = ofl + PetscSqr(k - 1);
6341: const PetscInt oebb = oebl + (k - 1);
6342: const PetscInt oebr = oebb + (k - 1);
6343: const PetscInt oebf = oebr + (k - 1);
6344: const PetscInt oetf = oebf + (k - 1);
6345: const PetscInt oetr = oetf + (k - 1);
6346: const PetscInt oetb = oetr + (k - 1);
6347: const PetscInt oetl = oetb + (k - 1);
6348: const PetscInt oerf = oetl + (k - 1);
6349: const PetscInt oelf = oerf + (k - 1);
6350: const PetscInt oelb = oelf + (k - 1);
6351: const PetscInt oerb = oelb + (k - 1);
6352: const PetscInt ovblf = oerb + (k - 1);
6353: const PetscInt ovblb = ovblf + 1;
6354: const PetscInt ovbrb = ovblb + 1;
6355: const PetscInt ovbrf = ovbrb + 1;
6356: const PetscInt ovtlf = ovbrf + 1;
6357: const PetscInt ovtrf = ovtlf + 1;
6358: const PetscInt ovtrb = ovtrf + 1;
6359: const PetscInt ovtlb = ovtrb + 1;
6360: PetscInt o, n;
6362: /* Bottom Slice */
6363: /* bottom */
6364: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblf * Nc + c + foffset;
6365: for (o = oetf - 1; o >= oebf; --o)
6366: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6367: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovbrf * Nc + c + foffset;
6368: /* middle */
6369: for (i = 0; i < k - 1; ++i) {
6370: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebl + i) * Nc + c + foffset;
6371: for (n = 0; n < k - 1; ++n) {
6372: o = ofb + n * (k - 1) + i;
6373: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6374: }
6375: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebr + (k - 2) - i) * Nc + c + foffset;
6376: }
6377: /* top */
6378: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblb * Nc + c + foffset;
6379: for (o = oebb; o < oebr; ++o)
6380: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6381: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovbrb * Nc + c + foffset;
6383: /* Middle Slice */
6384: for (j = 0; j < k - 1; ++j) {
6385: /* bottom */
6386: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelf + (k - 2) - j) * Nc + c + foffset;
6387: for (o = off + j * (k - 1); o < off + (j + 1) * (k - 1); ++o)
6388: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6389: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerf + j) * Nc + c + foffset;
6390: /* middle */
6391: for (i = 0; i < k - 1; ++i) {
6392: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofl + i * (k - 1) + j) * Nc + c + foffset;
6393: for (n = 0; n < k - 1; ++n)
6394: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oc + (j * (k - 1) + i) * (k - 1) + n) * Nc + c + foffset;
6395: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofr + j * (k - 1) + i) * Nc + c + foffset;
6396: }
6397: /* top */
6398: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelb + j) * Nc + c + foffset;
6399: for (o = ofk + j * (k - 1) + (k - 2); o >= ofk + j * (k - 1); --o)
6400: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6401: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerb + (k - 2) - j) * Nc + c + foffset;
6402: }
6404: /* Top Slice */
6405: /* bottom */
6406: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtlf * Nc + c + foffset;
6407: for (o = oetf; o < oetr; ++o)
6408: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6409: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtrf * Nc + c + foffset;
6410: /* middle */
6411: for (i = 0; i < k - 1; ++i) {
6412: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oetl + (k - 2) - i) * Nc + c + foffset;
6413: for (n = 0; n < k - 1; ++n)
6414: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oft + i * (k - 1) + n) * Nc + c + foffset;
6415: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oetr + i) * Nc + c + foffset;
6416: }
6417: /* top */
6418: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtlb * Nc + c + foffset;
6419: for (o = oetl - 1; o >= oetb; --o)
6420: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6421: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtrb * Nc + c + foffset;
6423: foffset = offset;
6424: } else {
6425: PetscInt dof;
6427: PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6428: for (i = 0; i < dof * Nc; ++i, ++offset) perm[offset] = i + foffset;
6429: foffset = offset;
6430: }
6431: break;
6432: default:
6433: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "No spectral ordering for dimension %" PetscInt_FMT, d);
6434: }
6435: }
6436: PetscCheck(offset == size, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Number of permutation entries %" PetscInt_FMT " != %" PetscInt_FMT, offset, size);
6437: /* Check permutation */
6438: {
6439: PetscInt *check;
6441: PetscCall(PetscMalloc1(size, &check));
6442: for (i = 0; i < size; ++i) {
6443: check[i] = -1;
6444: PetscCheck(perm[i] >= 0 && perm[i] < size, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Invalid permutation index p[%" PetscInt_FMT "] = %" PetscInt_FMT, i, perm[i]);
6445: }
6446: for (i = 0; i < size; ++i) check[perm[i]] = i;
6447: for (i = 0; i < size; ++i) PetscCheck(check[i] >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Missing permutation index %" PetscInt_FMT, i);
6448: PetscCall(PetscFree(check));
6449: }
6450: PetscCall(PetscSectionSetClosurePermutation_Internal(section, (PetscObject)dm, d, size, PETSC_OWN_POINTER, perm));
6451: if (d == dim) { // Add permutation for localized (in case this is a coordinate DM)
6452: PetscInt *loc_perm;
6453: PetscCall(PetscMalloc1(size * 2, &loc_perm));
6454: for (PetscInt i = 0; i < size; i++) {
6455: loc_perm[i] = perm[i];
6456: loc_perm[size + i] = size + perm[i];
6457: }
6458: PetscCall(PetscSectionSetClosurePermutation_Internal(section, (PetscObject)dm, d, size * 2, PETSC_OWN_POINTER, loc_perm));
6459: }
6460: }
6461: PetscFunctionReturn(PETSC_SUCCESS);
6462: }
6464: /*@
6465: DMPlexSetClosurePermutationLexicographic - Create a permutation from the default (BFS) point ordering in the closure, to a
6466: lexicographic ordering over the simplex (i.e., line, tri, tet, etc.), and set this permutation in the
6467: section provided (or the section of the `DM`).
6469: Not Collective
6471: Input Parameters:
6472: + dm - The `DM`
6473: . point - Either a cell (highest dim point) or an edge (dim 1 point), or `PETSC_DETERMINE`
6474: - section - The `PetscSection` to reorder, or `NULL` for the default section
6476: Example:
6477: A typical interpolated single-tri mesh might order points as
6478: .vb
6479: [c0, v1, v2, v3, e4, e5, e6]
6481: v3
6482: | \
6483: | \
6484: e6 e5
6485: | c0 \
6486: | \
6487: v1 -- e4 -- v2
6488: .ve
6490: (There is no significance to the ordering described here.) The default section for a P3 tri might typically assign
6491: dofs in the order of points, e.g.,
6492: .vb
6493: c0 -> [0]
6494: v1 -> [1]
6495: ...
6496: e4 -> [4, 5]
6497: .ve
6499: which corresponds to the dofs
6500: .vb
6501: 3
6502: 8 7
6503: 9 0 6
6504: 1 4 5 2
6505: .ve
6507: The closure in BFS ordering works through height strata (cells, edges, vertices) to produce the ordering
6508: .vb
6509: 0 4 5 6 7 8 9 1 2 3
6510: .ve
6512: After calling DMPlexSetClosurePermutationLexicographic(), the closure will be ordered lexicographically,
6513: .vb
6514: 1 4 5 2 9 0 6 8 7 3
6515: .ve
6517: Level: developer
6519: Notes:
6520: The point is used to determine the number of dofs/field on an edge. For SEM, this is related to the polynomial
6521: degree of the basis.
6523: The lexicographic order starts along the left edge, not the front, to match codes like GMsh with a bottom face oriented into the volume.
6525: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMGetLocalSection()`, `PetscSectionSetClosurePermutation()`, `DMPlexSetClosurePermutationTensor()`, `DMSetGlobalSection()`
6526: @*/
6527: PetscErrorCode DMPlexSetClosurePermutationLexicographic(DM dm, PetscInt point, PetscSection section)
6528: {
6529: DMLabel label;
6530: PetscInt dim, depth = -1, eStart = -1, Nf;
6531: PetscBool continuous = PETSC_TRUE, tensor = PETSC_TRUE;
6533: PetscFunctionBegin;
6536: // TODO: This needs to be tested for P4-6 using Plex ex3 with a linear field to check the permutations
6537: PetscCall(DMGetDimension(dm, &dim));
6538: if (dim < 1) PetscFunctionReturn(PETSC_SUCCESS);
6539: if (point < 0) {
6540: PetscInt sStart, sEnd;
6542: PetscCall(DMPlexGetDepthStratum(dm, 1, &sStart, &sEnd));
6543: point = sEnd - sStart ? sStart : point;
6544: }
6545: PetscCall(DMPlexGetDepthLabel(dm, &label));
6546: if (point >= 0) PetscCall(DMLabelGetValue(label, point, &depth));
6547: if (!section) PetscCall(DMGetLocalSection(dm, §ion));
6548: if (depth == 1) {
6549: eStart = point;
6550: } else if (depth == dim) {
6551: const PetscInt *cone;
6553: PetscCall(DMPlexGetCone(dm, point, &cone));
6554: if (dim == 2) eStart = cone[0];
6555: else if (dim == 3) {
6556: const PetscInt *cone2;
6557: PetscCall(DMPlexGetCone(dm, cone[0], &cone2));
6558: eStart = cone2[0];
6559: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Point %" PetscInt_FMT " of depth %" PetscInt_FMT " cannot be used to bootstrap spectral ordering for dim %" PetscInt_FMT, point, depth, dim);
6560: } else PetscCheck(depth < 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Point %" PetscInt_FMT " of depth %" PetscInt_FMT " cannot be used to bootstrap spectral ordering for dim %" PetscInt_FMT, point, depth, dim);
6562: PetscCall(PetscSectionGetNumFields(section, &Nf));
6563: for (PetscInt d = 1; d <= dim; d++) {
6564: PetscInt k, f, Nc, c, i, j, size = 0, offset = 0, foffset = 0;
6565: PetscInt *perm;
6567: for (f = 0; f < Nf; ++f) {
6568: PetscInt dof;
6570: PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6571: PetscCheck(dim == 1 || !tensor, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Field %" PetscInt_FMT " should not have a tensor product discretization", f);
6572: if (!continuous && d < dim) continue;
6573: PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6574: size += dof * Nc;
6575: }
6576: PetscCall(PetscMalloc1(size, &perm));
6577: for (f = 0; f < Nf; ++f) {
6578: switch (d) {
6579: case 1:
6580: PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6581: if (!continuous && d < dim) continue;
6582: /*
6583: Original ordering is [ edge of length k-1; vtx0; vtx1 ]
6584: We want [ vtx0; edge of length k-1; vtx1 ]
6585: */
6586: if (continuous) {
6587: for (c = 0; c < Nc; c++, offset++) perm[offset] = (k - 1) * Nc + c + foffset;
6588: for (i = 0; i < k - 1; i++)
6589: for (c = 0; c < Nc; c++, offset++) perm[offset] = i * Nc + c + foffset;
6590: for (c = 0; c < Nc; c++, offset++) perm[offset] = k * Nc + c + foffset;
6591: foffset = offset;
6592: } else {
6593: PetscInt dof;
6595: PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6596: for (i = 0; i < dof * Nc; ++i, ++offset) perm[offset] = i + foffset;
6597: foffset = offset;
6598: }
6599: break;
6600: case 2:
6601: /* The original tri closure is oriented clockwise, {f, e_b, e_r, e_l, v_lb, v_rb, v_lt} */
6602: PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6603: if (!continuous && d < dim) continue;
6604: /* The SEM order is
6606: v_lb, {e_b}, v_rb,
6607: e^{(k-1)-i}_l, {f^{i*(k-1-i)}}, e^i_r,
6608: v_lt
6609: */
6610: if (continuous) {
6611: const PetscInt of = 0;
6612: const PetscInt oeb = of + (k - 2) * (k - 1) / 2;
6613: const PetscInt oer = oeb + (k - 1);
6614: const PetscInt oel = oer + (k - 1);
6615: const PetscInt ovlb = oel + (k - 1);
6616: const PetscInt ovrb = ovlb + 1;
6617: const PetscInt ovlt = ovrb + 1;
6618: PetscInt o;
6620: /* bottom */
6621: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlb * Nc + c + foffset;
6622: for (o = oeb; o < oer; ++o)
6623: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6624: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovrb * Nc + c + foffset;
6625: /* middle */
6626: for (i = 0; i < k - 1; ++i) {
6627: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oel + (k - 2) - i) * Nc + c + foffset;
6628: // (k - 2) (k - 1) / 2 - (k - 2 - i) (k - 1 - i) / 2 = i (2 k - 3 - i) / 2
6629: for (o = of + i * (2 * k - 3 - i) / 2; o < of + (i + 1) * (2 * k - 4 - i) / 2; ++o)
6630: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6631: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oer + i) * Nc + c + foffset;
6632: }
6633: /* top */
6634: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovlt * Nc + c + foffset;
6635: foffset = offset;
6636: } else {
6637: PetscInt dof;
6639: PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6640: for (i = 0; i < dof * Nc; ++i, ++offset) perm[offset] = i + foffset;
6641: foffset = offset;
6642: }
6643: break;
6644: case 3:
6645: /* The original tet closure is
6647: {c,
6648: f_b, f_l, f_f, f_r,
6649: e_bl, e_br, e_bf, e_lf, e_rf, e_rb,
6650: v_blf, v_blb, v_brf, v_tlf}
6651: */
6652: PetscCall(PetscSectionFieldGetTensorDegree_Private(dm, section, f, eStart, &Nc, &k, &continuous, &tensor));
6653: if (!continuous && d < dim) continue;
6654: /* The SEM order (starting on the left edge since GMsh flips the bottom face) is
6655: Bottom Slice
6656: v_blb, {e^{-n}_bl}, v_blf,
6657: e^{i}_br, f^{i,-n}_b, e^{-i}_bf,
6658: v_brf,
6660: Middle Slice (j)
6661: e^{-j}_rb, {f^{-n,j}_l}, e^{j}_lf,
6662: f^{-n,j}_r, {c^{j,-n,i}}, f^{j,i}_f,
6663: e^{j}_rf,
6665: Top Slice
6666: v_tlf,
6667: */
6668: if (continuous) {
6669: const PetscInt oc = 0;
6670: const PetscInt ofb = oc + (k - 3) * (k - 2) * (k - 1) / 6;
6671: const PetscInt ofl = ofb + (k - 2) * (k - 1) / 2;
6672: const PetscInt off = ofl + (k - 2) * (k - 1) / 2;
6673: const PetscInt ofr = off + (k - 2) * (k - 1) / 2;
6674: const PetscInt oebl = ofr + (k - 2) * (k - 1) / 2;
6675: const PetscInt oebr = oebl + (k - 1);
6676: const PetscInt oebf = oebr + (k - 1);
6677: const PetscInt oelf = oebf + (k - 1);
6678: const PetscInt oerb = oelf + (k - 1);
6679: const PetscInt oerf = oerb + (k - 1);
6680: const PetscInt ovblf = oerf + (k - 1);
6681: const PetscInt ovblb = ovblf + 1;
6682: const PetscInt ovbrf = ovblb + 1;
6683: const PetscInt ovtlf = ovbrf + 1;
6684: PetscInt o;
6686: /* Bottom Slice */
6687: /* bottom */
6688: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblb * Nc + c + foffset;
6689: for (o = oebr - 1; o >= oebl; --o)
6690: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6691: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovblf * Nc + c + foffset;
6692: /* middle */
6693: for (i = 0; i < k - 1; ++i) {
6694: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebr + i) * Nc + c + foffset;
6695: for (PetscInt n = 0; n < k - 2 - i; ++n) {
6696: // (k - 2) (k - 1) / 2 - (k - 2 - i) (k - 1 - i) / 2 = i (2 k - 3 - i) / 2
6697: o = ofb + i * (2 * k - 3 - i) / 2 + (k - 2 - i - 1 - n);
6698: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6699: }
6700: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oebf + (k - 2) - i) * Nc + c + foffset;
6701: }
6702: /* top */
6703: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovbrf * Nc + c + foffset;
6705: /* Middle Slice */
6706: for (j = 0; j < k - 1; ++j) {
6707: /* bottom */
6708: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerb + k - 2 - j) * Nc + c + foffset;
6709: for (PetscInt n = k - 3 - j; n >= 0; --n) {
6710: // (k - 2) (k - 1) / 2 - (k - 2 - i) (k - 1 - i) / 2 = i (2 k - 3 - i) / 2
6711: o = ofl + n * (2 * k - 3 - n) / 2 + j;
6712: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = o * Nc + c + foffset;
6713: }
6714: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oelf + j) * Nc + c + foffset;
6715: /* middle */
6716: for (i = 0; i < k - 2 - j; ++i) {
6717: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (ofr + i * (2 * k - 1 - i) / 2 + j) * Nc + c + foffset;
6718: for (PetscInt n = k - 4 - j - i; n >= 0; --n) {
6719: // (k - 2) (k - 1) k / 6 - (k - 2 - j) (k - 1 - j) (k - j) / 6 = j (j^2 - 1 - 3 (k - 1) (j + k - 1)) / 6
6720: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oc + j * (j * j - 1 - 3 * (k - 1) * (j + k - 1)) / 6 + n * (2 * k - 3 - n) + i) * Nc + c + foffset;
6721: }
6722: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (off + j * (2 * k - 3 - j) / 2 + i) * Nc + c + foffset;
6723: }
6724: /* top */
6725: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = (oerf + j) * Nc + c + foffset;
6726: }
6728: /* Top Slice */
6729: for (c = 0; c < Nc; ++c, ++offset) perm[offset] = ovtlf * Nc + c + foffset;
6731: foffset = offset;
6732: } else {
6733: PetscInt dof;
6735: PetscCall(GetFieldSize_Private(d, k, tensor, &dof));
6736: for (i = 0; i < dof * Nc; ++i, ++offset) perm[offset] = i + foffset;
6737: foffset = offset;
6738: }
6739: break;
6740: default:
6741: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "No spectral ordering for dimension %" PetscInt_FMT, d);
6742: }
6743: }
6744: PetscCheck(offset == size, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Number of permutation entries %" PetscInt_FMT " != %" PetscInt_FMT, offset, size);
6745: /* Check permutation */
6746: {
6747: PetscInt *check;
6749: PetscCall(PetscMalloc1(size, &check));
6750: for (i = 0; i < size; ++i) {
6751: check[i] = -1;
6752: PetscCheck(perm[i] >= 0 && perm[i] < size, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Invalid permutation index p[%" PetscInt_FMT "] = %" PetscInt_FMT, i, perm[i]);
6753: }
6754: for (i = 0; i < size; ++i) check[perm[i]] = i;
6755: for (i = 0; i < size; ++i) PetscCheck(check[i] >= 0, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Missing permutation index %" PetscInt_FMT " out of %" PetscInt_FMT, i, size);
6756: PetscCall(PetscFree(check));
6757: }
6758: PetscCall(PetscSectionSetClosurePermutation_Internal(section, (PetscObject)dm, d, size, PETSC_OWN_POINTER, perm));
6759: if (d == dim) { // Add permutation for localized (in case this is a coordinate DM)
6760: PetscInt *loc_perm;
6761: PetscCall(PetscMalloc1(size * 2, &loc_perm));
6762: for (PetscInt i = 0; i < size; i++) {
6763: loc_perm[i] = perm[i];
6764: loc_perm[size + i] = size + perm[i];
6765: }
6766: PetscCall(PetscSectionSetClosurePermutation_Internal(section, (PetscObject)dm, d, size * 2, PETSC_OWN_POINTER, loc_perm));
6767: }
6768: }
6769: PetscFunctionReturn(PETSC_SUCCESS);
6770: }
6772: PetscErrorCode DMPlexGetPointDualSpaceFEM(DM dm, PetscInt point, PetscInt field, PetscDualSpace *dspace)
6773: {
6774: PetscDS prob;
6775: PetscInt depth, Nf, h;
6776: DMLabel label;
6778: PetscFunctionBeginHot;
6779: PetscCall(DMGetDS(dm, &prob));
6780: Nf = prob->Nf;
6781: label = dm->depthLabel;
6782: *dspace = NULL;
6783: if (field < Nf) {
6784: PetscObject disc = prob->disc[field];
6786: if (disc->classid == PETSCFE_CLASSID) {
6787: PetscDualSpace dsp;
6789: PetscCall(PetscFEGetDualSpace((PetscFE)disc, &dsp));
6790: PetscCall(DMLabelGetNumValues(label, &depth));
6791: PetscCall(DMLabelGetValue(label, point, &h));
6792: h = depth - 1 - h;
6793: if (h) PetscCall(PetscDualSpaceGetHeightSubspace(dsp, h, dspace));
6794: else *dspace = dsp;
6795: }
6796: }
6797: PetscFunctionReturn(PETSC_SUCCESS);
6798: }
6800: static inline PetscErrorCode DMPlexVecGetClosure_Depth1_Static(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
6801: {
6802: PetscScalar *array;
6803: const PetscScalar *vArray;
6804: const PetscInt *cone, *coneO;
6805: PetscInt pStart, pEnd, p, numPoints, size = 0, offset = 0;
6807: PetscFunctionBeginHot;
6808: PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
6809: PetscCall(DMPlexGetConeSize(dm, point, &numPoints));
6810: PetscCall(DMPlexGetCone(dm, point, &cone));
6811: PetscCall(DMPlexGetConeOrientation(dm, point, &coneO));
6812: if (!values || !*values) {
6813: if ((point >= pStart) && (point < pEnd)) {
6814: PetscInt dof;
6816: PetscCall(PetscSectionGetDof(section, point, &dof));
6817: size += dof;
6818: }
6819: for (p = 0; p < numPoints; ++p) {
6820: const PetscInt cp = cone[p];
6821: PetscInt dof;
6823: if ((cp < pStart) || (cp >= pEnd)) continue;
6824: PetscCall(PetscSectionGetDof(section, cp, &dof));
6825: size += dof;
6826: }
6827: if (!values) {
6828: if (csize) *csize = size;
6829: PetscFunctionReturn(PETSC_SUCCESS);
6830: }
6831: PetscCall(DMGetWorkArray(dm, size, MPIU_SCALAR, &array));
6832: } else {
6833: array = *values;
6834: }
6835: size = 0;
6836: PetscCall(VecGetArrayRead(v, &vArray));
6837: if ((point >= pStart) && (point < pEnd)) {
6838: PetscInt dof, off, d;
6839: const PetscScalar *varr;
6841: PetscCall(PetscSectionGetDof(section, point, &dof));
6842: PetscCall(PetscSectionGetOffset(section, point, &off));
6843: varr = PetscSafePointerPlusOffset(vArray, off);
6844: for (d = 0; d < dof; ++d, ++offset) array[offset] = varr[d];
6845: size += dof;
6846: }
6847: for (p = 0; p < numPoints; ++p) {
6848: const PetscInt cp = cone[p];
6849: PetscInt o = coneO[p];
6850: PetscInt dof, off, d;
6851: const PetscScalar *varr;
6853: if ((cp < pStart) || (cp >= pEnd)) continue;
6854: PetscCall(PetscSectionGetDof(section, cp, &dof));
6855: PetscCall(PetscSectionGetOffset(section, cp, &off));
6856: varr = PetscSafePointerPlusOffset(vArray, off);
6857: if (o >= 0) {
6858: for (d = 0; d < dof; ++d, ++offset) array[offset] = varr[d];
6859: } else {
6860: for (d = dof - 1; d >= 0; --d, ++offset) array[offset] = varr[d];
6861: }
6862: size += dof;
6863: }
6864: PetscCall(VecRestoreArrayRead(v, &vArray));
6865: if (!*values) {
6866: if (csize) *csize = size;
6867: *values = array;
6868: } else {
6869: PetscCheck(size <= *csize, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Size of input array %" PetscInt_FMT " < actual size %" PetscInt_FMT, *csize, size);
6870: *csize = size;
6871: }
6872: PetscFunctionReturn(PETSC_SUCCESS);
6873: }
6875: /* Compress out points not in the section */
6876: static inline PetscErrorCode CompressPoints_Private(PetscSection section, PetscInt *numPoints, PetscInt points[])
6877: {
6878: const PetscInt np = *numPoints;
6879: PetscInt pStart, pEnd, p, q;
6881: PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
6882: for (p = 0, q = 0; p < np; ++p) {
6883: const PetscInt r = points[p * 2];
6884: if ((r >= pStart) && (r < pEnd)) {
6885: points[q * 2] = r;
6886: points[q * 2 + 1] = points[p * 2 + 1];
6887: ++q;
6888: }
6889: }
6890: *numPoints = q;
6891: return PETSC_SUCCESS;
6892: }
6894: /* Compressed closure does not apply closure permutation */
6895: PetscErrorCode DMPlexGetCompressedClosure(DM dm, PetscSection section, PetscInt point, PetscInt ornt, PetscInt *numPoints, PetscInt **points, PetscSection *clSec, IS *clPoints, const PetscInt **clp)
6896: {
6897: const PetscInt *cla = NULL;
6898: PetscInt np, *pts = NULL;
6900: PetscFunctionBeginHot;
6901: PetscCall(PetscSectionGetClosureIndex(section, (PetscObject)dm, clSec, clPoints));
6902: if (!ornt && *clPoints) {
6903: PetscInt dof, off;
6905: PetscCall(PetscSectionGetDof(*clSec, point, &dof));
6906: PetscCall(PetscSectionGetOffset(*clSec, point, &off));
6907: PetscCall(ISGetIndices(*clPoints, &cla));
6908: np = dof / 2;
6909: pts = PetscSafePointerPlusOffset((PetscInt *)cla, off);
6910: } else {
6911: PetscCall(DMPlexGetTransitiveClosure_Internal(dm, point, ornt, PETSC_TRUE, &np, &pts));
6912: PetscCall(CompressPoints_Private(section, &np, pts));
6913: }
6914: *numPoints = np;
6915: *points = pts;
6916: *clp = cla;
6917: PetscFunctionReturn(PETSC_SUCCESS);
6918: }
6920: PetscErrorCode DMPlexRestoreCompressedClosure(DM dm, PetscSection section, PetscInt point, PetscInt *numPoints, PetscInt **points, PetscSection *clSec, IS *clPoints, const PetscInt **clp)
6921: {
6922: PetscFunctionBeginHot;
6923: if (!*clPoints) {
6924: PetscCall(DMPlexRestoreTransitiveClosure(dm, point, PETSC_TRUE, numPoints, points));
6925: } else {
6926: PetscCall(ISRestoreIndices(*clPoints, clp));
6927: }
6928: *numPoints = 0;
6929: *points = NULL;
6930: *clSec = NULL;
6931: *clPoints = NULL;
6932: *clp = NULL;
6933: PetscFunctionReturn(PETSC_SUCCESS);
6934: }
6936: static inline PetscErrorCode DMPlexVecGetClosure_Static(DM dm, PetscSection section, PetscInt numPoints, const PetscInt points[], const PetscInt clperm[], const PetscScalar vArray[], PetscInt *size, PetscScalar array[])
6937: {
6938: PetscInt offset = 0, p;
6939: const PetscInt **perms = NULL;
6940: const PetscScalar **flips = NULL;
6942: PetscFunctionBeginHot;
6943: *size = 0;
6944: PetscCall(PetscSectionGetPointSyms(section, numPoints, points, &perms, &flips));
6945: for (p = 0; p < numPoints; p++) {
6946: const PetscInt point = points[2 * p];
6947: const PetscInt *perm = perms ? perms[p] : NULL;
6948: const PetscScalar *flip = flips ? flips[p] : NULL;
6949: PetscInt dof, off, d;
6950: const PetscScalar *varr;
6952: PetscCall(PetscSectionGetDof(section, point, &dof));
6953: PetscCall(PetscSectionGetOffset(section, point, &off));
6954: varr = PetscSafePointerPlusOffset(vArray, off);
6955: if (clperm) {
6956: if (perm) {
6957: for (d = 0; d < dof; d++) array[clperm[offset + perm[d]]] = varr[d];
6958: } else {
6959: for (d = 0; d < dof; d++) array[clperm[offset + d]] = varr[d];
6960: }
6961: if (flip) {
6962: for (d = 0; d < dof; d++) array[clperm[offset + d]] *= flip[d];
6963: }
6964: } else {
6965: if (perm) {
6966: for (d = 0; d < dof; d++) array[offset + perm[d]] = varr[d];
6967: } else {
6968: for (d = 0; d < dof; d++) array[offset + d] = varr[d];
6969: }
6970: if (flip) {
6971: for (d = 0; d < dof; d++) array[offset + d] *= flip[d];
6972: }
6973: }
6974: offset += dof;
6975: }
6976: PetscCall(PetscSectionRestorePointSyms(section, numPoints, points, &perms, &flips));
6977: *size = offset;
6978: PetscFunctionReturn(PETSC_SUCCESS);
6979: }
6981: static inline PetscErrorCode DMPlexVecGetClosure_Fields_Static(DM dm, PetscSection section, PetscInt numPoints, const PetscInt points[], PetscInt numFields, const PetscInt clperm[], const PetscScalar vArray[], PetscInt *size, PetscScalar array[])
6982: {
6983: PetscInt offset = 0, f;
6985: PetscFunctionBeginHot;
6986: *size = 0;
6987: for (f = 0; f < numFields; ++f) {
6988: PetscInt p;
6989: const PetscInt **perms = NULL;
6990: const PetscScalar **flips = NULL;
6992: PetscCall(PetscSectionGetFieldPointSyms(section, f, numPoints, points, &perms, &flips));
6993: for (p = 0; p < numPoints; p++) {
6994: const PetscInt point = points[2 * p];
6995: PetscInt fdof, foff, b;
6996: const PetscScalar *varr;
6997: const PetscInt *perm = perms ? perms[p] : NULL;
6998: const PetscScalar *flip = flips ? flips[p] : NULL;
7000: PetscCall(PetscSectionGetFieldDof(section, point, f, &fdof));
7001: PetscCall(PetscSectionGetFieldOffset(section, point, f, &foff));
7002: varr = &vArray[foff];
7003: if (clperm) {
7004: if (perm) {
7005: for (b = 0; b < fdof; b++) array[clperm[offset + perm[b]]] = varr[b];
7006: } else {
7007: for (b = 0; b < fdof; b++) array[clperm[offset + b]] = varr[b];
7008: }
7009: if (flip) {
7010: for (b = 0; b < fdof; b++) array[clperm[offset + b]] *= flip[b];
7011: }
7012: } else {
7013: if (perm) {
7014: for (b = 0; b < fdof; b++) array[offset + perm[b]] = varr[b];
7015: } else {
7016: for (b = 0; b < fdof; b++) array[offset + b] = varr[b];
7017: }
7018: if (flip) {
7019: for (b = 0; b < fdof; b++) array[offset + b] *= flip[b];
7020: }
7021: }
7022: offset += fdof;
7023: }
7024: PetscCall(PetscSectionRestoreFieldPointSyms(section, f, numPoints, points, &perms, &flips));
7025: }
7026: *size = offset;
7027: PetscFunctionReturn(PETSC_SUCCESS);
7028: }
7030: /*@C
7031: DMPlexVecGetOrientedClosure - Get an array of the values on the closure of 'point' with a given orientation, optionally applying the closure permutation.
7033: Not collective
7035: Input Parameters:
7036: + dm - The `DM`
7037: . section - The section describing the layout in `v`, or `NULL` to use the default section
7038: . useClPerm - Flag for whether the provided closure permutation should be applied to the values
7039: . v - The local vector
7040: . point - The point in the `DM`
7041: - ornt - The orientation of the cell, an integer giving the prescription for cone traversal. Typically, this will be 0.
7043: Input/Output Parameters:
7044: + csize - The size of the input values array, or `NULL`; on output the number of values in the closure
7045: - values - An array to use for the values, or *values = `NULL` to have it allocated automatically;
7046: if the user provided `NULL`, it is a borrowed array and should not be freed, use `DMPlexVecRestoreClosure()` to return it
7048: Level: advanced
7050: Notes:
7051: `DMPlexVecGetOrientedClosure()`/`DMPlexVecRestoreClosure()` only allocates the values array if it set to `NULL` in the
7052: calling function. This is because `DMPlexVecGetOrientedClosure()` is typically called in the inner loop of a `Vec` or `Mat`
7053: assembly function, and a user may already have allocated storage for this operation.
7055: Fortran Notes:
7056: The `csize` argument is present in the Fortran binding. Since the Fortran `values` array contains its length information this argument may not be needed.
7057: In that case one may pass `PETSC_NULL_INTEGER` for `csize`.
7059: `values` must be declared with
7060: .vb
7061: PetscScalar,dimension(:),pointer :: values
7062: .ve
7063: and it will be allocated internally by PETSc to hold the values returned
7065: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexVecGetClosure()`, `DMPlexGetCellCoordinates()`, `DMPlexVecRestoreClosure()`, `DMPlexVecSetClosure()`
7066: @*/
7067: PetscErrorCode DMPlexVecGetOrientedClosure(DM dm, PetscSection section, PetscBool useClPerm, Vec v, PetscInt point, PetscInt ornt, PetscInt *csize, PetscScalar *values[])
7068: {
7069: PetscSection clSection;
7070: IS clPoints;
7071: PetscInt *points = NULL;
7072: const PetscInt *clp, *perm = NULL;
7073: PetscInt depth, numFields, numPoints, asize;
7075: PetscFunctionBeginHot;
7077: if (!section) PetscCall(DMGetLocalSection(dm, §ion));
7080: PetscCall(DMPlexGetDepth(dm, &depth));
7081: PetscCall(PetscSectionGetNumFields(section, &numFields));
7082: if (depth == 1 && numFields < 2) {
7083: PetscCall(DMPlexVecGetClosure_Depth1_Static(dm, section, v, point, csize, values));
7084: PetscFunctionReturn(PETSC_SUCCESS);
7085: }
7086: /* Get points */
7087: PetscCall(DMPlexGetCompressedClosure(dm, section, point, ornt, &numPoints, &points, &clSection, &clPoints, &clp));
7088: /* Get sizes */
7089: asize = 0;
7090: for (PetscInt p = 0; p < numPoints * 2; p += 2) {
7091: PetscInt dof;
7092: PetscCall(PetscSectionGetDof(section, points[p], &dof));
7093: asize += dof;
7094: }
7095: if (values) {
7096: const PetscScalar *vArray;
7097: PetscInt size;
7099: if (*values) {
7100: PetscCheck(*csize >= asize, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Provided array size %" PetscInt_FMT " not sufficient to hold closure size %" PetscInt_FMT, *csize, asize);
7101: } else PetscCall(DMGetWorkArray(dm, asize, MPIU_SCALAR, values));
7102: if (useClPerm) PetscCall(PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject)dm, depth, asize, &perm));
7103: PetscCall(VecGetArrayRead(v, &vArray));
7104: /* Get values */
7105: if (numFields > 0) PetscCall(DMPlexVecGetClosure_Fields_Static(dm, section, numPoints, points, numFields, perm, vArray, &size, *values));
7106: else PetscCall(DMPlexVecGetClosure_Static(dm, section, numPoints, points, perm, vArray, &size, *values));
7107: PetscCheck(asize == size, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Section size %" PetscInt_FMT " does not match Vec closure size %" PetscInt_FMT, asize, size);
7108: /* Cleanup array */
7109: PetscCall(VecRestoreArrayRead(v, &vArray));
7110: }
7111: if (csize) *csize = asize;
7112: /* Cleanup points */
7113: PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp));
7114: PetscFunctionReturn(PETSC_SUCCESS);
7115: }
7117: /*@C
7118: DMPlexVecGetClosure - Get an array of the values on the closure of 'point'
7120: Not collective
7122: Input Parameters:
7123: + dm - The `DM`
7124: . section - The section describing the layout in `v`, or `NULL` to use the default section
7125: . v - The local vector
7126: - point - The point in the `DM`
7128: Input/Output Parameters:
7129: + csize - The size of the input values array, or `NULL`; on output the number of values in the closure
7130: - values - An array to use for the values, or *values = `NULL` to have it allocated automatically;
7131: if the user provided `NULL`, it is a borrowed array and should not be freed, use `DMPlexVecRestoreClosure()` to return it
7133: Level: intermediate
7135: Notes:
7136: This is used for getting the all values in a `Vec` in the closure of a mesh point.
7137: To get only the values in the closure of a mesh point at a specific depth (for example, at mesh vertices), use `DMPlexVecGetClosureAtDepth()`.
7139: `DMPlexVecGetClosure()`/`DMPlexVecRestoreClosure()` only allocates the values array if it set to `NULL` in the
7140: calling function. This is because `DMPlexVecGetClosure()` is typically called in the inner loop of a `Vec` or `Mat`
7141: assembly function, and a user may already have allocated storage for this operation.
7143: A typical use could be
7144: .vb
7145: values = NULL;
7146: PetscCall(DMPlexVecGetClosure(dm, NULL, v, p, &clSize, &values));
7147: for (cl = 0; cl < clSize; ++cl) {
7148: <Compute on closure>
7149: }
7150: PetscCall(DMPlexVecRestoreClosure(dm, NULL, v, p, &clSize, &values));
7151: .ve
7152: or
7153: .vb
7154: PetscMalloc1(clMaxSize, &values);
7155: for (p = pStart; p < pEnd; ++p) {
7156: clSize = clMaxSize;
7157: PetscCall(DMPlexVecGetClosure(dm, NULL, v, p, &clSize, &values));
7158: for (cl = 0; cl < clSize; ++cl) {
7159: <Compute on closure>
7160: }
7161: }
7162: PetscFree(values);
7163: .ve
7165: Fortran Notes:
7166: The `csize` argument is present in the Fortran binding. Since the Fortran `values` array contains its length information this argument may not be needed.
7167: In that case one may pass `PETSC_NULL_INTEGER` for `csize`.
7169: `values` must be declared with
7170: .vb
7171: PetscScalar,dimension(:),pointer :: values
7172: .ve
7173: and it will be allocated internally by PETSc to hold the values returned
7175: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexVecGetClosureAtDepth()`, `DMPlexVecRestoreClosure()`, `DMPlexVecSetClosure()`, `DMPlexMatSetClosure()`
7176: @*/
7177: PetscErrorCode DMPlexVecGetClosure(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
7178: {
7179: PetscFunctionBeginHot;
7180: PetscCall(DMPlexVecGetOrientedClosure(dm, section, PETSC_TRUE, v, point, 0, csize, values));
7181: PetscFunctionReturn(PETSC_SUCCESS);
7182: }
7184: /*@C
7185: DMPlexVecGetClosureAtDepth - Get an array of the values on the closure of 'point' that are at a specific depth
7187: Not collective
7189: Input Parameters:
7190: + dm - The `DM`
7191: . section - The section describing the layout in `v`, or `NULL` to use the default section
7192: . v - The local vector
7193: . depth - The depth of mesh points that should be returned
7194: - point - The point in the `DM`
7196: Input/Output Parameters:
7197: + csize - The size of the input values array, or `NULL`; on output the number of values in the closure
7198: - values - An array to use for the values, or *values = `NULL` to have it allocated automatically;
7199: if the user provided `NULL`, it is a borrowed array and should not be freed, use `DMPlexVecRestoreClosure()` to return it
7201: Level: intermediate
7203: Notes:
7204: This is used for getting the values in a `Vec` associated with specific mesh points.
7205: For example, to get only the values at mesh vertices, pass `depth=0`. To get all the values in the closure of a mesh point, use `DMPlexVecGetClosure()`.
7207: `DMPlexVecGetClosureAtDepth()`/`DMPlexVecRestoreClosure()` only allocates the values array if it set to `NULL` in the
7208: calling function. This is because `DMPlexVecGetClosureAtDepth()` is typically called in the inner loop of a `Vec` or `Mat`
7209: assembly function, and a user may already have allocated storage for this operation.
7211: A typical use could be
7212: .vb
7213: values = NULL;
7214: PetscCall(DMPlexVecGetClosureAtDepth(dm, NULL, v, p, depth, &clSize, &values));
7215: for (cl = 0; cl < clSize; ++cl) {
7216: <Compute on closure>
7217: }
7218: PetscCall(DMPlexVecRestoreClosure(dm, NULL, v, p, &clSize, &values));
7219: .ve
7220: or
7221: .vb
7222: PetscMalloc1(clMaxSize, &values);
7223: for (p = pStart; p < pEnd; ++p) {
7224: clSize = clMaxSize;
7225: PetscCall(DMPlexVecGetClosureAtDepth(dm, NULL, v, p, depth, &clSize, &values));
7226: for (cl = 0; cl < clSize; ++cl) {
7227: <Compute on closure>
7228: }
7229: }
7230: PetscFree(values);
7231: .ve
7233: Fortran Notes:
7234: The `csize` argument is present in the Fortran binding. Since the Fortran `values` array contains its length information this argument may not be needed.
7235: In that case one may pass `PETSC_NULL_INTEGER` for `csize`.
7237: `values` must be declared with
7238: .vb
7239: PetscScalar,dimension(:),pointer :: values
7240: .ve
7241: and it will be allocated internally by PETSc to hold the values returned
7243: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexVecGetClosure()`, `DMPlexVecRestoreClosure()`, `DMPlexVecSetClosure()`, `DMPlexMatSetClosure()`
7244: @*/
7245: PetscErrorCode DMPlexVecGetClosureAtDepth(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt depth, PetscInt *csize, PetscScalar *values[])
7246: {
7247: DMLabel depthLabel;
7248: PetscSection clSection;
7249: IS clPoints;
7250: PetscScalar *array;
7251: const PetscScalar *vArray;
7252: PetscInt *points = NULL;
7253: const PetscInt *clp, *perm = NULL;
7254: PetscInt mdepth, numFields, numPoints, Np = 0, p, clsize, size;
7256: PetscFunctionBeginHot;
7258: if (!section) PetscCall(DMGetLocalSection(dm, §ion));
7261: PetscCall(DMPlexGetDepth(dm, &mdepth));
7262: PetscCall(DMPlexGetDepthLabel(dm, &depthLabel));
7263: PetscCall(PetscSectionGetNumFields(section, &numFields));
7264: if (mdepth == 1 && numFields < 2) {
7265: PetscCall(DMPlexVecGetClosure_Depth1_Static(dm, section, v, point, csize, values));
7266: PetscFunctionReturn(PETSC_SUCCESS);
7267: }
7268: /* Get points */
7269: PetscCall(DMPlexGetCompressedClosure(dm, section, point, 0, &numPoints, &points, &clSection, &clPoints, &clp));
7270: for (clsize = 0, p = 0; p < Np; p++) {
7271: PetscInt dof;
7272: PetscCall(PetscSectionGetDof(section, points[2 * p], &dof));
7273: clsize += dof;
7274: }
7275: PetscCall(PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject)dm, depth, clsize, &perm));
7276: /* Filter points */
7277: for (p = 0; p < numPoints * 2; p += 2) {
7278: PetscInt dep;
7280: PetscCall(DMLabelGetValue(depthLabel, points[p], &dep));
7281: if (dep != depth) continue;
7282: points[Np * 2 + 0] = points[p];
7283: points[Np * 2 + 1] = points[p + 1];
7284: ++Np;
7285: }
7286: /* Get array */
7287: if (!values || !*values) {
7288: PetscInt asize = 0, dof;
7290: for (p = 0; p < Np * 2; p += 2) {
7291: PetscCall(PetscSectionGetDof(section, points[p], &dof));
7292: asize += dof;
7293: }
7294: if (!values) {
7295: PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp));
7296: if (csize) *csize = asize;
7297: PetscFunctionReturn(PETSC_SUCCESS);
7298: }
7299: PetscCall(DMGetWorkArray(dm, asize, MPIU_SCALAR, &array));
7300: } else {
7301: array = *values;
7302: }
7303: PetscCall(VecGetArrayRead(v, &vArray));
7304: /* Get values */
7305: if (numFields > 0) PetscCall(DMPlexVecGetClosure_Fields_Static(dm, section, Np, points, numFields, perm, vArray, &size, array));
7306: else PetscCall(DMPlexVecGetClosure_Static(dm, section, Np, points, perm, vArray, &size, array));
7307: /* Cleanup points */
7308: PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp));
7309: /* Cleanup array */
7310: PetscCall(VecRestoreArrayRead(v, &vArray));
7311: if (!*values) {
7312: if (csize) *csize = size;
7313: *values = array;
7314: } else {
7315: PetscCheck(size <= *csize, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Size of input array %" PetscInt_FMT " < actual size %" PetscInt_FMT, *csize, size);
7316: *csize = size;
7317: }
7318: PetscFunctionReturn(PETSC_SUCCESS);
7319: }
7321: /*@C
7322: DMPlexVecRestoreClosure - Restore the array of the values on the closure of 'point' obtained with `DMPlexVecGetClosure()`
7324: Not collective
7326: Input Parameters:
7327: + dm - The `DM`
7328: . section - The section describing the layout in `v`, or `NULL` to use the default section
7329: . v - The local vector
7330: . point - The point in the `DM`
7331: . csize - The number of values in the closure, or `NULL`
7332: - values - The array of values
7334: Level: intermediate
7336: Note:
7337: The array values are discarded and not copied back into `v`. In order to copy values back to `v`, use `DMPlexVecSetClosure()`
7339: Fortran Note:
7340: The `csize` argument is present in the Fortran binding. Since the Fortran `values` array contains its length information this argument may not be needed.
7341: In that case one may pass `PETSC_NULL_INTEGER` for `csize`.
7343: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexVecGetClosure()`, `DMPlexVecSetClosure()`, `DMPlexMatSetClosure()`
7344: @*/
7345: PetscErrorCode DMPlexVecRestoreClosure(DM dm, PetscSection section, Vec v, PetscInt point, PetscInt *csize, PetscScalar *values[])
7346: {
7347: PetscInt size = 0;
7349: PetscFunctionBegin;
7350: /* Should work without recalculating size */
7351: PetscCall(DMRestoreWorkArray(dm, size, MPIU_SCALAR, (void *)values));
7352: *values = NULL;
7353: PetscFunctionReturn(PETSC_SUCCESS);
7354: }
7356: static inline void add(PetscScalar *x, PetscScalar y)
7357: {
7358: *x += y;
7359: }
7360: static inline void insert(PetscScalar *x, PetscScalar y)
7361: {
7362: *x = y;
7363: }
7365: static inline PetscErrorCode updatePoint_private(PetscSection section, PetscInt point, PetscInt dof, void (*fuse)(PetscScalar *, PetscScalar), PetscBool setBC, const PetscInt perm[], const PetscScalar flip[], const PetscInt clperm[], const PetscScalar values[], PetscInt offset, PetscScalar array[])
7366: {
7367: PetscInt cdof; /* The number of constraints on this point */
7368: const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
7369: PetscScalar *a;
7370: PetscInt off, cind = 0, k;
7372: PetscFunctionBegin;
7373: PetscCall(PetscSectionGetConstraintDof(section, point, &cdof));
7374: PetscCall(PetscSectionGetOffset(section, point, &off));
7375: a = &array[off];
7376: if (!cdof || setBC) {
7377: if (clperm) {
7378: if (perm) {
7379: for (k = 0; k < dof; ++k) fuse(&a[k], values[clperm[offset + perm[k]]] * (flip ? flip[perm[k]] : 1.));
7380: } else {
7381: for (k = 0; k < dof; ++k) fuse(&a[k], values[clperm[offset + k]] * (flip ? flip[k] : 1.));
7382: }
7383: } else {
7384: if (perm) {
7385: for (k = 0; k < dof; ++k) fuse(&a[k], values[offset + perm[k]] * (flip ? flip[perm[k]] : 1.));
7386: } else {
7387: for (k = 0; k < dof; ++k) fuse(&a[k], values[offset + k] * (flip ? flip[k] : 1.));
7388: }
7389: }
7390: } else {
7391: PetscCall(PetscSectionGetConstraintIndices(section, point, &cdofs));
7392: if (clperm) {
7393: if (perm) {
7394: for (k = 0; k < dof; ++k) {
7395: if ((cind < cdof) && (k == cdofs[cind])) {
7396: ++cind;
7397: continue;
7398: }
7399: fuse(&a[k], values[clperm[offset + perm[k]]] * (flip ? flip[perm[k]] : 1.));
7400: }
7401: } else {
7402: for (k = 0; k < dof; ++k) {
7403: if ((cind < cdof) && (k == cdofs[cind])) {
7404: ++cind;
7405: continue;
7406: }
7407: fuse(&a[k], values[clperm[offset + k]] * (flip ? flip[k] : 1.));
7408: }
7409: }
7410: } else {
7411: if (perm) {
7412: for (k = 0; k < dof; ++k) {
7413: if ((cind < cdof) && (k == cdofs[cind])) {
7414: ++cind;
7415: continue;
7416: }
7417: fuse(&a[k], values[offset + perm[k]] * (flip ? flip[perm[k]] : 1.));
7418: }
7419: } else {
7420: for (k = 0; k < dof; ++k) {
7421: if ((cind < cdof) && (k == cdofs[cind])) {
7422: ++cind;
7423: continue;
7424: }
7425: fuse(&a[k], values[offset + k] * (flip ? flip[k] : 1.));
7426: }
7427: }
7428: }
7429: }
7430: PetscFunctionReturn(PETSC_SUCCESS);
7431: }
7433: static inline PetscErrorCode updatePointBC_private(PetscSection section, PetscInt point, PetscInt dof, void (*fuse)(PetscScalar *, PetscScalar), const PetscInt perm[], const PetscScalar flip[], const PetscInt clperm[], const PetscScalar values[], PetscInt offset, PetscScalar array[])
7434: {
7435: PetscInt cdof; /* The number of constraints on this point */
7436: const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
7437: PetscScalar *a;
7438: PetscInt off, cind = 0, k;
7440: PetscFunctionBegin;
7441: PetscCall(PetscSectionGetConstraintDof(section, point, &cdof));
7442: PetscCall(PetscSectionGetOffset(section, point, &off));
7443: a = &array[off];
7444: if (cdof) {
7445: PetscCall(PetscSectionGetConstraintIndices(section, point, &cdofs));
7446: if (clperm) {
7447: if (perm) {
7448: for (k = 0; k < dof; ++k) {
7449: if ((cind < cdof) && (k == cdofs[cind])) {
7450: fuse(&a[k], values[clperm[offset + perm[k]]] * (flip ? flip[perm[k]] : 1.));
7451: cind++;
7452: }
7453: }
7454: } else {
7455: for (k = 0; k < dof; ++k) {
7456: if ((cind < cdof) && (k == cdofs[cind])) {
7457: fuse(&a[k], values[clperm[offset + k]] * (flip ? flip[k] : 1.));
7458: cind++;
7459: }
7460: }
7461: }
7462: } else {
7463: if (perm) {
7464: for (k = 0; k < dof; ++k) {
7465: if ((cind < cdof) && (k == cdofs[cind])) {
7466: fuse(&a[k], values[offset + perm[k]] * (flip ? flip[perm[k]] : 1.));
7467: cind++;
7468: }
7469: }
7470: } else {
7471: for (k = 0; k < dof; ++k) {
7472: if ((cind < cdof) && (k == cdofs[cind])) {
7473: fuse(&a[k], values[offset + k] * (flip ? flip[k] : 1.));
7474: cind++;
7475: }
7476: }
7477: }
7478: }
7479: }
7480: PetscFunctionReturn(PETSC_SUCCESS);
7481: }
7483: static inline PetscErrorCode updatePointFields_private(PetscSection section, PetscInt point, const PetscInt *perm, const PetscScalar *flip, PetscInt f, void (*fuse)(PetscScalar *, PetscScalar), PetscBool setBC, const PetscInt clperm[], const PetscScalar values[], PetscInt *offset, PetscScalar array[])
7484: {
7485: PetscScalar *a;
7486: PetscInt fdof, foff, fcdof, foffset = *offset;
7487: const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
7488: PetscInt cind = 0, b;
7490: PetscFunctionBegin;
7491: PetscCall(PetscSectionGetFieldDof(section, point, f, &fdof));
7492: PetscCall(PetscSectionGetFieldConstraintDof(section, point, f, &fcdof));
7493: PetscCall(PetscSectionGetFieldOffset(section, point, f, &foff));
7494: a = &array[foff];
7495: if (!fcdof || setBC) {
7496: if (clperm) {
7497: if (perm) {
7498: for (b = 0; b < fdof; b++) fuse(&a[b], values[clperm[foffset + perm[b]]] * (flip ? flip[perm[b]] : 1.));
7499: } else {
7500: for (b = 0; b < fdof; b++) fuse(&a[b], values[clperm[foffset + b]] * (flip ? flip[b] : 1.));
7501: }
7502: } else {
7503: if (perm) {
7504: for (b = 0; b < fdof; b++) fuse(&a[b], values[foffset + perm[b]] * (flip ? flip[perm[b]] : 1.));
7505: } else {
7506: for (b = 0; b < fdof; b++) fuse(&a[b], values[foffset + b] * (flip ? flip[b] : 1.));
7507: }
7508: }
7509: } else {
7510: PetscCall(PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs));
7511: if (clperm) {
7512: if (perm) {
7513: for (b = 0; b < fdof; b++) {
7514: if ((cind < fcdof) && (b == fcdofs[cind])) {
7515: ++cind;
7516: continue;
7517: }
7518: fuse(&a[b], values[clperm[foffset + perm[b]]] * (flip ? flip[perm[b]] : 1.));
7519: }
7520: } else {
7521: for (b = 0; b < fdof; b++) {
7522: if ((cind < fcdof) && (b == fcdofs[cind])) {
7523: ++cind;
7524: continue;
7525: }
7526: fuse(&a[b], values[clperm[foffset + b]] * (flip ? flip[b] : 1.));
7527: }
7528: }
7529: } else {
7530: if (perm) {
7531: for (b = 0; b < fdof; b++) {
7532: if ((cind < fcdof) && (b == fcdofs[cind])) {
7533: ++cind;
7534: continue;
7535: }
7536: fuse(&a[b], values[foffset + perm[b]] * (flip ? flip[perm[b]] : 1.));
7537: }
7538: } else {
7539: for (b = 0; b < fdof; b++) {
7540: if ((cind < fcdof) && (b == fcdofs[cind])) {
7541: ++cind;
7542: continue;
7543: }
7544: fuse(&a[b], values[foffset + b] * (flip ? flip[b] : 1.));
7545: }
7546: }
7547: }
7548: }
7549: *offset += fdof;
7550: PetscFunctionReturn(PETSC_SUCCESS);
7551: }
7553: static inline PetscErrorCode updatePointFieldsBC_private(PetscSection section, PetscInt point, const PetscInt perm[], const PetscScalar flip[], PetscInt f, PetscInt Ncc, const PetscInt comps[], void (*fuse)(PetscScalar *, PetscScalar), const PetscInt clperm[], const PetscScalar values[], PetscInt *offset, PetscScalar array[])
7554: {
7555: PetscScalar *a;
7556: PetscInt fdof, foff, fcdof, foffset = *offset;
7557: const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
7558: PetscInt Nc, cind = 0, ncind = 0, b;
7559: PetscBool ncSet, fcSet;
7561: PetscFunctionBegin;
7562: PetscCall(PetscSectionGetFieldComponents(section, f, &Nc));
7563: PetscCall(PetscSectionGetFieldDof(section, point, f, &fdof));
7564: PetscCall(PetscSectionGetFieldConstraintDof(section, point, f, &fcdof));
7565: PetscCall(PetscSectionGetFieldOffset(section, point, f, &foff));
7566: a = &array[foff];
7567: if (fcdof) {
7568: /* We just override fcdof and fcdofs with Ncc and comps */
7569: PetscCall(PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs));
7570: if (clperm) {
7571: if (perm) {
7572: if (comps) {
7573: for (b = 0; b < fdof; b++) {
7574: ncSet = fcSet = PETSC_FALSE;
7575: if (b % Nc == comps[ncind]) {
7576: ncind = (ncind + 1) % Ncc;
7577: ncSet = PETSC_TRUE;
7578: }
7579: if ((cind < fcdof) && (b == fcdofs[cind])) {
7580: ++cind;
7581: fcSet = PETSC_TRUE;
7582: }
7583: if (ncSet && fcSet) fuse(&a[b], values[clperm[foffset + perm[b]]] * (flip ? flip[perm[b]] : 1.));
7584: }
7585: } else {
7586: for (b = 0; b < fdof; b++) {
7587: if ((cind < fcdof) && (b == fcdofs[cind])) {
7588: fuse(&a[b], values[clperm[foffset + perm[b]]] * (flip ? flip[perm[b]] : 1.));
7589: ++cind;
7590: }
7591: }
7592: }
7593: } else {
7594: if (comps) {
7595: for (b = 0; b < fdof; b++) {
7596: ncSet = fcSet = PETSC_FALSE;
7597: if (b % Nc == comps[ncind]) {
7598: ncind = (ncind + 1) % Ncc;
7599: ncSet = PETSC_TRUE;
7600: }
7601: if ((cind < fcdof) && (b == fcdofs[cind])) {
7602: ++cind;
7603: fcSet = PETSC_TRUE;
7604: }
7605: if (ncSet && fcSet) fuse(&a[b], values[clperm[foffset + b]] * (flip ? flip[b] : 1.));
7606: }
7607: } else {
7608: for (b = 0; b < fdof; b++) {
7609: if ((cind < fcdof) && (b == fcdofs[cind])) {
7610: fuse(&a[b], values[clperm[foffset + b]] * (flip ? flip[b] : 1.));
7611: ++cind;
7612: }
7613: }
7614: }
7615: }
7616: } else {
7617: if (perm) {
7618: if (comps) {
7619: for (b = 0; b < fdof; b++) {
7620: ncSet = fcSet = PETSC_FALSE;
7621: if (b % Nc == comps[ncind]) {
7622: ncind = (ncind + 1) % Ncc;
7623: ncSet = PETSC_TRUE;
7624: }
7625: if ((cind < fcdof) && (b == fcdofs[cind])) {
7626: ++cind;
7627: fcSet = PETSC_TRUE;
7628: }
7629: if (ncSet && fcSet) fuse(&a[b], values[foffset + perm[b]] * (flip ? flip[perm[b]] : 1.));
7630: }
7631: } else {
7632: for (b = 0; b < fdof; b++) {
7633: if ((cind < fcdof) && (b == fcdofs[cind])) {
7634: fuse(&a[b], values[foffset + perm[b]] * (flip ? flip[perm[b]] : 1.));
7635: ++cind;
7636: }
7637: }
7638: }
7639: } else {
7640: if (comps) {
7641: for (b = 0; b < fdof; b++) {
7642: ncSet = fcSet = PETSC_FALSE;
7643: if (b % Nc == comps[ncind]) {
7644: ncind = (ncind + 1) % Ncc;
7645: ncSet = PETSC_TRUE;
7646: }
7647: if ((cind < fcdof) && (b == fcdofs[cind])) {
7648: ++cind;
7649: fcSet = PETSC_TRUE;
7650: }
7651: if (ncSet && fcSet) fuse(&a[b], values[foffset + b] * (flip ? flip[b] : 1.));
7652: }
7653: } else {
7654: for (b = 0; b < fdof; b++) {
7655: if ((cind < fcdof) && (b == fcdofs[cind])) {
7656: fuse(&a[b], values[foffset + b] * (flip ? flip[b] : 1.));
7657: ++cind;
7658: }
7659: }
7660: }
7661: }
7662: }
7663: }
7664: *offset += fdof;
7665: PetscFunctionReturn(PETSC_SUCCESS);
7666: }
7668: static inline PetscErrorCode DMPlexVecSetClosure_Depth1_Static(DM dm, PetscSection section, Vec v, PetscInt point, const PetscScalar values[], InsertMode mode)
7669: {
7670: PetscScalar *array;
7671: const PetscInt *cone, *coneO;
7672: PetscInt pStart, pEnd, p, numPoints, off, dof;
7674: PetscFunctionBeginHot;
7675: PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
7676: PetscCall(DMPlexGetConeSize(dm, point, &numPoints));
7677: PetscCall(DMPlexGetCone(dm, point, &cone));
7678: PetscCall(DMPlexGetConeOrientation(dm, point, &coneO));
7679: PetscCall(VecGetArray(v, &array));
7680: for (p = 0, off = 0; p <= numPoints; ++p, off += dof) {
7681: const PetscInt cp = !p ? point : cone[p - 1];
7682: const PetscInt o = !p ? 0 : coneO[p - 1];
7684: if ((cp < pStart) || (cp >= pEnd)) {
7685: dof = 0;
7686: continue;
7687: }
7688: PetscCall(PetscSectionGetDof(section, cp, &dof));
7689: /* ADD_VALUES */
7690: {
7691: const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
7692: PetscScalar *a;
7693: PetscInt cdof, coff, cind = 0, k;
7695: PetscCall(PetscSectionGetConstraintDof(section, cp, &cdof));
7696: PetscCall(PetscSectionGetOffset(section, cp, &coff));
7697: a = &array[coff];
7698: if (!cdof) {
7699: if (o >= 0) {
7700: for (k = 0; k < dof; ++k) a[k] += values[off + k];
7701: } else {
7702: for (k = 0; k < dof; ++k) a[k] += values[off + dof - k - 1];
7703: }
7704: } else {
7705: PetscCall(PetscSectionGetConstraintIndices(section, cp, &cdofs));
7706: if (o >= 0) {
7707: for (k = 0; k < dof; ++k) {
7708: if ((cind < cdof) && (k == cdofs[cind])) {
7709: ++cind;
7710: continue;
7711: }
7712: a[k] += values[off + k];
7713: }
7714: } else {
7715: for (k = 0; k < dof; ++k) {
7716: if ((cind < cdof) && (k == cdofs[cind])) {
7717: ++cind;
7718: continue;
7719: }
7720: a[k] += values[off + dof - k - 1];
7721: }
7722: }
7723: }
7724: }
7725: }
7726: PetscCall(VecRestoreArray(v, &array));
7727: PetscFunctionReturn(PETSC_SUCCESS);
7728: }
7730: /*@C
7731: DMPlexVecSetClosure - Set an array of the values on the closure of `point`
7733: Not collective
7735: Input Parameters:
7736: + dm - The `DM`
7737: . section - The section describing the layout in `v`, or `NULL` to use the default section
7738: . v - The local vector
7739: . point - The point in the `DM`
7740: . values - The array of values
7741: - mode - The insert mode. One of `INSERT_ALL_VALUES`, `ADD_ALL_VALUES`, `INSERT_VALUES`, `ADD_VALUES`, `INSERT_BC_VALUES`, and `ADD_BC_VALUES`,
7742: where `INSERT_ALL_VALUES` and `ADD_ALL_VALUES` also overwrite boundary conditions.
7744: Level: intermediate
7746: Note:
7747: Usually the input arrays were obtained with `DMPlexVecGetClosure()`
7749: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexVecGetClosure()`, `DMPlexMatSetClosure()`
7750: @*/
7751: PetscErrorCode DMPlexVecSetClosure(DM dm, PetscSection section, Vec v, PetscInt point, const PetscScalar values[], InsertMode mode)
7752: {
7753: PetscSection clSection;
7754: IS clPoints;
7755: PetscScalar *array;
7756: PetscInt *points = NULL;
7757: const PetscInt *clp, *clperm = NULL;
7758: PetscInt depth, numFields, numPoints, p, clsize;
7760: PetscFunctionBeginHot;
7762: if (!section) PetscCall(DMGetLocalSection(dm, §ion));
7765: PetscCall(DMPlexGetDepth(dm, &depth));
7766: PetscCall(PetscSectionGetNumFields(section, &numFields));
7767: if (depth == 1 && numFields < 2 && mode == ADD_VALUES) {
7768: PetscCall(DMPlexVecSetClosure_Depth1_Static(dm, section, v, point, values, mode));
7769: PetscFunctionReturn(PETSC_SUCCESS);
7770: }
7771: /* Get points */
7772: PetscCall(DMPlexGetCompressedClosure(dm, section, point, 0, &numPoints, &points, &clSection, &clPoints, &clp));
7773: for (clsize = 0, p = 0; p < numPoints; p++) {
7774: PetscInt dof;
7775: PetscCall(PetscSectionGetDof(section, points[2 * p], &dof));
7776: clsize += dof;
7777: }
7778: PetscCall(PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject)dm, depth, clsize, &clperm));
7779: /* Get array */
7780: PetscCall(VecGetArray(v, &array));
7781: /* Get values */
7782: if (numFields > 0) {
7783: PetscInt offset = 0, f;
7784: for (f = 0; f < numFields; ++f) {
7785: const PetscInt **perms = NULL;
7786: const PetscScalar **flips = NULL;
7788: PetscCall(PetscSectionGetFieldPointSyms(section, f, numPoints, points, &perms, &flips));
7789: switch (mode) {
7790: case INSERT_VALUES:
7791: for (p = 0; p < numPoints; p++) {
7792: const PetscInt point = points[2 * p];
7793: const PetscInt *perm = perms ? perms[p] : NULL;
7794: const PetscScalar *flip = flips ? flips[p] : NULL;
7795: PetscCall(updatePointFields_private(section, point, perm, flip, f, insert, PETSC_FALSE, clperm, values, &offset, array));
7796: }
7797: break;
7798: case INSERT_ALL_VALUES:
7799: for (p = 0; p < numPoints; p++) {
7800: const PetscInt point = points[2 * p];
7801: const PetscInt *perm = perms ? perms[p] : NULL;
7802: const PetscScalar *flip = flips ? flips[p] : NULL;
7803: PetscCall(updatePointFields_private(section, point, perm, flip, f, insert, PETSC_TRUE, clperm, values, &offset, array));
7804: }
7805: break;
7806: case INSERT_BC_VALUES:
7807: for (p = 0; p < numPoints; p++) {
7808: const PetscInt point = points[2 * p];
7809: const PetscInt *perm = perms ? perms[p] : NULL;
7810: const PetscScalar *flip = flips ? flips[p] : NULL;
7811: PetscCall(updatePointFieldsBC_private(section, point, perm, flip, f, -1, NULL, insert, clperm, values, &offset, array));
7812: }
7813: break;
7814: case ADD_VALUES:
7815: for (p = 0; p < numPoints; p++) {
7816: const PetscInt point = points[2 * p];
7817: const PetscInt *perm = perms ? perms[p] : NULL;
7818: const PetscScalar *flip = flips ? flips[p] : NULL;
7819: PetscCall(updatePointFields_private(section, point, perm, flip, f, add, PETSC_FALSE, clperm, values, &offset, array));
7820: }
7821: break;
7822: case ADD_ALL_VALUES:
7823: for (p = 0; p < numPoints; p++) {
7824: const PetscInt point = points[2 * p];
7825: const PetscInt *perm = perms ? perms[p] : NULL;
7826: const PetscScalar *flip = flips ? flips[p] : NULL;
7827: PetscCall(updatePointFields_private(section, point, perm, flip, f, add, PETSC_TRUE, clperm, values, &offset, array));
7828: }
7829: break;
7830: case ADD_BC_VALUES:
7831: for (p = 0; p < numPoints; p++) {
7832: const PetscInt point = points[2 * p];
7833: const PetscInt *perm = perms ? perms[p] : NULL;
7834: const PetscScalar *flip = flips ? flips[p] : NULL;
7835: PetscCall(updatePointFieldsBC_private(section, point, perm, flip, f, -1, NULL, add, clperm, values, &offset, array));
7836: }
7837: break;
7838: default:
7839: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
7840: }
7841: PetscCall(PetscSectionRestoreFieldPointSyms(section, f, numPoints, points, &perms, &flips));
7842: }
7843: } else {
7844: PetscInt dof, off;
7845: const PetscInt **perms = NULL;
7846: const PetscScalar **flips = NULL;
7848: PetscCall(PetscSectionGetPointSyms(section, numPoints, points, &perms, &flips));
7849: switch (mode) {
7850: case INSERT_VALUES:
7851: for (p = 0, off = 0; p < numPoints; p++, off += dof) {
7852: const PetscInt point = points[2 * p];
7853: const PetscInt *perm = perms ? perms[p] : NULL;
7854: const PetscScalar *flip = flips ? flips[p] : NULL;
7855: PetscCall(PetscSectionGetDof(section, point, &dof));
7856: PetscCall(updatePoint_private(section, point, dof, insert, PETSC_FALSE, perm, flip, clperm, values, off, array));
7857: }
7858: break;
7859: case INSERT_ALL_VALUES:
7860: for (p = 0, off = 0; p < numPoints; p++, off += dof) {
7861: const PetscInt point = points[2 * p];
7862: const PetscInt *perm = perms ? perms[p] : NULL;
7863: const PetscScalar *flip = flips ? flips[p] : NULL;
7864: PetscCall(PetscSectionGetDof(section, point, &dof));
7865: PetscCall(updatePoint_private(section, point, dof, insert, PETSC_TRUE, perm, flip, clperm, values, off, array));
7866: }
7867: break;
7868: case INSERT_BC_VALUES:
7869: for (p = 0, off = 0; p < numPoints; p++, off += dof) {
7870: const PetscInt point = points[2 * p];
7871: const PetscInt *perm = perms ? perms[p] : NULL;
7872: const PetscScalar *flip = flips ? flips[p] : NULL;
7873: PetscCall(PetscSectionGetDof(section, point, &dof));
7874: PetscCall(updatePointBC_private(section, point, dof, insert, perm, flip, clperm, values, off, array));
7875: }
7876: break;
7877: case ADD_VALUES:
7878: for (p = 0, off = 0; p < numPoints; p++, off += dof) {
7879: const PetscInt point = points[2 * p];
7880: const PetscInt *perm = perms ? perms[p] : NULL;
7881: const PetscScalar *flip = flips ? flips[p] : NULL;
7882: PetscCall(PetscSectionGetDof(section, point, &dof));
7883: PetscCall(updatePoint_private(section, point, dof, add, PETSC_FALSE, perm, flip, clperm, values, off, array));
7884: }
7885: break;
7886: case ADD_ALL_VALUES:
7887: for (p = 0, off = 0; p < numPoints; p++, off += dof) {
7888: const PetscInt point = points[2 * p];
7889: const PetscInt *perm = perms ? perms[p] : NULL;
7890: const PetscScalar *flip = flips ? flips[p] : NULL;
7891: PetscCall(PetscSectionGetDof(section, point, &dof));
7892: PetscCall(updatePoint_private(section, point, dof, add, PETSC_TRUE, perm, flip, clperm, values, off, array));
7893: }
7894: break;
7895: case ADD_BC_VALUES:
7896: for (p = 0, off = 0; p < numPoints; p++, off += dof) {
7897: const PetscInt point = points[2 * p];
7898: const PetscInt *perm = perms ? perms[p] : NULL;
7899: const PetscScalar *flip = flips ? flips[p] : NULL;
7900: PetscCall(PetscSectionGetDof(section, point, &dof));
7901: PetscCall(updatePointBC_private(section, point, dof, add, perm, flip, clperm, values, off, array));
7902: }
7903: break;
7904: default:
7905: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
7906: }
7907: PetscCall(PetscSectionRestorePointSyms(section, numPoints, points, &perms, &flips));
7908: }
7909: /* Cleanup points */
7910: PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp));
7911: /* Cleanup array */
7912: PetscCall(VecRestoreArray(v, &array));
7913: PetscFunctionReturn(PETSC_SUCCESS);
7914: }
7916: /* Check whether the given point is in the label. If not, update the offset to skip this point */
7917: static inline PetscErrorCode CheckPoint_Private(DMLabel label, PetscInt labelId, PetscSection section, PetscInt point, PetscInt f, PetscInt *offset, PetscBool *contains)
7918: {
7919: PetscFunctionBegin;
7920: *contains = PETSC_TRUE;
7921: if (label) {
7922: PetscInt fdof;
7924: PetscCall(DMLabelStratumHasPoint(label, labelId, point, contains));
7925: if (!*contains) {
7926: PetscCall(PetscSectionGetFieldDof(section, point, f, &fdof));
7927: *offset += fdof;
7928: PetscFunctionReturn(PETSC_SUCCESS);
7929: }
7930: }
7931: PetscFunctionReturn(PETSC_SUCCESS);
7932: }
7934: /* Unlike DMPlexVecSetClosure(), this uses plex-native closure permutation, not a user-specified permutation such as DMPlexSetClosurePermutationTensor(). */
7935: PetscErrorCode DMPlexVecSetFieldClosure_Internal(DM dm, PetscSection section, Vec v, PetscBool fieldActive[], PetscInt point, PetscInt Ncc, const PetscInt comps[], DMLabel label, PetscInt labelId, const PetscScalar values[], InsertMode mode)
7936: {
7937: PetscSection clSection;
7938: IS clPoints;
7939: PetscScalar *array;
7940: PetscInt *points = NULL;
7941: const PetscInt *clp;
7942: PetscInt numFields, numPoints, p;
7943: PetscInt offset = 0, f;
7945: PetscFunctionBeginHot;
7947: if (!section) PetscCall(DMGetLocalSection(dm, §ion));
7950: PetscCall(PetscSectionGetNumFields(section, &numFields));
7951: /* Get points */
7952: PetscCall(DMPlexGetCompressedClosure(dm, section, point, 0, &numPoints, &points, &clSection, &clPoints, &clp));
7953: /* Get array */
7954: PetscCall(VecGetArray(v, &array));
7955: /* Get values */
7956: for (f = 0; f < numFields; ++f) {
7957: const PetscInt **perms = NULL;
7958: const PetscScalar **flips = NULL;
7959: PetscBool contains;
7961: if (!fieldActive[f]) {
7962: for (p = 0; p < numPoints * 2; p += 2) {
7963: PetscInt fdof;
7964: PetscCall(PetscSectionGetFieldDof(section, points[p], f, &fdof));
7965: offset += fdof;
7966: }
7967: continue;
7968: }
7969: PetscCall(PetscSectionGetFieldPointSyms(section, f, numPoints, points, &perms, &flips));
7970: switch (mode) {
7971: case INSERT_VALUES:
7972: for (p = 0; p < numPoints; p++) {
7973: const PetscInt point = points[2 * p];
7974: const PetscInt *perm = perms ? perms[p] : NULL;
7975: const PetscScalar *flip = flips ? flips[p] : NULL;
7976: PetscCall(CheckPoint_Private(label, labelId, section, point, f, &offset, &contains));
7977: if (!contains) continue;
7978: PetscCall(updatePointFields_private(section, point, perm, flip, f, insert, PETSC_FALSE, NULL, values, &offset, array));
7979: }
7980: break;
7981: case INSERT_ALL_VALUES:
7982: for (p = 0; p < numPoints; p++) {
7983: const PetscInt point = points[2 * p];
7984: const PetscInt *perm = perms ? perms[p] : NULL;
7985: const PetscScalar *flip = flips ? flips[p] : NULL;
7986: PetscCall(CheckPoint_Private(label, labelId, section, point, f, &offset, &contains));
7987: if (!contains) continue;
7988: PetscCall(updatePointFields_private(section, point, perm, flip, f, insert, PETSC_TRUE, NULL, values, &offset, array));
7989: }
7990: break;
7991: case INSERT_BC_VALUES:
7992: for (p = 0; p < numPoints; p++) {
7993: const PetscInt point = points[2 * p];
7994: const PetscInt *perm = perms ? perms[p] : NULL;
7995: const PetscScalar *flip = flips ? flips[p] : NULL;
7996: PetscCall(CheckPoint_Private(label, labelId, section, point, f, &offset, &contains));
7997: if (!contains) continue;
7998: PetscCall(updatePointFieldsBC_private(section, point, perm, flip, f, Ncc, comps, insert, NULL, values, &offset, array));
7999: }
8000: break;
8001: case ADD_VALUES:
8002: for (p = 0; p < numPoints; p++) {
8003: const PetscInt point = points[2 * p];
8004: const PetscInt *perm = perms ? perms[p] : NULL;
8005: const PetscScalar *flip = flips ? flips[p] : NULL;
8006: PetscCall(CheckPoint_Private(label, labelId, section, point, f, &offset, &contains));
8007: if (!contains) continue;
8008: PetscCall(updatePointFields_private(section, point, perm, flip, f, add, PETSC_FALSE, NULL, values, &offset, array));
8009: }
8010: break;
8011: case ADD_ALL_VALUES:
8012: for (p = 0; p < numPoints; p++) {
8013: const PetscInt point = points[2 * p];
8014: const PetscInt *perm = perms ? perms[p] : NULL;
8015: const PetscScalar *flip = flips ? flips[p] : NULL;
8016: PetscCall(CheckPoint_Private(label, labelId, section, point, f, &offset, &contains));
8017: if (!contains) continue;
8018: PetscCall(updatePointFields_private(section, point, perm, flip, f, add, PETSC_TRUE, NULL, values, &offset, array));
8019: }
8020: break;
8021: default:
8022: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insert mode %d", mode);
8023: }
8024: PetscCall(PetscSectionRestoreFieldPointSyms(section, f, numPoints, points, &perms, &flips));
8025: }
8026: /* Cleanup points */
8027: PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &numPoints, &points, &clSection, &clPoints, &clp));
8028: /* Cleanup array */
8029: PetscCall(VecRestoreArray(v, &array));
8030: PetscFunctionReturn(PETSC_SUCCESS);
8031: }
8033: static PetscErrorCode DMPlexPrintMatSetValues(PetscViewer viewer, Mat A, PetscInt point, PetscInt numRIndices, const PetscInt rindices[], PetscInt numCIndices, const PetscInt cindices[], const PetscScalar values[])
8034: {
8035: PetscMPIInt rank;
8037: PetscFunctionBegin;
8038: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank));
8039: PetscCall(PetscViewerASCIIPrintf(viewer, "[%d]mat for point %" PetscInt_FMT "\n", rank, point));
8040: for (PetscInt i = 0; i < numRIndices; i++) PetscCall(PetscViewerASCIIPrintf(viewer, "[%d]mat row indices[%" PetscInt_FMT "] = %" PetscInt_FMT "\n", rank, i, rindices[i]));
8041: for (PetscInt i = 0; i < numCIndices; i++) PetscCall(PetscViewerASCIIPrintf(viewer, "[%d]mat col indices[%" PetscInt_FMT "] = %" PetscInt_FMT "\n", rank, i, cindices[i]));
8042: numCIndices = numCIndices ? numCIndices : numRIndices;
8043: if (!values) PetscFunctionReturn(PETSC_SUCCESS);
8044: for (PetscInt i = 0; i < numRIndices; i++) {
8045: PetscCall(PetscViewerASCIIPrintf(viewer, "[%d]", rank));
8046: for (PetscInt j = 0; j < numCIndices; j++) {
8047: #if defined(PETSC_USE_COMPLEX)
8048: PetscCall(PetscViewerASCIIPrintf(viewer, " (%g,%g)", (double)PetscRealPart(values[i * numCIndices + j]), (double)PetscImaginaryPart(values[i * numCIndices + j])));
8049: #else
8050: PetscCall(PetscViewerASCIIPrintf(viewer, " %g", (double)values[i * numCIndices + j]));
8051: #endif
8052: }
8053: PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
8054: }
8055: PetscFunctionReturn(PETSC_SUCCESS);
8056: }
8058: /*
8059: DMPlexGetIndicesPoint_Internal - Add the indices for dofs on a point to an index array
8061: Input Parameters:
8062: + section - The section for this data layout
8063: . islocal - Is the section (and thus indices being requested) local or global?
8064: . point - The point contributing dofs with these indices
8065: . off - The global offset of this point
8066: . loff - The local offset of each field
8067: . setBC - The flag determining whether to include indices of boundary values
8068: . perm - A permutation of the dofs on this point, or NULL
8069: - indperm - A permutation of the entire indices array, or NULL
8071: Output Parameter:
8072: . indices - Indices for dofs on this point
8074: Level: developer
8076: Note: The indices could be local or global, depending on the value of 'off'.
8077: */
8078: PetscErrorCode DMPlexGetIndicesPoint_Internal(PetscSection section, PetscBool islocal, PetscInt point, PetscInt off, PetscInt *loff, PetscBool setBC, const PetscInt perm[], const PetscInt indperm[], PetscInt indices[])
8079: {
8080: PetscInt dof; /* The number of unknowns on this point */
8081: PetscInt cdof; /* The number of constraints on this point */
8082: const PetscInt *cdofs; /* The indices of the constrained dofs on this point */
8083: PetscInt cind = 0, k;
8085: PetscFunctionBegin;
8086: PetscCheck(islocal || !setBC, PetscObjectComm((PetscObject)section), PETSC_ERR_ARG_INCOMP, "setBC incompatible with global indices; use a local section or disable setBC");
8087: PetscCall(PetscSectionGetDof(section, point, &dof));
8088: PetscCall(PetscSectionGetConstraintDof(section, point, &cdof));
8089: if (!cdof || setBC) {
8090: for (k = 0; k < dof; ++k) {
8091: const PetscInt preind = perm ? *loff + perm[k] : *loff + k;
8092: const PetscInt ind = indperm ? indperm[preind] : preind;
8094: indices[ind] = off + k;
8095: }
8096: } else {
8097: PetscCall(PetscSectionGetConstraintIndices(section, point, &cdofs));
8098: for (k = 0; k < dof; ++k) {
8099: const PetscInt preind = perm ? *loff + perm[k] : *loff + k;
8100: const PetscInt ind = indperm ? indperm[preind] : preind;
8102: if ((cind < cdof) && (k == cdofs[cind])) {
8103: /* Insert check for returning constrained indices */
8104: indices[ind] = -(off + k + 1);
8105: ++cind;
8106: } else {
8107: indices[ind] = off + k - (islocal ? 0 : cind);
8108: }
8109: }
8110: }
8111: *loff += dof;
8112: PetscFunctionReturn(PETSC_SUCCESS);
8113: }
8115: /*
8116: DMPlexGetIndicesPointFields_Internal - gets section indices for a point in its canonical ordering.
8118: Input Parameters:
8119: + section - a section (global or local)
8120: - islocal - `PETSC_TRUE` if requesting local indices (i.e., section is local); `PETSC_FALSE` for global
8121: . point - point within section
8122: . off - The offset of this point in the (local or global) indexed space - should match islocal and (usually) the section
8123: . foffs - array of length numFields containing the offset in canonical point ordering (the location in indices) of each field
8124: . setBC - identify constrained (boundary condition) points via involution.
8125: . perms - perms[f][permsoff][:] is a permutation of dofs within each field
8126: . permsoff - offset
8127: - indperm - index permutation
8129: Output Parameter:
8130: . foffs - each entry is incremented by the number of (unconstrained if setBC=FALSE) dofs in that field
8131: . indices - array to hold indices (as defined by section) of each dof associated with point
8133: Notes:
8134: If section is local and setBC=true, there is no distinction between constrained and unconstrained dofs.
8135: If section is local and setBC=false, the indices for constrained points are the involution -(i+1) of their position
8136: in the local vector.
8138: If section is global and setBC=false, the indices for constrained points are negative (and their value is not
8139: significant). It is invalid to call with a global section and setBC=true.
8141: Developer Note:
8142: The section is only used for field layout, so islocal is technically a statement about the offset (off). At some point
8143: in the future, global sections may have fields set, in which case we could pass the global section and obtain the
8144: offset could be obtained from the section instead of passing it explicitly as we do now.
8146: Example:
8147: Suppose a point contains one field with three components, and for which the unconstrained indices are {10, 11, 12}.
8148: When the middle component is constrained, we get the array {10, -12, 12} for (islocal=TRUE, setBC=FALSE).
8149: Note that -12 is the involution of 11, so the user can involute negative indices to recover local indices.
8150: The global vector does not store constrained dofs, so when this function returns global indices, say {110, -112, 111}, the value of -112 is an arbitrary flag that should not be interpreted beyond its sign.
8152: Level: developer
8153: */
8154: PetscErrorCode DMPlexGetIndicesPointFields_Internal(PetscSection section, PetscBool islocal, PetscInt point, PetscInt off, PetscInt foffs[], PetscBool setBC, const PetscInt ***perms, PetscInt permsoff, const PetscInt indperm[], PetscInt indices[])
8155: {
8156: PetscInt numFields, foff, f;
8158: PetscFunctionBegin;
8159: PetscCheck(islocal || !setBC, PetscObjectComm((PetscObject)section), PETSC_ERR_ARG_INCOMP, "setBC incompatible with global indices; use a local section or disable setBC");
8160: PetscCall(PetscSectionGetNumFields(section, &numFields));
8161: for (f = 0, foff = 0; f < numFields; ++f) {
8162: PetscInt fdof, cfdof;
8163: const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
8164: PetscInt cind = 0, b;
8165: const PetscInt *perm = (perms && perms[f]) ? perms[f][permsoff] : NULL;
8167: PetscCall(PetscSectionGetFieldDof(section, point, f, &fdof));
8168: PetscCall(PetscSectionGetFieldConstraintDof(section, point, f, &cfdof));
8169: if (!cfdof || setBC) {
8170: for (b = 0; b < fdof; ++b) {
8171: const PetscInt preind = perm ? foffs[f] + perm[b] : foffs[f] + b;
8172: const PetscInt ind = indperm ? indperm[preind] : preind;
8174: indices[ind] = off + foff + b;
8175: }
8176: } else {
8177: PetscCall(PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs));
8178: for (b = 0; b < fdof; ++b) {
8179: const PetscInt preind = perm ? foffs[f] + perm[b] : foffs[f] + b;
8180: const PetscInt ind = indperm ? indperm[preind] : preind;
8182: if ((cind < cfdof) && (b == fcdofs[cind])) {
8183: indices[ind] = -(off + foff + b + 1);
8184: ++cind;
8185: } else {
8186: indices[ind] = off + foff + b - (islocal ? 0 : cind);
8187: }
8188: }
8189: }
8190: foff += (setBC || islocal ? fdof : (fdof - cfdof));
8191: foffs[f] += fdof;
8192: }
8193: PetscFunctionReturn(PETSC_SUCCESS);
8194: }
8196: /*
8197: This version believes the globalSection offsets for each field, rather than just the point offset
8199: . foffs - The offset into 'indices' for each field, since it is segregated by field
8201: Notes:
8202: The semantics of this function relate to that of setBC=FALSE in DMPlexGetIndicesPointFields_Internal.
8203: Since this function uses global indices, setBC=TRUE would be invalid, so no such argument exists.
8204: */
8205: static PetscErrorCode DMPlexGetIndicesPointFieldsSplit_Internal(PetscSection section, PetscSection globalSection, PetscInt point, PetscInt foffs[], const PetscInt ***perms, PetscInt permsoff, const PetscInt indperm[], PetscInt indices[])
8206: {
8207: PetscInt numFields, foff, f;
8209: PetscFunctionBegin;
8210: PetscCall(PetscSectionGetNumFields(section, &numFields));
8211: for (f = 0; f < numFields; ++f) {
8212: PetscInt fdof, cfdof;
8213: const PetscInt *fcdofs; /* The indices of the constrained dofs for field f on this point */
8214: PetscInt cind = 0, b;
8215: const PetscInt *perm = (perms && perms[f]) ? perms[f][permsoff] : NULL;
8217: PetscCall(PetscSectionGetFieldDof(section, point, f, &fdof));
8218: PetscCall(PetscSectionGetFieldConstraintDof(section, point, f, &cfdof));
8219: PetscCall(PetscSectionGetFieldOffset(globalSection, point, f, &foff));
8220: if (!cfdof) {
8221: for (b = 0; b < fdof; ++b) {
8222: const PetscInt preind = perm ? foffs[f] + perm[b] : foffs[f] + b;
8223: const PetscInt ind = indperm ? indperm[preind] : preind;
8225: indices[ind] = foff + b;
8226: }
8227: } else {
8228: PetscCall(PetscSectionGetFieldConstraintIndices(section, point, f, &fcdofs));
8229: for (b = 0; b < fdof; ++b) {
8230: const PetscInt preind = perm ? foffs[f] + perm[b] : foffs[f] + b;
8231: const PetscInt ind = indperm ? indperm[preind] : preind;
8233: if ((cind < cfdof) && (b == fcdofs[cind])) {
8234: indices[ind] = -(foff + b + 1);
8235: ++cind;
8236: } else {
8237: indices[ind] = foff + b - cind;
8238: }
8239: }
8240: }
8241: foffs[f] += fdof;
8242: }
8243: PetscFunctionReturn(PETSC_SUCCESS);
8244: }
8246: static PetscErrorCode DMPlexAnchorsGetSubMatIndices(PetscInt nPoints, const PetscInt pnts[], PetscSection section, PetscSection cSec, PetscInt tmpIndices[], PetscInt fieldOffsets[], PetscInt indices[], const PetscInt ***perms)
8247: {
8248: PetscInt numFields, sStart, sEnd, cStart, cEnd;
8250: PetscFunctionBegin;
8251: PetscCall(PetscSectionGetNumFields(section, &numFields));
8252: PetscCall(PetscSectionGetChart(section, &sStart, &sEnd));
8253: PetscCall(PetscSectionGetChart(cSec, &cStart, &cEnd));
8254: for (PetscInt p = 0; p < nPoints; p++) {
8255: PetscInt b = pnts[2 * p];
8256: PetscInt bSecDof = 0, bOff;
8257: PetscInt cSecDof = 0;
8258: PetscSection indices_section;
8260: if (b >= sStart && b < sEnd) PetscCall(PetscSectionGetDof(section, b, &bSecDof));
8261: if (!bSecDof) continue;
8262: if (b >= cStart && b < cEnd) PetscCall(PetscSectionGetDof(cSec, b, &cSecDof));
8263: indices_section = cSecDof > 0 ? cSec : section;
8264: if (numFields) {
8265: PetscInt fStart[32], fEnd[32];
8267: fStart[0] = 0;
8268: fEnd[0] = 0;
8269: for (PetscInt f = 0; f < numFields; f++) {
8270: PetscInt fDof = 0;
8272: PetscCall(PetscSectionGetFieldDof(indices_section, b, f, &fDof));
8273: fStart[f + 1] = fStart[f] + fDof;
8274: fEnd[f + 1] = fStart[f + 1];
8275: }
8276: PetscCall(PetscSectionGetOffset(indices_section, b, &bOff));
8277: // only apply permutations on one side
8278: PetscCall(DMPlexGetIndicesPointFields_Internal(indices_section, PETSC_TRUE, b, bOff, fEnd, PETSC_TRUE, perms, perms ? p : -1, NULL, tmpIndices));
8279: for (PetscInt f = 0; f < numFields; f++) {
8280: for (PetscInt i = fStart[f]; i < fEnd[f]; i++) indices[fieldOffsets[f]++] = (cSecDof > 0) ? tmpIndices[i] : -(tmpIndices[i] + 1);
8281: }
8282: } else {
8283: PetscInt bEnd = 0;
8285: PetscCall(PetscSectionGetOffset(indices_section, b, &bOff));
8286: PetscCall(DMPlexGetIndicesPoint_Internal(indices_section, PETSC_TRUE, b, bOff, &bEnd, PETSC_TRUE, (perms && perms[0]) ? perms[0][p] : NULL, NULL, tmpIndices));
8288: for (PetscInt i = 0; i < bEnd; i++) indices[fieldOffsets[0]++] = (cSecDof > 0) ? tmpIndices[i] : -(tmpIndices[i] + 1);
8289: }
8290: }
8291: PetscFunctionReturn(PETSC_SUCCESS);
8292: }
8294: PETSC_INTERN PetscErrorCode DMPlexAnchorsGetSubMatModification(DM dm, PetscSection section, PetscInt numPoints, PetscInt numIndices, const PetscInt points[], const PetscInt ***perms, PetscInt *outNumPoints, PetscInt *outNumIndices, PetscInt *outPoints[], PetscInt offsets[], PetscScalar *outMat[])
8295: {
8296: Mat cMat;
8297: PetscSection aSec, cSec;
8298: IS aIS;
8299: PetscInt aStart = -1, aEnd = -1;
8300: PetscInt sStart = -1, sEnd = -1;
8301: PetscInt cStart = -1, cEnd = -1;
8302: const PetscInt *anchors;
8303: PetscInt numFields, p;
8304: PetscInt newNumPoints = 0, newNumIndices = 0;
8305: PetscInt *newPoints, *indices, *newIndices, *tmpIndices, *tmpNewIndices;
8306: PetscInt oldOffsets[32];
8307: PetscInt newOffsets[32];
8308: PetscInt oldOffsetsCopy[32];
8309: PetscInt newOffsetsCopy[32];
8310: PetscScalar *modMat = NULL;
8311: PetscBool anyConstrained = PETSC_FALSE;
8313: PetscFunctionBegin;
8316: PetscCall(PetscSectionGetNumFields(section, &numFields));
8318: PetscCall(DMPlexGetAnchors(dm, &aSec, &aIS));
8319: /* if there are point-to-point constraints */
8320: if (aSec) {
8321: PetscCall(PetscArrayzero(newOffsets, 32));
8322: PetscCall(PetscArrayzero(oldOffsets, 32));
8323: PetscCall(ISGetIndices(aIS, &anchors));
8324: PetscCall(PetscSectionGetChart(aSec, &aStart, &aEnd));
8325: PetscCall(PetscSectionGetChart(section, &sStart, &sEnd));
8326: /* figure out how many points are going to be in the new element matrix
8327: * (we allow double counting, because it's all just going to be summed
8328: * into the global matrix anyway) */
8329: for (p = 0; p < 2 * numPoints; p += 2) {
8330: PetscInt b = points[p];
8331: PetscInt bDof = 0, bSecDof = 0;
8333: if (b >= sStart && b < sEnd) PetscCall(PetscSectionGetDof(section, b, &bSecDof));
8334: if (!bSecDof) continue;
8336: for (PetscInt f = 0; f < numFields; f++) {
8337: PetscInt fDof = 0;
8339: PetscCall(PetscSectionGetFieldDof(section, b, f, &fDof));
8340: oldOffsets[f + 1] += fDof;
8341: }
8342: if (b >= aStart && b < aEnd) PetscCall(PetscSectionGetDof(aSec, b, &bDof));
8343: if (bDof) {
8344: /* this point is constrained */
8345: /* it is going to be replaced by its anchors */
8346: PetscInt bOff;
8348: PetscCall(PetscSectionGetOffset(aSec, b, &bOff));
8349: for (PetscInt q = 0; q < bDof; q++) {
8350: PetscInt a = anchors[bOff + q];
8351: PetscInt aDof = 0;
8353: if (a >= sStart && a < sEnd) PetscCall(PetscSectionGetDof(section, a, &aDof));
8354: if (aDof) {
8355: anyConstrained = PETSC_TRUE;
8356: newNumPoints += 1;
8357: }
8358: newNumIndices += aDof;
8359: for (PetscInt f = 0; f < numFields; ++f) {
8360: PetscInt fDof = 0;
8362: if (a >= sStart && a < sEnd) PetscCall(PetscSectionGetFieldDof(section, a, f, &fDof));
8363: newOffsets[f + 1] += fDof;
8364: }
8365: }
8366: } else {
8367: /* this point is not constrained */
8368: newNumPoints++;
8369: newNumIndices += bSecDof;
8370: for (PetscInt f = 0; f < numFields; ++f) {
8371: PetscInt fDof;
8373: PetscCall(PetscSectionGetFieldDof(section, b, f, &fDof));
8374: newOffsets[f + 1] += fDof;
8375: }
8376: }
8377: }
8378: }
8379: if (!anyConstrained) {
8380: if (outNumPoints) *outNumPoints = 0;
8381: if (outNumIndices) *outNumIndices = 0;
8382: if (outPoints) *outPoints = NULL;
8383: if (outMat) *outMat = NULL;
8384: if (aSec) PetscCall(ISRestoreIndices(aIS, &anchors));
8385: PetscFunctionReturn(PETSC_SUCCESS);
8386: }
8388: if (outNumPoints) *outNumPoints = newNumPoints;
8389: if (outNumIndices) *outNumIndices = newNumIndices;
8391: for (PetscInt f = 0; f < numFields; ++f) newOffsets[f + 1] += newOffsets[f];
8392: for (PetscInt f = 0; f < numFields; ++f) oldOffsets[f + 1] += oldOffsets[f];
8394: if (!outPoints && !outMat) {
8395: if (offsets) {
8396: for (PetscInt f = 0; f <= numFields; f++) offsets[f] = newOffsets[f];
8397: }
8398: if (aSec) PetscCall(ISRestoreIndices(aIS, &anchors));
8399: PetscFunctionReturn(PETSC_SUCCESS);
8400: }
8402: PetscCheck(!numFields || newOffsets[numFields] == newNumIndices, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid size for closure %" PetscInt_FMT " should be %" PetscInt_FMT, newOffsets[numFields], newNumIndices);
8403: PetscCheck(!numFields || oldOffsets[numFields] == numIndices, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid size for closure %" PetscInt_FMT " should be %" PetscInt_FMT, oldOffsets[numFields], numIndices);
8405: PetscCall(DMGetDefaultConstraints(dm, &cSec, &cMat, NULL));
8406: PetscCall(PetscSectionGetChart(cSec, &cStart, &cEnd));
8408: /* output arrays */
8409: PetscCall(DMGetWorkArray(dm, 2 * newNumPoints, MPIU_INT, &newPoints));
8410: PetscCall(PetscArrayzero(newPoints, 2 * newNumPoints));
8412: // get the new Points
8413: for (PetscInt p = 0, newP = 0; p < numPoints; p++) {
8414: PetscInt b = points[2 * p];
8415: PetscInt bDof = 0, bSecDof = 0, bOff;
8417: if (b >= sStart && b < sEnd) PetscCall(PetscSectionGetDof(section, b, &bSecDof));
8418: if (!bSecDof) continue;
8419: if (b >= aStart && b < aEnd) PetscCall(PetscSectionGetDof(aSec, b, &bDof));
8420: if (bDof) {
8421: PetscCall(PetscSectionGetOffset(aSec, b, &bOff));
8422: for (PetscInt q = 0; q < bDof; q++) {
8423: PetscInt a = anchors[bOff + q], aDof = 0;
8425: if (a >= sStart && a < sEnd) PetscCall(PetscSectionGetDof(section, a, &aDof));
8426: if (aDof) {
8427: newPoints[2 * newP] = a;
8428: newPoints[2 * newP + 1] = 0; // orientations are accounted for in constructing the matrix, newly added points are in default orientation
8429: newP++;
8430: }
8431: }
8432: } else {
8433: newPoints[2 * newP] = b;
8434: newPoints[2 * newP + 1] = points[2 * p + 1];
8435: newP++;
8436: }
8437: }
8439: if (outMat) {
8440: PetscScalar *tmpMat;
8441: PetscCall(PetscArraycpy(oldOffsetsCopy, oldOffsets, 32));
8442: PetscCall(PetscArraycpy(newOffsetsCopy, newOffsets, 32));
8444: PetscCall(DMGetWorkArray(dm, numIndices, MPIU_INT, &indices));
8445: PetscCall(DMGetWorkArray(dm, numIndices, MPIU_INT, &tmpIndices));
8446: PetscCall(DMGetWorkArray(dm, newNumIndices, MPIU_INT, &newIndices));
8447: PetscCall(DMGetWorkArray(dm, newNumIndices, MPIU_INT, &tmpNewIndices));
8449: for (PetscInt i = 0; i < numIndices; i++) indices[i] = -1;
8450: for (PetscInt i = 0; i < newNumIndices; i++) newIndices[i] = -1;
8452: PetscCall(DMPlexAnchorsGetSubMatIndices(numPoints, points, section, cSec, tmpIndices, oldOffsetsCopy, indices, perms));
8453: PetscCall(DMPlexAnchorsGetSubMatIndices(newNumPoints, newPoints, section, section, tmpNewIndices, newOffsetsCopy, newIndices, NULL));
8455: PetscCall(DMGetWorkArray(dm, numIndices * newNumIndices, MPIU_SCALAR, &modMat));
8456: PetscCall(DMGetWorkArray(dm, numIndices * newNumIndices, MPIU_SCALAR, &tmpMat));
8457: PetscCall(PetscArrayzero(modMat, newNumIndices * numIndices));
8458: // for each field, insert the anchor modification into modMat
8459: for (PetscInt f = 0; f < PetscMax(1, numFields); f++) {
8460: PetscInt fStart = oldOffsets[f];
8461: PetscInt fNewStart = newOffsets[f];
8462: for (PetscInt p = 0, o = fStart, oNew = fNewStart; p < numPoints; p++) {
8463: PetscInt b = points[2 * p];
8464: PetscInt bDof = 0, bSecDof = 0, bOff;
8466: if (b >= sStart && b < sEnd) {
8467: if (numFields) PetscCall(PetscSectionGetFieldDof(section, b, f, &bSecDof));
8468: else PetscCall(PetscSectionGetDof(section, b, &bSecDof));
8469: }
8470: if (!bSecDof) continue;
8471: if (b >= aStart && b < aEnd) PetscCall(PetscSectionGetDof(aSec, b, &bDof));
8472: if (bDof) {
8473: PetscCall(PetscSectionGetOffset(aSec, b, &bOff));
8474: for (PetscInt q = 0; q < bDof; q++) {
8475: PetscInt a = anchors[bOff + q], aDof = 0;
8477: if (a >= sStart && a < sEnd) {
8478: if (numFields) PetscCall(PetscSectionGetFieldDof(section, a, f, &aDof));
8479: else PetscCall(PetscSectionGetDof(section, a, &aDof));
8480: }
8481: if (aDof) {
8482: PetscCall(MatGetValues(cMat, bSecDof, &indices[o], aDof, &newIndices[oNew], tmpMat));
8483: for (PetscInt d = 0; d < bSecDof; d++) {
8484: for (PetscInt e = 0; e < aDof; e++) modMat[(o + d) * newNumIndices + oNew + e] = tmpMat[d * aDof + e];
8485: }
8486: }
8487: oNew += aDof;
8488: }
8489: } else {
8490: // Insert the identity matrix in this block
8491: for (PetscInt d = 0; d < bSecDof; d++) modMat[(o + d) * newNumIndices + oNew + d] = 1;
8492: oNew += bSecDof;
8493: }
8494: o += bSecDof;
8495: }
8496: }
8498: *outMat = modMat;
8500: PetscCall(DMRestoreWorkArray(dm, numIndices * newNumIndices, MPIU_SCALAR, &tmpMat));
8501: PetscCall(DMRestoreWorkArray(dm, newNumIndices, MPIU_INT, &tmpNewIndices));
8502: PetscCall(DMRestoreWorkArray(dm, newNumIndices, MPIU_INT, &newIndices));
8503: PetscCall(DMRestoreWorkArray(dm, numIndices, MPIU_INT, &tmpIndices));
8504: PetscCall(DMRestoreWorkArray(dm, numIndices, MPIU_INT, &indices));
8505: }
8506: PetscCall(ISRestoreIndices(aIS, &anchors));
8508: /* output */
8509: if (outPoints) {
8510: *outPoints = newPoints;
8511: } else {
8512: PetscCall(DMRestoreWorkArray(dm, 2 * newNumPoints, MPIU_INT, &newPoints));
8513: }
8514: for (PetscInt f = 0; f <= numFields; f++) offsets[f] = newOffsets[f];
8515: PetscFunctionReturn(PETSC_SUCCESS);
8516: }
8518: PETSC_INTERN PetscErrorCode DMPlexAnchorsModifyMat_Internal(DM dm, PetscSection section, PetscInt numPoints, PetscInt numIndices, const PetscInt points[], const PetscInt ***perms, PetscInt numRows, PetscInt numCols, const PetscScalar values[], PetscInt *outNumPoints, PetscInt *outNumIndices, PetscInt *outPoints[], PetscScalar *outValues[], PetscInt offsets[], PetscBool multiplyRight, PetscBool multiplyLeft)
8519: {
8520: PetscScalar *modMat = NULL;
8521: PetscInt newNumIndices = -1;
8523: PetscFunctionBegin;
8524: /* If M is the matrix represented by values, get the matrix C such that we will add M * C (or, if multiplyLeft, C^T * M * C) into the global matrix.
8525: modMat is that matrix C */
8526: PetscCall(DMPlexAnchorsGetSubMatModification(dm, section, numPoints, numIndices, points, perms, outNumPoints, &newNumIndices, outPoints, offsets, outValues ? &modMat : NULL));
8527: if (outNumIndices) *outNumIndices = newNumIndices;
8528: if (modMat) {
8529: const PetscScalar *newValues = values;
8531: if (multiplyRight) {
8532: PetscScalar *newNewValues = NULL;
8533: PetscBLASInt M, N, K;
8534: PetscScalar a = 1.0, b = 0.0;
8536: PetscCheck(numCols == numIndices, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "values matrix has the wrong number of columns: %" PetscInt_FMT ", expected %" PetscInt_FMT, numCols, numIndices);
8538: PetscCall(PetscBLASIntCast(newNumIndices, &M));
8539: PetscCall(PetscBLASIntCast(numRows, &N));
8540: PetscCall(PetscBLASIntCast(numIndices, &K));
8541: PetscCall(DMGetWorkArray(dm, numRows * newNumIndices, MPIU_SCALAR, &newNewValues));
8542: // row-major to column-major conversion, right multiplication becomes left multiplication
8543: PetscCallBLAS("BLASgemm", BLASgemm_("N", "N", &M, &N, &K, &a, modMat, &M, newValues, &K, &b, newNewValues, &M));
8544: numCols = newNumIndices;
8545: newValues = newNewValues;
8546: }
8548: if (multiplyLeft) {
8549: PetscScalar *newNewValues = NULL;
8550: PetscBLASInt M, N, K;
8551: PetscScalar a = 1.0, b = 0.0;
8553: PetscCheck(numRows == numIndices, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "values matrix has the wrong number of rows: %" PetscInt_FMT ", expected %" PetscInt_FMT, numRows, numIndices);
8555: PetscCall(PetscBLASIntCast(numCols, &M));
8556: PetscCall(PetscBLASIntCast(newNumIndices, &N));
8557: PetscCall(PetscBLASIntCast(numIndices, &K));
8558: PetscCall(DMGetWorkArray(dm, newNumIndices * numCols, MPIU_SCALAR, &newNewValues));
8559: // row-major to column-major conversion, left multiplication becomes right multiplication
8560: PetscCallBLAS("BLASgemm", BLASgemm_("N", "T", &M, &N, &K, &a, newValues, &M, modMat, &N, &b, newNewValues, &M));
8561: if (newValues != values) PetscCall(DMRestoreWorkArray(dm, numIndices * newNumIndices, MPIU_SCALAR, &newValues));
8562: newValues = newNewValues;
8563: }
8564: *outValues = (PetscScalar *)newValues;
8565: PetscCall(DMRestoreWorkArray(dm, numIndices * newNumIndices, MPIU_SCALAR, &modMat));
8566: }
8567: PetscFunctionReturn(PETSC_SUCCESS);
8568: }
8570: PETSC_INTERN PetscErrorCode DMPlexAnchorsModifyMat(DM dm, PetscSection section, PetscInt numPoints, PetscInt numIndices, const PetscInt points[], const PetscInt ***perms, const PetscScalar values[], PetscInt *outNumPoints, PetscInt *outNumIndices, PetscInt *outPoints[], PetscScalar *outValues[], PetscInt offsets[], PetscBool multiplyLeft)
8571: {
8572: PetscFunctionBegin;
8573: PetscCall(DMPlexAnchorsModifyMat_Internal(dm, section, numPoints, numIndices, points, perms, numIndices, numIndices, values, outNumPoints, outNumIndices, outPoints, outValues, offsets, PETSC_TRUE, multiplyLeft));
8574: PetscFunctionReturn(PETSC_SUCCESS);
8575: }
8577: static PetscErrorCode DMPlexGetClosureIndicesSize_Internal(DM dm, PetscSection section, PetscInt point, PetscInt *closureSize)
8578: {
8579: /* Closure ordering */
8580: PetscSection clSection;
8581: IS clPoints;
8582: const PetscInt *clp;
8583: PetscInt *points;
8584: PetscInt Ncl, Ni = 0;
8586: PetscFunctionBeginHot;
8587: PetscCall(DMPlexGetCompressedClosure(dm, section, point, 0, &Ncl, &points, &clSection, &clPoints, &clp));
8588: for (PetscInt p = 0; p < Ncl * 2; p += 2) {
8589: PetscInt dof;
8591: PetscCall(PetscSectionGetDof(section, points[p], &dof));
8592: Ni += dof;
8593: }
8594: PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp));
8595: *closureSize = Ni;
8596: PetscFunctionReturn(PETSC_SUCCESS);
8597: }
8599: static PetscErrorCode DMPlexGetClosureIndices_Internal(DM dm, PetscSection section, PetscSection idxSection, PetscInt point, PetscBool useClPerm, PetscInt *numRows, PetscInt *numCols, PetscInt *indices[], PetscInt outOffsets[], PetscScalar *values[], PetscBool multiplyRight, PetscBool multiplyLeft)
8600: {
8601: /* Closure ordering */
8602: PetscSection clSection;
8603: IS clPoints;
8604: const PetscInt *clp;
8605: PetscInt *points;
8606: const PetscInt *clperm = NULL;
8607: /* Dof permutation and sign flips */
8608: const PetscInt **perms[32] = {NULL};
8609: const PetscScalar **flips[32] = {NULL};
8610: PetscScalar *valCopy = NULL;
8611: /* Hanging node constraints */
8612: PetscInt *pointsC = NULL;
8613: PetscScalar *valuesC = NULL;
8614: PetscInt NclC, NiC;
8616: PetscInt *idx;
8617: PetscInt Nf, Ncl, Ni = 0, offsets[32], p, f;
8618: PetscBool isLocal = (section == idxSection) ? PETSC_TRUE : PETSC_FALSE;
8619: PetscInt idxStart, idxEnd;
8620: PetscInt nRows, nCols;
8622: PetscFunctionBeginHot;
8626: PetscAssertPointer(numRows, 6);
8627: PetscAssertPointer(numCols, 7);
8628: if (indices) PetscAssertPointer(indices, 8);
8629: if (outOffsets) PetscAssertPointer(outOffsets, 9);
8630: if (values) PetscAssertPointer(values, 10);
8631: PetscCall(PetscSectionGetNumFields(section, &Nf));
8632: PetscCheck(Nf <= 31, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %" PetscInt_FMT " limited to 31", Nf);
8633: PetscCall(PetscArrayzero(offsets, 32));
8634: /* 1) Get points in closure */
8635: PetscCall(DMPlexGetCompressedClosure(dm, section, point, 0, &Ncl, &points, &clSection, &clPoints, &clp));
8636: if (useClPerm) {
8637: PetscInt depth, clsize;
8638: PetscCall(DMPlexGetPointDepth(dm, point, &depth));
8639: for (clsize = 0, p = 0; p < Ncl; p++) {
8640: PetscInt dof;
8641: PetscCall(PetscSectionGetDof(section, points[2 * p], &dof));
8642: clsize += dof;
8643: }
8644: PetscCall(PetscSectionGetClosureInversePermutation_Internal(section, (PetscObject)dm, depth, clsize, &clperm));
8645: }
8646: /* 2) Get number of indices on these points and field offsets from section */
8647: for (p = 0; p < Ncl * 2; p += 2) {
8648: PetscInt dof, fdof;
8650: PetscCall(PetscSectionGetDof(section, points[p], &dof));
8651: for (f = 0; f < Nf; ++f) {
8652: PetscCall(PetscSectionGetFieldDof(section, points[p], f, &fdof));
8653: offsets[f + 1] += fdof;
8654: }
8655: Ni += dof;
8656: }
8657: if (*numRows == -1) *numRows = Ni;
8658: if (*numCols == -1) *numCols = Ni;
8659: nRows = *numRows;
8660: nCols = *numCols;
8661: for (f = 1; f < Nf; ++f) offsets[f + 1] += offsets[f];
8662: PetscCheck(!Nf || offsets[Nf] == Ni, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Invalid size for closure %" PetscInt_FMT " should be %" PetscInt_FMT, offsets[Nf], Ni);
8663: /* 3) Get symmetries and sign flips. Apply sign flips to values if passed in (only works for square values matrix) */
8664: if (multiplyRight) PetscCheck(nCols == Ni, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Expected %" PetscInt_FMT " columns, got %" PetscInt_FMT, Ni, nCols);
8665: if (multiplyLeft) PetscCheck(nRows == Ni, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_SIZ, "Expected %" PetscInt_FMT " rows, got %" PetscInt_FMT, Ni, nRows);
8666: for (f = 0; f < PetscMax(1, Nf); ++f) {
8667: if (Nf) PetscCall(PetscSectionGetFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]));
8668: else PetscCall(PetscSectionGetPointSyms(section, Ncl, points, &perms[f], &flips[f]));
8669: /* may need to apply sign changes to the element matrix */
8670: if (values && flips[f]) {
8671: PetscInt foffset = offsets[f];
8673: for (p = 0; p < Ncl; ++p) {
8674: PetscInt pnt = points[2 * p], fdof;
8675: const PetscScalar *flip = flips[f] ? flips[f][p] : NULL;
8677: if (!Nf) PetscCall(PetscSectionGetDof(section, pnt, &fdof));
8678: else PetscCall(PetscSectionGetFieldDof(section, pnt, f, &fdof));
8679: if (flip) {
8680: PetscInt i, j, k;
8682: if (!valCopy) {
8683: PetscCall(DMGetWorkArray(dm, Ni * Ni, MPIU_SCALAR, &valCopy));
8684: for (j = 0; j < Ni * Ni; ++j) valCopy[j] = (*values)[j];
8685: *values = valCopy;
8686: }
8687: for (i = 0; i < fdof; ++i) {
8688: PetscScalar fval = flip[i];
8690: if (multiplyRight) {
8691: for (k = 0; k < nRows; ++k) valCopy[Ni * k + (foffset + i)] *= fval;
8692: }
8693: if (multiplyLeft) {
8694: for (k = 0; k < nCols; ++k) valCopy[nCols * (foffset + i) + k] *= fval;
8695: }
8696: }
8697: }
8698: foffset += fdof;
8699: }
8700: }
8701: }
8702: /* 4) Apply hanging node constraints. Get new symmetries and replace all storage with constrained storage */
8703: PetscCall(DMPlexAnchorsModifyMat_Internal(dm, section, Ncl, Ni, points, perms, nRows, nCols, values ? *values : NULL, &NclC, &NiC, &pointsC, values ? &valuesC : NULL, offsets, multiplyRight, multiplyLeft));
8704: if (NclC) {
8705: if (multiplyRight) *numCols = NiC;
8706: if (multiplyLeft) *numRows = NiC;
8707: if (valCopy) PetscCall(DMRestoreWorkArray(dm, Ni * Ni, MPIU_SCALAR, &valCopy));
8708: for (f = 0; f < PetscMax(1, Nf); ++f) {
8709: if (Nf) PetscCall(PetscSectionRestoreFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]));
8710: else PetscCall(PetscSectionRestorePointSyms(section, Ncl, points, &perms[f], &flips[f]));
8711: }
8712: for (f = 0; f < PetscMax(1, Nf); ++f) {
8713: if (Nf) PetscCall(PetscSectionGetFieldPointSyms(section, f, NclC, pointsC, &perms[f], &flips[f]));
8714: else PetscCall(PetscSectionGetPointSyms(section, NclC, pointsC, &perms[f], &flips[f]));
8715: }
8716: PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp));
8717: Ncl = NclC;
8718: Ni = NiC;
8719: points = pointsC;
8720: if (values) *values = valuesC;
8721: }
8722: /* 5) Calculate indices */
8723: PetscCall(DMGetWorkArray(dm, Ni, MPIU_INT, &idx));
8724: PetscCall(PetscSectionGetChart(idxSection, &idxStart, &idxEnd));
8725: if (Nf) {
8726: PetscInt idxOff;
8727: PetscBool useFieldOffsets;
8729: if (outOffsets) {
8730: for (f = 0; f <= Nf; f++) outOffsets[f] = offsets[f];
8731: }
8732: PetscCall(PetscSectionGetUseFieldOffsets(idxSection, &useFieldOffsets));
8733: if (useFieldOffsets) {
8734: for (p = 0; p < Ncl; ++p) {
8735: const PetscInt pnt = points[p * 2];
8737: PetscCall(DMPlexGetIndicesPointFieldsSplit_Internal(section, idxSection, pnt, offsets, perms, p, clperm, idx));
8738: }
8739: } else {
8740: for (p = 0; p < Ncl; ++p) {
8741: const PetscInt pnt = points[p * 2];
8743: if (pnt < idxStart || pnt >= idxEnd) continue;
8744: PetscCall(PetscSectionGetOffset(idxSection, pnt, &idxOff));
8745: /* Note that we pass a local section even though we're using global offsets. This is because global sections do
8746: * not (at the time of this writing) have fields set. They probably should, in which case we would pass the
8747: * global section. */
8748: PetscCall(DMPlexGetIndicesPointFields_Internal(section, isLocal, pnt, idxOff < 0 ? -(idxOff + 1) : idxOff, offsets, PETSC_FALSE, perms, p, clperm, idx));
8749: }
8750: }
8751: } else {
8752: PetscInt off = 0, idxOff;
8754: for (p = 0; p < Ncl; ++p) {
8755: const PetscInt pnt = points[p * 2];
8756: const PetscInt *perm = perms[0] ? perms[0][p] : NULL;
8758: if (pnt < idxStart || pnt >= idxEnd) continue;
8759: PetscCall(PetscSectionGetOffset(idxSection, pnt, &idxOff));
8760: /* Note that we pass a local section even though we're using global offsets. This is because global sections do
8761: * not (at the time of this writing) have fields set. They probably should, in which case we would pass the global section. */
8762: PetscCall(DMPlexGetIndicesPoint_Internal(section, isLocal, pnt, idxOff < 0 ? -(idxOff + 1) : idxOff, &off, PETSC_FALSE, perm, clperm, idx));
8763: }
8764: }
8765: /* 6) Cleanup */
8766: for (f = 0; f < PetscMax(1, Nf); ++f) {
8767: if (Nf) PetscCall(PetscSectionRestoreFieldPointSyms(section, f, Ncl, points, &perms[f], &flips[f]));
8768: else PetscCall(PetscSectionRestorePointSyms(section, Ncl, points, &perms[f], &flips[f]));
8769: }
8770: if (NclC) {
8771: PetscCall(DMRestoreWorkArray(dm, NclC * 2, MPIU_INT, &pointsC));
8772: } else {
8773: PetscCall(DMPlexRestoreCompressedClosure(dm, section, point, &Ncl, &points, &clSection, &clPoints, &clp));
8774: }
8776: if (indices) *indices = idx;
8777: PetscFunctionReturn(PETSC_SUCCESS);
8778: }
8780: /*@C
8781: DMPlexGetClosureIndices - Gets the global dof indices associated with the closure of the given point within the provided sections.
8783: Not collective
8785: Input Parameters:
8786: + dm - The `DM`
8787: . section - The `PetscSection` describing the points (a local section)
8788: . idxSection - The `PetscSection` from which to obtain indices (may be local or global)
8789: . point - The point defining the closure
8790: - useClPerm - Use the closure point permutation if available
8792: Output Parameters:
8793: + numIndices - The number of dof indices in the closure of point with the input sections
8794: . indices - The dof indices
8795: . outOffsets - Array, of length the number of fields plus 1, to write the field offsets into, or `NULL`
8796: - values - The input values, which may be modified if sign flips are induced by the point symmetries, or `NULL`
8798: Level: advanced
8800: Notes:
8801: Call `DMPlexRestoreClosureIndices()` to free allocated memory
8803: If `idxSection` is global, any constrained dofs (see `DMAddBoundary()`, for example) will get negative indices. The value
8804: of those indices is not significant. If `idxSection` is local, the constrained dofs will yield the involution -(idx+1)
8805: of their index in a local vector. A caller who does not wish to distinguish those points may recover the nonnegative
8806: indices via involution, -(-(idx+1)+1)==idx. Local indices are provided when `idxSection` == section, otherwise global
8807: indices (with the above semantics) are implied.
8809: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexRestoreClosureIndices()`, `DMPlexVecGetClosure()`, `DMPlexMatSetClosure()`, `DMGetLocalSection()`,
8810: `PetscSection`, `DMGetGlobalSection()`
8811: @*/
8812: PetscErrorCode DMPlexGetClosureIndices(DM dm, PetscSection section, PetscSection idxSection, PetscInt point, PetscBool useClPerm, PetscInt *numIndices, PetscInt *indices[], PeOp PetscInt outOffsets[], PeOp PetscScalar *values[])
8813: {
8814: PetscInt numRows = -1, numCols = -1;
8816: PetscFunctionBeginHot;
8817: PetscCall(DMPlexGetClosureIndices_Internal(dm, section, idxSection, point, useClPerm, &numRows, &numCols, indices, outOffsets, values, PETSC_TRUE, PETSC_TRUE));
8818: PetscCheck(numRows == numCols, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Symmetric matrix transformation produces rectangular dimensions (%" PetscInt_FMT ", %" PetscInt_FMT ")", numRows, numCols);
8819: *numIndices = numRows;
8820: PetscFunctionReturn(PETSC_SUCCESS);
8821: }
8823: /*@C
8824: DMPlexRestoreClosureIndices - Restores the global dof indices associated with the closure of the given point within the provided sections.
8826: Not collective
8828: Input Parameters:
8829: + dm - The `DM`
8830: . section - The `PetscSection` describing the points (a local section)
8831: . idxSection - The `PetscSection` from which to obtain indices (may be local or global)
8832: . point - The point defining the closure
8833: - useClPerm - Use the closure point permutation if available
8835: Output Parameters:
8836: + numIndices - The number of dof indices in the closure of point with the input sections
8837: . indices - The dof indices
8838: . outOffsets - Array to write the field offsets into, or `NULL`
8839: - values - The input values, which may be modified if sign flips are induced by the point symmetries, or `NULL`
8841: Level: advanced
8843: Notes:
8844: If values were modified, the user is responsible for calling `DMRestoreWorkArray`(dm, 0, `MPIU_SCALAR`, &values).
8846: If idxSection is global, any constrained dofs (see `DMAddBoundary()`, for example) will get negative indices. The value
8847: of those indices is not significant. If idxSection is local, the constrained dofs will yield the involution -(idx+1)
8848: of their index in a local vector. A caller who does not wish to distinguish those points may recover the nonnegative
8849: indices via involution, -(-(idx+1)+1)==idx. Local indices are provided when idxSection == section, otherwise global
8850: indices (with the above semantics) are implied.
8852: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetClosureIndices()`, `DMPlexVecGetClosure()`, `DMPlexMatSetClosure()`, `DMGetLocalSection()`, `DMGetGlobalSection()`
8853: @*/
8854: PetscErrorCode DMPlexRestoreClosureIndices(DM dm, PetscSection section, PetscSection idxSection, PetscInt point, PetscBool useClPerm, PetscInt *numIndices, PetscInt *indices[], PeOp PetscInt outOffsets[], PeOp PetscScalar *values[])
8855: {
8856: PetscFunctionBegin;
8858: PetscAssertPointer(indices, 7);
8859: PetscCall(DMRestoreWorkArray(dm, 0, MPIU_INT, indices));
8860: PetscFunctionReturn(PETSC_SUCCESS);
8861: }
8863: PetscErrorCode DMPlexMatSetClosure_Internal(DM dm, PetscSection section, PetscSection globalSection, PetscBool useClPerm, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
8864: {
8865: DM_Plex *mesh = (DM_Plex *)dm->data;
8866: PetscInt *indices;
8867: PetscInt numIndices;
8868: const PetscScalar *valuesOrig = values;
8869: PetscErrorCode ierr;
8871: PetscFunctionBegin;
8873: if (!section) PetscCall(DMGetLocalSection(dm, §ion));
8875: if (!globalSection) PetscCall(DMGetGlobalSection(dm, &globalSection));
8879: PetscCall(DMPlexGetClosureIndices(dm, section, globalSection, point, useClPerm, &numIndices, &indices, NULL, (PetscScalar **)&values));
8881: if (mesh->printSetValues) PetscCall(DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numIndices, indices, 0, NULL, values));
8882: /* TODO: fix this code to not use error codes as handle-able exceptions! */
8883: ierr = MatSetValues(A, numIndices, indices, numIndices, indices, values, mode);
8884: if (ierr) {
8885: PetscMPIInt rank;
8887: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank));
8888: PetscCall((*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank));
8889: PetscCall(DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numIndices, indices, 0, NULL, values));
8890: PetscCall(DMPlexRestoreClosureIndices(dm, section, globalSection, point, PETSC_TRUE, &numIndices, &indices, NULL, (PetscScalar **)&values));
8891: if (values != valuesOrig) PetscCall(DMRestoreWorkArray(dm, 0, MPIU_SCALAR, &values));
8892: SETERRQ(PetscObjectComm((PetscObject)dm), ierr, "Not possible to set matrix values");
8893: }
8894: if (mesh->printFEM > 1) {
8895: PetscCall(PetscPrintf(PETSC_COMM_SELF, " Indices:"));
8896: for (PetscInt i = 0; i < numIndices; ++i) PetscCall(PetscPrintf(PETSC_COMM_SELF, " %" PetscInt_FMT, indices[i]));
8897: PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
8898: }
8900: PetscCall(DMPlexRestoreClosureIndices(dm, section, globalSection, point, PETSC_TRUE, &numIndices, &indices, NULL, (PetscScalar **)&values));
8901: if (values != valuesOrig) PetscCall(DMRestoreWorkArray(dm, 0, MPIU_SCALAR, &values));
8902: PetscFunctionReturn(PETSC_SUCCESS);
8903: }
8905: /*@C
8906: DMPlexMatSetClosure - Set an array of the values on the closure of 'point'
8908: Not collective
8910: Input Parameters:
8911: + dm - The `DM`
8912: . section - The section describing the layout in `v`, or `NULL` to use the default section
8913: . globalSection - The section describing the layout in `v`, or `NULL` to use the default global section
8914: . A - The matrix
8915: . point - The point in the `DM`
8916: . values - The array of values
8917: - mode - The insert mode, where `INSERT_ALL_VALUES` and `ADD_ALL_VALUES` also overwrite boundary conditions
8919: Level: intermediate
8921: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexMatSetClosureGeneral()`, `DMPlexVecGetClosure()`, `DMPlexVecSetClosure()`
8922: @*/
8923: PetscErrorCode DMPlexMatSetClosure(DM dm, PetscSection section, PetscSection globalSection, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
8924: {
8925: PetscFunctionBegin;
8926: PetscCall(DMPlexMatSetClosure_Internal(dm, section, globalSection, PETSC_TRUE, A, point, values, mode));
8927: PetscFunctionReturn(PETSC_SUCCESS);
8928: }
8930: /*@C
8931: DMPlexMatSetClosureGeneral - Set an array of the values on the closure of 'point' using a different row and column section
8933: Not collective
8935: Input Parameters:
8936: + dmRow - The `DM` for the row fields
8937: . sectionRow - The section describing the layout, or `NULL` to use the default section in `dmRow`
8938: . useRowPerm - The flag to use the closure permutation of the `dmRow` if available
8939: . globalSectionRow - The section describing the layout, or `NULL` to use the default global section in `dmRow`
8940: . dmCol - The `DM` for the column fields
8941: . sectionCol - The section describing the layout, or `NULL` to use the default section in `dmCol`
8942: . useColPerm - The flag to use the closure permutation of the `dmCol` if available
8943: . globalSectionCol - The section describing the layout, or `NULL` to use the default global section in `dmCol`
8944: . A - The matrix
8945: . point - The point in the `DM`
8946: . values - The array of values
8947: - mode - The insert mode, where `INSERT_ALL_VALUES` and `ADD_ALL_VALUES` also overwrite boundary conditions
8949: Level: intermediate
8951: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexMatSetClosure()`, `DMPlexVecGetClosure()`, `DMPlexVecSetClosure()`
8952: @*/
8953: PetscErrorCode DMPlexMatSetClosureGeneral(DM dmRow, PetscSection sectionRow, PetscSection globalSectionRow, PetscBool useRowPerm, DM dmCol, PetscSection sectionCol, PetscSection globalSectionCol, PetscBool useColPerm, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
8954: {
8955: DM_Plex *mesh = (DM_Plex *)dmRow->data;
8956: PetscInt *indicesRow, *indicesCol;
8957: PetscInt numIndicesRow = -1, numIndicesCol = -1;
8958: const PetscScalar *valuesV0 = values, *valuesV1, *valuesV2;
8960: PetscErrorCode ierr;
8962: PetscFunctionBegin;
8964: if (!sectionRow) PetscCall(DMGetLocalSection(dmRow, §ionRow));
8966: if (!globalSectionRow) PetscCall(DMGetGlobalSection(dmRow, &globalSectionRow));
8969: if (!sectionCol) PetscCall(DMGetLocalSection(dmCol, §ionCol));
8971: if (!globalSectionCol) PetscCall(DMGetGlobalSection(dmCol, &globalSectionCol));
8975: PetscCall(DMPlexGetClosureIndicesSize_Internal(dmRow, sectionRow, point, &numIndicesRow));
8976: PetscCall(DMPlexGetClosureIndicesSize_Internal(dmCol, sectionCol, point, &numIndicesCol));
8977: valuesV1 = valuesV0;
8978: PetscCall(DMPlexGetClosureIndices_Internal(dmRow, sectionRow, globalSectionRow, point, useRowPerm, &numIndicesRow, &numIndicesCol, &indicesRow, NULL, (PetscScalar **)&valuesV1, PETSC_FALSE, PETSC_TRUE));
8979: valuesV2 = valuesV1;
8980: PetscCall(DMPlexGetClosureIndices_Internal(dmCol, sectionCol, globalSectionCol, point, useColPerm, &numIndicesRow, &numIndicesCol, &indicesCol, NULL, (PetscScalar **)&valuesV2, PETSC_TRUE, PETSC_FALSE));
8982: if (mesh->printSetValues) PetscCall(DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numIndicesRow, indicesRow, numIndicesCol, indicesCol, valuesV2));
8983: /* TODO: fix this code to not use error codes as handle-able exceptions! */
8984: ierr = MatSetValues(A, numIndicesRow, indicesRow, numIndicesCol, indicesCol, valuesV2, mode);
8985: if (ierr) {
8986: PetscMPIInt rank;
8988: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank));
8989: PetscCall((*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank));
8990: PetscCall(DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numIndicesRow, indicesRow, numIndicesCol, indicesCol, values));
8991: PetscCall(DMPlexRestoreClosureIndices(dmCol, sectionCol, globalSectionCol, point, PETSC_TRUE, &numIndicesCol, &indicesRow, NULL, (PetscScalar **)&valuesV2));
8992: PetscCall(DMPlexRestoreClosureIndices(dmRow, sectionRow, globalSectionRow, point, PETSC_TRUE, &numIndicesRow, &indicesRow, NULL, (PetscScalar **)&valuesV1));
8993: if (valuesV2 != valuesV1) PetscCall(DMRestoreWorkArray(dmCol, 0, MPIU_SCALAR, &valuesV2));
8994: if (valuesV1 != valuesV0) PetscCall(DMRestoreWorkArray(dmRow, 0, MPIU_SCALAR, &valuesV1));
8995: }
8997: PetscCall(DMPlexRestoreClosureIndices(dmCol, sectionCol, globalSectionCol, point, useColPerm, &numIndicesCol, &indicesCol, NULL, (PetscScalar **)&valuesV2));
8998: PetscCall(DMPlexRestoreClosureIndices(dmRow, sectionRow, globalSectionRow, point, useRowPerm, &numIndicesRow, &indicesRow, NULL, (PetscScalar **)&valuesV1));
8999: if (valuesV2 != valuesV1) PetscCall(DMRestoreWorkArray(dmCol, 0, MPIU_SCALAR, &valuesV2));
9000: if (valuesV1 != valuesV0) PetscCall(DMRestoreWorkArray(dmRow, 0, MPIU_SCALAR, &valuesV1));
9001: PetscFunctionReturn(PETSC_SUCCESS);
9002: }
9004: PetscErrorCode DMPlexMatSetClosureRefined(DM dmf, PetscSection fsection, PetscSection globalFSection, DM dmc, PetscSection csection, PetscSection globalCSection, Mat A, PetscInt point, const PetscScalar values[], InsertMode mode)
9005: {
9006: DM_Plex *mesh = (DM_Plex *)dmf->data;
9007: PetscInt *fpoints = NULL, *ftotpoints = NULL;
9008: PetscInt *cpoints = NULL;
9009: PetscInt *findices, *cindices;
9010: const PetscInt *fclperm = NULL, *cclperm = NULL; /* Closure permutations cannot work here */
9011: PetscInt foffsets[32], coffsets[32];
9012: DMPolytopeType ct;
9013: PetscInt numFields, numSubcells, maxFPoints, numFPoints, numCPoints, numFIndices, numCIndices, dof, off, globalOff, pStart, pEnd, p, q, r, s, f;
9014: PetscErrorCode ierr;
9016: PetscFunctionBegin;
9019: if (!fsection) PetscCall(DMGetLocalSection(dmf, &fsection));
9021: if (!csection) PetscCall(DMGetLocalSection(dmc, &csection));
9023: if (!globalFSection) PetscCall(DMGetGlobalSection(dmf, &globalFSection));
9025: if (!globalCSection) PetscCall(DMGetGlobalSection(dmc, &globalCSection));
9028: PetscCall(PetscSectionGetNumFields(fsection, &numFields));
9029: PetscCheck(numFields <= 31, PetscObjectComm((PetscObject)dmf), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %" PetscInt_FMT " limited to 31", numFields);
9030: PetscCall(PetscArrayzero(foffsets, 32));
9031: PetscCall(PetscArrayzero(coffsets, 32));
9032: /* Column indices */
9033: PetscCall(DMPlexGetTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints));
9034: maxFPoints = numCPoints;
9035: /* Compress out points not in the section */
9036: /* TODO: Squeeze out points with 0 dof as well */
9037: PetscCall(PetscSectionGetChart(csection, &pStart, &pEnd));
9038: for (p = 0, q = 0; p < numCPoints * 2; p += 2) {
9039: if ((cpoints[p] >= pStart) && (cpoints[p] < pEnd)) {
9040: cpoints[q * 2] = cpoints[p];
9041: cpoints[q * 2 + 1] = cpoints[p + 1];
9042: ++q;
9043: }
9044: }
9045: numCPoints = q;
9046: for (p = 0, numCIndices = 0; p < numCPoints * 2; p += 2) {
9047: PetscInt fdof;
9049: PetscCall(PetscSectionGetDof(csection, cpoints[p], &dof));
9050: if (!dof) continue;
9051: for (f = 0; f < numFields; ++f) {
9052: PetscCall(PetscSectionGetFieldDof(csection, cpoints[p], f, &fdof));
9053: coffsets[f + 1] += fdof;
9054: }
9055: numCIndices += dof;
9056: }
9057: for (f = 1; f < numFields; ++f) coffsets[f + 1] += coffsets[f];
9058: /* Row indices */
9059: PetscCall(DMPlexGetCellType(dmc, point, &ct));
9060: {
9061: DMPlexTransform tr;
9062: DMPolytopeType *rct;
9063: PetscInt *rsize, *rcone, *rornt, Nt;
9065: PetscCall(DMPlexTransformCreate(PETSC_COMM_SELF, &tr));
9066: PetscCall(DMPlexTransformSetType(tr, DMPLEXREFINEREGULAR));
9067: PetscCall(DMPlexTransformCellTransform(tr, ct, point, NULL, &Nt, &rct, &rsize, &rcone, &rornt));
9068: numSubcells = rsize[Nt - 1];
9069: PetscCall(DMPlexTransformDestroy(&tr));
9070: }
9071: PetscCall(DMGetWorkArray(dmf, maxFPoints * 2 * numSubcells, MPIU_INT, &ftotpoints));
9072: for (r = 0, q = 0; r < numSubcells; ++r) {
9073: /* TODO Map from coarse to fine cells */
9074: PetscCall(DMPlexGetTransitiveClosure(dmf, point * numSubcells + r, PETSC_TRUE, &numFPoints, &fpoints));
9075: /* Compress out points not in the section */
9076: PetscCall(PetscSectionGetChart(fsection, &pStart, &pEnd));
9077: for (p = 0; p < numFPoints * 2; p += 2) {
9078: if ((fpoints[p] >= pStart) && (fpoints[p] < pEnd)) {
9079: PetscCall(PetscSectionGetDof(fsection, fpoints[p], &dof));
9080: if (!dof) continue;
9081: for (s = 0; s < q; ++s)
9082: if (fpoints[p] == ftotpoints[s * 2]) break;
9083: if (s < q) continue;
9084: ftotpoints[q * 2] = fpoints[p];
9085: ftotpoints[q * 2 + 1] = fpoints[p + 1];
9086: ++q;
9087: }
9088: }
9089: PetscCall(DMPlexRestoreTransitiveClosure(dmf, point, PETSC_TRUE, &numFPoints, &fpoints));
9090: }
9091: numFPoints = q;
9092: for (p = 0, numFIndices = 0; p < numFPoints * 2; p += 2) {
9093: PetscInt fdof;
9095: PetscCall(PetscSectionGetDof(fsection, ftotpoints[p], &dof));
9096: if (!dof) continue;
9097: for (f = 0; f < numFields; ++f) {
9098: PetscCall(PetscSectionGetFieldDof(fsection, ftotpoints[p], f, &fdof));
9099: foffsets[f + 1] += fdof;
9100: }
9101: numFIndices += dof;
9102: }
9103: for (f = 1; f < numFields; ++f) foffsets[f + 1] += foffsets[f];
9105: PetscCheck(!numFields || foffsets[numFields] == numFIndices, PetscObjectComm((PetscObject)dmf), PETSC_ERR_PLIB, "Invalid size for closure %" PetscInt_FMT " should be %" PetscInt_FMT, foffsets[numFields], numFIndices);
9106: PetscCheck(!numFields || coffsets[numFields] == numCIndices, PetscObjectComm((PetscObject)dmc), PETSC_ERR_PLIB, "Invalid size for closure %" PetscInt_FMT " should be %" PetscInt_FMT, coffsets[numFields], numCIndices);
9107: PetscCall(DMGetWorkArray(dmf, numFIndices, MPIU_INT, &findices));
9108: PetscCall(DMGetWorkArray(dmc, numCIndices, MPIU_INT, &cindices));
9109: if (numFields) {
9110: const PetscInt **permsF[32] = {NULL};
9111: const PetscInt **permsC[32] = {NULL};
9113: for (f = 0; f < numFields; f++) {
9114: PetscCall(PetscSectionGetFieldPointSyms(fsection, f, numFPoints, ftotpoints, &permsF[f], NULL));
9115: PetscCall(PetscSectionGetFieldPointSyms(csection, f, numCPoints, cpoints, &permsC[f], NULL));
9116: }
9117: for (p = 0; p < numFPoints; p++) {
9118: PetscCall(PetscSectionGetOffset(globalFSection, ftotpoints[2 * p], &globalOff));
9119: PetscCall(DMPlexGetIndicesPointFields_Internal(fsection, PETSC_FALSE, ftotpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, foffsets, PETSC_FALSE, permsF, p, fclperm, findices));
9120: }
9121: for (p = 0; p < numCPoints; p++) {
9122: PetscCall(PetscSectionGetOffset(globalCSection, cpoints[2 * p], &globalOff));
9123: PetscCall(DMPlexGetIndicesPointFields_Internal(csection, PETSC_FALSE, cpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, coffsets, PETSC_FALSE, permsC, p, cclperm, cindices));
9124: }
9125: for (f = 0; f < numFields; f++) {
9126: PetscCall(PetscSectionRestoreFieldPointSyms(fsection, f, numFPoints, ftotpoints, &permsF[f], NULL));
9127: PetscCall(PetscSectionRestoreFieldPointSyms(csection, f, numCPoints, cpoints, &permsC[f], NULL));
9128: }
9129: } else {
9130: const PetscInt **permsF = NULL;
9131: const PetscInt **permsC = NULL;
9133: PetscCall(PetscSectionGetPointSyms(fsection, numFPoints, ftotpoints, &permsF, NULL));
9134: PetscCall(PetscSectionGetPointSyms(csection, numCPoints, cpoints, &permsC, NULL));
9135: for (p = 0, off = 0; p < numFPoints; p++) {
9136: const PetscInt *perm = permsF ? permsF[p] : NULL;
9138: PetscCall(PetscSectionGetOffset(globalFSection, ftotpoints[2 * p], &globalOff));
9139: PetscCall(DMPlexGetIndicesPoint_Internal(fsection, PETSC_FALSE, ftotpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, &off, PETSC_FALSE, perm, fclperm, findices));
9140: }
9141: for (p = 0, off = 0; p < numCPoints; p++) {
9142: const PetscInt *perm = permsC ? permsC[p] : NULL;
9144: PetscCall(PetscSectionGetOffset(globalCSection, cpoints[2 * p], &globalOff));
9145: PetscCall(DMPlexGetIndicesPoint_Internal(csection, PETSC_FALSE, cpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, &off, PETSC_FALSE, perm, cclperm, cindices));
9146: }
9147: PetscCall(PetscSectionRestorePointSyms(fsection, numFPoints, ftotpoints, &permsF, NULL));
9148: PetscCall(PetscSectionRestorePointSyms(csection, numCPoints, cpoints, &permsC, NULL));
9149: }
9150: if (mesh->printSetValues) PetscCall(DMPlexPrintMatSetValues(PETSC_VIEWER_STDOUT_SELF, A, point, numFIndices, findices, numCIndices, cindices, values));
9151: /* TODO: flips */
9152: /* TODO: fix this code to not use error codes as handle-able exceptions! */
9153: ierr = MatSetValues(A, numFIndices, findices, numCIndices, cindices, values, mode);
9154: if (ierr) {
9155: PetscMPIInt rank;
9157: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)A), &rank));
9158: PetscCall((*PetscErrorPrintf)("[%d]ERROR in DMPlexMatSetClosure\n", rank));
9159: PetscCall(DMPlexPrintMatSetValues(PETSC_VIEWER_STDERR_SELF, A, point, numFIndices, findices, numCIndices, cindices, values));
9160: PetscCall(DMRestoreWorkArray(dmf, numFIndices, MPIU_INT, &findices));
9161: PetscCall(DMRestoreWorkArray(dmc, numCIndices, MPIU_INT, &cindices));
9162: }
9163: PetscCall(DMRestoreWorkArray(dmf, numCPoints * 2 * 4, MPIU_INT, &ftotpoints));
9164: PetscCall(DMPlexRestoreTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints));
9165: PetscCall(DMRestoreWorkArray(dmf, numFIndices, MPIU_INT, &findices));
9166: PetscCall(DMRestoreWorkArray(dmc, numCIndices, MPIU_INT, &cindices));
9167: PetscFunctionReturn(PETSC_SUCCESS);
9168: }
9170: PetscErrorCode DMPlexMatGetClosureIndicesRefined(DM dmf, PetscSection fsection, PetscSection globalFSection, DM dmc, PetscSection csection, PetscSection globalCSection, PetscInt point, PetscInt cindices[], PetscInt findices[])
9171: {
9172: PetscInt *fpoints = NULL, *ftotpoints = NULL;
9173: PetscInt *cpoints = NULL;
9174: PetscInt foffsets[32] = {0}, coffsets[32] = {0};
9175: const PetscInt *fclperm = NULL, *cclperm = NULL; /* Closure permutations cannot work here */
9176: DMPolytopeType ct;
9177: PetscInt numFields, numSubcells, maxFPoints, numFPoints, numCPoints, numFIndices, numCIndices, dof, off, globalOff, pStart, pEnd, p, q, r, s, f;
9179: PetscFunctionBegin;
9182: if (!fsection) PetscCall(DMGetLocalSection(dmf, &fsection));
9184: if (!csection) PetscCall(DMGetLocalSection(dmc, &csection));
9186: if (!globalFSection) PetscCall(DMGetGlobalSection(dmf, &globalFSection));
9188: if (!globalCSection) PetscCall(DMGetGlobalSection(dmc, &globalCSection));
9190: PetscCall(PetscSectionGetNumFields(fsection, &numFields));
9191: PetscCheck(numFields <= 31, PetscObjectComm((PetscObject)dmf), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields %" PetscInt_FMT " limited to 31", numFields);
9192: /* Column indices */
9193: PetscCall(DMPlexGetTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints));
9194: maxFPoints = numCPoints;
9195: /* Compress out points not in the section */
9196: /* TODO: Squeeze out points with 0 dof as well */
9197: PetscCall(PetscSectionGetChart(csection, &pStart, &pEnd));
9198: for (p = 0, q = 0; p < numCPoints * 2; p += 2) {
9199: if ((cpoints[p] >= pStart) && (cpoints[p] < pEnd)) {
9200: cpoints[q * 2] = cpoints[p];
9201: cpoints[q * 2 + 1] = cpoints[p + 1];
9202: ++q;
9203: }
9204: }
9205: numCPoints = q;
9206: for (p = 0, numCIndices = 0; p < numCPoints * 2; p += 2) {
9207: PetscInt fdof;
9209: PetscCall(PetscSectionGetDof(csection, cpoints[p], &dof));
9210: if (!dof) continue;
9211: for (f = 0; f < numFields; ++f) {
9212: PetscCall(PetscSectionGetFieldDof(csection, cpoints[p], f, &fdof));
9213: coffsets[f + 1] += fdof;
9214: }
9215: numCIndices += dof;
9216: }
9217: for (f = 1; f < numFields; ++f) coffsets[f + 1] += coffsets[f];
9218: /* Row indices */
9219: PetscCall(DMPlexGetCellType(dmc, point, &ct));
9220: {
9221: DMPlexTransform tr;
9222: DMPolytopeType *rct;
9223: PetscInt *rsize, *rcone, *rornt, Nt;
9225: PetscCall(DMPlexTransformCreate(PETSC_COMM_SELF, &tr));
9226: PetscCall(DMPlexTransformSetType(tr, DMPLEXREFINEREGULAR));
9227: PetscCall(DMPlexTransformCellTransform(tr, ct, point, NULL, &Nt, &rct, &rsize, &rcone, &rornt));
9228: numSubcells = rsize[Nt - 1];
9229: PetscCall(DMPlexTransformDestroy(&tr));
9230: }
9231: PetscCall(DMGetWorkArray(dmf, maxFPoints * 2 * numSubcells, MPIU_INT, &ftotpoints));
9232: for (r = 0, q = 0; r < numSubcells; ++r) {
9233: /* TODO Map from coarse to fine cells */
9234: PetscCall(DMPlexGetTransitiveClosure(dmf, point * numSubcells + r, PETSC_TRUE, &numFPoints, &fpoints));
9235: /* Compress out points not in the section */
9236: PetscCall(PetscSectionGetChart(fsection, &pStart, &pEnd));
9237: for (p = 0; p < numFPoints * 2; p += 2) {
9238: if ((fpoints[p] >= pStart) && (fpoints[p] < pEnd)) {
9239: PetscCall(PetscSectionGetDof(fsection, fpoints[p], &dof));
9240: if (!dof) continue;
9241: for (s = 0; s < q; ++s)
9242: if (fpoints[p] == ftotpoints[s * 2]) break;
9243: if (s < q) continue;
9244: ftotpoints[q * 2] = fpoints[p];
9245: ftotpoints[q * 2 + 1] = fpoints[p + 1];
9246: ++q;
9247: }
9248: }
9249: PetscCall(DMPlexRestoreTransitiveClosure(dmf, point, PETSC_TRUE, &numFPoints, &fpoints));
9250: }
9251: numFPoints = q;
9252: for (p = 0, numFIndices = 0; p < numFPoints * 2; p += 2) {
9253: PetscInt fdof;
9255: PetscCall(PetscSectionGetDof(fsection, ftotpoints[p], &dof));
9256: if (!dof) continue;
9257: for (f = 0; f < numFields; ++f) {
9258: PetscCall(PetscSectionGetFieldDof(fsection, ftotpoints[p], f, &fdof));
9259: foffsets[f + 1] += fdof;
9260: }
9261: numFIndices += dof;
9262: }
9263: for (f = 1; f < numFields; ++f) foffsets[f + 1] += foffsets[f];
9265: PetscCheck(!numFields || foffsets[numFields] == numFIndices, PetscObjectComm((PetscObject)dmf), PETSC_ERR_PLIB, "Invalid size for closure %" PetscInt_FMT " should be %" PetscInt_FMT, foffsets[numFields], numFIndices);
9266: PetscCheck(!numFields || coffsets[numFields] == numCIndices, PetscObjectComm((PetscObject)dmc), PETSC_ERR_PLIB, "Invalid size for closure %" PetscInt_FMT " should be %" PetscInt_FMT, coffsets[numFields], numCIndices);
9267: if (numFields) {
9268: const PetscInt **permsF[32] = {NULL};
9269: const PetscInt **permsC[32] = {NULL};
9271: for (f = 0; f < numFields; f++) {
9272: PetscCall(PetscSectionGetFieldPointSyms(fsection, f, numFPoints, ftotpoints, &permsF[f], NULL));
9273: PetscCall(PetscSectionGetFieldPointSyms(csection, f, numCPoints, cpoints, &permsC[f], NULL));
9274: }
9275: for (p = 0; p < numFPoints; p++) {
9276: PetscCall(PetscSectionGetOffset(globalFSection, ftotpoints[2 * p], &globalOff));
9277: PetscCall(DMPlexGetIndicesPointFields_Internal(fsection, PETSC_FALSE, ftotpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, foffsets, PETSC_FALSE, permsF, p, fclperm, findices));
9278: }
9279: for (p = 0; p < numCPoints; p++) {
9280: PetscCall(PetscSectionGetOffset(globalCSection, cpoints[2 * p], &globalOff));
9281: PetscCall(DMPlexGetIndicesPointFields_Internal(csection, PETSC_FALSE, cpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, coffsets, PETSC_FALSE, permsC, p, cclperm, cindices));
9282: }
9283: for (f = 0; f < numFields; f++) {
9284: PetscCall(PetscSectionRestoreFieldPointSyms(fsection, f, numFPoints, ftotpoints, &permsF[f], NULL));
9285: PetscCall(PetscSectionRestoreFieldPointSyms(csection, f, numCPoints, cpoints, &permsC[f], NULL));
9286: }
9287: } else {
9288: const PetscInt **permsF = NULL;
9289: const PetscInt **permsC = NULL;
9291: PetscCall(PetscSectionGetPointSyms(fsection, numFPoints, ftotpoints, &permsF, NULL));
9292: PetscCall(PetscSectionGetPointSyms(csection, numCPoints, cpoints, &permsC, NULL));
9293: for (p = 0, off = 0; p < numFPoints; p++) {
9294: const PetscInt *perm = permsF ? permsF[p] : NULL;
9296: PetscCall(PetscSectionGetOffset(globalFSection, ftotpoints[2 * p], &globalOff));
9297: PetscCall(DMPlexGetIndicesPoint_Internal(fsection, PETSC_FALSE, ftotpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, &off, PETSC_FALSE, perm, fclperm, findices));
9298: }
9299: for (p = 0, off = 0; p < numCPoints; p++) {
9300: const PetscInt *perm = permsC ? permsC[p] : NULL;
9302: PetscCall(PetscSectionGetOffset(globalCSection, cpoints[2 * p], &globalOff));
9303: PetscCall(DMPlexGetIndicesPoint_Internal(csection, PETSC_FALSE, cpoints[2 * p], globalOff < 0 ? -(globalOff + 1) : globalOff, &off, PETSC_FALSE, perm, cclperm, cindices));
9304: }
9305: PetscCall(PetscSectionRestorePointSyms(fsection, numFPoints, ftotpoints, &permsF, NULL));
9306: PetscCall(PetscSectionRestorePointSyms(csection, numCPoints, cpoints, &permsC, NULL));
9307: }
9308: PetscCall(DMRestoreWorkArray(dmf, numCPoints * 2 * 4, MPIU_INT, &ftotpoints));
9309: PetscCall(DMPlexRestoreTransitiveClosure(dmc, point, PETSC_TRUE, &numCPoints, &cpoints));
9310: PetscFunctionReturn(PETSC_SUCCESS);
9311: }
9313: /*@
9314: DMPlexGetVTKCellHeight - Returns the height in the DAG used to determine which points are cells (normally 0)
9316: Input Parameter:
9317: . dm - The `DMPLEX` object
9319: Output Parameter:
9320: . cellHeight - The height of a cell
9322: Level: developer
9324: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSetVTKCellHeight()`
9325: @*/
9326: PetscErrorCode DMPlexGetVTKCellHeight(DM dm, PetscInt *cellHeight)
9327: {
9328: DM_Plex *mesh = (DM_Plex *)dm->data;
9330: PetscFunctionBegin;
9332: PetscAssertPointer(cellHeight, 2);
9333: *cellHeight = mesh->vtkCellHeight;
9334: PetscFunctionReturn(PETSC_SUCCESS);
9335: }
9337: /*@
9338: DMPlexSetVTKCellHeight - Sets the height in the DAG used to determine which points are cells (normally 0)
9340: Input Parameters:
9341: + dm - The `DMPLEX` object
9342: - cellHeight - The height of a cell
9344: Level: developer
9346: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetVTKCellHeight()`
9347: @*/
9348: PetscErrorCode DMPlexSetVTKCellHeight(DM dm, PetscInt cellHeight)
9349: {
9350: DM_Plex *mesh = (DM_Plex *)dm->data;
9352: PetscFunctionBegin;
9354: mesh->vtkCellHeight = cellHeight;
9355: PetscFunctionReturn(PETSC_SUCCESS);
9356: }
9358: /*@
9359: DMPlexGetCellTypeStratum - Get the range of cells of a given celltype
9361: Input Parameters:
9362: + dm - The `DMPLEX` object
9363: - ct - The `DMPolytopeType` of the cell
9365: Output Parameters:
9366: + start - The first cell of this type, or `NULL`
9367: - end - The upper bound on this celltype, or `NULL`
9369: Level: advanced
9371: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexConstructGhostCells()`, `DMPlexGetDepthStratum()`, `DMPlexGetHeightStratum()`
9372: @*/
9373: PetscErrorCode DMPlexGetCellTypeStratum(DM dm, DMPolytopeType ct, PeOp PetscInt *start, PeOp PetscInt *end)
9374: {
9375: DM_Plex *mesh = (DM_Plex *)dm->data;
9376: DMLabel label;
9377: PetscInt pStart, pEnd;
9379: PetscFunctionBegin;
9381: if (start) {
9382: PetscAssertPointer(start, 3);
9383: *start = 0;
9384: }
9385: if (end) {
9386: PetscAssertPointer(end, 4);
9387: *end = 0;
9388: }
9389: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
9390: if (pStart == pEnd) PetscFunctionReturn(PETSC_SUCCESS);
9391: if (mesh->tr) {
9392: PetscCall(DMPlexTransformGetCellTypeStratum(mesh->tr, ct, start, end));
9393: } else {
9394: PetscCall(DMPlexGetCellTypeLabel(dm, &label));
9395: PetscCheck(label, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "No label named celltype was found");
9396: PetscCall(DMLabelGetStratumBounds(label, ct, start, end));
9397: }
9398: PetscFunctionReturn(PETSC_SUCCESS);
9399: }
9401: /*@
9402: DMPlexGetDepthStratumGlobalSize - Get the global size for a given depth stratum
9404: Input Parameters:
9405: + dm - The `DMPLEX` object
9406: - depth - The depth for the given point stratum
9408: Output Parameter:
9409: . gsize - The global number of points in the stratum
9411: Level: advanced
9413: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellNumbering()`, `DMPlexGetVertexNumbering()`, `DMPlexGetDepthStratum()`, `DMPlexGetHeightStratum()`
9414: @*/
9415: PetscErrorCode DMPlexGetDepthStratumGlobalSize(DM dm, PetscInt depth, PetscInt *gsize)
9416: {
9417: PetscSF sf;
9418: const PetscInt *leaves;
9419: PetscInt Nl, loc, start, end, lsize = 0;
9421: PetscFunctionBegin;
9422: PetscCall(DMGetPointSF(dm, &sf));
9423: PetscCall(PetscSFGetGraph(sf, NULL, &Nl, &leaves, NULL));
9424: PetscCall(DMPlexGetDepthStratum(dm, depth, &start, &end));
9425: for (PetscInt p = start; p < end; ++p) {
9426: PetscCall(PetscFindInt(p, Nl, leaves, &loc));
9427: if (loc < 0) ++lsize;
9428: }
9429: PetscCallMPI(MPIU_Allreduce(&lsize, gsize, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)dm)));
9430: PetscFunctionReturn(PETSC_SUCCESS);
9431: }
9433: PetscErrorCode DMPlexCreateNumbering_Plex(DM dm, PetscInt pStart, PetscInt pEnd, PetscInt shift, PetscInt *globalSize, PetscSF sf, IS *numbering)
9434: {
9435: PetscSection section, globalSection;
9436: PetscInt *numbers, p;
9438: PetscFunctionBegin;
9439: if (PetscDefined(USE_DEBUG)) PetscCall(DMPlexCheckPointSF(dm, sf, PETSC_TRUE));
9440: PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), §ion));
9441: PetscCall(PetscSectionSetChart(section, pStart, pEnd));
9442: for (p = pStart; p < pEnd; ++p) PetscCall(PetscSectionSetDof(section, p, 1));
9443: PetscCall(PetscSectionSetUp(section));
9444: PetscCall(PetscSectionCreateGlobalSection(section, sf, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &globalSection));
9445: PetscCall(PetscMalloc1(pEnd - pStart, &numbers));
9446: for (p = pStart; p < pEnd; ++p) {
9447: PetscCall(PetscSectionGetOffset(globalSection, p, &numbers[p - pStart]));
9448: if (numbers[p - pStart] < 0) numbers[p - pStart] -= shift;
9449: else numbers[p - pStart] += shift;
9450: }
9451: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)dm), pEnd - pStart, numbers, PETSC_OWN_POINTER, numbering));
9452: if (globalSize) {
9453: PetscLayout layout;
9454: PetscCall(PetscSectionGetPointLayout(PetscObjectComm((PetscObject)dm), globalSection, &layout));
9455: PetscCall(PetscLayoutGetSize(layout, globalSize));
9456: PetscCall(PetscLayoutDestroy(&layout));
9457: }
9458: PetscCall(PetscSectionDestroy(§ion));
9459: PetscCall(PetscSectionDestroy(&globalSection));
9460: PetscFunctionReturn(PETSC_SUCCESS);
9461: }
9463: /*@
9464: DMPlexCreateCellNumbering - Get a global cell numbering for all cells on this process
9466: Input Parameters:
9467: + dm - The `DMPLEX` object
9468: - includeAll - Whether to include all cells, or just the simplex and box cells
9470: Output Parameter:
9471: . globalCellNumbers - Global cell numbers for all cells on this process
9473: Level: developer
9475: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellNumbering()`, `DMPlexGetVertexNumbering()`
9476: @*/
9477: PetscErrorCode DMPlexCreateCellNumbering(DM dm, PetscBool includeAll, IS *globalCellNumbers)
9478: {
9479: PetscInt cellHeight, cStart, cEnd;
9481: PetscFunctionBegin;
9482: PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
9483: if (includeAll) PetscCall(DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd));
9484: else PetscCall(DMPlexGetSimplexOrBoxCells(dm, cellHeight, &cStart, &cEnd));
9485: PetscCall(DMPlexCreateNumbering_Plex(dm, cStart, cEnd, 0, NULL, dm->sf, globalCellNumbers));
9486: PetscFunctionReturn(PETSC_SUCCESS);
9487: }
9489: /*@
9490: DMPlexGetCellNumbering - Get a global cell numbering for all cells on this process
9492: Input Parameter:
9493: . dm - The `DMPLEX` object
9495: Output Parameter:
9496: . globalCellNumbers - Global cell numbers for all cells on this process
9498: Level: developer
9500: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCreateCellNumbering()`, `DMPlexGetVertexNumbering()`
9501: @*/
9502: PetscErrorCode DMPlexGetCellNumbering(DM dm, IS *globalCellNumbers)
9503: {
9504: DM_Plex *mesh = (DM_Plex *)dm->data;
9506: PetscFunctionBegin;
9508: if (!mesh->globalCellNumbers) PetscCall(DMPlexCreateCellNumbering(dm, PETSC_FALSE, &mesh->globalCellNumbers));
9509: *globalCellNumbers = mesh->globalCellNumbers;
9510: PetscFunctionReturn(PETSC_SUCCESS);
9511: }
9513: PetscErrorCode DMPlexCreateVertexNumbering_Internal(DM dm, PetscBool includeHybrid, IS *globalVertexNumbers)
9514: {
9515: PetscInt vStart, vEnd;
9517: PetscFunctionBegin;
9519: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
9520: PetscCall(DMPlexCreateNumbering_Plex(dm, vStart, vEnd, 0, NULL, dm->sf, globalVertexNumbers));
9521: PetscFunctionReturn(PETSC_SUCCESS);
9522: }
9524: /*@
9525: DMPlexGetVertexNumbering - Get a global vertex numbering for all vertices on this process
9527: Input Parameter:
9528: . dm - The `DMPLEX` object
9530: Output Parameter:
9531: . globalVertexNumbers - Global vertex numbers for all vertices on this process
9533: Level: developer
9535: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellNumbering()`
9536: @*/
9537: PetscErrorCode DMPlexGetVertexNumbering(DM dm, IS *globalVertexNumbers)
9538: {
9539: DM_Plex *mesh = (DM_Plex *)dm->data;
9541: PetscFunctionBegin;
9543: if (!mesh->globalVertexNumbers) PetscCall(DMPlexCreateVertexNumbering_Internal(dm, PETSC_FALSE, &mesh->globalVertexNumbers));
9544: *globalVertexNumbers = mesh->globalVertexNumbers;
9545: PetscFunctionReturn(PETSC_SUCCESS);
9546: }
9548: /*@
9549: DMPlexCreatePointNumbering - Create a global numbering for all points.
9551: Collective
9553: Input Parameter:
9554: . dm - The `DMPLEX` object
9556: Output Parameter:
9557: . globalPointNumbers - Global numbers for all points on this process
9559: Level: developer
9561: Notes:
9562: The point numbering `IS` is parallel, with local portion indexed by local points (see `DMGetLocalSection()`). The global
9563: points are taken as stratified, with each MPI rank owning a contiguous subset of each stratum. In the IS, owned points
9564: will have their non-negative value while points owned by different ranks will be involuted -(idx+1). As an example,
9565: consider a parallel mesh in which the first two elements and first two vertices are owned by rank 0.
9567: The partitioned mesh is
9568: ```
9569: (2)--0--(3)--1--(4) (1)--0--(2)
9570: ```
9571: and its global numbering is
9572: ```
9573: (3)--0--(4)--1--(5)--2--(6)
9574: ```
9575: Then the global numbering is provided as
9576: ```
9577: [0] Number of indices in set 5
9578: [0] 0 0
9579: [0] 1 1
9580: [0] 2 3
9581: [0] 3 4
9582: [0] 4 -6
9583: [1] Number of indices in set 3
9584: [1] 0 2
9585: [1] 1 5
9586: [1] 2 6
9587: ```
9589: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellNumbering()`
9590: @*/
9591: PetscErrorCode DMPlexCreatePointNumbering(DM dm, IS *globalPointNumbers)
9592: {
9593: IS nums[4];
9594: PetscInt depths[4], gdepths[4], starts[4];
9595: PetscInt depth, d, shift = 0;
9596: PetscBool empty = PETSC_FALSE;
9598: PetscFunctionBegin;
9600: PetscCall(DMPlexGetDepth(dm, &depth));
9601: // For unstratified meshes use dim instead of depth
9602: if (depth < 0) PetscCall(DMGetDimension(dm, &depth));
9603: // If any stratum is empty, we must mark all empty
9604: for (d = 0; d <= depth; ++d) {
9605: PetscInt end;
9607: depths[d] = depth - d;
9608: PetscCall(DMPlexGetDepthStratum(dm, depths[d], &starts[d], &end));
9609: if (!(starts[d] - end)) empty = PETSC_TRUE;
9610: }
9611: if (empty)
9612: for (d = 0; d <= depth; ++d) {
9613: depths[d] = -1;
9614: starts[d] = -1;
9615: }
9616: else PetscCall(PetscSortIntWithArray(depth + 1, starts, depths));
9617: PetscCallMPI(MPIU_Allreduce(depths, gdepths, depth + 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm)));
9618: for (d = 0; d <= depth; ++d) PetscCheck(starts[d] < 0 || depths[d] == gdepths[d], PETSC_COMM_SELF, PETSC_ERR_PLIB, "Expected depth %" PetscInt_FMT ", found %" PetscInt_FMT, depths[d], gdepths[d]);
9619: // Note here that 'shift' is collective, so that the numbering is stratified by depth
9620: for (d = 0; d <= depth; ++d) {
9621: PetscInt pStart, pEnd, gsize;
9623: PetscCall(DMPlexGetDepthStratum(dm, gdepths[d], &pStart, &pEnd));
9624: PetscCall(DMPlexCreateNumbering_Plex(dm, pStart, pEnd, shift, &gsize, dm->sf, &nums[d]));
9625: shift += gsize;
9626: }
9627: PetscCall(ISConcatenate(PETSC_COMM_SELF, depth + 1, nums, globalPointNumbers));
9628: for (d = 0; d <= depth; ++d) PetscCall(ISDestroy(&nums[d]));
9629: PetscFunctionReturn(PETSC_SUCCESS);
9630: }
9632: /*@
9633: DMPlexCreateEdgeNumbering - Create a global numbering for edges.
9635: Collective
9637: Input Parameter:
9638: . dm - The `DMPLEX` object
9640: Output Parameter:
9641: . globalEdgeNumbers - Global numbers for all edges on this process
9643: Level: developer
9645: Notes:
9646: The point numbering `IS` is parallel, with local portion indexed by local points (see `DMGetLocalSection()`). In the IS, owned edges will have their non-negative value while edges owned by different ranks will be involuted -(idx+1).
9648: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetCellNumbering()`, `DMPlexGetVertexNumbering()`, `DMPlexCreatePointNumbering()`
9649: @*/
9650: PetscErrorCode DMPlexCreateEdgeNumbering(DM dm, IS *globalEdgeNumbers)
9651: {
9652: PetscSF sf;
9653: PetscInt eStart, eEnd;
9655: PetscFunctionBegin;
9657: PetscCall(DMGetPointSF(dm, &sf));
9658: PetscCall(DMPlexGetDepthStratum(dm, 1, &eStart, &eEnd));
9659: PetscCall(DMPlexCreateNumbering_Plex(dm, eStart, eEnd, 0, NULL, sf, globalEdgeNumbers));
9660: PetscFunctionReturn(PETSC_SUCCESS);
9661: }
9663: /*@
9664: DMPlexCreateRankField - Create a cell field whose value is the rank of the owner
9666: Input Parameter:
9667: . dm - The `DMPLEX` object
9669: Output Parameter:
9670: . ranks - The rank field
9672: Options Database Key:
9673: . -dm_partition_view - Adds the rank field into the `DM` output from `-dm_view` using the same viewer
9675: Level: intermediate
9677: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMView()`
9678: @*/
9679: PetscErrorCode DMPlexCreateRankField(DM dm, Vec *ranks)
9680: {
9681: DM rdm;
9682: PetscFE fe;
9683: PetscScalar *r;
9684: PetscMPIInt rank;
9685: DMPolytopeType ct;
9686: PetscInt dim, cStart, cEnd, c;
9688: PetscFunctionBeginUser;
9690: PetscAssertPointer(ranks, 2);
9691: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
9692: PetscCall(DMClone(dm, &rdm));
9693: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)rdm, "PETSc___rank_"));
9694: PetscCall(DMGetDimension(rdm, &dim));
9695: PetscCall(DMPlexGetHeightStratum(rdm, 0, &cStart, &cEnd));
9696: if (cEnd > cStart) PetscCall(DMPlexGetCellType(rdm, cStart, &ct));
9697: else ct = DM_POLYTOPE_SEGMENT;
9698: PetscCall(PetscFECreateLagrangeByCell(PETSC_COMM_SELF, dim, 1, ct, 0, -1, &fe));
9699: PetscCall(PetscObjectSetName((PetscObject)fe, "rank"));
9700: PetscCall(DMSetField(rdm, 0, NULL, (PetscObject)fe));
9701: PetscCall(PetscFEDestroy(&fe));
9702: PetscCall(DMCreateDS(rdm));
9703: PetscCall(DMViewFromOptions(rdm, NULL, "-dm_view"));
9704: PetscCall(DMCreateGlobalVector(rdm, ranks));
9705: PetscCall(PetscObjectSetName((PetscObject)*ranks, "partition"));
9706: PetscCall(VecGetArray(*ranks, &r));
9707: if (r) {
9708: for (c = cStart; c < cEnd; ++c) {
9709: PetscScalar *lr;
9711: PetscCall(DMPlexPointGlobalRef(rdm, c, r, &lr));
9712: if (lr) *lr = rank;
9713: }
9714: }
9715: PetscCall(VecRestoreArray(*ranks, &r));
9716: PetscCall(DMDestroy(&rdm));
9717: PetscFunctionReturn(PETSC_SUCCESS);
9718: }
9720: /*@
9721: DMPlexCreateLabelField - Create a field whose value is the label value for that point
9723: Input Parameters:
9724: + dm - The `DMPLEX`
9725: - label - The `DMLabel`
9727: Output Parameter:
9728: . val - The label value field
9730: Options Database Key:
9731: . -dm_label_view - Adds the label value field into the `DM` output from `-dm_view` using the same viewer
9733: Level: intermediate
9735: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMView()`
9736: @*/
9737: PetscErrorCode DMPlexCreateLabelField(DM dm, DMLabel label, Vec *val)
9738: {
9739: DM rdm, plex;
9740: Vec lval;
9741: PetscSection section;
9742: PetscFE fe;
9743: PetscScalar *v;
9744: PetscInt dim, pStart, pEnd, p, cStart;
9745: DMPolytopeType ct;
9746: char name[PETSC_MAX_PATH_LEN];
9747: const char *lname, *prefix;
9749: PetscFunctionBeginUser;
9751: PetscAssertPointer(label, 2);
9752: PetscAssertPointer(val, 3);
9753: PetscCall(DMClone(dm, &rdm));
9754: PetscCall(DMConvert(rdm, DMPLEX, &plex));
9755: PetscCall(DMPlexGetHeightStratum(plex, 0, &cStart, NULL));
9756: PetscCall(DMPlexGetCellType(plex, cStart, &ct));
9757: PetscCall(DMDestroy(&plex));
9758: PetscCall(DMGetDimension(rdm, &dim));
9759: PetscCall(DMGetOptionsPrefix(dm, &prefix));
9760: PetscCall(PetscObjectGetName((PetscObject)label, &lname));
9761: PetscCall(PetscSNPrintf(name, sizeof(name), "%s%s_", prefix ? prefix : "", lname));
9762: PetscCall(PetscFECreateByCell(PETSC_COMM_SELF, dim, 1, ct, name, -1, &fe));
9763: PetscCall(PetscObjectSetName((PetscObject)fe, ""));
9764: PetscCall(DMSetField(rdm, 0, NULL, (PetscObject)fe));
9765: PetscCall(PetscFEDestroy(&fe));
9766: PetscCall(DMCreateDS(rdm));
9767: PetscCall(DMCreateGlobalVector(rdm, val));
9768: PetscCall(DMCreateLocalVector(rdm, &lval));
9769: PetscCall(PetscObjectSetName((PetscObject)*val, lname));
9770: PetscCall(DMGetLocalSection(rdm, §ion));
9771: PetscCall(PetscSectionGetChart(section, &pStart, &pEnd));
9772: PetscCall(VecGetArray(lval, &v));
9773: for (p = pStart; p < pEnd; ++p) {
9774: PetscInt cval, dof, off;
9776: PetscCall(PetscSectionGetDof(section, p, &dof));
9777: if (!dof) continue;
9778: PetscCall(DMLabelGetValue(label, p, &cval));
9779: PetscCall(PetscSectionGetOffset(section, p, &off));
9780: for (PetscInt d = 0; d < dof; d++) v[off + d] = cval;
9781: }
9782: PetscCall(VecRestoreArray(lval, &v));
9783: PetscCall(DMLocalToGlobal(rdm, lval, INSERT_VALUES, *val));
9784: PetscCall(VecDestroy(&lval));
9785: PetscCall(DMDestroy(&rdm));
9786: PetscFunctionReturn(PETSC_SUCCESS);
9787: }
9789: /*@
9790: DMPlexCheckSymmetry - Check that the adjacency information in the mesh is symmetric.
9792: Input Parameter:
9793: . dm - The `DMPLEX` object
9795: Level: developer
9797: Notes:
9798: This is a useful diagnostic when creating meshes programmatically.
9800: For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.
9802: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMCreate()`, `DMSetFromOptions()`
9803: @*/
9804: PetscErrorCode DMPlexCheckSymmetry(DM dm)
9805: {
9806: PetscSection coneSection, supportSection;
9807: const PetscInt *cone, *support;
9808: PetscInt coneSize, c, supportSize, s;
9809: PetscInt pStart, pEnd, p, pp, csize, ssize;
9810: PetscBool storagecheck = PETSC_TRUE;
9812: PetscFunctionBegin;
9814: PetscCall(DMViewFromOptions(dm, NULL, "-sym_dm_view"));
9815: PetscCall(DMPlexGetConeSection(dm, &coneSection));
9816: PetscCall(DMPlexGetSupportSection(dm, &supportSection));
9817: /* Check that point p is found in the support of its cone points, and vice versa */
9818: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
9819: for (p = pStart; p < pEnd; ++p) {
9820: PetscCall(DMPlexGetConeSize(dm, p, &coneSize));
9821: PetscCall(DMPlexGetCone(dm, p, &cone));
9822: for (c = 0; c < coneSize; ++c) {
9823: PetscBool dup = PETSC_FALSE;
9824: for (PetscInt d = c - 1; d >= 0; --d) {
9825: if (cone[c] == cone[d]) {
9826: dup = PETSC_TRUE;
9827: break;
9828: }
9829: }
9830: PetscCall(DMPlexGetSupportSize(dm, cone[c], &supportSize));
9831: PetscCall(DMPlexGetSupport(dm, cone[c], &support));
9832: for (s = 0; s < supportSize; ++s) {
9833: if (support[s] == p) break;
9834: }
9835: if ((s >= supportSize) || (dup && (support[s + 1] != p))) {
9836: PetscCall(PetscPrintf(PETSC_COMM_SELF, "p: %" PetscInt_FMT " cone: ", p));
9837: for (s = 0; s < coneSize; ++s) PetscCall(PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT ", ", cone[s]));
9838: PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
9839: PetscCall(PetscPrintf(PETSC_COMM_SELF, "p: %" PetscInt_FMT " support: ", cone[c]));
9840: for (s = 0; s < supportSize; ++s) PetscCall(PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT ", ", support[s]));
9841: PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
9842: PetscCheck(!dup, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %" PetscInt_FMT " not repeatedly found in support of repeated cone point %" PetscInt_FMT, p, cone[c]);
9843: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %" PetscInt_FMT " not found in support of cone point %" PetscInt_FMT, p, cone[c]);
9844: }
9845: }
9846: PetscCall(DMPlexGetTreeParent(dm, p, &pp, NULL));
9847: if (p != pp) {
9848: storagecheck = PETSC_FALSE;
9849: continue;
9850: }
9851: PetscCall(DMPlexGetSupportSize(dm, p, &supportSize));
9852: PetscCall(DMPlexGetSupport(dm, p, &support));
9853: for (s = 0; s < supportSize; ++s) {
9854: PetscCall(DMPlexGetConeSize(dm, support[s], &coneSize));
9855: PetscCall(DMPlexGetCone(dm, support[s], &cone));
9856: for (c = 0; c < coneSize; ++c) {
9857: PetscCall(DMPlexGetTreeParent(dm, cone[c], &pp, NULL));
9858: if (cone[c] != pp) {
9859: c = 0;
9860: break;
9861: }
9862: if (cone[c] == p) break;
9863: }
9864: if (c >= coneSize) {
9865: PetscCall(PetscPrintf(PETSC_COMM_SELF, "p: %" PetscInt_FMT " support: ", p));
9866: for (c = 0; c < supportSize; ++c) PetscCall(PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT ", ", support[c]));
9867: PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
9868: PetscCall(PetscPrintf(PETSC_COMM_SELF, "p: %" PetscInt_FMT " cone: ", support[s]));
9869: for (c = 0; c < coneSize; ++c) PetscCall(PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT ", ", cone[c]));
9870: PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
9871: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point %" PetscInt_FMT " not found in cone of support point %" PetscInt_FMT, p, support[s]);
9872: }
9873: }
9874: }
9875: if (storagecheck) {
9876: PetscCall(PetscSectionGetStorageSize(coneSection, &csize));
9877: PetscCall(PetscSectionGetStorageSize(supportSection, &ssize));
9878: PetscCheck(csize == ssize, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Total cone size %" PetscInt_FMT " != Total support size %" PetscInt_FMT, csize, ssize);
9879: }
9880: PetscFunctionReturn(PETSC_SUCCESS);
9881: }
9883: /*
9884: For submeshes with cohesive cells (see DMPlexConstructCohesiveCells()), we allow a special case where some of the boundary of a face (edges and vertices) are not duplicated. We call these special boundary points "unsplit", since the same edge or vertex appears in both copies of the face. These unsplit points throw off our counting, so we have to explicitly account for them here.
9885: */
9886: static PetscErrorCode DMPlexCellUnsplitVertices_Private(DM dm, PetscInt c, DMPolytopeType ct, PetscInt *unsplit)
9887: {
9888: DMPolytopeType cct;
9889: PetscInt ptpoints[4];
9890: const PetscInt *cone, *ccone, *ptcone;
9891: PetscInt coneSize, cp, cconeSize, ccp, npt = 0, pt;
9893: PetscFunctionBegin;
9894: *unsplit = 0;
9895: switch (ct) {
9896: case DM_POLYTOPE_POINT_PRISM_TENSOR:
9897: ptpoints[npt++] = c;
9898: break;
9899: case DM_POLYTOPE_SEG_PRISM_TENSOR:
9900: PetscCall(DMPlexGetCone(dm, c, &cone));
9901: PetscCall(DMPlexGetConeSize(dm, c, &coneSize));
9902: for (cp = 0; cp < coneSize; ++cp) {
9903: PetscCall(DMPlexGetCellType(dm, cone[cp], &cct));
9904: if (cct == DM_POLYTOPE_POINT_PRISM_TENSOR) ptpoints[npt++] = cone[cp];
9905: }
9906: break;
9907: case DM_POLYTOPE_TRI_PRISM_TENSOR:
9908: case DM_POLYTOPE_QUAD_PRISM_TENSOR:
9909: PetscCall(DMPlexGetCone(dm, c, &cone));
9910: PetscCall(DMPlexGetConeSize(dm, c, &coneSize));
9911: for (cp = 0; cp < coneSize; ++cp) {
9912: PetscCall(DMPlexGetCone(dm, cone[cp], &ccone));
9913: PetscCall(DMPlexGetConeSize(dm, cone[cp], &cconeSize));
9914: for (ccp = 0; ccp < cconeSize; ++ccp) {
9915: PetscCall(DMPlexGetCellType(dm, ccone[ccp], &cct));
9916: if (cct == DM_POLYTOPE_POINT_PRISM_TENSOR) {
9917: PetscInt p;
9918: for (p = 0; p < npt; ++p)
9919: if (ptpoints[p] == ccone[ccp]) break;
9920: if (p == npt) ptpoints[npt++] = ccone[ccp];
9921: }
9922: }
9923: }
9924: break;
9925: default:
9926: break;
9927: }
9928: for (pt = 0; pt < npt; ++pt) {
9929: PetscCall(DMPlexGetCone(dm, ptpoints[pt], &ptcone));
9930: if (ptcone[0] == ptcone[1]) ++(*unsplit);
9931: }
9932: PetscFunctionReturn(PETSC_SUCCESS);
9933: }
9935: /*@
9936: DMPlexCheckSkeleton - Check that each cell has the correct number of vertices
9938: Input Parameters:
9939: + dm - The `DMPLEX` object
9940: - cellHeight - Normally 0
9942: Level: developer
9944: Notes:
9945: This is a useful diagnostic when creating meshes programmatically.
9946: Currently applicable only to homogeneous simplex or tensor meshes.
9948: For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.
9950: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMCreate()`, `DMSetFromOptions()`
9951: @*/
9952: PetscErrorCode DMPlexCheckSkeleton(DM dm, PetscInt cellHeight)
9953: {
9954: DMPlexInterpolatedFlag interp;
9955: DMPolytopeType ct;
9956: PetscInt vStart, vEnd, cStart, cEnd, c;
9958: PetscFunctionBegin;
9960: PetscCall(DMPlexIsInterpolated(dm, &interp));
9961: PetscCall(DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd));
9962: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
9963: for (c = cStart; c < cEnd; ++c) {
9964: PetscInt *closure = NULL;
9965: PetscInt coneSize, closureSize, cl, Nv = 0;
9967: PetscCall(DMPlexGetCellType(dm, c, &ct));
9968: if (ct == DM_POLYTOPE_UNKNOWN) continue;
9969: if (interp == DMPLEX_INTERPOLATED_FULL) {
9970: PetscCall(DMPlexGetConeSize(dm, c, &coneSize));
9971: PetscCheck(coneSize == DMPolytopeTypeGetConeSize(ct), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %" PetscInt_FMT " of type %s has cone size %" PetscInt_FMT " != %" PetscInt_FMT, c, DMPolytopeTypes[ct], coneSize, DMPolytopeTypeGetConeSize(ct));
9972: }
9973: PetscCall(DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
9974: for (cl = 0; cl < closureSize * 2; cl += 2) {
9975: const PetscInt p = closure[cl];
9976: if ((p >= vStart) && (p < vEnd)) ++Nv;
9977: }
9978: PetscCall(DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
9979: /* Special Case: Tensor faces with identified vertices */
9980: if (Nv < DMPolytopeTypeGetNumVertices(ct)) {
9981: PetscInt unsplit;
9983: PetscCall(DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit));
9984: if (Nv + unsplit == DMPolytopeTypeGetNumVertices(ct)) continue;
9985: }
9986: PetscCheck(Nv == DMPolytopeTypeGetNumVertices(ct), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %" PetscInt_FMT " of type %s has %" PetscInt_FMT " vertices != %" PetscInt_FMT, c, DMPolytopeTypes[ct], Nv, DMPolytopeTypeGetNumVertices(ct));
9987: }
9988: PetscFunctionReturn(PETSC_SUCCESS);
9989: }
9991: /*@
9992: DMPlexCheckFaces - Check that the faces of each cell give a vertex order this is consistent with what we expect from the cell type
9994: Collective
9996: Input Parameters:
9997: + dm - The `DMPLEX` object
9998: - cellHeight - Normally 0
10000: Level: developer
10002: Notes:
10003: This is a useful diagnostic when creating meshes programmatically.
10004: This routine is only relevant for meshes that are fully interpolated across all ranks.
10005: It will error out if a partially interpolated mesh is given on some rank.
10006: It will do nothing for locally uninterpolated mesh (as there is nothing to check).
10008: For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.
10010: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMCreate()`, `DMPlexGetVTKCellHeight()`, `DMSetFromOptions()`
10011: @*/
10012: PetscErrorCode DMPlexCheckFaces(DM dm, PetscInt cellHeight)
10013: {
10014: PetscInt dim, depth, vStart, vEnd, cStart, cEnd, c, h;
10015: DMPlexInterpolatedFlag interpEnum;
10017: PetscFunctionBegin;
10019: PetscCall(DMPlexIsInterpolatedCollective(dm, &interpEnum));
10020: if (interpEnum == DMPLEX_INTERPOLATED_NONE) PetscFunctionReturn(PETSC_SUCCESS);
10021: if (interpEnum != DMPLEX_INTERPOLATED_FULL) {
10022: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), "DMPlexCheckFaces() warning: Mesh is only partially interpolated, this is currently not supported"));
10023: PetscFunctionReturn(PETSC_SUCCESS);
10024: }
10026: PetscCall(DMGetDimension(dm, &dim));
10027: PetscCall(DMPlexGetDepth(dm, &depth));
10028: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
10029: for (h = cellHeight; h < PetscMin(depth, dim); ++h) {
10030: PetscCall(DMPlexGetHeightStratum(dm, h, &cStart, &cEnd));
10031: for (c = cStart; c < cEnd; ++c) {
10032: const PetscInt *cone, *ornt, *faceSizes, *faces;
10033: const DMPolytopeType *faceTypes;
10034: DMPolytopeType ct;
10035: PetscInt numFaces, coneSize, f;
10036: PetscInt *closure = NULL, closureSize, cl, numCorners = 0, fOff = 0, unsplit;
10038: PetscCall(DMPlexGetCellType(dm, c, &ct));
10039: PetscCall(DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit));
10040: if (unsplit) continue;
10041: PetscCall(DMPlexGetConeSize(dm, c, &coneSize));
10042: PetscCall(DMPlexGetCone(dm, c, &cone));
10043: PetscCall(DMPlexGetConeOrientation(dm, c, &ornt));
10044: PetscCall(DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
10045: for (cl = 0; cl < closureSize * 2; cl += 2) {
10046: const PetscInt p = closure[cl];
10047: if ((p >= vStart) && (p < vEnd)) closure[numCorners++] = p;
10048: }
10049: PetscCall(DMPlexGetRawFaces_Internal(dm, ct, closure, &numFaces, &faceTypes, &faceSizes, &faces));
10050: PetscCheck(coneSize == numFaces, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cell %" PetscInt_FMT " of type %s has %" PetscInt_FMT " faces but should have %" PetscInt_FMT, c, DMPolytopeTypes[ct], coneSize, numFaces);
10051: for (f = 0; f < numFaces; ++f) {
10052: DMPolytopeType fct;
10053: PetscInt *fclosure = NULL, fclosureSize, cl, fnumCorners = 0, v;
10055: PetscCall(DMPlexGetCellType(dm, cone[f], &fct));
10056: PetscCall(DMPlexGetTransitiveClosure_Internal(dm, cone[f], ornt[f], PETSC_TRUE, &fclosureSize, &fclosure));
10057: for (cl = 0; cl < fclosureSize * 2; cl += 2) {
10058: const PetscInt p = fclosure[cl];
10059: if ((p >= vStart) && (p < vEnd)) fclosure[fnumCorners++] = p;
10060: }
10061: PetscCheck(fnumCorners == faceSizes[f], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " of type %s (cone idx %" PetscInt_FMT ") of cell %" PetscInt_FMT " of type %s has %" PetscInt_FMT " vertices but should have %" PetscInt_FMT, cone[f], DMPolytopeTypes[fct], f, c, DMPolytopeTypes[ct], fnumCorners, faceSizes[f]);
10062: for (v = 0; v < fnumCorners; ++v) {
10063: if (fclosure[v] != faces[fOff + v]) {
10064: PetscCall(PetscPrintf(PETSC_COMM_SELF, "face closure:"));
10065: for (PetscInt v1 = 0; v1 < fnumCorners; ++v1) PetscCall(PetscPrintf(PETSC_COMM_SELF, " %" PetscInt_FMT, fclosure[v1]));
10066: PetscCall(PetscPrintf(PETSC_COMM_SELF, "\ncell face:"));
10067: for (PetscInt v1 = 0; v1 < fnumCorners; ++v1) PetscCall(PetscPrintf(PETSC_COMM_SELF, " %" PetscInt_FMT, faces[fOff + v1]));
10068: PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
10069: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Face %" PetscInt_FMT " of type %s (cone idx %" PetscInt_FMT ", ornt %" PetscInt_FMT ") of cell %" PetscInt_FMT " of type %s vertex %" PetscInt_FMT ", %" PetscInt_FMT " != %" PetscInt_FMT, cone[f], DMPolytopeTypes[fct], f, ornt[f], c, DMPolytopeTypes[ct], v, fclosure[v], faces[fOff + v]);
10070: }
10071: }
10072: PetscCall(DMPlexRestoreTransitiveClosure(dm, cone[f], PETSC_TRUE, &fclosureSize, &fclosure));
10073: fOff += faceSizes[f];
10074: }
10075: PetscCall(DMPlexRestoreRawFaces_Internal(dm, ct, closure, &numFaces, &faceTypes, &faceSizes, &faces));
10076: PetscCall(DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &closureSize, &closure));
10077: }
10078: }
10079: PetscFunctionReturn(PETSC_SUCCESS);
10080: }
10082: /*@
10083: DMPlexCheckGeometry - Check the geometry of mesh cells
10085: Input Parameter:
10086: . dm - The `DMPLEX` object
10088: Level: developer
10090: Notes:
10091: This is a useful diagnostic when creating meshes programmatically.
10093: For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.
10095: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMCreate()`, `DMSetFromOptions()`
10096: @*/
10097: PetscErrorCode DMPlexCheckGeometry(DM dm)
10098: {
10099: Vec coordinates;
10100: PetscReal detJ, J[9], refVol = 1.0;
10101: PetscReal vol;
10102: PetscInt dim, depth, dE, d, cStart, cEnd, c;
10104: PetscFunctionBegin;
10105: PetscCall(DMGetDimension(dm, &dim));
10106: PetscCall(DMGetCoordinateDim(dm, &dE));
10107: if (dim != dE) PetscFunctionReturn(PETSC_SUCCESS);
10108: PetscCall(DMPlexGetDepth(dm, &depth));
10109: for (d = 0; d < dim; ++d) refVol *= 2.0;
10110: PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
10111: /* Make sure local coordinates are created, because that step is collective */
10112: PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
10113: if (!coordinates) PetscFunctionReturn(PETSC_SUCCESS);
10114: for (c = cStart; c < cEnd; ++c) {
10115: DMPolytopeType ct;
10116: PetscInt unsplit;
10117: PetscBool ignoreZeroVol = PETSC_FALSE;
10119: PetscCall(DMPlexGetCellType(dm, c, &ct));
10120: switch (ct) {
10121: case DM_POLYTOPE_SEG_PRISM_TENSOR:
10122: case DM_POLYTOPE_TRI_PRISM_TENSOR:
10123: case DM_POLYTOPE_QUAD_PRISM_TENSOR:
10124: ignoreZeroVol = PETSC_TRUE;
10125: break;
10126: default:
10127: break;
10128: }
10129: switch (ct) {
10130: case DM_POLYTOPE_TRI_PRISM:
10131: case DM_POLYTOPE_TRI_PRISM_TENSOR:
10132: case DM_POLYTOPE_QUAD_PRISM_TENSOR:
10133: case DM_POLYTOPE_PYRAMID:
10134: continue;
10135: default:
10136: break;
10137: }
10138: PetscCall(DMPlexCellUnsplitVertices_Private(dm, c, ct, &unsplit));
10139: if (unsplit) continue;
10140: PetscCall(DMPlexComputeCellGeometryFEM(dm, c, NULL, NULL, J, NULL, &detJ));
10141: PetscCheck(detJ >= -PETSC_SMALL && (detJ > 0.0 || ignoreZeroVol), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh cell %" PetscInt_FMT " of type %s is inverted, |J| = %g", c, DMPolytopeTypes[ct], (double)detJ);
10142: PetscCall(PetscInfo(dm, "Cell %" PetscInt_FMT " FEM Volume %g\n", c, (double)(detJ * refVol)));
10143: /* This should work with periodicity since DG coordinates should be used */
10144: if (depth > 1) {
10145: PetscCall(DMPlexComputeCellGeometryFVM(dm, c, &vol, NULL, NULL));
10146: PetscCheck(vol >= -PETSC_SMALL && (vol > 0.0 || ignoreZeroVol), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh cell %" PetscInt_FMT " of type %s is inverted, vol = %g", c, DMPolytopeTypes[ct], (double)vol);
10147: PetscCall(PetscInfo(dm, "Cell %" PetscInt_FMT " FVM Volume %g\n", c, (double)vol));
10148: }
10149: }
10150: PetscFunctionReturn(PETSC_SUCCESS);
10151: }
10153: /*@
10154: DMPlexCheckPointSF - Check that several necessary conditions are met for the point `PetscSF` of this plex.
10156: Collective
10158: Input Parameters:
10159: + dm - The `DMPLEX` object
10160: . pointSF - The `PetscSF`, or `NULL` for `PointSF` attached to `DM`
10161: - allowExtraRoots - Flag to allow extra points not present in the `DM`
10163: Level: developer
10165: Notes:
10166: This is mainly intended for debugging/testing purposes.
10168: For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.
10170: Extra roots can come from periodic cuts, where additional points appear on the boundary
10172: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMGetPointSF()`, `DMSetFromOptions()`
10173: @*/
10174: PetscErrorCode DMPlexCheckPointSF(DM dm, PetscSF pointSF, PetscBool allowExtraRoots)
10175: {
10176: PetscInt l, nleaves, nroots, overlap;
10177: const PetscInt *locals;
10178: const PetscSFNode *remotes;
10179: PetscBool distributed;
10180: MPI_Comm comm;
10181: PetscMPIInt rank;
10183: PetscFunctionBegin;
10186: else pointSF = dm->sf;
10187: PetscCall(DMViewFromOptions(dm, NULL, "-dm_plex_point_sf_view"));
10188: PetscCall(PetscSFViewFromOptions(pointSF, NULL, "-dm_plex_point_sf_view"));
10189: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
10190: PetscCheck(pointSF, comm, PETSC_ERR_ARG_WRONGSTATE, "DMPlex must have Point SF attached");
10191: PetscCallMPI(MPI_Comm_rank(comm, &rank));
10192: {
10193: PetscMPIInt mpiFlag;
10195: PetscCallMPI(MPI_Comm_compare(comm, PetscObjectComm((PetscObject)pointSF), &mpiFlag));
10196: PetscCheck(mpiFlag == MPI_CONGRUENT || mpiFlag == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "DM and Point SF have different communicators (flag %d)", mpiFlag);
10197: }
10198: PetscCall(PetscSFGetGraph(pointSF, &nroots, &nleaves, &locals, &remotes));
10199: PetscCall(DMPlexIsDistributed(dm, &distributed));
10200: if (!distributed) {
10201: PetscCheck(nroots < 0 || nleaves == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Undistributed DMPlex cannot have non-empty PointSF (has %" PetscInt_FMT " roots, %" PetscInt_FMT " leaves)", nroots, nleaves);
10202: PetscFunctionReturn(PETSC_SUCCESS);
10203: }
10204: PetscCheck(nroots >= 0, comm, PETSC_ERR_ARG_WRONGSTATE, "This DMPlex is distributed but its PointSF has no graph set (has %" PetscInt_FMT " roots, %" PetscInt_FMT " leaves)", nroots, nleaves);
10205: PetscCall(DMPlexGetOverlap(dm, &overlap));
10207: /* Check SF graph is compatible with DMPlex chart */
10208: {
10209: PetscInt pStart, pEnd, maxLeaf;
10211: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
10212: PetscCall(PetscSFGetLeafRange(pointSF, NULL, &maxLeaf));
10213: PetscCheck(allowExtraRoots || pEnd - pStart == nroots, PETSC_COMM_SELF, PETSC_ERR_PLIB, "pEnd - pStart = %" PetscInt_FMT " != nroots = %" PetscInt_FMT, pEnd - pStart, nroots);
10214: PetscCheck(maxLeaf < pEnd, PETSC_COMM_SELF, PETSC_ERR_PLIB, "maxLeaf = %" PetscInt_FMT " >= pEnd = %" PetscInt_FMT, maxLeaf, pEnd);
10215: }
10217: /* Check there are no cells in interface */
10218: if (!overlap) {
10219: PetscInt cellHeight, cStart, cEnd;
10221: PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
10222: PetscCall(DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd));
10223: for (l = 0; l < nleaves; ++l) {
10224: const PetscInt point = locals ? locals[l] : l;
10226: PetscCheck(point < cStart || point >= cEnd, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point SF contains %" PetscInt_FMT " which is a cell", point);
10227: }
10228: }
10230: /* If some point is in interface, then all its cone points must be also in interface (either as leaves or roots) */
10231: {
10232: const PetscInt *rootdegree;
10234: PetscCall(PetscSFComputeDegreeBegin(pointSF, &rootdegree));
10235: PetscCall(PetscSFComputeDegreeEnd(pointSF, &rootdegree));
10236: for (l = 0; l < nleaves; ++l) {
10237: const PetscInt point = locals ? locals[l] : l;
10238: const PetscInt *cone;
10239: PetscInt coneSize, c, idx;
10241: PetscCall(DMPlexGetConeSize(dm, point, &coneSize));
10242: PetscCall(DMPlexGetCone(dm, point, &cone));
10243: for (c = 0; c < coneSize; ++c) {
10244: if (!rootdegree[cone[c]]) {
10245: if (locals) PetscCall(PetscFindInt(cone[c], nleaves, locals, &idx));
10246: else idx = (cone[c] < nleaves) ? cone[c] : -1;
10247: PetscCheck(idx >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Point SF contains %" PetscInt_FMT " but not %" PetscInt_FMT " from its cone", point, cone[c]);
10248: }
10249: }
10250: }
10251: }
10253: // Depths of leaves should match depths of root
10254: // Does not work for geometrically non-conforming meshes
10255: if (!((DM_Plex *)dm->data)->parentSection) {
10256: PetscInt *starts, *gstarts, *depths;
10257: PetscInt depth;
10258: PetscMPIInt size;
10259: PetscBool skip = PETSC_FALSE;
10261: PetscCallMPI(MPI_Comm_size(comm, &size));
10262: PetscCall(DMPlexGetDepth(dm, &depth));
10263: PetscCall(PetscMalloc3(depth + 2, &starts, size * (depth + 2), &gstarts, depth + 2, &depths));
10264: depths[0] = depth;
10265: depths[1] = 0;
10266: for (PetscInt d = 2; d <= depth; ++d) depths[d] = depth + 1 - d;
10267: depths[depth + 1] = depth + 1;
10268: for (PetscInt d = 0; d <= depth; ++d) {
10269: PetscCall(DMPlexGetDepthStratum(dm, d, &starts[d], NULL));
10270: }
10271: // This is necessary because some strata might be missing
10272: PetscCall(DMPlexGetChart(dm, NULL, &starts[depth + 1]));
10273: PetscCallMPI(MPI_Allgather(starts, (int)(depth + 2), MPIU_INT, gstarts, (int)(depth + 2), MPIU_INT, comm));
10274: // Check is invalid with empty strata
10275: for (PetscInt p = 0; p < size * (depth + 2); ++p)
10276: if (gstarts[p] < 0) skip = PETSC_TRUE;
10277: for (l = skip ? nleaves : 0; l < nleaves; ++l) {
10278: const PetscInt point = locals ? locals[l] : l;
10279: const PetscInt rpoint = remotes[l].index;
10280: const PetscInt rrank = remotes[l].rank;
10281: PetscInt pdepth, rdepth = -1;
10283: PetscCall(DMPlexGetPointDepth(dm, point, &pdepth));
10284: for (PetscInt d = 0; d <= depth; ++d) {
10285: if (gstarts[rrank * (depth + 2) + depths[d]] <= rpoint && rpoint < gstarts[rrank * (depth + 2) + depths[d + 1]]) {
10286: rdepth = depths[d];
10287: break;
10288: }
10289: }
10290: PetscCheck(rdepth != -1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Leaf %" PetscInt_FMT " (%" PetscInt_FMT ") was not found on remote rank %" PetscInt_FMT, point, rpoint, rrank);
10291: PetscCheck(pdepth == rdepth, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Leaf %" PetscInt_FMT " has depth %" PetscInt_FMT " but remote (%" PetscInt_FMT ", %" PetscInt_FMT ") depth is %" PetscInt_FMT, point, pdepth, rpoint, rrank, rdepth);
10292: }
10293: PetscCall(PetscFree3(starts, gstarts, depths));
10294: }
10295: PetscFunctionReturn(PETSC_SUCCESS);
10296: }
10298: /*@
10299: DMPlexCheckOrphanVertices - Check that no vertices are disconnected from the mesh, unless the mesh only consists of disconnected vertices.
10301: Collective
10303: Input Parameter:
10304: . dm - The `DMPLEX` object
10306: Level: developer
10308: Notes:
10309: This is mainly intended for debugging/testing purposes.
10311: Other cell types which are disconnected would be caught by the symmetry and face checks.
10313: For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.
10315: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCheck()`, `DMSetFromOptions()`
10316: @*/
10317: PetscErrorCode DMPlexCheckOrphanVertices(DM dm)
10318: {
10319: PetscInt pStart, pEnd, vStart, vEnd;
10321: PetscFunctionBegin;
10322: PetscCall(DMPlexGetChart(dm, &pStart, &pEnd));
10323: PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
10324: if (pStart == vStart && pEnd == vEnd) PetscFunctionReturn(PETSC_SUCCESS);
10325: for (PetscInt v = vStart; v < vEnd; ++v) {
10326: PetscInt suppSize;
10328: PetscCall(DMPlexGetSupportSize(dm, v, &suppSize));
10329: PetscCheck(suppSize, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Vertex %" PetscInt_FMT " is disconnected from the mesh", v);
10330: }
10331: PetscFunctionReturn(PETSC_SUCCESS);
10332: }
10334: /*@
10335: DMPlexCheckTransform - If the mesh was produced by a transform, run the transform verification check on it
10337: Collective
10339: Input Parameter:
10340: . dm - The `DMPLEX` object
10342: Level: developer
10344: Notes:
10345: This is mainly intended for debugging/testing purposes.
10347: For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.
10349: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCheck()`, `DMSetFromOptions()`
10350: @*/
10351: PetscErrorCode DMPlexCheckTransform(DM dm)
10352: {
10353: DMPlexTransform tr;
10355: PetscFunctionBegin;
10356: PetscCall(DMPlexGetTransform(dm, &tr));
10357: if (tr) PetscCall(DMPlexTransformCheck(tr, dm));
10358: PetscFunctionReturn(PETSC_SUCCESS);
10359: }
10361: /*@
10362: DMPlexCheck - Perform various checks of `DMPLEX` sanity
10364: Collective
10366: Input Parameter:
10367: . dm - The `DMPLEX` object
10369: Level: developer
10371: Notes:
10372: This is a useful diagnostic when creating meshes programmatically.
10374: For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.
10376: Currently does not include `DMPlexCheckCellShape()`.
10378: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMCreate()`, `DMSetFromOptions()`
10379: @*/
10380: PetscErrorCode DMPlexCheck(DM dm)
10381: {
10382: PetscInt cellHeight;
10384: PetscFunctionBegin;
10385: PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
10386: PetscCall(DMPlexCheckSymmetry(dm));
10387: PetscCall(DMPlexCheckSkeleton(dm, cellHeight));
10388: PetscCall(DMPlexCheckFaces(dm, cellHeight));
10389: PetscCall(DMPlexCheckGeometry(dm));
10390: PetscCall(DMPlexCheckPointSF(dm, NULL, PETSC_FALSE));
10391: PetscCall(DMPlexCheckInterfaceCones(dm));
10392: PetscCall(DMPlexCheckOrphanVertices(dm));
10393: PetscCall(DMPlexCheckTransform(dm));
10394: PetscFunctionReturn(PETSC_SUCCESS);
10395: }
10397: typedef struct cell_stats {
10398: PetscReal min, max, sum, squaresum;
10399: PetscInt count;
10400: } cell_stats_t;
10402: static void MPIAPI cell_stats_reduce(void *a, void *b, int *len, MPI_Datatype *datatype)
10403: {
10404: PetscInt i, N = *len;
10406: for (i = 0; i < N; i++) {
10407: cell_stats_t *A = (cell_stats_t *)a;
10408: cell_stats_t *B = (cell_stats_t *)b;
10410: B->min = PetscMin(A->min, B->min);
10411: B->max = PetscMax(A->max, B->max);
10412: B->sum += A->sum;
10413: B->squaresum += A->squaresum;
10414: B->count += A->count;
10415: }
10416: }
10418: /*@
10419: DMPlexCheckCellShape - Checks the Jacobian of the mapping from reference to real cells and computes some minimal statistics.
10421: Collective
10423: Input Parameters:
10424: + dm - The `DMPLEX` object
10425: . output - If true, statistics will be displayed on `stdout`
10426: - condLimit - Display all cells above this condition number, or `PETSC_DETERMINE` for no cell output
10428: Level: developer
10430: Notes:
10431: The condition number $\kappa_c$ of a cell $c$ is given by
10432: ```{math}
10433: \kappa_c = \left\lVert J_c \right\rVert \left\lVert J^{-1}_c \right\rVert
10434: ```
10435: where $J_c$ is the Jacobian of the mapping from the reference cell to cell $c$.
10437: This is mainly intended for debugging/testing purposes.
10439: For the complete list of DMPlexCheck* functions, see `DMSetFromOptions()`.
10441: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMSetFromOptions()`, `DMPlexComputeOrthogonalQuality()`
10442: @*/
10443: PetscErrorCode DMPlexCheckCellShape(DM dm, PetscBool output, PetscReal condLimit)
10444: {
10445: DM dmCoarse;
10446: cell_stats_t stats, globalStats;
10447: MPI_Comm comm = PetscObjectComm((PetscObject)dm);
10448: PetscReal *J, *invJ, min = 0, max = 0, mean = 0, stdev = 0;
10449: PetscReal limit = condLimit > 0 ? condLimit : PETSC_MAX_REAL;
10450: PetscInt cdim, cStart, cEnd, c, eStart, eEnd, count = 0;
10451: PetscMPIInt rank, size;
10453: PetscFunctionBegin;
10455: stats.min = PETSC_MAX_REAL;
10456: stats.max = PETSC_MIN_REAL;
10457: stats.sum = stats.squaresum = 0.;
10458: stats.count = 0;
10460: PetscCallMPI(MPI_Comm_size(comm, &size));
10461: PetscCallMPI(MPI_Comm_rank(comm, &rank));
10462: PetscCall(DMGetCoordinateDim(dm, &cdim));
10463: PetscCall(DMGetCoordinatesLocalSetUp(dm));
10464: PetscCall(PetscMalloc2(PetscSqr(cdim), &J, PetscSqr(cdim), &invJ));
10465: PetscCall(DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd));
10466: PetscCall(DMPlexGetDepthStratum(dm, 1, &eStart, &eEnd));
10467: for (c = cStart; c < cEnd; c++) {
10468: PetscReal frobJ = 0., frobInvJ = 0., cond2, cond, detJ;
10470: PetscCall(DMPlexComputeCellGeometryAffineFEM(dm, c, NULL, J, invJ, &detJ));
10471: PetscCheck(detJ >= 0.0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mesh cell %" PetscInt_FMT " is inverted", c);
10472: for (PetscInt i = 0; i < PetscSqr(cdim); ++i) {
10473: frobJ += J[i] * J[i];
10474: frobInvJ += invJ[i] * invJ[i];
10475: }
10476: cond2 = frobJ * frobInvJ;
10477: cond = PetscSqrtReal(cond2);
10479: stats.min = PetscMin(stats.min, cond);
10480: stats.max = PetscMax(stats.max, cond);
10481: stats.sum += cond;
10482: stats.squaresum += cond2;
10483: stats.count++;
10484: if (output && cond > limit) {
10485: PetscSection coordSection;
10486: Vec coordsLocal;
10487: PetscScalar *coords = NULL;
10488: PetscInt Nv, d, clSize, cl, *closure = NULL;
10490: PetscCall(DMGetCoordinatesLocal(dm, &coordsLocal));
10491: PetscCall(DMGetCoordinateSection(dm, &coordSection));
10492: PetscCall(DMPlexVecGetClosure(dm, coordSection, coordsLocal, c, &Nv, &coords));
10493: PetscCall(PetscSynchronizedPrintf(comm, "[%d] Cell %" PetscInt_FMT " cond %g\n", rank, c, (double)cond));
10494: for (PetscInt i = 0; i < Nv / cdim; ++i) {
10495: PetscCall(PetscSynchronizedPrintf(comm, " Vertex %" PetscInt_FMT ": (", i));
10496: for (d = 0; d < cdim; ++d) {
10497: if (d > 0) PetscCall(PetscSynchronizedPrintf(comm, ", "));
10498: PetscCall(PetscSynchronizedPrintf(comm, "%g", (double)PetscRealPart(coords[i * cdim + d])));
10499: }
10500: PetscCall(PetscSynchronizedPrintf(comm, ")\n"));
10501: }
10502: PetscCall(DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure));
10503: for (cl = 0; cl < clSize * 2; cl += 2) {
10504: const PetscInt edge = closure[cl];
10506: if ((edge >= eStart) && (edge < eEnd)) {
10507: PetscReal len;
10509: PetscCall(DMPlexComputeCellGeometryFVM(dm, edge, &len, NULL, NULL));
10510: PetscCall(PetscSynchronizedPrintf(comm, " Edge %" PetscInt_FMT ": length %g\n", edge, (double)len));
10511: }
10512: }
10513: PetscCall(DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure));
10514: PetscCall(DMPlexVecRestoreClosure(dm, coordSection, coordsLocal, c, &Nv, &coords));
10515: }
10516: }
10517: if (output) PetscCall(PetscSynchronizedFlush(comm, NULL));
10519: if (size > 1) {
10520: PetscMPIInt blockLengths[2] = {4, 1};
10521: MPI_Aint blockOffsets[2] = {offsetof(cell_stats_t, min), offsetof(cell_stats_t, count)};
10522: MPI_Datatype blockTypes[2] = {MPIU_REAL, MPIU_INT}, statType;
10523: MPI_Op statReduce;
10525: PetscCallMPI(MPI_Type_create_struct(2, blockLengths, blockOffsets, blockTypes, &statType));
10526: PetscCallMPI(MPI_Type_commit(&statType));
10527: PetscCallMPI(MPI_Op_create(cell_stats_reduce, PETSC_TRUE, &statReduce));
10528: PetscCallMPI(MPI_Reduce(&stats, &globalStats, 1, statType, statReduce, 0, comm));
10529: PetscCallMPI(MPI_Op_free(&statReduce));
10530: PetscCallMPI(MPI_Type_free(&statType));
10531: } else {
10532: PetscCall(PetscArraycpy(&globalStats, &stats, 1));
10533: }
10534: if (rank == 0) {
10535: count = globalStats.count;
10536: min = globalStats.min;
10537: max = globalStats.max;
10538: mean = globalStats.sum / globalStats.count;
10539: stdev = globalStats.count > 1 ? PetscSqrtReal(PetscMax((globalStats.squaresum - globalStats.count * mean * mean) / (globalStats.count - 1), 0)) : 0.0;
10540: }
10542: if (output) PetscCall(PetscPrintf(comm, "Mesh with %" PetscInt_FMT " cells, shape condition numbers: min = %g, max = %g, mean = %g, stddev = %g\n", count, (double)min, (double)max, (double)mean, (double)stdev));
10543: PetscCall(PetscFree2(J, invJ));
10545: PetscCall(DMGetCoarseDM(dm, &dmCoarse));
10546: if (dmCoarse) {
10547: PetscBool isplex;
10549: PetscCall(PetscObjectTypeCompare((PetscObject)dmCoarse, DMPLEX, &isplex));
10550: if (isplex) PetscCall(DMPlexCheckCellShape(dmCoarse, output, condLimit));
10551: }
10552: PetscFunctionReturn(PETSC_SUCCESS);
10553: }
10555: /*@
10556: DMPlexComputeOrthogonalQuality - Compute cell-wise orthogonal quality mesh statistic. Optionally tags all cells with
10557: orthogonal quality below given tolerance.
10559: Collective
10561: Input Parameters:
10562: + dm - The `DMPLEX` object
10563: . fv - Optional `PetscFV` object for pre-computed cell/face centroid information
10564: - atol - [0, 1] Absolute tolerance for tagging cells.
10566: Output Parameters:
10567: + OrthQual - `Vec` containing orthogonal quality per cell
10568: - OrthQualLabel - `DMLabel` tagging cells below atol with `DM_ADAPT_REFINE`
10570: Options Database Keys:
10571: + -dm_plex_orthogonal_quality_label_view - view OrthQualLabel if label is requested. Currently only `PETSCVIEWERASCII` is supported.
10572: - -dm_plex_orthogonal_quality_vec_view - view OrthQual vector.
10574: Level: intermediate
10576: Notes:
10577: Orthogonal quality is given by the following formula\:
10579: $ \min \left[ \frac{A_i \cdot f_i}{\|A_i\| \|f_i\|} , \frac{A_i \cdot c_i}{\|A_i\| \|c_i\|} \right]$
10581: Where A_i is the i'th face-normal vector, f_i is the vector from the cell centroid to the i'th face centroid, and c_i
10582: is the vector from the current cells centroid to the centroid of its i'th neighbor (which shares a face with the
10583: current cell). This computes the vector similarity between each cell face and its corresponding neighbor centroid by
10584: calculating the cosine of the angle between these vectors.
10586: Orthogonal quality ranges from 1 (best) to 0 (worst).
10588: This routine is mainly useful for FVM, however is not restricted to only FVM. The `PetscFV` object is optionally used to check for
10589: pre-computed FVM cell data, but if it is not passed in then this data will be computed.
10591: Cells are tagged if they have an orthogonal quality less than or equal to the absolute tolerance.
10593: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexCheckCellShape()`, `DMCreateLabel()`, `PetscFV`, `DMLabel`, `Vec`
10594: @*/
10595: PetscErrorCode DMPlexComputeOrthogonalQuality(DM dm, PeOp PetscFV fv, PetscReal atol, Vec *OrthQual, DMLabel *OrthQualLabel)
10596: {
10597: PetscInt nc, cellHeight, cStart, cEnd, cell, cellIter = 0;
10598: PetscInt *idx;
10599: PetscScalar *oqVals;
10600: const PetscScalar *cellGeomArr, *faceGeomArr;
10601: PetscReal *ci, *fi, *Ai;
10602: MPI_Comm comm;
10603: Vec cellgeom, facegeom;
10604: DM dmFace, dmCell;
10605: IS glob;
10606: ISLocalToGlobalMapping ltog;
10607: PetscViewer vwr;
10609: PetscFunctionBegin;
10612: PetscAssertPointer(OrthQual, 4);
10613: PetscCheck(atol >= 0.0 && atol <= 1.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g not in [0,1]", (double)atol);
10614: PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
10615: PetscCall(DMGetDimension(dm, &nc));
10616: PetscCheck(nc >= 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "DM must have dimension >= 2 (current %" PetscInt_FMT ")", nc);
10617: {
10618: DMPlexInterpolatedFlag interpFlag;
10620: PetscCall(DMPlexIsInterpolated(dm, &interpFlag));
10621: if (interpFlag != DMPLEX_INTERPOLATED_FULL) {
10622: PetscMPIInt rank;
10624: PetscCallMPI(MPI_Comm_rank(comm, &rank));
10625: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "DM must be fully interpolated, DM on rank %d is not fully interpolated", rank);
10626: }
10627: }
10628: if (OrthQualLabel) {
10629: PetscAssertPointer(OrthQualLabel, 5);
10630: PetscCall(DMCreateLabel(dm, "Orthogonal_Quality"));
10631: PetscCall(DMGetLabel(dm, "Orthogonal_Quality", OrthQualLabel));
10632: } else {
10633: *OrthQualLabel = NULL;
10634: }
10635: PetscCall(DMPlexGetVTKCellHeight(dm, &cellHeight));
10636: PetscCall(DMPlexGetHeightStratum(dm, cellHeight, &cStart, &cEnd));
10637: PetscCall(DMPlexCreateCellNumbering(dm, PETSC_TRUE, &glob));
10638: PetscCall(ISLocalToGlobalMappingCreateIS(glob, <og));
10639: PetscCall(ISLocalToGlobalMappingSetType(ltog, ISLOCALTOGLOBALMAPPINGHASH));
10640: PetscCall(VecCreate(comm, OrthQual));
10641: PetscCall(VecSetType(*OrthQual, VECSTANDARD));
10642: PetscCall(VecSetSizes(*OrthQual, cEnd - cStart, PETSC_DETERMINE));
10643: PetscCall(VecSetLocalToGlobalMapping(*OrthQual, ltog));
10644: PetscCall(VecSetUp(*OrthQual));
10645: PetscCall(ISDestroy(&glob));
10646: PetscCall(ISLocalToGlobalMappingDestroy(<og));
10647: PetscCall(DMPlexGetDataFVM(dm, fv, &cellgeom, &facegeom, NULL));
10648: PetscCall(VecGetArrayRead(cellgeom, &cellGeomArr));
10649: PetscCall(VecGetArrayRead(facegeom, &faceGeomArr));
10650: PetscCall(VecGetDM(cellgeom, &dmCell));
10651: PetscCall(VecGetDM(facegeom, &dmFace));
10652: PetscCall(PetscMalloc5(cEnd - cStart, &idx, cEnd - cStart, &oqVals, nc, &ci, nc, &fi, nc, &Ai));
10653: for (cell = cStart; cell < cEnd; cellIter++, cell++) {
10654: PetscInt cellneigh, cellneighiter = 0, adjSize = PETSC_DETERMINE;
10655: PetscInt cellarr[2], *adj = NULL;
10656: PetscScalar *cArr, *fArr;
10657: PetscReal minvalc = 1.0, minvalf = 1.0;
10658: PetscFVCellGeom *cg;
10660: idx[cellIter] = cell - cStart;
10661: cellarr[0] = cell;
10662: /* Make indexing into cellGeom easier */
10663: PetscCall(DMPlexPointLocalRead(dmCell, cell, cellGeomArr, &cg));
10664: PetscCall(DMPlexGetAdjacency_Internal(dm, cell, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &adjSize, &adj));
10665: /* Technically 1 too big, but easier than fiddling with empty adjacency array */
10666: PetscCall(PetscCalloc2(adjSize, &cArr, adjSize, &fArr));
10667: for (cellneigh = 0; cellneigh < adjSize; cellneighiter++, cellneigh++) {
10668: const PetscInt neigh = adj[cellneigh];
10669: PetscReal normci = 0, normfi = 0, normai = 0;
10670: PetscFVCellGeom *cgneigh;
10671: PetscFVFaceGeom *fg;
10673: /* Don't count ourselves in the neighbor list */
10674: if (neigh == cell) continue;
10675: PetscCall(DMPlexPointLocalRead(dmCell, neigh, cellGeomArr, &cgneigh));
10676: cellarr[1] = neigh;
10677: {
10678: PetscInt numcovpts;
10679: const PetscInt *covpts;
10681: PetscCall(DMPlexGetMeet(dm, 2, cellarr, &numcovpts, &covpts));
10682: PetscCall(DMPlexPointLocalRead(dmFace, covpts[0], faceGeomArr, &fg));
10683: PetscCall(DMPlexRestoreMeet(dm, 2, cellarr, &numcovpts, &covpts));
10684: }
10686: /* Compute c_i, f_i and their norms */
10687: for (PetscInt i = 0; i < nc; i++) {
10688: ci[i] = cgneigh->centroid[i] - cg->centroid[i];
10689: fi[i] = fg->centroid[i] - cg->centroid[i];
10690: Ai[i] = fg->normal[i];
10691: normci += PetscPowReal(ci[i], 2);
10692: normfi += PetscPowReal(fi[i], 2);
10693: normai += PetscPowReal(Ai[i], 2);
10694: }
10695: normci = PetscSqrtReal(normci);
10696: normfi = PetscSqrtReal(normfi);
10697: normai = PetscSqrtReal(normai);
10699: /* Normalize and compute for each face-cell-normal pair */
10700: for (PetscInt i = 0; i < nc; i++) {
10701: ci[i] = ci[i] / normci;
10702: fi[i] = fi[i] / normfi;
10703: Ai[i] = Ai[i] / normai;
10704: /* PetscAbs because I don't know if normals are guaranteed to point out */
10705: cArr[cellneighiter] += PetscAbs(Ai[i] * ci[i]);
10706: fArr[cellneighiter] += PetscAbs(Ai[i] * fi[i]);
10707: }
10708: if (PetscRealPart(cArr[cellneighiter]) < minvalc) minvalc = PetscRealPart(cArr[cellneighiter]);
10709: if (PetscRealPart(fArr[cellneighiter]) < minvalf) minvalf = PetscRealPart(fArr[cellneighiter]);
10710: }
10711: PetscCall(PetscFree(adj));
10712: PetscCall(PetscFree2(cArr, fArr));
10713: /* Defer to cell if they're equal */
10714: oqVals[cellIter] = PetscMin(minvalf, minvalc);
10715: if (OrthQualLabel) {
10716: if (PetscRealPart(oqVals[cellIter]) <= atol) PetscCall(DMLabelSetValue(*OrthQualLabel, cell, DM_ADAPT_REFINE));
10717: }
10718: }
10719: PetscCall(VecSetValuesLocal(*OrthQual, cEnd - cStart, idx, oqVals, INSERT_VALUES));
10720: PetscCall(VecAssemblyBegin(*OrthQual));
10721: PetscCall(VecAssemblyEnd(*OrthQual));
10722: PetscCall(VecRestoreArrayRead(cellgeom, &cellGeomArr));
10723: PetscCall(VecRestoreArrayRead(facegeom, &faceGeomArr));
10724: PetscCall(PetscOptionsCreateViewer(comm, NULL, NULL, "-dm_plex_orthogonal_quality_label_view", &vwr, NULL, NULL));
10725: if (OrthQualLabel) {
10726: if (vwr) PetscCall(DMLabelView(*OrthQualLabel, vwr));
10727: }
10728: PetscCall(PetscFree5(idx, oqVals, ci, fi, Ai));
10729: PetscCall(PetscViewerDestroy(&vwr));
10730: PetscCall(VecViewFromOptions(*OrthQual, NULL, "-dm_plex_orthogonal_quality_vec_view"));
10731: PetscFunctionReturn(PETSC_SUCCESS);
10732: }
10734: /* this is here instead of DMGetOutputDM because output DM still has constraints in the local indices that affect
10735: * interpolator construction */
10736: static PetscErrorCode DMGetFullDM(DM dm, DM *odm)
10737: {
10738: PetscSection section, newSection, gsection;
10739: PetscSF sf;
10740: PetscBool hasConstraints, ghasConstraints;
10742: PetscFunctionBegin;
10744: PetscAssertPointer(odm, 2);
10745: PetscCall(DMGetLocalSection(dm, §ion));
10746: PetscCall(PetscSectionHasConstraints(section, &hasConstraints));
10747: PetscCallMPI(MPIU_Allreduce(&hasConstraints, &ghasConstraints, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)dm)));
10748: if (!ghasConstraints) {
10749: PetscCall(PetscObjectReference((PetscObject)dm));
10750: *odm = dm;
10751: PetscFunctionReturn(PETSC_SUCCESS);
10752: }
10753: PetscCall(DMClone(dm, odm));
10754: PetscCall(DMCopyFields(dm, PETSC_DETERMINE, PETSC_DETERMINE, *odm));
10755: PetscCall(DMGetLocalSection(*odm, &newSection));
10756: PetscCall(DMGetPointSF(*odm, &sf));
10757: PetscCall(PetscSectionCreateGlobalSection(newSection, sf, PETSC_TRUE, PETSC_TRUE, PETSC_FALSE, &gsection));
10758: PetscCall(DMSetGlobalSection(*odm, gsection));
10759: PetscCall(PetscSectionDestroy(&gsection));
10760: PetscFunctionReturn(PETSC_SUCCESS);
10761: }
10763: static PetscErrorCode DMCreateAffineInterpolationCorrection_Plex(DM dmc, DM dmf, Vec *shift)
10764: {
10765: DM dmco, dmfo;
10766: Mat interpo;
10767: Vec rscale;
10768: Vec cglobalo, clocal;
10769: Vec fglobal, fglobalo, flocal;
10770: PetscBool regular;
10772: PetscFunctionBegin;
10773: PetscCall(DMGetFullDM(dmc, &dmco));
10774: PetscCall(DMGetFullDM(dmf, &dmfo));
10775: PetscCall(DMSetCoarseDM(dmfo, dmco));
10776: PetscCall(DMPlexGetRegularRefinement(dmf, ®ular));
10777: PetscCall(DMPlexSetRegularRefinement(dmfo, regular));
10778: PetscCall(DMCreateInterpolation(dmco, dmfo, &interpo, &rscale));
10779: PetscCall(DMCreateGlobalVector(dmco, &cglobalo));
10780: PetscCall(DMCreateLocalVector(dmc, &clocal));
10781: PetscCall(DMCreateGlobalVector(dmf, &fglobal));
10782: PetscCall(DMCreateGlobalVector(dmfo, &fglobalo));
10783: PetscCall(DMCreateLocalVector(dmf, &flocal));
10784: PetscCall(DMPlexInsertBoundaryValues(dmc, PETSC_TRUE, clocal, 0., NULL, NULL, NULL));
10785: PetscCall(DMLocalToGlobalBegin(dmco, clocal, INSERT_VALUES, cglobalo));
10786: PetscCall(DMLocalToGlobalEnd(dmco, clocal, INSERT_VALUES, cglobalo));
10787: PetscCall(MatMult(interpo, cglobalo, fglobalo));
10788: PetscCall(DMGlobalToLocalBegin(dmfo, fglobalo, INSERT_VALUES, flocal));
10789: PetscCall(DMGlobalToLocalEnd(dmfo, fglobalo, INSERT_VALUES, flocal));
10790: PetscCall(DMLocalToGlobalBegin(dmf, flocal, INSERT_VALUES, fglobal));
10791: PetscCall(DMLocalToGlobalEnd(dmf, flocal, INSERT_VALUES, fglobal));
10792: *shift = fglobal;
10793: PetscCall(VecDestroy(&flocal));
10794: PetscCall(VecDestroy(&fglobalo));
10795: PetscCall(VecDestroy(&clocal));
10796: PetscCall(VecDestroy(&cglobalo));
10797: PetscCall(VecDestroy(&rscale));
10798: PetscCall(MatDestroy(&interpo));
10799: PetscCall(DMDestroy(&dmfo));
10800: PetscCall(DMDestroy(&dmco));
10801: PetscFunctionReturn(PETSC_SUCCESS);
10802: }
10804: PETSC_INTERN PetscErrorCode DMInterpolateSolution_Plex(DM coarse, DM fine, Mat interp, Vec coarseSol, Vec fineSol)
10805: {
10806: PetscObject shifto;
10807: Vec shift;
10809: PetscFunctionBegin;
10810: if (!interp) {
10811: Vec rscale;
10813: PetscCall(DMCreateInterpolation(coarse, fine, &interp, &rscale));
10814: PetscCall(VecDestroy(&rscale));
10815: } else {
10816: PetscCall(PetscObjectReference((PetscObject)interp));
10817: }
10818: PetscCall(PetscObjectQuery((PetscObject)interp, "_DMInterpolateSolution_Plex_Vec", &shifto));
10819: if (!shifto) {
10820: PetscCall(DMCreateAffineInterpolationCorrection_Plex(coarse, fine, &shift));
10821: PetscCall(PetscObjectCompose((PetscObject)interp, "_DMInterpolateSolution_Plex_Vec", (PetscObject)shift));
10822: shifto = (PetscObject)shift;
10823: PetscCall(VecDestroy(&shift));
10824: }
10825: shift = (Vec)shifto;
10826: PetscCall(MatInterpolate(interp, coarseSol, fineSol));
10827: PetscCall(VecAXPY(fineSol, 1.0, shift));
10828: PetscCall(MatDestroy(&interp));
10829: PetscFunctionReturn(PETSC_SUCCESS);
10830: }
10832: /* Pointwise interpolation
10833: Just code FEM for now
10834: u^f = I u^c
10835: sum_k u^f_k phi^f_k = I sum_j u^c_j phi^c_j
10836: u^f_i = sum_j psi^f_i I phi^c_j u^c_j
10837: I_{ij} = psi^f_i phi^c_j
10838: */
10839: PetscErrorCode DMCreateInterpolation_Plex(DM dmCoarse, DM dmFine, Mat *interpolation, Vec *scaling)
10840: {
10841: PetscSection gsc, gsf;
10842: PetscInt m, n;
10843: void *ctx;
10844: DM cdm;
10845: PetscBool regular, ismatis, isRefined = dmCoarse->data == dmFine->data ? PETSC_FALSE : PETSC_TRUE;
10847: PetscFunctionBegin;
10848: PetscCall(DMGetGlobalSection(dmFine, &gsf));
10849: PetscCall(PetscSectionGetConstrainedStorageSize(gsf, &m));
10850: PetscCall(DMGetGlobalSection(dmCoarse, &gsc));
10851: PetscCall(PetscSectionGetConstrainedStorageSize(gsc, &n));
10853: PetscCall(PetscStrcmp(dmCoarse->mattype, MATIS, &ismatis));
10854: PetscCall(MatCreate(PetscObjectComm((PetscObject)dmCoarse), interpolation));
10855: PetscCall(MatSetSizes(*interpolation, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
10856: PetscCall(MatSetType(*interpolation, ismatis ? MATAIJ : dmCoarse->mattype));
10857: PetscCall(DMGetApplicationContext(dmFine, &ctx));
10859: PetscCall(DMGetCoarseDM(dmFine, &cdm));
10860: PetscCall(DMPlexGetRegularRefinement(dmFine, ®ular));
10861: if (!isRefined || (regular && cdm == dmCoarse)) PetscCall(DMPlexComputeInterpolatorNested(dmCoarse, dmFine, isRefined, *interpolation, ctx));
10862: else PetscCall(DMPlexComputeInterpolatorGeneral(dmCoarse, dmFine, *interpolation, ctx));
10863: PetscCall(MatViewFromOptions(*interpolation, NULL, "-interp_mat_view"));
10864: if (scaling) {
10865: /* Use naive scaling */
10866: PetscCall(DMCreateInterpolationScale(dmCoarse, dmFine, *interpolation, scaling));
10867: }
10868: PetscFunctionReturn(PETSC_SUCCESS);
10869: }
10871: PetscErrorCode DMCreateInjection_Plex(DM dmCoarse, DM dmFine, Mat *mat)
10872: {
10873: VecScatter ctx;
10875: PetscFunctionBegin;
10876: PetscCall(DMPlexComputeInjectorFEM(dmCoarse, dmFine, &ctx, NULL));
10877: PetscCall(MatCreateScatter(PetscObjectComm((PetscObject)ctx), ctx, mat));
10878: PetscCall(VecScatterDestroy(&ctx));
10879: PetscFunctionReturn(PETSC_SUCCESS);
10880: }
10882: static void g0_identity_private(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[])
10883: {
10884: const PetscInt f = (PetscInt)PetscRealPart(constants[numConstants]);
10885: const PetscInt Nc = uOff[f + 1] - uOff[f];
10886: for (PetscInt c = 0; c < Nc; ++c) g0[c * Nc + c] = 1.0;
10887: }
10889: // The assumption here is that the test field is a vector and the basis field is a scalar (so we need the gradient)
10890: static void g1_identity_private(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g1[])
10891: {
10892: for (PetscInt c = 0; c < dim; ++c) g1[c * dim + c] = 1.0;
10893: }
10895: PetscErrorCode DMCreateMassMatrixLumped_Plex(DM dm, Vec *lmass, Vec *mass)
10896: {
10897: DM dmc;
10898: PetscDS ds;
10899: Vec ones, locmass;
10900: IS cellIS;
10901: PetscFormKey key;
10902: PetscInt depth;
10904: PetscFunctionBegin;
10905: PetscCall(DMClone(dm, &dmc));
10906: PetscCall(DMCopyDisc(dm, dmc));
10907: PetscCall(DMGetDS(dmc, &ds));
10908: for (PetscInt f = 0; f < dmc->Nf; ++f) PetscCall(PetscDSSetJacobian(ds, f, f, g0_identity_private, NULL, NULL, NULL));
10909: if (mass) PetscCall(DMCreateGlobalVector(dm, mass));
10910: if (lmass) PetscCall(DMCreateLocalVector(dm, &locmass));
10911: else PetscCall(DMGetLocalVector(dm, &locmass));
10912: PetscCall(DMGetLocalVector(dm, &ones));
10913: PetscCall(DMPlexGetDepth(dm, &depth));
10914: PetscCall(DMGetStratumIS(dm, "depth", depth, &cellIS));
10915: PetscCall(VecSet(locmass, 0.0));
10916: PetscCall(VecSet(ones, 1.0));
10917: key.label = NULL;
10918: key.value = 0;
10919: key.field = 0;
10920: key.part = 0;
10921: PetscCall(DMPlexComputeJacobianActionByKey(dmc, key, cellIS, 0.0, 0.0, ones, NULL, ones, locmass, NULL));
10922: PetscCall(ISDestroy(&cellIS));
10923: if (mass) {
10924: PetscCall(DMLocalToGlobalBegin(dm, locmass, ADD_VALUES, *mass));
10925: PetscCall(DMLocalToGlobalEnd(dm, locmass, ADD_VALUES, *mass));
10926: }
10927: PetscCall(DMRestoreLocalVector(dm, &ones));
10928: if (lmass) *lmass = locmass;
10929: else PetscCall(DMRestoreLocalVector(dm, &locmass));
10930: PetscCall(DMDestroy(&dmc));
10931: PetscFunctionReturn(PETSC_SUCCESS);
10932: }
10934: PetscErrorCode DMCreateMassMatrix_Plex(DM dmCoarse, DM dmFine, Mat *mass)
10935: {
10936: PetscSection gsc, gsf;
10937: PetscInt m, n;
10938: void *ctx;
10939: DM cdm;
10940: PetscBool regular;
10942: PetscFunctionBegin;
10943: if (dmFine == dmCoarse) {
10944: DM dmc;
10945: PetscDS ds;
10946: PetscWeakForm wf;
10947: Vec u;
10948: IS cellIS;
10949: PetscFormKey key;
10950: PetscInt depth;
10952: PetscCall(DMClone(dmFine, &dmc));
10953: PetscCall(DMCopyDisc(dmFine, dmc));
10954: PetscCall(DMGetDS(dmc, &ds));
10955: PetscCall(PetscDSGetWeakForm(ds, &wf));
10956: PetscCall(PetscWeakFormClear(wf));
10957: for (PetscInt f = 0; f < dmc->Nf; ++f) PetscCall(PetscDSSetJacobian(ds, f, f, g0_identity_private, NULL, NULL, NULL));
10958: PetscCall(DMCreateMatrix(dmc, mass));
10959: PetscCall(DMGetLocalVector(dmc, &u));
10960: PetscCall(DMPlexGetDepth(dmc, &depth));
10961: PetscCall(DMGetStratumIS(dmc, "depth", depth, &cellIS));
10962: PetscCall(MatZeroEntries(*mass));
10963: key.label = NULL;
10964: key.value = 0;
10965: key.field = 0;
10966: key.part = 0;
10967: PetscCall(DMPlexComputeJacobianByKey(dmc, key, cellIS, 0.0, 0.0, u, NULL, *mass, *mass, NULL));
10968: PetscCall(ISDestroy(&cellIS));
10969: PetscCall(DMRestoreLocalVector(dmc, &u));
10970: PetscCall(DMDestroy(&dmc));
10971: } else {
10972: PetscCall(DMGetGlobalSection(dmFine, &gsf));
10973: PetscCall(PetscSectionGetConstrainedStorageSize(gsf, &m));
10974: PetscCall(DMGetGlobalSection(dmCoarse, &gsc));
10975: PetscCall(PetscSectionGetConstrainedStorageSize(gsc, &n));
10977: PetscCall(MatCreate(PetscObjectComm((PetscObject)dmCoarse), mass));
10978: PetscCall(MatSetSizes(*mass, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
10979: PetscCall(MatSetType(*mass, dmCoarse->mattype));
10980: PetscCall(DMGetApplicationContext(dmFine, &ctx));
10982: PetscCall(DMGetCoarseDM(dmFine, &cdm));
10983: PetscCall(DMPlexGetRegularRefinement(dmFine, ®ular));
10984: if (regular && cdm == dmCoarse) PetscCall(DMPlexComputeMassMatrixNested(dmCoarse, dmFine, *mass, ctx));
10985: else PetscCall(DMPlexComputeMassMatrixGeneral(dmCoarse, dmFine, *mass, ctx));
10986: }
10987: PetscCall(MatViewFromOptions(*mass, NULL, "-mass_mat_view"));
10988: PetscFunctionReturn(PETSC_SUCCESS);
10989: }
10991: PetscErrorCode DMCreateGradientMatrix_Plex(DM dmc, DM dmr, Mat *derv)
10992: {
10993: PetscSection gsc, gsf;
10994: PetscInt m, n;
10995: void *ctx;
10997: PetscFunctionBegin;
10998: PetscCall(DMGetGlobalSection(dmr, &gsf));
10999: PetscCall(PetscSectionGetConstrainedStorageSize(gsf, &m));
11000: PetscCall(DMGetGlobalSection(dmc, &gsc));
11001: PetscCall(PetscSectionGetConstrainedStorageSize(gsc, &n));
11003: PetscCall(MatCreate(PetscObjectComm((PetscObject)dmc), derv));
11004: PetscCall(PetscObjectSetName((PetscObject)*derv, "Plex Derivative Matrix"));
11005: PetscCall(MatSetSizes(*derv, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
11006: PetscCall(MatSetType(*derv, dmc->mattype));
11008: PetscCall(DMGetApplicationContext(dmr, &ctx));
11009: {
11010: DM ndmr;
11011: PetscDS ds;
11012: PetscWeakForm wf;
11013: Vec u;
11014: IS cellIS;
11015: PetscFormKey key;
11016: PetscInt depth, Nf;
11018: PetscCall(DMClone(dmr, &ndmr));
11019: PetscCall(DMCopyDisc(dmr, ndmr));
11020: PetscCall(DMGetDS(ndmr, &ds));
11021: PetscCall(PetscDSGetWeakForm(ds, &wf));
11022: PetscCall(PetscWeakFormClear(wf));
11023: PetscCall(PetscDSGetNumFields(ds, &Nf));
11024: for (PetscInt f = 0; f < Nf; ++f) PetscCall(PetscDSSetJacobian(ds, f, f, NULL, g1_identity_private, NULL, NULL));
11025: PetscCall(DMGetLocalVector(ndmr, &u));
11026: PetscCall(DMPlexGetDepth(ndmr, &depth));
11027: PetscCall(DMGetStratumIS(ndmr, "depth", depth, &cellIS));
11028: PetscCall(MatZeroEntries(*derv));
11029: key.label = NULL;
11030: key.value = 0;
11031: key.field = 0;
11032: key.part = 0;
11033: PetscCall(DMPlexComputeJacobianByKeyGeneral(ndmr, dmc, key, cellIS, 0.0, 0.0, u, NULL, *derv, *derv, NULL));
11034: PetscCall(ISDestroy(&cellIS));
11035: PetscCall(DMRestoreLocalVector(ndmr, &u));
11036: PetscCall(DMDestroy(&ndmr));
11037: }
11038: PetscCall(MatViewFromOptions(*derv, NULL, "-gradient_mat_view"));
11039: PetscFunctionReturn(PETSC_SUCCESS);
11040: }
11042: /*@
11043: DMPlexGetRegularRefinement - Get the flag indicating that this mesh was obtained by regular refinement from its coarse mesh
11045: Input Parameter:
11046: . dm - The `DMPLEX` object
11048: Output Parameter:
11049: . regular - The flag
11051: Level: intermediate
11053: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSetRegularRefinement()`
11054: @*/
11055: PetscErrorCode DMPlexGetRegularRefinement(DM dm, PetscBool *regular)
11056: {
11057: PetscFunctionBegin;
11059: PetscAssertPointer(regular, 2);
11060: *regular = ((DM_Plex *)dm->data)->regularRefinement;
11061: PetscFunctionReturn(PETSC_SUCCESS);
11062: }
11064: /*@
11065: DMPlexSetRegularRefinement - Set the flag indicating that this mesh was obtained by regular refinement from its coarse mesh
11067: Input Parameters:
11068: + dm - The `DMPLEX` object
11069: - regular - The flag
11071: Level: intermediate
11073: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetRegularRefinement()`
11074: @*/
11075: PetscErrorCode DMPlexSetRegularRefinement(DM dm, PetscBool regular)
11076: {
11077: PetscFunctionBegin;
11079: ((DM_Plex *)dm->data)->regularRefinement = regular;
11080: PetscFunctionReturn(PETSC_SUCCESS);
11081: }
11083: /*@
11084: DMPlexGetAnchors - Get the layout of the anchor (point-to-point) constraints. Typically, the user will not have to
11085: call DMPlexGetAnchors() directly: if there are anchors, then `DMPlexGetAnchors()` is called during `DMGetDefaultConstraints()`.
11087: Not Collective
11089: Input Parameter:
11090: . dm - The `DMPLEX` object
11092: Output Parameters:
11093: + anchorSection - If not `NULL`, set to the section describing which points anchor the constrained points.
11094: - anchorIS - If not `NULL`, set to the list of anchors indexed by `anchorSection`
11096: Level: intermediate
11098: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexSetAnchors()`, `DMGetDefaultConstraints()`, `DMSetDefaultConstraints()`, `IS`, `PetscSection`
11099: @*/
11100: PetscErrorCode DMPlexGetAnchors(DM dm, PeOp PetscSection *anchorSection, PeOp IS *anchorIS)
11101: {
11102: DM_Plex *plex = (DM_Plex *)dm->data;
11104: PetscFunctionBegin;
11106: if (!plex->anchorSection && !plex->anchorIS && plex->createanchors) PetscCall((*plex->createanchors)(dm));
11107: if (anchorSection) *anchorSection = plex->anchorSection;
11108: if (anchorIS) *anchorIS = plex->anchorIS;
11109: PetscFunctionReturn(PETSC_SUCCESS);
11110: }
11112: /*@
11113: DMPlexSetAnchors - Set the layout of the local anchor (point-to-point) constraints.
11115: Collective
11117: Input Parameters:
11118: + dm - The `DMPLEX` object
11119: . anchorSection - The section that describes the mapping from constrained points to the anchor points listed in anchorIS.
11120: Must have a local communicator (`PETSC_COMM_SELF` or derivative).
11121: - anchorIS - The list of all anchor points. Must have a local communicator (`PETSC_COMM_SELF` or derivative).
11123: Level: intermediate
11125: Notes:
11126: Unlike boundary conditions, when a point's degrees of freedom in a section are constrained to
11127: an outside value, the anchor constraints set a point's degrees of freedom to be a linear
11128: combination of other points' degrees of freedom.
11130: After specifying the layout of constraints with `DMPlexSetAnchors()`, one specifies the constraints by calling
11131: `DMGetDefaultConstraints()` and filling in the entries in the constraint matrix.
11133: The reference counts of `anchorSection` and `anchorIS` are incremented.
11135: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMPlexGetAnchors()`, `DMGetDefaultConstraints()`, `DMSetDefaultConstraints()`
11136: @*/
11137: PetscErrorCode DMPlexSetAnchors(DM dm, PetscSection anchorSection, IS anchorIS)
11138: {
11139: DM_Plex *plex = (DM_Plex *)dm->data;
11140: PetscMPIInt result;
11142: PetscFunctionBegin;
11144: if (anchorSection) {
11146: PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)anchorSection), &result));
11147: PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "anchor section must have local communicator");
11148: }
11149: if (anchorIS) {
11151: PetscCallMPI(MPI_Comm_compare(PETSC_COMM_SELF, PetscObjectComm((PetscObject)anchorIS), &result));
11152: PetscCheck(result == MPI_CONGRUENT || result == MPI_IDENT, PETSC_COMM_SELF, PETSC_ERR_ARG_NOTSAMECOMM, "anchor IS must have local communicator");
11153: }
11155: PetscCall(PetscObjectReference((PetscObject)anchorSection));
11156: PetscCall(PetscSectionDestroy(&plex->anchorSection));
11157: plex->anchorSection = anchorSection;
11159: PetscCall(PetscObjectReference((PetscObject)anchorIS));
11160: PetscCall(ISDestroy(&plex->anchorIS));
11161: plex->anchorIS = anchorIS;
11163: if (PetscUnlikelyDebug(anchorIS && anchorSection)) {
11164: PetscInt size, a, pStart, pEnd;
11165: const PetscInt *anchors;
11167: PetscCall(PetscSectionGetChart(anchorSection, &pStart, &pEnd));
11168: PetscCall(ISGetLocalSize(anchorIS, &size));
11169: PetscCall(ISGetIndices(anchorIS, &anchors));
11170: for (a = 0; a < size; a++) {
11171: PetscInt p;
11173: p = anchors[a];
11174: if (p >= pStart && p < pEnd) {
11175: PetscInt dof;
11177: PetscCall(PetscSectionGetDof(anchorSection, p, &dof));
11178: if (dof) {
11179: PetscCall(ISRestoreIndices(anchorIS, &anchors));
11180: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Point %" PetscInt_FMT " cannot be constrained and an anchor", p);
11181: }
11182: }
11183: }
11184: PetscCall(ISRestoreIndices(anchorIS, &anchors));
11185: }
11186: /* reset the generic constraints */
11187: PetscCall(DMSetDefaultConstraints(dm, NULL, NULL, NULL));
11188: PetscFunctionReturn(PETSC_SUCCESS);
11189: }
11191: static PetscErrorCode DMPlexCreateConstraintSection_Anchors(DM dm, PetscSection section, PetscSection *cSec)
11192: {
11193: PetscSection anchorSection;
11194: PetscInt pStart, pEnd, sStart, sEnd, p, dof, numFields, f;
11196: PetscFunctionBegin;
11198: PetscCall(DMPlexGetAnchors(dm, &anchorSection, NULL));
11199: PetscCall(PetscSectionCreate(PETSC_COMM_SELF, cSec));
11200: PetscCall(PetscSectionGetNumFields(section, &numFields));
11201: if (numFields) {
11202: PetscInt f;
11203: PetscCall(PetscSectionSetNumFields(*cSec, numFields));
11205: for (f = 0; f < numFields; f++) {
11206: PetscInt numComp;
11208: PetscCall(PetscSectionGetFieldComponents(section, f, &numComp));
11209: PetscCall(PetscSectionSetFieldComponents(*cSec, f, numComp));
11210: }
11211: }
11212: PetscCall(PetscSectionGetChart(anchorSection, &pStart, &pEnd));
11213: PetscCall(PetscSectionGetChart(section, &sStart, &sEnd));
11214: pStart = PetscMax(pStart, sStart);
11215: pEnd = PetscMin(pEnd, sEnd);
11216: pEnd = PetscMax(pStart, pEnd);
11217: PetscCall(PetscSectionSetChart(*cSec, pStart, pEnd));
11218: for (p = pStart; p < pEnd; p++) {
11219: PetscCall(PetscSectionGetDof(anchorSection, p, &dof));
11220: if (dof) {
11221: PetscCall(PetscSectionGetDof(section, p, &dof));
11222: PetscCall(PetscSectionSetDof(*cSec, p, dof));
11223: for (f = 0; f < numFields; f++) {
11224: PetscCall(PetscSectionGetFieldDof(section, p, f, &dof));
11225: PetscCall(PetscSectionSetFieldDof(*cSec, p, f, dof));
11226: }
11227: }
11228: }
11229: PetscCall(PetscSectionSetUp(*cSec));
11230: PetscCall(PetscObjectSetName((PetscObject)*cSec, "Constraint Section"));
11231: PetscFunctionReturn(PETSC_SUCCESS);
11232: }
11234: static PetscErrorCode DMPlexCreateConstraintMatrix_Anchors(DM dm, PetscSection section, PetscSection cSec, Mat *cMat)
11235: {
11236: PetscSection aSec;
11237: PetscInt pStart, pEnd, p, sStart, sEnd, dof, aDof, aOff, off, nnz, annz, m, n, q, a, offset, *i, *j;
11238: const PetscInt *anchors;
11239: PetscInt numFields, f;
11240: IS aIS;
11241: MatType mtype;
11242: PetscBool iscuda, iskokkos;
11244: PetscFunctionBegin;
11246: PetscCall(PetscSectionGetStorageSize(cSec, &m));
11247: PetscCall(PetscSectionGetStorageSize(section, &n));
11248: PetscCall(MatCreate(PETSC_COMM_SELF, cMat));
11249: PetscCall(MatSetSizes(*cMat, m, n, m, n));
11250: PetscCall(PetscStrcmp(dm->mattype, MATSEQAIJCUSPARSE, &iscuda));
11251: if (!iscuda) PetscCall(PetscStrcmp(dm->mattype, MATMPIAIJCUSPARSE, &iscuda));
11252: PetscCall(PetscStrcmp(dm->mattype, MATSEQAIJKOKKOS, &iskokkos));
11253: if (!iskokkos) PetscCall(PetscStrcmp(dm->mattype, MATMPIAIJKOKKOS, &iskokkos));
11254: if (iscuda) mtype = MATSEQAIJCUSPARSE;
11255: else if (iskokkos) mtype = MATSEQAIJKOKKOS;
11256: else mtype = MATSEQAIJ;
11257: PetscCall(MatSetType(*cMat, mtype));
11258: PetscCall(DMPlexGetAnchors(dm, &aSec, &aIS));
11259: PetscCall(ISGetIndices(aIS, &anchors));
11260: /* cSec will be a subset of aSec and section */
11261: PetscCall(PetscSectionGetChart(cSec, &pStart, &pEnd));
11262: PetscCall(PetscSectionGetChart(section, &sStart, &sEnd));
11263: PetscCall(PetscMalloc1(m + 1, &i));
11264: i[0] = 0;
11265: PetscCall(PetscSectionGetNumFields(section, &numFields));
11266: for (p = pStart; p < pEnd; p++) {
11267: PetscInt rDof, rOff, r;
11269: PetscCall(PetscSectionGetDof(aSec, p, &rDof));
11270: if (!rDof) continue;
11271: PetscCall(PetscSectionGetOffset(aSec, p, &rOff));
11272: if (numFields) {
11273: for (f = 0; f < numFields; f++) {
11274: annz = 0;
11275: for (r = 0; r < rDof; r++) {
11276: a = anchors[rOff + r];
11277: if (a < sStart || a >= sEnd) continue;
11278: PetscCall(PetscSectionGetFieldDof(section, a, f, &aDof));
11279: annz += aDof;
11280: }
11281: PetscCall(PetscSectionGetFieldDof(cSec, p, f, &dof));
11282: PetscCall(PetscSectionGetFieldOffset(cSec, p, f, &off));
11283: for (q = 0; q < dof; q++) i[off + q + 1] = i[off + q] + annz;
11284: }
11285: } else {
11286: annz = 0;
11287: PetscCall(PetscSectionGetDof(cSec, p, &dof));
11288: for (q = 0; q < dof; q++) {
11289: a = anchors[rOff + q];
11290: if (a < sStart || a >= sEnd) continue;
11291: PetscCall(PetscSectionGetDof(section, a, &aDof));
11292: annz += aDof;
11293: }
11294: PetscCall(PetscSectionGetDof(cSec, p, &dof));
11295: PetscCall(PetscSectionGetOffset(cSec, p, &off));
11296: for (q = 0; q < dof; q++) i[off + q + 1] = i[off + q] + annz;
11297: }
11298: }
11299: nnz = i[m];
11300: PetscCall(PetscMalloc1(nnz, &j));
11301: offset = 0;
11302: for (p = pStart; p < pEnd; p++) {
11303: if (numFields) {
11304: for (f = 0; f < numFields; f++) {
11305: PetscCall(PetscSectionGetFieldDof(cSec, p, f, &dof));
11306: for (q = 0; q < dof; q++) {
11307: PetscInt rDof, rOff, r;
11308: PetscCall(PetscSectionGetDof(aSec, p, &rDof));
11309: PetscCall(PetscSectionGetOffset(aSec, p, &rOff));
11310: for (r = 0; r < rDof; r++) {
11311: a = anchors[rOff + r];
11312: if (a < sStart || a >= sEnd) continue;
11313: PetscCall(PetscSectionGetFieldDof(section, a, f, &aDof));
11314: PetscCall(PetscSectionGetFieldOffset(section, a, f, &aOff));
11315: for (PetscInt s = 0; s < aDof; s++) j[offset++] = aOff + s;
11316: }
11317: }
11318: }
11319: } else {
11320: PetscCall(PetscSectionGetDof(cSec, p, &dof));
11321: for (q = 0; q < dof; q++) {
11322: PetscInt rDof, rOff, r;
11323: PetscCall(PetscSectionGetDof(aSec, p, &rDof));
11324: PetscCall(PetscSectionGetOffset(aSec, p, &rOff));
11325: for (r = 0; r < rDof; r++) {
11326: a = anchors[rOff + r];
11327: if (a < sStart || a >= sEnd) continue;
11328: PetscCall(PetscSectionGetDof(section, a, &aDof));
11329: PetscCall(PetscSectionGetOffset(section, a, &aOff));
11330: for (PetscInt s = 0; s < aDof; s++) j[offset++] = aOff + s;
11331: }
11332: }
11333: }
11334: }
11335: PetscCall(MatSeqAIJSetPreallocationCSR(*cMat, i, j, NULL));
11336: PetscCall(PetscFree(i));
11337: PetscCall(PetscFree(j));
11338: PetscCall(ISRestoreIndices(aIS, &anchors));
11339: PetscFunctionReturn(PETSC_SUCCESS);
11340: }
11342: PetscErrorCode DMCreateDefaultConstraints_Plex(DM dm)
11343: {
11344: DM_Plex *plex = (DM_Plex *)dm->data;
11345: PetscSection anchorSection, section, cSec;
11346: Mat cMat;
11348: PetscFunctionBegin;
11350: PetscCall(DMPlexGetAnchors(dm, &anchorSection, NULL));
11351: if (anchorSection) {
11352: PetscInt Nf;
11354: PetscCall(DMGetLocalSection(dm, §ion));
11355: PetscCall(DMPlexCreateConstraintSection_Anchors(dm, section, &cSec));
11356: PetscCall(DMPlexCreateConstraintMatrix_Anchors(dm, section, cSec, &cMat));
11357: PetscCall(DMGetNumFields(dm, &Nf));
11358: if (Nf && plex->computeanchormatrix) PetscCall((*plex->computeanchormatrix)(dm, section, cSec, cMat));
11359: PetscCall(DMSetDefaultConstraints(dm, cSec, cMat, NULL));
11360: PetscCall(PetscSectionDestroy(&cSec));
11361: PetscCall(MatDestroy(&cMat));
11362: }
11363: PetscFunctionReturn(PETSC_SUCCESS);
11364: }
11366: PetscErrorCode DMCreateSubDomainDM_Plex(DM dm, DMLabel label, PetscInt value, IS *is, DM *subdm)
11367: {
11368: IS subis;
11369: PetscSection section, subsection;
11371: PetscFunctionBegin;
11372: PetscCall(DMGetLocalSection(dm, §ion));
11373: PetscCheck(section, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must set default section for DM before splitting subdomain");
11374: PetscCheck(subdm, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Must set output subDM for splitting subdomain");
11375: /* Create subdomain */
11376: PetscCall(DMPlexFilter(dm, label, value, PETSC_FALSE, PETSC_FALSE, PetscObjectComm((PetscObject)dm), NULL, subdm));
11377: /* Create submodel */
11378: PetscCall(DMPlexGetSubpointIS(*subdm, &subis));
11379: PetscCall(PetscSectionCreateSubmeshSection(section, subis, &subsection));
11380: PetscCall(DMSetLocalSection(*subdm, subsection));
11381: PetscCall(PetscSectionDestroy(&subsection));
11382: PetscCall(DMCopyDisc(dm, *subdm));
11383: /* Create map from submodel to global model */
11384: if (is) {
11385: PetscSection sectionGlobal, subsectionGlobal;
11386: IS spIS;
11387: const PetscInt *spmap;
11388: PetscInt *subIndices;
11389: PetscInt subSize = 0, subOff = 0, pStart, pEnd, p;
11390: PetscInt Nf, f, bs = -1, bsLocal[2], bsMinMax[2];
11392: PetscCall(DMPlexGetSubpointIS(*subdm, &spIS));
11393: PetscCall(ISGetIndices(spIS, &spmap));
11394: PetscCall(PetscSectionGetNumFields(section, &Nf));
11395: PetscCall(DMGetGlobalSection(dm, §ionGlobal));
11396: PetscCall(DMGetGlobalSection(*subdm, &subsectionGlobal));
11397: PetscCall(PetscSectionGetChart(subsection, &pStart, &pEnd));
11398: for (p = pStart; p < pEnd; ++p) {
11399: PetscInt gdof, pSubSize = 0;
11401: PetscCall(PetscSectionGetDof(sectionGlobal, p, &gdof));
11402: if (gdof > 0) {
11403: for (f = 0; f < Nf; ++f) {
11404: PetscInt fdof, fcdof;
11406: PetscCall(PetscSectionGetFieldDof(subsection, p, f, &fdof));
11407: PetscCall(PetscSectionGetFieldConstraintDof(subsection, p, f, &fcdof));
11408: pSubSize += fdof - fcdof;
11409: }
11410: subSize += pSubSize;
11411: if (pSubSize) {
11412: if (bs < 0) {
11413: bs = pSubSize;
11414: } else if (bs != pSubSize) {
11415: /* Layout does not admit a pointwise block size */
11416: bs = 1;
11417: }
11418: }
11419: }
11420: }
11421: /* Must have same blocksize on all procs (some might have no points) */
11422: bsLocal[0] = bs < 0 ? PETSC_INT_MAX : bs;
11423: bsLocal[1] = bs;
11424: PetscCall(PetscGlobalMinMaxInt(PetscObjectComm((PetscObject)dm), bsLocal, bsMinMax));
11425: if (bsMinMax[0] != bsMinMax[1]) bs = 1;
11426: else bs = bsMinMax[0];
11427: PetscCall(PetscMalloc1(subSize, &subIndices));
11428: for (p = pStart; p < pEnd; ++p) {
11429: PetscInt gdof, goff;
11431: PetscCall(PetscSectionGetDof(subsectionGlobal, p, &gdof));
11432: if (gdof > 0) {
11433: const PetscInt point = spmap[p];
11435: PetscCall(PetscSectionGetOffset(sectionGlobal, point, &goff));
11436: for (f = 0; f < Nf; ++f) {
11437: PetscInt fdof, fcdof, fc, f2, poff = 0;
11439: /* Can get rid of this loop by storing field information in the global section */
11440: for (f2 = 0; f2 < f; ++f2) {
11441: PetscCall(PetscSectionGetFieldDof(section, p, f2, &fdof));
11442: PetscCall(PetscSectionGetFieldConstraintDof(section, p, f2, &fcdof));
11443: poff += fdof - fcdof;
11444: }
11445: PetscCall(PetscSectionGetFieldDof(section, p, f, &fdof));
11446: PetscCall(PetscSectionGetFieldConstraintDof(section, p, f, &fcdof));
11447: for (fc = 0; fc < fdof - fcdof; ++fc, ++subOff) subIndices[subOff] = goff + poff + fc;
11448: }
11449: }
11450: }
11451: PetscCall(ISRestoreIndices(spIS, &spmap));
11452: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)dm), subSize, subIndices, PETSC_OWN_POINTER, is));
11453: if (bs > 1) {
11454: /* We need to check that the block size does not come from non-contiguous fields */
11455: PetscInt i, j, set = 1;
11456: for (i = 0; i < subSize; i += bs) {
11457: for (j = 0; j < bs; ++j) {
11458: if (subIndices[i + j] != subIndices[i] + j) {
11459: set = 0;
11460: break;
11461: }
11462: }
11463: }
11464: if (set) PetscCall(ISSetBlockSize(*is, bs));
11465: }
11466: // Attach nullspace
11467: if (dm->nullspaceConstructors) {
11468: for (f = 0; f < Nf; ++f) {
11469: (*subdm)->nullspaceConstructors[f] = dm->nullspaceConstructors[f];
11470: if ((*subdm)->nullspaceConstructors[f]) break;
11471: }
11472: if (f < Nf) {
11473: MatNullSpace nullSpace;
11474: PetscCall((*(*subdm)->nullspaceConstructors[f])(*subdm, f, f, &nullSpace));
11476: PetscCall(PetscObjectCompose((PetscObject)*is, "nullspace", (PetscObject)nullSpace));
11477: PetscCall(MatNullSpaceDestroy(&nullSpace));
11478: }
11479: }
11480: }
11481: PetscFunctionReturn(PETSC_SUCCESS);
11482: }
11484: /*@
11485: DMPlexMonitorThroughput - Report the cell throughput of FE integration
11487: Input Parameters:
11488: + dm - The `DM`
11489: - unused - unused argument
11491: Options Database Key:
11492: . -dm_plex_monitor_throughput - Activate the monitor
11494: Level: developer
11496: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMSetFromOptions()`, `DMPlexCreate()`
11497: @*/
11498: PetscErrorCode DMPlexMonitorThroughput(DM dm, void *unused)
11499: {
11500: PetscLogHandler default_handler;
11502: PetscFunctionBegin;
11504: PetscCall(PetscLogGetDefaultHandler(&default_handler));
11505: if (default_handler) {
11506: PetscLogEvent event;
11507: PetscEventPerfInfo eventInfo;
11508: PetscLogDouble cellRate, flopRate;
11509: PetscInt cStart, cEnd, Nf, N;
11510: const char *name;
11512: PetscCall(PetscObjectGetName((PetscObject)dm, &name));
11513: PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
11514: PetscCall(DMGetNumFields(dm, &Nf));
11515: PetscCall(PetscLogEventGetId("DMPlexResidualFE", &event));
11516: PetscCall(PetscLogEventGetPerfInfo(PETSC_DEFAULT, event, &eventInfo));
11517: N = (cEnd - cStart) * Nf * eventInfo.count;
11518: flopRate = eventInfo.flops / eventInfo.time;
11519: cellRate = N / eventInfo.time;
11520: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)dm), "DM (%s) FE Residual Integration: %" PetscInt_FMT " integrals %d reps\n Cell rate: %.2g/s flop rate: %.2g MF/s\n", name ? name : "unknown", N, eventInfo.count, cellRate, flopRate / 1.e6));
11521: } else {
11522: SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Plex Throughput Monitor is not supported if logging is turned off or the default log handler is not running. Reconfigure using --with-log and run with -log_view.");
11523: }
11524: PetscFunctionReturn(PETSC_SUCCESS);
11525: }
11527: static inline PetscInt DMPlex_GlobalID(PetscInt point)
11528: {
11529: return point >= 0 ? point : -(point + 1);
11530: }
11532: /*
11533: Computes the graph laplacian L at the given depth.
11534: L = D - A, with D = degree matrix and A = adjacency matrix
11535: */
11536: static PetscErrorCode DMPlexCreateGraphLaplacian_Private(DM dm, PetscInt depth, Mat *oL)
11537: {
11538: Mat L, preall;
11539: Vec x, y;
11540: IS pointNumbering;
11541: const PetscInt *pointNum;
11542: PetscInt *i, *j, numVertices, numEdges, shift, maxnnzrow, dim, *numDof, numFields;
11543: PetscInt pStart, pEnd;
11544: PetscScalar *vals;
11545: PetscSection s;
11547: PetscFunctionBeginUser;
11548: PetscCall(DMGetDimension(dm, &dim));
11549: {
11550: /* XXX this generalizes DMPlexCreatePartitionerGraph to any height and adjacency */
11551: PetscCall(DMPlexGetDepthStratum(dm, depth, &pStart, &pEnd));
11552: PetscCall(DMPlexCreatePointNumbering(dm, &pointNumbering));
11553: PetscCall(ISGetIndices(pointNumbering, &pointNum));
11554: shift = DMPlex_GlobalID(pointNum[pStart]);
11555: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &shift, 1, MPIU_INT, MPI_MIN, PetscObjectComm((PetscObject)dm)));
11556: /* Determine sizes */
11557: numVertices = 0;
11558: for (PetscInt p = pStart; p < pEnd; p++) {
11559: /* Skip non-owned cells in parallel */
11560: if (pointNum[p] < 0) continue;
11561: numVertices++;
11562: }
11563: numEdges = 0;
11564: for (PetscInt p = pStart; p < pEnd; p++) {
11565: PetscInt nadj = PETSC_DETERMINE;
11566: PetscInt *adj = NULL;
11567: /* Skip non-owned cells in parallel */
11568: if (pointNum[p] < 0) continue;
11569: PetscCall(DMPlexGetAdjacency(dm, p, &nadj, &adj));
11570: for (PetscInt a = 0; a < nadj; a++)
11571: if (adj[a] != p && pStart <= adj[a] && adj[a] < pEnd) numEdges++;
11572: PetscCall(PetscFree(adj));
11573: }
11574: /* Determine adjacency */
11575: PetscCall(PetscMalloc1(numVertices + 1, &i));
11576: PetscCall(PetscMalloc1(numEdges, &j));
11577: PetscInt iptr = 0;
11578: i[0] = iptr;
11579: for (PetscInt p = pStart; p < pEnd; p++) {
11580: PetscInt nadj = PETSC_DETERMINE;
11581: PetscInt *adj = NULL;
11582: /* Skip non-owned cells in parallel */
11583: if (pointNum[p] < 0) continue;
11584: PetscCall(DMPlexGetAdjacency(dm, p, &nadj, &adj));
11585: for (PetscInt a = 0; a < nadj; a++)
11586: if (adj[a] != p && pStart <= adj[a] && adj[a] < pEnd) j[iptr++] = DMPlex_GlobalID(pointNum[adj[a]]) - shift;
11587: PetscCall(PetscFree(adj));
11588: i[p - pStart + 1] = iptr;
11589: /* Sort adjacencies (not strictly necessary) */
11590: PetscCall(PetscSortInt(iptr - i[p - pStart], &j[i[p - pStart]]));
11591: }
11592: PetscCall(ISRestoreIndices(pointNumbering, &pointNum));
11593: PetscCall(ISDestroy(&pointNumbering));
11594: }
11595: /* First create a matrix object */
11596: PetscCall(MatCreate(PetscObjectComm((PetscObject)dm), &L));
11597: PetscCall(MatSetSizes(L, numVertices, numVertices, PETSC_DECIDE, PETSC_DECIDE));
11598: PetscCall(MatSetOptionsPrefix(L, "dm_plex_laplacian_"));
11599: PetscCall(MatSetFromOptions(L));
11600: /* Preallocation */
11601: PetscCall(MatCreate(PetscObjectComm((PetscObject)dm), &preall));
11602: PetscCall(MatSetSizes(preall, numVertices, numVertices, PETSC_DECIDE, PETSC_DECIDE));
11603: PetscCall(MatSetType(preall, MATPREALLOCATOR));
11604: PetscCall(MatSetUp(preall));
11605: PetscCall(MatGetOwnershipRange(preall, &shift, NULL));
11606: maxnnzrow = 0;
11607: for (PetscInt k = 0; k < numVertices; k++) {
11608: PetscInt nnzrow = i[k + 1] - i[k];
11609: PetscInt row = shift + k;
11610: PetscInt *col = j + i[k];
11611: maxnnzrow = PetscMax(maxnnzrow, nnzrow);
11612: /* Add adjacency connection */
11613: PetscCall(MatSetValues(preall, 1, &row, nnzrow, col, NULL, INSERT_VALUES));
11614: /* The graph CSR does not represent self-to-self connections, we need them
11615: for the graph laplacian */
11616: PetscCall(MatSetValues(preall, 1, &row, 1, &row, NULL, INSERT_VALUES));
11617: }
11618: PetscCall(MatAssemblyBegin(preall, MAT_FINAL_ASSEMBLY));
11619: PetscCall(MatAssemblyEnd(preall, MAT_FINAL_ASSEMBLY));
11620: /* Preallocate the graph laplacian matrix */
11621: PetscCall(MatPreallocatorPreallocate(preall, PETSC_TRUE, L));
11622: PetscCall(MatDestroy(&preall));
11623: /* Set values. We first set all values to -1.0 to obtain -A,
11624: and then use matrix API to modify for our needs and add the diagonal D matrix */
11625: PetscCall(PetscMalloc1(maxnnzrow, &vals));
11626: for (PetscInt k = 0; k < maxnnzrow; k++) vals[k] = -1.0;
11627: for (PetscInt k = 0; k < numVertices; k++) {
11628: PetscInt nnzrow = i[k + 1] - i[k];
11629: PetscInt row = shift + k;
11630: PetscInt *col = j + i[k];
11631: PetscCall(MatSetValues(L, 1, &row, nnzrow, col, vals, INSERT_VALUES));
11632: }
11633: PetscCall(MatAssemblyBegin(L, MAT_FINAL_ASSEMBLY));
11634: PetscCall(MatAssemblyEnd(L, MAT_FINAL_ASSEMBLY));
11635: /* Add D. Here we use the fact that D = rowsum(A) */
11636: PetscCall(MatCreateVecs(L, &x, &y));
11637: PetscCall(VecSet(x, -1.0));
11638: PetscCall(MatMult(L, x, y));
11639: PetscCall(MatDiagonalSet(L, y, INSERT_VALUES));
11640: PetscCall(MatAssemblyBegin(L, MAT_FINAL_ASSEMBLY));
11641: PetscCall(MatAssemblyEnd(L, MAT_FINAL_ASSEMBLY));
11642: PetscCall(VecDestroy(&x));
11643: PetscCall(VecDestroy(&y));
11644: /* Clean up */
11645: PetscCall(PetscFree(vals));
11646: PetscCall(PetscFree(i));
11647: PetscCall(PetscFree(j));
11648: /* Allow command line view via -laplacian_view */
11649: PetscCall(MatViewFromOptions(L, NULL, "-view"));
11650: /*
11651: For visualization purposes, we attach a DM to the matrix.
11652: Cloning makes a shallow (pointer) copy of the mesh topology and geometry,
11653: and allows us to consider different discretization spaces.
11654: In this case, we specify a one-field discretization with a PetscSection object.
11655: */
11656: PetscCall(DMClone(dm, &dm));
11657: numFields = 1;
11658: PetscCall(DMSetNumFields(dm, numFields));
11659: PetscCall(PetscCalloc1(dim + 1, &numDof));
11660: numDof[depth] = 1;
11661: PetscCall(DMPlexCreateSection(dm, NULL, &numFields, numDof, 0, NULL, NULL, NULL, NULL, &s));
11662: PetscCall(DMSetLocalSection(dm, s));
11663: PetscCall(PetscSectionDestroy(&s));
11664: PetscCall(PetscFree(numDof));
11665: /* Attach the DM to the matrix */
11666: PetscCall(MatSetDM(L, dm));
11667: /* the matrix holds a reference to the DM, we can decrease reference counting */
11668: PetscCall(DMDestroy(&dm));
11669: /* Return matrix to caller */
11670: *oL = L;
11671: PetscFunctionReturn(PETSC_SUCCESS);
11672: }
11674: /*@
11675: DMPlexCreateColoring - Gets coloring of the connectivity graph of the `DMPlex` points at a given depth.
11677: Collective
11679: Input Parameters:
11680: + dm - the `DMPlex` object
11681: . depth - the dimension of the entities in the connectivity graph.
11682: - distance - the distance of the coloring (either 1 or 2).
11684: Output Parameter:
11685: . coloring - the coloring
11687: Level: developer
11689: Notes:
11690: Unlike `DMCreateColoring`, the graph used for the coloring does not represent the operator matrix associated with the discretization of a PDE on the `DM`.
11691: Here the coloring is computed from the connectivity graph of the mesh entities.
11693: Coloring of matrices can also be computed directly from the sparse matrix nonzero structure via the `MatColoring` object or from the mesh from which the
11694: matrix comes from (what this function provides). In general using the mesh produces a more optimal coloring (fewer colors).
11696: Mesh colorings are useful for additive and multiplicative Schwarz methods.
11697: In particular, they mitigate overhead costs associated with setting up individual KSPs and PCs on many subdomains per process.
11698: A coloring of the vertices (`depth=0`) with `distance=1` can be use can be used to group non-overlapping vertex-star patches into multi-patch subdomains.
11699: Similarly, a vertex coloring with `distance=2` can be used to group non-overlapping Vanka patches into multi-patch subdomains.
11701: .seealso: [](ch_unstructured), `DMPlex`, `ISColoring`, `MatColoring`, `DMCreateColoring()`
11702: @*/
11703: PetscErrorCode DMPlexCreateColoring(DM dm, PetscInt depth, PetscInt distance, ISColoring *coloring)
11704: {
11705: Mat L = NULL;
11706: MatColoring mc = NULL;
11707: IS *iscolors = NULL;
11708: PetscInt pStart = 0, offset = 0, ncolors = 0;
11710: PetscFunctionBegin;
11711: /* Create a graph Laplacian */
11712: PetscCall(DMPlexCreateGraphLaplacian_Private(dm, depth, &L));
11713: /* Compute offset */
11714: PetscCall(MatGetOwnershipRange(L, &offset, NULL));
11715: PetscCall(DMPlexGetDepthStratum(dm, depth, &pStart, NULL));
11716: offset = pStart - offset;
11717: /* Obtain ISColoring via MatColoring */
11718: PetscCall(MatColoringCreate(L, &mc));
11719: PetscCall(MatColoringSetType(mc, MATCOLORINGGREEDY));
11720: PetscCall(MatColoringSetDistance(mc, distance));
11721: PetscCall(MatColoringSetFromOptions(mc));
11722: PetscCall(MatColoringApply(mc, coloring));
11723: PetscCall(MatColoringDestroy(&mc));
11724: /* Destroy the graph Laplacian */
11725: PetscCall(MatDestroy(&L));
11726: /* Shift ISColoring to align with the DMPlex numbering */
11727: PetscCall(ISColoringGetIS(*coloring, PETSC_USE_POINTER, &ncolors, &iscolors));
11728: for (PetscInt c = 0; c < ncolors; c++) {
11729: PetscCall(ISShift(iscolors[c], offset, iscolors[c]));
11730: }
11731: PetscCall(ISColoringRestoreIS(*coloring, PETSC_USE_POINTER, &iscolors));
11732: PetscFunctionReturn(PETSC_SUCCESS);
11733: }