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