xref: /petsc/src/ksp/pc/impls/patch/pcpatch.c (revision a041468a873ecb0eaa683d63e3e590db31f0074c)
1 #include <petsc/private/pcpatchimpl.h>     /*I "petscpc.h" I*/
2 #include <petsc/private/kspimpl.h>         /* For ksp->setfromoptionscalled */
3 #include <petsc/private/dmpleximpl.h> /* For DMPlexComputeJacobian_Patch_Internal() */
4 #include <petscsf.h>
5 #include <petscbt.h>
6 #include <petscds.h>
7 
8 PetscLogEvent PC_Patch_CreatePatches, PC_Patch_ComputeOp, PC_Patch_Solve, PC_Patch_Scatter, PC_Patch_Apply, PC_Patch_Prealloc;
9 
10 PETSC_STATIC_INLINE PetscErrorCode ObjectView(PetscObject obj, PetscViewer viewer, PetscViewerFormat format)
11 {
12   PetscErrorCode ierr;
13 
14   ierr = PetscViewerPushFormat(viewer, format);CHKERRQ(ierr);
15   ierr = PetscObjectView(obj, viewer);CHKERRQ(ierr);
16   ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr);
17   return(0);
18 }
19 
20 static PetscErrorCode PCPatchConstruct_Star(void *vpatch, DM dm, PetscInt point, PetscHSetI ht)
21 {
22   PetscInt       starSize;
23   PetscInt      *star = NULL, si;
24   PetscErrorCode ierr;
25 
26   PetscFunctionBegin;
27   PetscHSetIClear(ht);
28   /* To start with, add the point we care about */
29   ierr = PetscHSetIAdd(ht, point);CHKERRQ(ierr);
30   /* Loop over all the points that this point connects to */
31   ierr = DMPlexGetTransitiveClosure(dm, point, PETSC_FALSE, &starSize, &star);CHKERRQ(ierr);
32   for (si = 0; si < starSize*2; si += 2) {ierr = PetscHSetIAdd(ht, star[si]);CHKERRQ(ierr);}
33   ierr = DMPlexRestoreTransitiveClosure(dm, point, PETSC_FALSE, &starSize, &star);CHKERRQ(ierr);
34   PetscFunctionReturn(0);
35 }
36 
37 static PetscErrorCode PCPatchConstruct_Vanka(void *vpatch, DM dm, PetscInt point, PetscHSetI ht)
38 {
39   PC_PATCH      *patch = (PC_PATCH *) vpatch;
40   PetscInt       starSize;
41   PetscInt      *star = NULL;
42   PetscBool      shouldIgnore = PETSC_FALSE;
43   PetscInt       cStart, cEnd, iStart, iEnd, si;
44   PetscErrorCode ierr;
45 
46   PetscFunctionBegin;
47   ierr = PetscHSetIClear(ht);CHKERRQ(ierr);
48   /* To start with, add the point we care about */
49   ierr = PetscHSetIAdd(ht, point);CHKERRQ(ierr);
50   /* Should we ignore any points of a certain dimension? */
51   if (patch->vankadim >= 0) {
52     shouldIgnore = PETSC_TRUE;
53     ierr = DMPlexGetDepthStratum(dm, patch->vankadim, &iStart, &iEnd);CHKERRQ(ierr);
54   }
55   ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);
56   /* Loop over all the cells that this point connects to */
57   ierr = DMPlexGetTransitiveClosure(dm, point, PETSC_FALSE, &starSize, &star);CHKERRQ(ierr);
58   for (si = 0; si < starSize*2; si += 2) {
59     const PetscInt cell = star[si];
60     PetscInt       closureSize;
61     PetscInt      *closure = NULL, ci;
62 
63     if (cell < cStart || cell >= cEnd) continue;
64     /* now loop over all entities in the closure of that cell */
65     ierr = DMPlexGetTransitiveClosure(dm, cell, PETSC_TRUE, &closureSize, &closure);CHKERRQ(ierr);
66     for (ci = 0; ci < closureSize*2; ci += 2) {
67       const PetscInt newpoint = closure[ci];
68 
69       /* We've been told to ignore entities of this type.*/
70       if (shouldIgnore && newpoint >= iStart && newpoint < iEnd) continue;
71       ierr = PetscHSetIAdd(ht, newpoint);CHKERRQ(ierr);
72     }
73     ierr = DMPlexRestoreTransitiveClosure(dm, cell, PETSC_TRUE, &closureSize, &closure);CHKERRQ(ierr);
74   }
75   ierr = DMPlexRestoreTransitiveClosure(dm, point, PETSC_FALSE, &starSize, &star);CHKERRQ(ierr);
76   PetscFunctionReturn(0);
77 }
78 
79 static PetscErrorCode PCPatchConstruct_Pardecomp(void *vpatch, DM dm, PetscInt point, PetscHSetI ht)
80 {
81   PC_PATCH       *patch = (PC_PATCH *) vpatch;
82   DMLabel         ghost = NULL;
83   const PetscInt *leaves;
84   PetscInt        nleaves, pStart, pEnd, loc;
85   PetscBool       isFiredrake;
86   DM              plex;
87   PetscBool       flg;
88   PetscInt        starSize;
89   PetscInt       *star = NULL;
90   PetscInt        opoint, overlapi;
91   PetscErrorCode  ierr;
92 
93   PetscFunctionBegin;
94   PetscHSetIClear(ht);
95 
96   ierr = DMConvert(dm, DMPLEX, &plex);CHKERRQ(ierr);
97   ierr = DMPlexGetChart(plex, &pStart, &pEnd);CHKERRQ(ierr);
98 
99   ierr = DMHasLabel(dm, "pyop2_ghost", &isFiredrake);CHKERRQ(ierr);
100   if (isFiredrake) {
101     ierr = DMGetLabel(dm, "pyop2_ghost", &ghost);CHKERRQ(ierr);
102     ierr = DMLabelCreateIndex(ghost, pStart, pEnd);CHKERRQ(ierr);
103   } else {
104     PetscSF sf;
105     ierr = DMGetPointSF(dm, &sf);CHKERRQ(ierr);
106     ierr = PetscSFGetGraph(sf, NULL, &nleaves, &leaves, NULL);CHKERRQ(ierr);
107     nleaves = PetscMax(nleaves, 0);
108   }
109 
110   for (opoint = pStart; opoint < pEnd; ++opoint) {
111     if (ghost) {ierr = DMLabelHasPoint(ghost, opoint, &flg);CHKERRQ(ierr);}
112     else       {ierr = PetscFindInt(opoint, nleaves, leaves, &loc);CHKERRQ(ierr); flg = loc >=0 ? PETSC_TRUE : PETSC_FALSE;}
113     /* Not an owned entity, don't make a cell patch. */
114     if (flg) continue;
115     ierr = PetscHSetIAdd(ht, opoint);CHKERRQ(ierr);
116   }
117 
118   /* Now build the overlap for the patch */
119   for (overlapi = 0; overlapi < patch->pardecomp_overlap; ++overlapi) {
120     PetscInt index = 0;
121     PetscInt *htpoints = NULL;
122     PetscInt htsize;
123     PetscInt i;
124 
125     ierr = PetscHSetIGetSize(ht, &htsize);CHKERRQ(ierr);
126     ierr = PetscMalloc1(htsize, &htpoints);CHKERRQ(ierr);
127     ierr = PetscHSetIGetElems(ht, &index, htpoints);CHKERRQ(ierr);
128 
129     for (i = 0; i < htsize; ++i) {
130       PetscInt hpoint = htpoints[i];
131       PetscInt si;
132 
133       ierr = DMPlexGetTransitiveClosure(dm, hpoint, PETSC_FALSE, &starSize, &star);CHKERRQ(ierr);
134       for (si = 0; si < starSize*2; si += 2) {
135         const PetscInt starp = star[si];
136         PetscInt       closureSize;
137         PetscInt      *closure = NULL, ci;
138 
139         /* now loop over all entities in the closure of starp */
140         ierr = DMPlexGetTransitiveClosure(dm, starp, PETSC_TRUE, &closureSize, &closure);CHKERRQ(ierr);
141         for (ci = 0; ci < closureSize*2; ci += 2) {
142           const PetscInt closstarp = closure[ci];
143           ierr = PetscHSetIAdd(ht, closstarp);CHKERRQ(ierr);
144         }
145         ierr = DMPlexRestoreTransitiveClosure(dm, starp, PETSC_TRUE, &closureSize, &closure);CHKERRQ(ierr);
146       }
147       ierr = DMPlexRestoreTransitiveClosure(dm, hpoint, PETSC_FALSE, &starSize, &star);CHKERRQ(ierr);
148     }
149     ierr = PetscFree(htpoints);CHKERRQ(ierr);
150   }
151 
152   PetscFunctionReturn(0);
153 }
154 
155 /* The user's already set the patches in patch->userIS. Build the hash tables */
156 static PetscErrorCode PCPatchConstruct_User(void *vpatch, DM dm, PetscInt point, PetscHSetI ht)
157 {
158   PC_PATCH       *patch   = (PC_PATCH *) vpatch;
159   IS              patchis = patch->userIS[point];
160   PetscInt        n;
161   const PetscInt *patchdata;
162   PetscInt        pStart, pEnd, i;
163   PetscErrorCode  ierr;
164 
165   PetscFunctionBegin;
166   ierr = PetscHSetIClear(ht);CHKERRQ(ierr);
167   ierr = DMPlexGetChart(dm, &pStart, &pEnd);CHKERRQ(ierr);
168   ierr = ISGetLocalSize(patchis, &n);CHKERRQ(ierr);
169   ierr = ISGetIndices(patchis, &patchdata);CHKERRQ(ierr);
170   for (i = 0; i < n; ++i) {
171     const PetscInt ownedpoint = patchdata[i];
172 
173     if (ownedpoint < pStart || ownedpoint >= pEnd) {
174       SETERRQ3(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %D was not in [%D, %D)", ownedpoint, pStart, pEnd);
175     }
176     ierr = PetscHSetIAdd(ht, ownedpoint);CHKERRQ(ierr);
177   }
178   ierr = ISRestoreIndices(patchis, &patchdata);CHKERRQ(ierr);
179   PetscFunctionReturn(0);
180 }
181 
182 static PetscErrorCode PCPatchCreateDefaultSF_Private(PC pc, PetscInt n, const PetscSF *sf, const PetscInt *bs)
183 {
184   PC_PATCH      *patch = (PC_PATCH *) pc->data;
185   PetscInt       i;
186   PetscErrorCode ierr;
187 
188   PetscFunctionBegin;
189   if (n == 1 && bs[0] == 1) {
190     patch->defaultSF = sf[0];
191     ierr = PetscObjectReference((PetscObject) patch->defaultSF);CHKERRQ(ierr);
192   } else {
193     PetscInt     allRoots = 0, allLeaves = 0;
194     PetscInt     leafOffset = 0;
195     PetscInt    *ilocal = NULL;
196     PetscSFNode *iremote = NULL;
197     PetscInt    *remoteOffsets = NULL;
198     PetscInt     index = 0;
199     PetscHMapI   rankToIndex;
200     PetscInt     numRanks = 0;
201     PetscSFNode *remote = NULL;
202     PetscSF      rankSF;
203     PetscInt    *ranks = NULL;
204     PetscInt    *offsets = NULL;
205     MPI_Datatype contig;
206     PetscHSetI   ranksUniq;
207 
208     /* First figure out how many dofs there are in the concatenated numbering.
209      * allRoots: number of owned global dofs;
210      * allLeaves: number of visible dofs (global + ghosted).
211      */
212     for (i = 0; i < n; ++i) {
213       PetscInt nroots, nleaves;
214 
215       ierr = PetscSFGetGraph(sf[i], &nroots, &nleaves, NULL, NULL);CHKERRQ(ierr);
216       allRoots  += nroots * bs[i];
217       allLeaves += nleaves * bs[i];
218     }
219     ierr = PetscMalloc1(allLeaves, &ilocal);CHKERRQ(ierr);
220     ierr = PetscMalloc1(allLeaves, &iremote);CHKERRQ(ierr);
221     /* Now build an SF that just contains process connectivity. */
222     ierr = PetscHSetICreate(&ranksUniq);CHKERRQ(ierr);
223     for (i = 0; i < n; ++i) {
224       const PetscMPIInt *ranks = NULL;
225       PetscInt           nranks, j;
226 
227       ierr = PetscSFSetUp(sf[i]);CHKERRQ(ierr);
228       ierr = PetscSFGetRanks(sf[i], &nranks, &ranks, NULL, NULL, NULL);CHKERRQ(ierr);
229       /* These are all the ranks who communicate with me. */
230       for (j = 0; j < nranks; ++j) {
231         ierr = PetscHSetIAdd(ranksUniq, (PetscInt) ranks[j]);CHKERRQ(ierr);
232       }
233     }
234     ierr = PetscHSetIGetSize(ranksUniq, &numRanks);CHKERRQ(ierr);
235     ierr = PetscMalloc1(numRanks, &remote);CHKERRQ(ierr);
236     ierr = PetscMalloc1(numRanks, &ranks);CHKERRQ(ierr);
237     ierr = PetscHSetIGetElems(ranksUniq, &index, ranks);CHKERRQ(ierr);
238 
239     ierr = PetscHMapICreate(&rankToIndex);CHKERRQ(ierr);
240     for (i = 0; i < numRanks; ++i) {
241       remote[i].rank  = ranks[i];
242       remote[i].index = 0;
243       ierr = PetscHMapISet(rankToIndex, ranks[i], i);CHKERRQ(ierr);
244     }
245     ierr = PetscFree(ranks);CHKERRQ(ierr);
246     ierr = PetscHSetIDestroy(&ranksUniq);CHKERRQ(ierr);
247     ierr = PetscSFCreate(PetscObjectComm((PetscObject) pc), &rankSF);CHKERRQ(ierr);
248     ierr = PetscSFSetGraph(rankSF, 1, numRanks, NULL, PETSC_OWN_POINTER, remote, PETSC_OWN_POINTER);CHKERRQ(ierr);
249     ierr = PetscSFSetUp(rankSF);CHKERRQ(ierr);
250     /* OK, use it to communicate the root offset on the remote
251      * processes for each subspace. */
252     ierr = PetscMalloc1(n, &offsets);CHKERRQ(ierr);
253     ierr = PetscMalloc1(n*numRanks, &remoteOffsets);CHKERRQ(ierr);
254 
255     offsets[0] = 0;
256     for (i = 1; i < n; ++i) {
257       PetscInt nroots;
258 
259       ierr = PetscSFGetGraph(sf[i-1], &nroots, NULL, NULL, NULL);CHKERRQ(ierr);
260       offsets[i] = offsets[i-1] + nroots*bs[i-1];
261     }
262     /* Offsets are the offsets on the current process of the
263      * global dof numbering for the subspaces. */
264     ierr = MPI_Type_contiguous(n, MPIU_INT, &contig);CHKERRQ(ierr);
265     ierr = MPI_Type_commit(&contig);CHKERRQ(ierr);
266 
267     ierr = PetscSFBcastBegin(rankSF, contig, offsets, remoteOffsets);CHKERRQ(ierr);
268     ierr = PetscSFBcastEnd(rankSF, contig, offsets, remoteOffsets);CHKERRQ(ierr);
269     ierr = MPI_Type_free(&contig);CHKERRQ(ierr);
270     ierr = PetscFree(offsets);CHKERRQ(ierr);
271     ierr = PetscSFDestroy(&rankSF);CHKERRQ(ierr);
272     /* Now remoteOffsets contains the offsets on the remote
273      * processes who communicate with me.  So now we can
274      * concatenate the list of SFs into a single one. */
275     index = 0;
276     for (i = 0; i < n; ++i) {
277       const PetscSFNode *remote = NULL;
278       const PetscInt    *local  = NULL;
279       PetscInt           nroots, nleaves, j;
280 
281       ierr = PetscSFGetGraph(sf[i], &nroots, &nleaves, &local, &remote);CHKERRQ(ierr);
282       for (j = 0; j < nleaves; ++j) {
283         PetscInt rank = remote[j].rank;
284         PetscInt idx, rootOffset, k;
285 
286         ierr = PetscHMapIGet(rankToIndex, rank, &idx);CHKERRQ(ierr);
287         if (idx == -1) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Didn't find rank, huh?");
288         /* Offset on given rank for ith subspace */
289         rootOffset = remoteOffsets[n*idx + i];
290         for (k = 0; k < bs[i]; ++k) {
291           ilocal[index]        = (local ? local[j] : j)*bs[i] + k + leafOffset;
292           iremote[index].rank  = remote[j].rank;
293           iremote[index].index = remote[j].index*bs[i] + k + rootOffset;
294           ++index;
295         }
296       }
297       leafOffset += nleaves * bs[i];
298     }
299     ierr = PetscHMapIDestroy(&rankToIndex);CHKERRQ(ierr);
300     ierr = PetscFree(remoteOffsets);CHKERRQ(ierr);
301     ierr = PetscSFCreate(PetscObjectComm((PetscObject)pc), &patch->defaultSF);CHKERRQ(ierr);
302     ierr = PetscSFSetGraph(patch->defaultSF, allRoots, allLeaves, ilocal, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER);CHKERRQ(ierr);
303   }
304   PetscFunctionReturn(0);
305 }
306 
307 /* TODO: Docs */
308 PetscErrorCode PCPatchSetIgnoreDim(PC pc, PetscInt dim)
309 {
310   PC_PATCH *patch = (PC_PATCH *) pc->data;
311   PetscFunctionBegin;
312   patch->ignoredim = dim;
313   PetscFunctionReturn(0);
314 }
315 
316 /* TODO: Docs */
317 PetscErrorCode PCPatchGetIgnoreDim(PC pc, PetscInt *dim)
318 {
319   PC_PATCH *patch = (PC_PATCH *) pc->data;
320   PetscFunctionBegin;
321   *dim = patch->ignoredim;
322   PetscFunctionReturn(0);
323 }
324 
325 /* TODO: Docs */
326 PetscErrorCode PCPatchSetSaveOperators(PC pc, PetscBool flg)
327 {
328   PC_PATCH *patch = (PC_PATCH *) pc->data;
329   PetscFunctionBegin;
330   patch->save_operators = flg;
331   PetscFunctionReturn(0);
332 }
333 
334 /* TODO: Docs */
335 PetscErrorCode PCPatchGetSaveOperators(PC pc, PetscBool *flg)
336 {
337   PC_PATCH *patch = (PC_PATCH *) pc->data;
338   PetscFunctionBegin;
339   *flg = patch->save_operators;
340   PetscFunctionReturn(0);
341 }
342 
343 /* TODO: Docs */
344 PetscErrorCode PCPatchSetPrecomputeElementTensors(PC pc, PetscBool flg)
345 {
346   PC_PATCH *patch = (PC_PATCH *) pc->data;
347   PetscFunctionBegin;
348   patch->precomputeElementTensors = flg;
349   PetscFunctionReturn(0);
350 }
351 
352 /* TODO: Docs */
353 PetscErrorCode PCPatchGetPrecomputeElementTensors(PC pc, PetscBool *flg)
354 {
355   PC_PATCH *patch = (PC_PATCH *) pc->data;
356   PetscFunctionBegin;
357   *flg = patch->precomputeElementTensors;
358   PetscFunctionReturn(0);
359 }
360 
361 /* TODO: Docs */
362 PetscErrorCode PCPatchSetPartitionOfUnity(PC pc, PetscBool flg)
363 {
364   PC_PATCH *patch = (PC_PATCH *) pc->data;
365   PetscFunctionBegin;
366   patch->partition_of_unity = flg;
367   PetscFunctionReturn(0);
368 }
369 
370 /* TODO: Docs */
371 PetscErrorCode PCPatchGetPartitionOfUnity(PC pc, PetscBool *flg)
372 {
373   PC_PATCH *patch = (PC_PATCH *) pc->data;
374   PetscFunctionBegin;
375   *flg = patch->partition_of_unity;
376   PetscFunctionReturn(0);
377 }
378 
379 /* TODO: Docs */
380 PetscErrorCode PCPatchSetLocalComposition(PC pc, PCCompositeType type)
381 {
382   PC_PATCH *patch = (PC_PATCH *) pc->data;
383   PetscFunctionBegin;
384   if (type != PC_COMPOSITE_ADDITIVE && type != PC_COMPOSITE_MULTIPLICATIVE) SETERRQ(PetscObjectComm((PetscObject)pc),PETSC_ERR_SUP,"Only supports additive or multiplicative as the local type");
385   patch->local_composition_type = type;
386   PetscFunctionReturn(0);
387 }
388 
389 /* TODO: Docs */
390 PetscErrorCode PCPatchGetLocalComposition(PC pc, PCCompositeType *type)
391 {
392   PC_PATCH *patch = (PC_PATCH *) pc->data;
393   PetscFunctionBegin;
394   *type = patch->local_composition_type;
395   PetscFunctionReturn(0);
396 }
397 
398 /* TODO: Docs */
399 PetscErrorCode PCPatchSetSubMatType(PC pc, MatType sub_mat_type)
400 {
401   PC_PATCH      *patch = (PC_PATCH *) pc->data;
402   PetscErrorCode ierr;
403 
404   PetscFunctionBegin;
405   if (patch->sub_mat_type) {ierr = PetscFree(patch->sub_mat_type);CHKERRQ(ierr);}
406   ierr = PetscStrallocpy(sub_mat_type, (char **) &patch->sub_mat_type);CHKERRQ(ierr);
407   PetscFunctionReturn(0);
408 }
409 
410 /* TODO: Docs */
411 PetscErrorCode PCPatchGetSubMatType(PC pc, MatType *sub_mat_type)
412 {
413   PC_PATCH *patch = (PC_PATCH *) pc->data;
414   PetscFunctionBegin;
415   *sub_mat_type = patch->sub_mat_type;
416   PetscFunctionReturn(0);
417 }
418 
419 /* TODO: Docs */
420 PetscErrorCode PCPatchSetCellNumbering(PC pc, PetscSection cellNumbering)
421 {
422   PC_PATCH      *patch = (PC_PATCH *) pc->data;
423   PetscErrorCode ierr;
424 
425   PetscFunctionBegin;
426   patch->cellNumbering = cellNumbering;
427   ierr = PetscObjectReference((PetscObject) cellNumbering);CHKERRQ(ierr);
428   PetscFunctionReturn(0);
429 }
430 
431 /* TODO: Docs */
432 PetscErrorCode PCPatchGetCellNumbering(PC pc, PetscSection *cellNumbering)
433 {
434   PC_PATCH *patch = (PC_PATCH *) pc->data;
435   PetscFunctionBegin;
436   *cellNumbering = patch->cellNumbering;
437   PetscFunctionReturn(0);
438 }
439 
440 /* TODO: Docs */
441 PetscErrorCode PCPatchSetConstructType(PC pc, PCPatchConstructType ctype, PetscErrorCode (*func)(PC, PetscInt *, IS **, IS *, void *), void *ctx)
442 {
443   PC_PATCH *patch = (PC_PATCH *) pc->data;
444 
445   PetscFunctionBegin;
446   patch->ctype = ctype;
447   switch (ctype) {
448   case PC_PATCH_STAR:
449     patch->user_patches     = PETSC_FALSE;
450     patch->patchconstructop = PCPatchConstruct_Star;
451     break;
452   case PC_PATCH_VANKA:
453     patch->user_patches     = PETSC_FALSE;
454     patch->patchconstructop = PCPatchConstruct_Vanka;
455     break;
456   case PC_PATCH_PARDECOMP:
457     patch->user_patches     = PETSC_FALSE;
458     patch->patchconstructop = PCPatchConstruct_Pardecomp;
459     break;
460   case PC_PATCH_USER:
461   case PC_PATCH_PYTHON:
462     patch->user_patches     = PETSC_TRUE;
463     patch->patchconstructop = PCPatchConstruct_User;
464     if (func) {
465       patch->userpatchconstructionop = func;
466       patch->userpatchconstructctx   = ctx;
467     }
468     break;
469   default:
470     SETERRQ1(PetscObjectComm((PetscObject) pc), PETSC_ERR_USER, "Unknown patch construction type %D", (PetscInt) patch->ctype);
471   }
472   PetscFunctionReturn(0);
473 }
474 
475 /* TODO: Docs */
476 PetscErrorCode PCPatchGetConstructType(PC pc, PCPatchConstructType *ctype, PetscErrorCode (**func)(PC, PetscInt *, IS **, IS *, void *), void **ctx)
477 {
478   PC_PATCH *patch = (PC_PATCH *) pc->data;
479 
480   PetscFunctionBegin;
481   *ctype = patch->ctype;
482   switch (patch->ctype) {
483   case PC_PATCH_STAR:
484   case PC_PATCH_VANKA:
485   case PC_PATCH_PARDECOMP:
486     break;
487   case PC_PATCH_USER:
488   case PC_PATCH_PYTHON:
489     *func = patch->userpatchconstructionop;
490     *ctx  = patch->userpatchconstructctx;
491     break;
492   default:
493     SETERRQ1(PetscObjectComm((PetscObject) pc), PETSC_ERR_USER, "Unknown patch construction type %D", (PetscInt) patch->ctype);
494   }
495   PetscFunctionReturn(0);
496 }
497 
498 /* TODO: Docs */
499 PetscErrorCode PCPatchSetDiscretisationInfo(PC pc, PetscInt nsubspaces, DM *dms, PetscInt *bs, PetscInt *nodesPerCell, const PetscInt **cellNodeMap,
500                                             const PetscInt *subspaceOffsets, PetscInt numGhostBcs, const PetscInt *ghostBcNodes, PetscInt numGlobalBcs, const PetscInt *globalBcNodes)
501 {
502   PC_PATCH      *patch = (PC_PATCH *) pc->data;
503   DM             dm;
504   PetscSF       *sfs;
505   PetscInt       cStart, cEnd, i, j;
506   PetscErrorCode ierr;
507 
508   PetscFunctionBegin;
509   ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
510   ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);
511   ierr = PetscMalloc1(nsubspaces, &sfs);CHKERRQ(ierr);
512   ierr = PetscMalloc1(nsubspaces, &patch->dofSection);CHKERRQ(ierr);
513   ierr = PetscMalloc1(nsubspaces, &patch->bs);CHKERRQ(ierr);
514   ierr = PetscMalloc1(nsubspaces, &patch->nodesPerCell);CHKERRQ(ierr);
515   ierr = PetscMalloc1(nsubspaces, &patch->cellNodeMap);CHKERRQ(ierr);
516   ierr = PetscMalloc1(nsubspaces+1, &patch->subspaceOffsets);CHKERRQ(ierr);
517 
518   patch->nsubspaces       = nsubspaces;
519   patch->totalDofsPerCell = 0;
520   for (i = 0; i < nsubspaces; ++i) {
521     ierr = DMGetDefaultSection(dms[i], &patch->dofSection[i]);CHKERRQ(ierr);
522     ierr = PetscObjectReference((PetscObject) patch->dofSection[i]);CHKERRQ(ierr);
523     ierr = DMGetDefaultSF(dms[i], &sfs[i]);CHKERRQ(ierr);
524     patch->bs[i]              = bs[i];
525     patch->nodesPerCell[i]    = nodesPerCell[i];
526     patch->totalDofsPerCell  += nodesPerCell[i]*bs[i];
527     ierr = PetscMalloc1((cEnd-cStart)*nodesPerCell[i], &patch->cellNodeMap[i]);CHKERRQ(ierr);
528     for (j = 0; j < (cEnd-cStart)*nodesPerCell[i]; ++j) patch->cellNodeMap[i][j] = cellNodeMap[i][j];
529     patch->subspaceOffsets[i] = subspaceOffsets[i];
530   }
531   ierr = PCPatchCreateDefaultSF_Private(pc, nsubspaces, sfs, patch->bs);CHKERRQ(ierr);
532   ierr = PetscFree(sfs);CHKERRQ(ierr);
533 
534   patch->subspaceOffsets[nsubspaces] = subspaceOffsets[nsubspaces];
535   ierr = ISCreateGeneral(PETSC_COMM_SELF, numGhostBcs, ghostBcNodes, PETSC_COPY_VALUES, &patch->ghostBcNodes);CHKERRQ(ierr);
536   ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalBcs, globalBcNodes, PETSC_COPY_VALUES, &patch->globalBcNodes);CHKERRQ(ierr);
537   PetscFunctionReturn(0);
538 }
539 
540 /* TODO: Docs */
541 PetscErrorCode PCPatchSetDiscretisationInfoCombined(PC pc, DM dm, PetscInt *nodesPerCell, const PetscInt **cellNodeMap, PetscInt numGhostBcs, const PetscInt *ghostBcNodes, PetscInt numGlobalBcs, const PetscInt *globalBcNodes)
542 {
543   PC_PATCH      *patch = (PC_PATCH *) pc->data;
544   PetscInt       cStart, cEnd, i, j;
545   PetscErrorCode ierr;
546 
547   PetscFunctionBegin;
548   patch->combined = PETSC_TRUE;
549   ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);
550   ierr = DMGetNumFields(dm, &patch->nsubspaces);CHKERRQ(ierr);
551   ierr = PetscCalloc1(patch->nsubspaces, &patch->dofSection);CHKERRQ(ierr);
552   ierr = PetscMalloc1(patch->nsubspaces, &patch->bs);CHKERRQ(ierr);
553   ierr = PetscMalloc1(patch->nsubspaces, &patch->nodesPerCell);CHKERRQ(ierr);
554   ierr = PetscMalloc1(patch->nsubspaces, &patch->cellNodeMap);CHKERRQ(ierr);
555   ierr = PetscCalloc1(patch->nsubspaces+1, &patch->subspaceOffsets);CHKERRQ(ierr);
556   ierr = DMGetDefaultSection(dm, &patch->dofSection[0]);CHKERRQ(ierr);
557   ierr = PetscObjectReference((PetscObject) patch->dofSection[0]);CHKERRQ(ierr);
558   ierr = PetscSectionGetStorageSize(patch->dofSection[0], &patch->subspaceOffsets[patch->nsubspaces]);CHKERRQ(ierr);
559   patch->totalDofsPerCell = 0;
560   for (i = 0; i < patch->nsubspaces; ++i) {
561     patch->bs[i]             = 1;
562     patch->nodesPerCell[i]   = nodesPerCell[i];
563     patch->totalDofsPerCell += nodesPerCell[i];
564     ierr = PetscMalloc1((cEnd-cStart)*nodesPerCell[i], &patch->cellNodeMap[i]);CHKERRQ(ierr);
565     for (j = 0; j < (cEnd-cStart)*nodesPerCell[i]; ++j) patch->cellNodeMap[i][j] = cellNodeMap[i][j];
566   }
567   ierr = DMGetDefaultSF(dm, &patch->defaultSF);CHKERRQ(ierr);
568   ierr = PetscObjectReference((PetscObject) patch->defaultSF);CHKERRQ(ierr);
569   ierr = ISCreateGeneral(PETSC_COMM_SELF, numGhostBcs, ghostBcNodes, PETSC_COPY_VALUES, &patch->ghostBcNodes);CHKERRQ(ierr);
570   ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalBcs, globalBcNodes, PETSC_COPY_VALUES, &patch->globalBcNodes);CHKERRQ(ierr);
571   PetscFunctionReturn(0);
572 }
573 
574 /*@C
575 
576   PCPatchSetComputeFunction - Set the callback used to compute patch residuals
577 
578   Input Parameters:
579 + pc   - The PC
580 . func - The callback
581 - ctx  - The user context
582 
583   Level: advanced
584 
585   Note:
586   The callback has signature:
587 +  usercomputef(pc, point, x, f, cellIS, n, u, ctx)
588 +  pc     - The PC
589 +  point  - The point
590 +  x      - The input solution (not used in linear problems)
591 +  f      - The patch residual vector
592 +  cellIS - An array of the cell numbers
593 +  n      - The size of g2l
594 +  g2l    - The global to local dof translation table
595 +  ctx    - The user context
596   and can assume that the matrix entries have been set to zero before the call.
597 
598 .seealso: PCPatchSetComputeOperator(), PCPatchGetComputeOperator(), PCPatchSetDiscretisationInfo()
599 @*/
600 PetscErrorCode PCPatchSetComputeFunction(PC pc, PetscErrorCode (*func)(PC, PetscInt, Vec, Vec, IS, PetscInt, const PetscInt *, const PetscInt *, void *), void *ctx)
601 {
602   PC_PATCH *patch = (PC_PATCH *) pc->data;
603 
604   PetscFunctionBegin;
605   patch->usercomputef    = func;
606   patch->usercomputefctx = ctx;
607   PetscFunctionReturn(0);
608 }
609 
610 /*@C
611 
612   PCPatchSetComputeFunctionInteriorFacets - Set the callback used to compute facet integrals for patch residuals
613 
614   Input Parameters:
615 + pc   - The PC
616 . func - The callback
617 - ctx  - The user context
618 
619   Level: advanced
620 
621   Note:
622   The callback has signature:
623 +  usercomputef(pc, point, x, f, facetIS, n, u, ctx)
624 +  pc     - The PC
625 +  point  - The point
626 +  x      - The input solution (not used in linear problems)
627 +  f      - The patch residual vector
628 +  facetIS - An array of the facet numbers
629 +  n      - The size of g2l
630 +  g2l    - The global to local dof translation table
631 +  ctx    - The user context
632   and can assume that the matrix entries have been set to zero before the call.
633 
634 .seealso: PCPatchSetComputeOperator(), PCPatchGetComputeOperator(), PCPatchSetDiscretisationInfo()
635 @*/
636 PetscErrorCode PCPatchSetComputeFunctionInteriorFacets(PC pc, PetscErrorCode (*func)(PC, PetscInt, Vec, Vec, IS, PetscInt, const PetscInt *, const PetscInt *, void *), void *ctx)
637 {
638   PC_PATCH *patch = (PC_PATCH *) pc->data;
639 
640   PetscFunctionBegin;
641   patch->usercomputefintfacet    = func;
642   patch->usercomputefintfacetctx = ctx;
643   PetscFunctionReturn(0);
644 }
645 
646 /*@C
647 
648   PCPatchSetComputeOperator - Set the callback used to compute patch matrices
649 
650   Input Parameters:
651 + pc   - The PC
652 . func - The callback
653 - ctx  - The user context
654 
655   Level: advanced
656 
657   Note:
658   The callback has signature:
659 +  usercomputeop(pc, point, x, mat, cellIS, n, u, ctx)
660 +  pc     - The PC
661 +  point  - The point
662 +  x      - The input solution (not used in linear problems)
663 +  mat    - The patch matrix
664 +  cellIS - An array of the cell numbers
665 +  n      - The size of g2l
666 +  g2l    - The global to local dof translation table
667 +  ctx    - The user context
668   and can assume that the matrix entries have been set to zero before the call.
669 
670 .seealso: PCPatchGetComputeOperator(), PCPatchSetComputeFunction(), PCPatchSetDiscretisationInfo()
671 @*/
672 PetscErrorCode PCPatchSetComputeOperator(PC pc, PetscErrorCode (*func)(PC, PetscInt, Vec, Mat, IS, PetscInt, const PetscInt *, const PetscInt *, void *), void *ctx)
673 {
674   PC_PATCH *patch = (PC_PATCH *) pc->data;
675 
676   PetscFunctionBegin;
677   patch->usercomputeop    = func;
678   patch->usercomputeopctx = ctx;
679   PetscFunctionReturn(0);
680 }
681 
682 /*@C
683 
684   PCPatchSetComputeOperator - Set the callback used to compute facet integrals for patch matrices
685 
686   Input Parameters:
687 + pc   - The PC
688 . func - The callback
689 - ctx  - The user context
690 
691   Level: advanced
692 
693   Note:
694   The callback has signature:
695 +  usercomputeopintfacet(pc, point, x, mat, facetIS, n, u, ctx)
696 +  pc     - The PC
697 +  point  - The point
698 +  x      - The input solution (not used in linear problems)
699 +  mat    - The patch matrix
700 +  facetIS - An IS of the facet numbers
701 +  n      - The size of g2l
702 +  g2l    - The global to local dof translation table
703 +  ctx    - The user context
704   and can assume that the matrix entries have been set to zero before the call.
705 
706 .seealso: PCPatchGetComputeOperator(), PCPatchSetComputeFunction(), PCPatchSetDiscretisationInfo()
707 @*/
708 PetscErrorCode PCPatchSetComputeOperatorInteriorFacets(PC pc, PetscErrorCode (*func)(PC, PetscInt, Vec, Mat, IS, PetscInt, const PetscInt *, const PetscInt *, void *), void *ctx)
709 {
710   PC_PATCH *patch = (PC_PATCH *) pc->data;
711 
712   PetscFunctionBegin;
713   patch->usercomputeopintfacet    = func;
714   patch->usercomputeopintfacetctx = ctx;
715   PetscFunctionReturn(0);
716 }
717 
718 /* On entry, ht contains the topological entities whose dofs we are responsible for solving for;
719    on exit, cht contains all the topological entities we need to compute their residuals.
720    In full generality this should incorporate knowledge of the sparsity pattern of the matrix;
721    here we assume a standard FE sparsity pattern.*/
722 /* TODO: Use DMPlexGetAdjacency() */
723 static PetscErrorCode PCPatchCompleteCellPatch(PC pc, PetscHSetI ht, PetscHSetI cht)
724 {
725   DM             dm;
726   PC_PATCH      *patch = (PC_PATCH *) pc->data;
727   PetscHashIter  hi;
728   PetscInt       point;
729   PetscInt      *star = NULL, *closure = NULL;
730   PetscInt       ignoredim, iStart = 0, iEnd = -1, starSize, closureSize, si, ci;
731   PetscInt      *fStar = NULL, *fClosure = NULL;
732   PetscInt       fBegin, fEnd, fsi, fci, fStarSize, fClosureSize;
733   PetscErrorCode ierr;
734 
735   PetscFunctionBegin;
736   ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
737   ierr = DMPlexGetHeightStratum(dm, 1, &fBegin, &fEnd);CHKERRQ(ierr);
738   ierr = PCPatchGetIgnoreDim(pc, &ignoredim);CHKERRQ(ierr);
739   if (ignoredim >= 0) {ierr = DMPlexGetDepthStratum(dm, ignoredim, &iStart, &iEnd);CHKERRQ(ierr);}
740   ierr = PetscHSetIClear(cht);CHKERRQ(ierr);
741   PetscHashIterBegin(ht, hi);
742   while (!PetscHashIterAtEnd(ht, hi)) {
743 
744     PetscHashIterGetKey(ht, hi, point);
745     PetscHashIterNext(ht, hi);
746 
747     /* Loop over all the cells that this point connects to */
748     ierr = DMPlexGetTransitiveClosure(dm, point, PETSC_FALSE, &starSize, &star);CHKERRQ(ierr);
749     for (si = 0; si < starSize*2; si += 2) {
750       const PetscInt ownedpoint = star[si];
751       /* TODO Check for point in cht before running through closure again */
752       /* now loop over all entities in the closure of that cell */
753       ierr = DMPlexGetTransitiveClosure(dm, ownedpoint, PETSC_TRUE, &closureSize, &closure);CHKERRQ(ierr);
754       for (ci = 0; ci < closureSize*2; ci += 2) {
755         const PetscInt seenpoint = closure[ci];
756         if (ignoredim >= 0 && seenpoint >= iStart && seenpoint < iEnd) continue;
757         ierr = PetscHSetIAdd(cht, seenpoint);CHKERRQ(ierr);
758         /* Facet integrals couple dofs across facets, so in that case for each of
759          * the facets we need to add all dofs on the other side of the facet to
760          * the seen dofs. */
761         if(patch->usercomputeopintfacet){
762           if(fBegin <= seenpoint && seenpoint < fEnd){
763             ierr = DMPlexGetTransitiveClosure(dm, seenpoint, PETSC_FALSE, &fStarSize, &fStar);CHKERRQ(ierr);
764             for (fsi = 0; fsi < fStarSize*2; fsi += 2) {
765               ierr = DMPlexGetTransitiveClosure(dm, fStar[fsi], PETSC_TRUE, &fClosureSize, &fClosure);CHKERRQ(ierr);
766               for (fci = 0; fci < fClosureSize*2; fci += 2) {
767                 ierr = PetscHSetIAdd(cht, fClosure[fci]);CHKERRQ(ierr);
768               }
769               ierr = DMPlexRestoreTransitiveClosure(dm, fStar[fsi], PETSC_TRUE, NULL, &fClosure);CHKERRQ(ierr);
770             }
771             ierr = DMPlexRestoreTransitiveClosure(dm, seenpoint, PETSC_FALSE, NULL, &fStar);CHKERRQ(ierr);
772           }
773         }
774       }
775       ierr = DMPlexRestoreTransitiveClosure(dm, ownedpoint, PETSC_TRUE, NULL, &closure);CHKERRQ(ierr);
776     }
777     ierr = DMPlexRestoreTransitiveClosure(dm, point, PETSC_FALSE, NULL, &star);CHKERRQ(ierr);
778   }
779   PetscFunctionReturn(0);
780 }
781 
782 static PetscErrorCode PCPatchGetGlobalDofs(PC pc, PetscSection dofSection[], PetscInt f, PetscBool combined, PetscInt p, PetscInt *dof, PetscInt *off)
783 {
784   PetscErrorCode ierr;
785 
786   PetscFunctionBegin;
787   if (combined) {
788     if (f < 0) {
789       if (dof) {ierr = PetscSectionGetDof(dofSection[0], p, dof);CHKERRQ(ierr);}
790       if (off) {ierr = PetscSectionGetOffset(dofSection[0], p, off);CHKERRQ(ierr);}
791     } else {
792       if (dof) {ierr = PetscSectionGetFieldDof(dofSection[0], p, f, dof);CHKERRQ(ierr);}
793       if (off) {ierr = PetscSectionGetFieldOffset(dofSection[0], p, f, off);CHKERRQ(ierr);}
794     }
795   } else {
796     if (f < 0) {
797       PC_PATCH *patch = (PC_PATCH *) pc->data;
798       PetscInt  fdof, g;
799 
800       if (dof) {
801         *dof = 0;
802         for (g = 0; g < patch->nsubspaces; ++g) {
803           ierr = PetscSectionGetDof(dofSection[g], p, &fdof);CHKERRQ(ierr);
804           *dof += fdof;
805         }
806       }
807       if (off) {
808         *off = 0;
809         for (g = 0; g < patch->nsubspaces; ++g) {
810           ierr = PetscSectionGetOffset(dofSection[g], p, &fdof);CHKERRQ(ierr);
811           *off += fdof;
812         }
813       }
814     } else {
815       if (dof) {ierr = PetscSectionGetDof(dofSection[f], p, dof);CHKERRQ(ierr);}
816       if (off) {ierr = PetscSectionGetOffset(dofSection[f], p, off);CHKERRQ(ierr);}
817     }
818   }
819   PetscFunctionReturn(0);
820 }
821 
822 /* Given a hash table with a set of topological entities (pts), compute the degrees of
823    freedom in global concatenated numbering on those entities.
824    For Vanka smoothing, this needs to do something special: ignore dofs of the
825    constraint subspace on entities that aren't the base entity we're building the patch
826    around. */
827 static PetscErrorCode PCPatchGetPointDofs(PC pc, PetscHSetI pts, PetscHSetI dofs, PetscInt base, PetscHSetI* subspaces_to_exclude)
828 {
829   PC_PATCH      *patch = (PC_PATCH *) pc->data;
830   PetscHashIter  hi;
831   PetscInt       ldof, loff;
832   PetscInt       k, p;
833   PetscErrorCode ierr;
834 
835   PetscFunctionBegin;
836   ierr = PetscHSetIClear(dofs);CHKERRQ(ierr);
837   for (k = 0; k < patch->nsubspaces; ++k) {
838     PetscInt subspaceOffset = patch->subspaceOffsets[k];
839     PetscInt bs             = patch->bs[k];
840     PetscInt j, l;
841 
842     if (subspaces_to_exclude != NULL) {
843       PetscBool should_exclude_k = PETSC_FALSE;
844       PetscHSetIHas(*subspaces_to_exclude, k, &should_exclude_k);
845       if (should_exclude_k) {
846         /* only get this subspace dofs at the base entity, not any others */
847         ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, k, patch->combined, base, &ldof, &loff);CHKERRQ(ierr);
848         if (0 == ldof) continue;
849         for (j = loff; j < ldof + loff; ++j) {
850           for (l = 0; l < bs; ++l) {
851             PetscInt dof = bs*j + l + subspaceOffset;
852             ierr = PetscHSetIAdd(dofs, dof);CHKERRQ(ierr);
853           }
854         }
855         continue; /* skip the other dofs of this subspace */
856       }
857     }
858 
859     PetscHashIterBegin(pts, hi);
860     while (!PetscHashIterAtEnd(pts, hi)) {
861       PetscHashIterGetKey(pts, hi, p);
862       PetscHashIterNext(pts, hi);
863       ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, k, patch->combined, p, &ldof, &loff);CHKERRQ(ierr);
864       if (0 == ldof) continue;
865       for (j = loff; j < ldof + loff; ++j) {
866         for (l = 0; l < bs; ++l) {
867           PetscInt dof = bs*j + l + subspaceOffset;
868           ierr = PetscHSetIAdd(dofs, dof);CHKERRQ(ierr);
869         }
870       }
871     }
872   }
873   PetscFunctionReturn(0);
874 }
875 
876 /* Given two hash tables A and B, compute the keys in B that are not in A, and put them in C */
877 static PetscErrorCode PCPatchComputeSetDifference_Private(PetscHSetI A, PetscHSetI B, PetscHSetI C)
878 {
879   PetscHashIter  hi;
880   PetscInt       key;
881   PetscBool      flg;
882   PetscErrorCode ierr;
883 
884   PetscFunctionBegin;
885   ierr = PetscHSetIClear(C);CHKERRQ(ierr);
886   PetscHashIterBegin(B, hi);
887   while (!PetscHashIterAtEnd(B, hi)) {
888     PetscHashIterGetKey(B, hi, key);
889     PetscHashIterNext(B, hi);
890     ierr = PetscHSetIHas(A, key, &flg);CHKERRQ(ierr);
891     if (!flg) {ierr = PetscHSetIAdd(C, key);CHKERRQ(ierr);}
892   }
893   PetscFunctionReturn(0);
894 }
895 
896 /*
897  * PCPatchCreateCellPatches - create patches.
898  *
899  * Input Parameters:
900  * + dm - The DMPlex object defining the mesh
901  *
902  * Output Parameters:
903  * + cellCounts  - Section with counts of cells around each vertex
904  * . cells       - IS of the cell point indices of cells in each patch
905  * . pointCounts - Section with counts of cells around each vertex
906  * - point       - IS of the cell point indices of cells in each patch
907  */
908 static PetscErrorCode PCPatchCreateCellPatches(PC pc)
909 {
910   PC_PATCH       *patch = (PC_PATCH *) pc->data;
911   DMLabel         ghost = NULL;
912   DM              dm, plex;
913   PetscHSetI      ht, cht;
914   PetscSection    cellCounts,  pointCounts, intFacetCounts, extFacetCounts;
915   PetscInt       *cellsArray, *pointsArray, *intFacetsArray, *extFacetsArray, *intFacetsToPatchCell;
916   PetscInt        numCells, numPoints, numIntFacets, numExtFacets;
917   const PetscInt *leaves;
918   PetscInt        nleaves, pStart, pEnd, cStart, cEnd, vStart, vEnd, v;
919   PetscBool       isFiredrake;
920   PetscErrorCode  ierr;
921 
922   PetscFunctionBegin;
923   /* Used to keep track of the cells in the patch. */
924   ierr = PetscHSetICreate(&ht);CHKERRQ(ierr);
925   ierr = PetscHSetICreate(&cht);CHKERRQ(ierr);
926 
927   ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
928   if (!dm) SETERRQ(PetscObjectComm((PetscObject) pc), PETSC_ERR_ARG_WRONGSTATE, "DM not yet set on patch PC\n");
929   ierr = DMConvert(dm, DMPLEX, &plex);CHKERRQ(ierr);
930   ierr = DMPlexGetChart(plex, &pStart, &pEnd);CHKERRQ(ierr);
931   ierr = DMPlexGetHeightStratum(plex, 0, &cStart, &cEnd);CHKERRQ(ierr);
932 
933   if (patch->user_patches) {
934     ierr = patch->userpatchconstructionop(pc, &patch->npatch, &patch->userIS, &patch->iterationSet, patch->userpatchconstructctx);CHKERRQ(ierr);
935     vStart = 0; vEnd = patch->npatch;
936   } else if (patch->ctype == PC_PATCH_PARDECOMP) {
937     vStart = 0; vEnd = 1;
938   } else if (patch->codim < 0) {
939     if (patch->dim < 0) {ierr = DMPlexGetDepthStratum(plex,  0,            &vStart, &vEnd);CHKERRQ(ierr);}
940     else                {ierr = DMPlexGetDepthStratum(plex,  patch->dim,   &vStart, &vEnd);CHKERRQ(ierr);}
941   } else                {ierr = DMPlexGetHeightStratum(plex, patch->codim, &vStart, &vEnd);CHKERRQ(ierr);}
942   patch->npatch = vEnd - vStart;
943 
944   /* These labels mark the owned points.  We only create patches around points that this process owns. */
945   ierr = DMHasLabel(dm, "pyop2_ghost", &isFiredrake);CHKERRQ(ierr);
946   if (isFiredrake) {
947     ierr = DMGetLabel(dm, "pyop2_ghost", &ghost);CHKERRQ(ierr);
948     ierr = DMLabelCreateIndex(ghost, pStart, pEnd);CHKERRQ(ierr);
949   } else {
950     PetscSF sf;
951 
952     ierr = DMGetPointSF(dm, &sf);CHKERRQ(ierr);
953     ierr = PetscSFGetGraph(sf, NULL, &nleaves, &leaves, NULL);CHKERRQ(ierr);
954     nleaves = PetscMax(nleaves, 0);
955   }
956 
957   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->cellCounts);CHKERRQ(ierr);
958   ierr = PetscObjectSetName((PetscObject) patch->cellCounts, "Patch Cell Layout");CHKERRQ(ierr);
959   cellCounts = patch->cellCounts;
960   ierr = PetscSectionSetChart(cellCounts, vStart, vEnd);CHKERRQ(ierr);
961   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->pointCounts);CHKERRQ(ierr);
962   ierr = PetscObjectSetName((PetscObject) patch->pointCounts, "Patch Point Layout");CHKERRQ(ierr);
963   pointCounts = patch->pointCounts;
964   ierr = PetscSectionSetChart(pointCounts, vStart, vEnd);CHKERRQ(ierr);
965   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->extFacetCounts);CHKERRQ(ierr);
966   ierr = PetscObjectSetName((PetscObject) patch->extFacetCounts, "Patch Exterior Facet Layout");CHKERRQ(ierr);
967   extFacetCounts = patch->extFacetCounts;
968   ierr = PetscSectionSetChart(extFacetCounts, vStart, vEnd);CHKERRQ(ierr);
969   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->intFacetCounts);CHKERRQ(ierr);
970   ierr = PetscObjectSetName((PetscObject) patch->intFacetCounts, "Patch Interior Facet Layout");CHKERRQ(ierr);
971   intFacetCounts = patch->intFacetCounts;
972   ierr = PetscSectionSetChart(intFacetCounts, vStart, vEnd);CHKERRQ(ierr);
973   /* Count cells and points in the patch surrounding each entity */
974   PetscInt       fStart, fEnd;
975   ierr = DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd);CHKERRQ(ierr);
976   for (v = vStart; v < vEnd; ++v) {
977     PetscHashIter hi;
978     PetscInt       chtSize, loc = -1;
979     PetscBool      flg;
980 
981     if (!patch->user_patches && patch->ctype != PC_PATCH_PARDECOMP) {
982       if (ghost) {ierr = DMLabelHasPoint(ghost, v, &flg);CHKERRQ(ierr);}
983       else       {ierr = PetscFindInt(v, nleaves, leaves, &loc);CHKERRQ(ierr); flg = loc >=0 ? PETSC_TRUE : PETSC_FALSE;}
984       /* Not an owned entity, don't make a cell patch. */
985       if (flg) continue;
986     }
987 
988     ierr = patch->patchconstructop((void *) patch, dm, v, ht);CHKERRQ(ierr);
989     ierr = PCPatchCompleteCellPatch(pc, ht, cht);CHKERRQ(ierr);
990     ierr = PetscHSetIGetSize(cht, &chtSize);CHKERRQ(ierr);
991     /* empty patch, continue */
992     if (chtSize == 0) continue;
993 
994     /* safe because size(cht) > 0 from above */
995     PetscHashIterBegin(cht, hi);
996     while (!PetscHashIterAtEnd(cht, hi)) {
997       PetscInt point, pdof;
998 
999       PetscHashIterGetKey(cht, hi, point);
1000       if (fStart <= point && point < fEnd) {
1001         const PetscInt *support;
1002         PetscInt supportSize, p;
1003         PetscBool interior = PETSC_TRUE;
1004         ierr = DMPlexGetSupport(dm, point, &support);CHKERRQ(ierr);
1005         ierr = DMPlexGetSupportSize(dm, point, &supportSize);CHKERRQ(ierr);
1006         if (supportSize == 1) {
1007           interior = PETSC_FALSE;
1008         } else {
1009           for (p = 0; p < supportSize; p++) {
1010             PetscBool found;
1011             /* FIXME: can I do this while iterating over cht? */
1012             PetscHSetIHas(cht, support[p], &found);
1013             if (!found) {
1014               interior = PETSC_FALSE;
1015               break;
1016             }
1017           }
1018         }
1019         if (interior) {
1020           ierr = PetscSectionAddDof(intFacetCounts, v, 1);CHKERRQ(ierr);
1021         } else {
1022           ierr = PetscSectionAddDof(extFacetCounts, v, 1);CHKERRQ(ierr);
1023         }
1024       }
1025       ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, -1, patch->combined, point, &pdof, NULL);CHKERRQ(ierr);
1026       if (pdof)                            {ierr = PetscSectionAddDof(pointCounts, v, 1);CHKERRQ(ierr);}
1027       if (point >= cStart && point < cEnd) {ierr = PetscSectionAddDof(cellCounts, v, 1);CHKERRQ(ierr);}
1028       PetscHashIterNext(cht, hi);
1029     }
1030   }
1031   if (isFiredrake) {ierr = DMLabelDestroyIndex(ghost);CHKERRQ(ierr);}
1032 
1033   ierr = PetscSectionSetUp(cellCounts);CHKERRQ(ierr);
1034   ierr = PetscSectionGetStorageSize(cellCounts, &numCells);CHKERRQ(ierr);
1035   ierr = PetscMalloc1(numCells, &cellsArray);CHKERRQ(ierr);
1036   ierr = PetscSectionSetUp(pointCounts);CHKERRQ(ierr);
1037   ierr = PetscSectionGetStorageSize(pointCounts, &numPoints);CHKERRQ(ierr);
1038   ierr = PetscMalloc1(numPoints, &pointsArray);CHKERRQ(ierr);
1039 
1040   ierr = PetscSectionSetUp(intFacetCounts);CHKERRQ(ierr);
1041   ierr = PetscSectionSetUp(extFacetCounts);CHKERRQ(ierr);
1042   ierr = PetscSectionGetStorageSize(intFacetCounts, &numIntFacets);CHKERRQ(ierr);
1043   ierr = PetscSectionGetStorageSize(extFacetCounts, &numExtFacets);CHKERRQ(ierr);
1044   ierr = PetscMalloc1(numIntFacets, &intFacetsArray);CHKERRQ(ierr);
1045   ierr = PetscMalloc1(numIntFacets*2, &intFacetsToPatchCell);CHKERRQ(ierr);
1046   ierr = PetscMalloc1(numExtFacets, &extFacetsArray);CHKERRQ(ierr);
1047 
1048 
1049   /* Now that we know how much space we need, run through again and actually remember the cells. */
1050   for (v = vStart; v < vEnd; v++ ) {
1051     PetscHashIter hi;
1052     PetscInt       dof, off, cdof, coff, efdof, efoff, ifdof, ifoff, pdof, n = 0, cn = 0, ifn = 0, efn = 0;
1053 
1054     ierr = PetscSectionGetDof(pointCounts, v, &dof);CHKERRQ(ierr);
1055     ierr = PetscSectionGetOffset(pointCounts, v, &off);CHKERRQ(ierr);
1056     ierr = PetscSectionGetDof(cellCounts, v, &cdof);CHKERRQ(ierr);
1057     ierr = PetscSectionGetOffset(cellCounts, v, &coff);CHKERRQ(ierr);
1058     ierr = PetscSectionGetDof(intFacetCounts, v, &ifdof);CHKERRQ(ierr);
1059     ierr = PetscSectionGetOffset(intFacetCounts, v, &ifoff);CHKERRQ(ierr);
1060     ierr = PetscSectionGetDof(extFacetCounts, v, &efdof);CHKERRQ(ierr);
1061     ierr = PetscSectionGetOffset(extFacetCounts, v, &efoff);CHKERRQ(ierr);
1062     if (dof <= 0) continue;
1063     ierr = patch->patchconstructop((void *) patch, dm, v, ht);CHKERRQ(ierr);
1064     ierr = PCPatchCompleteCellPatch(pc, ht, cht);CHKERRQ(ierr);
1065     PetscHashIterBegin(cht, hi);
1066     while (!PetscHashIterAtEnd(cht, hi)) {
1067       PetscInt point;
1068 
1069       PetscHashIterGetKey(cht, hi, point);
1070       if (fStart <= point && point < fEnd) {
1071         const PetscInt *support;
1072         PetscInt supportSize, p;
1073         PetscBool interior = PETSC_TRUE;
1074         ierr = DMPlexGetSupport(dm, point, &support);CHKERRQ(ierr);
1075         ierr = DMPlexGetSupportSize(dm, point, &supportSize);CHKERRQ(ierr);
1076         if (supportSize == 1) {
1077           interior = PETSC_FALSE;
1078         } else {
1079           for (p = 0; p < supportSize; p++) {
1080             PetscBool found;
1081             /* FIXME: can I do this while iterating over cht? */
1082             PetscHSetIHas(cht, support[p], &found);
1083             if (!found) {
1084               interior = PETSC_FALSE;
1085               break;
1086             }
1087           }
1088         }
1089         if (interior) {
1090           intFacetsToPatchCell[2*(ifoff + ifn)] = support[0];
1091           intFacetsToPatchCell[2*(ifoff + ifn) + 1] = support[1];
1092           intFacetsArray[ifoff + ifn++] = point;
1093         } else {
1094           extFacetsArray[efoff + efn++] = point;
1095         }
1096       }
1097       ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, -1, patch->combined, point, &pdof, NULL);CHKERRQ(ierr);
1098       if (pdof)                            {pointsArray[off + n++] = point;}
1099       if (point >= cStart && point < cEnd) {cellsArray[coff + cn++] = point;}
1100       PetscHashIterNext(cht, hi);
1101     }
1102     if (ifn != ifdof) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Number of interior facets in patch %D is %D, but should be %D", v, ifn, ifdof);
1103     if (efn != efdof) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Number of exterior facets in patch %D is %D, but should be %D", v, efn, efdof);
1104     if (cn != cdof) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Number of cells in patch %D is %D, but should be %D", v, cn, cdof);
1105     if (n  != dof)  SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Number of points in patch %D is %D, but should be %D", v, n, dof);
1106 
1107     for (ifn = 0; ifn < ifdof; ifn++) {
1108       PetscInt cell0 = intFacetsToPatchCell[2*(ifoff + ifn)];
1109       PetscInt cell1 = intFacetsToPatchCell[2*(ifoff + ifn) + 1];
1110       PetscBool found0 = PETSC_FALSE, found1 = PETSC_FALSE;
1111       for (n = 0; n < cdof; n++) {
1112         if (!found0 && cell0 == cellsArray[coff + n]) {
1113           intFacetsToPatchCell[2*(ifoff + ifn)] = n;
1114           found0 = PETSC_TRUE;
1115         }
1116         if (!found1 && cell1 == cellsArray[coff + n]) {
1117           intFacetsToPatchCell[2*(ifoff + ifn) + 1] = n;
1118           found1 = PETSC_TRUE;
1119         }
1120         if (found0 && found1) break;
1121       }
1122       if (!(found0 && found1)) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Didn't manage to find local point numbers for facet support");
1123     }
1124   }
1125   ierr = PetscHSetIDestroy(&ht);CHKERRQ(ierr);
1126   ierr = PetscHSetIDestroy(&cht);CHKERRQ(ierr);
1127   ierr = DMDestroy(&plex);CHKERRQ(ierr);
1128 
1129   ierr = ISCreateGeneral(PETSC_COMM_SELF, numCells,  cellsArray,  PETSC_OWN_POINTER, &patch->cells);CHKERRQ(ierr);
1130   ierr = PetscObjectSetName((PetscObject) patch->cells,  "Patch Cells");CHKERRQ(ierr);
1131   if (patch->viewCells) {
1132     ierr = ObjectView((PetscObject) patch->cellCounts, patch->viewerCells, patch->formatCells);CHKERRQ(ierr);
1133     ierr = ObjectView((PetscObject) patch->cells,      patch->viewerCells, patch->formatCells);CHKERRQ(ierr);
1134   }
1135   ierr = ISCreateGeneral(PETSC_COMM_SELF, numIntFacets,  intFacetsArray,  PETSC_OWN_POINTER, &patch->intFacets);CHKERRQ(ierr);
1136   ierr = PetscObjectSetName((PetscObject) patch->intFacets,  "Patch Interior Facets");CHKERRQ(ierr);
1137   ierr = ISCreateGeneral(PETSC_COMM_SELF, 2*numIntFacets, intFacetsToPatchCell, PETSC_OWN_POINTER, &patch->intFacetsToPatchCell);CHKERRQ(ierr);
1138   ierr = PetscObjectSetName((PetscObject) patch->intFacetsToPatchCell,  "Patch Interior Facets local support");CHKERRQ(ierr);
1139   if (patch->viewIntFacets) {
1140     ierr = ObjectView((PetscObject) patch->intFacetCounts,       patch->viewerIntFacets, patch->formatIntFacets);CHKERRQ(ierr);
1141     ierr = ObjectView((PetscObject) patch->intFacets,            patch->viewerIntFacets, patch->formatIntFacets);CHKERRQ(ierr);
1142     ierr = ObjectView((PetscObject) patch->intFacetsToPatchCell, patch->viewerIntFacets, patch->formatIntFacets);CHKERRQ(ierr);
1143   }
1144   ierr = ISCreateGeneral(PETSC_COMM_SELF, numExtFacets,  extFacetsArray,  PETSC_OWN_POINTER, &patch->extFacets);CHKERRQ(ierr);
1145   ierr = PetscObjectSetName((PetscObject) patch->extFacets,  "Patch Exterior Facets");CHKERRQ(ierr);
1146   if (patch->viewExtFacets) {
1147     ierr = ObjectView((PetscObject) patch->extFacetCounts, patch->viewerExtFacets, patch->formatExtFacets);CHKERRQ(ierr);
1148     ierr = ObjectView((PetscObject) patch->extFacets,      patch->viewerExtFacets, patch->formatExtFacets);CHKERRQ(ierr);
1149   }
1150   ierr = ISCreateGeneral(PETSC_COMM_SELF, numPoints, pointsArray, PETSC_OWN_POINTER, &patch->points);CHKERRQ(ierr);
1151   ierr = PetscObjectSetName((PetscObject) patch->points, "Patch Points");CHKERRQ(ierr);
1152   if (patch->viewPoints) {
1153     ierr = ObjectView((PetscObject) patch->pointCounts, patch->viewerPoints, patch->formatPoints);CHKERRQ(ierr);
1154     ierr = ObjectView((PetscObject) patch->points,      patch->viewerPoints, patch->formatPoints);CHKERRQ(ierr);
1155   }
1156   PetscFunctionReturn(0);
1157 }
1158 
1159 /*
1160  * PCPatchCreateCellPatchDiscretisationInfo - Build the dof maps for cell patches
1161  *
1162  * Input Parameters:
1163  * + dm - The DMPlex object defining the mesh
1164  * . cellCounts - Section with counts of cells around each vertex
1165  * . cells - IS of the cell point indices of cells in each patch
1166  * . cellNumbering - Section mapping plex cell points to Firedrake cell indices.
1167  * . nodesPerCell - number of nodes per cell.
1168  * - cellNodeMap - map from cells to node indices (nodesPerCell * numCells)
1169  *
1170  * Output Parameters:
1171  * + dofs - IS of local dof numbers of each cell in the patch, where local is a patch local numbering
1172  * . gtolCounts - Section with counts of dofs per cell patch
1173  * - gtol - IS mapping from global dofs to local dofs for each patch.
1174  */
1175 static PetscErrorCode PCPatchCreateCellPatchDiscretisationInfo(PC pc)
1176 {
1177   PC_PATCH       *patch           = (PC_PATCH *) pc->data;
1178   PetscSection    cellCounts      = patch->cellCounts;
1179   PetscSection    pointCounts     = patch->pointCounts;
1180   PetscSection    gtolCounts, gtolCountsWithArtificial = NULL, gtolCountsWithAll = NULL;
1181   IS              cells           = patch->cells;
1182   IS              points          = patch->points;
1183   PetscSection    cellNumbering   = patch->cellNumbering;
1184   PetscInt        Nf              = patch->nsubspaces;
1185   PetscInt        numCells, numPoints;
1186   PetscInt        numDofs;
1187   PetscInt        numGlobalDofs, numGlobalDofsWithArtificial, numGlobalDofsWithAll;
1188   PetscInt        totalDofsPerCell = patch->totalDofsPerCell;
1189   PetscInt        vStart, vEnd, v;
1190   const PetscInt *cellsArray, *pointsArray;
1191   PetscInt       *newCellsArray   = NULL;
1192   PetscInt       *dofsArray       = NULL;
1193   PetscInt       *dofsArrayWithArtificial = NULL;
1194   PetscInt       *dofsArrayWithAll = NULL;
1195   PetscInt       *offsArray       = NULL;
1196   PetscInt       *offsArrayWithArtificial = NULL;
1197   PetscInt       *offsArrayWithAll = NULL;
1198   PetscInt       *asmArray        = NULL;
1199   PetscInt       *asmArrayWithArtificial = NULL;
1200   PetscInt       *asmArrayWithAll = NULL;
1201   PetscInt       *globalDofsArray = NULL;
1202   PetscInt       *globalDofsArrayWithArtificial = NULL;
1203   PetscInt       *globalDofsArrayWithAll = NULL;
1204   PetscInt        globalIndex     = 0;
1205   PetscInt        key             = 0;
1206   PetscInt        asmKey          = 0;
1207   DM              dm              = NULL;
1208   const PetscInt *bcNodes         = NULL;
1209   PetscHMapI      ht;
1210   PetscHMapI      htWithArtificial;
1211   PetscHMapI      htWithAll;
1212   PetscHSetI      globalBcs;
1213   PetscInt        numBcs;
1214   PetscHSetI      ownedpts, seenpts, owneddofs, seendofs, artificialbcs;
1215   PetscInt        pStart, pEnd, p, i;
1216   char            option[PETSC_MAX_PATH_LEN];
1217   PetscBool       isNonlinear;
1218   PetscErrorCode  ierr;
1219 
1220   PetscFunctionBegin;
1221 
1222   ierr = PCGetDM(pc, &dm); CHKERRQ(ierr);
1223   /* dofcounts section is cellcounts section * dofPerCell */
1224   ierr = PetscSectionGetStorageSize(cellCounts, &numCells);CHKERRQ(ierr);
1225   ierr = PetscSectionGetStorageSize(patch->pointCounts, &numPoints);CHKERRQ(ierr);
1226   numDofs = numCells * totalDofsPerCell;
1227   ierr = PetscMalloc1(numDofs, &dofsArray);CHKERRQ(ierr);
1228   ierr = PetscMalloc1(numPoints*Nf, &offsArray);CHKERRQ(ierr);
1229   ierr = PetscMalloc1(numDofs, &asmArray);CHKERRQ(ierr);
1230   ierr = PetscMalloc1(numCells, &newCellsArray);CHKERRQ(ierr);
1231   ierr = PetscSectionGetChart(cellCounts, &vStart, &vEnd);CHKERRQ(ierr);
1232   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->gtolCounts);CHKERRQ(ierr);
1233   gtolCounts = patch->gtolCounts;
1234   ierr = PetscSectionSetChart(gtolCounts, vStart, vEnd);CHKERRQ(ierr);
1235   ierr = PetscObjectSetName((PetscObject) patch->gtolCounts, "Patch Global Index Section");CHKERRQ(ierr);
1236 
1237   if(patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE)
1238   {
1239     ierr = PetscMalloc1(numPoints*Nf, &offsArrayWithArtificial);CHKERRQ(ierr);
1240     ierr = PetscMalloc1(numDofs, &asmArrayWithArtificial);CHKERRQ(ierr);
1241     ierr = PetscMalloc1(numDofs, &dofsArrayWithArtificial);CHKERRQ(ierr);
1242     ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->gtolCountsWithArtificial);CHKERRQ(ierr);
1243     gtolCountsWithArtificial = patch->gtolCountsWithArtificial;
1244     ierr = PetscSectionSetChart(gtolCountsWithArtificial, vStart, vEnd);CHKERRQ(ierr);
1245     ierr = PetscObjectSetName((PetscObject) patch->gtolCountsWithArtificial, "Patch Global Index Section Including Artificial BCs");CHKERRQ(ierr);
1246   }
1247 
1248   isNonlinear = patch->isNonlinear;
1249   if(isNonlinear)
1250   {
1251     ierr = PetscMalloc1(numPoints*Nf, &offsArrayWithAll);CHKERRQ(ierr);
1252     ierr = PetscMalloc1(numDofs, &asmArrayWithAll);CHKERRQ(ierr);
1253     ierr = PetscMalloc1(numDofs, &dofsArrayWithAll);CHKERRQ(ierr);
1254     ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->gtolCountsWithAll);CHKERRQ(ierr);
1255     gtolCountsWithAll = patch->gtolCountsWithAll;
1256     ierr = PetscSectionSetChart(gtolCountsWithAll, vStart, vEnd);CHKERRQ(ierr);
1257     ierr = PetscObjectSetName((PetscObject) patch->gtolCountsWithAll, "Patch Global Index Section Including All BCs");CHKERRQ(ierr);
1258   }
1259 
1260   /* Outside the patch loop, get the dofs that are globally-enforced Dirichlet
1261    conditions */
1262   ierr = PetscHSetICreate(&globalBcs);CHKERRQ(ierr);
1263   ierr = ISGetIndices(patch->ghostBcNodes, &bcNodes); CHKERRQ(ierr);
1264   ierr = ISGetSize(patch->ghostBcNodes, &numBcs); CHKERRQ(ierr);
1265   for (i = 0; i < numBcs; ++i) {
1266     ierr = PetscHSetIAdd(globalBcs, bcNodes[i]);CHKERRQ(ierr); /* these are already in concatenated numbering */
1267   }
1268   ierr = ISRestoreIndices(patch->ghostBcNodes, &bcNodes); CHKERRQ(ierr);
1269   ierr = ISDestroy(&patch->ghostBcNodes); CHKERRQ(ierr); /* memory optimisation */
1270 
1271   /* Hash tables for artificial BC construction */
1272   ierr = PetscHSetICreate(&ownedpts);CHKERRQ(ierr);
1273   ierr = PetscHSetICreate(&seenpts);CHKERRQ(ierr);
1274   ierr = PetscHSetICreate(&owneddofs);CHKERRQ(ierr);
1275   ierr = PetscHSetICreate(&seendofs);CHKERRQ(ierr);
1276   ierr = PetscHSetICreate(&artificialbcs);CHKERRQ(ierr);
1277 
1278   ierr = ISGetIndices(cells, &cellsArray);CHKERRQ(ierr);
1279   ierr = ISGetIndices(points, &pointsArray);CHKERRQ(ierr);
1280   ierr = PetscHMapICreate(&ht);CHKERRQ(ierr);
1281   ierr = PetscHMapICreate(&htWithArtificial);CHKERRQ(ierr);
1282   ierr = PetscHMapICreate(&htWithAll);CHKERRQ(ierr);
1283   for (v = vStart; v < vEnd; ++v) {
1284     PetscInt localIndex = 0;
1285     PetscInt localIndexWithArtificial = 0;
1286     PetscInt localIndexWithAll = 0;
1287     PetscInt dof, off, i, j, k, l;
1288 
1289     ierr = PetscHMapIClear(ht);CHKERRQ(ierr);
1290     ierr = PetscHMapIClear(htWithArtificial);CHKERRQ(ierr);
1291     ierr = PetscHMapIClear(htWithAll);CHKERRQ(ierr);
1292     ierr = PetscSectionGetDof(cellCounts, v, &dof);CHKERRQ(ierr);
1293     ierr = PetscSectionGetOffset(cellCounts, v, &off);CHKERRQ(ierr);
1294     if (dof <= 0) continue;
1295 
1296     /* Calculate the global numbers of the artificial BC dofs here first */
1297     ierr = patch->patchconstructop((void*)patch, dm, v, ownedpts); CHKERRQ(ierr);
1298     ierr = PCPatchCompleteCellPatch(pc, ownedpts, seenpts); CHKERRQ(ierr);
1299     ierr = PCPatchGetPointDofs(pc, ownedpts, owneddofs, v, &patch->subspaces_to_exclude); CHKERRQ(ierr);
1300     ierr = PCPatchGetPointDofs(pc, seenpts, seendofs, v, NULL); CHKERRQ(ierr);
1301     ierr = PCPatchComputeSetDifference_Private(owneddofs, seendofs, artificialbcs); CHKERRQ(ierr);
1302     if (patch->viewPatches) {
1303       PetscHSetI globalbcdofs;
1304       PetscHashIter hi;
1305       MPI_Comm comm = PetscObjectComm((PetscObject)pc);
1306 
1307       ierr = PetscHSetICreate(&globalbcdofs);CHKERRQ(ierr);
1308       ierr = PetscSynchronizedPrintf(comm, "Patch %d: owned dofs:\n", v); CHKERRQ(ierr);
1309       PetscHashIterBegin(owneddofs, hi);
1310       while (!PetscHashIterAtEnd(owneddofs, hi)) {
1311         PetscInt globalDof;
1312 
1313         PetscHashIterGetKey(owneddofs, hi, globalDof);
1314         PetscHashIterNext(owneddofs, hi);
1315         ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof); CHKERRQ(ierr);
1316       }
1317       ierr = PetscSynchronizedPrintf(comm, "\n"); CHKERRQ(ierr);
1318       ierr = PetscSynchronizedPrintf(comm, "Patch %d: seen dofs:\n", v); CHKERRQ(ierr);
1319       PetscHashIterBegin(seendofs, hi);
1320       while (!PetscHashIterAtEnd(seendofs, hi)) {
1321         PetscInt globalDof;
1322         PetscBool flg;
1323 
1324         PetscHashIterGetKey(seendofs, hi, globalDof);
1325         PetscHashIterNext(seendofs, hi);
1326         ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof); CHKERRQ(ierr);
1327 
1328         ierr = PetscHSetIHas(globalBcs, globalDof, &flg);CHKERRQ(ierr);
1329         if (flg) {ierr = PetscHSetIAdd(globalbcdofs, globalDof);CHKERRQ(ierr);}
1330       }
1331       ierr = PetscSynchronizedPrintf(comm, "\n"); CHKERRQ(ierr);
1332       ierr = PetscSynchronizedPrintf(comm, "Patch %d: global BCs:\n", v); CHKERRQ(ierr);
1333       ierr = PetscHSetIGetSize(globalbcdofs, &numBcs);CHKERRQ(ierr);
1334       if (numBcs > 0) {
1335         PetscHashIterBegin(globalbcdofs, hi);
1336         while (!PetscHashIterAtEnd(globalbcdofs, hi)) {
1337           PetscInt globalDof;
1338           PetscHashIterGetKey(globalbcdofs, hi, globalDof);
1339           PetscHashIterNext(globalbcdofs, hi);
1340           ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof);CHKERRQ(ierr);
1341         }
1342       }
1343       ierr = PetscSynchronizedPrintf(comm, "\n");CHKERRQ(ierr);
1344       ierr = PetscSynchronizedPrintf(comm, "Patch %d: artificial BCs:\n", v);CHKERRQ(ierr);
1345       ierr = PetscHSetIGetSize(artificialbcs, &numBcs);CHKERRQ(ierr);
1346       if (numBcs > 0) {
1347         PetscHashIterBegin(artificialbcs, hi);
1348         while (!PetscHashIterAtEnd(artificialbcs, hi)) {
1349           PetscInt globalDof;
1350           PetscHashIterGetKey(artificialbcs, hi, globalDof);
1351           PetscHashIterNext(artificialbcs, hi);
1352           ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof); CHKERRQ(ierr);
1353         }
1354       }
1355       ierr = PetscSynchronizedPrintf(comm, "\n\n"); CHKERRQ(ierr);
1356       ierr = PetscHSetIDestroy(&globalbcdofs);CHKERRQ(ierr);
1357     }
1358    for (k = 0; k < patch->nsubspaces; ++k) {
1359       const PetscInt *cellNodeMap    = patch->cellNodeMap[k];
1360       PetscInt        nodesPerCell   = patch->nodesPerCell[k];
1361       PetscInt        subspaceOffset = patch->subspaceOffsets[k];
1362       PetscInt        bs             = patch->bs[k];
1363 
1364       for (i = off; i < off + dof; ++i) {
1365         /* Walk over the cells in this patch. */
1366         const PetscInt c    = cellsArray[i];
1367         PetscInt       cell = c;
1368 
1369         /* TODO Change this to an IS */
1370         if (cellNumbering) {
1371           ierr = PetscSectionGetDof(cellNumbering, c, &cell);CHKERRQ(ierr);
1372           if (cell <= 0) SETERRQ1(PetscObjectComm((PetscObject) pc), PETSC_ERR_ARG_OUTOFRANGE, "Cell %D doesn't appear in cell numbering map", c);
1373           ierr = PetscSectionGetOffset(cellNumbering, c, &cell);CHKERRQ(ierr);
1374         }
1375         newCellsArray[i] = cell;
1376         for (j = 0; j < nodesPerCell; ++j) {
1377           /* For each global dof, map it into contiguous local storage. */
1378           const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + subspaceOffset;
1379           /* finally, loop over block size */
1380           for (l = 0; l < bs; ++l) {
1381             PetscInt  localDof;
1382             PetscBool isGlobalBcDof, isArtificialBcDof;
1383 
1384             /* first, check if this is either a globally enforced or locally enforced BC dof */
1385             ierr = PetscHSetIHas(globalBcs, globalDof + l, &isGlobalBcDof);CHKERRQ(ierr);
1386             ierr = PetscHSetIHas(artificialbcs, globalDof + l, &isArtificialBcDof);CHKERRQ(ierr);
1387 
1388             /* if it's either, don't ever give it a local dof number */
1389             if (isGlobalBcDof || isArtificialBcDof) {
1390               dofsArray[globalIndex] = -1; /* don't use this in assembly in this patch */
1391             } else {
1392               ierr = PetscHMapIGet(ht, globalDof + l, &localDof);CHKERRQ(ierr);
1393               if (localDof == -1) {
1394                 localDof = localIndex++;
1395                 ierr = PetscHMapISet(ht, globalDof + l, localDof);CHKERRQ(ierr);
1396               }
1397               if ( globalIndex >= numDofs ) SETERRQ2(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "Found more dofs %D than expected %D", globalIndex+1, numDofs);
1398               /* And store. */
1399               dofsArray[globalIndex] = localDof;
1400             }
1401 
1402             if(patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1403               if (isGlobalBcDof) {
1404                 dofsArrayWithArtificial[globalIndex] = -1; /* don't use this in assembly in this patch */
1405               } else {
1406                 ierr = PetscHMapIGet(htWithArtificial, globalDof + l, &localDof);CHKERRQ(ierr);
1407                 if (localDof == -1) {
1408                   localDof = localIndexWithArtificial++;
1409                   ierr = PetscHMapISet(htWithArtificial, globalDof + l, localDof);CHKERRQ(ierr);
1410                 }
1411                 if ( globalIndex >= numDofs ) SETERRQ2(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "Found more dofs %D than expected %D", globalIndex+1, numDofs);
1412                 /* And store.*/
1413                 dofsArrayWithArtificial[globalIndex] = localDof;
1414               }
1415             }
1416 
1417             if(isNonlinear) {
1418               /* Build the dofmap for the function space with _all_ dofs,
1419                  including those in any kind of boundary condition */
1420               ierr = PetscHMapIGet(htWithAll, globalDof + l, &localDof);CHKERRQ(ierr);
1421               if (localDof == -1) {
1422                 localDof = localIndexWithAll++;
1423                 ierr = PetscHMapISet(htWithAll, globalDof + l, localDof);CHKERRQ(ierr);
1424               }
1425               if ( globalIndex >= numDofs ) SETERRQ2(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "Found more dofs %D than expected %D", globalIndex+1, numDofs);
1426               /* And store.*/
1427               dofsArrayWithAll[globalIndex] = localDof;
1428             }
1429             globalIndex++;
1430           }
1431         }
1432       }
1433     }
1434      /*How many local dofs in this patch? */
1435    if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1436      ierr = PetscHMapIGetSize(htWithArtificial, &dof);CHKERRQ(ierr);
1437      ierr = PetscSectionSetDof(gtolCountsWithArtificial, v, dof);CHKERRQ(ierr);
1438    }
1439    if (isNonlinear) {
1440      ierr = PetscHMapIGetSize(htWithAll, &dof);CHKERRQ(ierr);
1441      ierr = PetscSectionSetDof(gtolCountsWithAll, v, dof);CHKERRQ(ierr);
1442    }
1443     ierr = PetscHMapIGetSize(ht, &dof);CHKERRQ(ierr);
1444     ierr = PetscSectionSetDof(gtolCounts, v, dof);CHKERRQ(ierr);
1445   }
1446   if (globalIndex != numDofs) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Expected number of dofs (%d) doesn't match found number (%d)", numDofs, globalIndex);
1447   ierr = PetscSectionSetUp(gtolCounts);CHKERRQ(ierr);
1448   ierr = PetscSectionGetStorageSize(gtolCounts, &numGlobalDofs);CHKERRQ(ierr);
1449   ierr = PetscMalloc1(numGlobalDofs, &globalDofsArray);CHKERRQ(ierr);
1450 
1451   if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1452     ierr = PetscSectionSetUp(gtolCountsWithArtificial);CHKERRQ(ierr);
1453     ierr = PetscSectionGetStorageSize(gtolCountsWithArtificial, &numGlobalDofsWithArtificial);CHKERRQ(ierr);
1454     ierr = PetscMalloc1(numGlobalDofsWithArtificial, &globalDofsArrayWithArtificial);CHKERRQ(ierr);
1455   }
1456   if (isNonlinear) {
1457     ierr = PetscSectionSetUp(gtolCountsWithAll);CHKERRQ(ierr);
1458     ierr = PetscSectionGetStorageSize(gtolCountsWithAll, &numGlobalDofsWithAll);CHKERRQ(ierr);
1459     ierr = PetscMalloc1(numGlobalDofsWithAll, &globalDofsArrayWithAll);CHKERRQ(ierr);
1460   }
1461   /* Now populate the global to local map.  This could be merged into the above loop if we were willing to deal with reallocs. */
1462   for (v = vStart; v < vEnd; ++v) {
1463     PetscHashIter hi;
1464     PetscInt      dof, off, Np, ooff, i, j, k, l;
1465 
1466     ierr = PetscHMapIClear(ht);CHKERRQ(ierr);
1467     ierr = PetscHMapIClear(htWithArtificial);CHKERRQ(ierr);
1468     ierr = PetscHMapIClear(htWithAll);CHKERRQ(ierr);
1469     ierr = PetscSectionGetDof(cellCounts, v, &dof);CHKERRQ(ierr);
1470     ierr = PetscSectionGetOffset(cellCounts, v, &off);CHKERRQ(ierr);
1471     ierr = PetscSectionGetDof(pointCounts, v, &Np);CHKERRQ(ierr);
1472     ierr = PetscSectionGetOffset(pointCounts, v, &ooff);CHKERRQ(ierr);
1473     if (dof <= 0) continue;
1474 
1475     for (k = 0; k < patch->nsubspaces; ++k) {
1476       const PetscInt *cellNodeMap    = patch->cellNodeMap[k];
1477       PetscInt        nodesPerCell   = patch->nodesPerCell[k];
1478       PetscInt        subspaceOffset = patch->subspaceOffsets[k];
1479       PetscInt        bs             = patch->bs[k];
1480       PetscInt        goff;
1481 
1482       for (i = off; i < off + dof; ++i) {
1483         /* Reconstruct mapping of global-to-local on this patch. */
1484         const PetscInt c    = cellsArray[i];
1485         PetscInt       cell = c;
1486 
1487         if (cellNumbering) {ierr = PetscSectionGetOffset(cellNumbering, c, &cell);CHKERRQ(ierr);}
1488         for (j = 0; j < nodesPerCell; ++j) {
1489           for (l = 0; l < bs; ++l) {
1490             const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + l + subspaceOffset;
1491             const PetscInt localDof  = dofsArray[key];
1492             if (localDof >= 0) {ierr = PetscHMapISet(ht, globalDof, localDof);CHKERRQ(ierr);}
1493             if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1494               const PetscInt localDofWithArtificial = dofsArrayWithArtificial[key];
1495               if (localDofWithArtificial >= 0) {
1496                 ierr = PetscHMapISet(htWithArtificial, globalDof, localDofWithArtificial);CHKERRQ(ierr);
1497               }
1498             }
1499             if (isNonlinear) {
1500               const PetscInt localDofWithAll = dofsArrayWithAll[key];
1501               if (localDofWithAll >= 0) {
1502                 ierr = PetscHMapISet(htWithAll, globalDof, localDofWithAll);CHKERRQ(ierr);
1503               }
1504             }
1505             key++;
1506           }
1507         }
1508       }
1509 
1510       /* Shove it in the output data structure. */
1511       ierr = PetscSectionGetOffset(gtolCounts, v, &goff);CHKERRQ(ierr);
1512       PetscHashIterBegin(ht, hi);
1513       while (!PetscHashIterAtEnd(ht, hi)) {
1514         PetscInt globalDof, localDof;
1515 
1516         PetscHashIterGetKey(ht, hi, globalDof);
1517         PetscHashIterGetVal(ht, hi, localDof);
1518         if (globalDof >= 0) globalDofsArray[goff + localDof] = globalDof;
1519         PetscHashIterNext(ht, hi);
1520       }
1521 
1522       if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1523         ierr = PetscSectionGetOffset(gtolCountsWithArtificial, v, &goff);CHKERRQ(ierr);
1524         PetscHashIterBegin(htWithArtificial, hi);
1525         while (!PetscHashIterAtEnd(htWithArtificial, hi)) {
1526           PetscInt globalDof, localDof;
1527           PetscHashIterGetKey(htWithArtificial, hi, globalDof);
1528           PetscHashIterGetVal(htWithArtificial, hi, localDof);
1529           if (globalDof >= 0) globalDofsArrayWithArtificial[goff + localDof] = globalDof;
1530           PetscHashIterNext(htWithArtificial, hi);
1531         }
1532       }
1533       if (isNonlinear) {
1534         ierr = PetscSectionGetOffset(gtolCountsWithAll, v, &goff);CHKERRQ(ierr);
1535         PetscHashIterBegin(htWithAll, hi);
1536         while (!PetscHashIterAtEnd(htWithAll, hi)) {
1537           PetscInt globalDof, localDof;
1538           PetscHashIterGetKey(htWithAll, hi, globalDof);
1539           PetscHashIterGetVal(htWithAll, hi, localDof);
1540           if (globalDof >= 0) globalDofsArrayWithAll[goff + localDof] = globalDof;
1541           PetscHashIterNext(htWithAll, hi);
1542         }
1543       }
1544 
1545       for (p = 0; p < Np; ++p) {
1546         const PetscInt point = pointsArray[ooff + p];
1547         PetscInt       globalDof, localDof;
1548 
1549         ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, k, patch->combined, point, NULL, &globalDof);CHKERRQ(ierr);
1550         ierr = PetscHMapIGet(ht, globalDof, &localDof);CHKERRQ(ierr);
1551         offsArray[(ooff + p)*Nf + k] = localDof;
1552         if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1553           ierr = PetscHMapIGet(htWithArtificial, globalDof, &localDof);CHKERRQ(ierr);
1554           offsArrayWithArtificial[(ooff + p)*Nf + k] = localDof;
1555         }
1556         if (isNonlinear) {
1557           ierr = PetscHMapIGet(htWithAll, globalDof, &localDof);CHKERRQ(ierr);
1558           offsArrayWithAll[(ooff + p)*Nf + k] = localDof;
1559         }
1560       }
1561     }
1562 
1563     ierr = PetscHSetIDestroy(&globalBcs);CHKERRQ(ierr);
1564     ierr = PetscHSetIDestroy(&ownedpts);CHKERRQ(ierr);
1565     ierr = PetscHSetIDestroy(&seenpts);CHKERRQ(ierr);
1566     ierr = PetscHSetIDestroy(&owneddofs);CHKERRQ(ierr);
1567     ierr = PetscHSetIDestroy(&seendofs);CHKERRQ(ierr);
1568     ierr = PetscHSetIDestroy(&artificialbcs);CHKERRQ(ierr);
1569 
1570       /* At this point, we have a hash table ht built that maps globalDof -> localDof.
1571      We need to create the dof table laid out cellwise first, then by subspace,
1572      as the assembler assembles cell-wise and we need to stuff the different
1573      contributions of the different function spaces to the right places. So we loop
1574      over cells, then over subspaces. */
1575     if (patch->nsubspaces > 1) { /* for nsubspaces = 1, data we need is already in dofsArray */
1576       for (i = off; i < off + dof; ++i) {
1577         const PetscInt c    = cellsArray[i];
1578         PetscInt       cell = c;
1579 
1580         if (cellNumbering) {ierr = PetscSectionGetOffset(cellNumbering, c, &cell);CHKERRQ(ierr);}
1581         for (k = 0; k < patch->nsubspaces; ++k) {
1582           const PetscInt *cellNodeMap    = patch->cellNodeMap[k];
1583           PetscInt        nodesPerCell   = patch->nodesPerCell[k];
1584           PetscInt        subspaceOffset = patch->subspaceOffsets[k];
1585           PetscInt        bs             = patch->bs[k];
1586 
1587           for (j = 0; j < nodesPerCell; ++j) {
1588             for (l = 0; l < bs; ++l) {
1589               const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + l + subspaceOffset;
1590               PetscInt       localDof;
1591 
1592               ierr = PetscHMapIGet(ht, globalDof, &localDof);CHKERRQ(ierr);
1593               /* If it's not in the hash table, i.e. is a BC dof,
1594                then the PetscHSetIMap above gives -1, which matches
1595                exactly the convention for PETSc's matrix assembly to
1596                ignore the dof. So we don't need to do anything here */
1597               asmArray[asmKey] = localDof;
1598               if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1599                 ierr = PetscHMapIGet(htWithArtificial, globalDof, &localDof);CHKERRQ(ierr);
1600                 asmArrayWithArtificial[asmKey] = localDof;
1601               }
1602               if (isNonlinear) {
1603                 ierr = PetscHMapIGet(htWithAll, globalDof, &localDof);CHKERRQ(ierr);
1604                 asmArrayWithAll[asmKey] = localDof;
1605               }
1606               asmKey++;
1607             }
1608           }
1609         }
1610       }
1611     }
1612   }
1613   if (1 == patch->nsubspaces) {
1614     ierr = PetscMemcpy(asmArray, dofsArray, numDofs * sizeof(PetscInt));CHKERRQ(ierr);
1615     if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1616       ierr = PetscMemcpy(asmArrayWithArtificial, dofsArrayWithArtificial, numDofs * sizeof(PetscInt));CHKERRQ(ierr);
1617     }
1618     if (isNonlinear) {
1619       ierr = PetscMemcpy(asmArrayWithAll, dofsArrayWithAll, numDofs * sizeof(PetscInt));CHKERRQ(ierr);
1620     }
1621   }
1622 
1623   ierr = PetscHMapIDestroy(&ht);CHKERRQ(ierr);
1624   ierr = PetscHMapIDestroy(&htWithArtificial);CHKERRQ(ierr);
1625   ierr = PetscHMapIDestroy(&htWithAll);CHKERRQ(ierr);
1626   ierr = ISRestoreIndices(cells, &cellsArray);CHKERRQ(ierr);
1627   ierr = ISRestoreIndices(points, &pointsArray);CHKERRQ(ierr);
1628   ierr = PetscFree(dofsArray);CHKERRQ(ierr);
1629   if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1630     ierr = PetscFree(dofsArrayWithArtificial);CHKERRQ(ierr);
1631   }
1632   if (isNonlinear) {
1633     ierr = PetscFree(dofsArrayWithAll);CHKERRQ(ierr);
1634   }
1635   /* Create placeholder section for map from points to patch dofs */
1636   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->patchSection);CHKERRQ(ierr);
1637   ierr = PetscSectionSetNumFields(patch->patchSection, patch->nsubspaces);CHKERRQ(ierr);
1638   if (patch->combined) {
1639     PetscInt numFields;
1640     ierr = PetscSectionGetNumFields(patch->dofSection[0], &numFields);CHKERRQ(ierr);
1641     if (numFields != patch->nsubspaces) SETERRQ2(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONG, "Mismatch between number of section fields %D and number of subspaces %D", numFields, patch->nsubspaces);
1642     ierr = PetscSectionGetChart(patch->dofSection[0], &pStart, &pEnd);CHKERRQ(ierr);
1643     ierr = PetscSectionSetChart(patch->patchSection, pStart, pEnd);CHKERRQ(ierr);
1644     for (p = pStart; p < pEnd; ++p) {
1645       PetscInt dof, fdof, f;
1646 
1647       ierr = PetscSectionGetDof(patch->dofSection[0], p, &dof);CHKERRQ(ierr);
1648       ierr = PetscSectionSetDof(patch->patchSection, p, dof);CHKERRQ(ierr);
1649       for (f = 0; f < patch->nsubspaces; ++f) {
1650         ierr = PetscSectionGetFieldDof(patch->dofSection[0], p, f, &fdof);CHKERRQ(ierr);
1651         ierr = PetscSectionSetFieldDof(patch->patchSection, p, f, fdof);CHKERRQ(ierr);
1652       }
1653     }
1654   } else {
1655     PetscInt pStartf, pEndf, f;
1656     pStart = PETSC_MAX_INT;
1657     pEnd = PETSC_MIN_INT;
1658     for (f = 0; f < patch->nsubspaces; ++f) {
1659       ierr = PetscSectionGetChart(patch->dofSection[f], &pStartf, &pEndf);CHKERRQ(ierr);
1660       pStart = PetscMin(pStart, pStartf);
1661       pEnd = PetscMax(pEnd, pEndf);
1662     }
1663     ierr = PetscSectionSetChart(patch->patchSection, pStart, pEnd);CHKERRQ(ierr);
1664     for (f = 0; f < patch->nsubspaces; ++f) {
1665       ierr = PetscSectionGetChart(patch->dofSection[f], &pStartf, &pEndf);CHKERRQ(ierr);
1666       for (p = pStartf; p < pEndf; ++p) {
1667         PetscInt fdof;
1668         ierr = PetscSectionGetDof(patch->dofSection[f], p, &fdof);CHKERRQ(ierr);
1669         ierr = PetscSectionAddDof(patch->patchSection, p, fdof);CHKERRQ(ierr);
1670         ierr = PetscSectionSetFieldDof(patch->patchSection, p, f, fdof);CHKERRQ(ierr);
1671       }
1672     }
1673   }
1674   ierr = PetscSectionSetUp(patch->patchSection);CHKERRQ(ierr);
1675   ierr = PetscSectionSetUseFieldOffsets(patch->patchSection, PETSC_TRUE);CHKERRQ(ierr);
1676   /* Replace cell indices with firedrake-numbered ones. */
1677   ierr = ISGeneralSetIndices(cells, numCells, (const PetscInt *) newCellsArray, PETSC_OWN_POINTER);CHKERRQ(ierr);
1678   ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalDofs, globalDofsArray, PETSC_OWN_POINTER, &patch->gtol);CHKERRQ(ierr);
1679   ierr = PetscObjectSetName((PetscObject) patch->gtol, "Global Indices");CHKERRQ(ierr);
1680   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_g2l_view", patch->classname);CHKERRQ(ierr);
1681   ierr = PetscSectionViewFromOptions(patch->gtolCounts, (PetscObject) pc, option);CHKERRQ(ierr);
1682   ierr = ISViewFromOptions(patch->gtol, (PetscObject) pc, option);CHKERRQ(ierr);
1683   ierr = ISCreateGeneral(PETSC_COMM_SELF, numDofs, asmArray, PETSC_OWN_POINTER, &patch->dofs);CHKERRQ(ierr);
1684   ierr = ISCreateGeneral(PETSC_COMM_SELF, numPoints*Nf, offsArray, PETSC_OWN_POINTER, &patch->offs);CHKERRQ(ierr);
1685   if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1686     ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalDofsWithArtificial, globalDofsArrayWithArtificial, PETSC_OWN_POINTER, &patch->gtolWithArtificial);CHKERRQ(ierr);
1687     ierr = ISCreateGeneral(PETSC_COMM_SELF, numDofs, asmArrayWithArtificial, PETSC_OWN_POINTER, &patch->dofsWithArtificial);CHKERRQ(ierr);
1688     ierr = ISCreateGeneral(PETSC_COMM_SELF, numPoints*Nf, offsArrayWithArtificial, PETSC_OWN_POINTER, &patch->offsWithArtificial);CHKERRQ(ierr);
1689   }
1690   if (isNonlinear) {
1691     ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalDofsWithAll, globalDofsArrayWithAll, PETSC_OWN_POINTER, &patch->gtolWithAll);CHKERRQ(ierr);
1692     ierr = ISCreateGeneral(PETSC_COMM_SELF, numDofs, asmArrayWithAll, PETSC_OWN_POINTER, &patch->dofsWithAll);CHKERRQ(ierr);
1693     ierr = ISCreateGeneral(PETSC_COMM_SELF, numPoints*Nf, offsArrayWithAll, PETSC_OWN_POINTER, &patch->offsWithAll);CHKERRQ(ierr);
1694   }
1695   PetscFunctionReturn(0);
1696 }
1697 
1698 static PetscErrorCode PCPatchCreateMatrix_Private(PC pc, PetscInt point, Mat *mat, PetscBool withArtificial)
1699 {
1700   PC_PATCH      *patch = (PC_PATCH *) pc->data;
1701   Vec            x, y;
1702   PetscBool      flg;
1703   PetscInt       csize, rsize;
1704   const char    *prefix = NULL;
1705   PetscErrorCode ierr;
1706 
1707   PetscFunctionBegin;
1708   if(withArtificial) {
1709     /* would be nice if we could create a rectangular matrix of size numDofsWithArtificial x numDofs here */
1710     x = patch->patchRHSWithArtificial[point];
1711     y = patch->patchRHSWithArtificial[point];
1712   } else {
1713     x = patch->patchRHS[point];
1714     y = patch->patchUpdate[point];
1715   }
1716 
1717   ierr = VecGetSize(x, &csize);CHKERRQ(ierr);
1718   ierr = VecGetSize(y, &rsize);CHKERRQ(ierr);
1719   ierr = MatCreate(PETSC_COMM_SELF, mat);CHKERRQ(ierr);
1720   ierr = PCGetOptionsPrefix(pc, &prefix);CHKERRQ(ierr);
1721   ierr = MatSetOptionsPrefix(*mat, prefix);CHKERRQ(ierr);
1722   ierr = MatAppendOptionsPrefix(*mat, "pc_patch_sub_");CHKERRQ(ierr);
1723   if (patch->sub_mat_type)       {ierr = MatSetType(*mat, patch->sub_mat_type);CHKERRQ(ierr);}
1724   else if (!patch->sub_mat_type) {ierr = MatSetType(*mat, MATDENSE);CHKERRQ(ierr);}
1725   ierr = MatSetSizes(*mat, rsize, csize, rsize, csize);CHKERRQ(ierr);
1726   ierr = PetscObjectTypeCompare((PetscObject) *mat, MATDENSE, &flg);CHKERRQ(ierr);
1727   if (!flg) {ierr = PetscObjectTypeCompare((PetscObject)*mat, MATSEQDENSE, &flg);CHKERRQ(ierr);}
1728   /* Sparse patch matrices */
1729   if (!flg) {
1730     PetscBT         bt;
1731     PetscInt       *dnnz      = NULL;
1732     const PetscInt *dofsArray = NULL;
1733     PetscInt        pStart, pEnd, ncell, offset, c, i, j;
1734 
1735     if(withArtificial) {
1736       ierr = ISGetIndices(patch->dofsWithArtificial, &dofsArray);CHKERRQ(ierr);
1737     } else {
1738       ierr = ISGetIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
1739     }
1740     ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd);CHKERRQ(ierr);
1741     point += pStart;
1742     if (point >= pEnd) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Operator point %D not in [%D, %D)\n", point, pStart, pEnd);CHKERRQ(ierr);
1743     ierr = PetscSectionGetDof(patch->cellCounts, point, &ncell);CHKERRQ(ierr);
1744     ierr = PetscSectionGetOffset(patch->cellCounts, point, &offset);CHKERRQ(ierr);
1745     ierr = PetscLogEventBegin(PC_Patch_Prealloc, pc, 0, 0, 0);CHKERRQ(ierr);
1746     /* A PetscBT uses N^2 bits to store the sparsity pattern on a
1747      * patch. This is probably OK if the patches are not too big,
1748      * but uses too much memory. We therefore switch based on rsize. */
1749     if (rsize < 3000) { /* FIXME: I picked this switch value out of my hat */
1750       PetscScalar *zeroes;
1751       PetscInt rows;
1752 
1753       ierr = PetscCalloc1(rsize, &dnnz);CHKERRQ(ierr);
1754       ierr = PetscBTCreate(rsize*rsize, &bt);CHKERRQ(ierr);
1755       for (c = 0; c < ncell; ++c) {
1756         const PetscInt *idx = dofsArray + (offset + c)*patch->totalDofsPerCell;
1757         for (i = 0; i < patch->totalDofsPerCell; ++i) {
1758           const PetscInt row = idx[i];
1759           if (row < 0) continue;
1760           for (j = 0; j < patch->totalDofsPerCell; ++j) {
1761             const PetscInt col = idx[j];
1762             const PetscInt key = row*rsize + col;
1763             if (col < 0) continue;
1764             if (!PetscBTLookupSet(bt, key)) ++dnnz[row];
1765           }
1766         }
1767       }
1768 
1769       if (patch->usercomputeopintfacet) {
1770         const PetscInt *intFacetsArray = NULL;
1771         PetscInt i, numIntFacets, intFacetOffset;
1772         const PetscInt *facetCells = NULL;
1773 
1774         ierr = PetscSectionGetDof(patch->intFacetCounts, point, &numIntFacets);CHKERRQ(ierr);
1775         ierr = PetscSectionGetOffset(patch->intFacetCounts, point, &intFacetOffset);CHKERRQ(ierr);
1776         ierr = ISGetIndices(patch->intFacetsToPatchCell, &facetCells);CHKERRQ(ierr);
1777         ierr = ISGetIndices(patch->intFacets, &intFacetsArray);CHKERRQ(ierr);
1778         for (i = 0; i < numIntFacets; i++) {
1779           const PetscInt cell0 = facetCells[2*(intFacetOffset + i) + 0];
1780           const PetscInt cell1 = facetCells[2*(intFacetOffset + i) + 1];
1781           PetscInt celli, cellj;
1782 
1783           for (celli = 0; celli < patch->totalDofsPerCell; celli++) {
1784             const PetscInt row = dofsArray[(offset + cell0)*patch->totalDofsPerCell + celli];
1785             if (row < 0) continue;
1786             for (cellj = 0; cellj < patch->totalDofsPerCell; cellj++) {
1787                 const PetscInt col = dofsArray[(offset + cell1)*patch->totalDofsPerCell + cellj];
1788                 const PetscInt key = row*rsize + col;
1789                 if (col < 0) continue;
1790                 if (!PetscBTLookupSet(bt, key)) ++dnnz[row];
1791             }
1792           }
1793 
1794           for (celli = 0; celli < patch->totalDofsPerCell; celli++) {
1795             const PetscInt row = dofsArray[(offset + cell1)*patch->totalDofsPerCell + celli];
1796             if (row < 0) continue;
1797             for (cellj = 0; cellj < patch->totalDofsPerCell; cellj++) {
1798                 const PetscInt col = dofsArray[(offset + cell0)*patch->totalDofsPerCell + cellj];
1799                 const PetscInt key = row*rsize + col;
1800                 if (col < 0) continue;
1801                 if (!PetscBTLookupSet(bt, key)) ++dnnz[row];
1802             }
1803           }
1804         }
1805       }
1806       ierr = PetscBTDestroy(&bt);CHKERRQ(ierr);
1807       ierr = MatXAIJSetPreallocation(*mat, 1, dnnz, NULL, NULL, NULL);CHKERRQ(ierr);
1808       ierr = PetscFree(dnnz);CHKERRQ(ierr);
1809 
1810       ierr = PetscCalloc1(patch->totalDofsPerCell*patch->totalDofsPerCell, &zeroes);CHKERRQ(ierr);
1811       for (c = 0; c < ncell; ++c) {
1812         const PetscInt *idx = &dofsArray[(offset + c)*patch->totalDofsPerCell];
1813         ierr = MatSetValues(*mat, patch->totalDofsPerCell, idx, patch->totalDofsPerCell, idx, zeroes, INSERT_VALUES);CHKERRQ(ierr);
1814       }
1815       ierr = MatGetLocalSize(*mat, &rows, NULL);CHKERRQ(ierr);
1816       for (i = 0; i < rows; ++i) {
1817         ierr = MatSetValues(*mat, 1, &i, 1, &i, zeroes, INSERT_VALUES);CHKERRQ(ierr);
1818       }
1819 
1820       if (patch->usercomputeopintfacet) {
1821         const PetscInt *intFacetsArray = NULL;
1822         PetscInt i, numIntFacets, intFacetOffset;
1823         const PetscInt *facetCells = NULL;
1824 
1825         ierr = PetscSectionGetDof(patch->intFacetCounts, point, &numIntFacets);CHKERRQ(ierr);
1826         ierr = PetscSectionGetOffset(patch->intFacetCounts, point, &intFacetOffset);CHKERRQ(ierr);
1827         ierr = ISGetIndices(patch->intFacetsToPatchCell, &facetCells);CHKERRQ(ierr);
1828         ierr = ISGetIndices(patch->intFacets, &intFacetsArray);CHKERRQ(ierr);
1829         for (i = 0; i < numIntFacets; i++) {
1830           const PetscInt cell0 = facetCells[2*(intFacetOffset + i) + 0];
1831           const PetscInt cell1 = facetCells[2*(intFacetOffset + i) + 1];
1832           const PetscInt *cell0idx = &dofsArray[(offset + cell0)*patch->totalDofsPerCell];
1833           const PetscInt *cell1idx = &dofsArray[(offset + cell1)*patch->totalDofsPerCell];
1834           ierr = MatSetValues(*mat, patch->totalDofsPerCell, cell0idx, patch->totalDofsPerCell, cell1idx, zeroes, INSERT_VALUES);CHKERRQ(ierr);
1835           ierr = MatSetValues(*mat, patch->totalDofsPerCell, cell1idx, patch->totalDofsPerCell, cell0idx, zeroes, INSERT_VALUES);CHKERRQ(ierr);
1836         }
1837       }
1838 
1839       ierr = MatAssemblyBegin(*mat, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
1840       ierr = MatAssemblyEnd(*mat, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
1841 
1842       ierr = PetscFree(zeroes);CHKERRQ(ierr);
1843 
1844     } else { /* rsize too big, use MATPREALLOCATOR */
1845       Mat preallocator;
1846       PetscScalar* vals;
1847 
1848       ierr = PetscCalloc1(patch->totalDofsPerCell*patch->totalDofsPerCell, &vals);CHKERRQ(ierr);
1849       ierr = MatCreate(PETSC_COMM_SELF, &preallocator);CHKERRQ(ierr);
1850       ierr = MatSetType(preallocator, MATPREALLOCATOR);CHKERRQ(ierr);
1851       ierr = MatSetSizes(preallocator, rsize, rsize, rsize, rsize);CHKERRQ(ierr);
1852       ierr = MatSetUp(preallocator);CHKERRQ(ierr);
1853 
1854       for (c = 0; c < ncell; ++c) {
1855         const PetscInt *idx = dofsArray + (offset + c)*patch->totalDofsPerCell;
1856         ierr = MatSetValues(preallocator, patch->totalDofsPerCell, idx, patch->totalDofsPerCell, idx, vals, INSERT_VALUES);CHKERRQ(ierr);
1857       }
1858 
1859       if (patch->usercomputeopintfacet) {
1860         const PetscInt *intFacetsArray = NULL;
1861         PetscInt i, numIntFacets, intFacetOffset;
1862         const PetscInt *facetCells = NULL;
1863 
1864         ierr = PetscSectionGetDof(patch->intFacetCounts, point, &numIntFacets);CHKERRQ(ierr);
1865         ierr = PetscSectionGetOffset(patch->intFacetCounts, point, &intFacetOffset);CHKERRQ(ierr);
1866         ierr = ISGetIndices(patch->intFacetsToPatchCell, &facetCells);CHKERRQ(ierr);
1867         ierr = ISGetIndices(patch->intFacets, &intFacetsArray);CHKERRQ(ierr);
1868         for (i = 0; i < numIntFacets; i++) {
1869           const PetscInt cell0 = facetCells[2*(intFacetOffset + i) + 0];
1870           const PetscInt cell1 = facetCells[2*(intFacetOffset + i) + 1];
1871           const PetscInt *cell0idx = &dofsArray[(offset + cell0)*patch->totalDofsPerCell];
1872           const PetscInt *cell1idx = &dofsArray[(offset + cell1)*patch->totalDofsPerCell];
1873           ierr = MatSetValues(preallocator, patch->totalDofsPerCell, cell0idx, patch->totalDofsPerCell, cell1idx, vals, INSERT_VALUES);CHKERRQ(ierr);
1874           ierr = MatSetValues(preallocator, patch->totalDofsPerCell, cell1idx, patch->totalDofsPerCell, cell0idx, vals, INSERT_VALUES);CHKERRQ(ierr);
1875         }
1876       }
1877 
1878       ierr = PetscFree(vals);CHKERRQ(ierr);
1879       ierr = MatAssemblyBegin(preallocator, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
1880       ierr = MatAssemblyEnd(preallocator, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
1881       ierr = MatPreallocatorPreallocate(preallocator, PETSC_TRUE, *mat);CHKERRQ(ierr);
1882       ierr = MatDestroy(&preallocator);CHKERRQ(ierr);
1883     }
1884     ierr = PetscLogEventEnd(PC_Patch_Prealloc, pc, 0, 0, 0);CHKERRQ(ierr);
1885     if(withArtificial) {
1886       ierr = ISRestoreIndices(patch->dofsWithArtificial, &dofsArray);CHKERRQ(ierr);
1887     } else {
1888       ierr = ISRestoreIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
1889     }
1890   }
1891   ierr = MatSetUp(*mat);CHKERRQ(ierr);
1892   PetscFunctionReturn(0);
1893 }
1894 
1895 static PetscErrorCode PCPatchComputeFunction_DMPlex_Private(PC pc, PetscInt patchNum, Vec x, Vec F, IS cellIS, PetscInt n, const PetscInt *l2p, const PetscInt *l2pWithAll, void *ctx)
1896 {
1897   PC_PATCH       *patch = (PC_PATCH *) pc->data;
1898   DM              dm;
1899   PetscSection    s;
1900   const PetscInt *parray, *oarray;
1901   PetscInt        Nf = patch->nsubspaces, Np, poff, p, f;
1902   PetscErrorCode  ierr;
1903 
1904   PetscFunctionBegin;
1905   if (patch->precomputeElementTensors) SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONGSTATE, "Precomputing element tensors not implemented with DMPlex compute operator");
1906   ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
1907   ierr = DMGetDefaultSection(dm, &s);CHKERRQ(ierr);
1908   /* Set offset into patch */
1909   ierr = PetscSectionGetDof(patch->pointCounts, patchNum, &Np);CHKERRQ(ierr);
1910   ierr = PetscSectionGetOffset(patch->pointCounts, patchNum, &poff);CHKERRQ(ierr);
1911   ierr = ISGetIndices(patch->points, &parray);CHKERRQ(ierr);
1912   ierr = ISGetIndices(patch->offs,   &oarray);CHKERRQ(ierr);
1913   for (f = 0; f < Nf; ++f) {
1914     for (p = 0; p < Np; ++p) {
1915       const PetscInt point = parray[poff+p];
1916       PetscInt       dof;
1917 
1918       ierr = PetscSectionGetFieldDof(patch->patchSection, point, f, &dof);CHKERRQ(ierr);
1919       ierr = PetscSectionSetFieldOffset(patch->patchSection, point, f, oarray[(poff+p)*Nf+f]);CHKERRQ(ierr);
1920       if (patch->nsubspaces == 1) {ierr = PetscSectionSetOffset(patch->patchSection, point, oarray[(poff+p)*Nf+f]);CHKERRQ(ierr);}
1921       else                        {ierr = PetscSectionSetOffset(patch->patchSection, point, -1);CHKERRQ(ierr);}
1922     }
1923   }
1924   ierr = ISRestoreIndices(patch->points, &parray);CHKERRQ(ierr);
1925   ierr = ISRestoreIndices(patch->offs,   &oarray);CHKERRQ(ierr);
1926   if (patch->viewSection) {ierr = ObjectView((PetscObject) patch->patchSection, patch->viewerSection, patch->formatSection);CHKERRQ(ierr);}
1927   ierr = DMPlexComputeResidual_Patch_Internal(pc->dm, patch->patchSection, cellIS, 0.0, x, NULL, F, ctx);CHKERRQ(ierr);
1928   PetscFunctionReturn(0);
1929 }
1930 
1931 PetscErrorCode PCPatchComputeFunction_Internal(PC pc, Vec x, Vec F, PetscInt point)
1932 {
1933   PC_PATCH       *patch = (PC_PATCH *) pc->data;
1934   const PetscInt *dofsArray;
1935   const PetscInt *dofsArrayWithAll;
1936   const PetscInt *cellsArray;
1937   PetscInt        ncell, offset, pStart, pEnd;
1938   PetscErrorCode  ierr;
1939 
1940   PetscFunctionBegin;
1941   ierr = PetscLogEventBegin(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
1942   if (!patch->usercomputeop) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call PCPatchSetComputeOperator() to set user callback\n");
1943   ierr = ISGetIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
1944   ierr = ISGetIndices(patch->dofsWithAll, &dofsArrayWithAll);CHKERRQ(ierr);
1945   ierr = ISGetIndices(patch->cells, &cellsArray);CHKERRQ(ierr);
1946   ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd);CHKERRQ(ierr);
1947 
1948   point += pStart;
1949   if (point >= pEnd) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Operator point %D not in [%D, %D)\n", point, pStart, pEnd);CHKERRQ(ierr);
1950 
1951   ierr = PetscSectionGetDof(patch->cellCounts, point, &ncell);CHKERRQ(ierr);
1952   ierr = PetscSectionGetOffset(patch->cellCounts, point, &offset);CHKERRQ(ierr);
1953   if (ncell <= 0) {
1954     ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
1955     PetscFunctionReturn(0);
1956   }
1957   PetscStackPush("PCPatch user callback");
1958   /* Cannot reuse the same IS because the geometry info is being cached in it */
1959   ierr = ISCreateGeneral(PETSC_COMM_SELF, ncell, cellsArray + offset, PETSC_USE_POINTER, &patch->cellIS);CHKERRQ(ierr);
1960   ierr = patch->usercomputef(pc, point, x, F, patch->cellIS, ncell*patch->totalDofsPerCell, dofsArray + offset*patch->totalDofsPerCell,
1961                                                                                             dofsArrayWithAll + offset*patch->totalDofsPerCell,
1962                                                                                             patch->usercomputefctx);CHKERRQ(ierr);
1963   PetscStackPop;
1964   ierr = ISDestroy(&patch->cellIS);CHKERRQ(ierr);
1965   ierr = ISRestoreIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
1966   ierr = ISRestoreIndices(patch->dofsWithAll, &dofsArrayWithAll);CHKERRQ(ierr);
1967   ierr = ISRestoreIndices(patch->cells, &cellsArray);CHKERRQ(ierr);
1968   if (patch->viewMatrix) {
1969     char name[PETSC_MAX_PATH_LEN];
1970 
1971     ierr = PetscSNPrintf(name, PETSC_MAX_PATH_LEN-1, "Patch vector for Point %D", point);CHKERRQ(ierr);
1972     ierr = PetscObjectSetName((PetscObject) F, name);CHKERRQ(ierr);
1973     ierr = ObjectView((PetscObject) F, patch->viewerMatrix, patch->formatMatrix);CHKERRQ(ierr);
1974   }
1975   ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
1976   PetscFunctionReturn(0);
1977 }
1978 
1979 static PetscErrorCode PCPatchComputeOperator_DMPlex_Private(PC pc, PetscInt patchNum, Vec x, Mat J, IS cellIS, PetscInt n, const PetscInt *l2p, const PetscInt *l2pWithAll, void *ctx)
1980 {
1981   PC_PATCH       *patch = (PC_PATCH *) pc->data;
1982   DM              dm;
1983   PetscSection    s;
1984   const PetscInt *parray, *oarray;
1985   PetscInt        Nf = patch->nsubspaces, Np, poff, p, f;
1986   PetscErrorCode  ierr;
1987 
1988   PetscFunctionBegin;
1989   ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
1990   ierr = DMGetDefaultSection(dm, &s);CHKERRQ(ierr);
1991   /* Set offset into patch */
1992   ierr = PetscSectionGetDof(patch->pointCounts, patchNum, &Np);CHKERRQ(ierr);
1993   ierr = PetscSectionGetOffset(patch->pointCounts, patchNum, &poff);CHKERRQ(ierr);
1994   ierr = ISGetIndices(patch->points, &parray);CHKERRQ(ierr);
1995   ierr = ISGetIndices(patch->offs,   &oarray);CHKERRQ(ierr);
1996   for (f = 0; f < Nf; ++f) {
1997     for (p = 0; p < Np; ++p) {
1998       const PetscInt point = parray[poff+p];
1999       PetscInt       dof;
2000 
2001       ierr = PetscSectionGetFieldDof(patch->patchSection, point, f, &dof);CHKERRQ(ierr);
2002       ierr = PetscSectionSetFieldOffset(patch->patchSection, point, f, oarray[(poff+p)*Nf+f]);CHKERRQ(ierr);
2003       if (patch->nsubspaces == 1) {ierr = PetscSectionSetOffset(patch->patchSection, point, oarray[(poff+p)*Nf+f]);CHKERRQ(ierr);}
2004       else                        {ierr = PetscSectionSetOffset(patch->patchSection, point, -1);CHKERRQ(ierr);}
2005     }
2006   }
2007   ierr = ISRestoreIndices(patch->points, &parray);CHKERRQ(ierr);
2008   ierr = ISRestoreIndices(patch->offs,   &oarray);CHKERRQ(ierr);
2009   if (patch->viewSection) {ierr = ObjectView((PetscObject) patch->patchSection, patch->viewerSection, patch->formatSection);CHKERRQ(ierr);}
2010   /* TODO Shut off MatViewFromOptions() in MatAssemblyEnd() here */
2011   ierr = DMPlexComputeJacobian_Patch_Internal(pc->dm, patch->patchSection, patch->patchSection, cellIS, 0.0, 0.0, x, NULL, J, J, ctx);CHKERRQ(ierr);
2012   PetscFunctionReturn(0);
2013 }
2014 
2015 PetscErrorCode PCPatchComputeOperator_Internal(PC pc, Vec x, Mat mat, PetscInt point, PetscBool withArtificial)
2016 {
2017   PC_PATCH       *patch = (PC_PATCH *) pc->data;
2018   const PetscInt *dofsArray;
2019   const PetscInt *dofsArrayWithAll = NULL;
2020   const PetscInt *cellsArray;
2021   PetscInt        ncell, offset, pStart, pEnd, numIntFacets, intFacetOffset;
2022   PetscBool       isNonlinear;
2023   PetscErrorCode  ierr;
2024 
2025   PetscFunctionBegin;
2026   ierr = PetscLogEventBegin(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
2027   isNonlinear = patch->isNonlinear;
2028   if (!patch->usercomputeop) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call PCPatchSetComputeOperator() to set user callback\n");
2029   if(withArtificial) {
2030     ierr = ISGetIndices(patch->dofsWithArtificial, &dofsArray);CHKERRQ(ierr);
2031   } else {
2032     ierr = ISGetIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
2033   }
2034   if (isNonlinear) {
2035     ierr = ISGetIndices(patch->dofsWithAll, &dofsArrayWithAll);CHKERRQ(ierr);
2036   }
2037   ierr = ISGetIndices(patch->cells, &cellsArray);CHKERRQ(ierr);
2038   ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd);CHKERRQ(ierr);
2039 
2040   point += pStart;
2041   if (point >= pEnd) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Operator point %D not in [%D, %D)\n", point, pStart, pEnd);CHKERRQ(ierr);
2042 
2043   ierr = PetscSectionGetDof(patch->cellCounts, point, &ncell);CHKERRQ(ierr);
2044   ierr = PetscSectionGetOffset(patch->cellCounts, point, &offset);CHKERRQ(ierr);
2045   if (ncell <= 0) {
2046     ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
2047     PetscFunctionReturn(0);
2048   }
2049   if (patch->precomputeElementTensors) {
2050     PetscInt           i;
2051     PetscInt           ndof = patch->totalDofsPerCell;
2052     const PetscScalar *elementTensors;
2053 
2054     ierr = VecGetArrayRead(patch->cellMats, &elementTensors);CHKERRQ(ierr);
2055     for (i = 0; i < ncell; i++) {
2056       const PetscInt     cell = cellsArray[i + offset];
2057       const PetscInt    *idx  = dofsArray + (offset + i)*ndof;
2058       const PetscScalar *v    = elementTensors + patch->precomputedTensorLocations[cell]*ndof*ndof;
2059       ierr = MatSetValues(mat, ndof, idx, ndof, idx, v, ADD_VALUES);CHKERRQ(ierr);
2060     }
2061     ierr = VecRestoreArrayRead(patch->cellMats, &elementTensors);CHKERRQ(ierr);
2062     ierr = MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2063     ierr = MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2064   } else {
2065     PetscStackPush("PCPatch user callback");
2066     /* Cannot reuse the same IS because the geometry info is being cached in it */
2067     ierr = ISCreateGeneral(PETSC_COMM_SELF, ncell, cellsArray + offset, PETSC_USE_POINTER, &patch->cellIS);CHKERRQ(ierr);
2068     ierr = patch->usercomputeop(pc, point, x, mat, patch->cellIS, ncell*patch->totalDofsPerCell, dofsArray + offset*patch->totalDofsPerCell, dofsArrayWithAll ? dofsArrayWithAll + offset*patch->totalDofsPerCell : NULL, patch->usercomputeopctx);CHKERRQ(ierr);
2069   }
2070   if (patch->usercomputeopintfacet) {
2071     ierr = PetscSectionGetDof(patch->intFacetCounts, point, &numIntFacets);CHKERRQ(ierr);
2072     ierr = PetscSectionGetOffset(patch->intFacetCounts, point, &intFacetOffset);CHKERRQ(ierr);
2073     if (numIntFacets > 0) {
2074       /* For each interior facet, grab the two cells (in local numbering, and concatenate dof numberings for those cells) */
2075       PetscInt *facetDofs = NULL, *facetDofsWithAll = NULL;
2076       const PetscInt *intFacetsArray = NULL;
2077       PetscInt idx = 0;
2078       PetscInt i, c, d;
2079       IS       facetIS = NULL;
2080       const PetscInt *facetCells = NULL;
2081       ierr = ISGetIndices(patch->intFacetsToPatchCell, &facetCells);CHKERRQ(ierr);
2082       ierr = ISGetIndices(patch->intFacets, &intFacetsArray);CHKERRQ(ierr);
2083       /* FIXME: Pull this malloc out. */
2084       ierr = PetscMalloc1(2 * patch->totalDofsPerCell * numIntFacets, &facetDofs);CHKERRQ(ierr);
2085       if (dofsArrayWithAll) {
2086         ierr = PetscMalloc1(2 * patch->totalDofsPerCell * numIntFacets, &facetDofsWithAll);CHKERRQ(ierr);
2087       }
2088       if (patch->precomputeElementTensors) {
2089         PetscInt           nFacetDof = 2*patch->totalDofsPerCell;
2090         const PetscScalar *elementTensors;
2091 
2092         ierr = VecGetArrayRead(patch->intFacetMats, &elementTensors);CHKERRQ(ierr);
2093 
2094         for (i = 0; i < numIntFacets; i++) {
2095           const PetscInt     facet = intFacetsArray[i + intFacetOffset];
2096           const PetscScalar *v     = elementTensors + patch->precomputedIntFacetTensorLocations[facet]*nFacetDof*nFacetDof;
2097           idx = 0;
2098           /*
2099            * 0--1
2100            * |\-|
2101            * |+\|
2102            * 2--3
2103            * [0, 2, 3, 0, 1, 3]
2104            */
2105           for (c = 0; c < 2; c++) {
2106             const PetscInt cell = facetCells[2*(intFacetOffset + i) + c];
2107             for (d = 0; d < patch->totalDofsPerCell; d++) {
2108               facetDofs[idx] = dofsArray[(offset + cell)*patch->totalDofsPerCell + d];
2109               idx++;
2110             }
2111           }
2112           ierr = MatSetValues(mat, nFacetDof, facetDofs, nFacetDof, facetDofs, v, ADD_VALUES);CHKERRQ(ierr);
2113         }
2114         ierr = VecRestoreArrayRead(patch->intFacetMats, &elementTensors);CHKERRQ(ierr);
2115       } else {
2116         /*
2117          * 0--1
2118          * |\-|
2119          * |+\|
2120          * 2--3
2121          * [0, 2, 3, 0, 1, 3]
2122          */
2123         for (i = 0; i < numIntFacets; i++) {
2124           for (c = 0; c < 2; c++) {
2125             const PetscInt cell = facetCells[2*(intFacetOffset + i) + c];
2126             for (d = 0; d < patch->totalDofsPerCell; d++) {
2127               facetDofs[idx] = dofsArray[(offset + cell)*patch->totalDofsPerCell + d];
2128               if (dofsArrayWithAll) {
2129                 facetDofsWithAll[idx] = dofsArrayWithAll[(offset + cell)*patch->totalDofsPerCell + d];
2130               }
2131               idx++;
2132             }
2133           }
2134         }
2135         ierr = ISCreateGeneral(PETSC_COMM_SELF, numIntFacets, intFacetsArray + intFacetOffset, PETSC_USE_POINTER, &facetIS);CHKERRQ(ierr);
2136         ierr = patch->usercomputeopintfacet(pc, point, x, mat, facetIS, 2*numIntFacets*patch->totalDofsPerCell, facetDofs, facetDofsWithAll, patch->usercomputeopintfacetctx);CHKERRQ(ierr);
2137         ierr = ISDestroy(&facetIS);CHKERRQ(ierr);
2138       }
2139       ierr = ISRestoreIndices(patch->intFacetsToPatchCell, &facetCells);CHKERRQ(ierr);
2140       ierr = ISRestoreIndices(patch->intFacets, &intFacetsArray);CHKERRQ(ierr);
2141       ierr = PetscFree(facetDofs);CHKERRQ(ierr);
2142       ierr = PetscFree(facetDofsWithAll);CHKERRQ(ierr);
2143     }
2144   }
2145 
2146   ierr = MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2147   ierr = MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2148 
2149   PetscStackPop;
2150   ierr = ISDestroy(&patch->cellIS);CHKERRQ(ierr);
2151   if(withArtificial) {
2152     ierr = ISRestoreIndices(patch->dofsWithArtificial, &dofsArray);CHKERRQ(ierr);
2153   } else {
2154     ierr = ISRestoreIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
2155   }
2156   if (isNonlinear) {
2157     ierr = ISRestoreIndices(patch->dofsWithAll, &dofsArrayWithAll);CHKERRQ(ierr);
2158   }
2159   ierr = ISRestoreIndices(patch->cells, &cellsArray);CHKERRQ(ierr);
2160   if (patch->viewMatrix) {
2161     char name[PETSC_MAX_PATH_LEN];
2162 
2163     ierr = PetscSNPrintf(name, PETSC_MAX_PATH_LEN-1, "Patch matrix for Point %D", point);CHKERRQ(ierr);
2164     ierr = PetscObjectSetName((PetscObject) mat, name);CHKERRQ(ierr);
2165     ierr = ObjectView((PetscObject) mat, patch->viewerMatrix, patch->formatMatrix);CHKERRQ(ierr);
2166   }
2167   ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
2168   PetscFunctionReturn(0);
2169 }
2170 
2171 static PetscErrorCode MatSetValues_PCPatch_Private(Mat mat, PetscInt m, const PetscInt idxm[],
2172                                                    PetscInt n, const PetscInt idxn[], const PetscScalar *v, InsertMode addv)
2173 {
2174   Vec data;
2175   PetscScalar *array;
2176   PetscInt bs, nz, i, j, cell;
2177   PetscErrorCode ierr;
2178 
2179   ierr = MatShellGetContext(mat, &data);CHKERRQ(ierr);
2180   ierr = VecGetBlockSize(data, &bs);CHKERRQ(ierr);
2181   ierr = VecGetSize(data, &nz);CHKERRQ(ierr);
2182   ierr = VecGetArray(data, &array);CHKERRQ(ierr);
2183   if (m != n) SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Only for square insertion");
2184   cell = (PetscInt)(idxm[0]/bs); // use the fact that this is called once per cell
2185   for (i = 0; i < m; i++) {
2186     //const PetscInt row = idxm[i];
2187     if (idxm[i] != idxn[i]) SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Row and column indices must match!");
2188     for (j = 0; j < n; j++) {
2189       const PetscScalar v_ = v[i*bs + j];
2190       /* Indexing is special to the data structure we have! */
2191       if (addv == INSERT_VALUES) {
2192         array[cell*bs*bs + i*bs + j] = v_;
2193       } else {
2194         array[cell*bs*bs + i*bs + j] += v_;
2195       }
2196     }
2197   }
2198   ierr = VecRestoreArray(data, &array);CHKERRQ(ierr);
2199   PetscFunctionReturn(0);
2200 }
2201 
2202 static PetscErrorCode PCPatchPrecomputePatchTensors_Private(PC pc)
2203 {
2204   PC_PATCH       *patch = (PC_PATCH *)pc->data;
2205   const PetscInt *cellsArray;
2206   PetscInt        ncell, offset;
2207   const PetscInt *dofMapArray;
2208   PetscInt        i, j;
2209   IS              dofMap;
2210   IS              cellIS;
2211   const PetscInt  ndof  = patch->totalDofsPerCell;
2212   PetscErrorCode  ierr;
2213   Mat             vecMat;
2214   PetscInt        cStart, cEnd;
2215   DM              dm, plex;
2216 
2217 
2218   ierr = PetscLogEventBegin(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
2219 
2220   if (!patch->allCells) {
2221     PetscHSetI      cells;
2222     PetscHashIter   hi;
2223     PetscInt pStart, pEnd;
2224     PetscInt *allCells = NULL;
2225     ierr = PetscHSetICreate(&cells);CHKERRQ(ierr);
2226     ierr = ISGetIndices(patch->cells, &cellsArray);CHKERRQ(ierr);
2227     ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd);CHKERRQ(ierr);
2228     for (i = pStart; i < pEnd; i++) {
2229       ierr = PetscSectionGetDof(patch->cellCounts, i, &ncell);CHKERRQ(ierr);
2230       ierr = PetscSectionGetOffset(patch->cellCounts, i, &offset);CHKERRQ(ierr);
2231       if (ncell <= 0) continue;
2232       for (j = 0; j < ncell; j++) {
2233         PetscHSetIAdd(cells, cellsArray[offset + j]);CHKERRQ(ierr);
2234       }
2235     }
2236     ierr = ISRestoreIndices(patch->cells, &cellsArray);CHKERRQ(ierr);
2237     ierr = PetscHSetIGetSize(cells, &ncell);CHKERRQ(ierr);
2238     ierr = PetscMalloc1(ncell, &allCells);CHKERRQ(ierr);
2239     ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
2240     ierr = DMConvert(dm, DMPLEX, &plex);CHKERRQ(ierr);
2241     ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);
2242     ierr = PetscMalloc1(cEnd-cStart, &patch->precomputedTensorLocations);CHKERRQ(ierr);
2243     i = 0;
2244     PetscHashIterBegin(cells, hi);
2245     while (!PetscHashIterAtEnd(cells, hi)) {
2246       PetscHashIterGetKey(cells, hi, allCells[i]);
2247       patch->precomputedTensorLocations[allCells[i]] = i;
2248       PetscHashIterNext(cells, hi);
2249       i++;
2250     }
2251     ierr = PetscHSetIDestroy(&cells);CHKERRQ(ierr);
2252     ierr = ISCreateGeneral(PETSC_COMM_SELF, ncell, allCells, PETSC_OWN_POINTER, &patch->allCells);CHKERRQ(ierr);
2253   }
2254   ierr = ISGetSize(patch->allCells, &ncell);CHKERRQ(ierr);
2255   if (!patch->cellMats) {
2256     ierr = VecCreateSeq(PETSC_COMM_SELF, ncell*ndof*ndof, &patch->cellMats);CHKERRQ(ierr);
2257     ierr = VecSetBlockSize(patch->cellMats, ndof);CHKERRQ(ierr);
2258   }
2259   ierr = VecSet(patch->cellMats, 0);CHKERRQ(ierr);
2260 
2261   ierr = MatCreateShell(PETSC_COMM_SELF, ncell*ndof, ncell*ndof, ncell*ndof, ncell*ndof,
2262                         (void*)patch->cellMats, &vecMat);
2263   ierr = MatShellSetOperation(vecMat, MATOP_SET_VALUES, (void(*)(void))&MatSetValues_PCPatch_Private);CHKERRQ(ierr);
2264   ierr = ISGetSize(patch->allCells, &ncell);CHKERRQ(ierr);
2265   ierr = ISCreateStride(PETSC_COMM_SELF, ndof*ncell, 0, 1, &dofMap);CHKERRQ(ierr);
2266   ierr = ISGetIndices(dofMap, &dofMapArray);CHKERRQ(ierr);
2267   ierr = ISGetIndices(patch->allCells, &cellsArray);CHKERRQ(ierr);
2268   ierr = ISCreateGeneral(PETSC_COMM_SELF, ncell, cellsArray, PETSC_USE_POINTER, &cellIS);CHKERRQ(ierr);
2269   PetscStackPush("PCPatch user callback");
2270   /* TODO: Fix for DMPlex compute op, this bypasses a lot of the machinery and just assembles every element tensor. */
2271   ierr = patch->usercomputeop(pc, -1, NULL, vecMat, cellIS, ndof*ncell, dofMapArray, NULL, patch->usercomputeopctx);CHKERRQ(ierr);
2272   PetscStackPop;
2273   ierr = ISDestroy(&cellIS);CHKERRQ(ierr);
2274   ierr = MatDestroy(&vecMat);CHKERRQ(ierr);
2275   ierr = ISRestoreIndices(patch->allCells, &cellsArray);CHKERRQ(ierr);
2276   ierr = ISRestoreIndices(dofMap, &dofMapArray);CHKERRQ(ierr);
2277   ierr = ISDestroy(&dofMap);CHKERRQ(ierr);
2278 
2279   if (patch->usercomputeopintfacet) {
2280     PetscInt nIntFacets;
2281     IS       intFacetsIS;
2282     const PetscInt *intFacetsArray = NULL;
2283     if (!patch->allIntFacets) {
2284       PetscHSetI      facets;
2285       PetscHashIter   hi;
2286       PetscInt pStart, pEnd, fStart, fEnd;
2287       PetscInt *allIntFacets = NULL;
2288       ierr = PetscHSetICreate(&facets);CHKERRQ(ierr);
2289       ierr = ISGetIndices(patch->intFacets, &intFacetsArray);CHKERRQ(ierr);
2290       ierr = PetscSectionGetChart(patch->intFacetCounts, &pStart, &pEnd);CHKERRQ(ierr);
2291       for (i = pStart; i < pEnd; i++) {
2292         ierr = PetscSectionGetDof(patch->intFacetCounts, i, &nIntFacets);CHKERRQ(ierr);
2293         ierr = PetscSectionGetOffset(patch->intFacetCounts, i, &offset);CHKERRQ(ierr);
2294         if (nIntFacets <= 0) continue;
2295         for (j = 0; j < nIntFacets; j++) {
2296           PetscHSetIAdd(facets, intFacetsArray[offset + j]);CHKERRQ(ierr);
2297         }
2298       }
2299       ierr = ISRestoreIndices(patch->intFacets, &intFacetsArray);CHKERRQ(ierr);
2300       ierr = PetscHSetIGetSize(facets, &nIntFacets);CHKERRQ(ierr);
2301       ierr = PetscMalloc1(nIntFacets, &allIntFacets);CHKERRQ(ierr);
2302       ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
2303       ierr = DMConvert(dm, DMPLEX, &plex);CHKERRQ(ierr);
2304       ierr = DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd);CHKERRQ(ierr);
2305       ierr = PetscMalloc1(fEnd-fStart, &patch->precomputedIntFacetTensorLocations);CHKERRQ(ierr);
2306       i = 0;
2307       PetscHashIterBegin(facets, hi);
2308       while (!PetscHashIterAtEnd(facets, hi)) {
2309         PetscHashIterGetKey(facets, hi, allIntFacets[i]);
2310         patch->precomputedIntFacetTensorLocations[allIntFacets[i]] = i;
2311         PetscHashIterNext(facets, hi);
2312         i++;
2313       }
2314       ierr = PetscHSetIDestroy(&facets);CHKERRQ(ierr);
2315       ierr = ISCreateGeneral(PETSC_COMM_SELF, nIntFacets, allIntFacets, PETSC_OWN_POINTER, &patch->allIntFacets);CHKERRQ(ierr);
2316     }
2317     ierr = ISGetSize(patch->allIntFacets, &nIntFacets);CHKERRQ(ierr);
2318     if (!patch->intFacetMats) {
2319       ierr = VecCreateSeq(PETSC_COMM_SELF, nIntFacets*ndof*ndof*4, &patch->intFacetMats);CHKERRQ(ierr);
2320       ierr = VecSetBlockSize(patch->intFacetMats, ndof*2);CHKERRQ(ierr);
2321     }
2322     ierr = VecSet(patch->intFacetMats, 0);CHKERRQ(ierr);
2323 
2324     ierr = MatCreateShell(PETSC_COMM_SELF, nIntFacets*ndof*2, nIntFacets*ndof*2, nIntFacets*ndof*2, nIntFacets*ndof*2,
2325                           (void*)patch->intFacetMats, &vecMat);
2326     ierr = MatShellSetOperation(vecMat, MATOP_SET_VALUES, (void(*)(void))&MatSetValues_PCPatch_Private);CHKERRQ(ierr);
2327     ierr = ISCreateStride(PETSC_COMM_SELF, 2*ndof*nIntFacets, 0, 1, &dofMap);CHKERRQ(ierr);
2328     ierr = ISGetIndices(dofMap, &dofMapArray);CHKERRQ(ierr);
2329     ierr = ISGetIndices(patch->allIntFacets, &intFacetsArray);CHKERRQ(ierr);
2330     ierr = ISCreateGeneral(PETSC_COMM_SELF, nIntFacets, intFacetsArray, PETSC_USE_POINTER, &intFacetsIS);CHKERRQ(ierr);
2331     PetscStackPush("PCPatch user callback (interior facets)");
2332     /* TODO: Fix for DMPlex compute op, this bypasses a lot of the machinery and just assembles every element tensor. */
2333     ierr = patch->usercomputeopintfacet(pc, -1, NULL, vecMat, intFacetsIS, 2*ndof*nIntFacets, dofMapArray, NULL, patch->usercomputeopintfacetctx);CHKERRQ(ierr);
2334     PetscStackPop;
2335     ierr = ISDestroy(&intFacetsIS);CHKERRQ(ierr);
2336     ierr = MatDestroy(&vecMat);CHKERRQ(ierr);
2337     ierr = ISRestoreIndices(patch->allIntFacets, &intFacetsArray);CHKERRQ(ierr);
2338     ierr = ISRestoreIndices(dofMap, &dofMapArray);CHKERRQ(ierr);
2339     ierr = ISDestroy(&dofMap);CHKERRQ(ierr);
2340   }
2341   ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
2342 
2343   PetscFunctionReturn(0);
2344 }
2345 
2346 PetscErrorCode PCPatch_ScatterLocal_Private(PC pc, PetscInt p, Vec x, Vec y, InsertMode mode, ScatterMode scat, PatchScatterType scattertype)
2347 {
2348   PC_PATCH          *patch     = (PC_PATCH *) pc->data;
2349   const PetscScalar *xArray    = NULL;
2350   PetscScalar       *yArray    = NULL;
2351   const PetscInt    *gtolArray = NULL;
2352   PetscInt           dof, offset, lidx;
2353   PetscErrorCode     ierr;
2354 
2355   PetscFunctionBeginHot;
2356   ierr = PetscLogEventBegin(PC_Patch_Scatter, pc, 0, 0, 0);CHKERRQ(ierr);
2357   ierr = VecGetArrayRead(x, &xArray);CHKERRQ(ierr);
2358   ierr = VecGetArray(y, &yArray);CHKERRQ(ierr);
2359   if (scattertype == SCATTER_WITHARTIFICIAL) {
2360     ierr = PetscSectionGetDof(patch->gtolCountsWithArtificial, p, &dof);CHKERRQ(ierr);
2361     ierr = PetscSectionGetOffset(patch->gtolCountsWithArtificial, p, &offset);CHKERRQ(ierr);
2362     ierr = ISGetIndices(patch->gtolWithArtificial, &gtolArray);CHKERRQ(ierr);
2363   } else if (scattertype == SCATTER_WITHALL) {
2364     ierr = PetscSectionGetDof(patch->gtolCountsWithAll, p, &dof);CHKERRQ(ierr);
2365     ierr = PetscSectionGetOffset(patch->gtolCountsWithAll, p, &offset);CHKERRQ(ierr);
2366     ierr = ISGetIndices(patch->gtolWithAll, &gtolArray);CHKERRQ(ierr);
2367   } else {
2368     ierr = PetscSectionGetDof(patch->gtolCounts, p, &dof);CHKERRQ(ierr);
2369     ierr = PetscSectionGetOffset(patch->gtolCounts, p, &offset);CHKERRQ(ierr);
2370     ierr = ISGetIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
2371   }
2372   if (mode == INSERT_VALUES && scat != SCATTER_FORWARD) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Can't insert if not scattering forward\n");
2373   if (mode == ADD_VALUES    && scat != SCATTER_REVERSE) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Can't add if not scattering reverse\n");
2374   for (lidx = 0; lidx < dof; ++lidx) {
2375     const PetscInt gidx = gtolArray[offset+lidx];
2376 
2377     if (mode == INSERT_VALUES) yArray[lidx]  = xArray[gidx]; /* Forward */
2378     else                       yArray[gidx] += xArray[lidx]; /* Reverse */
2379   }
2380   if (scattertype == SCATTER_WITHARTIFICIAL) {
2381     ierr = ISRestoreIndices(patch->gtolWithArtificial, &gtolArray);CHKERRQ(ierr);
2382   } else if (scattertype == SCATTER_WITHALL) {
2383     ierr = ISRestoreIndices(patch->gtolWithAll, &gtolArray);CHKERRQ(ierr);
2384   } else {
2385     ierr = ISRestoreIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
2386   }
2387   ierr = VecRestoreArrayRead(x, &xArray);CHKERRQ(ierr);
2388   ierr = VecRestoreArray(y, &yArray);CHKERRQ(ierr);
2389   ierr = PetscLogEventEnd(PC_Patch_Scatter, pc, 0, 0, 0);CHKERRQ(ierr);
2390   PetscFunctionReturn(0);
2391 }
2392 
2393 static PetscErrorCode PCSetUp_PATCH_Linear(PC pc)
2394 {
2395   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2396   const char    *prefix;
2397   PetscInt       i;
2398   PetscErrorCode ierr;
2399 
2400   PetscFunctionBegin;
2401   if (!pc->setupcalled) {
2402     ierr = PetscMalloc1(patch->npatch, &patch->solver);CHKERRQ(ierr);
2403     ierr = PCGetOptionsPrefix(pc, &prefix);CHKERRQ(ierr);
2404     for (i = 0; i < patch->npatch; ++i) {
2405       KSP ksp;
2406       PC  subpc;
2407 
2408       ierr = KSPCreate(PETSC_COMM_SELF, &ksp);CHKERRQ(ierr);
2409       ierr = KSPSetErrorIfNotConverged(ksp, pc->erroriffailure);CHKERRQ(ierr);
2410       ierr = KSPSetOptionsPrefix(ksp, prefix);CHKERRQ(ierr);
2411       ierr = KSPAppendOptionsPrefix(ksp, "sub_");CHKERRQ(ierr);
2412       ierr = PetscObjectIncrementTabLevel((PetscObject) ksp, (PetscObject) pc, 1);CHKERRQ(ierr);
2413       ierr = KSPGetPC(ksp, &subpc);CHKERRQ(ierr);
2414       ierr = PetscObjectIncrementTabLevel((PetscObject) subpc, (PetscObject) pc, 1);CHKERRQ(ierr);
2415       ierr = PetscLogObjectParent((PetscObject) pc, (PetscObject) ksp);CHKERRQ(ierr);
2416       patch->solver[i] = (PetscObject) ksp;
2417     }
2418   }
2419   if (patch->save_operators) {
2420     if (patch->precomputeElementTensors) {
2421       ierr = PCPatchPrecomputePatchTensors_Private(pc);CHKERRQ(ierr);
2422     }
2423     for (i = 0; i < patch->npatch; ++i) {
2424       ierr = MatZeroEntries(patch->mat[i]);CHKERRQ(ierr);
2425       ierr = PCPatchComputeOperator_Internal(pc, NULL, patch->mat[i], i, PETSC_FALSE);CHKERRQ(ierr);
2426       ierr = KSPSetOperators((KSP) patch->solver[i], patch->mat[i], patch->mat[i]);CHKERRQ(ierr);
2427     }
2428   }
2429   if(patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
2430     for (i = 0; i < patch->npatch; ++i) {
2431       /* Instead of padding patch->patchUpdate with zeros to get */
2432       /* patch->patchUpdateWithArtificial and then multiplying with the matrix, */
2433       /* just get rid of the columns that correspond to the dofs with */
2434       /* artificial bcs. That's of course fairly inefficient, hopefully we */
2435       /* can just assemble the rectangular matrix in the first place. */
2436       Mat matSquare;
2437       IS rowis;
2438       PetscInt dof;
2439 
2440       ierr = MatGetSize(patch->mat[i], &dof, NULL);CHKERRQ(ierr);
2441       if (dof == 0) {
2442         patch->matWithArtificial[i] = NULL;
2443         continue;
2444       }
2445 
2446       ierr = PCPatchCreateMatrix_Private(pc, i, &matSquare, PETSC_TRUE);CHKERRQ(ierr);
2447       ierr = MatZeroEntries(matSquare);CHKERRQ(ierr);
2448       ierr = PCPatchComputeOperator_Internal(pc, NULL, matSquare, i, PETSC_TRUE);CHKERRQ(ierr);
2449 
2450       ierr = MatGetSize(matSquare, &dof, NULL);CHKERRQ(ierr);
2451       ierr = ISCreateStride(PETSC_COMM_SELF, dof, 0, 1, &rowis); CHKERRQ(ierr);
2452       if(pc->setupcalled) {
2453         ierr = MatCreateSubMatrix(matSquare, rowis, patch->dofMappingWithoutToWithArtificial[i], MAT_REUSE_MATRIX, &patch->matWithArtificial[i]); CHKERRQ(ierr);
2454       } else {
2455         ierr = MatCreateSubMatrix(matSquare, rowis, patch->dofMappingWithoutToWithArtificial[i], MAT_INITIAL_MATRIX, &patch->matWithArtificial[i]); CHKERRQ(ierr);
2456       }
2457       ierr = ISDestroy(&rowis); CHKERRQ(ierr);
2458       ierr = MatDestroy(&matSquare);CHKERRQ(ierr);
2459     }
2460   }
2461   PetscFunctionReturn(0);
2462 }
2463 
2464 static PetscErrorCode PCSetUp_PATCH(PC pc)
2465 {
2466   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2467   PetscInt       i;
2468   PetscBool       isNonlinear;
2469   PetscErrorCode ierr;
2470 
2471   PetscFunctionBegin;
2472   if (!pc->setupcalled) {
2473     PetscInt pStart, pEnd, p;
2474     PetscInt localSize;
2475 
2476     ierr = PetscLogEventBegin(PC_Patch_CreatePatches, pc, 0, 0, 0);CHKERRQ(ierr);
2477 
2478     isNonlinear = patch->isNonlinear;
2479     if (!patch->nsubspaces) {
2480       DM           dm;
2481       PetscSection s;
2482       PetscInt     cStart, cEnd, c, Nf, f, numGlobalBcs = 0, *globalBcs, *Nb, totNb = 0, **cellDofs;
2483 
2484       ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
2485       if (!dm) SETERRQ(PetscObjectComm((PetscObject) pc), PETSC_ERR_ARG_WRONG, "Must set DM for PCPATCH or call PCPatchSetDiscretisationInfo()");
2486       ierr = DMGetDefaultSection(dm, &s);CHKERRQ(ierr);
2487       ierr = PetscSectionGetNumFields(s, &Nf);CHKERRQ(ierr);
2488       ierr = PetscSectionGetChart(s, &pStart, &pEnd);CHKERRQ(ierr);
2489       for (p = pStart; p < pEnd; ++p) {
2490         PetscInt cdof;
2491         ierr = PetscSectionGetConstraintDof(s, p, &cdof);CHKERRQ(ierr);
2492         numGlobalBcs += cdof;
2493       }
2494       ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);
2495       ierr = PetscMalloc3(Nf, &Nb, Nf, &cellDofs, numGlobalBcs, &globalBcs);CHKERRQ(ierr);
2496       for (f = 0; f < Nf; ++f) {
2497         PetscFE        fe;
2498         PetscDualSpace sp;
2499         PetscInt       cdoff = 0;
2500 
2501         ierr = DMGetField(dm, f, NULL, (PetscObject *) &fe);CHKERRQ(ierr);
2502         /* ierr = PetscFEGetNumComponents(fe, &Nc[f]);CHKERRQ(ierr); */
2503         ierr = PetscFEGetDualSpace(fe, &sp);CHKERRQ(ierr);
2504         ierr = PetscDualSpaceGetDimension(sp, &Nb[f]);CHKERRQ(ierr);
2505         totNb += Nb[f];
2506 
2507         ierr = PetscMalloc1((cEnd-cStart)*Nb[f], &cellDofs[f]);CHKERRQ(ierr);
2508         for (c = cStart; c < cEnd; ++c) {
2509           PetscInt *closure = NULL;
2510           PetscInt  clSize  = 0, cl;
2511 
2512           ierr = DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure);CHKERRQ(ierr);
2513           for (cl = 0; cl < clSize*2; cl += 2) {
2514             const PetscInt p = closure[cl];
2515             PetscInt       fdof, d, foff;
2516 
2517             ierr = PetscSectionGetFieldDof(s, p, f, &fdof);CHKERRQ(ierr);
2518             ierr = PetscSectionGetFieldOffset(s, p, f, &foff);CHKERRQ(ierr);
2519             for (d = 0; d < fdof; ++d, ++cdoff) cellDofs[f][cdoff] = foff + d;
2520           }
2521           ierr = DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure);CHKERRQ(ierr);
2522         }
2523         if (cdoff != (cEnd-cStart)*Nb[f]) SETERRQ4(PetscObjectComm((PetscObject) pc), PETSC_ERR_ARG_SIZ, "Total number of cellDofs %D for field %D should be Nc (%D) * cellDof (%D)", cdoff, f, cEnd-cStart, Nb[f]);
2524       }
2525       numGlobalBcs = 0;
2526       for (p = pStart; p < pEnd; ++p) {
2527         const PetscInt *ind;
2528         PetscInt        off, cdof, d;
2529 
2530         ierr = PetscSectionGetOffset(s, p, &off);CHKERRQ(ierr);
2531         ierr = PetscSectionGetConstraintDof(s, p, &cdof);CHKERRQ(ierr);
2532         ierr = PetscSectionGetConstraintIndices(s, p, &ind);CHKERRQ(ierr);
2533         for (d = 0; d < cdof; ++d) globalBcs[numGlobalBcs++] = off + ind[d];
2534       }
2535 
2536       ierr = PCPatchSetDiscretisationInfoCombined(pc, dm, Nb, (const PetscInt **) cellDofs, numGlobalBcs, globalBcs, numGlobalBcs, globalBcs);CHKERRQ(ierr);
2537       for (f = 0; f < Nf; ++f) {
2538         ierr = PetscFree(cellDofs[f]);CHKERRQ(ierr);
2539       }
2540       ierr = PetscFree3(Nb, cellDofs, globalBcs);CHKERRQ(ierr);
2541       ierr = PCPatchSetComputeFunction(pc, PCPatchComputeFunction_DMPlex_Private, NULL);CHKERRQ(ierr);
2542       ierr = PCPatchSetComputeOperator(pc, PCPatchComputeOperator_DMPlex_Private, NULL);CHKERRQ(ierr);
2543     }
2544 
2545     localSize = patch->subspaceOffsets[patch->nsubspaces];
2546     ierr = VecCreateSeq(PETSC_COMM_SELF, localSize, &patch->localRHS);CHKERRQ(ierr);
2547     ierr = VecSetUp(patch->localRHS);CHKERRQ(ierr);
2548     ierr = VecDuplicate(patch->localRHS, &patch->localUpdate);CHKERRQ(ierr);
2549     ierr = PCPatchCreateCellPatches(pc);CHKERRQ(ierr);
2550     ierr = PCPatchCreateCellPatchDiscretisationInfo(pc);CHKERRQ(ierr);
2551 
2552     /* OK, now build the work vectors */
2553     ierr = PetscSectionGetChart(patch->gtolCounts, &pStart, &pEnd);CHKERRQ(ierr);
2554     ierr = PetscMalloc1(patch->npatch, &patch->patchRHS);CHKERRQ(ierr);
2555     ierr = PetscMalloc1(patch->npatch, &patch->patchUpdate);CHKERRQ(ierr);
2556 
2557     if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
2558       ierr = PetscMalloc1(patch->npatch, &patch->patchRHSWithArtificial);CHKERRQ(ierr);
2559       ierr = PetscMalloc1(patch->npatch, &patch->dofMappingWithoutToWithArtificial);CHKERRQ(ierr);
2560     }
2561     if (isNonlinear) {
2562       ierr = PetscMalloc1(patch->npatch, &patch->dofMappingWithoutToWithAll);CHKERRQ(ierr);
2563     }
2564     for (p = pStart; p < pEnd; ++p) {
2565       PetscInt dof;
2566 
2567       ierr = PetscSectionGetDof(patch->gtolCounts, p, &dof);CHKERRQ(ierr);
2568       ierr = VecCreateSeq(PETSC_COMM_SELF, dof, &patch->patchRHS[p-pStart]);CHKERRQ(ierr);
2569       ierr = VecSetUp(patch->patchRHS[p-pStart]);CHKERRQ(ierr);
2570       ierr = VecCreateSeq(PETSC_COMM_SELF, dof, &patch->patchUpdate[p-pStart]);CHKERRQ(ierr);
2571       ierr = VecSetUp(patch->patchUpdate[p-pStart]);CHKERRQ(ierr);
2572       if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
2573         const PetscInt    *gtolArray, *gtolArrayWithArtificial = NULL;
2574         PetscInt           numPatchDofs, offset;
2575         PetscInt           numPatchDofsWithArtificial, offsetWithArtificial;
2576         PetscInt           dofWithoutArtificialCounter = 0;
2577         PetscInt          *patchWithoutArtificialToWithArtificialArray;
2578 
2579         ierr = PetscSectionGetDof(patch->gtolCountsWithArtificial, p, &dof);CHKERRQ(ierr);
2580         ierr = VecCreateSeq(PETSC_COMM_SELF, dof, &patch->patchRHSWithArtificial[p-pStart]);CHKERRQ(ierr);
2581         ierr = VecSetUp(patch->patchRHSWithArtificial[p-pStart]);CHKERRQ(ierr);
2582 
2583         /* Now build the mapping that for a dof in a patch WITHOUT dofs that have artificial bcs gives the */
2584         /* the index in the patch with all dofs */
2585         ierr = ISGetIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
2586 
2587         ierr = PetscSectionGetDof(patch->gtolCounts, p, &numPatchDofs);CHKERRQ(ierr);
2588         if (numPatchDofs == 0) {
2589           patch->dofMappingWithoutToWithArtificial[p-pStart] = NULL;
2590           continue;
2591         }
2592 
2593         ierr = PetscSectionGetOffset(patch->gtolCounts, p, &offset);CHKERRQ(ierr);
2594         ierr = ISGetIndices(patch->gtolWithArtificial, &gtolArrayWithArtificial);CHKERRQ(ierr);
2595         ierr = PetscSectionGetDof(patch->gtolCountsWithArtificial, p, &numPatchDofsWithArtificial);CHKERRQ(ierr);
2596         ierr = PetscSectionGetOffset(patch->gtolCountsWithArtificial, p, &offsetWithArtificial);CHKERRQ(ierr);
2597 
2598         ierr = PetscMalloc1(numPatchDofs, &patchWithoutArtificialToWithArtificialArray);CHKERRQ(ierr);
2599         for (i=0; i<numPatchDofsWithArtificial; i++) {
2600           if (gtolArrayWithArtificial[i+offsetWithArtificial] == gtolArray[offset+dofWithoutArtificialCounter]) {
2601             patchWithoutArtificialToWithArtificialArray[dofWithoutArtificialCounter] = i;
2602             dofWithoutArtificialCounter++;
2603             if (dofWithoutArtificialCounter == numPatchDofs)
2604               break;
2605           }
2606         }
2607         ierr = ISCreateGeneral(PETSC_COMM_SELF, numPatchDofs, patchWithoutArtificialToWithArtificialArray, PETSC_OWN_POINTER, &patch->dofMappingWithoutToWithArtificial[p-pStart]);CHKERRQ(ierr);
2608         ierr = ISRestoreIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
2609         ierr = ISRestoreIndices(patch->gtolWithArtificial, &gtolArrayWithArtificial);CHKERRQ(ierr);
2610       }
2611       if (isNonlinear) {
2612         const PetscInt    *gtolArray, *gtolArrayWithAll = NULL;
2613         PetscInt           numPatchDofs, offset;
2614         PetscInt           numPatchDofsWithAll, offsetWithAll;
2615         PetscInt           dofWithoutAllCounter = 0;
2616         PetscInt          *patchWithoutAllToWithAllArray;
2617 
2618         /* Now build the mapping that for a dof in a patch WITHOUT dofs that have artificial bcs gives the */
2619         /* the index in the patch with all dofs */
2620         ierr = ISGetIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
2621 
2622         ierr = PetscSectionGetDof(patch->gtolCounts, p, &numPatchDofs);CHKERRQ(ierr);
2623         if (numPatchDofs == 0) {
2624           patch->dofMappingWithoutToWithAll[p-pStart] = NULL;
2625           continue;
2626         }
2627 
2628         ierr = PetscSectionGetOffset(patch->gtolCounts, p, &offset);CHKERRQ(ierr);
2629         ierr = ISGetIndices(patch->gtolWithAll, &gtolArrayWithAll);CHKERRQ(ierr);
2630         ierr = PetscSectionGetDof(patch->gtolCountsWithAll, p, &numPatchDofsWithAll);CHKERRQ(ierr);
2631         ierr = PetscSectionGetOffset(patch->gtolCountsWithAll, p, &offsetWithAll);CHKERRQ(ierr);
2632 
2633         ierr = PetscMalloc1(numPatchDofs, &patchWithoutAllToWithAllArray);CHKERRQ(ierr);
2634 
2635         for (i=0; i<numPatchDofsWithAll; i++) {
2636           if (gtolArrayWithAll[i+offsetWithAll] == gtolArray[offset+dofWithoutAllCounter]) {
2637             patchWithoutAllToWithAllArray[dofWithoutAllCounter] = i;
2638             dofWithoutAllCounter++;
2639             if (dofWithoutAllCounter == numPatchDofs)
2640               break;
2641           }
2642         }
2643         ierr = ISCreateGeneral(PETSC_COMM_SELF, numPatchDofs, patchWithoutAllToWithAllArray, PETSC_OWN_POINTER, &patch->dofMappingWithoutToWithAll[p-pStart]);CHKERRQ(ierr);
2644         ierr = ISRestoreIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
2645         ierr = ISRestoreIndices(patch->gtolWithAll, &gtolArrayWithAll);CHKERRQ(ierr);
2646       }
2647     }
2648     if (patch->save_operators) {
2649       ierr = PetscMalloc1(patch->npatch, &patch->mat);CHKERRQ(ierr);
2650       for (i = 0; i < patch->npatch; ++i) {
2651         ierr = PCPatchCreateMatrix_Private(pc, i, &patch->mat[i], PETSC_FALSE);CHKERRQ(ierr);
2652       }
2653     }
2654     ierr = PetscLogEventEnd(PC_Patch_CreatePatches, pc, 0, 0, 0);CHKERRQ(ierr);
2655 
2656     /* If desired, calculate weights for dof multiplicity */
2657     if (patch->partition_of_unity) {
2658       PetscScalar *input = NULL;
2659       PetscScalar *output = NULL;
2660       Vec global;
2661 
2662       ierr = VecDuplicate(patch->localRHS, &patch->dof_weights);CHKERRQ(ierr);
2663       if(patch->local_composition_type == PC_COMPOSITE_ADDITIVE) {
2664         for (i = 0; i < patch->npatch; ++i) {
2665           PetscInt dof;
2666 
2667           ierr = PetscSectionGetDof(patch->gtolCounts, i+pStart, &dof);CHKERRQ(ierr);
2668           if (dof <= 0) continue;
2669           ierr = VecSet(patch->patchRHS[i], 1.0);CHKERRQ(ierr);
2670           ierr = PCPatch_ScatterLocal_Private(pc, i+pStart, patch->patchRHS[i], patch->dof_weights, ADD_VALUES, SCATTER_REVERSE, SCATTER_INTERIOR);CHKERRQ(ierr);
2671         }
2672       } else {
2673         /* multiplicative is actually only locally multiplicative and globally additive. need the pou where the mesh decomposition overlaps */
2674         ierr = VecSet(patch->dof_weights, 1.0);CHKERRQ(ierr);
2675       }
2676 
2677       VecDuplicate(patch->dof_weights, &global);
2678       VecSet(global, 0.);
2679 
2680       ierr = VecGetArray(patch->dof_weights, &input);CHKERRQ(ierr);
2681       ierr = VecGetArray(global, &output);CHKERRQ(ierr);
2682       ierr = PetscSFReduceBegin(patch->defaultSF, MPIU_SCALAR, input, output, MPI_SUM);CHKERRQ(ierr);
2683       ierr = PetscSFReduceEnd(patch->defaultSF, MPIU_SCALAR, input, output, MPI_SUM);CHKERRQ(ierr);
2684       ierr = VecRestoreArray(patch->dof_weights, &input);CHKERRQ(ierr);
2685       ierr = VecRestoreArray(global, &output);CHKERRQ(ierr);
2686 
2687       ierr = VecReciprocal(global);CHKERRQ(ierr);
2688 
2689       ierr = VecGetArray(patch->dof_weights, &output);CHKERRQ(ierr);
2690       ierr = VecGetArray(global, &input);CHKERRQ(ierr);
2691       ierr = PetscSFBcastBegin(patch->defaultSF, MPIU_SCALAR, input, output);CHKERRQ(ierr);
2692       ierr = PetscSFBcastEnd(patch->defaultSF, MPIU_SCALAR, input, output);CHKERRQ(ierr);
2693       ierr = VecRestoreArray(patch->dof_weights, &output);CHKERRQ(ierr);
2694       ierr = VecRestoreArray(global, &input);CHKERRQ(ierr);
2695       ierr = VecDestroy(&global);CHKERRQ(ierr);
2696     }
2697     if(patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE && patch->save_operators) {
2698       ierr = PetscMalloc1(patch->npatch, &patch->matWithArtificial);CHKERRQ(ierr);
2699     }
2700   }
2701   ierr = (*patch->setupsolver)(pc);CHKERRQ(ierr);
2702   PetscFunctionReturn(0);
2703 }
2704 
2705 static PetscErrorCode PCApply_PATCH_Linear(PC pc, PetscInt i, Vec x, Vec y)
2706 {
2707   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2708   KSP            ksp   = (KSP) patch->solver[i];
2709   PetscErrorCode ierr;
2710 
2711   PetscFunctionBegin;
2712   if (!patch->save_operators) {
2713     Mat mat;
2714 
2715     ierr = PCPatchCreateMatrix_Private(pc, i, &mat, PETSC_FALSE);CHKERRQ(ierr);
2716     /* Populate operator here. */
2717     ierr = PCPatchComputeOperator_Internal(pc, NULL, mat, i, PETSC_FALSE);CHKERRQ(ierr);
2718     ierr = KSPSetOperators(ksp, mat, mat);CHKERRQ(ierr);
2719     /* Drop reference so the KSPSetOperators below will blow it away. */
2720     ierr = MatDestroy(&mat);CHKERRQ(ierr);
2721   }
2722   ierr = PetscLogEventBegin(PC_Patch_Solve, pc, 0, 0, 0);CHKERRQ(ierr);
2723   if (!ksp->setfromoptionscalled) {
2724     ierr = KSPSetFromOptions(ksp);CHKERRQ(ierr);
2725   }
2726   ierr = KSPSolve(ksp, x, y);CHKERRQ(ierr);
2727   ierr = KSPCheckSolve(ksp, pc, y);CHKERRQ(ierr);
2728   ierr = PetscLogEventEnd(PC_Patch_Solve, pc, 0, 0, 0);CHKERRQ(ierr);
2729   if (!patch->save_operators) {
2730     PC pc;
2731     ierr = KSPSetOperators(ksp, NULL, NULL);CHKERRQ(ierr);
2732     ierr = KSPGetPC(ksp, &pc);CHKERRQ(ierr);
2733     /* Destroy PC context too, otherwise the factored matrix hangs around. */
2734     ierr = PCReset(pc);CHKERRQ(ierr);
2735   }
2736   PetscFunctionReturn(0);
2737 }
2738 
2739 static PetscErrorCode PCUpdateMultiplicative_PATCH_Linear(PC pc, PetscInt i, PetscInt pStart)
2740 {
2741   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2742   Mat multMat;
2743   PetscErrorCode ierr;
2744 
2745   PetscFunctionBegin;
2746 
2747   if (patch->save_operators) {
2748     multMat = patch->matWithArtificial[i];
2749   } else {
2750     /*Very inefficient, hopefully we can just assemble the rectangular matrix in the first place.*/
2751     Mat matSquare;
2752     PetscInt dof;
2753     IS rowis;
2754     ierr = PCPatchCreateMatrix_Private(pc, i, &matSquare, PETSC_TRUE);CHKERRQ(ierr);
2755     ierr = MatZeroEntries(matSquare);CHKERRQ(ierr);
2756     ierr = PCPatchComputeOperator_Internal(pc, NULL, matSquare, i, PETSC_TRUE);CHKERRQ(ierr);
2757     ierr = MatGetSize(matSquare, &dof, NULL);CHKERRQ(ierr);
2758     ierr = ISCreateStride(PETSC_COMM_SELF, dof, 0, 1, &rowis); CHKERRQ(ierr);
2759     ierr = MatCreateSubMatrix(matSquare, rowis, patch->dofMappingWithoutToWithArtificial[i], MAT_INITIAL_MATRIX, &multMat); CHKERRQ(ierr);
2760     ierr = MatDestroy(&matSquare);CHKERRQ(ierr);
2761     ierr = ISDestroy(&rowis); CHKERRQ(ierr);
2762   }
2763   ierr = MatMult(multMat, patch->patchUpdate[i], patch->patchRHSWithArtificial[i]); CHKERRQ(ierr);
2764   ierr = VecScale(patch->patchRHSWithArtificial[i], -1.0); CHKERRQ(ierr);
2765   ierr = PCPatch_ScatterLocal_Private(pc, i + pStart, patch->patchRHSWithArtificial[i], patch->localRHS, ADD_VALUES, SCATTER_REVERSE, SCATTER_WITHARTIFICIAL); CHKERRQ(ierr);
2766   if (!patch->save_operators) {
2767     ierr = MatDestroy(&multMat); CHKERRQ(ierr);
2768   }
2769   PetscFunctionReturn(0);
2770 }
2771 
2772 static PetscErrorCode PCApply_PATCH(PC pc, Vec x, Vec y)
2773 {
2774   PC_PATCH          *patch    = (PC_PATCH *) pc->data;
2775   const PetscScalar *globalRHS  = NULL;
2776   PetscScalar       *localRHS   = NULL;
2777   PetscScalar       *globalUpdate  = NULL;
2778   const PetscInt    *bcNodes  = NULL;
2779   PetscInt           nsweep   = patch->symmetrise_sweep ? 2 : 1;
2780   PetscInt           start[2] = {0, 0};
2781   PetscInt           end[2]   = {-1, -1};
2782   const PetscInt     inc[2]   = {1, -1};
2783   const PetscScalar *localUpdate;
2784   const PetscInt    *iterationSet;
2785   PetscInt           pStart, numBcs, n, sweep, bc, j;
2786   PetscErrorCode     ierr;
2787 
2788   PetscFunctionBegin;
2789   ierr = PetscLogEventBegin(PC_Patch_Apply, pc, 0, 0, 0);CHKERRQ(ierr);
2790   ierr = PetscOptionsPushGetViewerOff(PETSC_TRUE);CHKERRQ(ierr);
2791   /* start, end, inc have 2 entries to manage a second backward sweep if we symmetrize */
2792   end[0]   = patch->npatch;
2793   start[1] = patch->npatch-1;
2794   if (patch->user_patches) {
2795     ierr = ISGetLocalSize(patch->iterationSet, &end[0]);CHKERRQ(ierr);
2796     start[1] = end[0] - 1;
2797     ierr = ISGetIndices(patch->iterationSet, &iterationSet);CHKERRQ(ierr);
2798   }
2799   /* Scatter from global space into overlapped local spaces */
2800   ierr = VecGetArrayRead(x, &globalRHS);CHKERRQ(ierr);
2801   ierr = VecGetArray(patch->localRHS, &localRHS);CHKERRQ(ierr);
2802   ierr = PetscSFBcastBegin(patch->defaultSF, MPIU_SCALAR, globalRHS, localRHS);CHKERRQ(ierr);
2803   ierr = PetscSFBcastEnd(patch->defaultSF, MPIU_SCALAR, globalRHS, localRHS);CHKERRQ(ierr);
2804   ierr = VecRestoreArrayRead(x, &globalRHS);CHKERRQ(ierr);
2805   ierr = VecRestoreArray(patch->localRHS, &localRHS);CHKERRQ(ierr);
2806 
2807   ierr = VecSet(patch->localUpdate, 0.0);CHKERRQ(ierr);
2808   ierr = PetscSectionGetChart(patch->gtolCounts, &pStart, NULL);CHKERRQ(ierr);
2809   for (sweep = 0; sweep < nsweep; sweep++) {
2810     for (j = start[sweep]; j*inc[sweep] < end[sweep]*inc[sweep]; j += inc[sweep]) {
2811       PetscInt i       = patch->user_patches ? iterationSet[j] : j;
2812       PetscInt start, len;
2813 
2814       ierr = PetscSectionGetDof(patch->gtolCounts, i+pStart, &len);CHKERRQ(ierr);
2815       ierr = PetscSectionGetOffset(patch->gtolCounts, i+pStart, &start);CHKERRQ(ierr);
2816       /* TODO: Squash out these guys in the setup as well. */
2817       if (len <= 0) continue;
2818       /* TODO: Do we need different scatters for X and Y? */
2819       ierr = PCPatch_ScatterLocal_Private(pc, i+pStart, patch->localRHS, patch->patchRHS[i], INSERT_VALUES, SCATTER_FORWARD, SCATTER_INTERIOR);CHKERRQ(ierr);
2820       ierr = (*patch->applysolver)(pc, i, patch->patchRHS[i], patch->patchUpdate[i]);CHKERRQ(ierr);
2821       ierr = PCPatch_ScatterLocal_Private(pc, i+pStart, patch->patchUpdate[i], patch->localUpdate, ADD_VALUES, SCATTER_REVERSE, SCATTER_INTERIOR);CHKERRQ(ierr);
2822       if(patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
2823         ierr = (*patch->updatemultiplicative)(pc, i, pStart);CHKERRQ(ierr);
2824       }
2825     }
2826   }
2827   if (patch->user_patches) {ierr = ISRestoreIndices(patch->iterationSet, &iterationSet);CHKERRQ(ierr);}
2828   /* XXX: should we do this on the global vector? */
2829   if (patch->partition_of_unity) {
2830     ierr = VecPointwiseMult(patch->localUpdate, patch->localUpdate, patch->dof_weights);CHKERRQ(ierr);
2831   }
2832   /* Now patch->localUpdate contains the solution of the patch solves, so we need to combine them all. */
2833   ierr = VecSet(y, 0.0);CHKERRQ(ierr);
2834   ierr = VecGetArray(y, &globalUpdate);CHKERRQ(ierr);
2835   ierr = VecGetArrayRead(patch->localUpdate, &localUpdate);CHKERRQ(ierr);
2836   ierr = PetscSFReduceBegin(patch->defaultSF, MPIU_SCALAR, localUpdate, globalUpdate, MPI_SUM);CHKERRQ(ierr);
2837   ierr = PetscSFReduceEnd(patch->defaultSF, MPIU_SCALAR, localUpdate, globalUpdate, MPI_SUM);CHKERRQ(ierr);
2838   ierr = VecRestoreArrayRead(patch->localUpdate, &localUpdate);CHKERRQ(ierr);
2839 
2840   /* Now we need to send the global BC values through */
2841   ierr = VecGetArrayRead(x, &globalRHS);CHKERRQ(ierr);
2842   ierr = ISGetSize(patch->globalBcNodes, &numBcs);CHKERRQ(ierr);
2843   ierr = ISGetIndices(patch->globalBcNodes, &bcNodes);CHKERRQ(ierr);
2844   ierr = VecGetLocalSize(x, &n);CHKERRQ(ierr);
2845   for (bc = 0; bc < numBcs; ++bc) {
2846     const PetscInt idx = bcNodes[bc];
2847     if (idx < n) globalUpdate[idx] = globalRHS[idx];
2848   }
2849 
2850   ierr = ISRestoreIndices(patch->globalBcNodes, &bcNodes);CHKERRQ(ierr);
2851   ierr = VecRestoreArrayRead(x, &globalRHS);CHKERRQ(ierr);
2852   ierr = VecRestoreArray(y, &globalUpdate);CHKERRQ(ierr);
2853 
2854   ierr = PetscOptionsPopGetViewerOff();CHKERRQ(ierr);
2855   ierr = PetscLogEventEnd(PC_Patch_Apply, pc, 0, 0, 0);CHKERRQ(ierr);
2856   PetscFunctionReturn(0);
2857 }
2858 
2859 static PetscErrorCode PCReset_PATCH_Linear(PC pc)
2860 {
2861   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2862   PetscInt       i;
2863   PetscErrorCode ierr;
2864 
2865   PetscFunctionBegin;
2866   if (patch->solver) {
2867     for (i = 0; i < patch->npatch; ++i) {ierr = KSPReset((KSP) patch->solver[i]);CHKERRQ(ierr);}
2868   }
2869   PetscFunctionReturn(0);
2870 }
2871 
2872 static PetscErrorCode PCReset_PATCH(PC pc)
2873 {
2874   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2875   PetscInt       i;
2876   PetscErrorCode ierr;
2877 
2878   PetscFunctionBegin;
2879 
2880   ierr = PetscSFDestroy(&patch->defaultSF);CHKERRQ(ierr);
2881   ierr = PetscSectionDestroy(&patch->cellCounts);CHKERRQ(ierr);
2882   ierr = PetscSectionDestroy(&patch->pointCounts);CHKERRQ(ierr);
2883   ierr = PetscSectionDestroy(&patch->cellNumbering);CHKERRQ(ierr);
2884   ierr = PetscSectionDestroy(&patch->gtolCounts);CHKERRQ(ierr);
2885   ierr = ISDestroy(&patch->gtol);CHKERRQ(ierr);
2886   ierr = ISDestroy(&patch->cells);CHKERRQ(ierr);
2887   ierr = ISDestroy(&patch->points);CHKERRQ(ierr);
2888   ierr = ISDestroy(&patch->dofs);CHKERRQ(ierr);
2889   ierr = ISDestroy(&patch->offs);CHKERRQ(ierr);
2890   ierr = PetscSectionDestroy(&patch->patchSection);CHKERRQ(ierr);
2891   ierr = ISDestroy(&patch->ghostBcNodes);CHKERRQ(ierr);
2892   ierr = ISDestroy(&patch->globalBcNodes);CHKERRQ(ierr);
2893   ierr = PetscSectionDestroy(&patch->gtolCountsWithArtificial);CHKERRQ(ierr);
2894   ierr = ISDestroy(&patch->gtolWithArtificial);CHKERRQ(ierr);
2895   ierr = ISDestroy(&patch->dofsWithArtificial);CHKERRQ(ierr);
2896   ierr = ISDestroy(&patch->offsWithArtificial);CHKERRQ(ierr);
2897   ierr = PetscSectionDestroy(&patch->gtolCountsWithAll);CHKERRQ(ierr);
2898   ierr = ISDestroy(&patch->gtolWithAll);CHKERRQ(ierr);
2899   ierr = ISDestroy(&patch->dofsWithAll);CHKERRQ(ierr);
2900   ierr = ISDestroy(&patch->offsWithAll);CHKERRQ(ierr);
2901   ierr = VecDestroy(&patch->cellMats);CHKERRQ(ierr);
2902   ierr = VecDestroy(&patch->intFacetMats);CHKERRQ(ierr);
2903   ierr = ISDestroy(&patch->allCells);CHKERRQ(ierr);
2904 
2905   if (patch->dofSection) for (i = 0; i < patch->nsubspaces; i++) {ierr = PetscSectionDestroy(&patch->dofSection[i]);CHKERRQ(ierr);}
2906   ierr = PetscFree(patch->dofSection);CHKERRQ(ierr);
2907   ierr = PetscFree(patch->bs);CHKERRQ(ierr);
2908   ierr = PetscFree(patch->nodesPerCell);CHKERRQ(ierr);
2909   if (patch->cellNodeMap) for (i = 0; i < patch->nsubspaces; i++) {ierr = PetscFree(patch->cellNodeMap[i]);CHKERRQ(ierr);}
2910   ierr = PetscFree(patch->cellNodeMap);CHKERRQ(ierr);
2911   ierr = PetscFree(patch->subspaceOffsets);CHKERRQ(ierr);
2912 
2913   ierr = (*patch->resetsolver)(pc);CHKERRQ(ierr);
2914 
2915   if (patch->subspaces_to_exclude) {
2916     PetscHSetIDestroy(&patch->subspaces_to_exclude);
2917   }
2918 
2919   ierr = VecDestroy(&patch->localRHS);CHKERRQ(ierr);
2920   ierr = VecDestroy(&patch->localUpdate);CHKERRQ(ierr);
2921   if (patch->patchRHS) {
2922     for (i = 0; i < patch->npatch; ++i) {ierr = VecDestroy(&patch->patchRHS[i]);CHKERRQ(ierr);}
2923     ierr = PetscFree(patch->patchRHS);CHKERRQ(ierr);
2924   }
2925   if (patch->patchUpdate) {
2926     for (i = 0; i < patch->npatch; ++i) {ierr = VecDestroy(&patch->patchUpdate[i]);CHKERRQ(ierr);}
2927     ierr = PetscFree(patch->patchUpdate);CHKERRQ(ierr);
2928   }
2929   ierr = VecDestroy(&patch->dof_weights);CHKERRQ(ierr);
2930   if (patch->patch_dof_weights) {
2931     for (i = 0; i < patch->npatch; ++i) {ierr = VecDestroy(&patch->patch_dof_weights[i]);CHKERRQ(ierr);}
2932     ierr = PetscFree(patch->patch_dof_weights);CHKERRQ(ierr);
2933   }
2934   if (patch->mat) {
2935     for (i = 0; i < patch->npatch; ++i) {ierr = MatDestroy(&patch->mat[i]);CHKERRQ(ierr);}
2936     ierr = PetscFree(patch->mat);CHKERRQ(ierr);
2937   }
2938   if (patch->matWithArtificial) {
2939     for (i = 0; i < patch->npatch; ++i) {ierr = MatDestroy(&patch->matWithArtificial[i]);CHKERRQ(ierr);}
2940     ierr = PetscFree(patch->matWithArtificial);CHKERRQ(ierr);
2941   }
2942   if (patch->patchRHSWithArtificial) {
2943     for (i = 0; i < patch->npatch; ++i) {ierr = VecDestroy(&patch->patchRHSWithArtificial[i]);CHKERRQ(ierr);}
2944     ierr = PetscFree(patch->patchRHSWithArtificial);CHKERRQ(ierr);
2945   }
2946   if(patch->dofMappingWithoutToWithArtificial) {
2947     for (i = 0; i < patch->npatch; ++i) {ierr = ISDestroy(&patch->dofMappingWithoutToWithArtificial[i]);CHKERRQ(ierr);}
2948     ierr = PetscFree(patch->dofMappingWithoutToWithArtificial);CHKERRQ(ierr);
2949 
2950   }
2951   if(patch->dofMappingWithoutToWithAll) {
2952     for (i = 0; i < patch->npatch; ++i) {ierr = ISDestroy(&patch->dofMappingWithoutToWithAll[i]);CHKERRQ(ierr);}
2953     ierr = PetscFree(patch->dofMappingWithoutToWithAll);CHKERRQ(ierr);
2954 
2955   }
2956   ierr = PetscFree(patch->sub_mat_type);CHKERRQ(ierr);
2957   if (patch->userIS) {
2958     for (i = 0; i < patch->npatch; ++i) {ierr = ISDestroy(&patch->userIS[i]);CHKERRQ(ierr);}
2959     ierr = PetscFree(patch->userIS);CHKERRQ(ierr);
2960   }
2961   ierr = PetscFree(patch->precomputedTensorLocations);CHKERRQ(ierr);
2962   ierr = PetscFree(patch->precomputedIntFacetTensorLocations);CHKERRQ(ierr);
2963 
2964   patch->bs          = 0;
2965   patch->cellNodeMap = NULL;
2966   patch->nsubspaces  = 0;
2967   ierr = ISDestroy(&patch->iterationSet);CHKERRQ(ierr);
2968 
2969   ierr = PetscViewerDestroy(&patch->viewerSection);CHKERRQ(ierr);
2970   PetscFunctionReturn(0);
2971 }
2972 
2973 static PetscErrorCode PCDestroy_PATCH_Linear(PC pc)
2974 {
2975   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2976   PetscInt       i;
2977   PetscErrorCode ierr;
2978 
2979   PetscFunctionBegin;
2980   if (patch->solver) {
2981     for (i = 0; i < patch->npatch; ++i) {ierr = KSPDestroy((KSP *) &patch->solver[i]);CHKERRQ(ierr);}
2982     ierr = PetscFree(patch->solver);CHKERRQ(ierr);
2983   }
2984   PetscFunctionReturn(0);
2985 }
2986 
2987 static PetscErrorCode PCDestroy_PATCH(PC pc)
2988 {
2989   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2990   PetscErrorCode ierr;
2991 
2992   PetscFunctionBegin;
2993   ierr = PCReset_PATCH(pc);CHKERRQ(ierr);
2994   ierr = (*patch->destroysolver)(pc);CHKERRQ(ierr);
2995   ierr = PetscFree(pc->data);CHKERRQ(ierr);
2996   PetscFunctionReturn(0);
2997 }
2998 
2999 static PetscErrorCode PCSetFromOptions_PATCH(PetscOptionItems *PetscOptionsObject, PC pc)
3000 {
3001   PC_PATCH            *patch = (PC_PATCH *) pc->data;
3002   PCPatchConstructType patchConstructionType = PC_PATCH_STAR;
3003   char                 sub_mat_type[PETSC_MAX_PATH_LEN];
3004   char                 option[PETSC_MAX_PATH_LEN];
3005   const char          *prefix;
3006   PetscBool            flg, dimflg, codimflg;
3007   MPI_Comm             comm;
3008   PetscInt            *ifields, nfields, k;
3009   PetscErrorCode       ierr;
3010   PCCompositeType loctype = PC_COMPOSITE_ADDITIVE;
3011 
3012   PetscFunctionBegin;
3013   ierr = PetscObjectGetComm((PetscObject) pc, &comm);CHKERRQ(ierr);
3014   ierr = PetscObjectGetOptionsPrefix((PetscObject) pc, &prefix);CHKERRQ(ierr);
3015   ierr = PetscOptionsHead(PetscOptionsObject, "Patch solver options");CHKERRQ(ierr);
3016 
3017   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_save_operators", patch->classname);CHKERRQ(ierr);
3018   ierr = PetscOptionsBool(option,  "Store all patch operators for lifetime of object?", "PCPatchSetSaveOperators", patch->save_operators, &patch->save_operators, &flg);CHKERRQ(ierr);
3019 
3020   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_precompute_element_tensors", patch->classname);
3021   ierr = PetscOptionsBool(option,  "Compute each element tensor only once?", "PCPatchSetPrecomputeElementTensors", patch->precomputeElementTensors, &patch->precomputeElementTensors, &flg);CHKERRQ(ierr);
3022   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_partition_of_unity", patch->classname);
3023   ierr = PetscOptionsBool(option, "Weight contributions by dof multiplicity?", "PCPatchSetPartitionOfUnity", patch->partition_of_unity, &patch->partition_of_unity, &flg);CHKERRQ(ierr);
3024 
3025   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_local_type", patch->classname);CHKERRQ(ierr);
3026   ierr = PetscOptionsEnum(option,"Type of local solver composition (additive or multiplicative)","PCPatchSetLocalComposition",PCCompositeTypes,(PetscEnum)loctype,(PetscEnum*)&loctype,&flg);CHKERRQ(ierr);
3027   if(flg) { ierr = PCPatchSetLocalComposition(pc, loctype);CHKERRQ(ierr);}
3028 
3029   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_construct_dim", patch->classname);CHKERRQ(ierr);
3030   ierr = PetscOptionsInt(option, "What dimension of mesh point to construct patches by? (0 = vertices)", "PCPATCH", patch->dim, &patch->dim, &dimflg);CHKERRQ(ierr);
3031   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_construct_codim", patch->classname);CHKERRQ(ierr);
3032   ierr = PetscOptionsInt(option, "What co-dimension of mesh point to construct patches by? (0 = cells)", "PCPATCH", patch->codim, &patch->codim, &codimflg);CHKERRQ(ierr);
3033   if (dimflg && codimflg) SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Can only set one of dimension or co-dimension");
3034 
3035   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_construct_type", patch->classname);CHKERRQ(ierr);
3036   ierr = PetscOptionsEnum(option, "How should the patches be constructed?", "PCPatchSetConstructType", PCPatchConstructTypes, (PetscEnum) patchConstructionType, (PetscEnum *) &patchConstructionType, &flg);CHKERRQ(ierr);
3037   if (flg) {ierr = PCPatchSetConstructType(pc, patchConstructionType, NULL, NULL);CHKERRQ(ierr);}
3038 
3039   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_vanka_dim", patch->classname);CHKERRQ(ierr);
3040   ierr = PetscOptionsInt(option, "Topological dimension of entities for Vanka to ignore", "PCPATCH", patch->vankadim, &patch->vankadim, &flg);CHKERRQ(ierr);
3041 
3042   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_ignore_dim", patch->classname);CHKERRQ(ierr);
3043   ierr = PetscOptionsInt(option, "Topological dimension of entities for completion to ignore", "PCPATCH", patch->ignoredim, &patch->ignoredim, &flg);CHKERRQ(ierr);
3044 
3045   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_pardecomp_overlap", patch->classname);CHKERRQ(ierr);
3046   ierr = PetscOptionsInt(option, "What overlap should we use in construct type pardecomp?", "PCPATCH", patch->pardecomp_overlap, &patch->pardecomp_overlap, &flg);CHKERRQ(ierr);
3047 
3048   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_sub_mat_type", patch->classname);CHKERRQ(ierr);
3049   ierr = PetscOptionsFList(option, "Matrix type for patch solves", "PCPatchSetSubMatType", MatList, NULL, sub_mat_type, PETSC_MAX_PATH_LEN, &flg);CHKERRQ(ierr);
3050   if (flg) {ierr = PCPatchSetSubMatType(pc, sub_mat_type);CHKERRQ(ierr);}
3051 
3052   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_symmetrise_sweep", patch->classname);CHKERRQ(ierr);
3053   ierr = PetscOptionsBool(option, "Go start->end, end->start?", "PCPATCH", patch->symmetrise_sweep, &patch->symmetrise_sweep, &flg);CHKERRQ(ierr);
3054 
3055   /* If the user has set the number of subspaces, use that for the buffer size,
3056      otherwise use a large number */
3057   if (patch->nsubspaces <= 0) {
3058     nfields = 128;
3059   } else {
3060     nfields = patch->nsubspaces;
3061   }
3062   ierr = PetscMalloc1(nfields, &ifields);CHKERRQ(ierr);
3063   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_exclude_subspaces", patch->classname);CHKERRQ(ierr);
3064   ierr = PetscOptionsGetIntArray(((PetscObject)pc)->options,((PetscObject)pc)->prefix,option,ifields,&nfields,&flg);CHKERRQ(ierr);
3065   if (flg && (patchConstructionType == PC_PATCH_USER)) SETERRQ(comm, PETSC_ERR_ARG_INCOMP, "We cannot support excluding a subspace with user patches because we do not index patches with a mesh point");
3066   if (flg) {
3067     PetscHSetIClear(patch->subspaces_to_exclude);
3068     for (k = 0; k < nfields; k++) {
3069       PetscHSetIAdd(patch->subspaces_to_exclude, ifields[k]);
3070     }
3071   }
3072   ierr = PetscFree(ifields);CHKERRQ(ierr);
3073 
3074   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_patches_view", patch->classname);CHKERRQ(ierr);
3075   ierr = PetscOptionsBool(option, "Print out information during patch construction", "PCPATCH", patch->viewPatches, &patch->viewPatches, &flg);CHKERRQ(ierr);
3076   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_cells_view", patch->classname);CHKERRQ(ierr);
3077   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options, prefix, option, &patch->viewerCells, &patch->formatCells, &patch->viewCells);CHKERRQ(ierr);
3078   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_interior_facets_view", patch->classname);CHKERRQ(ierr);
3079   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options, prefix, option, &patch->viewerIntFacets, &patch->formatIntFacets, &patch->viewIntFacets);CHKERRQ(ierr);
3080   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_exterior_facets_view", patch->classname);CHKERRQ(ierr);
3081   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options, prefix, option, &patch->viewerExtFacets, &patch->formatExtFacets, &patch->viewExtFacets);CHKERRQ(ierr);
3082   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_points_view", patch->classname);CHKERRQ(ierr);
3083   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options, prefix, option, &patch->viewerPoints, &patch->formatPoints, &patch->viewPoints);CHKERRQ(ierr);
3084   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_section_view", patch->classname);CHKERRQ(ierr);
3085   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options, prefix, option, &patch->viewerSection, &patch->formatSection, &patch->viewSection);CHKERRQ(ierr);
3086   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_mat_view", patch->classname);CHKERRQ(ierr);
3087   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options, prefix, option, &patch->viewerMatrix, &patch->formatMatrix, &patch->viewMatrix);CHKERRQ(ierr);
3088   ierr = PetscOptionsTail();CHKERRQ(ierr);
3089   patch->optionsSet = PETSC_TRUE;
3090   PetscFunctionReturn(0);
3091 }
3092 
3093 static PetscErrorCode PCSetUpOnBlocks_PATCH(PC pc)
3094 {
3095   PC_PATCH          *patch = (PC_PATCH*) pc->data;
3096   KSPConvergedReason reason;
3097   PetscInt           i;
3098   PetscErrorCode     ierr;
3099 
3100   PetscFunctionBegin;
3101   if (!patch->save_operators) {
3102     /* Can't do this here because the sub KSPs don't have an operator attached yet. */
3103     PetscFunctionReturn(0);
3104   }
3105   for (i = 0; i < patch->npatch; ++i) {
3106     if (!((KSP) patch->solver[i])->setfromoptionscalled) {
3107       ierr = KSPSetFromOptions((KSP) patch->solver[i]);CHKERRQ(ierr);
3108     }
3109     ierr = KSPSetUp((KSP) patch->solver[i]);CHKERRQ(ierr);
3110     ierr = KSPGetConvergedReason((KSP) patch->solver[i], &reason);CHKERRQ(ierr);
3111     if (reason == KSP_DIVERGED_PC_FAILED) pc->failedreason = PC_SUBPC_ERROR;
3112   }
3113   PetscFunctionReturn(0);
3114 }
3115 
3116 static PetscErrorCode PCView_PATCH(PC pc, PetscViewer viewer)
3117 {
3118   PC_PATCH      *patch = (PC_PATCH *) pc->data;
3119   PetscViewer    sviewer;
3120   PetscBool      isascii;
3121   PetscMPIInt    rank;
3122   PetscErrorCode ierr;
3123 
3124   PetscFunctionBegin;
3125   /* TODO Redo tabbing with set tbas in new style */
3126   ierr = PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);CHKERRQ(ierr);
3127   if (!isascii) PetscFunctionReturn(0);
3128   ierr = MPI_Comm_rank(PetscObjectComm((PetscObject) pc), &rank);CHKERRQ(ierr);
3129   ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
3130   ierr = PetscViewerASCIIPrintf(viewer, "Subspace Correction preconditioner with %d patches\n", patch->npatch);CHKERRQ(ierr);
3131   if(patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
3132     ierr = PetscViewerASCIIPrintf(viewer, "Schwarz type: multiplicative\n");CHKERRQ(ierr);
3133   } else {
3134     ierr = PetscViewerASCIIPrintf(viewer, "Schwarz type: additive\n");CHKERRQ(ierr);
3135   }
3136   if (patch->partition_of_unity) {ierr = PetscViewerASCIIPrintf(viewer, "Weighting by partition of unity\n");CHKERRQ(ierr);}
3137   else                           {ierr = PetscViewerASCIIPrintf(viewer, "Not weighting by partition of unity\n");CHKERRQ(ierr);}
3138   if (patch->symmetrise_sweep) {ierr = PetscViewerASCIIPrintf(viewer, "Symmetrising sweep (start->end, then end->start)\n");CHKERRQ(ierr);}
3139   else                         {ierr = PetscViewerASCIIPrintf(viewer, "Not symmetrising sweep\n");CHKERRQ(ierr);}
3140   if (!patch->precomputeElementTensors) {ierr = PetscViewerASCIIPrintf(viewer, "Not precomputing element tensors (overlapping cells rebuilt in every patch assembly)\n");CHKERRQ(ierr);}
3141   else                            {ierr = PetscViewerASCIIPrintf(viewer, "Precomputing element tensors (each cell assembled only once)\n");CHKERRQ(ierr);}
3142   if (!patch->save_operators) {ierr = PetscViewerASCIIPrintf(viewer, "Not saving patch operators (rebuilt every PCApply)\n");CHKERRQ(ierr);}
3143   else                        {ierr = PetscViewerASCIIPrintf(viewer, "Saving patch operators (rebuilt every PCSetUp)\n");CHKERRQ(ierr);}
3144   if (patch->patchconstructop == PCPatchConstruct_Star)       {ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: star\n");CHKERRQ(ierr);}
3145   else if (patch->patchconstructop == PCPatchConstruct_Vanka) {ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: Vanka\n");CHKERRQ(ierr);}
3146   else if (patch->patchconstructop == PCPatchConstruct_User)  {ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: user-specified\n");CHKERRQ(ierr);}
3147   else                                                        {ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: unknown\n");CHKERRQ(ierr);}
3148 
3149   if (patch->isNonlinear) {
3150     ierr = PetscViewerASCIIPrintf(viewer, "SNES on patches (all same):\n");CHKERRQ(ierr);
3151   } else {
3152     ierr = PetscViewerASCIIPrintf(viewer, "KSP on patches (all same):\n");CHKERRQ(ierr);
3153   }
3154   if (patch->solver) {
3155     ierr = PetscViewerGetSubViewer(viewer, PETSC_COMM_SELF, &sviewer);CHKERRQ(ierr);
3156     if (!rank) {
3157       ierr = PetscViewerASCIIPushTab(sviewer);CHKERRQ(ierr);
3158       ierr = PetscObjectView(patch->solver[0], sviewer);CHKERRQ(ierr);
3159       ierr = PetscViewerASCIIPopTab(sviewer);CHKERRQ(ierr);
3160     }
3161     ierr = PetscViewerRestoreSubViewer(viewer, PETSC_COMM_SELF, &sviewer);CHKERRQ(ierr);
3162   } else {
3163     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
3164     ierr = PetscViewerASCIIPrintf(viewer, "Solver not yet set.\n");CHKERRQ(ierr);
3165     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
3166   }
3167   ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
3168   PetscFunctionReturn(0);
3169 }
3170 
3171 /*MC
3172   PCPATCH - A PC object that encapsulates flexible definition of blocks for overlapping and non-overlapping
3173             small block additive preconditioners. Block definition is based on topology from
3174             a DM and equation numbering from a PetscSection.
3175 
3176   Options Database Keys:
3177 + -pc_patch_cells_view   - Views the process local cell numbers for each patch
3178 . -pc_patch_points_view  - Views the process local mesh point numbers for each patch
3179 . -pc_patch_g2l_view     - Views the map between global dofs and patch local dofs for each patch
3180 . -pc_patch_patches_view - Views the global dofs associated with each patch and its boundary
3181 - -pc_patch_sub_mat_view - Views the matrix associated with each patch
3182 
3183   Level: intermediate
3184 
3185 .seealso: PCType, PCCreate(), PCSetType()
3186 M*/
3187 PETSC_EXTERN PetscErrorCode PCCreate_Patch(PC pc)
3188 {
3189   PC_PATCH      *patch;
3190   PetscErrorCode ierr;
3191 
3192   PetscFunctionBegin;
3193   ierr = PetscNewLog(pc, &patch);CHKERRQ(ierr);
3194 
3195   if (patch->subspaces_to_exclude) {
3196     PetscHSetIDestroy(&patch->subspaces_to_exclude);
3197   }
3198   PetscHSetICreate(&patch->subspaces_to_exclude);
3199 
3200   patch->classname = "pc";
3201   patch->isNonlinear = PETSC_FALSE;
3202 
3203   /* Set some defaults */
3204   patch->combined           = PETSC_FALSE;
3205   patch->save_operators     = PETSC_TRUE;
3206   patch->local_composition_type = PC_COMPOSITE_ADDITIVE;
3207   patch->precomputeElementTensors = PETSC_FALSE;
3208   patch->partition_of_unity = PETSC_FALSE;
3209   patch->codim              = -1;
3210   patch->dim                = -1;
3211   patch->vankadim           = -1;
3212   patch->ignoredim          = -1;
3213   patch->pardecomp_overlap  = 0;
3214   patch->patchconstructop   = PCPatchConstruct_Star;
3215   patch->symmetrise_sweep   = PETSC_FALSE;
3216   patch->npatch             = 0;
3217   patch->userIS             = NULL;
3218   patch->optionsSet         = PETSC_FALSE;
3219   patch->iterationSet       = NULL;
3220   patch->user_patches       = PETSC_FALSE;
3221   ierr = PetscStrallocpy(MATDENSE, (char **) &patch->sub_mat_type);CHKERRQ(ierr);
3222   patch->viewPatches        = PETSC_FALSE;
3223   patch->viewCells          = PETSC_FALSE;
3224   patch->viewPoints         = PETSC_FALSE;
3225   patch->viewSection        = PETSC_FALSE;
3226   patch->viewMatrix         = PETSC_FALSE;
3227   patch->setupsolver        = PCSetUp_PATCH_Linear;
3228   patch->applysolver        = PCApply_PATCH_Linear;
3229   patch->resetsolver        = PCReset_PATCH_Linear;
3230   patch->destroysolver      = PCDestroy_PATCH_Linear;
3231   patch->updatemultiplicative = PCUpdateMultiplicative_PATCH_Linear;
3232   patch->dofMappingWithoutToWithArtificial = NULL;
3233   patch->dofMappingWithoutToWithAll = NULL;
3234 
3235   pc->data                 = (void *) patch;
3236   pc->ops->apply           = PCApply_PATCH;
3237   pc->ops->applytranspose  = 0; /* PCApplyTranspose_PATCH; */
3238   pc->ops->setup           = PCSetUp_PATCH;
3239   pc->ops->reset           = PCReset_PATCH;
3240   pc->ops->destroy         = PCDestroy_PATCH;
3241   pc->ops->setfromoptions  = PCSetFromOptions_PATCH;
3242   pc->ops->setuponblocks   = PCSetUpOnBlocks_PATCH;
3243   pc->ops->view            = PCView_PATCH;
3244   pc->ops->applyrichardson = 0;
3245 
3246   PetscFunctionReturn(0);
3247 }
3248