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