xref: /petsc/src/snes/utils/dmplexsnes.c (revision b48ab24ab3d10fe53e9be11bf7e4243edd5ad7ec)
1 #include <petsc/private/dmpleximpl.h>   /*I "petscdmplex.h" I*/
2 #include <petsc/private/snesimpl.h>     /*I "petscsnes.h"   I*/
3 #include <petscds.h>
4 #include <petscblaslapack.h>
5 #include <petsc/private/petscimpl.h>
6 #include <petsc/private/petscfeimpl.h>
7 
8 /************************** Interpolation *******************************/
9 
10 static PetscErrorCode DMSNESConvertPlex(DM dm, DM *plex, PetscBool copy)
11 {
12   PetscBool      isPlex;
13   PetscErrorCode ierr;
14 
15   PetscFunctionBegin;
16   ierr = PetscObjectTypeCompare((PetscObject) dm, DMPLEX, &isPlex);CHKERRQ(ierr);
17   if (isPlex) {
18     *plex = dm;
19     ierr = PetscObjectReference((PetscObject) dm);CHKERRQ(ierr);
20   } else {
21     ierr = PetscObjectQuery((PetscObject) dm, "dm_plex", (PetscObject *) plex);CHKERRQ(ierr);
22     if (!*plex) {
23       ierr = DMConvert(dm,DMPLEX,plex);CHKERRQ(ierr);
24       ierr = PetscObjectCompose((PetscObject) dm, "dm_plex", (PetscObject) *plex);CHKERRQ(ierr);
25       if (copy) {
26         PetscInt    i;
27         PetscObject obj;
28         const char *comps[3] = {"A","dmAux","dmCh"};
29 
30         ierr = DMCopyDMSNES(dm, *plex);CHKERRQ(ierr);
31         for (i = 0; i < 3; i++) {
32           ierr = PetscObjectQuery((PetscObject) dm, comps[i], &obj);CHKERRQ(ierr);
33           ierr = PetscObjectCompose((PetscObject) *plex, comps[i], obj);CHKERRQ(ierr);
34         }
35       }
36     } else {
37       ierr = PetscObjectReference((PetscObject) *plex);CHKERRQ(ierr);
38     }
39   }
40   PetscFunctionReturn(0);
41 }
42 
43 PetscErrorCode DMInterpolationCreate(MPI_Comm comm, DMInterpolationInfo *ctx)
44 {
45   PetscErrorCode ierr;
46 
47   PetscFunctionBegin;
48   PetscValidPointer(ctx, 2);
49   ierr = PetscNew(ctx);CHKERRQ(ierr);
50 
51   (*ctx)->comm   = comm;
52   (*ctx)->dim    = -1;
53   (*ctx)->nInput = 0;
54   (*ctx)->points = NULL;
55   (*ctx)->cells  = NULL;
56   (*ctx)->n      = -1;
57   (*ctx)->coords = NULL;
58   PetscFunctionReturn(0);
59 }
60 
61 PetscErrorCode DMInterpolationSetDim(DMInterpolationInfo ctx, PetscInt dim)
62 {
63   PetscFunctionBegin;
64   if ((dim < 1) || (dim > 3)) SETERRQ1(ctx->comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid dimension for points: %d", dim);
65   ctx->dim = dim;
66   PetscFunctionReturn(0);
67 }
68 
69 PetscErrorCode DMInterpolationGetDim(DMInterpolationInfo ctx, PetscInt *dim)
70 {
71   PetscFunctionBegin;
72   PetscValidIntPointer(dim, 2);
73   *dim = ctx->dim;
74   PetscFunctionReturn(0);
75 }
76 
77 PetscErrorCode DMInterpolationSetDof(DMInterpolationInfo ctx, PetscInt dof)
78 {
79   PetscFunctionBegin;
80   if (dof < 1) SETERRQ1(ctx->comm, PETSC_ERR_ARG_OUTOFRANGE, "Invalid number of components: %d", dof);
81   ctx->dof = dof;
82   PetscFunctionReturn(0);
83 }
84 
85 PetscErrorCode DMInterpolationGetDof(DMInterpolationInfo ctx, PetscInt *dof)
86 {
87   PetscFunctionBegin;
88   PetscValidIntPointer(dof, 2);
89   *dof = ctx->dof;
90   PetscFunctionReturn(0);
91 }
92 
93 PetscErrorCode DMInterpolationAddPoints(DMInterpolationInfo ctx, PetscInt n, PetscReal points[])
94 {
95   PetscErrorCode ierr;
96 
97   PetscFunctionBegin;
98   if (ctx->dim < 0) SETERRQ(ctx->comm, PETSC_ERR_ARG_WRONGSTATE, "The spatial dimension has not been set");
99   if (ctx->points)  SETERRQ(ctx->comm, PETSC_ERR_ARG_WRONGSTATE, "Cannot add points multiple times yet");
100   ctx->nInput = n;
101 
102   ierr = PetscMalloc1(n*ctx->dim, &ctx->points);CHKERRQ(ierr);
103   ierr = PetscMemcpy(ctx->points, points, n*ctx->dim * sizeof(PetscReal));CHKERRQ(ierr);
104   PetscFunctionReturn(0);
105 }
106 
107 PetscErrorCode DMInterpolationSetUp(DMInterpolationInfo ctx, DM dm, PetscBool redundantPoints)
108 {
109   MPI_Comm          comm = ctx->comm;
110   PetscScalar       *a;
111   PetscInt          p, q, i;
112   PetscMPIInt       rank, size;
113   PetscErrorCode    ierr;
114   Vec               pointVec;
115   PetscSF           cellSF;
116   PetscLayout       layout;
117   PetscReal         *globalPoints;
118   PetscScalar       *globalPointsScalar;
119   const PetscInt    *ranges;
120   PetscMPIInt       *counts, *displs;
121   const PetscSFNode *foundCells;
122   const PetscInt    *foundPoints;
123   PetscMPIInt       *foundProcs, *globalProcs;
124   PetscInt          n, N, numFound;
125 
126   PetscFunctionBegin;
127   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
128   ierr = MPI_Comm_size(comm, &size);CHKERRQ(ierr);
129   ierr = MPI_Comm_rank(comm, &rank);CHKERRQ(ierr);
130   if (ctx->dim < 0) SETERRQ(comm, PETSC_ERR_ARG_WRONGSTATE, "The spatial dimension has not been set");
131   /* Locate points */
132   n = ctx->nInput;
133   if (!redundantPoints) {
134     ierr = PetscLayoutCreate(comm, &layout);CHKERRQ(ierr);
135     ierr = PetscLayoutSetBlockSize(layout, 1);CHKERRQ(ierr);
136     ierr = PetscLayoutSetLocalSize(layout, n);CHKERRQ(ierr);
137     ierr = PetscLayoutSetUp(layout);CHKERRQ(ierr);
138     ierr = PetscLayoutGetSize(layout, &N);CHKERRQ(ierr);
139     /* Communicate all points to all processes */
140     ierr = PetscMalloc3(N*ctx->dim,&globalPoints,size,&counts,size,&displs);CHKERRQ(ierr);
141     ierr = PetscLayoutGetRanges(layout, &ranges);CHKERRQ(ierr);
142     for (p = 0; p < size; ++p) {
143       counts[p] = (ranges[p+1] - ranges[p])*ctx->dim;
144       displs[p] = ranges[p]*ctx->dim;
145     }
146     ierr = MPI_Allgatherv(ctx->points, n*ctx->dim, MPIU_REAL, globalPoints, counts, displs, MPIU_REAL, comm);CHKERRQ(ierr);
147   } else {
148     N = n;
149     globalPoints = ctx->points;
150     counts = displs = NULL;
151     layout = NULL;
152   }
153 #if 0
154   ierr = PetscMalloc3(N,&foundCells,N,&foundProcs,N,&globalProcs);CHKERRQ(ierr);
155   /* foundCells[p] = m->locatePoint(&globalPoints[p*ctx->dim]); */
156 #else
157 #if defined(PETSC_USE_COMPLEX)
158   ierr = PetscMalloc1(N,&globalPointsScalar);CHKERRQ(ierr);
159   for (i=0; i<N; i++) globalPointsScalar[i] = globalPoints[i];
160 #else
161   globalPointsScalar = globalPoints;
162 #endif
163   ierr = VecCreateSeqWithArray(PETSC_COMM_SELF, ctx->dim, N*ctx->dim, globalPointsScalar, &pointVec);CHKERRQ(ierr);
164   ierr = PetscMalloc2(N,&foundProcs,N,&globalProcs);CHKERRQ(ierr);
165   for (p = 0; p < N; ++p) {foundProcs[p] = size;}
166   cellSF = NULL;
167   ierr = DMLocatePoints(dm, pointVec, DM_POINTLOCATION_REMOVE, &cellSF);CHKERRQ(ierr);
168   ierr = PetscSFGetGraph(cellSF,NULL,&numFound,&foundPoints,&foundCells);CHKERRQ(ierr);
169 #endif
170   for (p = 0; p < numFound; ++p) {
171     if (foundCells[p].index >= 0) foundProcs[foundPoints ? foundPoints[p] : p] = rank;
172   }
173   /* Let the lowest rank process own each point */
174   ierr   = MPIU_Allreduce(foundProcs, globalProcs, N, MPI_INT, MPI_MIN, comm);CHKERRQ(ierr);
175   ctx->n = 0;
176   for (p = 0; p < N; ++p) {
177     if (globalProcs[p] == size) SETERRQ4(comm, PETSC_ERR_PLIB, "Point %d: %g %g %g not located in mesh", p, globalPoints[p*ctx->dim+0], ctx->dim > 1 ? globalPoints[p*ctx->dim+1] : 0.0, ctx->dim > 2 ? globalPoints[p*ctx->dim+2] : 0.0);
178     else if (globalProcs[p] == rank) ctx->n++;
179   }
180   /* Create coordinates vector and array of owned cells */
181   ierr = PetscMalloc1(ctx->n, &ctx->cells);CHKERRQ(ierr);
182   ierr = VecCreate(comm, &ctx->coords);CHKERRQ(ierr);
183   ierr = VecSetSizes(ctx->coords, ctx->n*ctx->dim, PETSC_DECIDE);CHKERRQ(ierr);
184   ierr = VecSetBlockSize(ctx->coords, ctx->dim);CHKERRQ(ierr);
185   ierr = VecSetType(ctx->coords,VECSTANDARD);CHKERRQ(ierr);
186   ierr = VecGetArray(ctx->coords, &a);CHKERRQ(ierr);
187   for (p = 0, q = 0, i = 0; p < N; ++p) {
188     if (globalProcs[p] == rank) {
189       PetscInt d;
190 
191       for (d = 0; d < ctx->dim; ++d, ++i) a[i] = globalPoints[p*ctx->dim+d];
192       ctx->cells[q++] = foundCells[p].index;
193     }
194   }
195   ierr = VecRestoreArray(ctx->coords, &a);CHKERRQ(ierr);
196 #if 0
197   ierr = PetscFree3(foundCells,foundProcs,globalProcs);CHKERRQ(ierr);
198 #else
199   ierr = PetscFree2(foundProcs,globalProcs);CHKERRQ(ierr);
200   ierr = PetscSFDestroy(&cellSF);CHKERRQ(ierr);
201   ierr = VecDestroy(&pointVec);CHKERRQ(ierr);
202 #endif
203   if ((void*)globalPointsScalar != (void*)globalPoints) {ierr = PetscFree(globalPointsScalar);CHKERRQ(ierr);}
204   if (!redundantPoints) {ierr = PetscFree3(globalPoints,counts,displs);CHKERRQ(ierr);}
205   ierr = PetscLayoutDestroy(&layout);CHKERRQ(ierr);
206   PetscFunctionReturn(0);
207 }
208 
209 PetscErrorCode DMInterpolationGetCoordinates(DMInterpolationInfo ctx, Vec *coordinates)
210 {
211   PetscFunctionBegin;
212   PetscValidPointer(coordinates, 2);
213   if (!ctx->coords) SETERRQ(ctx->comm, PETSC_ERR_ARG_WRONGSTATE, "The interpolation context has not been setup.");
214   *coordinates = ctx->coords;
215   PetscFunctionReturn(0);
216 }
217 
218 PetscErrorCode DMInterpolationGetVector(DMInterpolationInfo ctx, Vec *v)
219 {
220   PetscErrorCode ierr;
221 
222   PetscFunctionBegin;
223   PetscValidPointer(v, 2);
224   if (!ctx->coords) SETERRQ(ctx->comm, PETSC_ERR_ARG_WRONGSTATE, "The interpolation context has not been setup.");
225   ierr = VecCreate(ctx->comm, v);CHKERRQ(ierr);
226   ierr = VecSetSizes(*v, ctx->n*ctx->dof, PETSC_DECIDE);CHKERRQ(ierr);
227   ierr = VecSetBlockSize(*v, ctx->dof);CHKERRQ(ierr);
228   ierr = VecSetType(*v,VECSTANDARD);CHKERRQ(ierr);
229   PetscFunctionReturn(0);
230 }
231 
232 PetscErrorCode DMInterpolationRestoreVector(DMInterpolationInfo ctx, Vec *v)
233 {
234   PetscErrorCode ierr;
235 
236   PetscFunctionBegin;
237   PetscValidPointer(v, 2);
238   if (!ctx->coords) SETERRQ(ctx->comm, PETSC_ERR_ARG_WRONGSTATE, "The interpolation context has not been setup.");
239   ierr = VecDestroy(v);CHKERRQ(ierr);
240   PetscFunctionReturn(0);
241 }
242 
243 PETSC_STATIC_INLINE PetscErrorCode DMInterpolate_Triangle_Private(DMInterpolationInfo ctx, DM dm, Vec xLocal, Vec v)
244 {
245   PetscReal      *v0, *J, *invJ, detJ;
246   const PetscScalar *coords;
247   PetscScalar    *a;
248   PetscInt       p;
249   PetscErrorCode ierr;
250 
251   PetscFunctionBegin;
252   ierr = PetscMalloc3(ctx->dim,&v0,ctx->dim*ctx->dim,&J,ctx->dim*ctx->dim,&invJ);CHKERRQ(ierr);
253   ierr = VecGetArrayRead(ctx->coords, &coords);CHKERRQ(ierr);
254   ierr = VecGetArray(v, &a);CHKERRQ(ierr);
255   for (p = 0; p < ctx->n; ++p) {
256     PetscInt     c = ctx->cells[p];
257     PetscScalar *x = NULL;
258     PetscReal    xi[4];
259     PetscInt     d, f, comp;
260 
261     ierr = DMPlexComputeCellGeometryFEM(dm, c, NULL, v0, J, invJ, &detJ);CHKERRQ(ierr);
262     if (detJ <= 0.0) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid determinant %g for element %d", detJ, c);
263     ierr = DMPlexVecGetClosure(dm, NULL, xLocal, c, NULL, &x);CHKERRQ(ierr);
264     for (comp = 0; comp < ctx->dof; ++comp) a[p*ctx->dof+comp] = x[0*ctx->dof+comp];
265 
266     for (d = 0; d < ctx->dim; ++d) {
267       xi[d] = 0.0;
268       for (f = 0; f < ctx->dim; ++f) xi[d] += invJ[d*ctx->dim+f]*0.5*PetscRealPart(coords[p*ctx->dim+f] - v0[f]);
269       for (comp = 0; comp < ctx->dof; ++comp) a[p*ctx->dof+comp] += PetscRealPart(x[(d+1)*ctx->dof+comp] - x[0*ctx->dof+comp])*xi[d];
270     }
271     ierr = DMPlexVecRestoreClosure(dm, NULL, xLocal, c, NULL, &x);CHKERRQ(ierr);
272   }
273   ierr = VecRestoreArray(v, &a);CHKERRQ(ierr);
274   ierr = VecRestoreArrayRead(ctx->coords, &coords);CHKERRQ(ierr);
275   ierr = PetscFree3(v0, J, invJ);CHKERRQ(ierr);
276   PetscFunctionReturn(0);
277 }
278 
279 PETSC_STATIC_INLINE PetscErrorCode DMInterpolate_Tetrahedron_Private(DMInterpolationInfo ctx, DM dm, Vec xLocal, Vec v)
280 {
281   PetscReal      *v0, *J, *invJ, detJ;
282   const PetscScalar *coords;
283   PetscScalar    *a;
284   PetscInt       p;
285   PetscErrorCode ierr;
286 
287   PetscFunctionBegin;
288   ierr = PetscMalloc3(ctx->dim,&v0,ctx->dim*ctx->dim,&J,ctx->dim*ctx->dim,&invJ);CHKERRQ(ierr);
289   ierr = VecGetArrayRead(ctx->coords, &coords);CHKERRQ(ierr);
290   ierr = VecGetArray(v, &a);CHKERRQ(ierr);
291   for (p = 0; p < ctx->n; ++p) {
292     PetscInt       c = ctx->cells[p];
293     const PetscInt order[3] = {2, 1, 3};
294     PetscScalar   *x = NULL;
295     PetscReal      xi[4];
296     PetscInt       d, f, comp;
297 
298     ierr = DMPlexComputeCellGeometryFEM(dm, c, NULL, v0, J, invJ, &detJ);CHKERRQ(ierr);
299     if (detJ <= 0.0) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid determinant %g for element %d", detJ, c);
300     ierr = DMPlexVecGetClosure(dm, NULL, xLocal, c, NULL, &x);CHKERRQ(ierr);
301     for (comp = 0; comp < ctx->dof; ++comp) a[p*ctx->dof+comp] = x[0*ctx->dof+comp];
302 
303     for (d = 0; d < ctx->dim; ++d) {
304       xi[d] = 0.0;
305       for (f = 0; f < ctx->dim; ++f) xi[d] += invJ[d*ctx->dim+f]*0.5*PetscRealPart(coords[p*ctx->dim+f] - v0[f]);
306       for (comp = 0; comp < ctx->dof; ++comp) a[p*ctx->dof+comp] += PetscRealPart(x[order[d]*ctx->dof+comp] - x[0*ctx->dof+comp])*xi[d];
307     }
308     ierr = DMPlexVecRestoreClosure(dm, NULL, xLocal, c, NULL, &x);CHKERRQ(ierr);
309   }
310   ierr = VecRestoreArray(v, &a);CHKERRQ(ierr);
311   ierr = VecRestoreArrayRead(ctx->coords, &coords);CHKERRQ(ierr);
312   ierr = PetscFree3(v0, J, invJ);CHKERRQ(ierr);
313   PetscFunctionReturn(0);
314 }
315 
316 PETSC_STATIC_INLINE PetscErrorCode QuadMap_Private(SNES snes, Vec Xref, Vec Xreal, void *ctx)
317 {
318   const PetscScalar *vertices = (const PetscScalar*) ctx;
319   const PetscScalar x0        = vertices[0];
320   const PetscScalar y0        = vertices[1];
321   const PetscScalar x1        = vertices[2];
322   const PetscScalar y1        = vertices[3];
323   const PetscScalar x2        = vertices[4];
324   const PetscScalar y2        = vertices[5];
325   const PetscScalar x3        = vertices[6];
326   const PetscScalar y3        = vertices[7];
327   const PetscScalar f_1       = x1 - x0;
328   const PetscScalar g_1       = y1 - y0;
329   const PetscScalar f_3       = x3 - x0;
330   const PetscScalar g_3       = y3 - y0;
331   const PetscScalar f_01      = x2 - x1 - x3 + x0;
332   const PetscScalar g_01      = y2 - y1 - y3 + y0;
333   const PetscScalar *ref;
334   PetscScalar       *real;
335   PetscErrorCode    ierr;
336 
337   PetscFunctionBegin;
338   ierr = VecGetArrayRead(Xref,  &ref);CHKERRQ(ierr);
339   ierr = VecGetArray(Xreal, &real);CHKERRQ(ierr);
340   {
341     const PetscScalar p0 = ref[0];
342     const PetscScalar p1 = ref[1];
343 
344     real[0] = x0 + f_1 * p0 + f_3 * p1 + f_01 * p0 * p1;
345     real[1] = y0 + g_1 * p0 + g_3 * p1 + g_01 * p0 * p1;
346   }
347   ierr = PetscLogFlops(28);CHKERRQ(ierr);
348   ierr = VecRestoreArrayRead(Xref,  &ref);CHKERRQ(ierr);
349   ierr = VecRestoreArray(Xreal, &real);CHKERRQ(ierr);
350   PetscFunctionReturn(0);
351 }
352 
353 #include <petsc/private/dmimpl.h>
354 PETSC_STATIC_INLINE PetscErrorCode QuadJacobian_Private(SNES snes, Vec Xref, Mat J, Mat M, void *ctx)
355 {
356   const PetscScalar *vertices = (const PetscScalar*) ctx;
357   const PetscScalar x0        = vertices[0];
358   const PetscScalar y0        = vertices[1];
359   const PetscScalar x1        = vertices[2];
360   const PetscScalar y1        = vertices[3];
361   const PetscScalar x2        = vertices[4];
362   const PetscScalar y2        = vertices[5];
363   const PetscScalar x3        = vertices[6];
364   const PetscScalar y3        = vertices[7];
365   const PetscScalar f_01      = x2 - x1 - x3 + x0;
366   const PetscScalar g_01      = y2 - y1 - y3 + y0;
367   const PetscScalar *ref;
368   PetscErrorCode    ierr;
369 
370   PetscFunctionBegin;
371   ierr = VecGetArrayRead(Xref,  &ref);CHKERRQ(ierr);
372   {
373     const PetscScalar x       = ref[0];
374     const PetscScalar y       = ref[1];
375     const PetscInt    rows[2] = {0, 1};
376     PetscScalar       values[4];
377 
378     values[0] = (x1 - x0 + f_01*y) * 0.5; values[1] = (x3 - x0 + f_01*x) * 0.5;
379     values[2] = (y1 - y0 + g_01*y) * 0.5; values[3] = (y3 - y0 + g_01*x) * 0.5;
380     ierr      = MatSetValues(J, 2, rows, 2, rows, values, INSERT_VALUES);CHKERRQ(ierr);
381   }
382   ierr = PetscLogFlops(30);CHKERRQ(ierr);
383   ierr = VecRestoreArrayRead(Xref,  &ref);CHKERRQ(ierr);
384   ierr = MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
385   ierr = MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
386   PetscFunctionReturn(0);
387 }
388 
389 PETSC_STATIC_INLINE PetscErrorCode DMInterpolate_Quad_Private(DMInterpolationInfo ctx, DM dm, Vec xLocal, Vec v)
390 {
391   DM             dmCoord;
392   PetscFE        fem = NULL;
393   SNES           snes;
394   KSP            ksp;
395   PC             pc;
396   Vec            coordsLocal, r, ref, real;
397   Mat            J;
398   const PetscScalar *coords;
399   PetscScalar    *a;
400   PetscInt       Nf, p;
401   const PetscInt dof = ctx->dof;
402   PetscErrorCode ierr;
403 
404   PetscFunctionBegin;
405   ierr = DMGetNumFields(dm, &Nf);CHKERRQ(ierr);
406   if (Nf) {ierr = DMGetField(dm, 0, (PetscObject *) &fem);CHKERRQ(ierr);}
407   ierr = DMGetCoordinatesLocal(dm, &coordsLocal);CHKERRQ(ierr);
408   ierr = DMGetCoordinateDM(dm, &dmCoord);CHKERRQ(ierr);
409   ierr = SNESCreate(PETSC_COMM_SELF, &snes);CHKERRQ(ierr);
410   ierr = SNESSetOptionsPrefix(snes, "quad_interp_");CHKERRQ(ierr);
411   ierr = VecCreate(PETSC_COMM_SELF, &r);CHKERRQ(ierr);
412   ierr = VecSetSizes(r, 2, 2);CHKERRQ(ierr);
413   ierr = VecSetType(r,dm->vectype);CHKERRQ(ierr);
414   ierr = VecDuplicate(r, &ref);CHKERRQ(ierr);
415   ierr = VecDuplicate(r, &real);CHKERRQ(ierr);
416   ierr = MatCreate(PETSC_COMM_SELF, &J);CHKERRQ(ierr);
417   ierr = MatSetSizes(J, 2, 2, 2, 2);CHKERRQ(ierr);
418   ierr = MatSetType(J, MATSEQDENSE);CHKERRQ(ierr);
419   ierr = MatSetUp(J);CHKERRQ(ierr);
420   ierr = SNESSetFunction(snes, r, QuadMap_Private, NULL);CHKERRQ(ierr);
421   ierr = SNESSetJacobian(snes, J, J, QuadJacobian_Private, NULL);CHKERRQ(ierr);
422   ierr = SNESGetKSP(snes, &ksp);CHKERRQ(ierr);
423   ierr = KSPGetPC(ksp, &pc);CHKERRQ(ierr);
424   ierr = PCSetType(pc, PCLU);CHKERRQ(ierr);
425   ierr = SNESSetFromOptions(snes);CHKERRQ(ierr);
426 
427   ierr = VecGetArrayRead(ctx->coords, &coords);CHKERRQ(ierr);
428   ierr = VecGetArray(v, &a);CHKERRQ(ierr);
429   for (p = 0; p < ctx->n; ++p) {
430     PetscScalar *x = NULL, *vertices = NULL;
431     PetscScalar *xi;
432     PetscReal    xir[2];
433     PetscInt     c = ctx->cells[p], comp, coordSize, xSize;
434 
435     /* Can make this do all points at once */
436     ierr = DMPlexVecGetClosure(dmCoord, NULL, coordsLocal, c, &coordSize, &vertices);CHKERRQ(ierr);
437     if (4*2 != coordSize) SETERRQ2(ctx->comm, PETSC_ERR_ARG_SIZ, "Invalid closure size %d should be %d", coordSize, 4*2);
438     ierr   = DMPlexVecGetClosure(dm, NULL, xLocal, c, &xSize, &x);CHKERRQ(ierr);
439     ierr   = SNESSetFunction(snes, NULL, NULL, (void*) vertices);CHKERRQ(ierr);
440     ierr   = SNESSetJacobian(snes, NULL, NULL, NULL, (void*) vertices);CHKERRQ(ierr);
441     ierr   = VecGetArray(real, &xi);CHKERRQ(ierr);
442     xi[0]  = coords[p*ctx->dim+0];
443     xi[1]  = coords[p*ctx->dim+1];
444     ierr   = VecRestoreArray(real, &xi);CHKERRQ(ierr);
445     ierr   = SNESSolve(snes, real, ref);CHKERRQ(ierr);
446     ierr   = VecGetArray(ref, &xi);CHKERRQ(ierr);
447     xir[0] = PetscRealPart(xi[0]);
448     xir[1] = PetscRealPart(xi[1]);
449     if (4*dof != xSize) {
450       PetscReal *B;
451       PetscInt   d;
452 
453       xir[0] = 2.0*xir[0] - 1.0; xir[1] = 2.0*xir[1] - 1.0;
454       ierr = PetscFEGetTabulation(fem, 1, xir, &B, NULL, NULL);CHKERRQ(ierr);
455       for (comp = 0; comp < dof; ++comp) {
456         a[p*dof+comp] = 0.0;
457         for (d = 0; d < xSize/dof; ++d) {
458           a[p*dof+comp] += x[d*dof+comp]*B[d*dof+comp];
459         }
460       }
461       ierr = PetscFERestoreTabulation(fem, 1, xir, &B, NULL, NULL);CHKERRQ(ierr);
462     } else {
463       for (comp = 0; comp < dof; ++comp)
464         a[p*dof+comp] = x[0*dof+comp]*(1 - xir[0])*(1 - xir[1]) + x[1*dof+comp]*xir[0]*(1 - xir[1]) + x[2*dof+comp]*xir[0]*xir[1] + x[3*dof+comp]*(1 - xir[0])*xir[1];
465     }
466     ierr = VecRestoreArray(ref, &xi);CHKERRQ(ierr);
467     ierr = DMPlexVecRestoreClosure(dmCoord, NULL, coordsLocal, c, &coordSize, &vertices);CHKERRQ(ierr);
468     ierr = DMPlexVecRestoreClosure(dm, NULL, xLocal, c, &xSize, &x);CHKERRQ(ierr);
469   }
470   ierr = VecRestoreArray(v, &a);CHKERRQ(ierr);
471   ierr = VecRestoreArrayRead(ctx->coords, &coords);CHKERRQ(ierr);
472 
473   ierr = SNESDestroy(&snes);CHKERRQ(ierr);
474   ierr = VecDestroy(&r);CHKERRQ(ierr);
475   ierr = VecDestroy(&ref);CHKERRQ(ierr);
476   ierr = VecDestroy(&real);CHKERRQ(ierr);
477   ierr = MatDestroy(&J);CHKERRQ(ierr);
478   PetscFunctionReturn(0);
479 }
480 
481 PETSC_STATIC_INLINE PetscErrorCode HexMap_Private(SNES snes, Vec Xref, Vec Xreal, void *ctx)
482 {
483   const PetscScalar *vertices = (const PetscScalar*) ctx;
484   const PetscScalar x0        = vertices[0];
485   const PetscScalar y0        = vertices[1];
486   const PetscScalar z0        = vertices[2];
487   const PetscScalar x1        = vertices[9];
488   const PetscScalar y1        = vertices[10];
489   const PetscScalar z1        = vertices[11];
490   const PetscScalar x2        = vertices[6];
491   const PetscScalar y2        = vertices[7];
492   const PetscScalar z2        = vertices[8];
493   const PetscScalar x3        = vertices[3];
494   const PetscScalar y3        = vertices[4];
495   const PetscScalar z3        = vertices[5];
496   const PetscScalar x4        = vertices[12];
497   const PetscScalar y4        = vertices[13];
498   const PetscScalar z4        = vertices[14];
499   const PetscScalar x5        = vertices[15];
500   const PetscScalar y5        = vertices[16];
501   const PetscScalar z5        = vertices[17];
502   const PetscScalar x6        = vertices[18];
503   const PetscScalar y6        = vertices[19];
504   const PetscScalar z6        = vertices[20];
505   const PetscScalar x7        = vertices[21];
506   const PetscScalar y7        = vertices[22];
507   const PetscScalar z7        = vertices[23];
508   const PetscScalar f_1       = x1 - x0;
509   const PetscScalar g_1       = y1 - y0;
510   const PetscScalar h_1       = z1 - z0;
511   const PetscScalar f_3       = x3 - x0;
512   const PetscScalar g_3       = y3 - y0;
513   const PetscScalar h_3       = z3 - z0;
514   const PetscScalar f_4       = x4 - x0;
515   const PetscScalar g_4       = y4 - y0;
516   const PetscScalar h_4       = z4 - z0;
517   const PetscScalar f_01      = x2 - x1 - x3 + x0;
518   const PetscScalar g_01      = y2 - y1 - y3 + y0;
519   const PetscScalar h_01      = z2 - z1 - z3 + z0;
520   const PetscScalar f_12      = x7 - x3 - x4 + x0;
521   const PetscScalar g_12      = y7 - y3 - y4 + y0;
522   const PetscScalar h_12      = z7 - z3 - z4 + z0;
523   const PetscScalar f_02      = x5 - x1 - x4 + x0;
524   const PetscScalar g_02      = y5 - y1 - y4 + y0;
525   const PetscScalar h_02      = z5 - z1 - z4 + z0;
526   const PetscScalar f_012     = x6 - x0 + x1 - x2 + x3 + x4 - x5 - x7;
527   const PetscScalar g_012     = y6 - y0 + y1 - y2 + y3 + y4 - y5 - y7;
528   const PetscScalar h_012     = z6 - z0 + z1 - z2 + z3 + z4 - z5 - z7;
529   const PetscScalar *ref;
530   PetscScalar       *real;
531   PetscErrorCode    ierr;
532 
533   PetscFunctionBegin;
534   ierr = VecGetArrayRead(Xref,  &ref);CHKERRQ(ierr);
535   ierr = VecGetArray(Xreal, &real);CHKERRQ(ierr);
536   {
537     const PetscScalar p0 = ref[0];
538     const PetscScalar p1 = ref[1];
539     const PetscScalar p2 = ref[2];
540 
541     real[0] = x0 + f_1*p0 + f_3*p1 + f_4*p2 + f_01*p0*p1 + f_12*p1*p2 + f_02*p0*p2 + f_012*p0*p1*p2;
542     real[1] = y0 + g_1*p0 + g_3*p1 + g_4*p2 + g_01*p0*p1 + g_01*p0*p1 + g_12*p1*p2 + g_02*p0*p2 + g_012*p0*p1*p2;
543     real[2] = z0 + h_1*p0 + h_3*p1 + h_4*p2 + h_01*p0*p1 + h_01*p0*p1 + h_12*p1*p2 + h_02*p0*p2 + h_012*p0*p1*p2;
544   }
545   ierr = PetscLogFlops(114);CHKERRQ(ierr);
546   ierr = VecRestoreArrayRead(Xref,  &ref);CHKERRQ(ierr);
547   ierr = VecRestoreArray(Xreal, &real);CHKERRQ(ierr);
548   PetscFunctionReturn(0);
549 }
550 
551 PETSC_STATIC_INLINE PetscErrorCode HexJacobian_Private(SNES snes, Vec Xref, Mat J, Mat M, void *ctx)
552 {
553   const PetscScalar *vertices = (const PetscScalar*) ctx;
554   const PetscScalar x0        = vertices[0];
555   const PetscScalar y0        = vertices[1];
556   const PetscScalar z0        = vertices[2];
557   const PetscScalar x1        = vertices[9];
558   const PetscScalar y1        = vertices[10];
559   const PetscScalar z1        = vertices[11];
560   const PetscScalar x2        = vertices[6];
561   const PetscScalar y2        = vertices[7];
562   const PetscScalar z2        = vertices[8];
563   const PetscScalar x3        = vertices[3];
564   const PetscScalar y3        = vertices[4];
565   const PetscScalar z3        = vertices[5];
566   const PetscScalar x4        = vertices[12];
567   const PetscScalar y4        = vertices[13];
568   const PetscScalar z4        = vertices[14];
569   const PetscScalar x5        = vertices[15];
570   const PetscScalar y5        = vertices[16];
571   const PetscScalar z5        = vertices[17];
572   const PetscScalar x6        = vertices[18];
573   const PetscScalar y6        = vertices[19];
574   const PetscScalar z6        = vertices[20];
575   const PetscScalar x7        = vertices[21];
576   const PetscScalar y7        = vertices[22];
577   const PetscScalar z7        = vertices[23];
578   const PetscScalar f_xy      = x2 - x1 - x3 + x0;
579   const PetscScalar g_xy      = y2 - y1 - y3 + y0;
580   const PetscScalar h_xy      = z2 - z1 - z3 + z0;
581   const PetscScalar f_yz      = x7 - x3 - x4 + x0;
582   const PetscScalar g_yz      = y7 - y3 - y4 + y0;
583   const PetscScalar h_yz      = z7 - z3 - z4 + z0;
584   const PetscScalar f_xz      = x5 - x1 - x4 + x0;
585   const PetscScalar g_xz      = y5 - y1 - y4 + y0;
586   const PetscScalar h_xz      = z5 - z1 - z4 + z0;
587   const PetscScalar f_xyz     = x6 - x0 + x1 - x2 + x3 + x4 - x5 - x7;
588   const PetscScalar g_xyz     = y6 - y0 + y1 - y2 + y3 + y4 - y5 - y7;
589   const PetscScalar h_xyz     = z6 - z0 + z1 - z2 + z3 + z4 - z5 - z7;
590   const PetscScalar *ref;
591   PetscErrorCode    ierr;
592 
593   PetscFunctionBegin;
594   ierr = VecGetArrayRead(Xref,  &ref);CHKERRQ(ierr);
595   {
596     const PetscScalar x       = ref[0];
597     const PetscScalar y       = ref[1];
598     const PetscScalar z       = ref[2];
599     const PetscInt    rows[3] = {0, 1, 2};
600     PetscScalar       values[9];
601 
602     values[0] = (x1 - x0 + f_xy*y + f_xz*z + f_xyz*y*z) / 2.0;
603     values[1] = (x3 - x0 + f_xy*x + f_yz*z + f_xyz*x*z) / 2.0;
604     values[2] = (x4 - x0 + f_yz*y + f_xz*x + f_xyz*x*y) / 2.0;
605     values[3] = (y1 - y0 + g_xy*y + g_xz*z + g_xyz*y*z) / 2.0;
606     values[4] = (y3 - y0 + g_xy*x + g_yz*z + g_xyz*x*z) / 2.0;
607     values[5] = (y4 - y0 + g_yz*y + g_xz*x + g_xyz*x*y) / 2.0;
608     values[6] = (z1 - z0 + h_xy*y + h_xz*z + h_xyz*y*z) / 2.0;
609     values[7] = (z3 - z0 + h_xy*x + h_yz*z + h_xyz*x*z) / 2.0;
610     values[8] = (z4 - z0 + h_yz*y + h_xz*x + h_xyz*x*y) / 2.0;
611 
612     ierr = MatSetValues(J, 3, rows, 3, rows, values, INSERT_VALUES);CHKERRQ(ierr);
613   }
614   ierr = PetscLogFlops(152);CHKERRQ(ierr);
615   ierr = VecRestoreArrayRead(Xref,  &ref);CHKERRQ(ierr);
616   ierr = MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
617   ierr = MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
618   PetscFunctionReturn(0);
619 }
620 
621 PETSC_STATIC_INLINE PetscErrorCode DMInterpolate_Hex_Private(DMInterpolationInfo ctx, DM dm, Vec xLocal, Vec v)
622 {
623   DM             dmCoord;
624   SNES           snes;
625   KSP            ksp;
626   PC             pc;
627   Vec            coordsLocal, r, ref, real;
628   Mat            J;
629   const PetscScalar *coords;
630   PetscScalar    *a;
631   PetscInt       p;
632   PetscErrorCode ierr;
633 
634   PetscFunctionBegin;
635   ierr = DMGetCoordinatesLocal(dm, &coordsLocal);CHKERRQ(ierr);
636   ierr = DMGetCoordinateDM(dm, &dmCoord);CHKERRQ(ierr);
637   ierr = SNESCreate(PETSC_COMM_SELF, &snes);CHKERRQ(ierr);
638   ierr = SNESSetOptionsPrefix(snes, "hex_interp_");CHKERRQ(ierr);
639   ierr = VecCreate(PETSC_COMM_SELF, &r);CHKERRQ(ierr);
640   ierr = VecSetSizes(r, 3, 3);CHKERRQ(ierr);
641   ierr = VecSetType(r,dm->vectype);CHKERRQ(ierr);
642   ierr = VecDuplicate(r, &ref);CHKERRQ(ierr);
643   ierr = VecDuplicate(r, &real);CHKERRQ(ierr);
644   ierr = MatCreate(PETSC_COMM_SELF, &J);CHKERRQ(ierr);
645   ierr = MatSetSizes(J, 3, 3, 3, 3);CHKERRQ(ierr);
646   ierr = MatSetType(J, MATSEQDENSE);CHKERRQ(ierr);
647   ierr = MatSetUp(J);CHKERRQ(ierr);
648   ierr = SNESSetFunction(snes, r, HexMap_Private, NULL);CHKERRQ(ierr);
649   ierr = SNESSetJacobian(snes, J, J, HexJacobian_Private, NULL);CHKERRQ(ierr);
650   ierr = SNESGetKSP(snes, &ksp);CHKERRQ(ierr);
651   ierr = KSPGetPC(ksp, &pc);CHKERRQ(ierr);
652   ierr = PCSetType(pc, PCLU);CHKERRQ(ierr);
653   ierr = SNESSetFromOptions(snes);CHKERRQ(ierr);
654 
655   ierr = VecGetArrayRead(ctx->coords, &coords);CHKERRQ(ierr);
656   ierr = VecGetArray(v, &a);CHKERRQ(ierr);
657   for (p = 0; p < ctx->n; ++p) {
658     PetscScalar *x = NULL, *vertices = NULL;
659     PetscScalar *xi;
660     PetscReal    xir[3];
661     PetscInt     c = ctx->cells[p], comp, coordSize, xSize;
662 
663     /* Can make this do all points at once */
664     ierr = DMPlexVecGetClosure(dmCoord, NULL, coordsLocal, c, &coordSize, &vertices);CHKERRQ(ierr);
665     if (8*3 != coordSize) SETERRQ2(ctx->comm, PETSC_ERR_ARG_SIZ, "Invalid closure size %d should be %d", coordSize, 8*3);
666     ierr = DMPlexVecGetClosure(dm, NULL, xLocal, c, &xSize, &x);CHKERRQ(ierr);
667     if (8*ctx->dof != xSize) SETERRQ2(ctx->comm, PETSC_ERR_ARG_SIZ, "Invalid closure size %d should be %d", xSize, 8*ctx->dof);
668     ierr   = SNESSetFunction(snes, NULL, NULL, (void*) vertices);CHKERRQ(ierr);
669     ierr   = SNESSetJacobian(snes, NULL, NULL, NULL, (void*) vertices);CHKERRQ(ierr);
670     ierr   = VecGetArray(real, &xi);CHKERRQ(ierr);
671     xi[0]  = coords[p*ctx->dim+0];
672     xi[1]  = coords[p*ctx->dim+1];
673     xi[2]  = coords[p*ctx->dim+2];
674     ierr   = VecRestoreArray(real, &xi);CHKERRQ(ierr);
675     ierr   = SNESSolve(snes, real, ref);CHKERRQ(ierr);
676     ierr   = VecGetArray(ref, &xi);CHKERRQ(ierr);
677     xir[0] = PetscRealPart(xi[0]);
678     xir[1] = PetscRealPart(xi[1]);
679     xir[2] = PetscRealPart(xi[2]);
680     for (comp = 0; comp < ctx->dof; ++comp) {
681       a[p*ctx->dof+comp] =
682         x[0*ctx->dof+comp]*(1-xir[0])*(1-xir[1])*(1-xir[2]) +
683         x[3*ctx->dof+comp]*    xir[0]*(1-xir[1])*(1-xir[2]) +
684         x[2*ctx->dof+comp]*    xir[0]*    xir[1]*(1-xir[2]) +
685         x[1*ctx->dof+comp]*(1-xir[0])*    xir[1]*(1-xir[2]) +
686         x[4*ctx->dof+comp]*(1-xir[0])*(1-xir[1])*   xir[2] +
687         x[5*ctx->dof+comp]*    xir[0]*(1-xir[1])*   xir[2] +
688         x[6*ctx->dof+comp]*    xir[0]*    xir[1]*   xir[2] +
689         x[7*ctx->dof+comp]*(1-xir[0])*    xir[1]*   xir[2];
690     }
691     ierr = VecRestoreArray(ref, &xi);CHKERRQ(ierr);
692     ierr = DMPlexVecRestoreClosure(dmCoord, NULL, coordsLocal, c, &coordSize, &vertices);CHKERRQ(ierr);
693     ierr = DMPlexVecRestoreClosure(dm, NULL, xLocal, c, &xSize, &x);CHKERRQ(ierr);
694   }
695   ierr = VecRestoreArray(v, &a);CHKERRQ(ierr);
696   ierr = VecRestoreArrayRead(ctx->coords, &coords);CHKERRQ(ierr);
697 
698   ierr = SNESDestroy(&snes);CHKERRQ(ierr);
699   ierr = VecDestroy(&r);CHKERRQ(ierr);
700   ierr = VecDestroy(&ref);CHKERRQ(ierr);
701   ierr = VecDestroy(&real);CHKERRQ(ierr);
702   ierr = MatDestroy(&J);CHKERRQ(ierr);
703   PetscFunctionReturn(0);
704 }
705 
706 /*
707   Input Parameters:
708 + ctx - The DMInterpolationInfo context
709 . dm  - The DM
710 - x   - The local vector containing the field to be interpolated
711 
712   Output Parameters:
713 . v   - The vector containing the interpolated values
714 */
715 PetscErrorCode DMInterpolationEvaluate(DMInterpolationInfo ctx, DM dm, Vec x, Vec v)
716 {
717   PetscInt       dim, coneSize, n;
718   PetscErrorCode ierr;
719 
720   PetscFunctionBegin;
721   PetscValidHeaderSpecific(dm, DM_CLASSID, 2);
722   PetscValidHeaderSpecific(x, VEC_CLASSID, 3);
723   PetscValidHeaderSpecific(v, VEC_CLASSID, 4);
724   ierr = VecGetLocalSize(v, &n);CHKERRQ(ierr);
725   if (n != ctx->n*ctx->dof) SETERRQ2(ctx->comm, PETSC_ERR_ARG_SIZ, "Invalid input vector size %d should be %d", n, ctx->n*ctx->dof);
726   if (n) {
727     ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
728     ierr = DMPlexGetConeSize(dm, ctx->cells[0], &coneSize);CHKERRQ(ierr);
729     if (dim == 2) {
730       if (coneSize == 3) {
731         ierr = DMInterpolate_Triangle_Private(ctx, dm, x, v);CHKERRQ(ierr);
732       } else if (coneSize == 4) {
733         ierr = DMInterpolate_Quad_Private(ctx, dm, x, v);CHKERRQ(ierr);
734       } else SETERRQ1(ctx->comm, PETSC_ERR_ARG_OUTOFRANGE, "Unsupported dimension %d for point interpolation", dim);
735     } else if (dim == 3) {
736       if (coneSize == 4) {
737         ierr = DMInterpolate_Tetrahedron_Private(ctx, dm, x, v);CHKERRQ(ierr);
738       } else {
739         ierr = DMInterpolate_Hex_Private(ctx, dm, x, v);CHKERRQ(ierr);
740       }
741     } else SETERRQ1(ctx->comm, PETSC_ERR_ARG_OUTOFRANGE, "Unsupported dimension %d for point interpolation", dim);
742   }
743   PetscFunctionReturn(0);
744 }
745 
746 PetscErrorCode DMInterpolationDestroy(DMInterpolationInfo *ctx)
747 {
748   PetscErrorCode ierr;
749 
750   PetscFunctionBegin;
751   PetscValidPointer(ctx, 2);
752   ierr = VecDestroy(&(*ctx)->coords);CHKERRQ(ierr);
753   ierr = PetscFree((*ctx)->points);CHKERRQ(ierr);
754   ierr = PetscFree((*ctx)->cells);CHKERRQ(ierr);
755   ierr = PetscFree(*ctx);CHKERRQ(ierr);
756   *ctx = NULL;
757   PetscFunctionReturn(0);
758 }
759 
760 /*@C
761   SNESMonitorFields - Monitors the residual for each field separately
762 
763   Collective on SNES
764 
765   Input Parameters:
766 + snes   - the SNES context
767 . its    - iteration number
768 . fgnorm - 2-norm of residual
769 - vf  - PetscViewerAndFormat of type ASCII
770 
771   Notes:
772   This routine prints the residual norm at each iteration.
773 
774   Level: intermediate
775 
776 .keywords: SNES, nonlinear, default, monitor, norm
777 .seealso: SNESMonitorSet(), SNESMonitorDefault()
778 @*/
779 PetscErrorCode SNESMonitorFields(SNES snes, PetscInt its, PetscReal fgnorm, PetscViewerAndFormat *vf)
780 {
781   PetscViewer        viewer = vf->viewer;
782   Vec                res;
783   DM                 dm;
784   PetscSection       s;
785   const PetscScalar *r;
786   PetscReal         *lnorms, *norms;
787   PetscInt           numFields, f, pStart, pEnd, p;
788   PetscErrorCode     ierr;
789 
790   PetscFunctionBegin;
791   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,4);
792   ierr = SNESGetFunction(snes, &res, 0, 0);CHKERRQ(ierr);
793   ierr = SNESGetDM(snes, &dm);CHKERRQ(ierr);
794   ierr = DMGetDefaultSection(dm, &s);CHKERRQ(ierr);
795   ierr = PetscSectionGetNumFields(s, &numFields);CHKERRQ(ierr);
796   ierr = PetscSectionGetChart(s, &pStart, &pEnd);CHKERRQ(ierr);
797   ierr = PetscCalloc2(numFields, &lnorms, numFields, &norms);CHKERRQ(ierr);
798   ierr = VecGetArrayRead(res, &r);CHKERRQ(ierr);
799   for (p = pStart; p < pEnd; ++p) {
800     for (f = 0; f < numFields; ++f) {
801       PetscInt fdof, foff, d;
802 
803       ierr = PetscSectionGetFieldDof(s, p, f, &fdof);CHKERRQ(ierr);
804       ierr = PetscSectionGetFieldOffset(s, p, f, &foff);CHKERRQ(ierr);
805       for (d = 0; d < fdof; ++d) lnorms[f] += PetscRealPart(PetscSqr(r[foff+d]));
806     }
807   }
808   ierr = VecRestoreArrayRead(res, &r);CHKERRQ(ierr);
809   ierr = MPIU_Allreduce(lnorms, norms, numFields, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject) dm));CHKERRQ(ierr);
810   ierr = PetscViewerPushFormat(viewer,vf->format);CHKERRQ(ierr);
811   ierr = PetscViewerASCIIAddTab(viewer, ((PetscObject) snes)->tablevel);CHKERRQ(ierr);
812   ierr = PetscViewerASCIIPrintf(viewer, "%3D SNES Function norm %14.12e [", its, (double) fgnorm);CHKERRQ(ierr);
813   for (f = 0; f < numFields; ++f) {
814     if (f > 0) {ierr = PetscViewerASCIIPrintf(viewer, ", ");CHKERRQ(ierr);}
815     ierr = PetscViewerASCIIPrintf(viewer, "%14.12e", (double) PetscSqrtReal(norms[f]));CHKERRQ(ierr);
816   }
817   ierr = PetscViewerASCIIPrintf(viewer, "]\n");CHKERRQ(ierr);
818   ierr = PetscViewerASCIISubtractTab(viewer, ((PetscObject) snes)->tablevel);CHKERRQ(ierr);
819   ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr);
820   ierr = PetscFree2(lnorms, norms);CHKERRQ(ierr);
821   PetscFunctionReturn(0);
822 }
823 
824 /********************* Residual Computation **************************/
825 
826 /*@
827   DMPlexSNESGetGeometryFEM - Return precomputed geometric data
828 
829   Input Parameter:
830 . dm - The DM
831 
832   Output Parameters:
833 . cellgeom - The values precomputed from cell geometry
834 
835   Level: developer
836 
837 .seealso: DMPlexSNESSetFunctionLocal()
838 @*/
839 PetscErrorCode DMPlexSNESGetGeometryFEM(DM dm, Vec *cellgeom)
840 {
841   DMSNES         dmsnes;
842   PetscObject    obj;
843   PetscErrorCode ierr;
844 
845   PetscFunctionBegin;
846   PetscValidHeaderSpecific(dm,DM_CLASSID,1);
847   ierr = DMGetDMSNES(dm, &dmsnes);CHKERRQ(ierr);
848   ierr = PetscObjectQuery((PetscObject) dmsnes, "DMPlexSNES_cellgeom_fem", &obj);CHKERRQ(ierr);
849   if (!obj) {
850     Vec cellgeom;
851 
852     ierr = DMPlexComputeGeometryFEM(dm, &cellgeom);CHKERRQ(ierr);
853     ierr = PetscObjectCompose((PetscObject) dmsnes, "DMPlexSNES_cellgeom_fem", (PetscObject) cellgeom);CHKERRQ(ierr);
854     ierr = VecDestroy(&cellgeom);CHKERRQ(ierr);
855   }
856   if (cellgeom) {PetscValidPointer(cellgeom, 3); ierr = PetscObjectQuery((PetscObject) dmsnes, "DMPlexSNES_cellgeom_fem", (PetscObject *) cellgeom);CHKERRQ(ierr);}
857   PetscFunctionReturn(0);
858 }
859 
860 /*@
861   DMPlexSNESGetGeometryFVM - Return precomputed geometric data
862 
863   Input Parameter:
864 . dm - The DM
865 
866   Output Parameters:
867 + facegeom - The values precomputed from face geometry
868 . cellgeom - The values precomputed from cell geometry
869 - minRadius - The minimum radius over the mesh of an inscribed sphere in a cell
870 
871   Level: developer
872 
873 .seealso: DMPlexTSSetRHSFunctionLocal()
874 @*/
875 PetscErrorCode DMPlexSNESGetGeometryFVM(DM dm, Vec *facegeom, Vec *cellgeom, PetscReal *minRadius)
876 {
877   DM             plex;
878   PetscErrorCode ierr;
879 
880   PetscFunctionBegin;
881   PetscValidHeaderSpecific(dm,DM_CLASSID,1);
882   ierr = DMSNESConvertPlex(dm,&plex,PETSC_TRUE);CHKERRQ(ierr);
883   ierr = DMPlexGetDataFVM(plex, NULL, cellgeom, facegeom, NULL);CHKERRQ(ierr);
884   if (minRadius) {ierr = DMPlexGetMinRadius(plex, minRadius);CHKERRQ(ierr);}
885   ierr = DMDestroy(&plex);CHKERRQ(ierr);
886   PetscFunctionReturn(0);
887 }
888 
889 /*@
890   DMPlexSNESGetGradientDM - Return gradient data layout
891 
892   Input Parameters:
893 + dm - The DM
894 - fv - The PetscFV
895 
896   Output Parameter:
897 . dmGrad - The layout for gradient values
898 
899   Level: developer
900 
901 .seealso: DMPlexSNESGetGeometryFVM()
902 @*/
903 PetscErrorCode DMPlexSNESGetGradientDM(DM dm, PetscFV fv, DM *dmGrad)
904 {
905   DM             plex;
906   PetscBool      computeGradients;
907   PetscErrorCode ierr;
908 
909   PetscFunctionBegin;
910   PetscValidHeaderSpecific(dm,DM_CLASSID,1);
911   PetscValidHeaderSpecific(fv,PETSCFV_CLASSID,2);
912   PetscValidPointer(dmGrad,3);
913   ierr = PetscFVGetComputeGradients(fv, &computeGradients);CHKERRQ(ierr);
914   if (!computeGradients) {*dmGrad = NULL; PetscFunctionReturn(0);}
915   ierr = DMSNESConvertPlex(dm,&plex,PETSC_TRUE);CHKERRQ(ierr);
916   ierr = DMPlexGetDataFVM(plex, fv, NULL, NULL, dmGrad);CHKERRQ(ierr);
917   ierr = DMDestroy(&plex);CHKERRQ(ierr);
918   PetscFunctionReturn(0);
919 }
920 
921 /*@C
922   DMPlexGetCellFields - Retrieve the field values values for a chunk of cells
923 
924   Input Parameters:
925 + dm     - The DM
926 . cStart - The first cell to include
927 . cEnd   - The first cell to exclude
928 . locX   - A local vector with the solution fields
929 . locX_t - A local vector with solution field time derivatives, or NULL
930 - locA   - A local vector with auxiliary fields, or NULL
931 
932   Output Parameters:
933 + u   - The field coefficients
934 . u_t - The fields derivative coefficients
935 - a   - The auxiliary field coefficients
936 
937   Level: developer
938 
939 .seealso: DMPlexGetFaceFields()
940 @*/
941 PetscErrorCode DMPlexGetCellFields(DM dm, PetscInt cStart, PetscInt cEnd, Vec locX, Vec locX_t, Vec locA, PetscScalar **u, PetscScalar **u_t, PetscScalar **a)
942 {
943   DM             dmAux;
944   PetscSection   section, sectionAux;
945   PetscDS        prob;
946   PetscInt       numCells = cEnd - cStart, totDim, totDimAux, c;
947   PetscErrorCode ierr;
948 
949   PetscFunctionBegin;
950   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
951   PetscValidHeaderSpecific(locX, VEC_CLASSID, 4);
952   if (locX_t) {PetscValidHeaderSpecific(locX_t, VEC_CLASSID, 5);}
953   if (locA)   {PetscValidHeaderSpecific(locA, VEC_CLASSID, 6);}
954   PetscValidPointer(u, 7);
955   PetscValidPointer(u_t, 8);
956   PetscValidPointer(a, 9);
957   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
958   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
959   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
960   if (locA) {
961     PetscDS probAux;
962 
963     ierr = VecGetDM(locA, &dmAux);CHKERRQ(ierr);
964     ierr = DMGetDefaultSection(dmAux, &sectionAux);CHKERRQ(ierr);
965     ierr = DMGetDS(dmAux, &probAux);CHKERRQ(ierr);
966     ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);
967   }
968   ierr = DMGetWorkArray(dm, numCells*totDim, PETSC_SCALAR, u);CHKERRQ(ierr);
969   if (locX_t) {ierr = DMGetWorkArray(dm, numCells*totDim, PETSC_SCALAR, u_t);CHKERRQ(ierr);} else {*u_t = NULL;}
970   if (locA)   {ierr = DMGetWorkArray(dm, numCells*totDimAux, PETSC_SCALAR, a);CHKERRQ(ierr);} else {*a = NULL;}
971   for (c = cStart; c < cEnd; ++c) {
972     PetscScalar *x = NULL, *x_t = NULL, *ul = *u, *ul_t = *u_t, *al = *a;
973     PetscInt     i;
974 
975     ierr = DMPlexVecGetClosure(dm, section, locX, c, NULL, &x);CHKERRQ(ierr);
976     for (i = 0; i < totDim; ++i) ul[(c-cStart)*totDim+i] = x[i];
977     ierr = DMPlexVecRestoreClosure(dm, section, locX, c, NULL, &x);CHKERRQ(ierr);
978     if (locX_t) {
979       ierr = DMPlexVecGetClosure(dm, section, locX_t, c, NULL, &x_t);CHKERRQ(ierr);
980       for (i = 0; i < totDim; ++i) ul_t[(c-cStart)*totDim+i] = x_t[i];
981       ierr = DMPlexVecRestoreClosure(dm, section, locX_t, c, NULL, &x_t);CHKERRQ(ierr);
982     }
983     if (locA) {
984       DM dmAuxPlex;
985 
986       ierr = DMSNESConvertPlex(dmAux, &dmAuxPlex, PETSC_FALSE);CHKERRQ(ierr);
987       ierr = DMPlexVecGetClosure(dmAuxPlex, sectionAux, locA, c, NULL, &x);CHKERRQ(ierr);
988       for (i = 0; i < totDimAux; ++i) al[(c-cStart)*totDimAux+i] = x[i];
989       ierr = DMPlexVecRestoreClosure(dmAuxPlex, sectionAux, locA, c, NULL, &x);CHKERRQ(ierr);
990       ierr = DMDestroy(&dmAuxPlex);CHKERRQ(ierr);
991     }
992   }
993   PetscFunctionReturn(0);
994 }
995 
996 /*@C
997   DMPlexRestoreCellFields - Restore the field values values for a chunk of cells
998 
999   Input Parameters:
1000 + dm     - The DM
1001 . cStart - The first cell to include
1002 . cEnd   - The first cell to exclude
1003 . locX   - A local vector with the solution fields
1004 . locX_t - A local vector with solution field time derivatives, or NULL
1005 - locA   - A local vector with auxiliary fields, or NULL
1006 
1007   Output Parameters:
1008 + u   - The field coefficients
1009 . u_t - The fields derivative coefficients
1010 - a   - The auxiliary field coefficients
1011 
1012   Level: developer
1013 
1014 .seealso: DMPlexGetFaceFields()
1015 @*/
1016 PetscErrorCode DMPlexRestoreCellFields(DM dm, PetscInt cStart, PetscInt cEnd, Vec locX, Vec locX_t, Vec locA, PetscScalar **u, PetscScalar **u_t, PetscScalar **a)
1017 {
1018   PetscErrorCode ierr;
1019 
1020   PetscFunctionBegin;
1021   ierr = DMRestoreWorkArray(dm, 0, PETSC_SCALAR, u);CHKERRQ(ierr);
1022   if (*u_t) {ierr = DMRestoreWorkArray(dm, 0, PETSC_SCALAR, u_t);CHKERRQ(ierr);}
1023   if (*a)   {ierr = DMRestoreWorkArray(dm, 0, PETSC_SCALAR, a);CHKERRQ(ierr);}
1024   PetscFunctionReturn(0);
1025 }
1026 
1027 /*@C
1028   DMPlexGetFaceFields - Retrieve the field values values for a chunk of faces
1029 
1030   Input Parameters:
1031 + dm     - The DM
1032 . fStart - The first face to include
1033 . fEnd   - The first face to exclude
1034 . locX   - A local vector with the solution fields
1035 . locX_t - A local vector with solution field time derivatives, or NULL
1036 . faceGeometry - A local vector with face geometry
1037 . cellGeometry - A local vector with cell geometry
1038 - locaGrad - A local vector with field gradients, or NULL
1039 
1040   Output Parameters:
1041 + Nface - The number of faces with field values
1042 . uL - The field values at the left side of the face
1043 - uR - The field values at the right side of the face
1044 
1045   Level: developer
1046 
1047 .seealso: DMPlexGetCellFields()
1048 @*/
1049 PetscErrorCode DMPlexGetFaceFields(DM dm, PetscInt fStart, PetscInt fEnd, Vec locX, Vec locX_t, Vec faceGeometry, Vec cellGeometry, Vec locGrad, PetscInt *Nface, PetscScalar **uL, PetscScalar **uR)
1050 {
1051   DM                 dmFace, dmCell, dmGrad = NULL;
1052   PetscSection       section;
1053   PetscDS            prob;
1054   DMLabel            ghostLabel;
1055   const PetscScalar *facegeom, *cellgeom, *x, *lgrad;
1056   PetscBool         *isFE;
1057   PetscInt           dim, Nf, f, Nc, numFaces = fEnd - fStart, iface, face;
1058   PetscErrorCode     ierr;
1059 
1060   PetscFunctionBegin;
1061   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
1062   PetscValidHeaderSpecific(locX, VEC_CLASSID, 4);
1063   if (locX_t) {PetscValidHeaderSpecific(locX_t, VEC_CLASSID, 5);}
1064   PetscValidHeaderSpecific(faceGeometry, VEC_CLASSID, 6);
1065   PetscValidHeaderSpecific(cellGeometry, VEC_CLASSID, 7);
1066   if (locGrad) {PetscValidHeaderSpecific(locGrad, VEC_CLASSID, 8);}
1067   PetscValidPointer(uL, 9);
1068   PetscValidPointer(uR, 10);
1069   ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
1070   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
1071   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
1072   ierr = PetscDSGetNumFields(prob, &Nf);CHKERRQ(ierr);
1073   ierr = PetscDSGetTotalComponents(prob, &Nc);CHKERRQ(ierr);
1074   ierr = PetscMalloc1(Nf, &isFE);CHKERRQ(ierr);
1075   for (f = 0; f < Nf; ++f) {
1076     PetscObject  obj;
1077     PetscClassId id;
1078 
1079     ierr = PetscDSGetDiscretization(prob, f, &obj);CHKERRQ(ierr);
1080     ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
1081     if (id == PETSCFE_CLASSID)      {isFE[f] = PETSC_TRUE;}
1082     else if (id == PETSCFV_CLASSID) {isFE[f] = PETSC_FALSE;}
1083     else                            {isFE[f] = PETSC_FALSE;}
1084   }
1085   ierr = DMGetLabel(dm, "ghost", &ghostLabel);CHKERRQ(ierr);
1086   ierr = VecGetArrayRead(locX, &x);CHKERRQ(ierr);
1087   ierr = VecGetDM(faceGeometry, &dmFace);CHKERRQ(ierr);
1088   ierr = VecGetArrayRead(faceGeometry, &facegeom);CHKERRQ(ierr);
1089   ierr = VecGetDM(cellGeometry, &dmCell);CHKERRQ(ierr);
1090   ierr = VecGetArrayRead(cellGeometry, &cellgeom);CHKERRQ(ierr);
1091   if (locGrad) {
1092     ierr = VecGetDM(locGrad, &dmGrad);CHKERRQ(ierr);
1093     ierr = VecGetArrayRead(locGrad, &lgrad);CHKERRQ(ierr);
1094   }
1095   ierr = DMGetWorkArray(dm, numFaces*Nc, PETSC_SCALAR, uL);CHKERRQ(ierr);
1096   ierr = DMGetWorkArray(dm, numFaces*Nc, PETSC_SCALAR, uR);CHKERRQ(ierr);
1097   /* Right now just eat the extra work for FE (could make a cell loop) */
1098   for (face = fStart, iface = 0; face < fEnd; ++face) {
1099     const PetscInt        *cells;
1100     PetscFVFaceGeom       *fg;
1101     PetscFVCellGeom       *cgL, *cgR;
1102     PetscScalar           *xL, *xR, *gL, *gR;
1103     PetscScalar           *uLl = *uL, *uRl = *uR;
1104     PetscInt               ghost, nsupp, nchild;
1105 
1106     ierr = DMLabelGetValue(ghostLabel, face, &ghost);CHKERRQ(ierr);
1107     ierr = DMPlexGetSupportSize(dm, face, &nsupp);CHKERRQ(ierr);
1108     ierr = DMPlexGetTreeChildren(dm, face, &nchild, NULL);CHKERRQ(ierr);
1109     if (ghost >= 0 || nsupp > 2 || nchild > 0) continue;
1110     ierr = DMPlexPointLocalRead(dmFace, face, facegeom, &fg);CHKERRQ(ierr);
1111     ierr = DMPlexGetSupport(dm, face, &cells);CHKERRQ(ierr);
1112     ierr = DMPlexPointLocalRead(dmCell, cells[0], cellgeom, &cgL);CHKERRQ(ierr);
1113     ierr = DMPlexPointLocalRead(dmCell, cells[1], cellgeom, &cgR);CHKERRQ(ierr);
1114     for (f = 0; f < Nf; ++f) {
1115       PetscInt off;
1116 
1117       ierr = PetscDSGetComponentOffset(prob, f, &off);CHKERRQ(ierr);
1118       if (isFE[f]) {
1119         const PetscInt *cone;
1120         PetscInt        comp, coneSizeL, coneSizeR, faceLocL, faceLocR, ldof, rdof, d;
1121 
1122         xL = xR = NULL;
1123         ierr = PetscSectionGetFieldComponents(section, f, &comp);CHKERRQ(ierr);
1124         ierr = DMPlexVecGetClosure(dm, section, locX, cells[0], &ldof, (PetscScalar **) &xL);CHKERRQ(ierr);
1125         ierr = DMPlexVecGetClosure(dm, section, locX, cells[1], &rdof, (PetscScalar **) &xR);CHKERRQ(ierr);
1126         ierr = DMPlexGetCone(dm, cells[0], &cone);CHKERRQ(ierr);
1127         ierr = DMPlexGetConeSize(dm, cells[0], &coneSizeL);CHKERRQ(ierr);
1128         for (faceLocL = 0; faceLocL < coneSizeL; ++faceLocL) if (cone[faceLocL] == face) break;
1129         ierr = DMPlexGetCone(dm, cells[1], &cone);CHKERRQ(ierr);
1130         ierr = DMPlexGetConeSize(dm, cells[1], &coneSizeR);CHKERRQ(ierr);
1131         for (faceLocR = 0; faceLocR < coneSizeR; ++faceLocR) if (cone[faceLocR] == face) break;
1132         if (faceLocL == coneSizeL && faceLocR == coneSizeR) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Could not find face %d in cone of cell %d or cell %d", face, cells[0], cells[1]);
1133         /* Check that FEM field has values in the right cell (sometimes its an FV ghost cell) */
1134         /* TODO: this is a hack that might not be right for nonconforming */
1135         if (faceLocL < coneSizeL) {
1136           ierr = EvaluateFaceFields(prob, f, faceLocL, xL, &uLl[iface*Nc+off]);CHKERRQ(ierr);
1137           if (rdof == ldof && faceLocR < coneSizeR) {ierr = EvaluateFaceFields(prob, f, faceLocR, xR, &uRl[iface*Nc+off]);CHKERRQ(ierr);}
1138           else              {for(d = 0; d < comp; ++d) uRl[iface*Nc+off+d] = uLl[iface*Nc+off+d];}
1139         }
1140         else {
1141           ierr = EvaluateFaceFields(prob, f, faceLocR, xR, &uRl[iface*Nc+off]);CHKERRQ(ierr);
1142           ierr = PetscSectionGetFieldComponents(section, f, &comp);CHKERRQ(ierr);
1143           for(d = 0; d < comp; ++d) uLl[iface*Nc+off+d] = uRl[iface*Nc+off+d];
1144         }
1145         ierr = DMPlexVecRestoreClosure(dm, section, locX, cells[0], &ldof, (PetscScalar **) &xL);CHKERRQ(ierr);
1146         ierr = DMPlexVecRestoreClosure(dm, section, locX, cells[1], &rdof, (PetscScalar **) &xR);CHKERRQ(ierr);
1147       } else {
1148         PetscFV  fv;
1149         PetscInt numComp, c;
1150 
1151         ierr = PetscDSGetDiscretization(prob, f, (PetscObject *) &fv);CHKERRQ(ierr);
1152         ierr = PetscFVGetNumComponents(fv, &numComp);CHKERRQ(ierr);
1153         ierr = DMPlexPointLocalFieldRead(dm, cells[0], f, x, &xL);CHKERRQ(ierr);
1154         ierr = DMPlexPointLocalFieldRead(dm, cells[1], f, x, &xR);CHKERRQ(ierr);
1155         if (dmGrad) {
1156           PetscReal dxL[3], dxR[3];
1157 
1158           ierr = DMPlexPointLocalRead(dmGrad, cells[0], lgrad, &gL);CHKERRQ(ierr);
1159           ierr = DMPlexPointLocalRead(dmGrad, cells[1], lgrad, &gR);CHKERRQ(ierr);
1160           DMPlex_WaxpyD_Internal(dim, -1, cgL->centroid, fg->centroid, dxL);
1161           DMPlex_WaxpyD_Internal(dim, -1, cgR->centroid, fg->centroid, dxR);
1162           for (c = 0; c < numComp; ++c) {
1163             uLl[iface*Nc+off+c] = xL[c] + DMPlex_DotD_Internal(dim, &gL[c*dim], dxL);
1164             uRl[iface*Nc+off+c] = xR[c] + DMPlex_DotD_Internal(dim, &gR[c*dim], dxR);
1165           }
1166         } else {
1167           for (c = 0; c < numComp; ++c) {
1168             uLl[iface*Nc+off+c] = xL[c];
1169             uRl[iface*Nc+off+c] = xR[c];
1170           }
1171         }
1172       }
1173     }
1174     ++iface;
1175   }
1176   *Nface = iface;
1177   ierr = VecRestoreArrayRead(locX, &x);CHKERRQ(ierr);
1178   ierr = VecRestoreArrayRead(faceGeometry, &facegeom);CHKERRQ(ierr);
1179   ierr = VecRestoreArrayRead(cellGeometry, &cellgeom);CHKERRQ(ierr);
1180   if (locGrad) {
1181     ierr = VecRestoreArrayRead(locGrad, &lgrad);CHKERRQ(ierr);
1182   }
1183   ierr = PetscFree(isFE);CHKERRQ(ierr);
1184   PetscFunctionReturn(0);
1185 }
1186 
1187 /*@C
1188   DMPlexRestoreFaceFields - Restore the field values values for a chunk of faces
1189 
1190   Input Parameters:
1191 + dm     - The DM
1192 . fStart - The first face to include
1193 . fEnd   - The first face to exclude
1194 . locX   - A local vector with the solution fields
1195 . locX_t - A local vector with solution field time derivatives, or NULL
1196 . faceGeometry - A local vector with face geometry
1197 . cellGeometry - A local vector with cell geometry
1198 - locaGrad - A local vector with field gradients, or NULL
1199 
1200   Output Parameters:
1201 + Nface - The number of faces with field values
1202 . uL - The field values at the left side of the face
1203 - uR - The field values at the right side of the face
1204 
1205   Level: developer
1206 
1207 .seealso: DMPlexGetFaceFields()
1208 @*/
1209 PetscErrorCode DMPlexRestoreFaceFields(DM dm, PetscInt fStart, PetscInt fEnd, Vec locX, Vec locX_t, Vec faceGeometry, Vec cellGeometry, Vec locGrad, PetscInt *Nface, PetscScalar **uL, PetscScalar **uR)
1210 {
1211   PetscErrorCode ierr;
1212 
1213   PetscFunctionBegin;
1214   ierr = DMRestoreWorkArray(dm, 0, PETSC_SCALAR, uL);CHKERRQ(ierr);
1215   ierr = DMRestoreWorkArray(dm, 0, PETSC_SCALAR, uR);CHKERRQ(ierr);
1216   PetscFunctionReturn(0);
1217 }
1218 
1219 /*@C
1220   DMPlexGetFaceGeometry - Retrieve the geometric values for a chunk of faces
1221 
1222   Input Parameters:
1223 + dm     - The DM
1224 . fStart - The first face to include
1225 . fEnd   - The first face to exclude
1226 . faceGeometry - A local vector with face geometry
1227 - cellGeometry - A local vector with cell geometry
1228 
1229   Output Parameters:
1230 + Nface - The number of faces with field values
1231 . fgeom - The extract the face centroid and normal
1232 - vol   - The cell volume
1233 
1234   Level: developer
1235 
1236 .seealso: DMPlexGetCellFields()
1237 @*/
1238 PetscErrorCode DMPlexGetFaceGeometry(DM dm, PetscInt fStart, PetscInt fEnd, Vec faceGeometry, Vec cellGeometry, PetscInt *Nface, PetscFVFaceGeom **fgeom, PetscReal **vol)
1239 {
1240   DM                 dmFace, dmCell;
1241   DMLabel            ghostLabel;
1242   const PetscScalar *facegeom, *cellgeom;
1243   PetscInt           dim, numFaces = fEnd - fStart, iface, face;
1244   PetscErrorCode     ierr;
1245 
1246   PetscFunctionBegin;
1247   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
1248   PetscValidHeaderSpecific(faceGeometry, VEC_CLASSID, 4);
1249   PetscValidHeaderSpecific(cellGeometry, VEC_CLASSID, 5);
1250   PetscValidPointer(fgeom, 6);
1251   PetscValidPointer(vol, 7);
1252   ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
1253   ierr = DMGetLabel(dm, "ghost", &ghostLabel);CHKERRQ(ierr);
1254   ierr = VecGetDM(faceGeometry, &dmFace);CHKERRQ(ierr);
1255   ierr = VecGetArrayRead(faceGeometry, &facegeom);CHKERRQ(ierr);
1256   ierr = VecGetDM(cellGeometry, &dmCell);CHKERRQ(ierr);
1257   ierr = VecGetArrayRead(cellGeometry, &cellgeom);CHKERRQ(ierr);
1258   ierr = PetscMalloc1(numFaces, fgeom);CHKERRQ(ierr);
1259   ierr = DMGetWorkArray(dm, numFaces*2, PETSC_SCALAR, vol);CHKERRQ(ierr);
1260   for (face = fStart, iface = 0; face < fEnd; ++face) {
1261     const PetscInt        *cells;
1262     PetscFVFaceGeom       *fg;
1263     PetscFVCellGeom       *cgL, *cgR;
1264     PetscFVFaceGeom       *fgeoml = *fgeom;
1265     PetscReal             *voll   = *vol;
1266     PetscInt               ghost, d, nchild, nsupp;
1267 
1268     ierr = DMLabelGetValue(ghostLabel, face, &ghost);CHKERRQ(ierr);
1269     ierr = DMPlexGetSupportSize(dm, face, &nsupp);CHKERRQ(ierr);
1270     ierr = DMPlexGetTreeChildren(dm, face, &nchild, NULL);CHKERRQ(ierr);
1271     if (ghost >= 0 || nsupp > 2 || nchild > 0) continue;
1272     ierr = DMPlexPointLocalRead(dmFace, face, facegeom, &fg);CHKERRQ(ierr);
1273     ierr = DMPlexGetSupport(dm, face, &cells);CHKERRQ(ierr);
1274     ierr = DMPlexPointLocalRead(dmCell, cells[0], cellgeom, &cgL);CHKERRQ(ierr);
1275     ierr = DMPlexPointLocalRead(dmCell, cells[1], cellgeom, &cgR);CHKERRQ(ierr);
1276     for (d = 0; d < dim; ++d) {
1277       fgeoml[iface].centroid[d] = fg->centroid[d];
1278       fgeoml[iface].normal[d]   = fg->normal[d];
1279     }
1280     voll[iface*2+0] = cgL->volume;
1281     voll[iface*2+1] = cgR->volume;
1282     ++iface;
1283   }
1284   *Nface = iface;
1285   ierr = VecRestoreArrayRead(faceGeometry, &facegeom);CHKERRQ(ierr);
1286   ierr = VecRestoreArrayRead(cellGeometry, &cellgeom);CHKERRQ(ierr);
1287   PetscFunctionReturn(0);
1288 }
1289 
1290 /*@C
1291   DMPlexRestoreFaceGeometry - Restore the field values values for a chunk of faces
1292 
1293   Input Parameters:
1294 + dm     - The DM
1295 . fStart - The first face to include
1296 . fEnd   - The first face to exclude
1297 . faceGeometry - A local vector with face geometry
1298 - cellGeometry - A local vector with cell geometry
1299 
1300   Output Parameters:
1301 + Nface - The number of faces with field values
1302 . fgeom - The extract the face centroid and normal
1303 - vol   - The cell volume
1304 
1305   Level: developer
1306 
1307 .seealso: DMPlexGetFaceFields()
1308 @*/
1309 PetscErrorCode DMPlexRestoreFaceGeometry(DM dm, PetscInt fStart, PetscInt fEnd, Vec faceGeometry, Vec cellGeometry, PetscInt *Nface, PetscFVFaceGeom **fgeom, PetscReal **vol)
1310 {
1311   PetscErrorCode ierr;
1312 
1313   PetscFunctionBegin;
1314   ierr = PetscFree(*fgeom);CHKERRQ(ierr);
1315   ierr = DMRestoreWorkArray(dm, 0, PETSC_REAL, vol);CHKERRQ(ierr);
1316   PetscFunctionReturn(0);
1317 }
1318 
1319 PetscErrorCode DMPlexComputeBdResidual_Internal(DM dm, Vec locX, Vec locX_t, PetscReal t, Vec locF, void *user)
1320 {
1321   DM_Plex         *mesh = (DM_Plex *) dm->data;
1322   DM               dmAux = NULL, plex = NULL;
1323   PetscSection     section, sectionAux = NULL;
1324   PetscDS          prob, probAux = NULL;
1325   DMLabel          depth;
1326   Vec              locA = NULL;
1327   PetscFEFaceGeom *fgeom;
1328   PetscScalar     *u = NULL, *u_t = NULL, *a = NULL, *elemVec = NULL;
1329   PetscInt         dim, totDim, totDimAux, numBd, bd;
1330   PetscErrorCode   ierr;
1331 
1332   PetscFunctionBegin;
1333   ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
1334   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
1335   ierr = DMPlexGetDepthLabel(dm, &depth);CHKERRQ(ierr);
1336   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
1337   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
1338   ierr = PetscDSGetNumBoundary(prob, &numBd);CHKERRQ(ierr);
1339   ierr = PetscObjectQuery((PetscObject) dm, "A", (PetscObject *) &locA);CHKERRQ(ierr);
1340   if (locA) {
1341     ierr = VecGetDM(locA, &dmAux);CHKERRQ(ierr);
1342     ierr = DMConvert(dmAux, DMPLEX, &plex);CHKERRQ(ierr);
1343     ierr = DMGetDefaultSection(plex, &sectionAux);CHKERRQ(ierr);
1344     ierr = DMGetDS(dmAux, &probAux);CHKERRQ(ierr);
1345     ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);
1346   }
1347   for (bd = 0; bd < numBd; ++bd) {
1348     DMBoundaryConditionType type;
1349     const char             *bdLabel;
1350     DMLabel                 label;
1351     IS                      pointIS;
1352     const PetscInt         *points;
1353     const PetscInt         *values;
1354     PetscInt                field, numValues, v, numPoints, p, dep, numFaces, face;
1355     PetscObject             obj;
1356     PetscClassId            id;
1357 
1358     ierr = PetscDSGetBoundary(prob, bd, &type, NULL, &bdLabel, &field, NULL, NULL, NULL, &numValues, &values, NULL);CHKERRQ(ierr);
1359     ierr = PetscDSGetDiscretization(prob, field, &obj);CHKERRQ(ierr);
1360     ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
1361     if ((id != PETSCFE_CLASSID) || (type & DM_BC_ESSENTIAL)) continue;
1362     ierr = DMGetLabel(dm, bdLabel, &label);CHKERRQ(ierr);
1363     for (v = 0; v < numValues; ++v) {
1364       ierr = DMLabelGetStratumSize(label, values[v], &numPoints);CHKERRQ(ierr);
1365       ierr = DMLabelGetStratumIS(label, values[v], &pointIS);CHKERRQ(ierr);
1366       if (!pointIS) continue; /* No points with that id on this process */
1367       ierr = ISGetIndices(pointIS, &points);CHKERRQ(ierr);
1368       for (p = 0, numFaces = 0; p < numPoints; ++p) {
1369         ierr = DMLabelGetValue(depth, points[p], &dep);CHKERRQ(ierr);
1370         if (dep == dim-1) ++numFaces;
1371       }
1372       ierr = PetscMalloc4(numFaces*totDim,&u,locX_t ? numFaces*totDim : 0, &u_t, numFaces,&fgeom, numFaces*totDim,&elemVec);CHKERRQ(ierr);
1373       if (locA) {ierr = PetscMalloc1(numFaces*totDimAux,&a);CHKERRQ(ierr);}
1374       for (p = 0, face = 0; p < numPoints; ++p) {
1375         const PetscInt point = points[p], *support, *cone;
1376         PetscScalar   *x     = NULL;
1377         PetscReal      dummyJ[9], dummyDetJ;
1378         PetscInt       i, coneSize, faceLoc;
1379 
1380         ierr = DMLabelGetValue(depth, points[p], &dep);CHKERRQ(ierr);
1381         if (dep != dim-1) continue;
1382         ierr = DMPlexGetSupport(dm, point, &support);CHKERRQ(ierr);
1383         ierr = DMPlexComputeCellGeometryFEM(dm, support[0], NULL, NULL, dummyJ, fgeom[face].invJ[0], &dummyDetJ);CHKERRQ(ierr);
1384         ierr = DMPlexComputeCellGeometryFEM(dm, point, NULL, fgeom[face].v0, fgeom[face].J, NULL, &fgeom[face].detJ);CHKERRQ(ierr);
1385         ierr = DMPlexComputeCellGeometryFVM(dm, point, NULL, NULL, fgeom[face].n);CHKERRQ(ierr);
1386         if (fgeom[face].detJ <= 0.0) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid determinant %g for face %d", fgeom[face].detJ, point);
1387         ierr = DMPlexGetConeSize(dm, support[0], &coneSize);CHKERRQ(ierr);
1388         ierr = DMPlexGetCone(dm, support[0], &cone);CHKERRQ(ierr);
1389         for (faceLoc = 0; faceLoc < coneSize; ++faceLoc) if (cone[faceLoc] == point) break;
1390         if (faceLoc == coneSize) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Could not find face %d in cone of support[0] %d", point, support[0]);
1391         fgeom[face].face[0] = faceLoc;
1392         ierr = DMPlexVecGetClosure(dm, section, locX, support[0], NULL, &x);CHKERRQ(ierr);
1393         for (i = 0; i < totDim; ++i) u[face*totDim+i] = x[i];
1394         ierr = DMPlexVecRestoreClosure(dm, section, locX, support[0], NULL, &x);CHKERRQ(ierr);
1395         if (locX_t) {
1396           ierr = DMPlexVecGetClosure(dm, section, locX_t, support[0], NULL, &x);CHKERRQ(ierr);
1397           for (i = 0; i < totDim; ++i) u_t[face*totDim+i] = x[i];
1398           ierr = DMPlexVecRestoreClosure(dm, section, locX_t, support[0], NULL, &x);CHKERRQ(ierr);
1399         }
1400         if (locA) {
1401           ierr = DMPlexVecGetClosure(plex, sectionAux, locA, support[0], NULL, &x);CHKERRQ(ierr);
1402           for (i = 0; i < totDimAux; ++i) a[face*totDimAux+i] = x[i];
1403           ierr = DMPlexVecRestoreClosure(plex, sectionAux, locA, support[0], NULL, &x);CHKERRQ(ierr);
1404         }
1405         ++face;
1406       }
1407       ierr = PetscMemzero(elemVec, numFaces* totDim * sizeof(PetscScalar));CHKERRQ(ierr);
1408       {
1409         PetscFE         fe;
1410         PetscQuadrature q;
1411         PetscInt        numQuadPoints, Nb;
1412         /* Conforming batches */
1413         PetscInt        numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
1414         /* Remainder */
1415         PetscInt        Nr, offset;
1416 
1417         ierr = PetscDSGetDiscretization(prob, field, (PetscObject *) &fe);CHKERRQ(ierr);
1418         ierr = PetscFEGetFaceQuadrature(fe, &q);CHKERRQ(ierr);
1419         ierr = PetscFEGetDimension(fe, &Nb);CHKERRQ(ierr);
1420         ierr = PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches);CHKERRQ(ierr);
1421         ierr = PetscQuadratureGetData(q, NULL, &numQuadPoints, NULL, NULL);CHKERRQ(ierr);
1422         blockSize = Nb*numQuadPoints;
1423         batchSize = numBlocks * blockSize;
1424         ierr =  PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches);CHKERRQ(ierr);
1425         numChunks = numFaces / (numBatches*batchSize);
1426         Ne        = numChunks*numBatches*batchSize;
1427         Nr        = numFaces % (numBatches*batchSize);
1428         offset    = numFaces - Nr;
1429         ierr = PetscFEIntegrateBdResidual(fe, prob, field, Ne, fgeom, u, u_t, probAux, a, t, elemVec);CHKERRQ(ierr);
1430         ierr = PetscFEIntegrateBdResidual(fe, prob, field, Nr, &fgeom[offset], &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, a ? &a[offset*totDimAux] : NULL, t, &elemVec[offset*totDim]);CHKERRQ(ierr);
1431       }
1432       for (p = 0, face = 0; p < numPoints; ++p) {
1433         const PetscInt point = points[p], *support;
1434 
1435         ierr = DMLabelGetValue(depth, point, &dep);CHKERRQ(ierr);
1436         if (dep != dim-1) continue;
1437         if (mesh->printFEM > 1) {ierr = DMPrintCellVector(point, "BdResidual", totDim, &elemVec[face*totDim]);CHKERRQ(ierr);}
1438         ierr = DMPlexGetSupport(dm, point, &support);CHKERRQ(ierr);
1439         ierr = DMPlexVecSetClosure(dm, NULL, locF, support[0], &elemVec[face*totDim], ADD_ALL_VALUES);CHKERRQ(ierr);
1440         ++face;
1441       }
1442       ierr = ISRestoreIndices(pointIS, &points);CHKERRQ(ierr);
1443       ierr = ISDestroy(&pointIS);CHKERRQ(ierr);
1444       ierr = PetscFree4(u,u_t,fgeom,elemVec);CHKERRQ(ierr);
1445       if (locA) {ierr = PetscFree(a);CHKERRQ(ierr);}
1446     }
1447   }
1448   if (plex) {ierr = DMDestroy(&plex);CHKERRQ(ierr);}
1449   PetscFunctionReturn(0);
1450 }
1451 
1452 PetscErrorCode DMPlexComputeResidual_Internal(DM dm, PetscInt cStart, PetscInt cEnd, PetscReal time, Vec locX, Vec locX_t, PetscReal t, Vec locF, void *user)
1453 {
1454   DM_Plex          *mesh       = (DM_Plex *) dm->data;
1455   const char       *name       = "Residual";
1456   DM                dmAux      = NULL;
1457   DM                dmGrad     = NULL;
1458   DMLabel           ghostLabel = NULL;
1459   PetscDS           prob       = NULL;
1460   PetscDS           probAux    = NULL;
1461   PetscSection      section    = NULL;
1462   PetscBool         useFEM     = PETSC_FALSE;
1463   PetscBool         useFVM     = PETSC_FALSE;
1464   PetscBool         isImplicit = (locX_t || time == PETSC_MIN_REAL) ? PETSC_TRUE : PETSC_FALSE;
1465   PetscFV           fvm        = NULL;
1466   PetscFECellGeom  *cgeomFEM   = NULL;
1467   PetscScalar      *cgeomScal;
1468   PetscFVCellGeom  *cgeomFVM   = NULL;
1469   PetscFVFaceGeom  *fgeomFVM   = NULL;
1470   Vec               locA, cellGeometryFEM = NULL, cellGeometryFVM = NULL, faceGeometryFVM = NULL, grad, locGrad = NULL;
1471   PetscScalar      *u = NULL, *u_t, *a, *uL, *uR;
1472   PetscInt          Nf, f, totDim, totDimAux, numChunks, cellChunkSize, faceChunkSize, chunk, fStart, fEnd;
1473   PetscErrorCode    ierr;
1474 
1475   PetscFunctionBegin;
1476   ierr = PetscLogEventBegin(DMPLEX_ResidualFEM,dm,0,0,0);CHKERRQ(ierr);
1477   /* TODO The places where we have to use isFE are probably the member functions for the PetscDisc class */
1478   /* TODO The FVM geometry is over-manipulated. Make the precalc functions return exactly what we need */
1479   /* FEM+FVM */
1480   /* 1: Get sizes from dm and dmAux */
1481   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
1482   ierr = DMGetLabel(dm, "ghost", &ghostLabel);CHKERRQ(ierr);
1483   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
1484   ierr = PetscDSGetNumFields(prob, &Nf);CHKERRQ(ierr);
1485   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
1486   ierr = PetscObjectQuery((PetscObject) dm, "A", (PetscObject *) &locA);CHKERRQ(ierr);
1487   if (locA) {
1488     ierr = VecGetDM(locA, &dmAux);CHKERRQ(ierr);
1489     ierr = DMGetDS(dmAux, &probAux);CHKERRQ(ierr);
1490     ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);
1491   }
1492   /* 2: Get geometric data */
1493   for (f = 0; f < Nf; ++f) {
1494     PetscObject  obj;
1495     PetscClassId id;
1496     PetscBool    fimp;
1497 
1498     ierr = PetscDSGetImplicit(prob, f, &fimp);CHKERRQ(ierr);
1499     if (isImplicit != fimp) continue;
1500     ierr = PetscDSGetDiscretization(prob, f, &obj);CHKERRQ(ierr);
1501     ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
1502     if (id == PETSCFE_CLASSID) {useFEM = PETSC_TRUE;}
1503     if (id == PETSCFV_CLASSID) {useFVM = PETSC_TRUE; fvm = (PetscFV) obj;}
1504   }
1505   if (useFEM) {
1506     ierr = DMPlexSNESGetGeometryFEM(dm, &cellGeometryFEM);CHKERRQ(ierr);
1507     ierr = VecGetArray(cellGeometryFEM, &cgeomScal);CHKERRQ(ierr);
1508     if (sizeof(PetscFECellGeom) % sizeof(PetscScalar)) {
1509       DM dmCell;
1510       PetscInt c;
1511 
1512       ierr = VecGetDM(cellGeometryFEM,&dmCell);CHKERRQ(ierr);
1513       ierr = PetscMalloc1(cEnd-cStart,&cgeomFEM);CHKERRQ(ierr);
1514       for (c = 0; c < cEnd - cStart; c++) {
1515         PetscScalar *thisgeom;
1516 
1517         ierr = DMPlexPointLocalRef(dmCell, c + cStart, cgeomScal, &thisgeom);CHKERRQ(ierr);
1518         cgeomFEM[c] = *((PetscFECellGeom *) thisgeom);
1519       }
1520     }
1521     else {
1522       cgeomFEM = (PetscFECellGeom *) cgeomScal;
1523     }
1524   }
1525   if (useFVM) {
1526     ierr = DMPlexSNESGetGeometryFVM(dm, &faceGeometryFVM, &cellGeometryFVM, NULL);CHKERRQ(ierr);
1527     ierr = VecGetArrayRead(faceGeometryFVM, (const PetscScalar **) &fgeomFVM);CHKERRQ(ierr);
1528     ierr = VecGetArrayRead(cellGeometryFVM, (const PetscScalar **) &cgeomFVM);CHKERRQ(ierr);
1529     /* Reconstruct and limit cell gradients */
1530     ierr = DMPlexSNESGetGradientDM(dm, fvm, &dmGrad);CHKERRQ(ierr);
1531     if (dmGrad) {
1532       ierr = DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd);CHKERRQ(ierr);
1533       ierr = DMGetGlobalVector(dmGrad, &grad);CHKERRQ(ierr);
1534       ierr = DMPlexReconstructGradients_Internal(dm, fvm, fStart, fEnd, faceGeometryFVM, cellGeometryFVM, locX, grad);CHKERRQ(ierr);
1535       /* Communicate gradient values */
1536       ierr = DMGetLocalVector(dmGrad, &locGrad);CHKERRQ(ierr);
1537       ierr = DMGlobalToLocalBegin(dmGrad, grad, INSERT_VALUES, locGrad);CHKERRQ(ierr);
1538       ierr = DMGlobalToLocalEnd(dmGrad, grad, INSERT_VALUES, locGrad);CHKERRQ(ierr);
1539       ierr = DMRestoreGlobalVector(dmGrad, &grad);CHKERRQ(ierr);
1540     }
1541     /* Handle non-essential (e.g. outflow) boundary values */
1542     ierr = DMPlexInsertBoundaryValues(dm, PETSC_FALSE, locX, time, faceGeometryFVM, cellGeometryFVM, locGrad);CHKERRQ(ierr);
1543   }
1544   /* Loop over chunks */
1545   ierr = DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd);CHKERRQ(ierr);
1546   numChunks     = 1;
1547   cellChunkSize = (cEnd - cStart)/numChunks;
1548   faceChunkSize = (fEnd - fStart)/numChunks;
1549   for (chunk = 0; chunk < numChunks; ++chunk) {
1550     PetscScalar     *elemVec, *fluxL, *fluxR;
1551     PetscReal       *vol;
1552     PetscFVFaceGeom *fgeom;
1553     PetscInt         cS = cStart+chunk*cellChunkSize, cE = PetscMin(cS+cellChunkSize, cEnd), numCells = cE - cS, cell;
1554     PetscInt         fS = fStart+chunk*faceChunkSize, fE = PetscMin(fS+faceChunkSize, fEnd), numFaces = 0, face;
1555 
1556     /* Extract field coefficients */
1557     if (useFEM) {
1558       ierr = DMPlexGetCellFields(dm, cS, cE, locX, locX_t, locA, &u, &u_t, &a);CHKERRQ(ierr);
1559       ierr = DMGetWorkArray(dm, numCells*totDim, PETSC_SCALAR, &elemVec);CHKERRQ(ierr);
1560       ierr = PetscMemzero(elemVec, numCells*totDim * sizeof(PetscScalar));CHKERRQ(ierr);
1561     }
1562     if (useFVM) {
1563       ierr = DMPlexGetFaceFields(dm, fS, fE, locX, locX_t, faceGeometryFVM, cellGeometryFVM, locGrad, &numFaces, &uL, &uR);CHKERRQ(ierr);
1564       ierr = DMPlexGetFaceGeometry(dm, fS, fE, faceGeometryFVM, cellGeometryFVM, &numFaces, &fgeom, &vol);CHKERRQ(ierr);
1565       ierr = DMGetWorkArray(dm, numFaces*totDim, PETSC_SCALAR, &fluxL);CHKERRQ(ierr);
1566       ierr = DMGetWorkArray(dm, numFaces*totDim, PETSC_SCALAR, &fluxR);CHKERRQ(ierr);
1567       ierr = PetscMemzero(fluxL, numFaces*totDim * sizeof(PetscScalar));CHKERRQ(ierr);
1568       ierr = PetscMemzero(fluxR, numFaces*totDim * sizeof(PetscScalar));CHKERRQ(ierr);
1569     }
1570     /* TODO We will interlace both our field coefficients (u, u_t, uL, uR, etc.) and our output (elemVec, fL, fR). I think this works */
1571     /* Loop over fields */
1572     for (f = 0; f < Nf; ++f) {
1573       PetscObject  obj;
1574       PetscClassId id;
1575       PetscBool    fimp;
1576       PetscInt     numChunks, numBatches, batchSize, numBlocks, blockSize, Ne, Nr, offset;
1577 
1578       ierr = PetscDSGetImplicit(prob, f, &fimp);CHKERRQ(ierr);
1579       if (isImplicit != fimp) continue;
1580       ierr = PetscDSGetDiscretization(prob, f, &obj);CHKERRQ(ierr);
1581       ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
1582       if (id == PETSCFE_CLASSID) {
1583         PetscFE         fe = (PetscFE) obj;
1584         PetscQuadrature q;
1585         PetscInt        Nq, Nb;
1586 
1587         ierr = PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches);CHKERRQ(ierr);
1588 
1589         ierr = PetscFEGetQuadrature(fe, &q);CHKERRQ(ierr);
1590         ierr = PetscQuadratureGetData(q, NULL, &Nq, NULL, NULL);CHKERRQ(ierr);
1591         ierr = PetscFEGetDimension(fe, &Nb);CHKERRQ(ierr);
1592         blockSize = Nb*Nq;
1593         batchSize = numBlocks * blockSize;
1594         ierr =  PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches);CHKERRQ(ierr);
1595         numChunks = numCells / (numBatches*batchSize);
1596         Ne        = numChunks*numBatches*batchSize;
1597         Nr        = numCells % (numBatches*batchSize);
1598         offset    = numCells - Nr;
1599         /* Integrate FE residual to get elemVec (need fields at quadrature points) */
1600         /*   For FV, I think we use a P0 basis and the cell coefficients (for subdivided cells, we can tweak the basis tabulation to be the indicator function) */
1601         ierr = PetscFEIntegrateResidual(fe, prob, f, Ne, cgeomFEM, u, u_t, probAux, a, t, elemVec);CHKERRQ(ierr);
1602         ierr = PetscFEIntegrateResidual(fe, prob, f, Nr, &cgeomFEM[offset], &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, &elemVec[offset*totDim]);CHKERRQ(ierr);
1603       } else if (id == PETSCFV_CLASSID) {
1604         PetscFV fv = (PetscFV) obj;
1605 
1606         Ne = numFaces;
1607         /* Riemann solve over faces (need fields at face centroids) */
1608         /*   We need to evaluate FE fields at those coordinates */
1609         ierr = PetscFVIntegrateRHSFunction(fv, prob, f, Ne, fgeom, vol, uL, uR, fluxL, fluxR);CHKERRQ(ierr);
1610       } else SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %d", f);
1611     }
1612     if (sizeof(PetscFECellGeom) % sizeof(PetscScalar)) {
1613       ierr = PetscFree(cgeomFEM);CHKERRQ(ierr);
1614     }
1615     else {
1616       cgeomFEM = NULL;
1617     }
1618     if (cellGeometryFEM) {ierr = VecRestoreArray(cellGeometryFEM, &cgeomScal);CHKERRQ(ierr);}
1619     /* Loop over domain */
1620     if (useFEM) {
1621       /* Add elemVec to locX */
1622       for (cell = cS; cell < cE; ++cell) {
1623         if (mesh->printFEM > 1) {ierr = DMPrintCellVector(cell, name, totDim, &elemVec[cell*totDim]);CHKERRQ(ierr);}
1624         if (ghostLabel) {
1625           PetscInt ghostVal;
1626 
1627           ierr = DMLabelGetValue(ghostLabel,cell,&ghostVal);CHKERRQ(ierr);
1628           if (ghostVal > 0) continue;
1629         }
1630         ierr = DMPlexVecSetClosure(dm, section, locF, cell, &elemVec[cell*totDim], ADD_ALL_VALUES);CHKERRQ(ierr);
1631       }
1632     }
1633     if (useFVM) {
1634       PetscScalar *fa;
1635       PetscInt     iface;
1636 
1637       ierr = VecGetArray(locF, &fa);CHKERRQ(ierr);
1638       for (f = 0; f < Nf; ++f) {
1639         PetscFV      fv;
1640         PetscObject  obj;
1641         PetscClassId id;
1642         PetscInt     foff, pdim;
1643 
1644         ierr = PetscDSGetDiscretization(prob, f, &obj);CHKERRQ(ierr);
1645         ierr = PetscDSGetFieldOffset(prob, f, &foff);CHKERRQ(ierr);
1646         ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
1647         if (id != PETSCFV_CLASSID) continue;
1648         fv   = (PetscFV) obj;
1649         ierr = PetscFVGetNumComponents(fv, &pdim);CHKERRQ(ierr);
1650         /* Accumulate fluxes to cells */
1651         for (face = fS, iface = 0; face < fE; ++face) {
1652           const PetscInt *cells;
1653           PetscScalar    *fL = NULL, *fR = NULL;
1654           PetscInt        ghost, d, nsupp, nchild;
1655 
1656           ierr = DMLabelGetValue(ghostLabel, face, &ghost);CHKERRQ(ierr);
1657           ierr = DMPlexGetSupportSize(dm, face, &nsupp);CHKERRQ(ierr);
1658           ierr = DMPlexGetTreeChildren(dm, face, &nchild, NULL);CHKERRQ(ierr);
1659           if (ghost >= 0 || nsupp > 2 || nchild > 0) continue;
1660           ierr = DMPlexGetSupport(dm, face, &cells);CHKERRQ(ierr);
1661           ierr = DMLabelGetValue(ghostLabel,cells[0],&ghost);CHKERRQ(ierr);
1662           if (ghost <= 0) {ierr = DMPlexPointLocalFieldRef(dm, cells[0], f, fa, &fL);CHKERRQ(ierr);}
1663           ierr = DMLabelGetValue(ghostLabel,cells[1],&ghost);CHKERRQ(ierr);
1664           if (ghost <= 0) {ierr = DMPlexPointLocalFieldRef(dm, cells[1], f, fa, &fR);CHKERRQ(ierr);}
1665           for (d = 0; d < pdim; ++d) {
1666             if (fL) fL[d] -= fluxL[iface*totDim+foff+d];
1667             if (fR) fR[d] += fluxR[iface*totDim+foff+d];
1668           }
1669           ++iface;
1670         }
1671       }
1672       ierr = VecRestoreArray(locF, &fa);CHKERRQ(ierr);
1673     }
1674     /* Handle time derivative */
1675     if (locX_t) {
1676       PetscScalar *x_t, *fa;
1677 
1678       ierr = VecGetArray(locF, &fa);CHKERRQ(ierr);
1679       ierr = VecGetArray(locX_t, &x_t);CHKERRQ(ierr);
1680       for (f = 0; f < Nf; ++f) {
1681         PetscFV      fv;
1682         PetscObject  obj;
1683         PetscClassId id;
1684         PetscInt     pdim, d;
1685 
1686         ierr = PetscDSGetDiscretization(prob, f, &obj);CHKERRQ(ierr);
1687         ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
1688         if (id != PETSCFV_CLASSID) continue;
1689         fv   = (PetscFV) obj;
1690         ierr = PetscFVGetNumComponents(fv, &pdim);CHKERRQ(ierr);
1691         for (cell = cS; cell < cE; ++cell) {
1692           PetscScalar *u_t, *r;
1693 
1694           if (ghostLabel) {
1695             PetscInt ghostVal;
1696 
1697             ierr = DMLabelGetValue(ghostLabel,cell,&ghostVal);CHKERRQ(ierr);
1698             if (ghostVal > 0) continue;
1699           }
1700           ierr = DMPlexPointLocalFieldRead(dm, cell, f, x_t, &u_t);CHKERRQ(ierr);
1701           ierr = DMPlexPointLocalFieldRef(dm, cell, f, fa, &r);CHKERRQ(ierr);
1702           for (d = 0; d < pdim; ++d) r[d] += u_t[d];
1703         }
1704       }
1705       ierr = VecRestoreArray(locX_t, &x_t);CHKERRQ(ierr);
1706       ierr = VecRestoreArray(locF, &fa);CHKERRQ(ierr);
1707     }
1708     if (useFEM) {
1709       ierr = DMPlexRestoreCellFields(dm, cS, cE, locX, locX_t, locA, &u, &u_t, &a);CHKERRQ(ierr);
1710       ierr = DMRestoreWorkArray(dm, numCells*totDim, PETSC_SCALAR, &elemVec);CHKERRQ(ierr);
1711     }
1712     if (useFVM) {
1713       ierr = DMPlexRestoreFaceFields(dm, fS, fE, locX, locX_t, faceGeometryFVM, cellGeometryFVM, locGrad, &numFaces, &uL, &uR);CHKERRQ(ierr);
1714       ierr = DMPlexRestoreFaceGeometry(dm, fS, fE, faceGeometryFVM, cellGeometryFVM, &numFaces, &fgeom, &vol);CHKERRQ(ierr);
1715       ierr = DMRestoreWorkArray(dm, numFaces*totDim, PETSC_SCALAR, &fluxL);CHKERRQ(ierr);
1716       ierr = DMRestoreWorkArray(dm, numFaces*totDim, PETSC_SCALAR, &fluxR);CHKERRQ(ierr);
1717       if (dmGrad) {ierr = DMRestoreLocalVector(dmGrad, &locGrad);CHKERRQ(ierr);}
1718     }
1719   }
1720 
1721   if (useFEM) {ierr = DMPlexComputeBdResidual_Internal(dm, locX, locX_t, t, locF, user);CHKERRQ(ierr);}
1722 
1723   /* FEM */
1724   /* 1: Get sizes from dm and dmAux */
1725   /* 2: Get geometric data */
1726   /* 3: Handle boundary values */
1727   /* 4: Loop over domain */
1728   /*   Extract coefficients */
1729   /* Loop over fields */
1730   /*   Set tiling for FE*/
1731   /*   Integrate FE residual to get elemVec */
1732   /*     Loop over subdomain */
1733   /*       Loop over quad points */
1734   /*         Transform coords to real space */
1735   /*         Evaluate field and aux fields at point */
1736   /*         Evaluate residual at point */
1737   /*         Transform residual to real space */
1738   /*       Add residual to elemVec */
1739   /* Loop over domain */
1740   /*   Add elemVec to locX */
1741 
1742   /* FVM */
1743   /* Get geometric data */
1744   /* If using gradients */
1745   /*   Compute gradient data */
1746   /*   Loop over domain faces */
1747   /*     Count computational faces */
1748   /*     Reconstruct cell gradient */
1749   /*   Loop over domain cells */
1750   /*     Limit cell gradients */
1751   /* Handle boundary values */
1752   /* Loop over domain faces */
1753   /*   Read out field, centroid, normal, volume for each side of face */
1754   /* Riemann solve over faces */
1755   /* Loop over domain faces */
1756   /*   Accumulate fluxes to cells */
1757   /* TODO Change printFEM to printDisc here */
1758   if (mesh->printFEM) {
1759     Vec         locFbc;
1760     PetscInt    pStart, pEnd, p, maxDof;
1761     PetscScalar *zeroes;
1762 
1763     ierr = VecDuplicate(locF,&locFbc);CHKERRQ(ierr);
1764     ierr = VecCopy(locF,locFbc);CHKERRQ(ierr);
1765     ierr = PetscSectionGetChart(section,&pStart,&pEnd);CHKERRQ(ierr);
1766     ierr = PetscSectionGetMaxDof(section,&maxDof);CHKERRQ(ierr);
1767     ierr = PetscCalloc1(maxDof,&zeroes);CHKERRQ(ierr);
1768     for (p = pStart; p < pEnd; p++) {
1769       ierr = VecSetValuesSection(locFbc,section,p,zeroes,INSERT_BC_VALUES);CHKERRQ(ierr);
1770     }
1771     ierr = PetscFree(zeroes);CHKERRQ(ierr);
1772     ierr = DMPrintLocalVec(dm, name, mesh->printTol, locFbc);CHKERRQ(ierr);
1773     ierr = VecDestroy(&locFbc);CHKERRQ(ierr);
1774   }
1775   ierr = PetscLogEventEnd(DMPLEX_ResidualFEM,dm,0,0,0);CHKERRQ(ierr);
1776   PetscFunctionReturn(0);
1777 }
1778 
1779 static PetscErrorCode DMPlexComputeResidualFEM_Check_Internal(DM dm, Vec X, Vec X_t, PetscReal t, Vec F, void *user)
1780 {
1781   DM                dmCh, dmAux;
1782   Vec               A, cellgeom;
1783   PetscDS           prob, probCh, probAux = NULL;
1784   PetscQuadrature   q;
1785   PetscSection      section, sectionAux;
1786   PetscFECellGeom  *cgeom = NULL;
1787   PetscScalar      *cgeomScal;
1788   PetscScalar      *elemVec, *elemVecCh, *u, *u_t, *a = NULL;
1789   PetscInt          dim, Nf, f, numCells, cStart, cEnd, c;
1790   PetscInt          totDim, totDimAux = 0, diffCell = 0;
1791   PetscErrorCode    ierr;
1792 
1793   PetscFunctionBegin;
1794   ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
1795   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
1796   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
1797   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
1798   ierr = PetscSectionGetNumFields(section, &Nf);CHKERRQ(ierr);
1799   ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);
1800   numCells = cEnd - cStart;
1801   ierr = PetscObjectQuery((PetscObject) dm, "dmCh", (PetscObject *) &dmCh);CHKERRQ(ierr);
1802   ierr = DMGetDS(dmCh, &probCh);CHKERRQ(ierr);
1803   ierr = PetscObjectQuery((PetscObject) dm, "dmAux", (PetscObject *) &dmAux);CHKERRQ(ierr);
1804   ierr = PetscObjectQuery((PetscObject) dm, "A", (PetscObject *) &A);CHKERRQ(ierr);
1805   if (dmAux) {
1806     ierr = DMGetDefaultSection(dmAux, &sectionAux);CHKERRQ(ierr);
1807     ierr = DMGetDS(dmAux, &probAux);CHKERRQ(ierr);
1808     ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);
1809   }
1810   ierr = VecSet(F, 0.0);CHKERRQ(ierr);
1811   ierr = PetscMalloc3(numCells*totDim,&u,X_t ? numCells*totDim : 0,&u_t,numCells*totDim,&elemVec);CHKERRQ(ierr);
1812   ierr = PetscMalloc1(numCells*totDim,&elemVecCh);CHKERRQ(ierr);
1813   if (dmAux) {ierr = PetscMalloc1(numCells*totDimAux, &a);CHKERRQ(ierr);}
1814   ierr = DMPlexSNESGetGeometryFEM(dm, &cellgeom);CHKERRQ(ierr);
1815   ierr = VecGetArray(cellgeom, &cgeomScal);CHKERRQ(ierr);
1816   if (sizeof(PetscFECellGeom) % sizeof(PetscScalar)) {
1817     DM dmCell;
1818 
1819     ierr = VecGetDM(cellgeom,&dmCell);CHKERRQ(ierr);
1820     ierr = PetscMalloc1(cEnd-cStart,&cgeom);CHKERRQ(ierr);
1821     for (c = 0; c < cEnd - cStart; c++) {
1822       PetscScalar *thisgeom;
1823 
1824       ierr = DMPlexPointLocalRef(dmCell, c + cStart, cgeomScal, &thisgeom);CHKERRQ(ierr);
1825       cgeom[c] = *((PetscFECellGeom *) thisgeom);
1826     }
1827   }
1828   else {
1829     cgeom = (PetscFECellGeom *) cgeomScal;
1830   }
1831   for (c = cStart; c < cEnd; ++c) {
1832     PetscScalar *x = NULL, *x_t = NULL;
1833     PetscInt     i;
1834 
1835     ierr = DMPlexVecGetClosure(dm, section, X, c, NULL, &x);CHKERRQ(ierr);
1836     for (i = 0; i < totDim; ++i) u[c*totDim+i] = x[i];
1837     ierr = DMPlexVecRestoreClosure(dm, section, X, c, NULL, &x);CHKERRQ(ierr);
1838     if (X_t) {
1839       ierr = DMPlexVecGetClosure(dm, section, X_t, c, NULL, &x_t);CHKERRQ(ierr);
1840       for (i = 0; i < totDim; ++i) u_t[c*totDim+i] = x_t[i];
1841       ierr = DMPlexVecRestoreClosure(dm, section, X_t, c, NULL, &x_t);CHKERRQ(ierr);
1842     }
1843     if (dmAux) {
1844       DM dmAuxPlex;
1845 
1846       ierr = DMSNESConvertPlex(dmAux,&dmAuxPlex, PETSC_FALSE);CHKERRQ(ierr);
1847       ierr = DMPlexVecGetClosure(dmAuxPlex, sectionAux, A, c, NULL, &x);CHKERRQ(ierr);
1848       for (i = 0; i < totDimAux; ++i) a[c*totDimAux+i] = x[i];
1849       ierr = DMPlexVecRestoreClosure(dmAuxPlex, sectionAux, A, c, NULL, &x);CHKERRQ(ierr);
1850       ierr = DMDestroy(&dmAuxPlex);CHKERRQ(ierr);
1851     }
1852   }
1853   for (f = 0; f < Nf; ++f) {
1854     PetscFE  fe, feCh;
1855     PetscInt numQuadPoints, Nb;
1856     /* Conforming batches */
1857     PetscInt numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
1858     /* Remainder */
1859     PetscInt Nr, offset;
1860 
1861     ierr = PetscDSGetDiscretization(prob, f, (PetscObject *) &fe);CHKERRQ(ierr);
1862     ierr = PetscDSGetDiscretization(probCh, f, (PetscObject *) &feCh);CHKERRQ(ierr);
1863     ierr = PetscFEGetQuadrature(fe, &q);CHKERRQ(ierr);
1864     ierr = PetscFEGetDimension(fe, &Nb);CHKERRQ(ierr);
1865     ierr = PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches);CHKERRQ(ierr);
1866     ierr = PetscQuadratureGetData(q, NULL, &numQuadPoints, NULL, NULL);CHKERRQ(ierr);
1867     blockSize = Nb*numQuadPoints;
1868     batchSize = numBlocks * blockSize;
1869     ierr =  PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches);CHKERRQ(ierr);
1870     numChunks = numCells / (numBatches*batchSize);
1871     Ne        = numChunks*numBatches*batchSize;
1872     Nr        = numCells % (numBatches*batchSize);
1873     offset    = numCells - Nr;
1874     ierr = PetscFEIntegrateResidual(fe, prob, f, Ne, cgeom, u, u_t, probAux, a, t, elemVec);CHKERRQ(ierr);
1875     ierr = PetscFEIntegrateResidual(feCh, prob, f, Ne, cgeom, u, u_t, probAux, a, t, elemVecCh);CHKERRQ(ierr);
1876     ierr = PetscFEIntegrateResidual(fe, prob, f, Nr, &cgeom[offset], &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, &elemVec[offset*totDim]);CHKERRQ(ierr);
1877     ierr = PetscFEIntegrateResidual(feCh, prob, f, Nr, &cgeom[offset], &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, &elemVecCh[offset*totDim]);CHKERRQ(ierr);
1878   }
1879   for (c = cStart; c < cEnd; ++c) {
1880     PetscBool diff = PETSC_FALSE;
1881     PetscInt  d;
1882 
1883     for (d = 0; d < totDim; ++d) if (PetscAbsScalar(elemVec[c*totDim+d] - elemVecCh[c*totDim+d]) > 1.0e-7) {diff = PETSC_TRUE;break;}
1884     if (diff) {
1885       ierr = PetscPrintf(PetscObjectComm((PetscObject) dm), "Different cell %d\n", c);CHKERRQ(ierr);
1886       ierr = DMPrintCellVector(c, "Residual", totDim, &elemVec[c*totDim]);CHKERRQ(ierr);
1887       ierr = DMPrintCellVector(c, "Check Residual", totDim, &elemVecCh[c*totDim]);CHKERRQ(ierr);
1888       ++diffCell;
1889     }
1890     if (diffCell > 9) break;
1891     ierr = DMPlexVecSetClosure(dm, section, F, c, &elemVec[c*totDim], ADD_ALL_VALUES);CHKERRQ(ierr);
1892   }
1893   if (sizeof(PetscFECellGeom) % sizeof(PetscScalar)) {
1894     ierr = PetscFree(cgeom);CHKERRQ(ierr);
1895   }
1896   else {
1897     cgeom = NULL;
1898   }
1899   ierr = VecRestoreArray(cellgeom, &cgeomScal);CHKERRQ(ierr);
1900   ierr = PetscFree3(u,u_t,elemVec);CHKERRQ(ierr);
1901   ierr = PetscFree(elemVecCh);CHKERRQ(ierr);
1902   if (dmAux) {ierr = PetscFree(a);CHKERRQ(ierr);}
1903   PetscFunctionReturn(0);
1904 }
1905 
1906 /*@
1907   DMPlexSNESComputeResidualFEM - Form the local residual F from the local input X using pointwise functions specified by the user
1908 
1909   Input Parameters:
1910 + dm - The mesh
1911 . X  - Local solution
1912 - user - The user context
1913 
1914   Output Parameter:
1915 . F  - Local output vector
1916 
1917   Level: developer
1918 
1919 .seealso: DMPlexComputeJacobianActionFEM()
1920 @*/
1921 PetscErrorCode DMPlexSNESComputeResidualFEM(DM dm, Vec X, Vec F, void *user)
1922 {
1923   PetscObject    check;
1924   PetscInt       cStart, cEnd, cEndInterior;
1925   DM             plex;
1926   PetscErrorCode ierr;
1927 
1928   PetscFunctionBegin;
1929   ierr = DMSNESConvertPlex(dm,&plex,PETSC_TRUE);CHKERRQ(ierr);
1930   ierr = DMPlexGetHeightStratum(plex, 0, &cStart, &cEnd);CHKERRQ(ierr);
1931   ierr = DMPlexGetHybridBounds(plex, &cEndInterior, NULL, NULL, NULL);CHKERRQ(ierr);
1932   cEnd = cEndInterior < 0 ? cEnd : cEndInterior;
1933   /* The dmCh is used to check two mathematically equivalent discretizations for computational equivalence */
1934   ierr = PetscObjectQuery((PetscObject) plex, "dmCh", &check);CHKERRQ(ierr);
1935   if (check) {ierr = DMPlexComputeResidualFEM_Check_Internal(plex, X, NULL, 0.0, F, user);CHKERRQ(ierr);}
1936   else       {ierr = DMPlexComputeResidual_Internal(plex, cStart, cEnd, PETSC_MIN_REAL, X, NULL, 0.0, F, user);CHKERRQ(ierr);}
1937   ierr = DMDestroy(&plex);CHKERRQ(ierr);
1938   PetscFunctionReturn(0);
1939 }
1940 
1941 /*@
1942   DMPlexSNESComputeBoundaryFEM - Form the boundary values for the local input X
1943 
1944   Input Parameters:
1945 + dm - The mesh
1946 - user - The user context
1947 
1948   Output Parameter:
1949 . X  - Local solution
1950 
1951   Level: developer
1952 
1953 .seealso: DMPlexComputeJacobianActionFEM()
1954 @*/
1955 PetscErrorCode DMPlexSNESComputeBoundaryFEM(DM dm, Vec X, void *user)
1956 {
1957   DM             plex;
1958   PetscErrorCode ierr;
1959 
1960   PetscFunctionBegin;
1961   ierr = DMSNESConvertPlex(dm,&plex,PETSC_TRUE);CHKERRQ(ierr);
1962   ierr = DMPlexInsertBoundaryValues(plex, PETSC_TRUE, X, PETSC_MIN_REAL, NULL, NULL, NULL);CHKERRQ(ierr);
1963   ierr = DMDestroy(&plex);CHKERRQ(ierr);
1964   PetscFunctionReturn(0);
1965 }
1966 
1967 PetscErrorCode DMPlexComputeBdJacobian_Internal(DM dm, Vec locX, Vec locX_t, PetscReal t, PetscReal X_tShift, Mat Jac, Mat JacP, void *user)
1968 {
1969   DM_Plex         *mesh = (DM_Plex *) dm->data;
1970   DM               dmAux = NULL, plex = NULL;
1971   PetscSection     section, globalSection, subSection, sectionAux = NULL;
1972   PetscDS          prob, probAux = NULL;
1973   DMLabel          depth;
1974   Vec              locA = NULL;
1975   PetscFEFaceGeom *fgeom;
1976   PetscScalar     *u = NULL, *u_t = NULL, *a = NULL, *elemMat = NULL;
1977   PetscInt         dim, totDim, totDimAux, numBd, bd, Nf;
1978   PetscBool        isMatISP;
1979   PetscErrorCode   ierr;
1980 
1981   PetscFunctionBegin;
1982   ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
1983   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
1984   ierr = PetscObjectTypeCompare((PetscObject) JacP, MATIS, &isMatISP);CHKERRQ(ierr);
1985   ierr = DMGetDefaultGlobalSection(dm, &globalSection);CHKERRQ(ierr);
1986   if (isMatISP) {
1987     ierr = DMPlexGetSubdomainSection(dm, &subSection);CHKERRQ(ierr);
1988   }
1989   ierr = DMPlexGetDepthLabel(dm, &depth);CHKERRQ(ierr);
1990   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
1991   ierr = PetscDSGetNumFields(prob, &Nf);CHKERRQ(ierr);
1992   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
1993   ierr = PetscDSGetNumBoundary(prob, &numBd);CHKERRQ(ierr);
1994   ierr = PetscObjectQuery((PetscObject) dm, "A", (PetscObject *) &locA);CHKERRQ(ierr);
1995   if (locA) {
1996     ierr = VecGetDM(locA, &dmAux);CHKERRQ(ierr);
1997     ierr = DMConvert(dmAux, DMPLEX, &plex);CHKERRQ(ierr);
1998     ierr = DMGetDefaultSection(plex, &sectionAux);CHKERRQ(ierr);
1999     ierr = DMGetDS(dmAux, &probAux);CHKERRQ(ierr);
2000     ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);
2001   }
2002   for (bd = 0; bd < numBd; ++bd) {
2003     DMBoundaryConditionType type;
2004     const char             *bdLabel;
2005     DMLabel                 label;
2006     IS                      pointIS;
2007     const PetscInt         *points;
2008     const PetscInt         *values;
2009     PetscInt                fieldI, fieldJ, numValues, v, numPoints, p, dep, numFaces, face;
2010     PetscObject             obj;
2011     PetscClassId            id;
2012 
2013     ierr = PetscDSGetBoundary(prob, bd, &type, NULL, &bdLabel, &fieldI, NULL, NULL, NULL, &numValues, &values, NULL);CHKERRQ(ierr);
2014     ierr = PetscDSGetDiscretization(prob, fieldI, &obj);CHKERRQ(ierr);
2015     ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
2016     if ((id != PETSCFE_CLASSID) || (type & DM_BC_ESSENTIAL)) continue;
2017     ierr = DMGetLabel(dm, bdLabel, &label);CHKERRQ(ierr);
2018     for (v = 0; v < numValues; ++v) {
2019       ierr = DMLabelGetStratumSize(label, values[v], &numPoints);CHKERRQ(ierr);
2020       ierr = DMLabelGetStratumIS(label, values[v], &pointIS);CHKERRQ(ierr);
2021       if (!pointIS) continue; /* No points with that id on this process */
2022       ierr = ISGetIndices(pointIS, &points);CHKERRQ(ierr);
2023       for (p = 0, numFaces = 0; p < numPoints; ++p) {
2024         ierr = DMLabelGetValue(depth, points[p], &dep);CHKERRQ(ierr);
2025         if (dep == dim-1) ++numFaces;
2026       }
2027       ierr = PetscMalloc4(numFaces*totDim,&u,locX_t ? numFaces*totDim : 0,&u_t,numFaces,&fgeom,numFaces*totDim*totDim,&elemMat);CHKERRQ(ierr);
2028       if (locA) {ierr = PetscMalloc1(numFaces*totDimAux,&a);CHKERRQ(ierr);}
2029       for (p = 0, face = 0; p < numPoints; ++p) {
2030         const PetscInt point = points[p], *support, *cone;
2031         PetscScalar   *x     = NULL;
2032         PetscReal      dummyJ[9], dummyDetJ;
2033         PetscInt       i, coneSize, faceLoc;
2034 
2035         ierr = DMLabelGetValue(depth, points[p], &dep);CHKERRQ(ierr);
2036         if (dep != dim-1) continue;
2037         ierr = DMPlexGetSupport(dm, point, &support);CHKERRQ(ierr);
2038         ierr = DMPlexComputeCellGeometryFEM(dm, support[0], NULL, NULL, dummyJ, fgeom[face].invJ[0], &dummyDetJ);CHKERRQ(ierr);
2039         ierr = DMPlexComputeCellGeometryFEM(dm, point, NULL, fgeom[face].v0, fgeom[face].J, NULL, &fgeom[face].detJ);CHKERRQ(ierr);
2040         ierr = DMPlexComputeCellGeometryFVM(dm, point, NULL, NULL, fgeom[face].n);CHKERRQ(ierr);
2041         if (fgeom[face].detJ <= 0.0) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid determinant %g for face %d", fgeom[face].detJ, point);
2042         ierr = DMPlexGetConeSize(dm, support[0], &coneSize);CHKERRQ(ierr);
2043         ierr = DMPlexGetCone(dm, support[0], &cone);CHKERRQ(ierr);
2044         for (faceLoc = 0; faceLoc < coneSize; ++faceLoc) if (cone[faceLoc] == point) break;
2045         if (faceLoc == coneSize) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Could not find face %d in cone of support[0] %d", point, support[0]);
2046         fgeom[face].face[0] = faceLoc;
2047         ierr = DMPlexVecGetClosure(dm, section, locX, support[0], NULL, &x);CHKERRQ(ierr);
2048         for (i = 0; i < totDim; ++i) u[face*totDim+i] = x[i];
2049         ierr = DMPlexVecRestoreClosure(dm, section, locX, support[0], NULL, &x);CHKERRQ(ierr);
2050         if (locX_t) {
2051           ierr = DMPlexVecGetClosure(dm, section, locX_t, support[0], NULL, &x);CHKERRQ(ierr);
2052           for (i = 0; i < totDim; ++i) u_t[face*totDim+i] = x[i];
2053           ierr = DMPlexVecRestoreClosure(dm, section, locX_t, support[0], NULL, &x);CHKERRQ(ierr);
2054         }
2055         if (locA) {
2056           ierr = DMPlexVecGetClosure(plex, sectionAux, locA, support[0], NULL, &x);CHKERRQ(ierr);
2057           for (i = 0; i < totDimAux; ++i) a[face*totDimAux+i] = x[i];
2058           ierr = DMPlexVecRestoreClosure(plex, sectionAux, locA, support[0], NULL, &x);CHKERRQ(ierr);
2059         }
2060         ++face;
2061       }
2062       ierr = PetscMemzero(elemMat, numFaces*totDim*totDim * sizeof(PetscScalar));CHKERRQ(ierr);
2063       {
2064         PetscFE         fe;
2065         PetscQuadrature q;
2066         PetscInt        numQuadPoints, Nb;
2067         /* Conforming batches */
2068         PetscInt        numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
2069         /* Remainder */
2070         PetscInt        Nr, offset;
2071 
2072         ierr = PetscDSGetDiscretization(prob, fieldI, (PetscObject *) &fe);CHKERRQ(ierr);
2073         ierr = PetscFEGetFaceQuadrature(fe, &q);CHKERRQ(ierr);
2074         ierr = PetscFEGetDimension(fe, &Nb);CHKERRQ(ierr);
2075         ierr = PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches);CHKERRQ(ierr);
2076         ierr = PetscQuadratureGetData(q, NULL, &numQuadPoints, NULL, NULL);CHKERRQ(ierr);
2077         blockSize = Nb*numQuadPoints;
2078         batchSize = numBlocks * blockSize;
2079         ierr =  PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches);CHKERRQ(ierr);
2080         numChunks = numFaces / (numBatches*batchSize);
2081         Ne        = numChunks*numBatches*batchSize;
2082         Nr        = numFaces % (numBatches*batchSize);
2083         offset    = numFaces - Nr;
2084         for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
2085           ierr = PetscFEIntegrateBdJacobian(fe, prob, fieldI, fieldJ, Ne, fgeom, u, u_t, probAux, a, t, X_tShift, elemMat);CHKERRQ(ierr);
2086           ierr = PetscFEIntegrateBdJacobian(fe, prob, fieldI, fieldJ, Nr, &fgeom[offset], &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, a ? &a[offset*totDimAux] : NULL, t, X_tShift, &elemMat[offset*totDim*totDim]);CHKERRQ(ierr);
2087         }
2088       }
2089       for (p = 0, face = 0; p < numPoints; ++p) {
2090         const PetscInt point = points[p], *support;
2091 
2092         ierr = DMLabelGetValue(depth, point, &dep);CHKERRQ(ierr);
2093         if (dep != dim-1) continue;
2094         if (mesh->printFEM > 1) {ierr = DMPrintCellMatrix(point, "BdJacobian", totDim, totDim, &elemMat[face*totDim*totDim]);CHKERRQ(ierr);}
2095         ierr = DMPlexGetSupport(dm, point, &support);CHKERRQ(ierr);
2096         if (!isMatISP) {
2097           ierr = DMPlexMatSetClosure(dm, section, globalSection, JacP, support[0], &elemMat[face*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2098         } else {
2099           Mat lJ;
2100 
2101           ierr = MatISGetLocalMat(JacP,&lJ);CHKERRQ(ierr);
2102           ierr = DMPlexMatSetClosure(dm, section, subSection, lJ, support[0], &elemMat[face*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2103         }
2104         ++face;
2105       }
2106       ierr = ISRestoreIndices(pointIS, &points);CHKERRQ(ierr);
2107       ierr = ISDestroy(&pointIS);CHKERRQ(ierr);
2108       ierr = PetscFree4(u,u_t,fgeom,elemMat);CHKERRQ(ierr);
2109       if (locA) {ierr = PetscFree(a);CHKERRQ(ierr);}
2110     }
2111   }
2112   if (plex) {ierr = DMDestroy(&plex);CHKERRQ(ierr);}
2113   PetscFunctionReturn(0);
2114 }
2115 
2116 PetscErrorCode DMPlexComputeJacobian_Internal(DM dm, PetscInt cStart, PetscInt cEnd, PetscReal t, PetscReal X_tShift, Vec X, Vec X_t, Mat Jac, Mat JacP,void *user)
2117 {
2118   DM_Plex          *mesh  = (DM_Plex *) dm->data;
2119   const char       *name  = "Jacobian";
2120   DM                dmAux, plex;
2121   Vec               A, cellgeom;
2122   PetscDS           prob, probAux = NULL;
2123   PetscSection      section, globalSection, subSection, sectionAux;
2124   PetscFECellGeom  *cgeom = NULL;
2125   PetscScalar      *cgeomScal;
2126   PetscScalar      *elemMat, *elemMatP, *elemMatD, *u, *u_t, *a = NULL;
2127   PetscInt          dim, Nf, fieldI, fieldJ, numCells, c;
2128   PetscInt          totDim, totDimAux;
2129   PetscBool         isMatIS, isMatISP, isShell, hasJac, hasPrec, hasDyn, hasFV = PETSC_FALSE;
2130   PetscErrorCode    ierr;
2131 
2132   PetscFunctionBegin;
2133   ierr = PetscLogEventBegin(DMPLEX_JacobianFEM,dm,0,0,0);CHKERRQ(ierr);
2134   ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
2135   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
2136   ierr = PetscObjectTypeCompare((PetscObject) JacP, MATIS, &isMatISP);CHKERRQ(ierr);
2137   ierr = DMGetDefaultGlobalSection(dm, &globalSection);CHKERRQ(ierr);
2138   if (isMatISP) {
2139     ierr = DMPlexGetSubdomainSection(dm, &subSection);CHKERRQ(ierr);
2140   }
2141   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
2142   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
2143   ierr = PetscDSHasJacobian(prob, &hasJac);CHKERRQ(ierr);
2144   ierr = PetscDSHasJacobianPreconditioner(prob, &hasPrec);CHKERRQ(ierr);
2145   ierr = PetscDSHasDynamicJacobian(prob, &hasDyn);CHKERRQ(ierr);
2146   hasDyn = hasDyn && (X_tShift != 0.0) ? PETSC_TRUE : PETSC_FALSE;
2147   ierr = PetscSectionGetNumFields(section, &Nf);CHKERRQ(ierr);
2148   numCells = cEnd - cStart;
2149   ierr = PetscObjectQuery((PetscObject) dm, "dmAux", (PetscObject *) &dmAux);CHKERRQ(ierr);
2150   ierr = PetscObjectQuery((PetscObject) dm, "A", (PetscObject *) &A);CHKERRQ(ierr);
2151   if (dmAux) {
2152     ierr = DMConvert(dmAux, DMPLEX, &plex);CHKERRQ(ierr);
2153     ierr = DMGetDefaultSection(plex, &sectionAux);CHKERRQ(ierr);
2154     ierr = DMGetDS(dmAux, &probAux);CHKERRQ(ierr);
2155     ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);
2156   }
2157   if (hasJac && hasPrec) {ierr = MatZeroEntries(Jac);CHKERRQ(ierr);}
2158   ierr = MatZeroEntries(JacP);CHKERRQ(ierr);
2159   ierr = PetscMalloc5(numCells*totDim,&u,X_t ? numCells*totDim : 0,&u_t,hasJac ? numCells*totDim*totDim : 0,&elemMat,hasPrec ? numCells*totDim*totDim : 0, &elemMatP,hasDyn ? numCells*totDim*totDim : 0, &elemMatD);CHKERRQ(ierr);
2160   if (dmAux) {ierr = PetscMalloc1(numCells*totDimAux, &a);CHKERRQ(ierr);}
2161   ierr = DMPlexSNESGetGeometryFEM(dm, &cellgeom);CHKERRQ(ierr);
2162   ierr = VecGetArray(cellgeom, &cgeomScal);CHKERRQ(ierr);
2163   if (sizeof(PetscFECellGeom) % sizeof(PetscScalar)) {
2164     DM dmCell;
2165 
2166     ierr = VecGetDM(cellgeom,&dmCell);CHKERRQ(ierr);
2167     ierr = PetscMalloc1(cEnd-cStart,&cgeom);CHKERRQ(ierr);
2168     for (c = 0; c < cEnd - cStart; c++) {
2169       PetscScalar *thisgeom;
2170 
2171       ierr = DMPlexPointLocalRef(dmCell, c + cStart, cgeomScal, &thisgeom);CHKERRQ(ierr);
2172       cgeom[c] = *((PetscFECellGeom *) thisgeom);
2173     }
2174   } else {
2175     cgeom = (PetscFECellGeom *) cgeomScal;
2176   }
2177   for (c = cStart; c < cEnd; ++c) {
2178     PetscScalar *x = NULL,  *x_t = NULL;
2179     PetscInt     i;
2180 
2181     ierr = DMPlexVecGetClosure(dm, section, X, c, NULL, &x);CHKERRQ(ierr);
2182     for (i = 0; i < totDim; ++i) u[(c-cStart)*totDim+i] = x[i];
2183     ierr = DMPlexVecRestoreClosure(dm, section, X, c, NULL, &x);CHKERRQ(ierr);
2184     if (X_t) {
2185       ierr = DMPlexVecGetClosure(dm, section, X_t, c, NULL, &x_t);CHKERRQ(ierr);
2186       for (i = 0; i < totDim; ++i) u_t[(c-cStart)*totDim+i] = x_t[i];
2187       ierr = DMPlexVecRestoreClosure(dm, section, X_t, c, NULL, &x_t);CHKERRQ(ierr);
2188     }
2189     if (dmAux) {
2190       ierr = DMPlexVecGetClosure(plex, sectionAux, A, c, NULL, &x);CHKERRQ(ierr);
2191       for (i = 0; i < totDimAux; ++i) a[(c-cStart)*totDimAux+i] = x[i];
2192       ierr = DMPlexVecRestoreClosure(plex, sectionAux, A, c, NULL, &x);CHKERRQ(ierr);
2193     }
2194   }
2195   if (hasJac)  {ierr = PetscMemzero(elemMat,  numCells*totDim*totDim * sizeof(PetscScalar));CHKERRQ(ierr);}
2196   if (hasPrec) {ierr = PetscMemzero(elemMatP, numCells*totDim*totDim * sizeof(PetscScalar));CHKERRQ(ierr);}
2197   if (hasDyn)  {ierr = PetscMemzero(elemMatD, numCells*totDim*totDim * sizeof(PetscScalar));CHKERRQ(ierr);}
2198   for (fieldI = 0; fieldI < Nf; ++fieldI) {
2199     PetscClassId    id;
2200     PetscFE         fe;
2201     PetscQuadrature q;
2202     PetscInt        numQuadPoints, Nb;
2203     /* Conforming batches */
2204     PetscInt        numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
2205     /* Remainder */
2206     PetscInt        Nr, offset;
2207 
2208     ierr = PetscDSGetDiscretization(prob, fieldI, (PetscObject *) &fe);CHKERRQ(ierr);
2209     ierr = PetscObjectGetClassId((PetscObject) fe, &id);CHKERRQ(ierr);
2210     if (id == PETSCFV_CLASSID) {hasFV = PETSC_TRUE; continue;}
2211     ierr = PetscFEGetQuadrature(fe, &q);CHKERRQ(ierr);
2212     ierr = PetscFEGetDimension(fe, &Nb);CHKERRQ(ierr);
2213     ierr = PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches);CHKERRQ(ierr);
2214     ierr = PetscQuadratureGetData(q, NULL, &numQuadPoints, NULL, NULL);CHKERRQ(ierr);
2215     blockSize = Nb*numQuadPoints;
2216     batchSize = numBlocks * blockSize;
2217     ierr = PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches);CHKERRQ(ierr);
2218     numChunks = numCells / (numBatches*batchSize);
2219     Ne        = numChunks*numBatches*batchSize;
2220     Nr        = numCells % (numBatches*batchSize);
2221     offset    = numCells - Nr;
2222     for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
2223       if (hasJac) {
2224         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN, fieldI, fieldJ, Ne, cgeom, u, u_t, probAux, a, t, X_tShift, elemMat);CHKERRQ(ierr);
2225         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN, fieldI, fieldJ, Nr, &cgeom[offset], &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, X_tShift, &elemMat[offset*totDim*totDim]);CHKERRQ(ierr);
2226       }
2227       if (hasPrec) {
2228         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN_PRE, fieldI, fieldJ, Ne, cgeom, u, u_t, probAux, a, t, X_tShift, elemMatP);CHKERRQ(ierr);
2229         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN_PRE, fieldI, fieldJ, Nr, &cgeom[offset], &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, X_tShift, &elemMatP[offset*totDim*totDim]);CHKERRQ(ierr);
2230       }
2231       if (hasDyn) {
2232         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN_DYN, fieldI, fieldJ, Ne, cgeom, u, u_t, probAux, a, t, X_tShift, elemMatD);CHKERRQ(ierr);
2233         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN_DYN, fieldI, fieldJ, Nr, &cgeom[offset], &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, X_tShift, &elemMatD[offset*totDim*totDim]);CHKERRQ(ierr);
2234       }
2235     }
2236   }
2237   if (hasDyn) {
2238     for (c = 0; c < (cEnd - cStart)*totDim*totDim; ++c) elemMat[c] += X_tShift*elemMatD[c];
2239   }
2240   if (hasFV) {
2241     PetscClassId id;
2242     PetscFV      fv;
2243     PetscInt     offsetI, NcI, NbI = 1, fc, f;
2244 
2245     for (fieldI = 0; fieldI < Nf; ++fieldI) {
2246       ierr = PetscDSGetDiscretization(prob, fieldI, (PetscObject *) &fv);CHKERRQ(ierr);
2247       ierr = PetscDSGetFieldOffset(prob, fieldI, &offsetI);CHKERRQ(ierr);
2248       ierr = PetscObjectGetClassId((PetscObject) fv, &id);CHKERRQ(ierr);
2249       if (id != PETSCFV_CLASSID) continue;
2250       /* Put in the identity */
2251       ierr = PetscFVGetNumComponents(fv, &NcI);CHKERRQ(ierr);
2252       for (c = cStart; c < cEnd; ++c) {
2253         const PetscInt eOffset = (c-cStart)*totDim*totDim;
2254         for (fc = 0; fc < NcI; ++fc) {
2255           for (f = 0; f < NbI; ++f) {
2256             const PetscInt i = offsetI + f*NcI+fc;
2257             if (hasPrec) {
2258               if (hasJac) {elemMat[eOffset+i*totDim+i] = 1.0;}
2259               elemMatP[eOffset+i*totDim+i] = 1.0;
2260             } else {elemMat[eOffset+i*totDim+i] = 1.0;}
2261           }
2262         }
2263       }
2264     }
2265     /* No allocated space for FV stuff, so ignore the zero entries */
2266     ierr = MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE);CHKERRQ(ierr);
2267   }
2268   isMatIS = PETSC_FALSE;
2269   if (hasPrec && hasJac) {
2270     ierr = PetscObjectTypeCompare((PetscObject) JacP, MATIS, &isMatIS);CHKERRQ(ierr);
2271   }
2272   if (isMatIS && !subSection) {
2273     ierr = DMPlexGetSubdomainSection(dm, &subSection);CHKERRQ(ierr);
2274   }
2275   for (c = cStart; c < cEnd; ++c) {
2276     if (hasPrec) {
2277       if (hasJac) {
2278         if (mesh->printFEM > 1) {ierr = DMPrintCellMatrix(c, name, totDim, totDim, &elemMat[(c-cStart)*totDim*totDim]);CHKERRQ(ierr);}
2279         if (!isMatIS) {
2280           ierr = DMPlexMatSetClosure(dm, section, globalSection, Jac, c, &elemMat[(c-cStart)*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2281         } else {
2282           Mat lJ;
2283 
2284           ierr = MatISGetLocalMat(Jac,&lJ);CHKERRQ(ierr);
2285           ierr = DMPlexMatSetClosure(dm, section, subSection, lJ, c, &elemMat[(c-cStart)*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2286         }
2287       }
2288       if (mesh->printFEM > 1) {ierr = DMPrintCellMatrix(c, name, totDim, totDim, &elemMatP[(c-cStart)*totDim*totDim]);CHKERRQ(ierr);}
2289       if (!isMatISP) {
2290         ierr = DMPlexMatSetClosure(dm, section, globalSection, JacP, c, &elemMatP[(c-cStart)*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2291       } else {
2292         Mat lJ;
2293 
2294         ierr = MatISGetLocalMat(JacP,&lJ);CHKERRQ(ierr);
2295         ierr = DMPlexMatSetClosure(dm, section, subSection, lJ, c, &elemMatP[(c-cStart)*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2296       }
2297     } else {
2298       if (mesh->printFEM > 1) {ierr = DMPrintCellMatrix(c, name, totDim, totDim, &elemMat[(c-cStart)*totDim*totDim]);CHKERRQ(ierr);}
2299       if (!isMatISP) {
2300         ierr = DMPlexMatSetClosure(dm, section, globalSection, JacP, c, &elemMat[(c-cStart)*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2301       } else {
2302         Mat lJ;
2303 
2304         ierr = MatISGetLocalMat(JacP,&lJ);CHKERRQ(ierr);
2305         ierr = DMPlexMatSetClosure(dm, section, subSection, lJ, c, &elemMat[(c-cStart)*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2306       }
2307     }
2308   }
2309   if (hasFV) {ierr = MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_FALSE);CHKERRQ(ierr);}
2310   if (sizeof(PetscFECellGeom) % sizeof(PetscScalar)) {
2311     ierr = PetscFree(cgeom);CHKERRQ(ierr);
2312   } else {
2313     cgeom = NULL;
2314   }
2315   ierr = VecRestoreArray(cellgeom, &cgeomScal);CHKERRQ(ierr);
2316   ierr = PetscFree5(u,u_t,elemMat,elemMatP,elemMatD);CHKERRQ(ierr);
2317   if (dmAux) {
2318     ierr = PetscFree(a);CHKERRQ(ierr);
2319     ierr = DMDestroy(&plex);CHKERRQ(ierr);
2320   }
2321   ierr = DMPlexComputeBdJacobian_Internal(dm, X, X_t, t, X_tShift, Jac, JacP, user);CHKERRQ(ierr);
2322   if (hasJac && hasPrec) {
2323     ierr = MatAssemblyBegin(Jac, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2324     ierr = MatAssemblyEnd(Jac, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2325   }
2326   ierr = MatAssemblyBegin(JacP, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2327   ierr = MatAssemblyEnd(JacP, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2328   if (mesh->printFEM) {
2329     ierr = PetscPrintf(PETSC_COMM_WORLD, "%s:\n", name);CHKERRQ(ierr);
2330     ierr = MatChop(JacP, 1.0e-10);CHKERRQ(ierr);
2331     ierr = MatView(JacP, PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
2332   }
2333   ierr = PetscLogEventEnd(DMPLEX_JacobianFEM,dm,0,0,0);CHKERRQ(ierr);
2334   ierr = PetscObjectTypeCompare((PetscObject) Jac, MATSHELL, &isShell);CHKERRQ(ierr);
2335   if (isShell) {
2336     JacActionCtx *jctx;
2337 
2338     ierr = MatShellGetContext(Jac, &jctx);CHKERRQ(ierr);
2339     ierr = VecCopy(X, jctx->u);CHKERRQ(ierr);
2340   }
2341   PetscFunctionReturn(0);
2342 }
2343 
2344 
2345 PetscErrorCode DMPlexComputeJacobianAction_Internal(DM dm, PetscInt cStart, PetscInt cEnd, PetscReal t, PetscReal X_tShift, Vec X, Vec X_t, Vec Y, Vec Z, void *user)
2346 {
2347   DM_Plex          *mesh  = (DM_Plex *) dm->data;
2348   const char       *name  = "Jacobian";
2349   DM                dmAux, plex;
2350   Vec               A, cellgeom;
2351   PetscDS           prob, probAux = NULL;
2352   PetscQuadrature   quad;
2353   PetscSection      section, globalSection, sectionAux;
2354   PetscFECellGeom  *cgeom = NULL;
2355   PetscScalar      *cgeomScal;
2356   PetscScalar      *elemMat, *elemMatD, *u, *u_t, *a = NULL, *y, *z;
2357   PetscInt          dim, Nf, fieldI, fieldJ, numCells, c;
2358   PetscInt          totDim, totDimAux = 0;
2359   PetscBool         hasDyn;
2360   PetscErrorCode    ierr;
2361 
2362   PetscFunctionBegin;
2363   ierr = PetscLogEventBegin(DMPLEX_JacobianFEM,dm,0,0,0);CHKERRQ(ierr);
2364   ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
2365   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
2366   ierr = DMGetDefaultGlobalSection(dm, &globalSection);CHKERRQ(ierr);
2367   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
2368   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
2369   ierr = PetscDSHasDynamicJacobian(prob, &hasDyn);CHKERRQ(ierr);
2370   hasDyn = hasDyn && (X_tShift != 0.0) ? PETSC_TRUE : PETSC_FALSE;
2371   ierr = PetscSectionGetNumFields(section, &Nf);CHKERRQ(ierr);
2372   ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);
2373   numCells = cEnd - cStart;
2374   ierr = PetscObjectQuery((PetscObject) dm, "dmAux", (PetscObject *) &dmAux);CHKERRQ(ierr);
2375   ierr = PetscObjectQuery((PetscObject) dm, "A", (PetscObject *) &A);CHKERRQ(ierr);
2376   if (dmAux) {
2377     ierr = DMConvert(dmAux, DMPLEX, &plex);CHKERRQ(ierr);
2378     ierr = DMGetDefaultSection(plex, &sectionAux);CHKERRQ(ierr);
2379     ierr = DMGetDS(dmAux, &probAux);CHKERRQ(ierr);
2380     ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);
2381   }
2382   ierr = VecSet(Z, 0.0);CHKERRQ(ierr);
2383   ierr = PetscMalloc6(numCells*totDim,&u,X_t ? numCells*totDim : 0,&u_t,numCells*totDim*totDim,&elemMat,hasDyn ? numCells*totDim*totDim : 0, &elemMatD,numCells*totDim,&y,totDim,&z);CHKERRQ(ierr);
2384   if (dmAux) {ierr = PetscMalloc1(numCells*totDimAux, &a);CHKERRQ(ierr);}
2385   ierr = DMPlexSNESGetGeometryFEM(dm, &cellgeom);CHKERRQ(ierr);
2386   ierr = VecGetArray(cellgeom, &cgeomScal);CHKERRQ(ierr);
2387   if (sizeof(PetscFECellGeom) % sizeof(PetscScalar)) {
2388     DM dmCell;
2389 
2390     ierr = VecGetDM(cellgeom,&dmCell);CHKERRQ(ierr);
2391     ierr = PetscMalloc1(cEnd-cStart,&cgeom);CHKERRQ(ierr);
2392     for (c = 0; c < cEnd - cStart; c++) {
2393       PetscScalar *thisgeom;
2394 
2395       ierr = DMPlexPointLocalRef(dmCell, c + cStart, cgeomScal, &thisgeom);CHKERRQ(ierr);
2396       cgeom[c] = *((PetscFECellGeom *) thisgeom);
2397     }
2398   } else {
2399     cgeom = (PetscFECellGeom *) cgeomScal;
2400   }
2401   for (c = cStart; c < cEnd; ++c) {
2402     PetscScalar *x = NULL,  *x_t = NULL;
2403     PetscInt     i;
2404 
2405     ierr = DMPlexVecGetClosure(dm, section, X, c, NULL, &x);CHKERRQ(ierr);
2406     for (i = 0; i < totDim; ++i) u[(c-cStart)*totDim+i] = x[i];
2407     ierr = DMPlexVecRestoreClosure(dm, section, X, c, NULL, &x);CHKERRQ(ierr);
2408     if (X_t) {
2409       ierr = DMPlexVecGetClosure(dm, section, X_t, c, NULL, &x_t);CHKERRQ(ierr);
2410       for (i = 0; i < totDim; ++i) u_t[(c-cStart)*totDim+i] = x_t[i];
2411       ierr = DMPlexVecRestoreClosure(dm, section, X_t, c, NULL, &x_t);CHKERRQ(ierr);
2412     }
2413     if (dmAux) {
2414       ierr = DMPlexVecGetClosure(plex, sectionAux, A, c, NULL, &x);CHKERRQ(ierr);
2415       for (i = 0; i < totDimAux; ++i) a[(c-cStart)*totDimAux+i] = x[i];
2416       ierr = DMPlexVecRestoreClosure(plex, sectionAux, A, c, NULL, &x);CHKERRQ(ierr);
2417     }
2418     ierr = DMPlexVecGetClosure(dm, section, Y, c, NULL, &x);CHKERRQ(ierr);
2419     for (i = 0; i < totDim; ++i) y[(c-cStart)*totDim+i] = x[i];
2420     ierr = DMPlexVecRestoreClosure(dm, section, Y, c, NULL, &x);CHKERRQ(ierr);
2421   }
2422   ierr = PetscMemzero(elemMat, numCells*totDim*totDim * sizeof(PetscScalar));CHKERRQ(ierr);
2423   if (hasDyn)  {ierr = PetscMemzero(elemMatD, numCells*totDim*totDim * sizeof(PetscScalar));CHKERRQ(ierr);}
2424   for (fieldI = 0; fieldI < Nf; ++fieldI) {
2425     PetscFE  fe;
2426     PetscInt numQuadPoints, Nb;
2427     /* Conforming batches */
2428     PetscInt numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
2429     /* Remainder */
2430     PetscInt Nr, offset;
2431 
2432     ierr = PetscDSGetDiscretization(prob, fieldI, (PetscObject *) &fe);CHKERRQ(ierr);
2433     ierr = PetscFEGetQuadrature(fe, &quad);CHKERRQ(ierr);
2434     ierr = PetscFEGetDimension(fe, &Nb);CHKERRQ(ierr);
2435     ierr = PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches);CHKERRQ(ierr);
2436     ierr = PetscQuadratureGetData(quad, NULL, &numQuadPoints, NULL, NULL);CHKERRQ(ierr);
2437     blockSize = Nb*numQuadPoints;
2438     batchSize = numBlocks * blockSize;
2439     ierr = PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches);CHKERRQ(ierr);
2440     numChunks = numCells / (numBatches*batchSize);
2441     Ne        = numChunks*numBatches*batchSize;
2442     Nr        = numCells % (numBatches*batchSize);
2443     offset    = numCells - Nr;
2444     for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
2445       ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN, fieldI, fieldJ, Ne, cgeom, u, u_t, probAux, a, t, X_tShift, elemMat);CHKERRQ(ierr);
2446       ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN, fieldI, fieldJ, Nr, &cgeom[offset], &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, X_tShift, &elemMat[offset*totDim*totDim]);CHKERRQ(ierr);
2447       if (hasDyn) {
2448         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN_DYN, fieldI, fieldJ, Ne, cgeom, u, u_t, probAux, a, t, X_tShift, elemMatD);CHKERRQ(ierr);
2449         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN_DYN, fieldI, fieldJ, Nr, &cgeom[offset], &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, X_tShift, &elemMatD[offset*totDim*totDim]);CHKERRQ(ierr);
2450       }
2451     }
2452   }
2453   if (hasDyn) {
2454     for (c = 0; c < (cEnd - cStart)*totDim*totDim; ++c) elemMat[c] += X_tShift*elemMatD[c];
2455   }
2456   for (c = cStart; c < cEnd; ++c) {
2457     const PetscBLASInt M = totDim, one = 1;
2458     const PetscScalar  a = 1.0, b = 0.0;
2459 
2460     PetscStackCallBLAS("BLASgemv", BLASgemv_("N", &M, &M, &a, &elemMat[(c-cStart)*totDim*totDim], &M, &y[(c-cStart)*totDim], &one, &b, z, &one));
2461     if (mesh->printFEM > 1) {
2462       ierr = DMPrintCellMatrix(c, name, totDim, totDim, &elemMat[(c-cStart)*totDim*totDim]);CHKERRQ(ierr);
2463       ierr = DMPrintCellVector(c, "Y",  totDim, &y[(c-cStart)*totDim]);CHKERRQ(ierr);
2464       ierr = DMPrintCellVector(c, "Z",  totDim, z);CHKERRQ(ierr);
2465     }
2466     ierr = DMPlexVecSetClosure(dm, section, Z, c, z, ADD_VALUES);CHKERRQ(ierr);
2467   }
2468   if (sizeof(PetscFECellGeom) % sizeof(PetscScalar)) {ierr = PetscFree(cgeom);CHKERRQ(ierr);}
2469   else                                               {cgeom = NULL;}
2470   ierr = VecRestoreArray(cellgeom, &cgeomScal);CHKERRQ(ierr);
2471   ierr = PetscFree6(u,u_t,elemMat,elemMatD,y,z);CHKERRQ(ierr);
2472   if (dmAux) {
2473     ierr = PetscFree(a);CHKERRQ(ierr);
2474     ierr = DMDestroy(&plex);CHKERRQ(ierr);
2475   }
2476   if (mesh->printFEM) {
2477     ierr = PetscPrintf(PETSC_COMM_WORLD, "Z:\n");CHKERRQ(ierr);
2478     ierr = VecView(Z, PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
2479   }
2480   ierr = PetscLogEventEnd(DMPLEX_JacobianFEM,dm,0,0,0);CHKERRQ(ierr);
2481   PetscFunctionReturn(0);
2482 }
2483 
2484 /*@
2485   DMPlexSNESComputeJacobianFEM - Form the local portion of the Jacobian matrix J at the local solution X using pointwise functions specified by the user.
2486 
2487   Input Parameters:
2488 + dm - The mesh
2489 . X  - Local input vector
2490 - user - The user context
2491 
2492   Output Parameter:
2493 . Jac  - Jacobian matrix
2494 
2495   Note:
2496   We form the residual one batch of elements at a time. This allows us to offload work onto an accelerator,
2497   like a GPU, or vectorize on a multicore machine.
2498 
2499   Level: developer
2500 
2501 .seealso: FormFunctionLocal()
2502 @*/
2503 PetscErrorCode DMPlexSNESComputeJacobianFEM(DM dm, Vec X, Mat Jac, Mat JacP,void *user)
2504 {
2505   PetscInt       cStart, cEnd, cEndInterior;
2506   DM             plex;
2507   PetscErrorCode ierr;
2508 
2509   PetscFunctionBegin;
2510   ierr = DMSNESConvertPlex(dm,&plex,PETSC_TRUE);CHKERRQ(ierr);
2511   ierr = DMPlexGetHeightStratum(plex, 0, &cStart, &cEnd);CHKERRQ(ierr);
2512   ierr = DMPlexGetHybridBounds(plex, &cEndInterior, NULL, NULL, NULL);CHKERRQ(ierr);
2513   cEnd = cEndInterior < 0 ? cEnd : cEndInterior;
2514   ierr = DMPlexComputeJacobian_Internal(plex, cStart, cEnd, 0.0, 0.0, X, NULL, Jac, JacP, user);CHKERRQ(ierr);
2515   ierr = DMDestroy(&plex);CHKERRQ(ierr);
2516   PetscFunctionReturn(0);
2517 }
2518 
2519 /*@
2520   DMPlexSNESComputeJacobianActionFEM - Form the local portion of the Jacobian action Z = J(X) Y at the local solution X using pointwise functions specified by the user.
2521 
2522   Input Parameters:
2523 + dm - The mesh
2524 . X  - Local solution vector
2525 . Y  - Local input vector
2526 - user - The user context
2527 
2528   Output Parameter:
2529 . Z - Local output vector
2530 
2531   Note:
2532   We form the residual one batch of elements at a time. This allows us to offload work onto an accelerator,
2533   like a GPU, or vectorize on a multicore machine.
2534 
2535   Level: developer
2536 
2537 .seealso: FormFunctionLocal()
2538 @*/
2539 PetscErrorCode DMPlexSNESComputeJacobianActionFEM(DM dm, Vec X, Vec Y, Vec Z, void *user)
2540 {
2541   PetscInt       cStart, cEnd, cEndInterior;
2542   DM             plex;
2543   PetscErrorCode ierr;
2544 
2545   PetscFunctionBegin;
2546   ierr = DMSNESConvertPlex(dm,&plex,PETSC_TRUE);CHKERRQ(ierr);
2547   ierr = DMPlexGetHeightStratum(plex, 0, &cStart, &cEnd);CHKERRQ(ierr);
2548   ierr = DMPlexGetHybridBounds(plex, &cEndInterior, NULL, NULL, NULL);CHKERRQ(ierr);
2549   cEnd = cEndInterior < 0 ? cEnd : cEndInterior;
2550   ierr = DMPlexComputeJacobianAction_Internal(plex, cStart, cEnd, 0.0, 0.0, X, NULL, Y, Z, user);CHKERRQ(ierr);
2551   ierr = DMDestroy(&plex);CHKERRQ(ierr);
2552   PetscFunctionReturn(0);
2553 }
2554 
2555 /*@
2556   DMPlexSetSNESLocalFEM - Use DMPlex's internal FEM routines to compute SNES boundary values, residual, and Jacobian.
2557 
2558   Input Parameters:
2559 + dm - The DM object
2560 . boundaryctx - the user context that will be passed to pointwise evaluation of boundary values (see PetscDSAddBoundary())
2561 . residualctx - the user context that will be passed to pointwise evaluation of finite element residual computations (see PetscDSSetResidual())
2562 - jacobianctx - the user context that will be passed to pointwise evaluation of finite element Jacobian construction (see PetscDSSetJacobian())
2563 
2564   Level: developer
2565 @*/
2566 PetscErrorCode DMPlexSetSNESLocalFEM(DM dm, void *boundaryctx, void *residualctx, void *jacobianctx)
2567 {
2568   PetscErrorCode ierr;
2569 
2570   PetscFunctionBegin;
2571   ierr = DMSNESSetBoundaryLocal(dm,DMPlexSNESComputeBoundaryFEM,boundaryctx);CHKERRQ(ierr);
2572   ierr = DMSNESSetFunctionLocal(dm,DMPlexSNESComputeResidualFEM,residualctx);CHKERRQ(ierr);
2573   ierr = DMSNESSetJacobianLocal(dm,DMPlexSNESComputeJacobianFEM,jacobianctx);CHKERRQ(ierr);
2574   PetscFunctionReturn(0);
2575 }
2576 
2577 PetscErrorCode DMSNESCheckFromOptions_Internal(SNES snes, DM dm, Vec u, Vec sol, PetscErrorCode (**exactFuncs)(PetscInt, PetscReal, const PetscReal x[], PetscInt, PetscScalar *u, void *ctx), void **ctxs)
2578 {
2579   PetscDS        prob;
2580   Mat            J, M;
2581   Vec            r, b;
2582   MatNullSpace   nullSpace;
2583   PetscReal     *error, res = 0.0;
2584   PetscInt       numFields;
2585   PetscBool      hasJac, hasPrec;
2586   PetscErrorCode ierr;
2587 
2588   PetscFunctionBegin;
2589   ierr = VecDuplicate(u, &r);CHKERRQ(ierr);
2590   ierr = DMCreateMatrix(dm, &J);CHKERRQ(ierr);
2591   /* TODO Null space for J */
2592   /* Check discretization error */
2593   ierr = DMGetNumFields(dm, &numFields);CHKERRQ(ierr);
2594   ierr = PetscMalloc1(PetscMax(1, numFields), &error);CHKERRQ(ierr);
2595   if (numFields > 1) {
2596     PetscInt f;
2597 
2598     ierr = DMComputeL2FieldDiff(dm, 0.0, exactFuncs, ctxs, u, error);CHKERRQ(ierr);
2599     ierr = PetscPrintf(PETSC_COMM_WORLD, "L_2 Error: [");CHKERRQ(ierr);
2600     for (f = 0; f < numFields; ++f) {
2601       if (f) {ierr = PetscPrintf(PETSC_COMM_WORLD, ", ");CHKERRQ(ierr);}
2602       if (error[f] >= 1.0e-11) {ierr = PetscPrintf(PETSC_COMM_WORLD, "%g", error[f]);CHKERRQ(ierr);}
2603       else                     {ierr = PetscPrintf(PETSC_COMM_WORLD, "< 1.0e-11");CHKERRQ(ierr);}
2604     }
2605     ierr = PetscPrintf(PETSC_COMM_WORLD, "]\n");CHKERRQ(ierr);
2606   } else {
2607     ierr = DMComputeL2Diff(dm, 0.0, exactFuncs, ctxs, u, &error[0]);CHKERRQ(ierr);
2608     if (error[0] >= 1.0e-11) {ierr = PetscPrintf(PETSC_COMM_WORLD, "L_2 Error: %g\n", error[0]);CHKERRQ(ierr);}
2609     else                     {ierr = PetscPrintf(PETSC_COMM_WORLD, "L_2 Error: < 1.0e-11\n");CHKERRQ(ierr);}
2610   }
2611   ierr = PetscFree(error);CHKERRQ(ierr);
2612   /* Check residual */
2613   ierr = SNESComputeFunction(snes, u, r);CHKERRQ(ierr);
2614   ierr = VecNorm(r, NORM_2, &res);CHKERRQ(ierr);
2615   ierr = PetscPrintf(PETSC_COMM_WORLD, "L_2 Residual: %g\n", res);CHKERRQ(ierr);
2616   ierr = VecChop(r, 1.0e-10);CHKERRQ(ierr);
2617   ierr = PetscObjectSetName((PetscObject) r, "Initial Residual");CHKERRQ(ierr);
2618   ierr = PetscObjectSetOptionsPrefix((PetscObject)r,"res_");CHKERRQ(ierr);
2619   ierr = VecViewFromOptions(r, NULL, "-vec_view");CHKERRQ(ierr);
2620   /* Check Jacobian */
2621   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
2622   ierr = PetscDSHasJacobian(prob, &hasJac);CHKERRQ(ierr);
2623   ierr = PetscDSHasJacobianPreconditioner(prob, &hasPrec);CHKERRQ(ierr);
2624   if (hasJac && hasPrec) {
2625     ierr = DMCreateMatrix(dm, &M);CHKERRQ(ierr);
2626     ierr = SNESComputeJacobian(snes, u, J, M);CHKERRQ(ierr);
2627     ierr = PetscObjectSetOptionsPrefix((PetscObject) M, "jacpre_");CHKERRQ(ierr);
2628     ierr = MatViewFromOptions(M, NULL, "-mat_view");CHKERRQ(ierr);
2629     ierr = MatDestroy(&M);CHKERRQ(ierr);
2630   } else {
2631     ierr = SNESComputeJacobian(snes, u, J, J);CHKERRQ(ierr);
2632   }
2633   ierr = PetscObjectSetOptionsPrefix((PetscObject) J, "jac_");CHKERRQ(ierr);
2634   ierr = MatViewFromOptions(J, NULL, "-mat_view");CHKERRQ(ierr);
2635   ierr = MatGetNullSpace(J, &nullSpace);CHKERRQ(ierr);
2636   if (nullSpace) {
2637     PetscBool isNull;
2638     ierr = MatNullSpaceTest(nullSpace, J, &isNull);CHKERRQ(ierr);
2639     if (!isNull) SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_PLIB, "The null space calculated for the system operator is invalid.");
2640   }
2641   ierr = VecDuplicate(u, &b);CHKERRQ(ierr);
2642   ierr = VecSet(r, 0.0);CHKERRQ(ierr);
2643   ierr = SNESComputeFunction(snes, r, b);CHKERRQ(ierr);
2644   ierr = MatMult(J, u, r);CHKERRQ(ierr);
2645   ierr = VecAXPY(r, 1.0, b);CHKERRQ(ierr);
2646   ierr = VecDestroy(&b);CHKERRQ(ierr);
2647   ierr = VecNorm(r, NORM_2, &res);CHKERRQ(ierr);
2648   ierr = PetscPrintf(PETSC_COMM_WORLD, "Linear L_2 Residual: %g\n", res);CHKERRQ(ierr);
2649   ierr = VecChop(r, 1.0e-10);CHKERRQ(ierr);
2650   ierr = PetscObjectSetName((PetscObject) r, "Au - b = Au + F(0)");CHKERRQ(ierr);
2651   ierr = PetscObjectSetOptionsPrefix((PetscObject)r,"linear_res_");CHKERRQ(ierr);
2652   ierr = VecViewFromOptions(r, NULL, "-vec_view");CHKERRQ(ierr);
2653   ierr = VecDestroy(&r);CHKERRQ(ierr);
2654   ierr = MatNullSpaceDestroy(&nullSpace);CHKERRQ(ierr);
2655   ierr = MatDestroy(&J);CHKERRQ(ierr);
2656   PetscFunctionReturn(0);
2657 }
2658 
2659 PetscErrorCode DMSNESCheckFromOptions(SNES snes, Vec u, PetscErrorCode (**exactFuncs)(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx), void **ctxs)
2660 {
2661   DM             dm;
2662   Vec            sol;
2663   PetscBool      check;
2664   PetscErrorCode ierr;
2665 
2666   PetscFunctionBegin;
2667   ierr = PetscOptionsHasName(((PetscObject)snes)->options,((PetscObject)snes)->prefix, "-dmsnes_check", &check);CHKERRQ(ierr);
2668   if (!check) PetscFunctionReturn(0);
2669   ierr = SNESGetDM(snes, &dm);CHKERRQ(ierr);
2670   ierr = VecDuplicate(u, &sol);CHKERRQ(ierr);
2671   ierr = SNESSetSolution(snes, sol);CHKERRQ(ierr);
2672   ierr = DMSNESCheckFromOptions_Internal(snes, dm, u, sol, exactFuncs, ctxs);CHKERRQ(ierr);
2673   ierr = VecDestroy(&sol);CHKERRQ(ierr);
2674   PetscFunctionReturn(0);
2675 }
2676