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