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