xref: /petsc/src/snes/tutorials/ex13.c (revision d529f056d75cd16b380adc3e50ccb741df53d0de)
1 static char help[] = "Poisson Problem in 2d and 3d with finite elements.\n\
2 We solve the Poisson problem in a rectangular\n\
3 domain, using a parallel unstructured mesh (DMPLEX) to discretize it.\n\
4 This example supports automatic convergence estimation\n\
5 and eventually adaptivity.\n\n\n";
6 
7 #include <petscdmplex.h>
8 #include <petscsnes.h>
9 #include <petscds.h>
10 #include <petscconvest.h>
11 
12 typedef struct {
13   /* Domain and mesh definition */
14   PetscBool spectral;    /* Look at the spectrum along planes in the solution */
15   PetscBool shear;       /* Shear the domain */
16   PetscBool adjoint;     /* Solve the adjoint problem */
17   PetscBool homogeneous; /* Use homogeneous boundary conditions */
18   PetscBool viewError;   /* Output the solution error */
19 } AppCtx;
20 
21 static PetscErrorCode zero(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, void *ctx)
22 {
23   *u = 0.0;
24   return PETSC_SUCCESS;
25 }
26 
27 static PetscErrorCode trig_inhomogeneous_u(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, void *ctx)
28 {
29   PetscInt d;
30   *u = 0.0;
31   for (d = 0; d < dim; ++d) *u += PetscSinReal(2.0 * PETSC_PI * x[d]);
32   return PETSC_SUCCESS;
33 }
34 
35 static PetscErrorCode trig_homogeneous_u(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, void *ctx)
36 {
37   PetscInt d;
38   *u = 1.0;
39   for (d = 0; d < dim; ++d) *u *= PetscSinReal(2.0 * PETSC_PI * x[d]);
40   return PETSC_SUCCESS;
41 }
42 
43 /* Compute integral of (residual of solution)*(adjoint solution - projection of adjoint solution) */
44 static void obj_error_u(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar obj[])
45 {
46   obj[0] = a[aOff[0]] * (u[0] - a[aOff[1]]);
47 }
48 
49 static void f0_trig_inhomogeneous_u(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
50 {
51   PetscInt d;
52   for (d = 0; d < dim; ++d) f0[0] += -4.0 * PetscSqr(PETSC_PI) * PetscSinReal(2.0 * PETSC_PI * x[d]);
53 }
54 
55 static void f0_trig_homogeneous_u(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
56 {
57   PetscInt d;
58   for (d = 0; d < dim; ++d) {
59     PetscScalar v = 1.;
60     for (PetscInt e = 0; e < dim; e++) {
61       if (e == d) {
62         v *= -4.0 * PetscSqr(PETSC_PI) * PetscSinReal(2.0 * PETSC_PI * x[d]);
63       } else {
64         v *= PetscSinReal(2.0 * PETSC_PI * x[d]);
65       }
66     }
67     f0[0] += v;
68   }
69 }
70 
71 static void f0_unity_u(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
72 {
73   f0[0] = 1.0;
74 }
75 
76 static void f0_identityaux_u(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
77 {
78   f0[0] = a[0];
79 }
80 
81 static void f1_u(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f1[])
82 {
83   PetscInt d;
84   for (d = 0; d < dim; ++d) f1[d] = u_x[d];
85 }
86 
87 static void g3_uu(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 g3[])
88 {
89   PetscInt d;
90   for (d = 0; d < dim; ++d) g3[d * dim + d] = 1.0;
91 }
92 
93 static PetscErrorCode ProcessOptions(MPI_Comm comm, AppCtx *options)
94 {
95   PetscFunctionBeginUser;
96   options->shear       = PETSC_FALSE;
97   options->spectral    = PETSC_FALSE;
98   options->adjoint     = PETSC_FALSE;
99   options->homogeneous = PETSC_FALSE;
100   options->viewError   = PETSC_FALSE;
101 
102   PetscOptionsBegin(comm, "", "Poisson Problem Options", "DMPLEX");
103   PetscCall(PetscOptionsBool("-shear", "Shear the domain", "ex13.c", options->shear, &options->shear, NULL));
104   PetscCall(PetscOptionsBool("-spectral", "Look at the spectrum along planes of the solution", "ex13.c", options->spectral, &options->spectral, NULL));
105   PetscCall(PetscOptionsBool("-adjoint", "Solve the adjoint problem", "ex13.c", options->adjoint, &options->adjoint, NULL));
106   PetscCall(PetscOptionsBool("-homogeneous", "Use homogeneous boundary conditions", "ex13.c", options->homogeneous, &options->homogeneous, NULL));
107   PetscCall(PetscOptionsBool("-error_view", "Output the solution error", "ex13.c", options->viewError, &options->viewError, NULL));
108   PetscOptionsEnd();
109   PetscFunctionReturn(PETSC_SUCCESS);
110 }
111 
112 static PetscErrorCode CreateSpectralPlanes(DM dm, PetscInt numPlanes, const PetscInt planeDir[], const PetscReal planeCoord[], AppCtx *user)
113 {
114   PetscSection       coordSection;
115   Vec                coordinates;
116   const PetscScalar *coords;
117   PetscInt           dim, p, vStart, vEnd, v;
118 
119   PetscFunctionBeginUser;
120   PetscCall(DMGetCoordinateDim(dm, &dim));
121   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
122   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
123   PetscCall(DMGetCoordinateSection(dm, &coordSection));
124   PetscCall(VecGetArrayRead(coordinates, &coords));
125   for (p = 0; p < numPlanes; ++p) {
126     DMLabel label;
127     char    name[PETSC_MAX_PATH_LEN];
128 
129     PetscCall(PetscSNPrintf(name, PETSC_MAX_PATH_LEN, "spectral_plane_%" PetscInt_FMT, p));
130     PetscCall(DMCreateLabel(dm, name));
131     PetscCall(DMGetLabel(dm, name, &label));
132     PetscCall(DMLabelAddStratum(label, 1));
133     for (v = vStart; v < vEnd; ++v) {
134       PetscInt off;
135 
136       PetscCall(PetscSectionGetOffset(coordSection, v, &off));
137       if (PetscAbsReal(planeCoord[p] - PetscRealPart(coords[off + planeDir[p]])) < PETSC_SMALL) PetscCall(DMLabelSetValue(label, v, 1));
138     }
139   }
140   PetscCall(VecRestoreArrayRead(coordinates, &coords));
141   PetscFunctionReturn(PETSC_SUCCESS);
142 }
143 
144 static PetscErrorCode CreateMesh(MPI_Comm comm, AppCtx *user, DM *dm)
145 {
146   PetscFunctionBeginUser;
147   PetscCall(DMCreate(comm, dm));
148   PetscCall(DMSetType(*dm, DMPLEX));
149   PetscCall(DMSetFromOptions(*dm));
150   if (user->shear) PetscCall(DMPlexShearGeometry(*dm, DM_X, NULL));
151   PetscCall(DMSetApplicationContext(*dm, user));
152   PetscCall(DMViewFromOptions(*dm, NULL, "-dm_view"));
153   if (user->spectral) {
154     PetscInt  planeDir[2]   = {0, 1};
155     PetscReal planeCoord[2] = {0., 1.};
156 
157     PetscCall(CreateSpectralPlanes(*dm, 2, planeDir, planeCoord, user));
158   }
159   PetscFunctionReturn(PETSC_SUCCESS);
160 }
161 
162 static PetscErrorCode SetupPrimalProblem(DM dm, AppCtx *user)
163 {
164   PetscDS        ds;
165   DMLabel        label;
166   const PetscInt id                                                                             = 1;
167   PetscPointFunc f0                                                                             = user->homogeneous ? f0_trig_homogeneous_u : f0_trig_inhomogeneous_u;
168   PetscErrorCode (*ex)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *) = user->homogeneous ? trig_homogeneous_u : trig_inhomogeneous_u;
169 
170   PetscFunctionBeginUser;
171   PetscCall(DMGetDS(dm, &ds));
172   PetscCall(PetscDSSetResidual(ds, 0, f0, f1_u));
173   PetscCall(PetscDSSetJacobian(ds, 0, 0, NULL, NULL, NULL, g3_uu));
174   PetscCall(PetscDSSetExactSolution(ds, 0, ex, user));
175   PetscCall(DMGetLabel(dm, "marker", &label));
176   if (label) PetscCall(DMAddBoundary(dm, DM_BC_ESSENTIAL, "wall", label, 1, &id, 0, 0, NULL, (void (*)(void))ex, NULL, user, NULL));
177   PetscFunctionReturn(PETSC_SUCCESS);
178 }
179 
180 static PetscErrorCode SetupAdjointProblem(DM dm, AppCtx *user)
181 {
182   PetscDS        ds;
183   DMLabel        label;
184   const PetscInt id = 1;
185 
186   PetscFunctionBeginUser;
187   PetscCall(DMGetDS(dm, &ds));
188   PetscCall(PetscDSSetResidual(ds, 0, f0_unity_u, f1_u));
189   PetscCall(PetscDSSetJacobian(ds, 0, 0, NULL, NULL, NULL, g3_uu));
190   PetscCall(PetscDSSetObjective(ds, 0, obj_error_u));
191   PetscCall(DMGetLabel(dm, "marker", &label));
192   PetscCall(DMAddBoundary(dm, DM_BC_ESSENTIAL, "wall", label, 1, &id, 0, 0, NULL, (void (*)(void))zero, NULL, user, NULL));
193   PetscFunctionReturn(PETSC_SUCCESS);
194 }
195 
196 static PetscErrorCode SetupErrorProblem(DM dm, AppCtx *user)
197 {
198   PetscDS prob;
199 
200   PetscFunctionBeginUser;
201   PetscCall(DMGetDS(dm, &prob));
202   PetscFunctionReturn(PETSC_SUCCESS);
203 }
204 
205 static PetscErrorCode SetupDiscretization(DM dm, const char name[], PetscErrorCode (*setup)(DM, AppCtx *), AppCtx *user)
206 {
207   DM             cdm = dm;
208   PetscFE        fe;
209   DMPolytopeType ct;
210   PetscBool      simplex;
211   PetscInt       dim, cStart;
212   char           prefix[PETSC_MAX_PATH_LEN];
213 
214   PetscFunctionBeginUser;
215   PetscCall(DMGetDimension(dm, &dim));
216   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, NULL));
217   PetscCall(DMPlexGetCellType(dm, cStart, &ct));
218   simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;
219   /* Create finite element */
220   PetscCall(PetscSNPrintf(prefix, PETSC_MAX_PATH_LEN, "%s_", name));
221   PetscCall(PetscFECreateDefault(PETSC_COMM_SELF, dim, 1, simplex, name ? prefix : NULL, -1, &fe));
222   PetscCall(PetscObjectSetName((PetscObject)fe, name));
223   /* Set discretization and boundary conditions for each mesh */
224   PetscCall(DMSetField(dm, 0, NULL, (PetscObject)fe));
225   PetscCall(DMCreateDS(dm));
226   PetscCall((*setup)(dm, user));
227   while (cdm) {
228     PetscCall(DMCopyDisc(dm, cdm));
229     /* TODO: Check whether the boundary of coarse meshes is marked */
230     PetscCall(DMGetCoarseDM(cdm, &cdm));
231   }
232   PetscCall(PetscFEDestroy(&fe));
233   PetscFunctionReturn(PETSC_SUCCESS);
234 }
235 
236 static PetscErrorCode ComputeSpectral(Vec u, PetscInt numPlanes, const PetscInt planeDir[], const PetscReal planeCoord[], AppCtx *user)
237 {
238   MPI_Comm           comm;
239   DM                 dm;
240   PetscSection       coordSection, section;
241   Vec                coordinates, uloc;
242   const PetscScalar *coords, *array;
243   PetscInt           p;
244   PetscMPIInt        size, rank;
245 
246   PetscFunctionBeginUser;
247   if (!user->spectral) PetscFunctionReturn(PETSC_SUCCESS);
248   PetscCall(VecGetDM(u, &dm));
249   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
250   PetscCallMPI(MPI_Comm_size(comm, &size));
251   PetscCallMPI(MPI_Comm_rank(comm, &rank));
252   PetscCall(DMGetLocalVector(dm, &uloc));
253   PetscCall(DMGlobalToLocalBegin(dm, u, INSERT_VALUES, uloc));
254   PetscCall(DMGlobalToLocalEnd(dm, u, INSERT_VALUES, uloc));
255   PetscCall(DMPlexInsertBoundaryValues(dm, PETSC_TRUE, uloc, 0.0, NULL, NULL, NULL));
256   PetscCall(VecViewFromOptions(uloc, NULL, "-sol_view"));
257   PetscCall(DMGetLocalSection(dm, &section));
258   PetscCall(VecGetArrayRead(uloc, &array));
259   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
260   PetscCall(DMGetCoordinateSection(dm, &coordSection));
261   PetscCall(VecGetArrayRead(coordinates, &coords));
262   for (p = 0; p < numPlanes; ++p) {
263     DMLabel         label;
264     char            name[PETSC_MAX_PATH_LEN];
265     Mat             F;
266     Vec             x, y;
267     IS              stratum;
268     PetscReal      *ray, *gray;
269     PetscScalar    *rvals, *svals, *gsvals;
270     PetscInt       *perm, *nperm;
271     PetscInt        n, N, i, j, off, offu;
272     const PetscInt *points;
273 
274     PetscCall(PetscSNPrintf(name, PETSC_MAX_PATH_LEN, "spectral_plane_%" PetscInt_FMT, p));
275     PetscCall(DMGetLabel(dm, name, &label));
276     PetscCall(DMLabelGetStratumIS(label, 1, &stratum));
277     PetscCall(ISGetLocalSize(stratum, &n));
278     PetscCall(ISGetIndices(stratum, &points));
279     PetscCall(PetscMalloc2(n, &ray, n, &svals));
280     for (i = 0; i < n; ++i) {
281       PetscCall(PetscSectionGetOffset(coordSection, points[i], &off));
282       PetscCall(PetscSectionGetOffset(section, points[i], &offu));
283       ray[i]   = PetscRealPart(coords[off + ((planeDir[p] + 1) % 2)]);
284       svals[i] = array[offu];
285     }
286     /* Gather the ray data to proc 0 */
287     if (size > 1) {
288       PetscMPIInt *cnt, *displs, p;
289 
290       PetscCall(PetscCalloc2(size, &cnt, size, &displs));
291       PetscCallMPI(MPI_Gather(&n, 1, MPIU_INT, cnt, 1, MPIU_INT, 0, comm));
292       for (p = 1; p < size; ++p) displs[p] = displs[p - 1] + cnt[p - 1];
293       N = displs[size - 1] + cnt[size - 1];
294       PetscCall(PetscMalloc2(N, &gray, N, &gsvals));
295       PetscCallMPI(MPI_Gatherv(ray, n, MPIU_REAL, gray, cnt, displs, MPIU_REAL, 0, comm));
296       PetscCallMPI(MPI_Gatherv(svals, n, MPIU_SCALAR, gsvals, cnt, displs, MPIU_SCALAR, 0, comm));
297       PetscCall(PetscFree2(cnt, displs));
298     } else {
299       N      = n;
300       gray   = ray;
301       gsvals = svals;
302     }
303     if (rank == 0) {
304       /* Sort point along ray */
305       PetscCall(PetscMalloc2(N, &perm, N, &nperm));
306       for (i = 0; i < N; ++i) perm[i] = i;
307       PetscCall(PetscSortRealWithPermutation(N, gray, perm));
308       /* Count duplicates and squish mapping */
309       nperm[0] = perm[0];
310       for (i = 1, j = 1; i < N; ++i) {
311         if (PetscAbsReal(gray[perm[i]] - gray[perm[i - 1]]) > PETSC_SMALL) nperm[j++] = perm[i];
312       }
313       /* Create FFT structs */
314       PetscCall(MatCreateFFT(PETSC_COMM_SELF, 1, &j, MATFFTW, &F));
315       PetscCall(MatCreateVecs(F, &x, &y));
316       PetscCall(PetscObjectSetName((PetscObject)y, name));
317       PetscCall(VecGetArray(x, &rvals));
318       for (i = 0, j = 0; i < N; ++i) {
319         if (i > 0 && PetscAbsReal(gray[perm[i]] - gray[perm[i - 1]]) < PETSC_SMALL) continue;
320         rvals[j] = gsvals[nperm[j]];
321         ++j;
322       }
323       PetscCall(PetscFree2(perm, nperm));
324       if (size > 1) PetscCall(PetscFree2(gray, gsvals));
325       PetscCall(VecRestoreArray(x, &rvals));
326       /* Do FFT along the ray */
327       PetscCall(MatMult(F, x, y));
328       /* Chop FFT */
329       PetscCall(VecFilter(y, PETSC_SMALL));
330       PetscCall(VecViewFromOptions(x, NULL, "-real_view"));
331       PetscCall(VecViewFromOptions(y, NULL, "-fft_view"));
332       PetscCall(VecDestroy(&x));
333       PetscCall(VecDestroy(&y));
334       PetscCall(MatDestroy(&F));
335     }
336     PetscCall(ISRestoreIndices(stratum, &points));
337     PetscCall(ISDestroy(&stratum));
338     PetscCall(PetscFree2(ray, svals));
339   }
340   PetscCall(VecRestoreArrayRead(coordinates, &coords));
341   PetscCall(VecRestoreArrayRead(uloc, &array));
342   PetscCall(DMRestoreLocalVector(dm, &uloc));
343   PetscFunctionReturn(PETSC_SUCCESS);
344 }
345 
346 static PetscErrorCode ComputeAdjoint(Vec u, AppCtx *user)
347 {
348   PetscFunctionBegin;
349   if (!user->adjoint) PetscFunctionReturn(PETSC_SUCCESS);
350   DM   dm, dmAdj;
351   SNES snesAdj;
352   Vec  uAdj;
353 
354   PetscCall(VecGetDM(u, &dm));
355   PetscCall(SNESCreate(PETSC_COMM_WORLD, &snesAdj));
356   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snesAdj, "adjoint_"));
357   PetscCall(DMClone(dm, &dmAdj));
358   PetscCall(SNESSetDM(snesAdj, dmAdj));
359   PetscCall(SetupDiscretization(dmAdj, "adjoint", SetupAdjointProblem, user));
360   PetscCall(DMCreateGlobalVector(dmAdj, &uAdj));
361   PetscCall(VecSet(uAdj, 0.0));
362   PetscCall(PetscObjectSetName((PetscObject)uAdj, "adjoint"));
363   PetscCall(DMPlexSetSNESLocalFEM(dmAdj, user, user, user));
364   PetscCall(SNESSetFromOptions(snesAdj));
365   PetscCall(SNESSolve(snesAdj, NULL, uAdj));
366   PetscCall(SNESGetSolution(snesAdj, &uAdj));
367   PetscCall(VecViewFromOptions(uAdj, NULL, "-adjoint_view"));
368   /* Error representation */
369   {
370     DM        dmErr, dmErrAux, dms[2];
371     Vec       errorEst, errorL2, uErr, uErrLoc, uAdjLoc, uAdjProj;
372     IS       *subis;
373     PetscReal errorEstTot, errorL2Norm, errorL2Tot;
374     PetscInt  N, i;
375     PetscErrorCode (*funcs[1])(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar *, void *) = {user->homogeneous ? trig_homogeneous_u : trig_inhomogeneous_u};
376     void (*identity[1])(PetscInt, PetscInt, PetscInt, const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[], const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[], PetscReal, const PetscReal[], PetscInt, const PetscScalar[], PetscScalar[]) = {f0_identityaux_u};
377     void *ctxs[1] = {0};
378 
379     ctxs[0] = user;
380     PetscCall(DMClone(dm, &dmErr));
381     PetscCall(SetupDiscretization(dmErr, "error", SetupErrorProblem, user));
382     PetscCall(DMGetGlobalVector(dmErr, &errorEst));
383     PetscCall(DMGetGlobalVector(dmErr, &errorL2));
384     /*   Compute auxiliary data (solution and projection of adjoint solution) */
385     PetscCall(DMGetLocalVector(dmAdj, &uAdjLoc));
386     PetscCall(DMGlobalToLocalBegin(dmAdj, uAdj, INSERT_VALUES, uAdjLoc));
387     PetscCall(DMGlobalToLocalEnd(dmAdj, uAdj, INSERT_VALUES, uAdjLoc));
388     PetscCall(DMGetGlobalVector(dm, &uAdjProj));
389     PetscCall(DMSetAuxiliaryVec(dm, NULL, 0, 0, uAdjLoc));
390     PetscCall(DMProjectField(dm, 0.0, u, identity, INSERT_VALUES, uAdjProj));
391     PetscCall(DMSetAuxiliaryVec(dm, NULL, 0, 0, NULL));
392     PetscCall(DMRestoreLocalVector(dmAdj, &uAdjLoc));
393     /*   Attach auxiliary data */
394     dms[0] = dm;
395     dms[1] = dm;
396     PetscCall(DMCreateSuperDM(dms, 2, &subis, &dmErrAux));
397     if (0) {
398       PetscSection sec;
399 
400       PetscCall(DMGetLocalSection(dms[0], &sec));
401       PetscCall(PetscSectionView(sec, PETSC_VIEWER_STDOUT_WORLD));
402       PetscCall(DMGetLocalSection(dms[1], &sec));
403       PetscCall(PetscSectionView(sec, PETSC_VIEWER_STDOUT_WORLD));
404       PetscCall(DMGetLocalSection(dmErrAux, &sec));
405       PetscCall(PetscSectionView(sec, PETSC_VIEWER_STDOUT_WORLD));
406     }
407     PetscCall(DMViewFromOptions(dmErrAux, NULL, "-dm_err_view"));
408     PetscCall(ISViewFromOptions(subis[0], NULL, "-super_is_view"));
409     PetscCall(ISViewFromOptions(subis[1], NULL, "-super_is_view"));
410     PetscCall(DMGetGlobalVector(dmErrAux, &uErr));
411     PetscCall(VecViewFromOptions(u, NULL, "-map_vec_view"));
412     PetscCall(VecViewFromOptions(uAdjProj, NULL, "-map_vec_view"));
413     PetscCall(VecViewFromOptions(uErr, NULL, "-map_vec_view"));
414     PetscCall(VecISCopy(uErr, subis[0], SCATTER_FORWARD, u));
415     PetscCall(VecISCopy(uErr, subis[1], SCATTER_FORWARD, uAdjProj));
416     PetscCall(DMRestoreGlobalVector(dm, &uAdjProj));
417     for (i = 0; i < 2; ++i) { PetscCall(ISDestroy(&subis[i])); }
418     PetscCall(PetscFree(subis));
419     PetscCall(DMGetLocalVector(dmErrAux, &uErrLoc));
420     PetscCall(DMGlobalToLocalBegin(dm, uErr, INSERT_VALUES, uErrLoc));
421     PetscCall(DMGlobalToLocalEnd(dm, uErr, INSERT_VALUES, uErrLoc));
422     PetscCall(DMRestoreGlobalVector(dmErrAux, &uErr));
423     PetscCall(DMSetAuxiliaryVec(dmAdj, NULL, 0, 0, uErrLoc));
424     /*   Compute cellwise error estimate */
425     PetscCall(VecSet(errorEst, 0.0));
426     PetscCall(DMPlexComputeCellwiseIntegralFEM(dmAdj, uAdj, errorEst, user));
427     PetscCall(DMSetAuxiliaryVec(dmAdj, NULL, 0, 0, NULL));
428     PetscCall(DMRestoreLocalVector(dmErrAux, &uErrLoc));
429     PetscCall(DMDestroy(&dmErrAux));
430     /*   Plot cellwise error vector */
431     PetscCall(VecViewFromOptions(errorEst, NULL, "-error_view"));
432     /*   Compute ratio of estimate (sum over cells) with actual L_2 error */
433     PetscCall(DMComputeL2Diff(dm, 0.0, funcs, ctxs, u, &errorL2Norm));
434     PetscCall(DMPlexComputeL2DiffVec(dm, 0.0, funcs, ctxs, u, errorL2));
435     PetscCall(VecViewFromOptions(errorL2, NULL, "-l2_error_view"));
436     PetscCall(VecNorm(errorL2, NORM_INFINITY, &errorL2Tot));
437     PetscCall(VecNorm(errorEst, NORM_INFINITY, &errorEstTot));
438     PetscCall(VecGetSize(errorEst, &N));
439     PetscCall(VecPointwiseDivide(errorEst, errorEst, errorL2));
440     PetscCall(PetscObjectSetName((PetscObject)errorEst, "Error ratio"));
441     PetscCall(VecViewFromOptions(errorEst, NULL, "-error_ratio_view"));
442     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "N: %" PetscInt_FMT " L2 error: %g Error Ratio: %g/%g = %g\n", N, (double)errorL2Norm, (double)errorEstTot, (double)PetscSqrtReal(errorL2Tot), (double)(errorEstTot / PetscSqrtReal(errorL2Tot))));
443     PetscCall(DMRestoreGlobalVector(dmErr, &errorEst));
444     PetscCall(DMRestoreGlobalVector(dmErr, &errorL2));
445     PetscCall(DMDestroy(&dmErr));
446   }
447   PetscCall(DMDestroy(&dmAdj));
448   PetscCall(VecDestroy(&uAdj));
449   PetscCall(SNESDestroy(&snesAdj));
450   PetscFunctionReturn(PETSC_SUCCESS);
451 }
452 
453 static PetscErrorCode ErrorView(Vec u, AppCtx *user)
454 {
455   PetscErrorCode (*sol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
456   void     *ctx;
457   DM        dm;
458   PetscDS   ds;
459   PetscReal error;
460   PetscInt  N;
461 
462   PetscFunctionBegin;
463   if (!user->viewError) PetscFunctionReturn(PETSC_SUCCESS);
464   PetscCall(VecGetDM(u, &dm));
465   PetscCall(DMGetDS(dm, &ds));
466   PetscCall(PetscDSGetExactSolution(ds, 0, &sol, &ctx));
467   PetscCall(VecGetSize(u, &N));
468   PetscCall(DMComputeL2Diff(dm, 0.0, &sol, &ctx, u, &error));
469   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "N: %" PetscInt_FMT " L2 error: %g\n", N, (double)error));
470   PetscFunctionReturn(PETSC_SUCCESS);
471 }
472 
473 int main(int argc, char **argv)
474 {
475   DM        dm;   /* Problem specification */
476   SNES      snes; /* Nonlinear solver */
477   Vec       u;    /* Solutions */
478   AppCtx    user; /* User-defined work context */
479   PetscInt  planeDir[2]   = {0, 1};
480   PetscReal planeCoord[2] = {0., 1.};
481 
482   PetscFunctionBeginUser;
483   PetscCall(PetscInitialize(&argc, &argv, NULL, help));
484   PetscCall(ProcessOptions(PETSC_COMM_WORLD, &user));
485   /* Primal system */
486   PetscCall(SNESCreate(PETSC_COMM_WORLD, &snes));
487   PetscCall(CreateMesh(PETSC_COMM_WORLD, &user, &dm));
488   PetscCall(SNESSetDM(snes, dm));
489   PetscCall(SetupDiscretization(dm, "potential", SetupPrimalProblem, &user));
490   PetscCall(DMCreateGlobalVector(dm, &u));
491   PetscCall(VecSet(u, 0.0));
492   PetscCall(PetscObjectSetName((PetscObject)u, "potential"));
493   PetscCall(DMPlexSetSNESLocalFEM(dm, &user, &user, &user));
494   PetscCall(SNESSetFromOptions(snes));
495   PetscCall(SNESSolve(snes, NULL, u));
496   PetscCall(SNESGetSolution(snes, &u));
497   PetscCall(VecViewFromOptions(u, NULL, "-potential_view"));
498   PetscCall(ErrorView(u, &user));
499   PetscCall(ComputeSpectral(u, 2, planeDir, planeCoord, &user));
500   PetscCall(ComputeAdjoint(u, &user));
501   /* Cleanup */
502   PetscCall(VecDestroy(&u));
503   PetscCall(SNESDestroy(&snes));
504   PetscCall(DMDestroy(&dm));
505   PetscCall(PetscFinalize());
506   return 0;
507 }
508 
509 /*TEST
510 
511   test:
512     # Using -dm_refine 2 -convest_num_refine 3 we get L_2 convergence rate: 1.9
513     suffix: 2d_p1_conv
514     requires: triangle
515     args: -potential_petscspace_degree 1 -snes_convergence_estimate -convest_num_refine 2
516   test:
517     # Using -dm_refine 2 -convest_num_refine 3 we get L_2 convergence rate: 2.9
518     suffix: 2d_p2_conv
519     requires: triangle
520     args: -potential_petscspace_degree 2 -snes_convergence_estimate -convest_num_refine 2
521   test:
522     # Using -dm_refine 2 -convest_num_refine 3 we get L_2 convergence rate: 3.9
523     suffix: 2d_p3_conv
524     requires: triangle
525     args: -potential_petscspace_degree 3 -snes_convergence_estimate -convest_num_refine 2
526   test:
527     # Using -dm_refine 2 -convest_num_refine 3 we get L_2 convergence rate: 1.9
528     suffix: 2d_q1_conv
529     args: -dm_plex_simplex 0 -potential_petscspace_degree 1 -snes_convergence_estimate -convest_num_refine 2
530   test:
531     # Using -dm_refine 2 -convest_num_refine 3 we get L_2 convergence rate: 2.9
532     suffix: 2d_q2_conv
533     args: -dm_plex_simplex 0 -potential_petscspace_degree 2 -snes_convergence_estimate -convest_num_refine 2
534   test:
535     # Using -dm_refine 2 -convest_num_refine 3 we get L_2 convergence rate: 3.9
536     suffix: 2d_q3_conv
537     args: -dm_plex_simplex 0 -potential_petscspace_degree 3 -snes_convergence_estimate -convest_num_refine 2
538   test:
539     # Using -dm_refine 2 -convest_num_refine 3 we get L_2 convergence rate: 1.9
540     suffix: 2d_q1_shear_conv
541     args: -dm_plex_simplex 0 -shear -potential_petscspace_degree 1 -snes_convergence_estimate -convest_num_refine 2
542   test:
543     # Using -dm_refine 2 -convest_num_refine 3 we get L_2 convergence rate: 2.9
544     suffix: 2d_q2_shear_conv
545     args: -dm_plex_simplex 0 -shear -potential_petscspace_degree 2 -snes_convergence_estimate -convest_num_refine 2
546   test:
547     # Using -dm_refine 2 -convest_num_refine 3 we get L_2 convergence rate: 3.9
548     suffix: 2d_q3_shear_conv
549     args: -dm_plex_simplex 0 -shear -potential_petscspace_degree 3 -snes_convergence_estimate -convest_num_refine 2
550   test:
551     # Using -convest_num_refine 3 we get L_2 convergence rate: 1.7
552     suffix: 3d_p1_conv
553     requires: ctetgen
554     args: -dm_plex_dim 3 -dm_refine 1 -potential_petscspace_degree 1 -snes_convergence_estimate -convest_num_refine 1
555   test:
556     # Using -dm_refine 1 -convest_num_refine 3 we get L_2 convergence rate: 2.8
557     suffix: 3d_p2_conv
558     requires: ctetgen
559     args: -dm_plex_dim 3 -dm_plex_box_faces 2,2,2 -potential_petscspace_degree 2 -snes_convergence_estimate -convest_num_refine 1
560   test:
561     # Using -dm_refine 1 -convest_num_refine 3 we get L_2 convergence rate: 4.0
562     suffix: 3d_p3_conv
563     requires: ctetgen
564     args: -dm_plex_dim 3 -dm_plex_box_faces 2,2,2 -potential_petscspace_degree 3 -snes_convergence_estimate -convest_num_refine 1
565   test:
566     # Using -dm_refine 2 -convest_num_refine 3 we get L_2 convergence rate: 1.8
567     suffix: 3d_q1_conv
568     args: -dm_plex_dim 3 -dm_plex_simplex 0 -dm_refine 1 -potential_petscspace_degree 1 -snes_convergence_estimate -convest_num_refine 1
569   test:
570     # Using -dm_refine 2 -convest_num_refine 3 we get L_2 convergence rate: 2.8
571     suffix: 3d_q2_conv
572     args: -dm_plex_dim 3 -dm_plex_simplex 0 -potential_petscspace_degree 2 -snes_convergence_estimate -convest_num_refine 1
573   test:
574     # Using -dm_refine 1 -convest_num_refine 3 we get L_2 convergence rate: 3.8
575     suffix: 3d_q3_conv
576     args: -dm_plex_dim 3 -dm_plex_simplex 0 -potential_petscspace_degree 3 -snes_convergence_estimate -convest_num_refine 1
577   test:
578     suffix: 2d_p1_fas_full
579     requires: triangle
580     args: -potential_petscspace_degree 1 -dm_refine_hierarchy 5 \
581       -snes_max_it 1 -snes_type fas -snes_fas_levels 5 -snes_fas_type full -snes_fas_full_total \
582         -fas_coarse_snes_monitor -fas_coarse_snes_max_it 1 -fas_coarse_ksp_atol 1.e-13 \
583         -fas_levels_snes_monitor -fas_levels_snes_max_it 1 -fas_levels_snes_type newtonls \
584           -fas_levels_pc_type none -fas_levels_ksp_max_it 2 -fas_levels_ksp_converged_maxits -fas_levels_ksp_type chebyshev \
585             -fas_levels_esteig_ksp_type cg -fas_levels_ksp_chebyshev_esteig 0,0.25,0,1.1 -fas_levels_esteig_ksp_max_it 10
586   test:
587     suffix: 2d_p1_fas_full_homogeneous
588     requires: triangle
589     args: -homogeneous -potential_petscspace_degree 1 -dm_refine_hierarchy 5 \
590       -snes_max_it 1 -snes_type fas -snes_fas_levels 5 -snes_fas_type full \
591         -fas_coarse_snes_monitor -fas_coarse_snes_max_it 1 -fas_coarse_ksp_atol 1.e-13 \
592         -fas_levels_snes_monitor -fas_levels_snes_max_it 1 -fas_levels_snes_type newtonls \
593           -fas_levels_pc_type none -fas_levels_ksp_max_it 2 -fas_levels_ksp_converged_maxits -fas_levels_ksp_type chebyshev \
594             -fas_levels_esteig_ksp_type cg -fas_levels_ksp_chebyshev_esteig 0,0.25,0,1.1 -fas_levels_esteig_ksp_max_it 10
595 
596   test:
597     suffix: 2d_p1_scalable
598     requires: triangle
599     args: -potential_petscspace_degree 1 -dm_refine 3 \
600       -ksp_type cg -ksp_rtol 1.e-11 -ksp_norm_type unpreconditioned \
601       -pc_type gamg -pc_gamg_esteig_ksp_type cg -pc_gamg_esteig_ksp_max_it 10 \
602         -pc_gamg_type agg -pc_gamg_agg_nsmooths 1 \
603         -pc_gamg_coarse_eq_limit 1000 \
604         -pc_gamg_threshold 0.05 \
605         -pc_gamg_threshold_scale .0 \
606         -mg_levels_ksp_type chebyshev \
607         -mg_levels_ksp_max_it 1 \
608         -mg_levels_pc_type jacobi \
609       -matptap_via scalable
610   test:
611     suffix: 2d_p1_gmg_vcycle
612     requires: triangle
613     args: -potential_petscspace_degree 1 -dm_plex_box_faces 2,2 -dm_refine_hierarchy 3 \
614           -ksp_rtol 5e-10 -pc_type mg \
615             -mg_levels_ksp_max_it 1 \
616             -mg_levels_esteig_ksp_type cg \
617             -mg_levels_esteig_ksp_max_it 10 \
618             -mg_levels_ksp_chebyshev_esteig 0,0.1,0,1.1 \
619             -mg_levels_pc_type jacobi
620   test:
621     suffix: 2d_p1_gmg_fcycle
622     requires: triangle
623     args: -potential_petscspace_degree 1 -dm_plex_box_faces 2,2 -dm_refine_hierarchy 3 \
624           -ksp_rtol 5e-10 -pc_type mg -pc_mg_type full \
625             -mg_levels_ksp_max_it 2 \
626             -mg_levels_esteig_ksp_type cg \
627             -mg_levels_esteig_ksp_max_it 10 \
628             -mg_levels_ksp_chebyshev_esteig 0,0.1,0,1.1 \
629             -mg_levels_pc_type jacobi
630   test:
631     suffix: 2d_p1_gmg_vcycle_adapt
632     requires: triangle
633     args: -petscpartitioner_type simple -potential_petscspace_degree 1 -dm_plex_box_faces 2,2 -dm_refine_hierarchy 3 \
634           -ksp_rtol 5e-10 -pc_type mg -pc_mg_galerkin -pc_mg_adapt_interp_coarse_space harmonic -pc_mg_adapt_interp_n 8 \
635             -mg_levels_ksp_max_it 1 \
636             -mg_levels_esteig_ksp_type cg \
637             -mg_levels_esteig_ksp_max_it 10 \
638             -mg_levels_ksp_chebyshev_esteig 0,0.1,0,1.1 \
639             -mg_levels_pc_type jacobi
640   test:
641     suffix: 2d_p1_spectral_0
642     requires: triangle fftw !complex
643     args: -dm_plex_box_faces 1,1 -potential_petscspace_degree 1 -dm_refine 6 -spectral -fft_view
644   test:
645     suffix: 2d_p1_spectral_1
646     requires: triangle fftw !complex
647     nsize: 2
648     args: -dm_plex_box_faces 4,4 -potential_petscspace_degree 1 -spectral -fft_view
649   test:
650     suffix: 2d_p1_adj_0
651     requires: triangle
652     args: -potential_petscspace_degree 1 -dm_refine 1 -adjoint -adjoint_petscspace_degree 1 -error_petscspace_degree 0
653   test:
654     nsize: 2
655     requires: kokkos_kernels
656     suffix: kokkos
657     args: -dm_plex_dim 3 -dm_plex_box_faces 2,3,6 -petscpartitioner_type simple -dm_plex_simplex 0 -potential_petscspace_degree 1 \
658          -dm_refine 0 -ksp_type cg -ksp_rtol 1.e-11 -ksp_norm_type unpreconditioned -pc_type gamg -pc_gamg_coarse_eq_limit 1000 -pc_gamg_threshold 0.0 \
659          -pc_gamg_threshold_scale .5 -mg_levels_ksp_type chebyshev -mg_levels_ksp_max_it 2 -pc_gamg_esteig_ksp_type cg -pc_gamg_esteig_ksp_max_it 10 \
660          -ksp_monitor -snes_monitor -dm_view -dm_mat_type aijkokkos -dm_vec_type kokkos
661 
662 TEST*/
663