xref: /petsc/src/snes/utils/dmplexsnes.c (revision 9305a4c72a61c8923c0d13a5c2c65da27d97353f)
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 static PetscErrorCode PetscContainerUserDestroy_PetscFEGeom (void *ctx)
828 {
829   PetscFEGeom *geom = (PetscFEGeom *) ctx;
830   PetscErrorCode ierr;
831 
832   PetscFunctionBegin;
833   ierr = PetscFEGeomDestroy(&geom);CHKERRQ(ierr);
834   PetscFunctionReturn(0);
835 }
836 
837 static PetscErrorCode DMSNESGetFEGeom(DMField coordField, IS pointIS, PetscQuadrature quad, PetscBool faceData, PetscFEGeom **geom)
838 {
839   char            composeStr[33] = {0};
840   PetscObjectId   id;
841   PetscContainer  container;
842   PetscErrorCode  ierr;
843 
844   PetscFunctionBegin;
845   ierr = PetscObjectGetId((PetscObject)quad,&id);CHKERRQ(ierr);
846   ierr = PetscSNPrintf(composeStr, 32, "DMSNESGetFEGeom_%x\n", id);CHKERRQ(ierr);
847   ierr = PetscObjectQuery((PetscObject) pointIS, composeStr, (PetscObject *) &container);CHKERRQ(ierr);
848   if (container) {
849     ierr = PetscContainerGetPointer(container, (void **) geom);CHKERRQ(ierr);
850   } else {
851     ierr = DMFieldCreateFEGeom(coordField, pointIS, quad, faceData, geom);CHKERRQ(ierr);
852     ierr = PetscContainerCreate(PETSC_COMM_SELF,&container);CHKERRQ(ierr);
853     ierr = PetscContainerSetPointer(container, (void *) *geom);CHKERRQ(ierr);
854     ierr = PetscContainerSetUserDestroy(container, PetscContainerUserDestroy_PetscFEGeom);CHKERRQ(ierr);
855     ierr = PetscObjectCompose((PetscObject) pointIS, composeStr, (PetscObject) container);CHKERRQ(ierr);
856     ierr = PetscContainerDestroy(&container);CHKERRQ(ierr);
857   }
858   PetscFunctionReturn(0);
859 }
860 
861 static PetscErrorCode DMSNESRestoreFEGeom(DMField coordField, IS pointIS, PetscQuadrature quad, PetscBool faceData, PetscFEGeom **geom)
862 {
863   PetscFunctionBegin;
864   *geom = NULL;
865   PetscFunctionReturn(0);
866 }
867 
868 /*@
869   DMPlexSNESGetGeometryFVM - Return precomputed geometric data
870 
871   Input Parameter:
872 . dm - The DM
873 
874   Output Parameters:
875 + facegeom - The values precomputed from face geometry
876 . cellgeom - The values precomputed from cell geometry
877 - minRadius - The minimum radius over the mesh of an inscribed sphere in a cell
878 
879   Level: developer
880 
881 .seealso: DMPlexTSSetRHSFunctionLocal()
882 @*/
883 PetscErrorCode DMPlexSNESGetGeometryFVM(DM dm, Vec *facegeom, Vec *cellgeom, PetscReal *minRadius)
884 {
885   DM             plex;
886   PetscErrorCode ierr;
887 
888   PetscFunctionBegin;
889   PetscValidHeaderSpecific(dm,DM_CLASSID,1);
890   ierr = DMSNESConvertPlex(dm,&plex,PETSC_TRUE);CHKERRQ(ierr);
891   ierr = DMPlexGetDataFVM(plex, NULL, cellgeom, facegeom, NULL);CHKERRQ(ierr);
892   if (minRadius) {ierr = DMPlexGetMinRadius(plex, minRadius);CHKERRQ(ierr);}
893   ierr = DMDestroy(&plex);CHKERRQ(ierr);
894   PetscFunctionReturn(0);
895 }
896 
897 /*@
898   DMPlexSNESGetGradientDM - Return gradient data layout
899 
900   Input Parameters:
901 + dm - The DM
902 - fv - The PetscFV
903 
904   Output Parameter:
905 . dmGrad - The layout for gradient values
906 
907   Level: developer
908 
909 .seealso: DMPlexSNESGetGeometryFVM()
910 @*/
911 PetscErrorCode DMPlexSNESGetGradientDM(DM dm, PetscFV fv, DM *dmGrad)
912 {
913   DM             plex;
914   PetscBool      computeGradients;
915   PetscErrorCode ierr;
916 
917   PetscFunctionBegin;
918   PetscValidHeaderSpecific(dm,DM_CLASSID,1);
919   PetscValidHeaderSpecific(fv,PETSCFV_CLASSID,2);
920   PetscValidPointer(dmGrad,3);
921   ierr = PetscFVGetComputeGradients(fv, &computeGradients);CHKERRQ(ierr);
922   if (!computeGradients) {*dmGrad = NULL; PetscFunctionReturn(0);}
923   ierr = DMSNESConvertPlex(dm,&plex,PETSC_TRUE);CHKERRQ(ierr);
924   ierr = DMPlexGetDataFVM(plex, fv, NULL, NULL, dmGrad);CHKERRQ(ierr);
925   ierr = DMDestroy(&plex);CHKERRQ(ierr);
926   PetscFunctionReturn(0);
927 }
928 
929 /*@C
930   DMPlexGetCellFields - Retrieve the field values values for a chunk of cells
931 
932   Input Parameters:
933 + dm     - The DM
934 . cellIS - The cells to include
935 . locX   - A local vector with the solution fields
936 . locX_t - A local vector with solution field time derivatives, or NULL
937 - locA   - A local vector with auxiliary fields, or NULL
938 
939   Output Parameters:
940 + u   - The field coefficients
941 . u_t - The fields derivative coefficients
942 - a   - The auxiliary field coefficients
943 
944   Level: developer
945 
946 .seealso: DMPlexGetFaceFields()
947 @*/
948 PetscErrorCode DMPlexGetCellFields(DM dm, IS cellIS, Vec locX, Vec locX_t, Vec locA, PetscScalar **u, PetscScalar **u_t, PetscScalar **a)
949 {
950   DM              plex, plexA = NULL;
951   PetscSection    section, sectionAux;
952   PetscDS         prob;
953   const PetscInt *cells;
954   PetscInt        cStart, cEnd, numCells, totDim, totDimAux, c;
955   PetscErrorCode  ierr;
956 
957   PetscFunctionBegin;
958   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
959   PetscValidHeaderSpecific(locX, VEC_CLASSID, 4);
960   if (locX_t) {PetscValidHeaderSpecific(locX_t, VEC_CLASSID, 5);}
961   if (locA)   {PetscValidHeaderSpecific(locA, VEC_CLASSID, 6);}
962   PetscValidPointer(u, 7);
963   PetscValidPointer(u_t, 8);
964   PetscValidPointer(a, 9);
965   ierr = DMSNESConvertPlex(dm, &plex, PETSC_FALSE);CHKERRQ(ierr);
966   ierr = ISGetPointRange(cellIS, &cStart, &cEnd, &cells);CHKERRQ(ierr);
967   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
968   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
969   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
970   if (locA) {
971     DM      dmAux;
972     PetscDS probAux;
973 
974     ierr = VecGetDM(locA, &dmAux);CHKERRQ(ierr);
975     ierr = DMSNESConvertPlex(dmAux, &plexA, PETSC_FALSE);CHKERRQ(ierr);
976     ierr = DMGetDefaultSection(dmAux, &sectionAux);CHKERRQ(ierr);
977     ierr = DMGetDS(dmAux, &probAux);CHKERRQ(ierr);
978     ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);
979   }
980   numCells = cEnd - cStart;
981   ierr = DMGetWorkArray(dm, numCells*totDim, MPIU_SCALAR, u);CHKERRQ(ierr);
982   if (locX_t) {ierr = DMGetWorkArray(dm, numCells*totDim, MPIU_SCALAR, u_t);CHKERRQ(ierr);} else {*u_t = NULL;}
983   if (locA)   {ierr = DMGetWorkArray(dm, numCells*totDimAux, MPIU_SCALAR, a);CHKERRQ(ierr);} else {*a = NULL;}
984   for (c = cStart; c < cEnd; ++c) {
985     const PetscInt cell = cells ? cells[c] : c;
986     const PetscInt cind = c - cStart;
987     PetscScalar   *x = NULL, *x_t = NULL, *ul = *u, *ul_t = *u_t, *al = *a;
988     PetscInt       i;
989 
990     ierr = DMPlexVecGetClosure(plex, section, locX, cell, NULL, &x);CHKERRQ(ierr);
991     for (i = 0; i < totDim; ++i) ul[cind*totDim+i] = x[i];
992     ierr = DMPlexVecRestoreClosure(plex, section, locX, cell, NULL, &x);CHKERRQ(ierr);
993     if (locX_t) {
994       ierr = DMPlexVecGetClosure(plex, section, locX_t, cell, NULL, &x_t);CHKERRQ(ierr);
995       for (i = 0; i < totDim; ++i) ul_t[cind*totDim+i] = x_t[i];
996       ierr = DMPlexVecRestoreClosure(plex, section, locX_t, cell, NULL, &x_t);CHKERRQ(ierr);
997     }
998     if (locA) {
999       ierr = DMPlexVecGetClosure(plexA, sectionAux, locA, cell, NULL, &x);CHKERRQ(ierr);
1000       for (i = 0; i < totDimAux; ++i) al[cind*totDimAux+i] = x[i];
1001       ierr = DMPlexVecRestoreClosure(plexA, sectionAux, locA, cell, NULL, &x);CHKERRQ(ierr);
1002     }
1003   }
1004   ierr = DMDestroy(&plex);CHKERRQ(ierr);
1005   if (locA) {ierr = DMDestroy(&plexA);CHKERRQ(ierr);}
1006   ierr = ISRestorePointRange(cellIS, &cStart, &cEnd, &cells);CHKERRQ(ierr);
1007   PetscFunctionReturn(0);
1008 }
1009 
1010 /*@C
1011   DMPlexRestoreCellFields - Restore the field values values for a chunk of cells
1012 
1013   Input Parameters:
1014 + dm     - The DM
1015 . cellIS - The cells to include
1016 . locX   - A local vector with the solution fields
1017 . locX_t - A local vector with solution field time derivatives, or NULL
1018 - locA   - A local vector with auxiliary fields, or NULL
1019 
1020   Output Parameters:
1021 + u   - The field coefficients
1022 . u_t - The fields derivative coefficients
1023 - a   - The auxiliary field coefficients
1024 
1025   Level: developer
1026 
1027 .seealso: DMPlexGetFaceFields()
1028 @*/
1029 PetscErrorCode DMPlexRestoreCellFields(DM dm, IS cellIS, Vec locX, Vec locX_t, Vec locA, PetscScalar **u, PetscScalar **u_t, PetscScalar **a)
1030 {
1031   PetscErrorCode ierr;
1032 
1033   PetscFunctionBegin;
1034   ierr = DMRestoreWorkArray(dm, 0, MPIU_SCALAR, u);CHKERRQ(ierr);
1035   if (locX_t) {ierr = DMRestoreWorkArray(dm, 0, MPIU_SCALAR, u_t);CHKERRQ(ierr);}
1036   if (locA)   {ierr = DMRestoreWorkArray(dm, 0, MPIU_SCALAR, a);CHKERRQ(ierr);}
1037   PetscFunctionReturn(0);
1038 }
1039 
1040 /*@C
1041   DMPlexGetFaceFields - Retrieve the field values values for a chunk of faces
1042 
1043   Input Parameters:
1044 + dm     - The DM
1045 . fStart - The first face to include
1046 . fEnd   - The first face to exclude
1047 . locX   - A local vector with the solution fields
1048 . locX_t - A local vector with solution field time derivatives, or NULL
1049 . faceGeometry - A local vector with face geometry
1050 . cellGeometry - A local vector with cell geometry
1051 - locaGrad - A local vector with field gradients, or NULL
1052 
1053   Output Parameters:
1054 + Nface - The number of faces with field values
1055 . uL - The field values at the left side of the face
1056 - uR - The field values at the right side of the face
1057 
1058   Level: developer
1059 
1060 .seealso: DMPlexGetCellFields()
1061 @*/
1062 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)
1063 {
1064   DM                 dmFace, dmCell, dmGrad = NULL;
1065   PetscSection       section;
1066   PetscDS            prob;
1067   DMLabel            ghostLabel;
1068   const PetscScalar *facegeom, *cellgeom, *x, *lgrad;
1069   PetscBool         *isFE;
1070   PetscInt           dim, Nf, f, Nc, numFaces = fEnd - fStart, iface, face;
1071   PetscErrorCode     ierr;
1072 
1073   PetscFunctionBegin;
1074   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
1075   PetscValidHeaderSpecific(locX, VEC_CLASSID, 4);
1076   if (locX_t) {PetscValidHeaderSpecific(locX_t, VEC_CLASSID, 5);}
1077   PetscValidHeaderSpecific(faceGeometry, VEC_CLASSID, 6);
1078   PetscValidHeaderSpecific(cellGeometry, VEC_CLASSID, 7);
1079   if (locGrad) {PetscValidHeaderSpecific(locGrad, VEC_CLASSID, 8);}
1080   PetscValidPointer(uL, 9);
1081   PetscValidPointer(uR, 10);
1082   ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
1083   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
1084   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
1085   ierr = PetscDSGetNumFields(prob, &Nf);CHKERRQ(ierr);
1086   ierr = PetscDSGetTotalComponents(prob, &Nc);CHKERRQ(ierr);
1087   ierr = PetscMalloc1(Nf, &isFE);CHKERRQ(ierr);
1088   for (f = 0; f < Nf; ++f) {
1089     PetscObject  obj;
1090     PetscClassId id;
1091 
1092     ierr = PetscDSGetDiscretization(prob, f, &obj);CHKERRQ(ierr);
1093     ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
1094     if (id == PETSCFE_CLASSID)      {isFE[f] = PETSC_TRUE;}
1095     else if (id == PETSCFV_CLASSID) {isFE[f] = PETSC_FALSE;}
1096     else                            {isFE[f] = PETSC_FALSE;}
1097   }
1098   ierr = DMGetLabel(dm, "ghost", &ghostLabel);CHKERRQ(ierr);
1099   ierr = VecGetArrayRead(locX, &x);CHKERRQ(ierr);
1100   ierr = VecGetDM(faceGeometry, &dmFace);CHKERRQ(ierr);
1101   ierr = VecGetArrayRead(faceGeometry, &facegeom);CHKERRQ(ierr);
1102   ierr = VecGetDM(cellGeometry, &dmCell);CHKERRQ(ierr);
1103   ierr = VecGetArrayRead(cellGeometry, &cellgeom);CHKERRQ(ierr);
1104   if (locGrad) {
1105     ierr = VecGetDM(locGrad, &dmGrad);CHKERRQ(ierr);
1106     ierr = VecGetArrayRead(locGrad, &lgrad);CHKERRQ(ierr);
1107   }
1108   ierr = DMGetWorkArray(dm, numFaces*Nc, MPIU_SCALAR, uL);CHKERRQ(ierr);
1109   ierr = DMGetWorkArray(dm, numFaces*Nc, MPIU_SCALAR, uR);CHKERRQ(ierr);
1110   /* Right now just eat the extra work for FE (could make a cell loop) */
1111   for (face = fStart, iface = 0; face < fEnd; ++face) {
1112     const PetscInt        *cells;
1113     PetscFVFaceGeom       *fg;
1114     PetscFVCellGeom       *cgL, *cgR;
1115     PetscScalar           *xL, *xR, *gL, *gR;
1116     PetscScalar           *uLl = *uL, *uRl = *uR;
1117     PetscInt               ghost, nsupp, nchild;
1118 
1119     ierr = DMLabelGetValue(ghostLabel, face, &ghost);CHKERRQ(ierr);
1120     ierr = DMPlexGetSupportSize(dm, face, &nsupp);CHKERRQ(ierr);
1121     ierr = DMPlexGetTreeChildren(dm, face, &nchild, NULL);CHKERRQ(ierr);
1122     if (ghost >= 0 || nsupp > 2 || nchild > 0) continue;
1123     ierr = DMPlexPointLocalRead(dmFace, face, facegeom, &fg);CHKERRQ(ierr);
1124     ierr = DMPlexGetSupport(dm, face, &cells);CHKERRQ(ierr);
1125     ierr = DMPlexPointLocalRead(dmCell, cells[0], cellgeom, &cgL);CHKERRQ(ierr);
1126     ierr = DMPlexPointLocalRead(dmCell, cells[1], cellgeom, &cgR);CHKERRQ(ierr);
1127     for (f = 0; f < Nf; ++f) {
1128       PetscInt off;
1129 
1130       ierr = PetscDSGetComponentOffset(prob, f, &off);CHKERRQ(ierr);
1131       if (isFE[f]) {
1132         const PetscInt *cone;
1133         PetscInt        comp, coneSizeL, coneSizeR, faceLocL, faceLocR, ldof, rdof, d;
1134 
1135         xL = xR = NULL;
1136         ierr = PetscSectionGetFieldComponents(section, f, &comp);CHKERRQ(ierr);
1137         ierr = DMPlexVecGetClosure(dm, section, locX, cells[0], &ldof, (PetscScalar **) &xL);CHKERRQ(ierr);
1138         ierr = DMPlexVecGetClosure(dm, section, locX, cells[1], &rdof, (PetscScalar **) &xR);CHKERRQ(ierr);
1139         ierr = DMPlexGetCone(dm, cells[0], &cone);CHKERRQ(ierr);
1140         ierr = DMPlexGetConeSize(dm, cells[0], &coneSizeL);CHKERRQ(ierr);
1141         for (faceLocL = 0; faceLocL < coneSizeL; ++faceLocL) if (cone[faceLocL] == face) break;
1142         ierr = DMPlexGetCone(dm, cells[1], &cone);CHKERRQ(ierr);
1143         ierr = DMPlexGetConeSize(dm, cells[1], &coneSizeR);CHKERRQ(ierr);
1144         for (faceLocR = 0; faceLocR < coneSizeR; ++faceLocR) if (cone[faceLocR] == face) break;
1145         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]);
1146         /* Check that FEM field has values in the right cell (sometimes its an FV ghost cell) */
1147         /* TODO: this is a hack that might not be right for nonconforming */
1148         if (faceLocL < coneSizeL) {
1149           ierr = EvaluateFaceFields(prob, f, faceLocL, xL, &uLl[iface*Nc+off]);CHKERRQ(ierr);
1150           if (rdof == ldof && faceLocR < coneSizeR) {ierr = EvaluateFaceFields(prob, f, faceLocR, xR, &uRl[iface*Nc+off]);CHKERRQ(ierr);}
1151           else              {for(d = 0; d < comp; ++d) uRl[iface*Nc+off+d] = uLl[iface*Nc+off+d];}
1152         }
1153         else {
1154           ierr = EvaluateFaceFields(prob, f, faceLocR, xR, &uRl[iface*Nc+off]);CHKERRQ(ierr);
1155           ierr = PetscSectionGetFieldComponents(section, f, &comp);CHKERRQ(ierr);
1156           for(d = 0; d < comp; ++d) uLl[iface*Nc+off+d] = uRl[iface*Nc+off+d];
1157         }
1158         ierr = DMPlexVecRestoreClosure(dm, section, locX, cells[0], &ldof, (PetscScalar **) &xL);CHKERRQ(ierr);
1159         ierr = DMPlexVecRestoreClosure(dm, section, locX, cells[1], &rdof, (PetscScalar **) &xR);CHKERRQ(ierr);
1160       } else {
1161         PetscFV  fv;
1162         PetscInt numComp, c;
1163 
1164         ierr = PetscDSGetDiscretization(prob, f, (PetscObject *) &fv);CHKERRQ(ierr);
1165         ierr = PetscFVGetNumComponents(fv, &numComp);CHKERRQ(ierr);
1166         ierr = DMPlexPointLocalFieldRead(dm, cells[0], f, x, &xL);CHKERRQ(ierr);
1167         ierr = DMPlexPointLocalFieldRead(dm, cells[1], f, x, &xR);CHKERRQ(ierr);
1168         if (dmGrad) {
1169           PetscReal dxL[3], dxR[3];
1170 
1171           ierr = DMPlexPointLocalRead(dmGrad, cells[0], lgrad, &gL);CHKERRQ(ierr);
1172           ierr = DMPlexPointLocalRead(dmGrad, cells[1], lgrad, &gR);CHKERRQ(ierr);
1173           DMPlex_WaxpyD_Internal(dim, -1, cgL->centroid, fg->centroid, dxL);
1174           DMPlex_WaxpyD_Internal(dim, -1, cgR->centroid, fg->centroid, dxR);
1175           for (c = 0; c < numComp; ++c) {
1176             uLl[iface*Nc+off+c] = xL[c] + DMPlex_DotD_Internal(dim, &gL[c*dim], dxL);
1177             uRl[iface*Nc+off+c] = xR[c] + DMPlex_DotD_Internal(dim, &gR[c*dim], dxR);
1178           }
1179         } else {
1180           for (c = 0; c < numComp; ++c) {
1181             uLl[iface*Nc+off+c] = xL[c];
1182             uRl[iface*Nc+off+c] = xR[c];
1183           }
1184         }
1185       }
1186     }
1187     ++iface;
1188   }
1189   *Nface = iface;
1190   ierr = VecRestoreArrayRead(locX, &x);CHKERRQ(ierr);
1191   ierr = VecRestoreArrayRead(faceGeometry, &facegeom);CHKERRQ(ierr);
1192   ierr = VecRestoreArrayRead(cellGeometry, &cellgeom);CHKERRQ(ierr);
1193   if (locGrad) {
1194     ierr = VecRestoreArrayRead(locGrad, &lgrad);CHKERRQ(ierr);
1195   }
1196   ierr = PetscFree(isFE);CHKERRQ(ierr);
1197   PetscFunctionReturn(0);
1198 }
1199 
1200 /*@C
1201   DMPlexRestoreFaceFields - Restore the field values values for a chunk of faces
1202 
1203   Input Parameters:
1204 + dm     - The DM
1205 . fStart - The first face to include
1206 . fEnd   - The first face to exclude
1207 . locX   - A local vector with the solution fields
1208 . locX_t - A local vector with solution field time derivatives, or NULL
1209 . faceGeometry - A local vector with face geometry
1210 . cellGeometry - A local vector with cell geometry
1211 - locaGrad - A local vector with field gradients, or NULL
1212 
1213   Output Parameters:
1214 + Nface - The number of faces with field values
1215 . uL - The field values at the left side of the face
1216 - uR - The field values at the right side of the face
1217 
1218   Level: developer
1219 
1220 .seealso: DMPlexGetFaceFields()
1221 @*/
1222 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)
1223 {
1224   PetscErrorCode ierr;
1225 
1226   PetscFunctionBegin;
1227   ierr = DMRestoreWorkArray(dm, 0, MPIU_SCALAR, uL);CHKERRQ(ierr);
1228   ierr = DMRestoreWorkArray(dm, 0, MPIU_SCALAR, uR);CHKERRQ(ierr);
1229   PetscFunctionReturn(0);
1230 }
1231 
1232 /*@C
1233   DMPlexGetFaceGeometry - Retrieve the geometric values for a chunk of faces
1234 
1235   Input Parameters:
1236 + dm     - The DM
1237 . fStart - The first face to include
1238 . fEnd   - The first face to exclude
1239 . faceGeometry - A local vector with face geometry
1240 - cellGeometry - A local vector with cell geometry
1241 
1242   Output Parameters:
1243 + Nface - The number of faces with field values
1244 . fgeom - The extract the face centroid and normal
1245 - vol   - The cell volume
1246 
1247   Level: developer
1248 
1249 .seealso: DMPlexGetCellFields()
1250 @*/
1251 PetscErrorCode DMPlexGetFaceGeometry(DM dm, PetscInt fStart, PetscInt fEnd, Vec faceGeometry, Vec cellGeometry, PetscInt *Nface, PetscFVFaceGeom **fgeom, PetscReal **vol)
1252 {
1253   DM                 dmFace, dmCell;
1254   DMLabel            ghostLabel;
1255   const PetscScalar *facegeom, *cellgeom;
1256   PetscInt           dim, numFaces = fEnd - fStart, iface, face;
1257   PetscErrorCode     ierr;
1258 
1259   PetscFunctionBegin;
1260   PetscValidHeaderSpecific(dm, DM_CLASSID, 1);
1261   PetscValidHeaderSpecific(faceGeometry, VEC_CLASSID, 4);
1262   PetscValidHeaderSpecific(cellGeometry, VEC_CLASSID, 5);
1263   PetscValidPointer(fgeom, 6);
1264   PetscValidPointer(vol, 7);
1265   ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
1266   ierr = DMGetLabel(dm, "ghost", &ghostLabel);CHKERRQ(ierr);
1267   ierr = VecGetDM(faceGeometry, &dmFace);CHKERRQ(ierr);
1268   ierr = VecGetArrayRead(faceGeometry, &facegeom);CHKERRQ(ierr);
1269   ierr = VecGetDM(cellGeometry, &dmCell);CHKERRQ(ierr);
1270   ierr = VecGetArrayRead(cellGeometry, &cellgeom);CHKERRQ(ierr);
1271   ierr = PetscMalloc1(numFaces, fgeom);CHKERRQ(ierr);
1272   ierr = DMGetWorkArray(dm, numFaces*2, MPIU_SCALAR, vol);CHKERRQ(ierr);
1273   for (face = fStart, iface = 0; face < fEnd; ++face) {
1274     const PetscInt        *cells;
1275     PetscFVFaceGeom       *fg;
1276     PetscFVCellGeom       *cgL, *cgR;
1277     PetscFVFaceGeom       *fgeoml = *fgeom;
1278     PetscReal             *voll   = *vol;
1279     PetscInt               ghost, d, nchild, nsupp;
1280 
1281     ierr = DMLabelGetValue(ghostLabel, face, &ghost);CHKERRQ(ierr);
1282     ierr = DMPlexGetSupportSize(dm, face, &nsupp);CHKERRQ(ierr);
1283     ierr = DMPlexGetTreeChildren(dm, face, &nchild, NULL);CHKERRQ(ierr);
1284     if (ghost >= 0 || nsupp > 2 || nchild > 0) continue;
1285     ierr = DMPlexPointLocalRead(dmFace, face, facegeom, &fg);CHKERRQ(ierr);
1286     ierr = DMPlexGetSupport(dm, face, &cells);CHKERRQ(ierr);
1287     ierr = DMPlexPointLocalRead(dmCell, cells[0], cellgeom, &cgL);CHKERRQ(ierr);
1288     ierr = DMPlexPointLocalRead(dmCell, cells[1], cellgeom, &cgR);CHKERRQ(ierr);
1289     for (d = 0; d < dim; ++d) {
1290       fgeoml[iface].centroid[d] = fg->centroid[d];
1291       fgeoml[iface].normal[d]   = fg->normal[d];
1292     }
1293     voll[iface*2+0] = cgL->volume;
1294     voll[iface*2+1] = cgR->volume;
1295     ++iface;
1296   }
1297   *Nface = iface;
1298   ierr = VecRestoreArrayRead(faceGeometry, &facegeom);CHKERRQ(ierr);
1299   ierr = VecRestoreArrayRead(cellGeometry, &cellgeom);CHKERRQ(ierr);
1300   PetscFunctionReturn(0);
1301 }
1302 
1303 /*@C
1304   DMPlexRestoreFaceGeometry - Restore the field values values for a chunk of faces
1305 
1306   Input Parameters:
1307 + dm     - The DM
1308 . fStart - The first face to include
1309 . fEnd   - The first face to exclude
1310 . faceGeometry - A local vector with face geometry
1311 - cellGeometry - A local vector with cell geometry
1312 
1313   Output Parameters:
1314 + Nface - The number of faces with field values
1315 . fgeom - The extract the face centroid and normal
1316 - vol   - The cell volume
1317 
1318   Level: developer
1319 
1320 .seealso: DMPlexGetFaceFields()
1321 @*/
1322 PetscErrorCode DMPlexRestoreFaceGeometry(DM dm, PetscInt fStart, PetscInt fEnd, Vec faceGeometry, Vec cellGeometry, PetscInt *Nface, PetscFVFaceGeom **fgeom, PetscReal **vol)
1323 {
1324   PetscErrorCode ierr;
1325 
1326   PetscFunctionBegin;
1327   ierr = PetscFree(*fgeom);CHKERRQ(ierr);
1328   ierr = DMRestoreWorkArray(dm, 0, MPIU_REAL, vol);CHKERRQ(ierr);
1329   PetscFunctionReturn(0);
1330 }
1331 
1332 static PetscErrorCode ISIntersect_Caching(IS is1, IS is2, IS *isect)
1333 {
1334   PetscErrorCode ierr;
1335 
1336   PetscFunctionBegin;
1337   *isect = NULL;
1338   if (is2 && is1) {
1339     char           composeStr[33] = {0};
1340     PetscObjectId  is2id;
1341 
1342     ierr = PetscObjectGetId((PetscObject)is2,&is2id);CHKERRQ(ierr);
1343     ierr = PetscSNPrintf(composeStr,32,"ISIntersect_Caching_%x",is2id);CHKERRQ(ierr);
1344     ierr = PetscObjectQuery((PetscObject) is1, composeStr, (PetscObject *) isect);CHKERRQ(ierr);
1345     if (*isect == NULL) {
1346       ierr = ISIntersect(is1, is2, isect);CHKERRQ(ierr);
1347       ierr = PetscObjectCompose((PetscObject) is1, composeStr, (PetscObject) *isect);CHKERRQ(ierr);
1348     } else {
1349       ierr = PetscObjectReference((PetscObject) *isect);CHKERRQ(ierr);
1350     }
1351   }
1352   PetscFunctionReturn(0);
1353 }
1354 
1355 static PetscErrorCode DMPlexComputeBdResidual_Single_Internal(DM dm, PetscReal t, DMLabel label, PetscInt numValues, const PetscInt values[], PetscInt field, Vec locX, Vec locX_t, Vec locF, DMField coordField, IS facetIS)
1356 {
1357   DM_Plex         *mesh = (DM_Plex *) dm->data;
1358   DM               plex = NULL, plexA = NULL;
1359   PetscDS          prob, probAux = NULL;
1360   PetscSection     section, sectionAux = NULL;
1361   Vec              locA = NULL;
1362   PetscFEGeom     *fgeom;
1363   PetscScalar     *u = NULL, *u_t = NULL, *a = NULL, *elemVec = NULL;
1364   PetscInt         v;
1365   PetscInt         totDim, totDimAux = 0;
1366   PetscErrorCode   ierr;
1367 
1368   PetscFunctionBegin;
1369   ierr = DMConvert(dm, DMPLEX, &plex);CHKERRQ(ierr);
1370   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
1371   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
1372   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
1373   ierr = PetscObjectQuery((PetscObject) dm, "A", (PetscObject *) &locA);CHKERRQ(ierr);
1374   if (locA) {
1375     DM dmAux;
1376 
1377     ierr = VecGetDM(locA, &dmAux);CHKERRQ(ierr);
1378     ierr = DMConvert(dmAux, DMPLEX, &plexA);CHKERRQ(ierr);
1379     ierr = DMGetDS(plexA, &probAux);CHKERRQ(ierr);
1380     ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);
1381     ierr = DMGetDefaultSection(plexA, &sectionAux);CHKERRQ(ierr);
1382   }
1383   for (v = 0; v < numValues; ++v) {
1384     PetscBool        isAffine;
1385     PetscQuadrature  qGeom = NULL;
1386     IS               pointIS;
1387     const PetscInt  *points;
1388     PetscInt         numFaces, face, Nq;
1389 
1390     ierr = DMLabelGetStratumIS(label, values[v], &pointIS);CHKERRQ(ierr);
1391     if (!pointIS) continue; /* No points with that id on this process */
1392     {
1393       IS isectIS;
1394 
1395       /* TODO: Special cases of ISIntersect where it is quick to check a priori if one is a superset of the other */
1396       ierr = ISIntersect_Caching(facetIS,pointIS,&isectIS);CHKERRQ(ierr);
1397       ierr = ISDestroy(&pointIS);CHKERRQ(ierr);
1398       pointIS = isectIS;
1399     }
1400     ierr = ISGetLocalSize(pointIS,&numFaces);CHKERRQ(ierr);
1401     ierr = ISGetIndices(pointIS,&points);CHKERRQ(ierr);
1402     ierr = PetscMalloc4(numFaces*totDim, &u, locX_t ? numFaces*totDim : 0, &u_t, numFaces*totDim, &elemVec, locA ? numFaces*totDimAux : 0, &a);CHKERRQ(ierr);
1403     ierr = DMFieldGetFEInvariance(coordField,pointIS,NULL,&isAffine,NULL);CHKERRQ(ierr);
1404     if (isAffine) {
1405       ierr = DMFieldCreateDefaultQuadrature(coordField,pointIS,&qGeom);CHKERRQ(ierr);
1406     }
1407     if (!qGeom) {
1408       PetscFE fe;
1409 
1410       ierr = PetscDSGetDiscretization(prob, field, (PetscObject *) &fe);CHKERRQ(ierr);
1411       ierr = PetscFEGetFaceQuadrature(fe, &qGeom);CHKERRQ(ierr);
1412       ierr = PetscObjectReference((PetscObject)qGeom);CHKERRQ(ierr);
1413     }
1414     ierr = PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL);CHKERRQ(ierr);
1415     ierr = DMSNESGetFEGeom(coordField,pointIS,qGeom,PETSC_TRUE,&fgeom);CHKERRQ(ierr);
1416     for (face = 0; face < numFaces; ++face) {
1417       const PetscInt point = points[face], *support, *cone;
1418       PetscScalar   *x     = NULL;
1419       PetscInt       i, coneSize, faceLoc;
1420 
1421       ierr = DMPlexGetSupport(dm, point, &support);CHKERRQ(ierr);
1422       ierr = DMPlexGetConeSize(dm, support[0], &coneSize);CHKERRQ(ierr);
1423       ierr = DMPlexGetCone(dm, support[0], &cone);CHKERRQ(ierr);
1424       for (faceLoc = 0; faceLoc < coneSize; ++faceLoc) if (cone[faceLoc] == point) break;
1425       if (faceLoc == coneSize) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Could not find face %D in cone of support[0] %D", point, support[0]);
1426       fgeom->face[face][0] = faceLoc;
1427       ierr = DMPlexVecGetClosure(dm, section, locX, support[0], NULL, &x);CHKERRQ(ierr);
1428       for (i = 0; i < totDim; ++i) u[face*totDim+i] = x[i];
1429       ierr = DMPlexVecRestoreClosure(plex, section, locX, support[0], NULL, &x);CHKERRQ(ierr);
1430       if (locX_t) {
1431         ierr = DMPlexVecGetClosure(plex, section, locX_t, support[0], NULL, &x);CHKERRQ(ierr);
1432         for (i = 0; i < totDim; ++i) u_t[face*totDim+i] = x[i];
1433         ierr = DMPlexVecRestoreClosure(plex, section, locX_t, support[0], NULL, &x);CHKERRQ(ierr);
1434       }
1435       if (locA) {
1436         PetscInt subp;
1437         ierr = DMPlexGetSubpoint(plexA, support[0], &subp);CHKERRQ(ierr);
1438         ierr = DMPlexVecGetClosure(plexA, sectionAux, locA, subp, NULL, &x);CHKERRQ(ierr);
1439         for (i = 0; i < totDimAux; ++i) a[face*totDimAux+i] = x[i];
1440         ierr = DMPlexVecRestoreClosure(plexA, sectionAux, locA, subp, NULL, &x);CHKERRQ(ierr);
1441       }
1442     }
1443     ierr = PetscMemzero(elemVec, numFaces*totDim * sizeof(PetscScalar));CHKERRQ(ierr);
1444     {
1445       PetscFE         fe;
1446       PetscInt        Nb;
1447       PetscFEGeom     *chunkGeom = NULL;
1448       /* Conforming batches */
1449       PetscInt        numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
1450       /* Remainder */
1451       PetscInt        Nr, offset;
1452 
1453       ierr = PetscDSGetDiscretization(prob, field, (PetscObject *) &fe);CHKERRQ(ierr);
1454       ierr = PetscFEGetDimension(fe, &Nb);CHKERRQ(ierr);
1455       ierr = PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches);CHKERRQ(ierr);
1456       /* TODO: documentation is unclear about what is going on with these numbers: how should Nb / Nq factor in ? */
1457       blockSize = Nb;
1458       batchSize = numBlocks * blockSize;
1459       ierr =  PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches);CHKERRQ(ierr);
1460       numChunks = numFaces / (numBatches*batchSize);
1461       Ne        = numChunks*numBatches*batchSize;
1462       Nr        = numFaces % (numBatches*batchSize);
1463       offset    = numFaces - Nr;
1464       ierr = PetscFEGeomGetChunk(fgeom,0,offset,&chunkGeom);CHKERRQ(ierr);
1465       ierr = PetscFEIntegrateBdResidual(fe, prob, field, Ne, chunkGeom, u, u_t, probAux, a, t, elemVec);CHKERRQ(ierr);
1466       ierr = PetscFEGeomGetChunk(fgeom,offset,numFaces,&chunkGeom);CHKERRQ(ierr);
1467       ierr = PetscFEIntegrateBdResidual(fe, prob, field, Nr, chunkGeom, &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, a ? &a[offset*totDimAux] : NULL, t, &elemVec[offset*totDim]);CHKERRQ(ierr);
1468       ierr = PetscFEGeomRestoreChunk(fgeom,offset,numFaces,&chunkGeom);CHKERRQ(ierr);
1469     }
1470     for (face = 0; face < numFaces; ++face) {
1471       const PetscInt point = points[face], *support;
1472 
1473       if (mesh->printFEM > 1) {ierr = DMPrintCellVector(point, "BdResidual", totDim, &elemVec[face*totDim]);CHKERRQ(ierr);}
1474       ierr = DMPlexGetSupport(plex, point, &support);CHKERRQ(ierr);
1475       ierr = DMPlexVecSetClosure(plex, NULL, locF, support[0], &elemVec[face*totDim], ADD_ALL_VALUES);CHKERRQ(ierr);
1476     }
1477     ierr = DMSNESRestoreFEGeom(coordField,pointIS,qGeom,PETSC_TRUE,&fgeom);CHKERRQ(ierr);
1478     ierr = PetscQuadratureDestroy(&qGeom);CHKERRQ(ierr);
1479     ierr = ISRestoreIndices(pointIS, &points);CHKERRQ(ierr);
1480     ierr = ISDestroy(&pointIS);CHKERRQ(ierr);
1481     ierr = PetscFree4(u, u_t, elemVec, a);CHKERRQ(ierr);
1482   }
1483   if (plex)  {ierr = DMDestroy(&plex);CHKERRQ(ierr);}
1484   if (plexA) {ierr = DMDestroy(&plexA);CHKERRQ(ierr);}
1485   PetscFunctionReturn(0);
1486 }
1487 
1488 PetscErrorCode DMPlexComputeBdResidualSingle(DM dm, PetscReal t, DMLabel label, PetscInt numValues, const PetscInt values[], PetscInt field, Vec locX, Vec locX_t, Vec locF)
1489 {
1490   DMField        coordField;
1491   DMLabel        depthLabel;
1492   IS             facetIS;
1493   PetscInt       dim;
1494   PetscErrorCode ierr;
1495 
1496   PetscFunctionBegin;
1497   ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
1498   ierr = DMPlexGetDepthLabel(dm, &depthLabel);CHKERRQ(ierr);
1499   ierr = DMLabelGetStratumIS(depthLabel, dim-1, &facetIS);CHKERRQ(ierr);
1500   ierr = DMGetCoordinateField(dm, &coordField);CHKERRQ(ierr);
1501   ierr = DMPlexComputeBdResidual_Single_Internal(dm, t, label, numValues, values, field, locX, locX_t, locF, coordField, facetIS);CHKERRQ(ierr);
1502   PetscFunctionReturn(0);
1503 }
1504 
1505 PetscErrorCode DMPlexComputeBdResidual_Internal(DM dm, Vec locX, Vec locX_t, PetscReal t, Vec locF, void *user)
1506 {
1507   PetscDS        prob;
1508   PetscInt       dim, numBd, bd;
1509   DMLabel        depthLabel;
1510   DMField        coordField = NULL;
1511   IS             facetIS;
1512   PetscErrorCode ierr;
1513 
1514   PetscFunctionBegin;
1515   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
1516   ierr = DMPlexGetDepthLabel(dm, &depthLabel);CHKERRQ(ierr);
1517   ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
1518   ierr = DMLabelGetStratumIS(depthLabel,dim - 1,&facetIS);CHKERRQ(ierr);
1519   ierr = PetscDSGetNumBoundary(prob, &numBd);CHKERRQ(ierr);
1520   ierr = DMGetCoordinateField(dm, &coordField);CHKERRQ(ierr);
1521   for (bd = 0; bd < numBd; ++bd) {
1522     DMBoundaryConditionType type;
1523     const char             *bdLabel;
1524     DMLabel                 label;
1525     const PetscInt         *values;
1526     PetscInt                field, numValues;
1527     PetscObject             obj;
1528     PetscClassId            id;
1529 
1530     ierr = PetscDSGetBoundary(prob, bd, &type, NULL, &bdLabel, &field, NULL, NULL, NULL, &numValues, &values, NULL);CHKERRQ(ierr);
1531     ierr = PetscDSGetDiscretization(prob, field, &obj);CHKERRQ(ierr);
1532     ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
1533     if ((id != PETSCFE_CLASSID) || (type & DM_BC_ESSENTIAL)) continue;
1534     ierr = DMGetLabel(dm, bdLabel, &label);CHKERRQ(ierr);
1535     ierr = DMPlexComputeBdResidual_Single_Internal(dm, t, label, numValues, values, field, locX, locX_t, locF, coordField, facetIS);CHKERRQ(ierr);
1536   }
1537   ierr = ISDestroy(&facetIS);CHKERRQ(ierr);
1538   PetscFunctionReturn(0);
1539 }
1540 
1541 PetscErrorCode DMPlexComputeResidual_Internal(DM dm, IS cellIS, PetscReal time, Vec locX, Vec locX_t, PetscReal t, Vec locF, void *user)
1542 {
1543   DM_Plex         *mesh       = (DM_Plex *) dm->data;
1544   const char      *name       = "Residual";
1545   DM               dmAux      = NULL;
1546   DM               dmGrad     = NULL;
1547   DMLabel          ghostLabel = NULL;
1548   PetscDS          prob       = NULL;
1549   PetscDS          probAux    = NULL;
1550   PetscSection     section    = NULL;
1551   PetscBool        useFEM     = PETSC_FALSE;
1552   PetscBool        useFVM     = PETSC_FALSE;
1553   PetscBool        isImplicit = (locX_t || time == PETSC_MIN_REAL) ? PETSC_TRUE : PETSC_FALSE;
1554   PetscFV          fvm        = NULL;
1555   PetscFVCellGeom *cgeomFVM   = NULL;
1556   PetscFVFaceGeom *fgeomFVM   = NULL;
1557   DMField          coordField = NULL;
1558   Vec              locA, cellGeometryFVM = NULL, faceGeometryFVM = NULL, grad, locGrad = NULL;
1559   PetscScalar     *u = NULL, *u_t, *a, *uL, *uR;
1560   IS               chunkIS;
1561   const PetscInt  *cells;
1562   PetscInt         cStart, cEnd, numCells;
1563   PetscInt         Nf, f, totDim, totDimAux, numChunks, cellChunkSize, faceChunkSize, chunk, fStart, fEnd;
1564   PetscBool        isAffine = PETSC_FALSE;
1565   PetscQuadrature  affineQuad = NULL, *quads = NULL;
1566   PetscFEGeom     *affineGeom = NULL, **geoms = NULL;
1567   PetscErrorCode   ierr;
1568 
1569   PetscFunctionBegin;
1570   ierr = PetscLogEventBegin(DMPLEX_ResidualFEM,dm,0,0,0);CHKERRQ(ierr);
1571   /* TODO The places where we have to use isFE are probably the member functions for the PetscDisc class */
1572   /* TODO The FVM geometry is over-manipulated. Make the precalc functions return exactly what we need */
1573   /* FEM+FVM */
1574   /* 1: Get sizes from dm and dmAux */
1575   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
1576   ierr = DMGetLabel(dm, "ghost", &ghostLabel);CHKERRQ(ierr);
1577   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
1578   ierr = PetscDSGetNumFields(prob, &Nf);CHKERRQ(ierr);
1579   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
1580   ierr = PetscObjectQuery((PetscObject) dm, "A", (PetscObject *) &locA);CHKERRQ(ierr);
1581   if (locA) {
1582     ierr = VecGetDM(locA, &dmAux);CHKERRQ(ierr);
1583     ierr = DMGetDS(dmAux, &probAux);CHKERRQ(ierr);
1584     ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);
1585   }
1586   /* 2: Get geometric data */
1587   for (f = 0; f < Nf; ++f) {
1588     PetscObject  obj;
1589     PetscClassId id;
1590     PetscBool    fimp;
1591 
1592     ierr = PetscDSGetImplicit(prob, f, &fimp);CHKERRQ(ierr);
1593     if (isImplicit != fimp) continue;
1594     ierr = PetscDSGetDiscretization(prob, f, &obj);CHKERRQ(ierr);
1595     ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
1596     if (id == PETSCFE_CLASSID) {useFEM = PETSC_TRUE;}
1597     if (id == PETSCFV_CLASSID) {useFVM = PETSC_TRUE; fvm = (PetscFV) obj;}
1598   }
1599   if (useFEM) {
1600     ierr = DMGetCoordinateField(dm, &coordField);CHKERRQ(ierr);
1601     ierr = DMFieldGetFEInvariance(coordField,cellIS,NULL,&isAffine,NULL);CHKERRQ(ierr);
1602     if (isAffine) {
1603       ierr = DMFieldCreateDefaultQuadrature(coordField,cellIS,&affineQuad);CHKERRQ(ierr);
1604       if (affineQuad) {
1605         ierr = DMSNESGetFEGeom(coordField,cellIS,affineQuad,PETSC_FALSE,&affineGeom);CHKERRQ(ierr);
1606       }
1607     } else {
1608       ierr = PetscCalloc2(Nf,&quads,Nf,&geoms);CHKERRQ(ierr);
1609       for (f = 0; f < Nf; ++f) {
1610         PetscObject  obj;
1611         PetscClassId id;
1612         PetscBool    fimp;
1613 
1614         ierr = PetscDSGetImplicit(prob, f, &fimp);CHKERRQ(ierr);
1615         if (isImplicit != fimp) continue;
1616         ierr = PetscDSGetDiscretization(prob, f, &obj);CHKERRQ(ierr);
1617         ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
1618         if (id == PETSCFE_CLASSID) {
1619           PetscFE fe = (PetscFE) obj;
1620 
1621           ierr = PetscFEGetQuadrature(fe, &quads[f]);CHKERRQ(ierr);
1622           ierr = PetscObjectReference((PetscObject)quads[f]);CHKERRQ(ierr);
1623           ierr = DMSNESGetFEGeom(coordField,cellIS,quads[f],PETSC_FALSE,&geoms[f]);CHKERRQ(ierr);
1624         }
1625       }
1626     }
1627   }
1628   if (useFVM) {
1629     ierr = DMPlexSNESGetGeometryFVM(dm, &faceGeometryFVM, &cellGeometryFVM, NULL);CHKERRQ(ierr);
1630     ierr = VecGetArrayRead(faceGeometryFVM, (const PetscScalar **) &fgeomFVM);CHKERRQ(ierr);
1631     ierr = VecGetArrayRead(cellGeometryFVM, (const PetscScalar **) &cgeomFVM);CHKERRQ(ierr);
1632     /* Reconstruct and limit cell gradients */
1633     ierr = DMPlexSNESGetGradientDM(dm, fvm, &dmGrad);CHKERRQ(ierr);
1634     if (dmGrad) {
1635       ierr = DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd);CHKERRQ(ierr);
1636       ierr = DMGetGlobalVector(dmGrad, &grad);CHKERRQ(ierr);
1637       ierr = DMPlexReconstructGradients_Internal(dm, fvm, fStart, fEnd, faceGeometryFVM, cellGeometryFVM, locX, grad);CHKERRQ(ierr);
1638       /* Communicate gradient values */
1639       ierr = DMGetLocalVector(dmGrad, &locGrad);CHKERRQ(ierr);
1640       ierr = DMGlobalToLocalBegin(dmGrad, grad, INSERT_VALUES, locGrad);CHKERRQ(ierr);
1641       ierr = DMGlobalToLocalEnd(dmGrad, grad, INSERT_VALUES, locGrad);CHKERRQ(ierr);
1642       ierr = DMRestoreGlobalVector(dmGrad, &grad);CHKERRQ(ierr);
1643     }
1644     /* Handle non-essential (e.g. outflow) boundary values */
1645     ierr = DMPlexInsertBoundaryValues(dm, PETSC_FALSE, locX, time, faceGeometryFVM, cellGeometryFVM, locGrad);CHKERRQ(ierr);
1646   }
1647   /* Loop over chunks */
1648   ierr = ISGetPointRange(cellIS, &cStart, &cEnd, &cells);CHKERRQ(ierr);
1649   ierr = DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd);CHKERRQ(ierr);
1650   if (useFEM) {ierr = ISCreate(PETSC_COMM_SELF, &chunkIS);CHKERRQ(ierr);}
1651   numCells      = cEnd - cStart;
1652   numChunks     = 1;
1653   cellChunkSize = numCells/numChunks;
1654   faceChunkSize = (fEnd - fStart)/numChunks;
1655   numChunks     = PetscMin(1,numCells);
1656   for (chunk = 0; chunk < numChunks; ++chunk) {
1657     PetscScalar     *elemVec, *fluxL, *fluxR;
1658     PetscReal       *vol;
1659     PetscFVFaceGeom *fgeom;
1660     PetscInt         cS = cStart+chunk*cellChunkSize, cE = PetscMin(cS+cellChunkSize, cEnd), numCells = cE - cS, c;
1661     PetscInt         fS = fStart+chunk*faceChunkSize, fE = PetscMin(fS+faceChunkSize, fEnd), numFaces = 0, face;
1662 
1663     /* Extract field coefficients */
1664     if (useFEM) {
1665       ierr = ISGetPointSubrange(chunkIS, cS, cE, cells);CHKERRQ(ierr);
1666       ierr = DMPlexGetCellFields(dm, chunkIS, locX, locX_t, locA, &u, &u_t, &a);CHKERRQ(ierr);
1667       ierr = DMGetWorkArray(dm, numCells*totDim, MPIU_SCALAR, &elemVec);CHKERRQ(ierr);
1668       ierr = PetscMemzero(elemVec, numCells*totDim * sizeof(PetscScalar));CHKERRQ(ierr);
1669     }
1670     if (useFVM) {
1671       ierr = DMPlexGetFaceFields(dm, fS, fE, locX, locX_t, faceGeometryFVM, cellGeometryFVM, locGrad, &numFaces, &uL, &uR);CHKERRQ(ierr);
1672       ierr = DMPlexGetFaceGeometry(dm, fS, fE, faceGeometryFVM, cellGeometryFVM, &numFaces, &fgeom, &vol);CHKERRQ(ierr);
1673       ierr = DMGetWorkArray(dm, numFaces*totDim, MPIU_SCALAR, &fluxL);CHKERRQ(ierr);
1674       ierr = DMGetWorkArray(dm, numFaces*totDim, MPIU_SCALAR, &fluxR);CHKERRQ(ierr);
1675       ierr = PetscMemzero(fluxL, numFaces*totDim * sizeof(PetscScalar));CHKERRQ(ierr);
1676       ierr = PetscMemzero(fluxR, numFaces*totDim * sizeof(PetscScalar));CHKERRQ(ierr);
1677     }
1678     /* TODO We will interlace both our field coefficients (u, u_t, uL, uR, etc.) and our output (elemVec, fL, fR). I think this works */
1679     /* Loop over fields */
1680     for (f = 0; f < Nf; ++f) {
1681       PetscObject  obj;
1682       PetscClassId id;
1683       PetscBool    fimp;
1684       PetscInt     numChunks, numBatches, batchSize, numBlocks, blockSize, Ne, Nr, offset;
1685 
1686       ierr = PetscDSGetImplicit(prob, f, &fimp);CHKERRQ(ierr);
1687       if (isImplicit != fimp) continue;
1688       ierr = PetscDSGetDiscretization(prob, f, &obj);CHKERRQ(ierr);
1689       ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
1690       if (id == PETSCFE_CLASSID) {
1691         PetscFE         fe = (PetscFE) obj;
1692         PetscFEGeom    *geom = affineGeom ? affineGeom : geoms[f];
1693         PetscFEGeom    *chunkGeom = NULL;
1694         PetscQuadrature quad = affineQuad ? affineQuad : quads[f];
1695         PetscInt        Nq, Nb;
1696 
1697         ierr = PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches);CHKERRQ(ierr);
1698         ierr = PetscQuadratureGetData(quad, NULL, NULL, &Nq, NULL, NULL);CHKERRQ(ierr);
1699         ierr = PetscFEGetDimension(fe, &Nb);CHKERRQ(ierr);
1700         blockSize = Nb;
1701         batchSize = numBlocks * blockSize;
1702         ierr      = PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches);CHKERRQ(ierr);
1703         numChunks = numCells / (numBatches*batchSize);
1704         Ne        = numChunks*numBatches*batchSize;
1705         Nr        = numCells % (numBatches*batchSize);
1706         offset    = numCells - Nr;
1707         /* Integrate FE residual to get elemVec (need fields at quadrature points) */
1708         /*   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) */
1709         ierr = PetscFEGeomGetChunk(geom,0,offset,&chunkGeom);CHKERRQ(ierr);
1710         ierr = PetscFEIntegrateResidual(fe, prob, f, Ne, chunkGeom, u, u_t, probAux, a, t, elemVec);CHKERRQ(ierr);
1711         ierr = PetscFEGeomGetChunk(geom,offset,numCells,&chunkGeom);CHKERRQ(ierr);
1712         ierr = PetscFEIntegrateResidual(fe, prob, f, Nr, chunkGeom, &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, &elemVec[offset*totDim]);CHKERRQ(ierr);
1713         ierr = PetscFEGeomRestoreChunk(geom,offset,numCells,&chunkGeom);CHKERRQ(ierr);
1714       } else if (id == PETSCFV_CLASSID) {
1715         PetscFV fv = (PetscFV) obj;
1716 
1717         Ne = numFaces;
1718         /* Riemann solve over faces (need fields at face centroids) */
1719         /*   We need to evaluate FE fields at those coordinates */
1720         ierr = PetscFVIntegrateRHSFunction(fv, prob, f, Ne, fgeom, vol, uL, uR, fluxL, fluxR);CHKERRQ(ierr);
1721       } else SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, "Unknown discretization type for field %d", f);
1722     }
1723     /* Loop over domain */
1724     if (useFEM) {
1725       /* Add elemVec to locX */
1726       for (c = cS; c < cE; ++c) {
1727         const PetscInt cell = cells ? cells[c] : c;
1728         const PetscInt cind = c - cStart;
1729 
1730         if (mesh->printFEM > 1) {ierr = DMPrintCellVector(cell, name, totDim, &elemVec[cind*totDim]);CHKERRQ(ierr);}
1731         if (ghostLabel) {
1732           PetscInt ghostVal;
1733 
1734           ierr = DMLabelGetValue(ghostLabel,cell,&ghostVal);CHKERRQ(ierr);
1735           if (ghostVal > 0) continue;
1736         }
1737         ierr = DMPlexVecSetClosure(dm, section, locF, cell, &elemVec[cind*totDim], ADD_ALL_VALUES);CHKERRQ(ierr);
1738       }
1739     }
1740     if (useFVM) {
1741       PetscScalar *fa;
1742       PetscInt     iface;
1743 
1744       ierr = VecGetArray(locF, &fa);CHKERRQ(ierr);
1745       for (f = 0; f < Nf; ++f) {
1746         PetscFV      fv;
1747         PetscObject  obj;
1748         PetscClassId id;
1749         PetscInt     foff, pdim;
1750 
1751         ierr = PetscDSGetDiscretization(prob, f, &obj);CHKERRQ(ierr);
1752         ierr = PetscDSGetFieldOffset(prob, f, &foff);CHKERRQ(ierr);
1753         ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
1754         if (id != PETSCFV_CLASSID) continue;
1755         fv   = (PetscFV) obj;
1756         ierr = PetscFVGetNumComponents(fv, &pdim);CHKERRQ(ierr);
1757         /* Accumulate fluxes to cells */
1758         for (face = fS, iface = 0; face < fE; ++face) {
1759           const PetscInt *scells;
1760           PetscScalar    *fL = NULL, *fR = NULL;
1761           PetscInt        ghost, d, nsupp, nchild;
1762 
1763           ierr = DMLabelGetValue(ghostLabel, face, &ghost);CHKERRQ(ierr);
1764           ierr = DMPlexGetSupportSize(dm, face, &nsupp);CHKERRQ(ierr);
1765           ierr = DMPlexGetTreeChildren(dm, face, &nchild, NULL);CHKERRQ(ierr);
1766           if (ghost >= 0 || nsupp > 2 || nchild > 0) continue;
1767           ierr = DMPlexGetSupport(dm, face, &scells);CHKERRQ(ierr);
1768           ierr = DMLabelGetValue(ghostLabel,scells[0],&ghost);CHKERRQ(ierr);
1769           if (ghost <= 0) {ierr = DMPlexPointLocalFieldRef(dm, scells[0], f, fa, &fL);CHKERRQ(ierr);}
1770           ierr = DMLabelGetValue(ghostLabel,scells[1],&ghost);CHKERRQ(ierr);
1771           if (ghost <= 0) {ierr = DMPlexPointLocalFieldRef(dm, scells[1], f, fa, &fR);CHKERRQ(ierr);}
1772           for (d = 0; d < pdim; ++d) {
1773             if (fL) fL[d] -= fluxL[iface*totDim+foff+d];
1774             if (fR) fR[d] += fluxR[iface*totDim+foff+d];
1775           }
1776           ++iface;
1777         }
1778       }
1779       ierr = VecRestoreArray(locF, &fa);CHKERRQ(ierr);
1780     }
1781     /* Handle time derivative */
1782     if (locX_t) {
1783       PetscScalar *x_t, *fa;
1784 
1785       ierr = VecGetArray(locF, &fa);CHKERRQ(ierr);
1786       ierr = VecGetArray(locX_t, &x_t);CHKERRQ(ierr);
1787       for (f = 0; f < Nf; ++f) {
1788         PetscFV      fv;
1789         PetscObject  obj;
1790         PetscClassId id;
1791         PetscInt     pdim, d;
1792 
1793         ierr = PetscDSGetDiscretization(prob, f, &obj);CHKERRQ(ierr);
1794         ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
1795         if (id != PETSCFV_CLASSID) continue;
1796         fv   = (PetscFV) obj;
1797         ierr = PetscFVGetNumComponents(fv, &pdim);CHKERRQ(ierr);
1798         for (c = cS; c < cE; ++c) {
1799           const PetscInt cell = cells ? cells[c] : c;
1800           PetscScalar   *u_t, *r;
1801 
1802           if (ghostLabel) {
1803             PetscInt ghostVal;
1804 
1805             ierr = DMLabelGetValue(ghostLabel, cell, &ghostVal);CHKERRQ(ierr);
1806             if (ghostVal > 0) continue;
1807           }
1808           ierr = DMPlexPointLocalFieldRead(dm, cell, f, x_t, &u_t);CHKERRQ(ierr);
1809           ierr = DMPlexPointLocalFieldRef(dm, cell, f, fa, &r);CHKERRQ(ierr);
1810           for (d = 0; d < pdim; ++d) r[d] += u_t[d];
1811         }
1812       }
1813       ierr = VecRestoreArray(locX_t, &x_t);CHKERRQ(ierr);
1814       ierr = VecRestoreArray(locF, &fa);CHKERRQ(ierr);
1815     }
1816     if (useFEM) {
1817       ierr = DMPlexRestoreCellFields(dm, chunkIS, locX, locX_t, locA, &u, &u_t, &a);CHKERRQ(ierr);
1818       ierr = DMRestoreWorkArray(dm, numCells*totDim, MPIU_SCALAR, &elemVec);CHKERRQ(ierr);
1819     }
1820     if (useFVM) {
1821       ierr = DMPlexRestoreFaceFields(dm, fS, fE, locX, locX_t, faceGeometryFVM, cellGeometryFVM, locGrad, &numFaces, &uL, &uR);CHKERRQ(ierr);
1822       ierr = DMPlexRestoreFaceGeometry(dm, fS, fE, faceGeometryFVM, cellGeometryFVM, &numFaces, &fgeom, &vol);CHKERRQ(ierr);
1823       ierr = DMRestoreWorkArray(dm, numFaces*totDim, MPIU_SCALAR, &fluxL);CHKERRQ(ierr);
1824       ierr = DMRestoreWorkArray(dm, numFaces*totDim, MPIU_SCALAR, &fluxR);CHKERRQ(ierr);
1825       if (dmGrad) {ierr = DMRestoreLocalVector(dmGrad, &locGrad);CHKERRQ(ierr);}
1826     }
1827   }
1828   if (useFEM) {ierr = ISDestroy(&chunkIS);CHKERRQ(ierr);}
1829   ierr = ISRestorePointRange(cellIS, &cStart, &cEnd, &cells);CHKERRQ(ierr);
1830 
1831   if (useFEM) {
1832     ierr = DMPlexComputeBdResidual_Internal(dm, locX, locX_t, t, locF, user);CHKERRQ(ierr);
1833 
1834     if (isAffine) {
1835       ierr = DMSNESRestoreFEGeom(coordField,cellIS,affineQuad,PETSC_FALSE,&affineGeom);CHKERRQ(ierr);
1836       ierr = PetscQuadratureDestroy(&affineQuad);CHKERRQ(ierr);
1837     } else {
1838       for (f = 0; f < Nf; ++f) {
1839         ierr = DMSNESRestoreFEGeom(coordField,cellIS,quads[f],PETSC_FALSE,&geoms[f]);CHKERRQ(ierr);
1840         ierr = PetscQuadratureDestroy(&quads[f]);CHKERRQ(ierr);
1841       }
1842       ierr = PetscFree2(quads,geoms);CHKERRQ(ierr);
1843     }
1844   }
1845 
1846   /* FEM */
1847   /* 1: Get sizes from dm and dmAux */
1848   /* 2: Get geometric data */
1849   /* 3: Handle boundary values */
1850   /* 4: Loop over domain */
1851   /*   Extract coefficients */
1852   /* Loop over fields */
1853   /*   Set tiling for FE*/
1854   /*   Integrate FE residual to get elemVec */
1855   /*     Loop over subdomain */
1856   /*       Loop over quad points */
1857   /*         Transform coords to real space */
1858   /*         Evaluate field and aux fields at point */
1859   /*         Evaluate residual at point */
1860   /*         Transform residual to real space */
1861   /*       Add residual to elemVec */
1862   /* Loop over domain */
1863   /*   Add elemVec to locX */
1864 
1865   /* FVM */
1866   /* Get geometric data */
1867   /* If using gradients */
1868   /*   Compute gradient data */
1869   /*   Loop over domain faces */
1870   /*     Count computational faces */
1871   /*     Reconstruct cell gradient */
1872   /*   Loop over domain cells */
1873   /*     Limit cell gradients */
1874   /* Handle boundary values */
1875   /* Loop over domain faces */
1876   /*   Read out field, centroid, normal, volume for each side of face */
1877   /* Riemann solve over faces */
1878   /* Loop over domain faces */
1879   /*   Accumulate fluxes to cells */
1880   /* TODO Change printFEM to printDisc here */
1881   if (mesh->printFEM) {
1882     Vec         locFbc;
1883     PetscInt    pStart, pEnd, p, maxDof;
1884     PetscScalar *zeroes;
1885 
1886     ierr = VecDuplicate(locF,&locFbc);CHKERRQ(ierr);
1887     ierr = VecCopy(locF,locFbc);CHKERRQ(ierr);
1888     ierr = PetscSectionGetChart(section,&pStart,&pEnd);CHKERRQ(ierr);
1889     ierr = PetscSectionGetMaxDof(section,&maxDof);CHKERRQ(ierr);
1890     ierr = PetscCalloc1(maxDof,&zeroes);CHKERRQ(ierr);
1891     for (p = pStart; p < pEnd; p++) {
1892       ierr = VecSetValuesSection(locFbc,section,p,zeroes,INSERT_BC_VALUES);CHKERRQ(ierr);
1893     }
1894     ierr = PetscFree(zeroes);CHKERRQ(ierr);
1895     ierr = DMPrintLocalVec(dm, name, mesh->printTol, locFbc);CHKERRQ(ierr);
1896     ierr = VecDestroy(&locFbc);CHKERRQ(ierr);
1897   }
1898   ierr = PetscLogEventEnd(DMPLEX_ResidualFEM,dm,0,0,0);CHKERRQ(ierr);
1899   PetscFunctionReturn(0);
1900 }
1901 
1902 static PetscErrorCode DMPlexComputeResidualFEM_Check_Internal(DM dm, Vec X, Vec X_t, PetscReal t, Vec F, void *user)
1903 {
1904   DM                dmCh, dmAux;
1905   Vec               A;
1906   DMField           coordField = NULL;
1907   PetscDS           prob, probCh, probAux = NULL;
1908   PetscSection      section, sectionAux;
1909   PetscScalar      *elemVec, *elemVecCh, *u, *u_t, *a = NULL;
1910   PetscInt          Nf, f, numCells, cStart, cEnd, c;
1911   PetscInt          totDim, totDimAux = 0, diffCell = 0;
1912   PetscInt          depth;
1913   PetscBool         isAffine;
1914   IS                cellIS;
1915   DMLabel           depthLabel;
1916   PetscErrorCode    ierr;
1917 
1918   PetscFunctionBegin;
1919   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
1920   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
1921   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
1922   ierr = PetscSectionGetNumFields(section, &Nf);CHKERRQ(ierr);
1923   ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);
1924   numCells = cEnd - cStart;
1925   ierr = PetscObjectQuery((PetscObject) dm, "dmCh", (PetscObject *) &dmCh);CHKERRQ(ierr);
1926   ierr = DMGetDS(dmCh, &probCh);CHKERRQ(ierr);
1927   ierr = PetscObjectQuery((PetscObject) dm, "dmAux", (PetscObject *) &dmAux);CHKERRQ(ierr);
1928   ierr = PetscObjectQuery((PetscObject) dm, "A", (PetscObject *) &A);CHKERRQ(ierr);
1929   if (dmAux) {
1930     ierr = DMGetDefaultSection(dmAux, &sectionAux);CHKERRQ(ierr);
1931     ierr = DMGetDS(dmAux, &probAux);CHKERRQ(ierr);
1932     ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);
1933   }
1934   ierr = VecSet(F, 0.0);CHKERRQ(ierr);
1935   ierr = PetscMalloc3(numCells*totDim,&u,X_t ? numCells*totDim : 0,&u_t,numCells*totDim,&elemVec);CHKERRQ(ierr);
1936   ierr = PetscMalloc1(numCells*totDim,&elemVecCh);CHKERRQ(ierr);
1937   if (dmAux) {ierr = PetscMalloc1(numCells*totDimAux, &a);CHKERRQ(ierr);}
1938   ierr = DMPlexGetDepthLabel(dm, &depthLabel);CHKERRQ(ierr);
1939   ierr = DMPlexGetDepth(dm,&depth);CHKERRQ(ierr);
1940   ierr = DMLabelGetStratumIS(depthLabel,depth,&cellIS);CHKERRQ(ierr);
1941   ierr = DMGetCoordinateField(dm, &coordField);CHKERRQ(ierr);
1942   for (c = cStart; c < cEnd; ++c) {
1943     PetscScalar *x = NULL, *x_t = NULL;
1944     PetscInt     i;
1945 
1946     ierr = DMPlexVecGetClosure(dm, section, X, c, NULL, &x);CHKERRQ(ierr);
1947     for (i = 0; i < totDim; ++i) u[c*totDim+i] = x[i];
1948     ierr = DMPlexVecRestoreClosure(dm, section, X, c, NULL, &x);CHKERRQ(ierr);
1949     if (X_t) {
1950       ierr = DMPlexVecGetClosure(dm, section, X_t, c, NULL, &x_t);CHKERRQ(ierr);
1951       for (i = 0; i < totDim; ++i) u_t[c*totDim+i] = x_t[i];
1952       ierr = DMPlexVecRestoreClosure(dm, section, X_t, c, NULL, &x_t);CHKERRQ(ierr);
1953     }
1954     if (dmAux) {
1955       DM dmAuxPlex;
1956 
1957       ierr = DMSNESConvertPlex(dmAux,&dmAuxPlex, PETSC_FALSE);CHKERRQ(ierr);
1958       ierr = DMPlexVecGetClosure(dmAuxPlex, sectionAux, A, c, NULL, &x);CHKERRQ(ierr);
1959       for (i = 0; i < totDimAux; ++i) a[c*totDimAux+i] = x[i];
1960       ierr = DMPlexVecRestoreClosure(dmAuxPlex, sectionAux, A, c, NULL, &x);CHKERRQ(ierr);
1961       ierr = DMDestroy(&dmAuxPlex);CHKERRQ(ierr);
1962     }
1963   }
1964   for (f = 0; f < Nf; ++f) {
1965     PetscFE  fe, feCh;
1966     PetscInt Nq, Nb;
1967     /* Conforming batches */
1968     PetscInt numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
1969     /* Remainder */
1970     PetscInt Nr, offset;
1971     PetscQuadrature qGeom = NULL;
1972     PetscFEGeom *cgeomFEM, *chunkGeom = NULL;
1973 
1974     ierr = PetscDSGetDiscretization(prob, f, (PetscObject *) &fe);CHKERRQ(ierr);
1975     ierr = PetscDSGetDiscretization(probCh, f, (PetscObject *) &feCh);CHKERRQ(ierr);
1976     ierr = PetscFEGetDimension(fe, &Nb);CHKERRQ(ierr);
1977     ierr = PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches);CHKERRQ(ierr);
1978     ierr = DMFieldGetFEInvariance(coordField,cellIS,NULL,&isAffine,NULL);CHKERRQ(ierr);
1979     if (isAffine) {
1980       ierr = DMFieldCreateDefaultQuadrature(coordField,cellIS,&qGeom);CHKERRQ(ierr);
1981     }
1982     if (!qGeom) {
1983       ierr = PetscFEGetQuadrature(fe, &qGeom);CHKERRQ(ierr);
1984       ierr = PetscObjectReference((PetscObject)qGeom);CHKERRQ(ierr);
1985     }
1986     ierr = PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL);CHKERRQ(ierr);
1987     ierr = DMSNESGetFEGeom(coordField,cellIS,qGeom,PETSC_FALSE,&cgeomFEM);CHKERRQ(ierr);
1988     blockSize = Nb;
1989     batchSize = numBlocks * blockSize;
1990     ierr =  PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches);CHKERRQ(ierr);
1991     numChunks = numCells / (numBatches*batchSize);
1992     Ne        = numChunks*numBatches*batchSize;
1993     Nr        = numCells % (numBatches*batchSize);
1994     offset    = numCells - Nr;
1995     ierr = PetscFEGeomGetChunk(cgeomFEM,0,offset,&chunkGeom);CHKERRQ(ierr);
1996     ierr = PetscFEIntegrateResidual(fe, prob, f, Ne, chunkGeom, u, u_t, probAux, a, t, elemVec);CHKERRQ(ierr);
1997     ierr = PetscFEIntegrateResidual(feCh, prob, f, Ne, chunkGeom, u, u_t, probAux, a, t, elemVecCh);CHKERRQ(ierr);
1998     ierr = PetscFEGeomGetChunk(cgeomFEM,offset,numCells,&chunkGeom);CHKERRQ(ierr);
1999     ierr = PetscFEIntegrateResidual(fe, prob, f, Nr, chunkGeom, &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, &elemVec[offset*totDim]);CHKERRQ(ierr);
2000     ierr = PetscFEIntegrateResidual(feCh, prob, f, Nr, chunkGeom, &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, &elemVecCh[offset*totDim]);CHKERRQ(ierr);
2001     ierr = PetscFEGeomRestoreChunk(cgeomFEM,offset,numCells,&chunkGeom);CHKERRQ(ierr);
2002     ierr = DMSNESRestoreFEGeom(coordField,cellIS,qGeom,PETSC_FALSE,&cgeomFEM);CHKERRQ(ierr);
2003     ierr = PetscQuadratureDestroy(&qGeom);CHKERRQ(ierr);
2004   }
2005   ierr = ISDestroy(&cellIS);CHKERRQ(ierr);
2006   for (c = cStart; c < cEnd; ++c) {
2007     PetscBool diff = PETSC_FALSE;
2008     PetscInt  d;
2009 
2010     for (d = 0; d < totDim; ++d) if (PetscAbsScalar(elemVec[c*totDim+d] - elemVecCh[c*totDim+d]) > 1.0e-7) {diff = PETSC_TRUE;break;}
2011     if (diff) {
2012       ierr = PetscPrintf(PetscObjectComm((PetscObject) dm), "Different cell %d\n", c);CHKERRQ(ierr);
2013       ierr = DMPrintCellVector(c, "Residual", totDim, &elemVec[c*totDim]);CHKERRQ(ierr);
2014       ierr = DMPrintCellVector(c, "Check Residual", totDim, &elemVecCh[c*totDim]);CHKERRQ(ierr);
2015       ++diffCell;
2016     }
2017     if (diffCell > 9) break;
2018     ierr = DMPlexVecSetClosure(dm, section, F, c, &elemVec[c*totDim], ADD_ALL_VALUES);CHKERRQ(ierr);
2019   }
2020   ierr = PetscFree3(u,u_t,elemVec);CHKERRQ(ierr);
2021   ierr = PetscFree(elemVecCh);CHKERRQ(ierr);
2022   if (dmAux) {ierr = PetscFree(a);CHKERRQ(ierr);}
2023   PetscFunctionReturn(0);
2024 }
2025 
2026 /*@
2027   DMPlexSNESComputeResidualFEM - Form the local residual F from the local input X using pointwise functions specified by the user
2028 
2029   Input Parameters:
2030 + dm - The mesh
2031 . X  - Local solution
2032 - user - The user context
2033 
2034   Output Parameter:
2035 . F  - Local output vector
2036 
2037   Level: developer
2038 
2039 .seealso: DMPlexComputeJacobianAction()
2040 @*/
2041 PetscErrorCode DMPlexSNESComputeResidualFEM(DM dm, Vec X, Vec F, void *user)
2042 {
2043   PetscObject    check;
2044   DM             plex;
2045   IS             cellIS;
2046   PetscInt       depth;
2047   PetscErrorCode ierr;
2048 
2049   PetscFunctionBegin;
2050   ierr = DMSNESConvertPlex(dm,&plex,PETSC_TRUE);CHKERRQ(ierr);
2051   ierr = DMPlexGetDepth(plex, &depth);CHKERRQ(ierr);
2052   ierr = DMGetStratumIS(plex, "dim", depth, &cellIS);CHKERRQ(ierr);
2053   if (!cellIS) {
2054     ierr = DMGetStratumIS(plex, "depth", depth, &cellIS);CHKERRQ(ierr);
2055   }
2056   /* The dmCh is used to check two mathematically equivalent discretizations for computational equivalence */
2057   ierr = PetscObjectQuery((PetscObject) plex, "dmCh", &check);CHKERRQ(ierr);
2058   if (check) {ierr = DMPlexComputeResidualFEM_Check_Internal(plex, X, NULL, 0.0, F, user);CHKERRQ(ierr);}
2059   else       {ierr = DMPlexComputeResidual_Internal(plex, cellIS, PETSC_MIN_REAL, X, NULL, 0.0, F, user);CHKERRQ(ierr);}
2060   ierr = ISDestroy(&cellIS);CHKERRQ(ierr);
2061   ierr = DMDestroy(&plex);CHKERRQ(ierr);
2062   PetscFunctionReturn(0);
2063 }
2064 
2065 /*@
2066   DMPlexSNESComputeBoundaryFEM - Form the boundary values for the local input X
2067 
2068   Input Parameters:
2069 + dm - The mesh
2070 - user - The user context
2071 
2072   Output Parameter:
2073 . X  - Local solution
2074 
2075   Level: developer
2076 
2077 .seealso: DMPlexComputeJacobianAction()
2078 @*/
2079 PetscErrorCode DMPlexSNESComputeBoundaryFEM(DM dm, Vec X, void *user)
2080 {
2081   DM             plex;
2082   PetscErrorCode ierr;
2083 
2084   PetscFunctionBegin;
2085   ierr = DMSNESConvertPlex(dm,&plex,PETSC_TRUE);CHKERRQ(ierr);
2086   ierr = DMPlexInsertBoundaryValues(plex, PETSC_TRUE, X, PETSC_MIN_REAL, NULL, NULL, NULL);CHKERRQ(ierr);
2087   ierr = DMDestroy(&plex);CHKERRQ(ierr);
2088   PetscFunctionReturn(0);
2089 }
2090 
2091 PetscErrorCode DMPlexComputeBdJacobian_Internal(DM dm, Vec locX, Vec locX_t, PetscReal t, PetscReal X_tShift, Mat Jac, Mat JacP, void *user)
2092 {
2093   DM_Plex         *mesh = (DM_Plex *) dm->data;
2094   DM               dmAux = NULL, plex = NULL;
2095   DMField          coordField = NULL;
2096   PetscSection     section, globalSection, subSection, sectionAux = NULL;
2097   PetscDS          prob, probAux = NULL;
2098   DMLabel          depth;
2099   Vec              locA = NULL;
2100   PetscScalar     *u = NULL, *u_t = NULL, *a = NULL, *elemMat = NULL;
2101   PetscInt         dim, totDim, totDimAux, numBd, bd, Nf;
2102   PetscBool        isMatISP;
2103   IS               facetIS;
2104   PetscErrorCode   ierr;
2105 
2106   PetscFunctionBegin;
2107   ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
2108   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
2109   ierr = PetscObjectTypeCompare((PetscObject) JacP, MATIS, &isMatISP);CHKERRQ(ierr);
2110   ierr = DMGetDefaultGlobalSection(dm, &globalSection);CHKERRQ(ierr);
2111   if (isMatISP) {
2112     ierr = DMPlexGetSubdomainSection(dm, &subSection);CHKERRQ(ierr);
2113   }
2114   ierr = DMPlexGetDepthLabel(dm, &depth);CHKERRQ(ierr);
2115   ierr = DMLabelGetStratumIS(depth,dim-1,&facetIS);CHKERRQ(ierr);
2116   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
2117   ierr = PetscDSGetNumFields(prob, &Nf);CHKERRQ(ierr);
2118   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
2119   ierr = PetscDSGetNumBoundary(prob, &numBd);CHKERRQ(ierr);
2120   ierr = PetscObjectQuery((PetscObject) dm, "A", (PetscObject *) &locA);CHKERRQ(ierr);
2121   if (locA) {
2122     ierr = VecGetDM(locA, &dmAux);CHKERRQ(ierr);
2123     ierr = DMConvert(dmAux, DMPLEX, &plex);CHKERRQ(ierr);
2124     ierr = DMGetDefaultSection(plex, &sectionAux);CHKERRQ(ierr);
2125     ierr = DMGetDS(dmAux, &probAux);CHKERRQ(ierr);
2126     ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);
2127   }
2128   ierr = DMGetCoordinateField(dm, &coordField);CHKERRQ(ierr);
2129   for (bd = 0; bd < numBd; ++bd) {
2130     DMBoundaryConditionType type;
2131     const char             *bdLabel;
2132     DMLabel                 label;
2133     IS                      pointIS;
2134     const PetscInt         *points;
2135     const PetscInt         *values;
2136     PetscInt                fieldI, fieldJ, numValues, v, numFaces, face, Nq;
2137     PetscObject             obj;
2138     PetscBool               isAffine;
2139     PetscFE                 fe;
2140     PetscClassId            id;
2141 
2142     ierr = PetscDSGetBoundary(prob, bd, &type, NULL, &bdLabel, &fieldI, NULL, NULL, NULL, &numValues, &values, NULL);CHKERRQ(ierr);
2143     ierr = PetscDSGetDiscretization(prob, fieldI, &obj);CHKERRQ(ierr);
2144     ierr = PetscObjectGetClassId(obj, &id);CHKERRQ(ierr);
2145     if ((id != PETSCFE_CLASSID) || (type & DM_BC_ESSENTIAL)) continue;
2146     fe   = (PetscFE) obj;
2147     ierr = DMGetLabel(dm, bdLabel, &label);CHKERRQ(ierr);
2148     for (v = 0; v < numValues; ++v) {
2149       PetscQuadrature qGeom = NULL;
2150       PetscFEGeom     *fgeom;
2151 
2152       ierr = DMLabelGetStratumIS(label, values[v], &pointIS);CHKERRQ(ierr);
2153       if (!pointIS) continue; /* No points with that id on this process */
2154       {
2155         IS isectIS;
2156 
2157         /* TODO: Special cases of ISIntersect where it is quick to check a prior if one is a superset of the other */
2158         ierr = ISIntersect_Caching(facetIS,pointIS,&isectIS);CHKERRQ(ierr);
2159         ierr = ISDestroy(&pointIS);CHKERRQ(ierr);
2160         pointIS = isectIS;
2161       }
2162       ierr = ISGetLocalSize(pointIS, &numFaces);CHKERRQ(ierr);
2163       ierr = ISGetIndices(pointIS, &points);CHKERRQ(ierr);
2164       ierr = PetscMalloc3(numFaces*totDim,&u,locX_t ? numFaces*totDim : 0,&u_t,numFaces*totDim*totDim,&elemMat);CHKERRQ(ierr);
2165       if (locA) {ierr = PetscMalloc1(numFaces*totDimAux,&a);CHKERRQ(ierr);}
2166       ierr = DMFieldGetFEInvariance(coordField,pointIS,NULL,&isAffine,NULL);CHKERRQ(ierr);
2167       if (isAffine) {
2168         ierr = DMFieldCreateDefaultQuadrature(coordField,pointIS,&qGeom);CHKERRQ(ierr);
2169       }
2170       if (!qGeom) {
2171         ierr = PetscFEGetFaceQuadrature(fe, &qGeom);CHKERRQ(ierr);
2172         ierr = PetscObjectReference((PetscObject)qGeom);CHKERRQ(ierr);
2173       }
2174       ierr = PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL);CHKERRQ(ierr);
2175       ierr = DMSNESGetFEGeom(coordField,pointIS,qGeom,PETSC_TRUE,&fgeom);CHKERRQ(ierr);
2176       for (face = 0; face < numFaces; ++face) {
2177         const PetscInt point = points[face], *support, *cone;
2178         PetscScalar   *x     = NULL;
2179         PetscInt       i, coneSize, faceLoc;
2180 
2181         ierr = DMPlexGetSupport(dm, point, &support);CHKERRQ(ierr);
2182         ierr = DMPlexGetConeSize(dm, support[0], &coneSize);CHKERRQ(ierr);
2183         ierr = DMPlexGetCone(dm, support[0], &cone);CHKERRQ(ierr);
2184         for (faceLoc = 0; faceLoc < coneSize; ++faceLoc) if (cone[faceLoc] == point) break;
2185         if (faceLoc == coneSize) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Could not find face %d in cone of support[0] %d", point, support[0]);
2186         fgeom->face[face][0] = faceLoc;
2187         ierr = DMPlexVecGetClosure(dm, section, locX, support[0], NULL, &x);CHKERRQ(ierr);
2188         for (i = 0; i < totDim; ++i) u[face*totDim+i] = x[i];
2189         ierr = DMPlexVecRestoreClosure(dm, section, locX, support[0], NULL, &x);CHKERRQ(ierr);
2190         if (locX_t) {
2191           ierr = DMPlexVecGetClosure(dm, section, locX_t, support[0], NULL, &x);CHKERRQ(ierr);
2192           for (i = 0; i < totDim; ++i) u_t[face*totDim+i] = x[i];
2193           ierr = DMPlexVecRestoreClosure(dm, section, locX_t, support[0], NULL, &x);CHKERRQ(ierr);
2194         }
2195         if (locA) {
2196           ierr = DMPlexVecGetClosure(plex, sectionAux, locA, support[0], NULL, &x);CHKERRQ(ierr);
2197           for (i = 0; i < totDimAux; ++i) a[face*totDimAux+i] = x[i];
2198           ierr = DMPlexVecRestoreClosure(plex, sectionAux, locA, support[0], NULL, &x);CHKERRQ(ierr);
2199         }
2200       }
2201       ierr = PetscMemzero(elemMat, numFaces*totDim*totDim * sizeof(PetscScalar));CHKERRQ(ierr);
2202       {
2203         PetscFE         fe;
2204         PetscInt        Nb;
2205         /* Conforming batches */
2206         PetscInt        numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
2207         /* Remainder */
2208         PetscFEGeom    *chunkGeom = NULL;
2209         PetscInt        Nr, offset;
2210 
2211         ierr = PetscDSGetDiscretization(prob, fieldI, (PetscObject *) &fe);CHKERRQ(ierr);
2212         ierr = PetscFEGetDimension(fe, &Nb);CHKERRQ(ierr);
2213         ierr = PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches);CHKERRQ(ierr);
2214         blockSize = Nb;
2215         batchSize = numBlocks * blockSize;
2216         ierr = PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches);CHKERRQ(ierr);
2217         numChunks = numFaces / (numBatches*batchSize);
2218         Ne        = numChunks*numBatches*batchSize;
2219         Nr        = numFaces % (numBatches*batchSize);
2220         offset    = numFaces - Nr;
2221         ierr = PetscFEGeomGetChunk(fgeom,0,offset,&chunkGeom);CHKERRQ(ierr);
2222         for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
2223           ierr = PetscFEIntegrateBdJacobian(fe, prob, fieldI, fieldJ, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMat);CHKERRQ(ierr);
2224         }
2225         ierr = PetscFEGeomGetChunk(fgeom,offset,numFaces,&chunkGeom);CHKERRQ(ierr);
2226         for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
2227           ierr = PetscFEIntegrateBdJacobian(fe, prob, fieldI, fieldJ, Nr, chunkGeom, &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);
2228         }
2229         ierr = PetscFEGeomRestoreChunk(fgeom,offset,numFaces,&chunkGeom);CHKERRQ(ierr);
2230       }
2231       for (face = 0; face < numFaces; ++face) {
2232         const PetscInt point = points[face], *support;
2233 
2234         if (mesh->printFEM > 1) {ierr = DMPrintCellMatrix(point, "BdJacobian", totDim, totDim, &elemMat[face*totDim*totDim]);CHKERRQ(ierr);}
2235         ierr = DMPlexGetSupport(dm, point, &support);CHKERRQ(ierr);
2236         if (!isMatISP) {
2237           ierr = DMPlexMatSetClosure(dm, section, globalSection, JacP, support[0], &elemMat[face*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2238         } else {
2239           Mat lJ;
2240 
2241           ierr = MatISGetLocalMat(JacP,&lJ);CHKERRQ(ierr);
2242           ierr = DMPlexMatSetClosure(dm, section, subSection, lJ, support[0], &elemMat[face*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2243         }
2244       }
2245       ierr = DMSNESRestoreFEGeom(coordField,pointIS,qGeom,PETSC_TRUE,&fgeom);CHKERRQ(ierr);
2246       ierr = PetscQuadratureDestroy(&qGeom);CHKERRQ(ierr);
2247       ierr = PetscFree3(u,u_t,elemMat);CHKERRQ(ierr);
2248       ierr = ISRestoreIndices(pointIS, &points);CHKERRQ(ierr);
2249       ierr = ISDestroy(&pointIS);CHKERRQ(ierr);
2250       if (locA) {ierr = PetscFree(a);CHKERRQ(ierr);}
2251     }
2252   }
2253   ierr = ISDestroy(&facetIS);CHKERRQ(ierr);
2254   if (plex) {ierr = DMDestroy(&plex);CHKERRQ(ierr);}
2255   PetscFunctionReturn(0);
2256 }
2257 
2258 /*
2259   We always assemble JacP, and if the matrix is different from Jac and two different sets of point functions are provided, we also assemble Jac
2260 
2261   X   - The local solution vector
2262   X_t - The local solution time derviative vector, or NULL
2263 */
2264 PetscErrorCode DMPlexComputeJacobian_Patch_Internal(DM dm, PetscSection section, PetscSection globalSection, IS cellIS,
2265                                                     PetscReal t, PetscReal X_tShift, Vec X, Vec X_t, Mat Jac, Mat JacP, void *ctx)
2266 {
2267   DM_Plex         *mesh  = (DM_Plex *) dm->data;
2268   const char      *name = "Jacobian", *nameP = "JacobianPre";
2269   DM               dmAux = NULL;
2270   PetscDS          prob,   probAux = NULL;
2271   PetscSection     sectionAux = NULL;
2272   Vec              A;
2273   DMField          coordField;
2274   PetscFEGeom     *cgeomFEM;
2275   PetscQuadrature  qGeom = NULL;
2276   Mat              J = Jac, JP = JacP;
2277   PetscScalar     *work, *u = NULL, *u_t = NULL, *a = NULL, *elemMat = NULL, *elemMatP = NULL, *elemMatD = NULL;
2278   PetscBool        hasJac, hasPrec, hasDyn, isAffine, assembleJac, isMatIS, isMatISP, *isFE, hasFV = PETSC_FALSE;
2279   const PetscInt  *cells;
2280   PetscInt         Nf, fieldI, fieldJ, numCells, cStart, cEnd, numChunks, chunkSize, chunk, totDim, totDimAux = 0, sz, wsz, off = 0, offCell = 0;
2281   PetscErrorCode   ierr;
2282 
2283   PetscFunctionBegin;
2284   CHKMEMQ;
2285   ierr = ISGetLocalSize(cellIS, &numCells);CHKERRQ(ierr);
2286   ierr = ISGetPointRange(cellIS, &cStart, &cEnd, &cells);CHKERRQ(ierr);
2287   ierr = PetscLogEventBegin(DMPLEX_JacobianFEM,dm,0,0,0);CHKERRQ(ierr);
2288   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
2289   ierr = PetscObjectQuery((PetscObject) dm, "dmAux", (PetscObject *) &dmAux);CHKERRQ(ierr);
2290   ierr = PetscObjectQuery((PetscObject) dm, "A", (PetscObject *) &A);CHKERRQ(ierr);
2291   if (dmAux) {
2292     ierr = DMGetDefaultSection(dmAux, &sectionAux);CHKERRQ(ierr);
2293     ierr = DMGetDS(dmAux, &probAux);CHKERRQ(ierr);
2294   }
2295   /* Get flags */
2296   ierr = PetscDSGetNumFields(prob, &Nf);CHKERRQ(ierr);
2297   ierr = DMGetWorkArray(dm, Nf, MPIU_BOOL, &isFE);CHKERRQ(ierr);
2298   for (fieldI = 0; fieldI < Nf; ++fieldI) {
2299     PetscObject  disc;
2300     PetscClassId id;
2301     ierr = PetscDSGetDiscretization(prob, fieldI, &disc);CHKERRQ(ierr);
2302     ierr = PetscObjectGetClassId(disc, &id);CHKERRQ(ierr);
2303     if (id == PETSCFE_CLASSID)      {isFE[fieldI] = PETSC_TRUE;}
2304     else if (id == PETSCFV_CLASSID) {hasFV = PETSC_TRUE; isFE[fieldI] = PETSC_FALSE;}
2305   }
2306   ierr = PetscDSHasJacobian(prob, &hasJac);CHKERRQ(ierr);
2307   ierr = PetscDSHasJacobianPreconditioner(prob, &hasPrec);CHKERRQ(ierr);
2308   ierr = PetscDSHasDynamicJacobian(prob, &hasDyn);CHKERRQ(ierr);
2309   assembleJac = hasJac && hasPrec && (Jac != JacP) ? PETSC_TRUE : PETSC_FALSE;
2310   hasDyn      = hasDyn && (X_tShift != 0.0) ? PETSC_TRUE : PETSC_FALSE;
2311   ierr = PetscObjectTypeCompare((PetscObject) Jac,  MATIS, &isMatIS);CHKERRQ(ierr);
2312   ierr = PetscObjectTypeCompare((PetscObject) JacP, MATIS, &isMatISP);CHKERRQ(ierr);
2313   /* Setup input data and temp arrays (should be DMGetWorkArray) */
2314   if (isMatISP || isMatISP) {ierr = DMPlexGetSubdomainSection(dm, &globalSection);CHKERRQ(ierr);}
2315   if (isMatIS)  {ierr = MatISGetLocalMat(Jac,  &J);CHKERRQ(ierr);}
2316   if (isMatISP) {ierr = MatISGetLocalMat(JacP, &JP);CHKERRQ(ierr);}
2317   if (hasFV)    {ierr = MatSetOption(JP, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE);CHKERRQ(ierr);} /* No allocated space for FV stuff, so ignore the zero entries */
2318   ierr = PetscObjectQuery((PetscObject) dm, "dmAux", (PetscObject *) &dmAux);CHKERRQ(ierr);
2319   ierr = PetscObjectQuery((PetscObject) dm, "A", (PetscObject *) &A);CHKERRQ(ierr);
2320   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
2321   if (probAux) {ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);}
2322   CHKMEMQ;
2323   /* Compute batch sizes */
2324   if (isFE[0]) {
2325     PetscFE         fe;
2326     PetscQuadrature q;
2327     PetscInt        numQuadPoints, numBatches, batchSize, numBlocks, blockSize, Nb;
2328 
2329     ierr = PetscDSGetDiscretization(prob, 0, (PetscObject *) &fe);CHKERRQ(ierr);
2330     ierr = PetscFEGetQuadrature(fe, &q);CHKERRQ(ierr);
2331     ierr = PetscQuadratureGetData(q, NULL, NULL, &numQuadPoints, NULL, NULL);CHKERRQ(ierr);
2332     ierr = PetscFEGetDimension(fe, &Nb);CHKERRQ(ierr);
2333     ierr = PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches);CHKERRQ(ierr);
2334     blockSize = Nb*numQuadPoints;
2335     batchSize = numBlocks  * blockSize;
2336     chunkSize = numBatches * batchSize;
2337     numChunks = numCells / chunkSize + numCells % chunkSize;
2338     ierr = PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches);CHKERRQ(ierr);
2339   } else {
2340     chunkSize = numCells;
2341     numChunks = 1;
2342   }
2343   /* Get work space */
2344   wsz  = (((X?1:0) + (X_t?1:0) + (dmAux?1:0))*totDim + ((hasJac?1:0) + (hasPrec?1:0) + (hasDyn?1:0))*totDim*totDim)*chunkSize;
2345   ierr = DMGetWorkArray(dm, wsz, MPIU_SCALAR, &work);CHKERRQ(ierr);
2346   ierr = PetscMemzero(work, wsz * sizeof(PetscScalar));CHKERRQ(ierr);
2347   off      = 0;
2348   u        = X       ? (sz = chunkSize*totDim,        off += sz, work+off-sz) : NULL;
2349   u_t      = X_t     ? (sz = chunkSize*totDim,        off += sz, work+off-sz) : NULL;
2350   a        = dmAux   ? (sz = chunkSize*totDimAux,     off += sz, work+off-sz) : NULL;
2351   elemMat  = hasJac  ? (sz = chunkSize*totDim*totDim, off += sz, work+off-sz) : NULL;
2352   elemMatP = hasPrec ? (sz = chunkSize*totDim*totDim, off += sz, work+off-sz) : NULL;
2353   elemMatD = hasDyn  ? (sz = chunkSize*totDim*totDim, off += sz, work+off-sz) : NULL;
2354   if (off != wsz) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Error is workspace size %D should be %D", off, wsz);
2355   /* Setup geometry */
2356   ierr = DMGetCoordinateField(dm, &coordField);CHKERRQ(ierr);
2357   ierr = DMFieldGetFEInvariance(coordField, cellIS, NULL, &isAffine, NULL);CHKERRQ(ierr);
2358   if (isAffine) {ierr = DMFieldCreateDefaultQuadrature(coordField, cellIS, &qGeom);CHKERRQ(ierr);}
2359   if (!qGeom) {
2360     PetscFE fe;
2361 
2362     ierr = PetscDSGetDiscretization(prob, 0, (PetscObject *) &fe);CHKERRQ(ierr);
2363     ierr = PetscFEGetQuadrature(fe, &qGeom);CHKERRQ(ierr);
2364     ierr = PetscObjectReference((PetscObject) qGeom);CHKERRQ(ierr);
2365   }
2366   ierr = DMSNESGetFEGeom(coordField, cellIS, qGeom, PETSC_FALSE, &cgeomFEM);CHKERRQ(ierr);
2367   /* Compute volume integrals */
2368   if (assembleJac) {ierr = MatZeroEntries(J);CHKERRQ(ierr);}
2369   ierr = MatZeroEntries(JP);CHKERRQ(ierr);
2370   for (chunk = 0; chunk < numChunks; ++chunk, offCell += chunkSize) {
2371     const PetscInt   Ncell = PetscMin(chunkSize, numCells - offCell);
2372     PetscInt         c;
2373 
2374     /* Extract values */
2375     for (c = 0; c < Ncell; ++c) {
2376       const PetscInt cell = cells ? cells[c+offCell] : c+offCell;
2377       PetscScalar   *x = NULL,  *x_t = NULL;
2378       PetscInt       i;
2379 
2380       if (X) {
2381         ierr = DMPlexVecGetClosure(dm, section, X, cell, NULL, &x);CHKERRQ(ierr);
2382         for (i = 0; i < totDim; ++i) u[c*totDim+i] = x[i];
2383         ierr = DMPlexVecRestoreClosure(dm, section, X, cell, NULL, &x);CHKERRQ(ierr);
2384       }
2385       if (X_t) {
2386         ierr = DMPlexVecGetClosure(dm, section, X_t, cell, NULL, &x_t);CHKERRQ(ierr);
2387         for (i = 0; i < totDim; ++i) u_t[c*totDim+i] = x_t[i];
2388         ierr = DMPlexVecRestoreClosure(dm, section, X_t, cell, NULL, &x_t);CHKERRQ(ierr);
2389       }
2390       if (dmAux) {
2391         ierr = DMPlexVecGetClosure(dmAux, sectionAux, A, cell, NULL, &x);CHKERRQ(ierr);
2392         for (i = 0; i < totDimAux; ++i) a[c*totDimAux+i] = x[i];
2393         ierr = DMPlexVecRestoreClosure(dmAux, sectionAux, A, cell, NULL, &x);CHKERRQ(ierr);
2394       }
2395     }
2396     CHKMEMQ;
2397     for (fieldI = 0; fieldI < Nf; ++fieldI) {
2398       PetscFE fe;
2399       ierr = PetscDSGetDiscretization(prob, fieldI, (PetscObject *) &fe);CHKERRQ(ierr);
2400       for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
2401         if (hasJac)  {ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN,     fieldI, fieldJ, Ncell, cgeomFEM, u, u_t, probAux, a, t, X_tShift, elemMat);CHKERRQ(ierr);}
2402         if (hasPrec) {ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN_PRE, fieldI, fieldJ, Ncell, cgeomFEM, u, u_t, probAux, a, t, X_tShift, elemMatP);CHKERRQ(ierr);}
2403         if (hasDyn)  {ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN_DYN, fieldI, fieldJ, Ncell, cgeomFEM, u, u_t, probAux, a, t, X_tShift, elemMatD);CHKERRQ(ierr);}
2404       }
2405       /* For finite volume, add the identity */
2406       if (!isFE[fieldI]) {
2407         PetscFV  fv;
2408         PetscInt eOffset = 0, Nc, fc, foff;
2409 
2410         ierr = PetscDSGetFieldOffset(prob, fieldI, &foff);CHKERRQ(ierr);
2411         ierr = PetscDSGetDiscretization(prob, fieldI, (PetscObject *) &fv);CHKERRQ(ierr);
2412         ierr = PetscFVGetNumComponents(fv, &Nc);CHKERRQ(ierr);
2413         for (c = 0; c < chunkSize; ++c, eOffset += totDim*totDim) {
2414           for (fc = 0; fc < Nc; ++fc) {
2415             const PetscInt i = foff + fc;
2416             if (hasJac)  {elemMat [eOffset+i*totDim+i] = 1.0;}
2417             if (hasPrec) {elemMatP[eOffset+i*totDim+i] = 1.0;}
2418           }
2419         }
2420       }
2421     }
2422     CHKMEMQ;
2423     /*   Add contribution from X_t */
2424     if (hasDyn) {for (c = 0; c < chunkSize*totDim*totDim; ++c) elemMat[c] += X_tShift*elemMatD[c];}
2425     /* Insert values into matrix */
2426     for (c = 0; c < Ncell; ++c) {
2427       const PetscInt cell = cells ? cells[c+offCell] : c+offCell;
2428       if (mesh->printFEM > 1) {
2429         if (hasJac)  {ierr = DMPrintCellMatrix(cell, name,  totDim, totDim, &elemMat[(c-cStart)*totDim*totDim]);CHKERRQ(ierr);}
2430         if (hasPrec) {ierr = DMPrintCellMatrix(cell, nameP, totDim, totDim, &elemMatP[(c-cStart)*totDim*totDim]);CHKERRQ(ierr);}
2431       }
2432       if (assembleJac) {ierr = DMPlexMatSetClosure(dm, section, globalSection, Jac, cell, &elemMat[(c-cStart)*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);}
2433       ierr = DMPlexMatSetClosure(dm, section, globalSection, JP, cell, &elemMat[(c-cStart)*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2434     }
2435     CHKMEMQ;
2436   }
2437   /* Cleanup */
2438   ierr = DMSNESRestoreFEGeom(coordField, cellIS, qGeom, PETSC_FALSE, &cgeomFEM);CHKERRQ(ierr);
2439   ierr = PetscQuadratureDestroy(&qGeom);CHKERRQ(ierr);
2440   if (hasFV) {ierr = MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_FALSE);CHKERRQ(ierr);}
2441   ierr = DMRestoreWorkArray(dm, Nf, MPIU_BOOL, &isFE);CHKERRQ(ierr);
2442   ierr = DMRestoreWorkArray(dm, ((1 + (X_t?1:0) + (dmAux?1:0))*totDim + ((hasJac?1:0) + (hasPrec?1:0) + (hasDyn?1:0))*totDim*totDim)*chunkSize, MPIU_SCALAR, &work);CHKERRQ(ierr);
2443   /* Compute boundary integrals */
2444   /* ierr = DMPlexComputeBdJacobian_Internal(dm, X, X_t, t, X_tShift, Jac, JacP, ctx);CHKERRQ(ierr); */
2445   /* Assemble matrix */
2446   if (assembleJac) {ierr = MatAssemblyBegin(Jac, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);ierr = MatAssemblyEnd(Jac, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);}
2447   ierr = MatAssemblyBegin(JacP, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);ierr = MatAssemblyEnd(JacP, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2448   ierr = PetscLogEventEnd(DMPLEX_JacobianFEM,dm,0,0,0);CHKERRQ(ierr);
2449   CHKMEMQ;
2450   PetscFunctionReturn(0);
2451 }
2452 
2453 PetscErrorCode DMPlexComputeJacobian_Internal(DM dm, IS cellIS, PetscReal t, PetscReal X_tShift, Vec X, Vec X_t, Mat Jac, Mat JacP,void *user)
2454 {
2455   DM_Plex        *mesh  = (DM_Plex *) dm->data;
2456   const char     *name  = "Jacobian";
2457   DM              dmAux, plex;
2458   Vec             A;
2459   DMField         coordField;
2460   PetscDS         prob, probAux = NULL;
2461   PetscSection    section, globalSection, subSection, sectionAux;
2462   PetscScalar    *elemMat, *elemMatP, *elemMatD, *u, *u_t, *a = NULL;
2463   const PetscInt *cells;
2464   PetscInt        Nf, fieldI, fieldJ;
2465   PetscInt        totDim, totDimAux, cStart, cEnd, numCells, c;
2466   PetscBool       isMatIS, isMatISP, hasJac, hasPrec, hasDyn, hasFV = PETSC_FALSE;
2467   PetscErrorCode  ierr;
2468 
2469   PetscFunctionBegin;
2470   ierr = PetscLogEventBegin(DMPLEX_JacobianFEM,dm,0,0,0);CHKERRQ(ierr);
2471   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
2472   ierr = PetscObjectTypeCompare((PetscObject) JacP, MATIS, &isMatISP);CHKERRQ(ierr);
2473   ierr = DMGetDefaultGlobalSection(dm, &globalSection);CHKERRQ(ierr);
2474   if (isMatISP) {ierr = DMPlexGetSubdomainSection(dm, &subSection);CHKERRQ(ierr);}
2475   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
2476   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
2477   ierr = PetscDSHasJacobian(prob, &hasJac);CHKERRQ(ierr);
2478   ierr = PetscDSHasJacobianPreconditioner(prob, &hasPrec);CHKERRQ(ierr);
2479   ierr = PetscDSHasDynamicJacobian(prob, &hasDyn);CHKERRQ(ierr);
2480   hasDyn = hasDyn && (X_tShift != 0.0) ? PETSC_TRUE : PETSC_FALSE;
2481   ierr = PetscSectionGetNumFields(section, &Nf);CHKERRQ(ierr);
2482   ierr = ISGetLocalSize(cellIS, &numCells);CHKERRQ(ierr);
2483   ierr = ISGetPointRange(cellIS, &cStart, &cEnd, &cells);CHKERRQ(ierr);
2484   ierr = PetscObjectQuery((PetscObject) dm, "dmAux", (PetscObject *) &dmAux);CHKERRQ(ierr);
2485   ierr = PetscObjectQuery((PetscObject) dm, "A", (PetscObject *) &A);CHKERRQ(ierr);
2486   if (dmAux) {
2487     ierr = DMConvert(dmAux, DMPLEX, &plex);CHKERRQ(ierr);
2488     ierr = DMGetDefaultSection(plex, &sectionAux);CHKERRQ(ierr);
2489     ierr = DMGetDS(dmAux, &probAux);CHKERRQ(ierr);
2490     ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);
2491   }
2492   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);
2493   if (dmAux) {ierr = PetscMalloc1(numCells*totDimAux, &a);CHKERRQ(ierr);}
2494   ierr = DMGetCoordinateField(dm, &coordField);CHKERRQ(ierr);
2495   for (c = cStart; c < cEnd; ++c) {
2496     const PetscInt cell = cells ? cells[c] : c;
2497     const PetscInt cind = c - cStart;
2498     PetscScalar   *x = NULL,  *x_t = NULL;
2499     PetscInt       i;
2500 
2501     ierr = DMPlexVecGetClosure(dm, section, X, cell, NULL, &x);CHKERRQ(ierr);
2502     for (i = 0; i < totDim; ++i) u[cind*totDim+i] = x[i];
2503     ierr = DMPlexVecRestoreClosure(dm, section, X, cell, NULL, &x);CHKERRQ(ierr);
2504     if (X_t) {
2505       ierr = DMPlexVecGetClosure(dm, section, X_t, cell, NULL, &x_t);CHKERRQ(ierr);
2506       for (i = 0; i < totDim; ++i) u_t[cind*totDim+i] = x_t[i];
2507       ierr = DMPlexVecRestoreClosure(dm, section, X_t, cell, NULL, &x_t);CHKERRQ(ierr);
2508     }
2509     if (dmAux) {
2510       ierr = DMPlexVecGetClosure(plex, sectionAux, A, cell, NULL, &x);CHKERRQ(ierr);
2511       for (i = 0; i < totDimAux; ++i) a[cind*totDimAux+i] = x[i];
2512       ierr = DMPlexVecRestoreClosure(plex, sectionAux, A, cell, NULL, &x);CHKERRQ(ierr);
2513     }
2514   }
2515   if (hasJac)  {ierr = PetscMemzero(elemMat,  numCells*totDim*totDim * sizeof(PetscScalar));CHKERRQ(ierr);}
2516   if (hasPrec) {ierr = PetscMemzero(elemMatP, numCells*totDim*totDim * sizeof(PetscScalar));CHKERRQ(ierr);}
2517   if (hasDyn)  {ierr = PetscMemzero(elemMatD, numCells*totDim*totDim * sizeof(PetscScalar));CHKERRQ(ierr);}
2518   for (fieldI = 0; fieldI < Nf; ++fieldI) {
2519     PetscClassId    id;
2520     PetscFE         fe;
2521     PetscQuadrature qGeom = NULL;
2522     PetscInt        Nb;
2523     /* Conforming batches */
2524     PetscInt        numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
2525     /* Remainder */
2526     PetscInt        Nr, offset, Nq;
2527     PetscBool       isAffine;
2528     PetscFEGeom     *cgeomFEM, *chunkGeom = NULL, *remGeom = NULL;
2529 
2530     ierr = PetscDSGetDiscretization(prob, fieldI, (PetscObject *) &fe);CHKERRQ(ierr);
2531     ierr = PetscObjectGetClassId((PetscObject) fe, &id);CHKERRQ(ierr);
2532     if (id == PETSCFV_CLASSID) {hasFV = PETSC_TRUE; continue;}
2533     ierr = PetscFEGetDimension(fe, &Nb);CHKERRQ(ierr);
2534     ierr = PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches);CHKERRQ(ierr);
2535     ierr = DMFieldGetFEInvariance(coordField,cellIS,NULL,&isAffine,NULL);CHKERRQ(ierr);
2536     if (isAffine) {
2537       ierr = DMFieldCreateDefaultQuadrature(coordField,cellIS,&qGeom);CHKERRQ(ierr);
2538     }
2539     if (!qGeom) {
2540       ierr = PetscFEGetQuadrature(fe,&qGeom);CHKERRQ(ierr);
2541       ierr = PetscObjectReference((PetscObject)qGeom);CHKERRQ(ierr);
2542     }
2543     ierr = PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL);CHKERRQ(ierr);
2544     ierr = DMSNESGetFEGeom(coordField,cellIS,qGeom,PETSC_FALSE,&cgeomFEM);CHKERRQ(ierr);
2545     blockSize = Nb;
2546     batchSize = numBlocks * blockSize;
2547     ierr = PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches);CHKERRQ(ierr);
2548     numChunks = numCells / (numBatches*batchSize);
2549     Ne        = numChunks*numBatches*batchSize;
2550     Nr        = numCells % (numBatches*batchSize);
2551     offset    = numCells - Nr;
2552     ierr = PetscFEGeomGetChunk(cgeomFEM,0,offset,&chunkGeom);CHKERRQ(ierr);
2553     ierr = PetscFEGeomGetChunk(cgeomFEM,offset,numCells,&remGeom);CHKERRQ(ierr);
2554     for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
2555       if (hasJac) {
2556         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN, fieldI, fieldJ, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMat);CHKERRQ(ierr);
2557         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN, fieldI, fieldJ, Nr, remGeom, &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, X_tShift, &elemMat[offset*totDim*totDim]);CHKERRQ(ierr);
2558       }
2559       if (hasPrec) {
2560         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN_PRE, fieldI, fieldJ, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMatP);CHKERRQ(ierr);
2561         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN_PRE, fieldI, fieldJ, Nr, remGeom, &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, X_tShift, &elemMatP[offset*totDim*totDim]);CHKERRQ(ierr);
2562       }
2563       if (hasDyn) {
2564         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN_DYN, fieldI, fieldJ, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMatD);CHKERRQ(ierr);
2565         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN_DYN, fieldI, fieldJ, Nr, remGeom, &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, X_tShift, &elemMatD[offset*totDim*totDim]);CHKERRQ(ierr);
2566       }
2567     }
2568     ierr = PetscFEGeomRestoreChunk(cgeomFEM,offset,numCells,&remGeom);CHKERRQ(ierr);
2569     ierr = PetscFEGeomRestoreChunk(cgeomFEM,0,offset,&chunkGeom);CHKERRQ(ierr);
2570     ierr = DMSNESRestoreFEGeom(coordField,cellIS,qGeom,PETSC_FALSE,&cgeomFEM);CHKERRQ(ierr);
2571     ierr = PetscQuadratureDestroy(&qGeom);CHKERRQ(ierr);
2572   }
2573   /*   Add contribution from X_t */
2574   if (hasDyn) {for (c = 0; c < numCells*totDim*totDim; ++c) elemMat[c] += X_tShift*elemMatD[c];}
2575   if (hasFV) {
2576     PetscClassId id;
2577     PetscFV      fv;
2578     PetscInt     offsetI, NcI, NbI = 1, fc, f;
2579 
2580     for (fieldI = 0; fieldI < Nf; ++fieldI) {
2581       ierr = PetscDSGetDiscretization(prob, fieldI, (PetscObject *) &fv);CHKERRQ(ierr);
2582       ierr = PetscDSGetFieldOffset(prob, fieldI, &offsetI);CHKERRQ(ierr);
2583       ierr = PetscObjectGetClassId((PetscObject) fv, &id);CHKERRQ(ierr);
2584       if (id != PETSCFV_CLASSID) continue;
2585       /* Put in the identity */
2586       ierr = PetscFVGetNumComponents(fv, &NcI);CHKERRQ(ierr);
2587       for (c = cStart; c < cEnd; ++c) {
2588         const PetscInt cind    = c - cStart;
2589         const PetscInt eOffset = cind*totDim*totDim;
2590         for (fc = 0; fc < NcI; ++fc) {
2591           for (f = 0; f < NbI; ++f) {
2592             const PetscInt i = offsetI + f*NcI+fc;
2593             if (hasPrec) {
2594               if (hasJac) {elemMat[eOffset+i*totDim+i] = 1.0;}
2595               elemMatP[eOffset+i*totDim+i] = 1.0;
2596             } else {elemMat[eOffset+i*totDim+i] = 1.0;}
2597           }
2598         }
2599       }
2600     }
2601     /* No allocated space for FV stuff, so ignore the zero entries */
2602     ierr = MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE);CHKERRQ(ierr);
2603   }
2604   /* Insert values into matrix */
2605   isMatIS = PETSC_FALSE;
2606   if (hasPrec && hasJac) {
2607     ierr = PetscObjectTypeCompare((PetscObject) JacP, MATIS, &isMatIS);CHKERRQ(ierr);
2608   }
2609   if (isMatIS && !subSection) {
2610     ierr = DMPlexGetSubdomainSection(dm, &subSection);CHKERRQ(ierr);
2611   }
2612   for (c = cStart; c < cEnd; ++c) {
2613     const PetscInt cell = cells ? cells[c] : c;
2614     const PetscInt cind = c - cStart;
2615 
2616     if (hasPrec) {
2617       if (hasJac) {
2618         if (mesh->printFEM > 1) {ierr = DMPrintCellMatrix(cell, name, totDim, totDim, &elemMat[cind*totDim*totDim]);CHKERRQ(ierr);}
2619         if (!isMatIS) {
2620           ierr = DMPlexMatSetClosure(dm, section, globalSection, Jac, cell, &elemMat[cind*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2621         } else {
2622           Mat lJ;
2623 
2624           ierr = MatISGetLocalMat(Jac,&lJ);CHKERRQ(ierr);
2625           ierr = DMPlexMatSetClosure(dm, section, subSection, lJ, cell, &elemMat[cind*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2626         }
2627       }
2628       if (mesh->printFEM > 1) {ierr = DMPrintCellMatrix(cell, name, totDim, totDim, &elemMatP[cind*totDim*totDim]);CHKERRQ(ierr);}
2629       if (!isMatISP) {
2630         ierr = DMPlexMatSetClosure(dm, section, globalSection, JacP, cell, &elemMatP[cind*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2631       } else {
2632         Mat lJ;
2633 
2634         ierr = MatISGetLocalMat(JacP,&lJ);CHKERRQ(ierr);
2635         ierr = DMPlexMatSetClosure(dm, section, subSection, lJ, cell, &elemMatP[cind*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2636       }
2637     } else {
2638       if (mesh->printFEM > 1) {ierr = DMPrintCellMatrix(cell, name, totDim, totDim, &elemMat[cind*totDim*totDim]);CHKERRQ(ierr);}
2639       if (!isMatISP) {
2640         ierr = DMPlexMatSetClosure(dm, section, globalSection, JacP, cell, &elemMat[cind*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2641       } else {
2642         Mat lJ;
2643 
2644         ierr = MatISGetLocalMat(JacP,&lJ);CHKERRQ(ierr);
2645         ierr = DMPlexMatSetClosure(dm, section, subSection, lJ, cell, &elemMat[cind*totDim*totDim], ADD_VALUES);CHKERRQ(ierr);
2646       }
2647     }
2648   }
2649   ierr = ISRestorePointRange(cellIS, &cStart, &cEnd, &cells);CHKERRQ(ierr);
2650   if (hasFV) {ierr = MatSetOption(JacP, MAT_IGNORE_ZERO_ENTRIES, PETSC_FALSE);CHKERRQ(ierr);}
2651   ierr = PetscFree5(u,u_t,elemMat,elemMatP,elemMatD);CHKERRQ(ierr);
2652   if (dmAux) {
2653     ierr = PetscFree(a);CHKERRQ(ierr);
2654     ierr = DMDestroy(&plex);CHKERRQ(ierr);
2655   }
2656   /* Compute boundary integrals */
2657   ierr = DMPlexComputeBdJacobian_Internal(dm, X, X_t, t, X_tShift, Jac, JacP, user);CHKERRQ(ierr);
2658   /* Assemble matrix */
2659   if (hasJac && hasPrec) {
2660     ierr = MatAssemblyBegin(Jac, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2661     ierr = MatAssemblyEnd(Jac, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2662   }
2663   ierr = MatAssemblyBegin(JacP, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2664   ierr = MatAssemblyEnd(JacP, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2665   ierr = PetscLogEventEnd(DMPLEX_JacobianFEM,dm,0,0,0);CHKERRQ(ierr);
2666   PetscFunctionReturn(0);
2667 }
2668 
2669 /*@
2670   DMPlexComputeJacobianAction - Form the local portion of the Jacobian action Z = J(X) Y at the local solution X using pointwise functions specified by the user.
2671 
2672   Input Parameters:
2673 + dm - The mesh
2674 . cellIS -
2675 . t  - The time
2676 . X_tShift - The multiplier for the Jacobian with repsect to X_t
2677 . X  - Local solution vector
2678 . X_t  - Time-derivative of the local solution vector
2679 . Y  - Local input vector
2680 - user - The user context
2681 
2682   Output Parameter:
2683 . Z - Local output vector
2684 
2685   Note:
2686   We form the residual one batch of elements at a time. This allows us to offload work onto an accelerator,
2687   like a GPU, or vectorize on a multicore machine.
2688 
2689   Level: developer
2690 
2691 .seealso: FormFunctionLocal()
2692 @*/
2693 PetscErrorCode DMPlexComputeJacobianAction(DM dm, IS cellIS, PetscReal t, PetscReal X_tShift, Vec X, Vec X_t, Vec Y, Vec Z, void *user)
2694 {
2695   DM_Plex          *mesh  = (DM_Plex *) dm->data;
2696   const char       *name  = "Jacobian";
2697   DM                dmAux, plex, plexAux = NULL;
2698   Vec               A;
2699   PetscDS           prob, probAux = NULL;
2700   PetscQuadrature   quad;
2701   PetscSection      section, globalSection, sectionAux;
2702   PetscScalar      *elemMat, *elemMatD, *u, *u_t, *a = NULL, *y, *z;
2703   PetscInt          Nf, fieldI, fieldJ;
2704   PetscInt          totDim, totDimAux = 0;
2705   const PetscInt   *cells;
2706   PetscInt          cStart, cEnd, numCells, c;
2707   PetscBool         hasDyn;
2708   DMField           coordField;
2709   PetscErrorCode    ierr;
2710 
2711   PetscFunctionBegin;
2712   ierr = PetscLogEventBegin(DMPLEX_JacobianFEM,dm,0,0,0);CHKERRQ(ierr);
2713   ierr = DMSNESConvertPlex(dm, &plex, PETSC_TRUE);CHKERRQ(ierr);
2714   if (!cellIS) {
2715     PetscInt depth;
2716 
2717     ierr = DMPlexGetDepth(plex, &depth);CHKERRQ(ierr);
2718     ierr = DMGetStratumIS(plex, "dim", depth, &cellIS);CHKERRQ(ierr);
2719     if (!cellIS) {ierr = DMGetStratumIS(plex, "depth", depth, &cellIS);CHKERRQ(ierr);}
2720   } else {
2721     ierr = PetscObjectReference((PetscObject) cellIS);CHKERRQ(ierr);
2722   }
2723   ierr = DMGetDefaultSection(dm, &section);CHKERRQ(ierr);
2724   ierr = DMGetDefaultGlobalSection(dm, &globalSection);CHKERRQ(ierr);
2725   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
2726   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
2727   ierr = PetscDSHasDynamicJacobian(prob, &hasDyn);CHKERRQ(ierr);
2728   hasDyn = hasDyn && (X_tShift != 0.0) ? PETSC_TRUE : PETSC_FALSE;
2729   ierr = PetscSectionGetNumFields(section, &Nf);CHKERRQ(ierr);
2730   ierr = ISGetLocalSize(cellIS, &numCells);CHKERRQ(ierr);
2731   ierr = ISGetPointRange(cellIS, &cStart, &cEnd, &cells);CHKERRQ(ierr);
2732   ierr = PetscObjectQuery((PetscObject) dm, "dmAux", (PetscObject *) &dmAux);CHKERRQ(ierr);
2733   ierr = PetscObjectQuery((PetscObject) dm, "A", (PetscObject *) &A);CHKERRQ(ierr);
2734   if (dmAux) {
2735     ierr = DMConvert(dmAux, DMPLEX, &plexAux);CHKERRQ(ierr);
2736     ierr = DMGetDefaultSection(plexAux, &sectionAux);CHKERRQ(ierr);
2737     ierr = DMGetDS(dmAux, &probAux);CHKERRQ(ierr);
2738     ierr = PetscDSGetTotalDimension(probAux, &totDimAux);CHKERRQ(ierr);
2739   }
2740   ierr = VecSet(Z, 0.0);CHKERRQ(ierr);
2741   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);
2742   if (dmAux) {ierr = PetscMalloc1(numCells*totDimAux, &a);CHKERRQ(ierr);}
2743   ierr = DMGetCoordinateField(dm, &coordField);CHKERRQ(ierr);
2744   for (c = cStart; c < cEnd; ++c) {
2745     const PetscInt cell = cells ? cells[c] : c;
2746     const PetscInt cind = c - cStart;
2747     PetscScalar   *x = NULL,  *x_t = NULL;
2748     PetscInt       i;
2749 
2750     ierr = DMPlexVecGetClosure(dm, section, X, cell, NULL, &x);CHKERRQ(ierr);
2751     for (i = 0; i < totDim; ++i) u[cind*totDim+i] = x[i];
2752     ierr = DMPlexVecRestoreClosure(dm, section, X, cell, NULL, &x);CHKERRQ(ierr);
2753     if (X_t) {
2754       ierr = DMPlexVecGetClosure(dm, section, X_t, cell, NULL, &x_t);CHKERRQ(ierr);
2755       for (i = 0; i < totDim; ++i) u_t[cind*totDim+i] = x_t[i];
2756       ierr = DMPlexVecRestoreClosure(dm, section, X_t, cell, NULL, &x_t);CHKERRQ(ierr);
2757     }
2758     if (dmAux) {
2759       ierr = DMPlexVecGetClosure(plexAux, sectionAux, A, cell, NULL, &x);CHKERRQ(ierr);
2760       for (i = 0; i < totDimAux; ++i) a[cind*totDimAux+i] = x[i];
2761       ierr = DMPlexVecRestoreClosure(plexAux, sectionAux, A, cell, NULL, &x);CHKERRQ(ierr);
2762     }
2763     ierr = DMPlexVecGetClosure(dm, section, Y, cell, NULL, &x);CHKERRQ(ierr);
2764     for (i = 0; i < totDim; ++i) y[cind*totDim+i] = x[i];
2765     ierr = DMPlexVecRestoreClosure(dm, section, Y, cell, NULL, &x);CHKERRQ(ierr);
2766   }
2767   ierr = PetscMemzero(elemMat, numCells*totDim*totDim * sizeof(PetscScalar));CHKERRQ(ierr);
2768   if (hasDyn)  {ierr = PetscMemzero(elemMatD, numCells*totDim*totDim * sizeof(PetscScalar));CHKERRQ(ierr);}
2769   for (fieldI = 0; fieldI < Nf; ++fieldI) {
2770     PetscFE  fe;
2771     PetscInt Nb;
2772     /* Conforming batches */
2773     PetscInt numChunks, numBatches, numBlocks, Ne, blockSize, batchSize;
2774     /* Remainder */
2775     PetscInt Nr, offset, Nq;
2776     PetscQuadrature qGeom = NULL;
2777     PetscBool   isAffine;
2778     PetscFEGeom *cgeomFEM, *chunkGeom = NULL, *remGeom = NULL;
2779 
2780     ierr = PetscDSGetDiscretization(prob, fieldI, (PetscObject *) &fe);CHKERRQ(ierr);
2781     ierr = PetscFEGetQuadrature(fe, &quad);CHKERRQ(ierr);
2782     ierr = PetscFEGetDimension(fe, &Nb);CHKERRQ(ierr);
2783     ierr = PetscFEGetTileSizes(fe, NULL, &numBlocks, NULL, &numBatches);CHKERRQ(ierr);
2784     ierr = DMFieldGetFEInvariance(coordField,cellIS,NULL,&isAffine,NULL);CHKERRQ(ierr);
2785     if (isAffine) {ierr = DMFieldCreateDefaultQuadrature(coordField,cellIS,&qGeom);CHKERRQ(ierr);}
2786     if (!qGeom) {
2787       ierr = PetscFEGetQuadrature(fe,&qGeom);CHKERRQ(ierr);
2788       ierr = PetscObjectReference((PetscObject)qGeom);CHKERRQ(ierr);
2789     }
2790     ierr = PetscQuadratureGetData(qGeom, NULL, NULL, &Nq, NULL, NULL);CHKERRQ(ierr);
2791     ierr = DMSNESGetFEGeom(coordField,cellIS,qGeom,PETSC_FALSE,&cgeomFEM);CHKERRQ(ierr);
2792     blockSize = Nb;
2793     batchSize = numBlocks * blockSize;
2794     ierr = PetscFESetTileSizes(fe, blockSize, numBlocks, batchSize, numBatches);CHKERRQ(ierr);
2795     numChunks = numCells / (numBatches*batchSize);
2796     Ne        = numChunks*numBatches*batchSize;
2797     Nr        = numCells % (numBatches*batchSize);
2798     offset    = numCells - Nr;
2799     ierr = PetscFEGeomGetChunk(cgeomFEM,0,offset,&chunkGeom);CHKERRQ(ierr);
2800     ierr = PetscFEGeomGetChunk(cgeomFEM,offset,numCells,&remGeom);CHKERRQ(ierr);
2801     for (fieldJ = 0; fieldJ < Nf; ++fieldJ) {
2802       ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN, fieldI, fieldJ, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMat);CHKERRQ(ierr);
2803       ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN, fieldI, fieldJ, Nr, remGeom, &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, X_tShift, &elemMat[offset*totDim*totDim]);CHKERRQ(ierr);
2804       if (hasDyn) {
2805         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN_DYN, fieldI, fieldJ, Ne, chunkGeom, u, u_t, probAux, a, t, X_tShift, elemMatD);CHKERRQ(ierr);
2806         ierr = PetscFEIntegrateJacobian(fe, prob, PETSCFE_JACOBIAN_DYN, fieldI, fieldJ, Nr, remGeom, &u[offset*totDim], u_t ? &u_t[offset*totDim] : NULL, probAux, &a[offset*totDimAux], t, X_tShift, &elemMatD[offset*totDim*totDim]);CHKERRQ(ierr);
2807       }
2808     }
2809     ierr = PetscFEGeomRestoreChunk(cgeomFEM,offset,numCells,&remGeom);CHKERRQ(ierr);
2810     ierr = PetscFEGeomRestoreChunk(cgeomFEM,0,offset,&chunkGeom);CHKERRQ(ierr);
2811     ierr = DMSNESRestoreFEGeom(coordField,cellIS,qGeom,PETSC_FALSE,&cgeomFEM);CHKERRQ(ierr);
2812     ierr = PetscQuadratureDestroy(&qGeom);CHKERRQ(ierr);
2813   }
2814   if (hasDyn) {
2815     for (c = 0; c < numCells*totDim*totDim; ++c) elemMat[c] += X_tShift*elemMatD[c];
2816   }
2817   for (c = cStart; c < cEnd; ++c) {
2818     const PetscInt     cell = cells ? cells[c] : c;
2819     const PetscInt     cind = c - cStart;
2820     const PetscBLASInt M = totDim, one = 1;
2821     const PetscScalar  a = 1.0, b = 0.0;
2822 
2823     PetscStackCallBLAS("BLASgemv", BLASgemv_("N", &M, &M, &a, &elemMat[cind*totDim*totDim], &M, &y[cind*totDim], &one, &b, z, &one));
2824     if (mesh->printFEM > 1) {
2825       ierr = DMPrintCellMatrix(c, name, totDim, totDim, &elemMat[cind*totDim*totDim]);CHKERRQ(ierr);
2826       ierr = DMPrintCellVector(c, "Y",  totDim, &y[cind*totDim]);CHKERRQ(ierr);
2827       ierr = DMPrintCellVector(c, "Z",  totDim, z);CHKERRQ(ierr);
2828     }
2829     ierr = DMPlexVecSetClosure(dm, section, Z, cell, z, ADD_VALUES);CHKERRQ(ierr);
2830   }
2831   ierr = PetscFree6(u,u_t,elemMat,elemMatD,y,z);CHKERRQ(ierr);
2832   if (mesh->printFEM) {
2833     ierr = PetscPrintf(PETSC_COMM_WORLD, "Z:\n");CHKERRQ(ierr);
2834     ierr = VecView(Z, PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
2835   }
2836   ierr = PetscFree(a);CHKERRQ(ierr);
2837   ierr = ISDestroy(&cellIS);CHKERRQ(ierr);
2838   ierr = DMDestroy(&plexAux);CHKERRQ(ierr);
2839   ierr = DMDestroy(&plex);CHKERRQ(ierr);
2840   ierr = PetscLogEventEnd(DMPLEX_JacobianFEM,dm,0,0,0);CHKERRQ(ierr);
2841   PetscFunctionReturn(0);
2842 }
2843 
2844 /*@
2845   DMPlexSNESComputeJacobianFEM - Form the local portion of the Jacobian matrix J at the local solution X using pointwise functions specified by the user.
2846 
2847   Input Parameters:
2848 + dm - The mesh
2849 . X  - Local input vector
2850 - user - The user context
2851 
2852   Output Parameter:
2853 . Jac  - Jacobian matrix
2854 
2855   Note:
2856   We form the residual one batch of elements at a time. This allows us to offload work onto an accelerator,
2857   like a GPU, or vectorize on a multicore machine.
2858 
2859   Level: developer
2860 
2861 .seealso: FormFunctionLocal()
2862 @*/
2863 PetscErrorCode DMPlexSNESComputeJacobianFEM(DM dm, Vec X, Mat Jac, Mat JacP,void *user)
2864 {
2865   DM             plex;
2866   PetscDS        prob;
2867   IS             cellIS;
2868   PetscBool      hasJac, hasPrec;
2869   PetscInt       depth;
2870   PetscErrorCode ierr;
2871 
2872   PetscFunctionBegin;
2873   ierr = DMSNESConvertPlex(dm,&plex,PETSC_TRUE);CHKERRQ(ierr);
2874   ierr = DMPlexGetDepth(plex, &depth);CHKERRQ(ierr);
2875   ierr = DMGetStratumIS(plex, "dim", depth, &cellIS);CHKERRQ(ierr);
2876   if (!cellIS) {ierr = DMGetStratumIS(plex, "depth", depth, &cellIS);CHKERRQ(ierr);}
2877   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
2878   ierr = PetscDSHasJacobian(prob, &hasJac);CHKERRQ(ierr);
2879   ierr = PetscDSHasJacobianPreconditioner(prob, &hasPrec);CHKERRQ(ierr);
2880   if (hasJac && hasPrec) {ierr = MatZeroEntries(Jac);CHKERRQ(ierr);}
2881   ierr = MatZeroEntries(JacP);CHKERRQ(ierr);
2882   ierr = DMPlexComputeJacobian_Internal(plex, cellIS, 0.0, 0.0, X, NULL, Jac, JacP, user);CHKERRQ(ierr);
2883   ierr = ISDestroy(&cellIS);CHKERRQ(ierr);
2884   ierr = DMDestroy(&plex);CHKERRQ(ierr);
2885   PetscFunctionReturn(0);
2886 }
2887 
2888 /*@
2889   DMPlexSetSNESLocalFEM - Use DMPlex's internal FEM routines to compute SNES boundary values, residual, and Jacobian.
2890 
2891   Input Parameters:
2892 + dm - The DM object
2893 . boundaryctx - the user context that will be passed to pointwise evaluation of boundary values (see PetscDSAddBoundary())
2894 . residualctx - the user context that will be passed to pointwise evaluation of finite element residual computations (see PetscDSSetResidual())
2895 - jacobianctx - the user context that will be passed to pointwise evaluation of finite element Jacobian construction (see PetscDSSetJacobian())
2896 
2897   Level: developer
2898 @*/
2899 PetscErrorCode DMPlexSetSNESLocalFEM(DM dm, void *boundaryctx, void *residualctx, void *jacobianctx)
2900 {
2901   PetscErrorCode ierr;
2902 
2903   PetscFunctionBegin;
2904   ierr = DMSNESSetBoundaryLocal(dm,DMPlexSNESComputeBoundaryFEM,boundaryctx);CHKERRQ(ierr);
2905   ierr = DMSNESSetFunctionLocal(dm,DMPlexSNESComputeResidualFEM,residualctx);CHKERRQ(ierr);
2906   ierr = DMSNESSetJacobianLocal(dm,DMPlexSNESComputeJacobianFEM,jacobianctx);CHKERRQ(ierr);
2907   PetscFunctionReturn(0);
2908 }
2909 
2910 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)
2911 {
2912   PetscDS        prob;
2913   Mat            J, M;
2914   Vec            r, b;
2915   MatNullSpace   nullSpace;
2916   PetscReal     *error, res = 0.0;
2917   PetscInt       numFields;
2918   PetscBool      hasJac, hasPrec;
2919   PetscErrorCode ierr;
2920 
2921   PetscFunctionBegin;
2922   ierr = VecDuplicate(u, &r);CHKERRQ(ierr);
2923   ierr = DMCreateMatrix(dm, &J);CHKERRQ(ierr);
2924   /* TODO Null space for J */
2925   /* Check discretization error */
2926   ierr = DMGetNumFields(dm, &numFields);CHKERRQ(ierr);
2927   ierr = PetscMalloc1(PetscMax(1, numFields), &error);CHKERRQ(ierr);
2928   if (numFields > 1) {
2929     PetscInt f;
2930 
2931     ierr = DMComputeL2FieldDiff(dm, 0.0, exactFuncs, ctxs, u, error);CHKERRQ(ierr);
2932     ierr = PetscPrintf(PETSC_COMM_WORLD, "L_2 Error: [");CHKERRQ(ierr);
2933     for (f = 0; f < numFields; ++f) {
2934       if (f) {ierr = PetscPrintf(PETSC_COMM_WORLD, ", ");CHKERRQ(ierr);}
2935       if (error[f] >= 1.0e-11) {ierr = PetscPrintf(PETSC_COMM_WORLD, "%g", (double)error[f]);CHKERRQ(ierr);}
2936       else                     {ierr = PetscPrintf(PETSC_COMM_WORLD, "< 1.0e-11");CHKERRQ(ierr);}
2937     }
2938     ierr = PetscPrintf(PETSC_COMM_WORLD, "]\n");CHKERRQ(ierr);
2939   } else {
2940     ierr = DMComputeL2Diff(dm, 0.0, exactFuncs, ctxs, u, &error[0]);CHKERRQ(ierr);
2941     if (error[0] >= 1.0e-11) {ierr = PetscPrintf(PETSC_COMM_WORLD, "L_2 Error: %g\n", (double)error[0]);CHKERRQ(ierr);}
2942     else                     {ierr = PetscPrintf(PETSC_COMM_WORLD, "L_2 Error: < 1.0e-11\n");CHKERRQ(ierr);}
2943   }
2944   ierr = PetscFree(error);CHKERRQ(ierr);
2945   /* Check residual */
2946   ierr = SNESComputeFunction(snes, u, r);CHKERRQ(ierr);
2947   ierr = VecNorm(r, NORM_2, &res);CHKERRQ(ierr);
2948   ierr = PetscPrintf(PETSC_COMM_WORLD, "L_2 Residual: %g\n", (double)res);CHKERRQ(ierr);
2949   ierr = VecChop(r, 1.0e-10);CHKERRQ(ierr);
2950   ierr = PetscObjectSetName((PetscObject) r, "Initial Residual");CHKERRQ(ierr);
2951   ierr = PetscObjectSetOptionsPrefix((PetscObject)r,"res_");CHKERRQ(ierr);
2952   ierr = VecViewFromOptions(r, NULL, "-vec_view");CHKERRQ(ierr);
2953   /* Check Jacobian */
2954   ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
2955   ierr = PetscDSHasJacobian(prob, &hasJac);CHKERRQ(ierr);
2956   ierr = PetscDSHasJacobianPreconditioner(prob, &hasPrec);CHKERRQ(ierr);
2957   if (hasJac && hasPrec) {
2958     ierr = DMCreateMatrix(dm, &M);CHKERRQ(ierr);
2959     ierr = SNESComputeJacobian(snes, u, J, M);CHKERRQ(ierr);
2960     ierr = PetscObjectSetOptionsPrefix((PetscObject) M, "jacpre_");CHKERRQ(ierr);
2961     ierr = MatViewFromOptions(M, NULL, "-mat_view");CHKERRQ(ierr);
2962     ierr = MatDestroy(&M);CHKERRQ(ierr);
2963   } else {
2964     ierr = SNESComputeJacobian(snes, u, J, J);CHKERRQ(ierr);
2965   }
2966   ierr = PetscObjectSetOptionsPrefix((PetscObject) J, "jac_");CHKERRQ(ierr);
2967   ierr = MatViewFromOptions(J, NULL, "-mat_view");CHKERRQ(ierr);
2968   ierr = MatGetNullSpace(J, &nullSpace);CHKERRQ(ierr);
2969   if (nullSpace) {
2970     PetscBool isNull;
2971     ierr = MatNullSpaceTest(nullSpace, J, &isNull);CHKERRQ(ierr);
2972     if (!isNull) SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_PLIB, "The null space calculated for the system operator is invalid.");
2973   }
2974   ierr = VecDuplicate(u, &b);CHKERRQ(ierr);
2975   ierr = VecSet(r, 0.0);CHKERRQ(ierr);
2976   ierr = SNESComputeFunction(snes, r, b);CHKERRQ(ierr);
2977   ierr = MatMult(J, u, r);CHKERRQ(ierr);
2978   ierr = VecAXPY(r, 1.0, b);CHKERRQ(ierr);
2979   ierr = VecDestroy(&b);CHKERRQ(ierr);
2980   ierr = VecNorm(r, NORM_2, &res);CHKERRQ(ierr);
2981   ierr = PetscPrintf(PETSC_COMM_WORLD, "Linear L_2 Residual: %g\n", (double)res);CHKERRQ(ierr);
2982   ierr = VecChop(r, 1.0e-10);CHKERRQ(ierr);
2983   ierr = PetscObjectSetName((PetscObject) r, "Au - b = Au + F(0)");CHKERRQ(ierr);
2984   ierr = PetscObjectSetOptionsPrefix((PetscObject)r,"linear_res_");CHKERRQ(ierr);
2985   ierr = VecViewFromOptions(r, NULL, "-vec_view");CHKERRQ(ierr);
2986   ierr = VecDestroy(&r);CHKERRQ(ierr);
2987   ierr = MatNullSpaceDestroy(&nullSpace);CHKERRQ(ierr);
2988   ierr = MatDestroy(&J);CHKERRQ(ierr);
2989   PetscFunctionReturn(0);
2990 }
2991 
2992 PetscErrorCode DMSNESCheckFromOptions(SNES snes, Vec u, PetscErrorCode (**exactFuncs)(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx), void **ctxs)
2993 {
2994   DM             dm;
2995   Vec            sol;
2996   PetscBool      check;
2997   PetscErrorCode ierr;
2998 
2999   PetscFunctionBegin;
3000   ierr = PetscOptionsHasName(((PetscObject)snes)->options,((PetscObject)snes)->prefix, "-dmsnes_check", &check);CHKERRQ(ierr);
3001   if (!check) PetscFunctionReturn(0);
3002   ierr = SNESGetDM(snes, &dm);CHKERRQ(ierr);
3003   ierr = VecDuplicate(u, &sol);CHKERRQ(ierr);
3004   ierr = SNESSetSolution(snes, sol);CHKERRQ(ierr);
3005   ierr = DMSNESCheckFromOptions_Internal(snes, dm, u, sol, exactFuncs, ctxs);CHKERRQ(ierr);
3006   ierr = VecDestroy(&sol);CHKERRQ(ierr);
3007   PetscFunctionReturn(0);
3008 }
3009