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