xref: /petsc/src/ksp/pc/impls/patch/pcpatch.c (revision c3faab338d2b48eae7544b4a2e8b6d94787d5f37)
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   PCPatchSetComputeOperator - Set the callback used to compute patch matrices
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 +  usercomputeop(pc, point, x, mat, cellIS, n, u, ctx)
606 +  pc     - The PC
607 +  point  - The point
608 +  x      - The input solution (not used in linear problems)
609 +  mat    - The patch matrix
610 +  cellIS - An array of the cell 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: PCPatchGetComputeOperator(), PCPatchSetComputeFunction(), PCPatchSetDiscretisationInfo()
617 @*/
618 PetscErrorCode PCPatchSetComputeOperator(PC pc, PetscErrorCode (*func)(PC, PetscInt, Vec, Mat, IS, PetscInt, const PetscInt *, const PetscInt *, void *), void *ctx)
619 {
620   PC_PATCH *patch = (PC_PATCH *) pc->data;
621 
622   PetscFunctionBegin;
623   patch->usercomputeop    = func;
624   patch->usercomputeopctx = ctx;
625   PetscFunctionReturn(0);
626 }
627 
628 /* On entry, ht contains the topological entities whose dofs we are responsible for solving for;
629    on exit, cht contains all the topological entities we need to compute their residuals.
630    In full generality this should incorporate knowledge of the sparsity pattern of the matrix;
631    here we assume a standard FE sparsity pattern.*/
632 /* TODO: Use DMPlexGetAdjacency() */
633 static PetscErrorCode PCPatchCompleteCellPatch(PC pc, PetscHSetI ht, PetscHSetI cht)
634 {
635   DM             dm;
636   PetscHashIter  hi;
637   PetscInt       point;
638   PetscInt      *star = NULL, *closure = NULL;
639   PetscInt       ignoredim, iStart = 0, iEnd = -1, starSize, closureSize, si, ci;
640   PetscErrorCode ierr;
641 
642   PetscFunctionBegin;
643   ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
644   ierr = PCPatchGetIgnoreDim(pc, &ignoredim);CHKERRQ(ierr);
645   if (ignoredim >= 0) {ierr = DMPlexGetDepthStratum(dm, ignoredim, &iStart, &iEnd);CHKERRQ(ierr);}
646   ierr = PetscHSetIClear(cht);CHKERRQ(ierr);
647   PetscHashIterBegin(ht, hi);
648   while (!PetscHashIterAtEnd(ht, hi)) {
649 
650     PetscHashIterGetKey(ht, hi, point);
651     PetscHashIterNext(ht, hi);
652 
653     /* Loop over all the cells that this point connects to */
654     ierr = DMPlexGetTransitiveClosure(dm, point, PETSC_FALSE, &starSize, &star);CHKERRQ(ierr);
655     for (si = 0; si < starSize*2; si += 2) {
656       const PetscInt ownedpoint = star[si];
657       /* TODO Check for point in cht before running through closure again */
658       /* now loop over all entities in the closure of that cell */
659       ierr = DMPlexGetTransitiveClosure(dm, ownedpoint, PETSC_TRUE, &closureSize, &closure);CHKERRQ(ierr);
660       for (ci = 0; ci < closureSize*2; ci += 2) {
661         const PetscInt seenpoint = closure[ci];
662         if (ignoredim >= 0 && seenpoint >= iStart && seenpoint < iEnd) continue;
663         ierr = PetscHSetIAdd(cht, seenpoint);CHKERRQ(ierr);
664       }
665       ierr = DMPlexRestoreTransitiveClosure(dm, ownedpoint, PETSC_TRUE, NULL, &closure);CHKERRQ(ierr);
666     }
667     ierr = DMPlexRestoreTransitiveClosure(dm, point, PETSC_FALSE, NULL, &star);CHKERRQ(ierr);
668   }
669   PetscFunctionReturn(0);
670 }
671 
672 static PetscErrorCode PCPatchGetGlobalDofs(PC pc, PetscSection dofSection[], PetscInt f, PetscBool combined, PetscInt p, PetscInt *dof, PetscInt *off)
673 {
674   PetscErrorCode ierr;
675 
676   PetscFunctionBegin;
677   if (combined) {
678     if (f < 0) {
679       if (dof) {ierr = PetscSectionGetDof(dofSection[0], p, dof);CHKERRQ(ierr);}
680       if (off) {ierr = PetscSectionGetOffset(dofSection[0], p, off);CHKERRQ(ierr);}
681     } else {
682       if (dof) {ierr = PetscSectionGetFieldDof(dofSection[0], p, f, dof);CHKERRQ(ierr);}
683       if (off) {ierr = PetscSectionGetFieldOffset(dofSection[0], p, f, off);CHKERRQ(ierr);}
684     }
685   } else {
686     if (f < 0) {
687       PC_PATCH *patch = (PC_PATCH *) pc->data;
688       PetscInt  fdof, g;
689 
690       if (dof) {
691         *dof = 0;
692         for (g = 0; g < patch->nsubspaces; ++g) {
693           ierr = PetscSectionGetDof(dofSection[g], p, &fdof);CHKERRQ(ierr);
694           *dof += fdof;
695         }
696       }
697       if (off) {
698         *off = 0;
699         for (g = 0; g < patch->nsubspaces; ++g) {
700           ierr = PetscSectionGetOffset(dofSection[g], p, &fdof);CHKERRQ(ierr);
701           *off += fdof;
702         }
703       }
704     } else {
705       if (dof) {ierr = PetscSectionGetDof(dofSection[f], p, dof);CHKERRQ(ierr);}
706       if (off) {ierr = PetscSectionGetOffset(dofSection[f], p, off);CHKERRQ(ierr);}
707     }
708   }
709   PetscFunctionReturn(0);
710 }
711 
712 /* Given a hash table with a set of topological entities (pts), compute the degrees of
713    freedom in global concatenated numbering on those entities.
714    For Vanka smoothing, this needs to do something special: ignore dofs of the
715    constraint subspace on entities that aren't the base entity we're building the patch
716    around. */
717 static PetscErrorCode PCPatchGetPointDofs(PC pc, PetscHSetI pts, PetscHSetI dofs, PetscInt base, PetscHSetI* subspaces_to_exclude)
718 {
719   PC_PATCH      *patch = (PC_PATCH *) pc->data;
720   PetscHashIter  hi;
721   PetscInt       ldof, loff;
722   PetscInt       k, p;
723   PetscErrorCode ierr;
724 
725   PetscFunctionBegin;
726   ierr = PetscHSetIClear(dofs);CHKERRQ(ierr);
727   for (k = 0; k < patch->nsubspaces; ++k) {
728     PetscInt subspaceOffset = patch->subspaceOffsets[k];
729     PetscInt bs             = patch->bs[k];
730     PetscInt j, l;
731 
732     if (subspaces_to_exclude != NULL) {
733       PetscBool should_exclude_k = PETSC_FALSE;
734       PetscHSetIHas(*subspaces_to_exclude, k, &should_exclude_k);
735       if (should_exclude_k) {
736         /* only get this subspace dofs at the base entity, not any others */
737         ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, k, patch->combined, base, &ldof, &loff);CHKERRQ(ierr);
738         if (0 == ldof) continue;
739         for (j = loff; j < ldof + loff; ++j) {
740           for (l = 0; l < bs; ++l) {
741             PetscInt dof = bs*j + l + subspaceOffset;
742             ierr = PetscHSetIAdd(dofs, dof);CHKERRQ(ierr);
743           }
744         }
745         continue; /* skip the other dofs of this subspace */
746       }
747     }
748 
749     PetscHashIterBegin(pts, hi);
750     while (!PetscHashIterAtEnd(pts, hi)) {
751       PetscHashIterGetKey(pts, hi, p);
752       PetscHashIterNext(pts, hi);
753       ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, k, patch->combined, p, &ldof, &loff);CHKERRQ(ierr);
754       if (0 == ldof) continue;
755       for (j = loff; j < ldof + loff; ++j) {
756         for (l = 0; l < bs; ++l) {
757           PetscInt dof = bs*j + l + subspaceOffset;
758           ierr = PetscHSetIAdd(dofs, dof);CHKERRQ(ierr);
759         }
760       }
761     }
762   }
763   PetscFunctionReturn(0);
764 }
765 
766 /* Given two hash tables A and B, compute the keys in B that are not in A, and put them in C */
767 static PetscErrorCode PCPatchComputeSetDifference_Private(PetscHSetI A, PetscHSetI B, PetscHSetI C)
768 {
769   PetscHashIter  hi;
770   PetscInt       key;
771   PetscBool      flg;
772   PetscErrorCode ierr;
773 
774   PetscFunctionBegin;
775   ierr = PetscHSetIClear(C);CHKERRQ(ierr);
776   PetscHashIterBegin(B, hi);
777   while (!PetscHashIterAtEnd(B, hi)) {
778     PetscHashIterGetKey(B, hi, key);
779     PetscHashIterNext(B, hi);
780     ierr = PetscHSetIHas(A, key, &flg);CHKERRQ(ierr);
781     if (!flg) {ierr = PetscHSetIAdd(C, key);CHKERRQ(ierr);}
782   }
783   PetscFunctionReturn(0);
784 }
785 
786 /*
787  * PCPatchCreateCellPatches - create patches.
788  *
789  * Input Parameters:
790  * + dm - The DMPlex object defining the mesh
791  *
792  * Output Parameters:
793  * + cellCounts  - Section with counts of cells around each vertex
794  * . cells       - IS of the cell point indices of cells in each patch
795  * . pointCounts - Section with counts of cells around each vertex
796  * - point       - IS of the cell point indices of cells in each patch
797  */
798 static PetscErrorCode PCPatchCreateCellPatches(PC pc)
799 {
800   PC_PATCH       *patch = (PC_PATCH *) pc->data;
801   DMLabel         ghost = NULL;
802   DM              dm, plex;
803   PetscHSetI      ht, cht;
804   PetscSection    cellCounts,  pointCounts, intFacetCounts, extFacetCounts;
805   PetscInt       *cellsArray, *pointsArray, *intFacetsArray, *extFacetsArray, *intFacetsToPatchCell;
806   PetscInt        numCells, numPoints, numIntFacets, numExtFacets;
807   const PetscInt *leaves;
808   PetscInt        nleaves, pStart, pEnd, cStart, cEnd, vStart, vEnd, v;
809   PetscBool       isFiredrake;
810   PetscErrorCode  ierr;
811 
812   PetscFunctionBegin;
813   /* Used to keep track of the cells in the patch. */
814   ierr = PetscHSetICreate(&ht);CHKERRQ(ierr);
815   ierr = PetscHSetICreate(&cht);CHKERRQ(ierr);
816 
817   ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
818   if (!dm) SETERRQ(PetscObjectComm((PetscObject) pc), PETSC_ERR_ARG_WRONGSTATE, "DM not yet set on patch PC\n");
819   ierr = DMConvert(dm, DMPLEX, &plex);CHKERRQ(ierr);
820   ierr = DMPlexGetChart(plex, &pStart, &pEnd);CHKERRQ(ierr);
821   ierr = DMPlexGetHeightStratum(plex, 0, &cStart, &cEnd);CHKERRQ(ierr);
822 
823   if (patch->user_patches) {
824     ierr = patch->userpatchconstructionop(pc, &patch->npatch, &patch->userIS, &patch->iterationSet, patch->userpatchconstructctx);CHKERRQ(ierr);
825     vStart = 0; vEnd = patch->npatch;
826   } else if (patch->ctype == PC_PATCH_PARDECOMP) {
827     vStart = 0; vEnd = 1;
828   } else if (patch->codim < 0) {
829     if (patch->dim < 0) {ierr = DMPlexGetDepthStratum(plex,  0,            &vStart, &vEnd);CHKERRQ(ierr);}
830     else                {ierr = DMPlexGetDepthStratum(plex,  patch->dim,   &vStart, &vEnd);CHKERRQ(ierr);}
831   } else                {ierr = DMPlexGetHeightStratum(plex, patch->codim, &vStart, &vEnd);CHKERRQ(ierr);}
832   patch->npatch = vEnd - vStart;
833 
834   /* These labels mark the owned points.  We only create patches around points that this process owns. */
835   ierr = DMHasLabel(dm, "pyop2_ghost", &isFiredrake);CHKERRQ(ierr);
836   if (isFiredrake) {
837     ierr = DMGetLabel(dm, "pyop2_ghost", &ghost);CHKERRQ(ierr);
838     ierr = DMLabelCreateIndex(ghost, pStart, pEnd);CHKERRQ(ierr);
839   } else {
840     PetscSF sf;
841 
842     ierr = DMGetPointSF(dm, &sf);CHKERRQ(ierr);
843     ierr = PetscSFGetGraph(sf, NULL, &nleaves, &leaves, NULL);CHKERRQ(ierr);
844     nleaves = PetscMax(nleaves, 0);
845   }
846 
847   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->cellCounts);CHKERRQ(ierr);
848   ierr = PetscObjectSetName((PetscObject) patch->cellCounts, "Patch Cell Layout");CHKERRQ(ierr);
849   cellCounts = patch->cellCounts;
850   ierr = PetscSectionSetChart(cellCounts, vStart, vEnd);CHKERRQ(ierr);
851   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->pointCounts);CHKERRQ(ierr);
852   ierr = PetscObjectSetName((PetscObject) patch->pointCounts, "Patch Point Layout");CHKERRQ(ierr);
853   pointCounts = patch->pointCounts;
854   ierr = PetscSectionSetChart(pointCounts, vStart, vEnd);CHKERRQ(ierr);
855   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->extFacetCounts);CHKERRQ(ierr);
856   ierr = PetscObjectSetName((PetscObject) patch->extFacetCounts, "Patch Exterior Facet Layout");CHKERRQ(ierr);
857   extFacetCounts = patch->extFacetCounts;
858   ierr = PetscSectionSetChart(extFacetCounts, vStart, vEnd);CHKERRQ(ierr);
859   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->intFacetCounts);CHKERRQ(ierr);
860   ierr = PetscObjectSetName((PetscObject) patch->intFacetCounts, "Patch Interior Facet Layout");CHKERRQ(ierr);
861   intFacetCounts = patch->intFacetCounts;
862   ierr = PetscSectionSetChart(intFacetCounts, vStart, vEnd);CHKERRQ(ierr);
863   /* Count cells and points in the patch surrounding each entity */
864   PetscInt       fStart, fEnd;
865   ierr = DMPlexGetHeightStratum(dm, 1, &fStart, &fEnd);CHKERRQ(ierr);
866   for (v = vStart; v < vEnd; ++v) {
867     PetscHashIter hi;
868     PetscInt       chtSize, loc = -1;
869     PetscBool      flg;
870 
871     if (!patch->user_patches && patch->ctype != PC_PATCH_PARDECOMP) {
872       if (ghost) {ierr = DMLabelHasPoint(ghost, v, &flg);CHKERRQ(ierr);}
873       else       {ierr = PetscFindInt(v, nleaves, leaves, &loc);CHKERRQ(ierr); flg = loc >=0 ? PETSC_TRUE : PETSC_FALSE;}
874       /* Not an owned entity, don't make a cell patch. */
875       if (flg) continue;
876     }
877 
878     ierr = patch->patchconstructop((void *) patch, dm, v, ht);CHKERRQ(ierr);
879     ierr = PCPatchCompleteCellPatch(pc, ht, cht);CHKERRQ(ierr);
880     ierr = PetscHSetIGetSize(cht, &chtSize);CHKERRQ(ierr);
881     /* empty patch, continue */
882     if (chtSize == 0) continue;
883 
884     /* safe because size(cht) > 0 from above */
885     PetscHashIterBegin(cht, hi);
886     while (!PetscHashIterAtEnd(cht, hi)) {
887       PetscInt point, pdof;
888 
889       PetscHashIterGetKey(cht, hi, point);
890       if (fStart <= point && point < fEnd) {
891         const PetscInt *support;
892         PetscInt supportSize, p;
893         PetscBool interior = PETSC_TRUE;
894         ierr = DMPlexGetSupport(dm, point, &support);CHKERRQ(ierr);
895         ierr = DMPlexGetSupportSize(dm, point, &supportSize);CHKERRQ(ierr);
896         if (supportSize == 1) {
897           interior = PETSC_FALSE;
898         } else {
899           for (p = 0; p < supportSize; p++) {
900             PetscBool found;
901             /* FIXME: can I do this while iterating over cht? */
902             PetscHSetIHas(cht, support[p], &found);
903             if (!found) {
904               interior = PETSC_FALSE;
905               break;
906             }
907           }
908         }
909         if (interior) {
910           ierr = PetscSectionAddDof(intFacetCounts, v, 1);CHKERRQ(ierr);
911         } else {
912           ierr = PetscSectionAddDof(extFacetCounts, v, 1);CHKERRQ(ierr);
913         }
914       }
915       ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, -1, patch->combined, point, &pdof, NULL);CHKERRQ(ierr);
916       if (pdof)                            {ierr = PetscSectionAddDof(pointCounts, v, 1);CHKERRQ(ierr);}
917       if (point >= cStart && point < cEnd) {ierr = PetscSectionAddDof(cellCounts, v, 1);CHKERRQ(ierr);}
918       PetscHashIterNext(cht, hi);
919     }
920   }
921   if (isFiredrake) {ierr = DMLabelDestroyIndex(ghost);CHKERRQ(ierr);}
922 
923   ierr = PetscSectionSetUp(cellCounts);CHKERRQ(ierr);
924   ierr = PetscSectionGetStorageSize(cellCounts, &numCells);CHKERRQ(ierr);
925   ierr = PetscMalloc1(numCells, &cellsArray);CHKERRQ(ierr);
926   ierr = PetscSectionSetUp(pointCounts);CHKERRQ(ierr);
927   ierr = PetscSectionGetStorageSize(pointCounts, &numPoints);CHKERRQ(ierr);
928   ierr = PetscMalloc1(numPoints, &pointsArray);CHKERRQ(ierr);
929 
930   ierr = PetscSectionSetUp(intFacetCounts);CHKERRQ(ierr);
931   ierr = PetscSectionSetUp(extFacetCounts);CHKERRQ(ierr);
932   ierr = PetscSectionGetStorageSize(intFacetCounts, &numIntFacets);CHKERRQ(ierr);
933   ierr = PetscSectionGetStorageSize(extFacetCounts, &numExtFacets);CHKERRQ(ierr);
934   ierr = PetscMalloc1(numIntFacets, &intFacetsArray);CHKERRQ(ierr);
935   ierr = PetscMalloc1(numIntFacets*2, &intFacetsToPatchCell);CHKERRQ(ierr);
936   ierr = PetscMalloc1(numExtFacets, &extFacetsArray);CHKERRQ(ierr);
937 
938 
939   /* Now that we know how much space we need, run through again and actually remember the cells. */
940   for (v = vStart; v < vEnd; v++ ) {
941     PetscHashIter hi;
942     PetscInt       dof, off, cdof, coff, efdof, efoff, ifdof, ifoff, pdof, n = 0, cn = 0, ifn = 0, efn = 0;
943 
944     ierr = PetscSectionGetDof(pointCounts, v, &dof);CHKERRQ(ierr);
945     ierr = PetscSectionGetOffset(pointCounts, v, &off);CHKERRQ(ierr);
946     ierr = PetscSectionGetDof(cellCounts, v, &cdof);CHKERRQ(ierr);
947     ierr = PetscSectionGetOffset(cellCounts, v, &coff);CHKERRQ(ierr);
948     ierr = PetscSectionGetDof(intFacetCounts, v, &ifdof);CHKERRQ(ierr);
949     ierr = PetscSectionGetOffset(intFacetCounts, v, &ifoff);CHKERRQ(ierr);
950     ierr = PetscSectionGetDof(extFacetCounts, v, &efdof);CHKERRQ(ierr);
951     ierr = PetscSectionGetOffset(extFacetCounts, v, &efoff);CHKERRQ(ierr);
952     if (dof <= 0) continue;
953     ierr = patch->patchconstructop((void *) patch, dm, v, ht);CHKERRQ(ierr);
954     ierr = PCPatchCompleteCellPatch(pc, ht, cht);CHKERRQ(ierr);
955     PetscHashIterBegin(cht, hi);
956     while (!PetscHashIterAtEnd(cht, hi)) {
957       PetscInt point;
958 
959       PetscHashIterGetKey(cht, hi, point);
960       if (fStart <= point && point < fEnd) {
961         const PetscInt *support;
962         PetscInt supportSize, p;
963         PetscBool interior = PETSC_TRUE;
964         ierr = DMPlexGetSupport(dm, point, &support);CHKERRQ(ierr);
965         ierr = DMPlexGetSupportSize(dm, point, &supportSize);CHKERRQ(ierr);
966         if (supportSize == 1) {
967           interior = PETSC_FALSE;
968         } else {
969           for (p = 0; p < supportSize; p++) {
970             PetscBool found;
971             /* FIXME: can I do this while iterating over cht? */
972             PetscHSetIHas(cht, support[p], &found);
973             if (!found) {
974               interior = PETSC_FALSE;
975               break;
976             }
977           }
978         }
979         if (interior) {
980           intFacetsToPatchCell[2*(ifoff + ifn)] = support[0];
981           intFacetsToPatchCell[2*(ifoff + ifn) + 1] = support[1];
982           intFacetsArray[ifoff + ifn++] = point;
983         } else {
984           extFacetsArray[efoff + efn++] = point;
985         }
986       }
987       ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, -1, patch->combined, point, &pdof, NULL);CHKERRQ(ierr);
988       if (pdof)                            {pointsArray[off + n++] = point;}
989       if (point >= cStart && point < cEnd) {cellsArray[coff + cn++] = point;}
990       PetscHashIterNext(cht, hi);
991     }
992     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);
993     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);
994     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);
995     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);
996 
997     for (ifn = 0; ifn < ifdof; ifn++) {
998       PetscInt cell0 = intFacetsToPatchCell[2*(ifoff + ifn)];
999       PetscInt cell1 = intFacetsToPatchCell[2*(ifoff + ifn) + 1];
1000       PetscBool found0 = PETSC_FALSE, found1 = PETSC_FALSE;
1001       for (n = 0; n < cdof; n++) {
1002         if (!found0 && cell0 == cellsArray[coff + n]) {
1003           intFacetsToPatchCell[2*(ifoff + ifn)] = n;
1004           found0 = PETSC_TRUE;
1005         }
1006         if (!found1 && cell1 == cellsArray[coff + n]) {
1007           intFacetsToPatchCell[2*(ifoff + ifn) + 1] = n;
1008           found1 = PETSC_TRUE;
1009         }
1010         if (found0 && found1) break;
1011       }
1012       if (!(found0 && found1)) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Didn't manage to find local point numbers for facet support");
1013     }
1014   }
1015   ierr = PetscHSetIDestroy(&ht);CHKERRQ(ierr);
1016   ierr = PetscHSetIDestroy(&cht);CHKERRQ(ierr);
1017   ierr = DMDestroy(&plex);CHKERRQ(ierr);
1018 
1019   ierr = ISCreateGeneral(PETSC_COMM_SELF, numCells,  cellsArray,  PETSC_OWN_POINTER, &patch->cells);CHKERRQ(ierr);
1020   ierr = PetscObjectSetName((PetscObject) patch->cells,  "Patch Cells");CHKERRQ(ierr);
1021   if (patch->viewCells) {
1022     ierr = ObjectView((PetscObject) patch->cellCounts, patch->viewerCells, patch->formatCells);CHKERRQ(ierr);
1023     ierr = ObjectView((PetscObject) patch->cells,      patch->viewerCells, patch->formatCells);CHKERRQ(ierr);
1024   }
1025   ierr = ISCreateGeneral(PETSC_COMM_SELF, numIntFacets,  intFacetsArray,  PETSC_OWN_POINTER, &patch->intFacets);CHKERRQ(ierr);
1026   ierr = PetscObjectSetName((PetscObject) patch->intFacets,  "Patch Interior Facets");CHKERRQ(ierr);
1027   ierr = ISCreateGeneral(PETSC_COMM_SELF, 2*numIntFacets, intFacetsToPatchCell, PETSC_OWN_POINTER, &patch->intFacetsToPatchCell);CHKERRQ(ierr);
1028   ierr = PetscObjectSetName((PetscObject) patch->intFacetsToPatchCell,  "Patch Interior Facets local support");CHKERRQ(ierr);
1029   if (patch->viewIntFacets) {
1030     ierr = ObjectView((PetscObject) patch->intFacetCounts,       patch->viewerIntFacets, patch->formatIntFacets);CHKERRQ(ierr);
1031     ierr = ObjectView((PetscObject) patch->intFacets,            patch->viewerIntFacets, patch->formatIntFacets);CHKERRQ(ierr);
1032     ierr = ObjectView((PetscObject) patch->intFacetsToPatchCell, patch->viewerIntFacets, patch->formatIntFacets);CHKERRQ(ierr);
1033   }
1034   ierr = ISCreateGeneral(PETSC_COMM_SELF, numExtFacets,  extFacetsArray,  PETSC_OWN_POINTER, &patch->extFacets);CHKERRQ(ierr);
1035   ierr = PetscObjectSetName((PetscObject) patch->extFacets,  "Patch Exterior Facets");CHKERRQ(ierr);
1036   if (patch->viewExtFacets) {
1037     ierr = ObjectView((PetscObject) patch->extFacetCounts, patch->viewerExtFacets, patch->formatExtFacets);CHKERRQ(ierr);
1038     ierr = ObjectView((PetscObject) patch->extFacets,      patch->viewerExtFacets, patch->formatExtFacets);CHKERRQ(ierr);
1039   }
1040   ierr = ISCreateGeneral(PETSC_COMM_SELF, numPoints, pointsArray, PETSC_OWN_POINTER, &patch->points);CHKERRQ(ierr);
1041   ierr = PetscObjectSetName((PetscObject) patch->points, "Patch Points");CHKERRQ(ierr);
1042   if (patch->viewPoints) {
1043     ierr = ObjectView((PetscObject) patch->pointCounts, patch->viewerPoints, patch->formatPoints);CHKERRQ(ierr);
1044     ierr = ObjectView((PetscObject) patch->points,      patch->viewerPoints, patch->formatPoints);CHKERRQ(ierr);
1045   }
1046   PetscFunctionReturn(0);
1047 }
1048 
1049 /*
1050  * PCPatchCreateCellPatchDiscretisationInfo - Build the dof maps for cell patches
1051  *
1052  * Input Parameters:
1053  * + dm - The DMPlex object defining the mesh
1054  * . cellCounts - Section with counts of cells around each vertex
1055  * . cells - IS of the cell point indices of cells in each patch
1056  * . cellNumbering - Section mapping plex cell points to Firedrake cell indices.
1057  * . nodesPerCell - number of nodes per cell.
1058  * - cellNodeMap - map from cells to node indices (nodesPerCell * numCells)
1059  *
1060  * Output Parameters:
1061  * + dofs - IS of local dof numbers of each cell in the patch, where local is a patch local numbering
1062  * . gtolCounts - Section with counts of dofs per cell patch
1063  * - gtol - IS mapping from global dofs to local dofs for each patch.
1064  */
1065 static PetscErrorCode PCPatchCreateCellPatchDiscretisationInfo(PC pc)
1066 {
1067   PC_PATCH       *patch           = (PC_PATCH *) pc->data;
1068   PetscSection    cellCounts      = patch->cellCounts;
1069   PetscSection    pointCounts     = patch->pointCounts;
1070   PetscSection    gtolCounts, gtolCountsWithArtificial = NULL, gtolCountsWithAll = NULL;
1071   IS              cells           = patch->cells;
1072   IS              points          = patch->points;
1073   PetscSection    cellNumbering   = patch->cellNumbering;
1074   PetscInt        Nf              = patch->nsubspaces;
1075   PetscInt        numCells, numPoints;
1076   PetscInt        numDofs;
1077   PetscInt        numGlobalDofs, numGlobalDofsWithArtificial, numGlobalDofsWithAll;
1078   PetscInt        totalDofsPerCell = patch->totalDofsPerCell;
1079   PetscInt        vStart, vEnd, v;
1080   const PetscInt *cellsArray, *pointsArray;
1081   PetscInt       *newCellsArray   = NULL;
1082   PetscInt       *dofsArray       = NULL;
1083   PetscInt       *dofsArrayWithArtificial = NULL;
1084   PetscInt       *dofsArrayWithAll = NULL;
1085   PetscInt       *offsArray       = NULL;
1086   PetscInt       *offsArrayWithArtificial = NULL;
1087   PetscInt       *offsArrayWithAll = NULL;
1088   PetscInt       *asmArray        = NULL;
1089   PetscInt       *asmArrayWithArtificial = NULL;
1090   PetscInt       *asmArrayWithAll = NULL;
1091   PetscInt       *globalDofsArray = NULL;
1092   PetscInt       *globalDofsArrayWithArtificial = NULL;
1093   PetscInt       *globalDofsArrayWithAll = NULL;
1094   PetscInt        globalIndex     = 0;
1095   PetscInt        key             = 0;
1096   PetscInt        asmKey          = 0;
1097   DM              dm              = NULL;
1098   const PetscInt *bcNodes         = NULL;
1099   PetscHMapI      ht;
1100   PetscHMapI      htWithArtificial;
1101   PetscHMapI      htWithAll;
1102   PetscHSetI      globalBcs;
1103   PetscInt        numBcs;
1104   PetscHSetI      ownedpts, seenpts, owneddofs, seendofs, artificialbcs;
1105   PetscInt        pStart, pEnd, p, i;
1106   char            option[PETSC_MAX_PATH_LEN];
1107   PetscBool       isNonlinear;
1108   PetscErrorCode  ierr;
1109 
1110   PetscFunctionBegin;
1111 
1112   ierr = PCGetDM(pc, &dm); CHKERRQ(ierr);
1113   /* dofcounts section is cellcounts section * dofPerCell */
1114   ierr = PetscSectionGetStorageSize(cellCounts, &numCells);CHKERRQ(ierr);
1115   ierr = PetscSectionGetStorageSize(patch->pointCounts, &numPoints);CHKERRQ(ierr);
1116   numDofs = numCells * totalDofsPerCell;
1117   ierr = PetscMalloc1(numDofs, &dofsArray);CHKERRQ(ierr);
1118   ierr = PetscMalloc1(numPoints*Nf, &offsArray);CHKERRQ(ierr);
1119   ierr = PetscMalloc1(numDofs, &asmArray);CHKERRQ(ierr);
1120   ierr = PetscMalloc1(numCells, &newCellsArray);CHKERRQ(ierr);
1121   ierr = PetscSectionGetChart(cellCounts, &vStart, &vEnd);CHKERRQ(ierr);
1122   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->gtolCounts);CHKERRQ(ierr);
1123   gtolCounts = patch->gtolCounts;
1124   ierr = PetscSectionSetChart(gtolCounts, vStart, vEnd);CHKERRQ(ierr);
1125   ierr = PetscObjectSetName((PetscObject) patch->gtolCounts, "Patch Global Index Section");CHKERRQ(ierr);
1126 
1127   if(patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE)
1128   {
1129     ierr = PetscMalloc1(numPoints*Nf, &offsArrayWithArtificial);CHKERRQ(ierr);
1130     ierr = PetscMalloc1(numDofs, &asmArrayWithArtificial);CHKERRQ(ierr);
1131     ierr = PetscMalloc1(numDofs, &dofsArrayWithArtificial);CHKERRQ(ierr);
1132     ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->gtolCountsWithArtificial);CHKERRQ(ierr);
1133     gtolCountsWithArtificial = patch->gtolCountsWithArtificial;
1134     ierr = PetscSectionSetChart(gtolCountsWithArtificial, vStart, vEnd);CHKERRQ(ierr);
1135     ierr = PetscObjectSetName((PetscObject) patch->gtolCountsWithArtificial, "Patch Global Index Section Including Artificial BCs");CHKERRQ(ierr);
1136   }
1137 
1138   isNonlinear = patch->isNonlinear;
1139   if(isNonlinear)
1140   {
1141     ierr = PetscMalloc1(numPoints*Nf, &offsArrayWithAll);CHKERRQ(ierr);
1142     ierr = PetscMalloc1(numDofs, &asmArrayWithAll);CHKERRQ(ierr);
1143     ierr = PetscMalloc1(numDofs, &dofsArrayWithAll);CHKERRQ(ierr);
1144     ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->gtolCountsWithAll);CHKERRQ(ierr);
1145     gtolCountsWithAll = patch->gtolCountsWithAll;
1146     ierr = PetscSectionSetChart(gtolCountsWithAll, vStart, vEnd);CHKERRQ(ierr);
1147     ierr = PetscObjectSetName((PetscObject) patch->gtolCountsWithAll, "Patch Global Index Section Including All BCs");CHKERRQ(ierr);
1148   }
1149 
1150   /* Outside the patch loop, get the dofs that are globally-enforced Dirichlet
1151    conditions */
1152   ierr = PetscHSetICreate(&globalBcs);CHKERRQ(ierr);
1153   ierr = ISGetIndices(patch->ghostBcNodes, &bcNodes); CHKERRQ(ierr);
1154   ierr = ISGetSize(patch->ghostBcNodes, &numBcs); CHKERRQ(ierr);
1155   for (i = 0; i < numBcs; ++i) {
1156     ierr = PetscHSetIAdd(globalBcs, bcNodes[i]);CHKERRQ(ierr); /* these are already in concatenated numbering */
1157   }
1158   ierr = ISRestoreIndices(patch->ghostBcNodes, &bcNodes); CHKERRQ(ierr);
1159   ierr = ISDestroy(&patch->ghostBcNodes); CHKERRQ(ierr); /* memory optimisation */
1160 
1161   /* Hash tables for artificial BC construction */
1162   ierr = PetscHSetICreate(&ownedpts);CHKERRQ(ierr);
1163   ierr = PetscHSetICreate(&seenpts);CHKERRQ(ierr);
1164   ierr = PetscHSetICreate(&owneddofs);CHKERRQ(ierr);
1165   ierr = PetscHSetICreate(&seendofs);CHKERRQ(ierr);
1166   ierr = PetscHSetICreate(&artificialbcs);CHKERRQ(ierr);
1167 
1168   ierr = ISGetIndices(cells, &cellsArray);CHKERRQ(ierr);
1169   ierr = ISGetIndices(points, &pointsArray);CHKERRQ(ierr);
1170   ierr = PetscHMapICreate(&ht);CHKERRQ(ierr);
1171   ierr = PetscHMapICreate(&htWithArtificial);CHKERRQ(ierr);
1172   ierr = PetscHMapICreate(&htWithAll);CHKERRQ(ierr);
1173   for (v = vStart; v < vEnd; ++v) {
1174     PetscInt localIndex = 0;
1175     PetscInt localIndexWithArtificial = 0;
1176     PetscInt localIndexWithAll = 0;
1177     PetscInt dof, off, i, j, k, l;
1178 
1179     ierr = PetscHMapIClear(ht);CHKERRQ(ierr);
1180     ierr = PetscHMapIClear(htWithArtificial);CHKERRQ(ierr);
1181     ierr = PetscHMapIClear(htWithAll);CHKERRQ(ierr);
1182     ierr = PetscSectionGetDof(cellCounts, v, &dof);CHKERRQ(ierr);
1183     ierr = PetscSectionGetOffset(cellCounts, v, &off);CHKERRQ(ierr);
1184     if (dof <= 0) continue;
1185 
1186     /* Calculate the global numbers of the artificial BC dofs here first */
1187     ierr = patch->patchconstructop((void*)patch, dm, v, ownedpts); CHKERRQ(ierr);
1188     ierr = PCPatchCompleteCellPatch(pc, ownedpts, seenpts); CHKERRQ(ierr);
1189     ierr = PCPatchGetPointDofs(pc, ownedpts, owneddofs, v, &patch->subspaces_to_exclude); CHKERRQ(ierr);
1190     ierr = PCPatchGetPointDofs(pc, seenpts, seendofs, v, NULL); CHKERRQ(ierr);
1191     ierr = PCPatchComputeSetDifference_Private(owneddofs, seendofs, artificialbcs); CHKERRQ(ierr);
1192     if (patch->viewPatches) {
1193       PetscHSetI globalbcdofs;
1194       PetscHashIter hi;
1195       MPI_Comm comm = PetscObjectComm((PetscObject)pc);
1196 
1197       ierr = PetscHSetICreate(&globalbcdofs);CHKERRQ(ierr);
1198       ierr = PetscSynchronizedPrintf(comm, "Patch %d: owned dofs:\n", v); CHKERRQ(ierr);
1199       PetscHashIterBegin(owneddofs, hi);
1200       while (!PetscHashIterAtEnd(owneddofs, hi)) {
1201         PetscInt globalDof;
1202 
1203         PetscHashIterGetKey(owneddofs, hi, globalDof);
1204         PetscHashIterNext(owneddofs, hi);
1205         ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof); CHKERRQ(ierr);
1206       }
1207       ierr = PetscSynchronizedPrintf(comm, "\n"); CHKERRQ(ierr);
1208       ierr = PetscSynchronizedPrintf(comm, "Patch %d: seen dofs:\n", v); CHKERRQ(ierr);
1209       PetscHashIterBegin(seendofs, hi);
1210       while (!PetscHashIterAtEnd(seendofs, hi)) {
1211         PetscInt globalDof;
1212         PetscBool flg;
1213 
1214         PetscHashIterGetKey(seendofs, hi, globalDof);
1215         PetscHashIterNext(seendofs, hi);
1216         ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof); CHKERRQ(ierr);
1217 
1218         ierr = PetscHSetIHas(globalBcs, globalDof, &flg);CHKERRQ(ierr);
1219         if (flg) {ierr = PetscHSetIAdd(globalbcdofs, globalDof);CHKERRQ(ierr);}
1220       }
1221       ierr = PetscSynchronizedPrintf(comm, "\n"); CHKERRQ(ierr);
1222       ierr = PetscSynchronizedPrintf(comm, "Patch %d: global BCs:\n", v); CHKERRQ(ierr);
1223       ierr = PetscHSetIGetSize(globalbcdofs, &numBcs);CHKERRQ(ierr);
1224       if (numBcs > 0) {
1225         PetscHashIterBegin(globalbcdofs, hi);
1226         while (!PetscHashIterAtEnd(globalbcdofs, hi)) {
1227           PetscInt globalDof;
1228           PetscHashIterGetKey(globalbcdofs, hi, globalDof);
1229           PetscHashIterNext(globalbcdofs, hi);
1230           ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof);CHKERRQ(ierr);
1231         }
1232       }
1233       ierr = PetscSynchronizedPrintf(comm, "\n");CHKERRQ(ierr);
1234       ierr = PetscSynchronizedPrintf(comm, "Patch %d: artificial BCs:\n", v);CHKERRQ(ierr);
1235       ierr = PetscHSetIGetSize(artificialbcs, &numBcs);CHKERRQ(ierr);
1236       if (numBcs > 0) {
1237         PetscHashIterBegin(artificialbcs, hi);
1238         while (!PetscHashIterAtEnd(artificialbcs, hi)) {
1239           PetscInt globalDof;
1240           PetscHashIterGetKey(artificialbcs, hi, globalDof);
1241           PetscHashIterNext(artificialbcs, hi);
1242           ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof); CHKERRQ(ierr);
1243         }
1244       }
1245       ierr = PetscSynchronizedPrintf(comm, "\n\n"); CHKERRQ(ierr);
1246       ierr = PetscHSetIDestroy(&globalbcdofs);CHKERRQ(ierr);
1247     }
1248    for (k = 0; k < patch->nsubspaces; ++k) {
1249       const PetscInt *cellNodeMap    = patch->cellNodeMap[k];
1250       PetscInt        nodesPerCell   = patch->nodesPerCell[k];
1251       PetscInt        subspaceOffset = patch->subspaceOffsets[k];
1252       PetscInt        bs             = patch->bs[k];
1253 
1254       for (i = off; i < off + dof; ++i) {
1255         /* Walk over the cells in this patch. */
1256         const PetscInt c    = cellsArray[i];
1257         PetscInt       cell = c;
1258 
1259         /* TODO Change this to an IS */
1260         if (cellNumbering) {
1261           ierr = PetscSectionGetDof(cellNumbering, c, &cell);CHKERRQ(ierr);
1262           if (cell <= 0) SETERRQ1(PetscObjectComm((PetscObject) pc), PETSC_ERR_ARG_OUTOFRANGE, "Cell %D doesn't appear in cell numbering map", c);
1263           ierr = PetscSectionGetOffset(cellNumbering, c, &cell);CHKERRQ(ierr);
1264         }
1265         newCellsArray[i] = cell;
1266         for (j = 0; j < nodesPerCell; ++j) {
1267           /* For each global dof, map it into contiguous local storage. */
1268           const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + subspaceOffset;
1269           /* finally, loop over block size */
1270           for (l = 0; l < bs; ++l) {
1271             PetscInt  localDof;
1272             PetscBool isGlobalBcDof, isArtificialBcDof;
1273 
1274             /* first, check if this is either a globally enforced or locally enforced BC dof */
1275             ierr = PetscHSetIHas(globalBcs, globalDof + l, &isGlobalBcDof);CHKERRQ(ierr);
1276             ierr = PetscHSetIHas(artificialbcs, globalDof + l, &isArtificialBcDof);CHKERRQ(ierr);
1277 
1278             /* if it's either, don't ever give it a local dof number */
1279             if (isGlobalBcDof || isArtificialBcDof) {
1280               dofsArray[globalIndex] = -1; /* don't use this in assembly in this patch */
1281             } else {
1282               ierr = PetscHMapIGet(ht, globalDof + l, &localDof);CHKERRQ(ierr);
1283               if (localDof == -1) {
1284                 localDof = localIndex++;
1285                 ierr = PetscHMapISet(ht, globalDof + l, localDof);CHKERRQ(ierr);
1286               }
1287               if ( globalIndex >= numDofs ) SETERRQ2(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "Found more dofs %D than expected %D", globalIndex+1, numDofs);
1288               /* And store. */
1289               dofsArray[globalIndex] = localDof;
1290             }
1291 
1292             if(patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1293               if (isGlobalBcDof) {
1294                 dofsArrayWithArtificial[globalIndex] = -1; /* don't use this in assembly in this patch */
1295               } else {
1296                 ierr = PetscHMapIGet(htWithArtificial, globalDof + l, &localDof);CHKERRQ(ierr);
1297                 if (localDof == -1) {
1298                   localDof = localIndexWithArtificial++;
1299                   ierr = PetscHMapISet(htWithArtificial, globalDof + l, localDof);CHKERRQ(ierr);
1300                 }
1301                 if ( globalIndex >= numDofs ) SETERRQ2(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "Found more dofs %D than expected %D", globalIndex+1, numDofs);
1302                 /* And store.*/
1303                 dofsArrayWithArtificial[globalIndex] = localDof;
1304               }
1305             }
1306 
1307             if(isNonlinear) {
1308               /* Build the dofmap for the function space with _all_ dofs,
1309                  including those in any kind of boundary condition */
1310               ierr = PetscHMapIGet(htWithAll, globalDof + l, &localDof);CHKERRQ(ierr);
1311               if (localDof == -1) {
1312                 localDof = localIndexWithAll++;
1313                 ierr = PetscHMapISet(htWithAll, globalDof + l, localDof);CHKERRQ(ierr);
1314               }
1315               if ( globalIndex >= numDofs ) SETERRQ2(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "Found more dofs %D than expected %D", globalIndex+1, numDofs);
1316               /* And store.*/
1317               dofsArrayWithAll[globalIndex] = localDof;
1318             }
1319             globalIndex++;
1320           }
1321         }
1322       }
1323     }
1324      /*How many local dofs in this patch? */
1325    if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1326      ierr = PetscHMapIGetSize(htWithArtificial, &dof);CHKERRQ(ierr);
1327      ierr = PetscSectionSetDof(gtolCountsWithArtificial, v, dof);CHKERRQ(ierr);
1328    }
1329    if (isNonlinear) {
1330      ierr = PetscHMapIGetSize(htWithAll, &dof);CHKERRQ(ierr);
1331      ierr = PetscSectionSetDof(gtolCountsWithAll, v, dof);CHKERRQ(ierr);
1332    }
1333     ierr = PetscHMapIGetSize(ht, &dof);CHKERRQ(ierr);
1334     ierr = PetscSectionSetDof(gtolCounts, v, dof);CHKERRQ(ierr);
1335   }
1336   if (globalIndex != numDofs) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Expected number of dofs (%d) doesn't match found number (%d)", numDofs, globalIndex);
1337   ierr = PetscSectionSetUp(gtolCounts);CHKERRQ(ierr);
1338   ierr = PetscSectionGetStorageSize(gtolCounts, &numGlobalDofs);CHKERRQ(ierr);
1339   ierr = PetscMalloc1(numGlobalDofs, &globalDofsArray);CHKERRQ(ierr);
1340 
1341   if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1342     ierr = PetscSectionSetUp(gtolCountsWithArtificial);CHKERRQ(ierr);
1343     ierr = PetscSectionGetStorageSize(gtolCountsWithArtificial, &numGlobalDofsWithArtificial);CHKERRQ(ierr);
1344     ierr = PetscMalloc1(numGlobalDofsWithArtificial, &globalDofsArrayWithArtificial);CHKERRQ(ierr);
1345   }
1346   if (isNonlinear) {
1347     ierr = PetscSectionSetUp(gtolCountsWithAll);CHKERRQ(ierr);
1348     ierr = PetscSectionGetStorageSize(gtolCountsWithAll, &numGlobalDofsWithAll);CHKERRQ(ierr);
1349     ierr = PetscMalloc1(numGlobalDofsWithAll, &globalDofsArrayWithAll);CHKERRQ(ierr);
1350   }
1351   /* Now populate the global to local map.  This could be merged into the above loop if we were willing to deal with reallocs. */
1352   for (v = vStart; v < vEnd; ++v) {
1353     PetscHashIter hi;
1354     PetscInt      dof, off, Np, ooff, i, j, k, l;
1355 
1356     ierr = PetscHMapIClear(ht);CHKERRQ(ierr);
1357     ierr = PetscHMapIClear(htWithArtificial);CHKERRQ(ierr);
1358     ierr = PetscHMapIClear(htWithAll);CHKERRQ(ierr);
1359     ierr = PetscSectionGetDof(cellCounts, v, &dof);CHKERRQ(ierr);
1360     ierr = PetscSectionGetOffset(cellCounts, v, &off);CHKERRQ(ierr);
1361     ierr = PetscSectionGetDof(pointCounts, v, &Np);CHKERRQ(ierr);
1362     ierr = PetscSectionGetOffset(pointCounts, v, &ooff);CHKERRQ(ierr);
1363     if (dof <= 0) continue;
1364 
1365     for (k = 0; k < patch->nsubspaces; ++k) {
1366       const PetscInt *cellNodeMap    = patch->cellNodeMap[k];
1367       PetscInt        nodesPerCell   = patch->nodesPerCell[k];
1368       PetscInt        subspaceOffset = patch->subspaceOffsets[k];
1369       PetscInt        bs             = patch->bs[k];
1370       PetscInt        goff;
1371 
1372       for (i = off; i < off + dof; ++i) {
1373         /* Reconstruct mapping of global-to-local on this patch. */
1374         const PetscInt c    = cellsArray[i];
1375         PetscInt       cell = c;
1376 
1377         if (cellNumbering) {ierr = PetscSectionGetOffset(cellNumbering, c, &cell);CHKERRQ(ierr);}
1378         for (j = 0; j < nodesPerCell; ++j) {
1379           for (l = 0; l < bs; ++l) {
1380             const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + l + subspaceOffset;
1381             const PetscInt localDof  = dofsArray[key];
1382             if (localDof >= 0) {ierr = PetscHMapISet(ht, globalDof, localDof);CHKERRQ(ierr);}
1383             if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1384               const PetscInt localDofWithArtificial = dofsArrayWithArtificial[key];
1385               if (localDofWithArtificial >= 0) {
1386                 ierr = PetscHMapISet(htWithArtificial, globalDof, localDofWithArtificial);CHKERRQ(ierr);
1387               }
1388             }
1389             if (isNonlinear) {
1390               const PetscInt localDofWithAll = dofsArrayWithAll[key];
1391               if (localDofWithAll >= 0) {
1392                 ierr = PetscHMapISet(htWithAll, globalDof, localDofWithAll);CHKERRQ(ierr);
1393               }
1394             }
1395             key++;
1396           }
1397         }
1398       }
1399 
1400       /* Shove it in the output data structure. */
1401       ierr = PetscSectionGetOffset(gtolCounts, v, &goff);CHKERRQ(ierr);
1402       PetscHashIterBegin(ht, hi);
1403       while (!PetscHashIterAtEnd(ht, hi)) {
1404         PetscInt globalDof, localDof;
1405 
1406         PetscHashIterGetKey(ht, hi, globalDof);
1407         PetscHashIterGetVal(ht, hi, localDof);
1408         if (globalDof >= 0) globalDofsArray[goff + localDof] = globalDof;
1409         PetscHashIterNext(ht, hi);
1410       }
1411 
1412       if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1413         ierr = PetscSectionGetOffset(gtolCountsWithArtificial, v, &goff);CHKERRQ(ierr);
1414         PetscHashIterBegin(htWithArtificial, hi);
1415         while (!PetscHashIterAtEnd(htWithArtificial, hi)) {
1416           PetscInt globalDof, localDof;
1417           PetscHashIterGetKey(htWithArtificial, hi, globalDof);
1418           PetscHashIterGetVal(htWithArtificial, hi, localDof);
1419           if (globalDof >= 0) globalDofsArrayWithArtificial[goff + localDof] = globalDof;
1420           PetscHashIterNext(htWithArtificial, hi);
1421         }
1422       }
1423       if (isNonlinear) {
1424         ierr = PetscSectionGetOffset(gtolCountsWithAll, v, &goff);CHKERRQ(ierr);
1425         PetscHashIterBegin(htWithAll, hi);
1426         while (!PetscHashIterAtEnd(htWithAll, hi)) {
1427           PetscInt globalDof, localDof;
1428           PetscHashIterGetKey(htWithAll, hi, globalDof);
1429           PetscHashIterGetVal(htWithAll, hi, localDof);
1430           if (globalDof >= 0) globalDofsArrayWithAll[goff + localDof] = globalDof;
1431           PetscHashIterNext(htWithAll, hi);
1432         }
1433       }
1434 
1435       for (p = 0; p < Np; ++p) {
1436         const PetscInt point = pointsArray[ooff + p];
1437         PetscInt       globalDof, localDof;
1438 
1439         ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, k, patch->combined, point, NULL, &globalDof);CHKERRQ(ierr);
1440         ierr = PetscHMapIGet(ht, globalDof, &localDof);CHKERRQ(ierr);
1441         offsArray[(ooff + p)*Nf + k] = localDof;
1442         if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1443           ierr = PetscHMapIGet(htWithArtificial, globalDof, &localDof);CHKERRQ(ierr);
1444           offsArrayWithArtificial[(ooff + p)*Nf + k] = localDof;
1445         }
1446         if (isNonlinear) {
1447           ierr = PetscHMapIGet(htWithAll, globalDof, &localDof);CHKERRQ(ierr);
1448           offsArrayWithAll[(ooff + p)*Nf + k] = localDof;
1449         }
1450       }
1451     }
1452 
1453     ierr = PetscHSetIDestroy(&globalBcs);CHKERRQ(ierr);
1454     ierr = PetscHSetIDestroy(&ownedpts);CHKERRQ(ierr);
1455     ierr = PetscHSetIDestroy(&seenpts);CHKERRQ(ierr);
1456     ierr = PetscHSetIDestroy(&owneddofs);CHKERRQ(ierr);
1457     ierr = PetscHSetIDestroy(&seendofs);CHKERRQ(ierr);
1458     ierr = PetscHSetIDestroy(&artificialbcs);CHKERRQ(ierr);
1459 
1460       /* At this point, we have a hash table ht built that maps globalDof -> localDof.
1461      We need to create the dof table laid out cellwise first, then by subspace,
1462      as the assembler assembles cell-wise and we need to stuff the different
1463      contributions of the different function spaces to the right places. So we loop
1464      over cells, then over subspaces. */
1465     if (patch->nsubspaces > 1) { /* for nsubspaces = 1, data we need is already in dofsArray */
1466       for (i = off; i < off + dof; ++i) {
1467         const PetscInt c    = cellsArray[i];
1468         PetscInt       cell = c;
1469 
1470         if (cellNumbering) {ierr = PetscSectionGetOffset(cellNumbering, c, &cell);CHKERRQ(ierr);}
1471         for (k = 0; k < patch->nsubspaces; ++k) {
1472           const PetscInt *cellNodeMap    = patch->cellNodeMap[k];
1473           PetscInt        nodesPerCell   = patch->nodesPerCell[k];
1474           PetscInt        subspaceOffset = patch->subspaceOffsets[k];
1475           PetscInt        bs             = patch->bs[k];
1476 
1477           for (j = 0; j < nodesPerCell; ++j) {
1478             for (l = 0; l < bs; ++l) {
1479               const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + l + subspaceOffset;
1480               PetscInt       localDof;
1481 
1482               ierr = PetscHMapIGet(ht, globalDof, &localDof);CHKERRQ(ierr);
1483               /* If it's not in the hash table, i.e. is a BC dof,
1484                then the PetscHSetIMap above gives -1, which matches
1485                exactly the convention for PETSc's matrix assembly to
1486                ignore the dof. So we don't need to do anything here */
1487               asmArray[asmKey] = localDof;
1488               if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1489                 ierr = PetscHMapIGet(htWithArtificial, globalDof, &localDof);CHKERRQ(ierr);
1490                 asmArrayWithArtificial[asmKey] = localDof;
1491               }
1492               if (isNonlinear) {
1493                 ierr = PetscHMapIGet(htWithAll, globalDof, &localDof);CHKERRQ(ierr);
1494                 asmArrayWithAll[asmKey] = localDof;
1495               }
1496               asmKey++;
1497             }
1498           }
1499         }
1500       }
1501     }
1502   }
1503   if (1 == patch->nsubspaces) {
1504     ierr = PetscMemcpy(asmArray, dofsArray, numDofs * sizeof(PetscInt));CHKERRQ(ierr);
1505     if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1506       ierr = PetscMemcpy(asmArrayWithArtificial, dofsArrayWithArtificial, numDofs * sizeof(PetscInt));CHKERRQ(ierr);
1507     }
1508     if (isNonlinear) {
1509       ierr = PetscMemcpy(asmArrayWithAll, dofsArrayWithAll, numDofs * sizeof(PetscInt));CHKERRQ(ierr);
1510     }
1511   }
1512 
1513   ierr = PetscHMapIDestroy(&ht);CHKERRQ(ierr);
1514   ierr = PetscHMapIDestroy(&htWithArtificial);CHKERRQ(ierr);
1515   ierr = PetscHMapIDestroy(&htWithAll);CHKERRQ(ierr);
1516   ierr = ISRestoreIndices(cells, &cellsArray);CHKERRQ(ierr);
1517   ierr = ISRestoreIndices(points, &pointsArray);CHKERRQ(ierr);
1518   ierr = PetscFree(dofsArray);CHKERRQ(ierr);
1519   if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1520     ierr = PetscFree(dofsArrayWithArtificial);CHKERRQ(ierr);
1521   }
1522   if (isNonlinear) {
1523     ierr = PetscFree(dofsArrayWithAll);CHKERRQ(ierr);
1524   }
1525   /* Create placeholder section for map from points to patch dofs */
1526   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->patchSection);CHKERRQ(ierr);
1527   ierr = PetscSectionSetNumFields(patch->patchSection, patch->nsubspaces);CHKERRQ(ierr);
1528   if (patch->combined) {
1529     PetscInt numFields;
1530     ierr = PetscSectionGetNumFields(patch->dofSection[0], &numFields);CHKERRQ(ierr);
1531     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);
1532     ierr = PetscSectionGetChart(patch->dofSection[0], &pStart, &pEnd);CHKERRQ(ierr);
1533     ierr = PetscSectionSetChart(patch->patchSection, pStart, pEnd);CHKERRQ(ierr);
1534     for (p = pStart; p < pEnd; ++p) {
1535       PetscInt dof, fdof, f;
1536 
1537       ierr = PetscSectionGetDof(patch->dofSection[0], p, &dof);CHKERRQ(ierr);
1538       ierr = PetscSectionSetDof(patch->patchSection, p, dof);CHKERRQ(ierr);
1539       for (f = 0; f < patch->nsubspaces; ++f) {
1540         ierr = PetscSectionGetFieldDof(patch->dofSection[0], p, f, &fdof);CHKERRQ(ierr);
1541         ierr = PetscSectionSetFieldDof(patch->patchSection, p, f, fdof);CHKERRQ(ierr);
1542       }
1543     }
1544   } else {
1545     PetscInt pStartf, pEndf, f;
1546     pStart = PETSC_MAX_INT;
1547     pEnd = PETSC_MIN_INT;
1548     for (f = 0; f < patch->nsubspaces; ++f) {
1549       ierr = PetscSectionGetChart(patch->dofSection[f], &pStartf, &pEndf);CHKERRQ(ierr);
1550       pStart = PetscMin(pStart, pStartf);
1551       pEnd = PetscMax(pEnd, pEndf);
1552     }
1553     ierr = PetscSectionSetChart(patch->patchSection, pStart, pEnd);CHKERRQ(ierr);
1554     for (f = 0; f < patch->nsubspaces; ++f) {
1555       ierr = PetscSectionGetChart(patch->dofSection[f], &pStartf, &pEndf);CHKERRQ(ierr);
1556       for (p = pStartf; p < pEndf; ++p) {
1557         PetscInt fdof;
1558         ierr = PetscSectionGetDof(patch->dofSection[f], p, &fdof);CHKERRQ(ierr);
1559         ierr = PetscSectionAddDof(patch->patchSection, p, fdof);CHKERRQ(ierr);
1560         ierr = PetscSectionSetFieldDof(patch->patchSection, p, f, fdof);CHKERRQ(ierr);
1561       }
1562     }
1563   }
1564   ierr = PetscSectionSetUp(patch->patchSection);CHKERRQ(ierr);
1565   ierr = PetscSectionSetUseFieldOffsets(patch->patchSection, PETSC_TRUE);CHKERRQ(ierr);
1566   /* Replace cell indices with firedrake-numbered ones. */
1567   ierr = ISGeneralSetIndices(cells, numCells, (const PetscInt *) newCellsArray, PETSC_OWN_POINTER);CHKERRQ(ierr);
1568   ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalDofs, globalDofsArray, PETSC_OWN_POINTER, &patch->gtol);CHKERRQ(ierr);
1569   ierr = PetscObjectSetName((PetscObject) patch->gtol, "Global Indices");CHKERRQ(ierr);
1570   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_g2l_view", patch->classname);CHKERRQ(ierr);
1571   ierr = PetscSectionViewFromOptions(patch->gtolCounts, (PetscObject) pc, option);CHKERRQ(ierr);
1572   ierr = ISViewFromOptions(patch->gtol, (PetscObject) pc, option);CHKERRQ(ierr);
1573   ierr = ISCreateGeneral(PETSC_COMM_SELF, numDofs, asmArray, PETSC_OWN_POINTER, &patch->dofs);CHKERRQ(ierr);
1574   ierr = ISCreateGeneral(PETSC_COMM_SELF, numPoints*Nf, offsArray, PETSC_OWN_POINTER, &patch->offs);CHKERRQ(ierr);
1575   if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
1576     ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalDofsWithArtificial, globalDofsArrayWithArtificial, PETSC_OWN_POINTER, &patch->gtolWithArtificial);CHKERRQ(ierr);
1577     ierr = ISCreateGeneral(PETSC_COMM_SELF, numDofs, asmArrayWithArtificial, PETSC_OWN_POINTER, &patch->dofsWithArtificial);CHKERRQ(ierr);
1578     ierr = ISCreateGeneral(PETSC_COMM_SELF, numPoints*Nf, offsArrayWithArtificial, PETSC_OWN_POINTER, &patch->offsWithArtificial);CHKERRQ(ierr);
1579   }
1580   if (isNonlinear) {
1581     ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalDofsWithAll, globalDofsArrayWithAll, PETSC_OWN_POINTER, &patch->gtolWithAll);CHKERRQ(ierr);
1582     ierr = ISCreateGeneral(PETSC_COMM_SELF, numDofs, asmArrayWithAll, PETSC_OWN_POINTER, &patch->dofsWithAll);CHKERRQ(ierr);
1583     ierr = ISCreateGeneral(PETSC_COMM_SELF, numPoints*Nf, offsArrayWithAll, PETSC_OWN_POINTER, &patch->offsWithAll);CHKERRQ(ierr);
1584   }
1585   PetscFunctionReturn(0);
1586 }
1587 
1588 static PetscErrorCode PCPatchZeroFillMatrix_Private(Mat mat, const PetscInt ncell, const PetscInt ndof, const PetscInt *dof)
1589 {
1590   PetscScalar    *values = NULL;
1591   PetscInt        rows, c, i;
1592   PetscErrorCode  ierr;
1593 
1594   PetscFunctionBegin;
1595   ierr = PetscCalloc1(ndof*ndof, &values);CHKERRQ(ierr);
1596   for (c = 0; c < ncell; ++c) {
1597     const PetscInt *idx = &dof[ndof*c];
1598     ierr = MatSetValues(mat, ndof, idx, ndof, idx, values, INSERT_VALUES);CHKERRQ(ierr);
1599   }
1600   ierr = MatGetLocalSize(mat, &rows, NULL);CHKERRQ(ierr);
1601   for (i = 0; i < rows; ++i) {
1602     ierr = MatSetValues(mat, 1, &i, 1, &i, values, INSERT_VALUES);CHKERRQ(ierr);
1603   }
1604   ierr = MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
1605   ierr = MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
1606   ierr = PetscFree(values);CHKERRQ(ierr);
1607   PetscFunctionReturn(0);
1608 }
1609 
1610 static PetscErrorCode PCPatchCreateMatrix_Private(PC pc, PetscInt point, Mat *mat, PetscBool withArtificial)
1611 {
1612   PC_PATCH      *patch = (PC_PATCH *) pc->data;
1613   Vec            x, y;
1614   PetscBool      flg;
1615   PetscInt       csize, rsize;
1616   const char    *prefix = NULL;
1617   PetscErrorCode ierr;
1618 
1619   PetscFunctionBegin;
1620   if(withArtificial) {
1621     /* would be nice if we could create a rectangular matrix of size numDofsWithArtificial x numDofs here */
1622     x = patch->patchRHSWithArtificial[point];
1623     y = patch->patchRHSWithArtificial[point];
1624   } else {
1625     x = patch->patchRHS[point];
1626     y = patch->patchUpdate[point];
1627   }
1628 
1629   ierr = VecGetSize(x, &csize);CHKERRQ(ierr);
1630   ierr = VecGetSize(y, &rsize);CHKERRQ(ierr);
1631   ierr = MatCreate(PETSC_COMM_SELF, mat);CHKERRQ(ierr);
1632   ierr = PCGetOptionsPrefix(pc, &prefix);CHKERRQ(ierr);
1633   ierr = MatSetOptionsPrefix(*mat, prefix);CHKERRQ(ierr);
1634   ierr = MatAppendOptionsPrefix(*mat, "pc_patch_sub_");CHKERRQ(ierr);
1635   if (patch->sub_mat_type)       {ierr = MatSetType(*mat, patch->sub_mat_type);CHKERRQ(ierr);}
1636   else if (!patch->sub_mat_type) {ierr = MatSetType(*mat, MATDENSE);CHKERRQ(ierr);}
1637   ierr = MatSetSizes(*mat, rsize, csize, rsize, csize);CHKERRQ(ierr);
1638   ierr = PetscObjectTypeCompare((PetscObject) *mat, MATDENSE, &flg);CHKERRQ(ierr);
1639   if (!flg) {ierr = PetscObjectTypeCompare((PetscObject)*mat, MATSEQDENSE, &flg);CHKERRQ(ierr);}
1640   /* Sparse patch matrices */
1641   if (!flg) {
1642     PetscBT         bt;
1643     PetscInt       *dnnz      = NULL;
1644     const PetscInt *dofsArray = NULL;
1645     PetscInt        pStart, pEnd, ncell, offset, c, i, j;
1646 
1647     if(withArtificial) {
1648       ierr = ISGetIndices(patch->dofsWithArtificial, &dofsArray);CHKERRQ(ierr);
1649     } else {
1650       ierr = ISGetIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
1651     }
1652     ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd);CHKERRQ(ierr);
1653     point += pStart;
1654     if (point >= pEnd) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Operator point %D not in [%D, %D)\n", point, pStart, pEnd);CHKERRQ(ierr);
1655     ierr = PetscSectionGetDof(patch->cellCounts, point, &ncell);CHKERRQ(ierr);
1656     ierr = PetscSectionGetOffset(patch->cellCounts, point, &offset);CHKERRQ(ierr);
1657     ierr = PetscLogEventBegin(PC_Patch_Prealloc, pc, 0, 0, 0);CHKERRQ(ierr);
1658     /* A PetscBT uses N^2 bits to store the sparsity pattern on a
1659      * patch. This is probably OK if the patches are not too big,
1660      * but uses too much memory. We therefore switch based on rsize. */
1661     if (rsize < 3000) { /* FIXME: I picked this switch value out of my hat */
1662       ierr = PetscCalloc1(rsize, &dnnz);CHKERRQ(ierr);
1663       ierr = PetscBTCreate(rsize*rsize, &bt);CHKERRQ(ierr);
1664       for (c = 0; c < ncell; ++c) {
1665         const PetscInt *idx = dofsArray + (offset + c)*patch->totalDofsPerCell;
1666         for (i = 0; i < patch->totalDofsPerCell; ++i) {
1667           const PetscInt row = idx[i];
1668           if (row < 0) continue;
1669           for (j = 0; j < patch->totalDofsPerCell; ++j) {
1670             const PetscInt col = idx[j];
1671             const PetscInt key = row*rsize + col;
1672             if (col < 0) continue;
1673             if (!PetscBTLookupSet(bt, key)) ++dnnz[row];
1674           }
1675         }
1676       }
1677       ierr = PetscBTDestroy(&bt);CHKERRQ(ierr);
1678       ierr = MatXAIJSetPreallocation(*mat, 1, dnnz, NULL, NULL, NULL);CHKERRQ(ierr);
1679       ierr = PetscFree(dnnz);CHKERRQ(ierr);
1680       ierr = PCPatchZeroFillMatrix_Private(*mat, ncell, patch->totalDofsPerCell, &dofsArray[offset*patch->totalDofsPerCell]);CHKERRQ(ierr);
1681     } else { /* rsize too big, use MATPREALLOCATOR */
1682       Mat preallocator;
1683       PetscScalar* vals;
1684 
1685       ierr = PetscCalloc1(patch->totalDofsPerCell*patch->totalDofsPerCell, &vals);CHKERRQ(ierr);
1686       ierr = MatCreate(PETSC_COMM_SELF, &preallocator);CHKERRQ(ierr);
1687       ierr = MatSetType(preallocator, MATPREALLOCATOR);CHKERRQ(ierr);
1688       ierr = MatSetSizes(preallocator, rsize, rsize, rsize, rsize);CHKERRQ(ierr);
1689       ierr = MatSetUp(preallocator);CHKERRQ(ierr);
1690       for (c = 0; c < ncell; ++c) {
1691         const PetscInt *idx = dofsArray + (offset + c)*patch->totalDofsPerCell;
1692         ierr = MatSetValues(preallocator, patch->totalDofsPerCell, idx, patch->totalDofsPerCell, idx, vals, INSERT_VALUES);CHKERRQ(ierr);
1693       }
1694       ierr = PetscFree(vals);CHKERRQ(ierr);
1695       ierr = MatAssemblyBegin(preallocator, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
1696       ierr = MatAssemblyEnd(preallocator, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
1697       ierr = MatPreallocatorPreallocate(preallocator, PETSC_TRUE, *mat);CHKERRQ(ierr);
1698       ierr = MatDestroy(&preallocator);CHKERRQ(ierr);
1699     }
1700     ierr = PetscLogEventEnd(PC_Patch_Prealloc, pc, 0, 0, 0);CHKERRQ(ierr);
1701     if(withArtificial) {
1702       ierr = ISRestoreIndices(patch->dofsWithArtificial, &dofsArray);CHKERRQ(ierr);
1703     } else {
1704       ierr = ISRestoreIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
1705     }
1706   }
1707   ierr = MatSetUp(*mat);CHKERRQ(ierr);
1708   PetscFunctionReturn(0);
1709 }
1710 
1711 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)
1712 {
1713   PC_PATCH       *patch = (PC_PATCH *) pc->data;
1714   DM              dm;
1715   PetscSection    s;
1716   const PetscInt *parray, *oarray;
1717   PetscInt        Nf = patch->nsubspaces, Np, poff, p, f;
1718   PetscErrorCode  ierr;
1719 
1720   PetscFunctionBegin;
1721   ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
1722   ierr = DMGetDefaultSection(dm, &s);CHKERRQ(ierr);
1723   /* Set offset into patch */
1724   ierr = PetscSectionGetDof(patch->pointCounts, patchNum, &Np);CHKERRQ(ierr);
1725   ierr = PetscSectionGetOffset(patch->pointCounts, patchNum, &poff);CHKERRQ(ierr);
1726   ierr = ISGetIndices(patch->points, &parray);CHKERRQ(ierr);
1727   ierr = ISGetIndices(patch->offs,   &oarray);CHKERRQ(ierr);
1728   for (f = 0; f < Nf; ++f) {
1729     for (p = 0; p < Np; ++p) {
1730       const PetscInt point = parray[poff+p];
1731       PetscInt       dof;
1732 
1733       ierr = PetscSectionGetFieldDof(patch->patchSection, point, f, &dof);CHKERRQ(ierr);
1734       ierr = PetscSectionSetFieldOffset(patch->patchSection, point, f, oarray[(poff+p)*Nf+f]);CHKERRQ(ierr);
1735       if (patch->nsubspaces == 1) {ierr = PetscSectionSetOffset(patch->patchSection, point, oarray[(poff+p)*Nf+f]);CHKERRQ(ierr);}
1736       else                        {ierr = PetscSectionSetOffset(patch->patchSection, point, -1);CHKERRQ(ierr);}
1737     }
1738   }
1739   ierr = ISRestoreIndices(patch->points, &parray);CHKERRQ(ierr);
1740   ierr = ISRestoreIndices(patch->offs,   &oarray);CHKERRQ(ierr);
1741   if (patch->viewSection) {ierr = ObjectView((PetscObject) patch->patchSection, patch->viewerSection, patch->formatSection);CHKERRQ(ierr);}
1742   ierr = DMPlexComputeResidual_Patch_Internal(pc->dm, patch->patchSection, cellIS, 0.0, x, NULL, F, ctx);CHKERRQ(ierr);
1743   PetscFunctionReturn(0);
1744 }
1745 
1746 PetscErrorCode PCPatchComputeFunction_Internal(PC pc, Vec x, Vec F, PetscInt point)
1747 {
1748   PC_PATCH       *patch = (PC_PATCH *) pc->data;
1749   const PetscInt *dofsArray;
1750   const PetscInt *dofsArrayWithAll;
1751   const PetscInt *cellsArray;
1752   PetscInt        ncell, offset, pStart, pEnd;
1753   PetscErrorCode  ierr;
1754 
1755   PetscFunctionBegin;
1756   ierr = PetscLogEventBegin(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
1757   if (!patch->usercomputeop) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call PCPatchSetComputeOperator() to set user callback\n");
1758   ierr = ISGetIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
1759   ierr = ISGetIndices(patch->dofsWithAll, &dofsArrayWithAll);CHKERRQ(ierr);
1760   ierr = ISGetIndices(patch->cells, &cellsArray);CHKERRQ(ierr);
1761   ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd);CHKERRQ(ierr);
1762 
1763   point += pStart;
1764   if (point >= pEnd) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Operator point %D not in [%D, %D)\n", point, pStart, pEnd);CHKERRQ(ierr);
1765 
1766   ierr = PetscSectionGetDof(patch->cellCounts, point, &ncell);CHKERRQ(ierr);
1767   ierr = PetscSectionGetOffset(patch->cellCounts, point, &offset);CHKERRQ(ierr);
1768   if (ncell <= 0) {
1769     ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
1770     PetscFunctionReturn(0);
1771   }
1772   PetscStackPush("PCPatch user callback");
1773   /* Cannot reuse the same IS because the geometry info is being cached in it */
1774   ierr = ISCreateGeneral(PETSC_COMM_SELF, ncell, cellsArray + offset, PETSC_USE_POINTER, &patch->cellIS);CHKERRQ(ierr);
1775   ierr = patch->usercomputef(pc, point, x, F, patch->cellIS, ncell*patch->totalDofsPerCell, dofsArray + offset*patch->totalDofsPerCell,
1776                                                                                             dofsArrayWithAll + offset*patch->totalDofsPerCell,
1777                                                                                             patch->usercomputefctx);CHKERRQ(ierr);
1778   PetscStackPop;
1779   ierr = ISDestroy(&patch->cellIS);CHKERRQ(ierr);
1780   ierr = ISRestoreIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
1781   ierr = ISRestoreIndices(patch->dofsWithAll, &dofsArrayWithAll);CHKERRQ(ierr);
1782   ierr = ISRestoreIndices(patch->cells, &cellsArray);CHKERRQ(ierr);
1783   if (patch->viewMatrix) {
1784     char name[PETSC_MAX_PATH_LEN];
1785 
1786     ierr = PetscSNPrintf(name, PETSC_MAX_PATH_LEN-1, "Patch vector for Point %D", point);CHKERRQ(ierr);
1787     ierr = PetscObjectSetName((PetscObject) F, name);CHKERRQ(ierr);
1788     ierr = ObjectView((PetscObject) F, patch->viewerMatrix, patch->formatMatrix);CHKERRQ(ierr);
1789   }
1790   ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
1791   PetscFunctionReturn(0);
1792 }
1793 
1794 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)
1795 {
1796   PC_PATCH       *patch = (PC_PATCH *) pc->data;
1797   DM              dm;
1798   PetscSection    s;
1799   const PetscInt *parray, *oarray;
1800   PetscInt        Nf = patch->nsubspaces, Np, poff, p, f;
1801   PetscErrorCode  ierr;
1802 
1803   PetscFunctionBegin;
1804   ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
1805   ierr = DMGetDefaultSection(dm, &s);CHKERRQ(ierr);
1806   /* Set offset into patch */
1807   ierr = PetscSectionGetDof(patch->pointCounts, patchNum, &Np);CHKERRQ(ierr);
1808   ierr = PetscSectionGetOffset(patch->pointCounts, patchNum, &poff);CHKERRQ(ierr);
1809   ierr = ISGetIndices(patch->points, &parray);CHKERRQ(ierr);
1810   ierr = ISGetIndices(patch->offs,   &oarray);CHKERRQ(ierr);
1811   for (f = 0; f < Nf; ++f) {
1812     for (p = 0; p < Np; ++p) {
1813       const PetscInt point = parray[poff+p];
1814       PetscInt       dof;
1815 
1816       ierr = PetscSectionGetFieldDof(patch->patchSection, point, f, &dof);CHKERRQ(ierr);
1817       ierr = PetscSectionSetFieldOffset(patch->patchSection, point, f, oarray[(poff+p)*Nf+f]);CHKERRQ(ierr);
1818       if (patch->nsubspaces == 1) {ierr = PetscSectionSetOffset(patch->patchSection, point, oarray[(poff+p)*Nf+f]);CHKERRQ(ierr);}
1819       else                        {ierr = PetscSectionSetOffset(patch->patchSection, point, -1);CHKERRQ(ierr);}
1820     }
1821   }
1822   ierr = ISRestoreIndices(patch->points, &parray);CHKERRQ(ierr);
1823   ierr = ISRestoreIndices(patch->offs,   &oarray);CHKERRQ(ierr);
1824   if (patch->viewSection) {ierr = ObjectView((PetscObject) patch->patchSection, patch->viewerSection, patch->formatSection);CHKERRQ(ierr);}
1825   /* TODO Shut off MatViewFromOptions() in MatAssemblyEnd() here */
1826   ierr = DMPlexComputeJacobian_Patch_Internal(pc->dm, patch->patchSection, patch->patchSection, cellIS, 0.0, 0.0, x, NULL, J, J, ctx);CHKERRQ(ierr);
1827   PetscFunctionReturn(0);
1828 }
1829 
1830 PetscErrorCode PCPatchComputeOperator_Internal(PC pc, Vec x, Mat mat, PetscInt point, PetscBool withArtificial)
1831 {
1832   PC_PATCH       *patch = (PC_PATCH *) pc->data;
1833   const PetscInt *dofsArray;
1834   const PetscInt *dofsArrayWithArtificial = NULL;
1835   const PetscInt *dofsArrayWithAll = NULL;
1836   const PetscInt *cellsArray;
1837   PetscInt        ncell, offset, pStart, pEnd, numIntFacets, intFacetOffset;
1838   PetscBool       isNonlinear;
1839   PetscErrorCode  ierr;
1840 
1841   PetscFunctionBegin;
1842   ierr = PetscLogEventBegin(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
1843   isNonlinear = patch->isNonlinear;
1844   if (!patch->usercomputeop) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call PCPatchSetComputeOperator() to set user callback\n");
1845   if(withArtificial) {
1846     ierr = ISGetIndices(patch->dofsWithArtificial, &dofsArray);CHKERRQ(ierr);
1847   } else {
1848     ierr = ISGetIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
1849   }
1850   if (isNonlinear) {
1851     ierr = ISGetIndices(patch->dofsWithAll, &dofsArrayWithAll);CHKERRQ(ierr);
1852   }
1853   ierr = ISGetIndices(patch->cells, &cellsArray);CHKERRQ(ierr);
1854   ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd);CHKERRQ(ierr);
1855 
1856   point += pStart;
1857   if (point >= pEnd) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Operator point %D not in [%D, %D)\n", point, pStart, pEnd);CHKERRQ(ierr);
1858 
1859   ierr = PetscSectionGetDof(patch->cellCounts, point, &ncell);CHKERRQ(ierr);
1860   ierr = PetscSectionGetOffset(patch->cellCounts, point, &offset);CHKERRQ(ierr);
1861   if (ncell <= 0) {
1862     ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
1863     PetscFunctionReturn(0);
1864   }
1865   PetscStackPush("PCPatch user callback");
1866   /* Cannot reuse the same IS because the geometry info is being cached in it */
1867   ierr = ISCreateGeneral(PETSC_COMM_SELF, ncell, cellsArray + offset, PETSC_USE_POINTER, &patch->cellIS);CHKERRQ(ierr);
1868   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);
1869 
1870   ierr = PetscSectionGetDof(patch->intFacetCounts, point, &numIntFacets);CHKERRQ(ierr);
1871   ierr = PetscSectionGetOffset(patch->intFacetCounts, point, &intFacetOffset);CHKERRQ(ierr);
1872   if (numIntFacets > 0) {
1873     /* For each interior facet, grab the two cells (in local numbering, and concatenate dof numberings for those cells) */
1874     PetscInt *facetDofs = NULL, *facetDofsWithAll = NULL;
1875     const PetscInt *intFacetsArray = NULL;
1876     PetscInt idx = 0;
1877     PetscInt i, c, d;
1878     IS       facetIS = NULL;
1879     const PetscInt *facetCells = NULL;
1880     ierr = ISGetIndices(patch->intFacetsToPatchCell, &facetCells);CHKERRQ(ierr);
1881     ierr = ISGetIndices(patch->intFacets, &intFacetsArray);CHKERRQ(ierr);
1882     /* FIXME: Pull this malloc out. */
1883     ierr = PetscMalloc1(2 * patch->totalDofsPerCell * numIntFacets, &facetDofs);CHKERRQ(ierr);
1884     if (dofsArrayWithAll) {
1885       ierr = PetscMalloc1(2 * patch->totalDofsPerCell * numIntFacets, &facetDofsWithAll);CHKERRQ(ierr);
1886     }
1887     /*
1888      * 0--1
1889      * |\-|
1890      * |+\|
1891      * 2--3
1892      * [0, 2, 3, 0, 1, 3]
1893      */
1894     for (i = 0; i < numIntFacets; i++) {
1895       for (c = 0; c < 2; c++) {
1896         const PetscInt cell = facetCells[2*(intFacetOffset + i) + c];
1897         for (d = 0; d < patch->totalDofsPerCell; d++) {
1898           facetDofs[idx] = dofsArray[(offset + cell)*patch->totalDofsPerCell + d];
1899           if (dofsArrayWithAll) {
1900             facetDofsWithAll[idx] = dofsArrayWithAll[(offset + cell)*patch->totalDofsPerCell + d];
1901           }
1902           idx++;
1903         }
1904       }
1905     }
1906     ierr = ISCreateGeneral(PETSC_COMM_SELF, numIntFacets, intFacetsArray + intFacetOffset, PETSC_USE_POINTER, &facetIS);CHKERRQ(ierr);
1907     /*
1908      * ierr = patch->usercomputeopintfacet(pc, point, x, mat, facetIS, 2*numIntFacets*patch->totalDofsPerCell, facetDofs, facetDofsWithAll, patch->usercomputeopctx);CHKERRQ(ierr);
1909      */
1910     ierr = ISDestroy(&facetIS);CHKERRQ(ierr);
1911     ierr = ISRestoreIndices(patch->intFacetsToPatchCell, &facetCells);CHKERRQ(ierr);
1912     ierr = PetscFree(facetDofs);CHKERRQ(ierr);
1913     ierr = PetscFree(facetDofsWithAll);CHKERRQ(ierr);
1914   }
1915   PetscStackPop;
1916   ierr = ISDestroy(&patch->cellIS);CHKERRQ(ierr);
1917   if(withArtificial) {
1918     ierr = ISRestoreIndices(patch->dofsWithArtificial, &dofsArray);CHKERRQ(ierr);
1919   } else {
1920     ierr = ISRestoreIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
1921   }
1922   if (isNonlinear) {
1923     ierr = ISRestoreIndices(patch->dofsWithAll, &dofsArrayWithAll);CHKERRQ(ierr);
1924   }
1925   ierr = ISRestoreIndices(patch->cells, &cellsArray);CHKERRQ(ierr);
1926   if (patch->viewMatrix) {
1927     char name[PETSC_MAX_PATH_LEN];
1928 
1929     ierr = PetscSNPrintf(name, PETSC_MAX_PATH_LEN-1, "Patch matrix for Point %D", point);CHKERRQ(ierr);
1930     ierr = PetscObjectSetName((PetscObject) mat, name);CHKERRQ(ierr);
1931     ierr = ObjectView((PetscObject) mat, patch->viewerMatrix, patch->formatMatrix);CHKERRQ(ierr);
1932   }
1933   ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
1934   PetscFunctionReturn(0);
1935 }
1936 
1937 PetscErrorCode PCPatch_ScatterLocal_Private(PC pc, PetscInt p, Vec x, Vec y, InsertMode mode, ScatterMode scat, PatchScatterType scattertype)
1938 {
1939   PC_PATCH          *patch     = (PC_PATCH *) pc->data;
1940   const PetscScalar *xArray    = NULL;
1941   PetscScalar       *yArray    = NULL;
1942   const PetscInt    *gtolArray = NULL;
1943   PetscInt           dof, offset, lidx;
1944   PetscErrorCode     ierr;
1945 
1946   PetscFunctionBeginHot;
1947   ierr = PetscLogEventBegin(PC_Patch_Scatter, pc, 0, 0, 0);CHKERRQ(ierr);
1948   ierr = VecGetArrayRead(x, &xArray);CHKERRQ(ierr);
1949   ierr = VecGetArray(y, &yArray);CHKERRQ(ierr);
1950   if (scattertype == SCATTER_WITHARTIFICIAL) {
1951     ierr = PetscSectionGetDof(patch->gtolCountsWithArtificial, p, &dof);CHKERRQ(ierr);
1952     ierr = PetscSectionGetOffset(patch->gtolCountsWithArtificial, p, &offset);CHKERRQ(ierr);
1953     ierr = ISGetIndices(patch->gtolWithArtificial, &gtolArray);CHKERRQ(ierr);
1954   } else if (scattertype == SCATTER_WITHALL) {
1955     ierr = PetscSectionGetDof(patch->gtolCountsWithAll, p, &dof);CHKERRQ(ierr);
1956     ierr = PetscSectionGetOffset(patch->gtolCountsWithAll, p, &offset);CHKERRQ(ierr);
1957     ierr = ISGetIndices(patch->gtolWithAll, &gtolArray);CHKERRQ(ierr);
1958   } else {
1959     ierr = PetscSectionGetDof(patch->gtolCounts, p, &dof);CHKERRQ(ierr);
1960     ierr = PetscSectionGetOffset(patch->gtolCounts, p, &offset);CHKERRQ(ierr);
1961     ierr = ISGetIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
1962   }
1963   if (mode == INSERT_VALUES && scat != SCATTER_FORWARD) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Can't insert if not scattering forward\n");
1964   if (mode == ADD_VALUES    && scat != SCATTER_REVERSE) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Can't add if not scattering reverse\n");
1965   for (lidx = 0; lidx < dof; ++lidx) {
1966     const PetscInt gidx = gtolArray[offset+lidx];
1967 
1968     if (mode == INSERT_VALUES) yArray[lidx]  = xArray[gidx]; /* Forward */
1969     else                       yArray[gidx] += xArray[lidx]; /* Reverse */
1970   }
1971   if (scattertype == SCATTER_WITHARTIFICIAL) {
1972     ierr = ISRestoreIndices(patch->gtolWithArtificial, &gtolArray);CHKERRQ(ierr);
1973   } else if (scattertype == SCATTER_WITHALL) {
1974     ierr = ISRestoreIndices(patch->gtolWithAll, &gtolArray);CHKERRQ(ierr);
1975   } else {
1976     ierr = ISRestoreIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
1977   }
1978   ierr = VecRestoreArrayRead(x, &xArray);CHKERRQ(ierr);
1979   ierr = VecRestoreArray(y, &yArray);CHKERRQ(ierr);
1980   ierr = PetscLogEventEnd(PC_Patch_Scatter, pc, 0, 0, 0);CHKERRQ(ierr);
1981   PetscFunctionReturn(0);
1982 }
1983 
1984 static PetscErrorCode PCSetUp_PATCH_Linear(PC pc)
1985 {
1986   PC_PATCH      *patch = (PC_PATCH *) pc->data;
1987   const char    *prefix;
1988   PetscInt       i;
1989   PetscErrorCode ierr;
1990 
1991   PetscFunctionBegin;
1992   if (!pc->setupcalled) {
1993     ierr = PetscMalloc1(patch->npatch, &patch->solver);CHKERRQ(ierr);
1994     ierr = PCGetOptionsPrefix(pc, &prefix);CHKERRQ(ierr);
1995     for (i = 0; i < patch->npatch; ++i) {
1996       KSP ksp;
1997       PC  subpc;
1998 
1999       ierr = KSPCreate(PETSC_COMM_SELF, &ksp);CHKERRQ(ierr);
2000       ierr = KSPSetErrorIfNotConverged(ksp, pc->erroriffailure);CHKERRQ(ierr);
2001       ierr = KSPSetOptionsPrefix(ksp, prefix);CHKERRQ(ierr);
2002       ierr = KSPAppendOptionsPrefix(ksp, "sub_");CHKERRQ(ierr);
2003       ierr = PetscObjectIncrementTabLevel((PetscObject) ksp, (PetscObject) pc, 1);CHKERRQ(ierr);
2004       ierr = KSPGetPC(ksp, &subpc);CHKERRQ(ierr);
2005       ierr = PetscObjectIncrementTabLevel((PetscObject) subpc, (PetscObject) pc, 1);CHKERRQ(ierr);
2006       ierr = PetscLogObjectParent((PetscObject) pc, (PetscObject) ksp);CHKERRQ(ierr);
2007       patch->solver[i] = (PetscObject) ksp;
2008     }
2009   }
2010   if (patch->save_operators) {
2011     for (i = 0; i < patch->npatch; ++i) {
2012       ierr = MatZeroEntries(patch->mat[i]);CHKERRQ(ierr);
2013       ierr = PCPatchComputeOperator_Internal(pc, NULL, patch->mat[i], i, PETSC_FALSE);CHKERRQ(ierr);
2014       ierr = KSPSetOperators((KSP) patch->solver[i], patch->mat[i], patch->mat[i]);CHKERRQ(ierr);
2015     }
2016   }
2017   if(patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
2018     for (i = 0; i < patch->npatch; ++i) {
2019       /* Instead of padding patch->patchUpdate with zeros to get */
2020       /* patch->patchUpdateWithArtificial and then multiplying with the matrix, */
2021       /* just get rid of the columns that correspond to the dofs with */
2022       /* artificial bcs. That's of course fairly inefficient, hopefully we */
2023       /* can just assemble the rectangular matrix in the first place. */
2024       Mat matSquare;
2025       IS rowis;
2026       PetscInt dof;
2027 
2028       ierr = MatGetSize(patch->mat[i], &dof, NULL);CHKERRQ(ierr);
2029       if (dof == 0) {
2030         patch->matWithArtificial[i] = NULL;
2031         continue;
2032       }
2033 
2034       ierr = PCPatchCreateMatrix_Private(pc, i, &matSquare, PETSC_TRUE);CHKERRQ(ierr);
2035       ierr = MatZeroEntries(matSquare);CHKERRQ(ierr);
2036       ierr = PCPatchComputeOperator_Internal(pc, NULL, matSquare, i, PETSC_TRUE);CHKERRQ(ierr);
2037 
2038       ierr = MatGetSize(matSquare, &dof, NULL);CHKERRQ(ierr);
2039       ierr = ISCreateStride(PETSC_COMM_SELF, dof, 0, 1, &rowis); CHKERRQ(ierr);
2040       if(pc->setupcalled) {
2041         ierr = MatCreateSubMatrix(matSquare, rowis, patch->dofMappingWithoutToWithArtificial[i], MAT_REUSE_MATRIX, &patch->matWithArtificial[i]); CHKERRQ(ierr);
2042       } else {
2043         ierr = MatCreateSubMatrix(matSquare, rowis, patch->dofMappingWithoutToWithArtificial[i], MAT_INITIAL_MATRIX, &patch->matWithArtificial[i]); CHKERRQ(ierr);
2044       }
2045       ierr = ISDestroy(&rowis); CHKERRQ(ierr);
2046       ierr = MatDestroy(&matSquare);CHKERRQ(ierr);
2047     }
2048   }
2049   PetscFunctionReturn(0);
2050 }
2051 
2052 static PetscErrorCode PCSetUp_PATCH(PC pc)
2053 {
2054   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2055   PetscInt       i;
2056   PetscBool       isNonlinear;
2057   PetscErrorCode ierr;
2058 
2059   PetscFunctionBegin;
2060   if (!pc->setupcalled) {
2061     PetscInt pStart, pEnd, p;
2062     PetscInt localSize;
2063 
2064     ierr = PetscLogEventBegin(PC_Patch_CreatePatches, pc, 0, 0, 0);CHKERRQ(ierr);
2065 
2066     isNonlinear = patch->isNonlinear;
2067     if (!patch->nsubspaces) {
2068       DM           dm;
2069       PetscDS      prob;
2070       PetscSection s;
2071       PetscInt     cStart, cEnd, c, Nf, f, numGlobalBcs = 0, *globalBcs, *Nb, totNb = 0, **cellDofs;
2072 
2073       ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
2074       if (!dm) SETERRQ(PetscObjectComm((PetscObject) pc), PETSC_ERR_ARG_WRONG, "Must set DM for PCPATCH or call PCPatchSetDiscretisationInfo()");
2075       ierr = DMGetDefaultSection(dm, &s);CHKERRQ(ierr);
2076       ierr = PetscSectionGetNumFields(s, &Nf);CHKERRQ(ierr);
2077       ierr = PetscSectionGetChart(s, &pStart, &pEnd);CHKERRQ(ierr);
2078       for (p = pStart; p < pEnd; ++p) {
2079         PetscInt cdof;
2080         ierr = PetscSectionGetConstraintDof(s, p, &cdof);CHKERRQ(ierr);
2081         numGlobalBcs += cdof;
2082       }
2083       ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);
2084       ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
2085       ierr = PetscMalloc3(Nf, &Nb, Nf, &cellDofs, numGlobalBcs, &globalBcs);CHKERRQ(ierr);
2086       for (f = 0; f < Nf; ++f) {
2087         PetscFE        fe;
2088         PetscDualSpace sp;
2089         PetscInt       cdoff = 0;
2090 
2091         ierr = PetscDSGetDiscretization(prob, f, (PetscObject *) &fe);CHKERRQ(ierr);
2092         /* ierr = PetscFEGetNumComponents(fe, &Nc[f]);CHKERRQ(ierr); */
2093         ierr = PetscFEGetDualSpace(fe, &sp);CHKERRQ(ierr);
2094         ierr = PetscDualSpaceGetDimension(sp, &Nb[f]);CHKERRQ(ierr);
2095         totNb += Nb[f];
2096 
2097         ierr = PetscMalloc1((cEnd-cStart)*Nb[f], &cellDofs[f]);CHKERRQ(ierr);
2098         for (c = cStart; c < cEnd; ++c) {
2099           PetscInt *closure = NULL;
2100           PetscInt  clSize  = 0, cl;
2101 
2102           ierr = DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure);CHKERRQ(ierr);
2103           for (cl = 0; cl < clSize*2; cl += 2) {
2104             const PetscInt p = closure[cl];
2105             PetscInt       fdof, d, foff;
2106 
2107             ierr = PetscSectionGetFieldDof(s, p, f, &fdof);CHKERRQ(ierr);
2108             ierr = PetscSectionGetFieldOffset(s, p, f, &foff);CHKERRQ(ierr);
2109             for (d = 0; d < fdof; ++d, ++cdoff) cellDofs[f][cdoff] = foff + d;
2110           }
2111           ierr = DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure);CHKERRQ(ierr);
2112         }
2113         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]);
2114       }
2115       numGlobalBcs = 0;
2116       for (p = pStart; p < pEnd; ++p) {
2117         const PetscInt *ind;
2118         PetscInt        off, cdof, d;
2119 
2120         ierr = PetscSectionGetOffset(s, p, &off);CHKERRQ(ierr);
2121         ierr = PetscSectionGetConstraintDof(s, p, &cdof);CHKERRQ(ierr);
2122         ierr = PetscSectionGetConstraintIndices(s, p, &ind);CHKERRQ(ierr);
2123         for (d = 0; d < cdof; ++d) globalBcs[numGlobalBcs++] = off + ind[d];
2124       }
2125 
2126       ierr = PCPatchSetDiscretisationInfoCombined(pc, dm, Nb, (const PetscInt **) cellDofs, numGlobalBcs, globalBcs, numGlobalBcs, globalBcs);CHKERRQ(ierr);
2127       for (f = 0; f < Nf; ++f) {
2128         ierr = PetscFree(cellDofs[f]);CHKERRQ(ierr);
2129       }
2130       ierr = PetscFree3(Nb, cellDofs, globalBcs);CHKERRQ(ierr);
2131       ierr = PCPatchSetComputeFunction(pc, PCPatchComputeFunction_DMPlex_Private, NULL);CHKERRQ(ierr);
2132       ierr = PCPatchSetComputeOperator(pc, PCPatchComputeOperator_DMPlex_Private, NULL);CHKERRQ(ierr);
2133     }
2134 
2135     localSize = patch->subspaceOffsets[patch->nsubspaces];
2136     ierr = VecCreateSeq(PETSC_COMM_SELF, localSize, &patch->localRHS);CHKERRQ(ierr);
2137     ierr = VecSetUp(patch->localRHS);CHKERRQ(ierr);
2138     ierr = VecDuplicate(patch->localRHS, &patch->localUpdate);CHKERRQ(ierr);
2139     ierr = PCPatchCreateCellPatches(pc);CHKERRQ(ierr);
2140     ierr = PCPatchCreateCellPatchDiscretisationInfo(pc);CHKERRQ(ierr);
2141 
2142     /* OK, now build the work vectors */
2143     ierr = PetscSectionGetChart(patch->gtolCounts, &pStart, &pEnd);CHKERRQ(ierr);
2144     ierr = PetscMalloc1(patch->npatch, &patch->patchRHS);CHKERRQ(ierr);
2145     ierr = PetscMalloc1(patch->npatch, &patch->patchUpdate);CHKERRQ(ierr);
2146 
2147     if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
2148       ierr = PetscMalloc1(patch->npatch, &patch->patchRHSWithArtificial);CHKERRQ(ierr);
2149       ierr = PetscMalloc1(patch->npatch, &patch->dofMappingWithoutToWithArtificial);CHKERRQ(ierr);
2150     }
2151     if (isNonlinear) {
2152       ierr = PetscMalloc1(patch->npatch, &patch->dofMappingWithoutToWithAll);CHKERRQ(ierr);
2153     }
2154     for (p = pStart; p < pEnd; ++p) {
2155       PetscInt dof;
2156 
2157       ierr = PetscSectionGetDof(patch->gtolCounts, p, &dof);CHKERRQ(ierr);
2158       ierr = VecCreateSeq(PETSC_COMM_SELF, dof, &patch->patchRHS[p-pStart]);CHKERRQ(ierr);
2159       ierr = VecSetUp(patch->patchRHS[p-pStart]);CHKERRQ(ierr);
2160       ierr = VecCreateSeq(PETSC_COMM_SELF, dof, &patch->patchUpdate[p-pStart]);CHKERRQ(ierr);
2161       ierr = VecSetUp(patch->patchUpdate[p-pStart]);CHKERRQ(ierr);
2162       if (patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
2163         const PetscInt    *gtolArray, *gtolArrayWithArtificial = NULL;
2164         PetscInt           numPatchDofs, offset;
2165         PetscInt           numPatchDofsWithArtificial, offsetWithArtificial;
2166         PetscInt           dofWithoutArtificialCounter = 0;
2167         PetscInt          *patchWithoutArtificialToWithArtificialArray;
2168 
2169         ierr = PetscSectionGetDof(patch->gtolCountsWithArtificial, p, &dof);CHKERRQ(ierr);
2170         ierr = VecCreateSeq(PETSC_COMM_SELF, dof, &patch->patchRHSWithArtificial[p-pStart]);CHKERRQ(ierr);
2171         ierr = VecSetUp(patch->patchRHSWithArtificial[p-pStart]);CHKERRQ(ierr);
2172 
2173         /* Now build the mapping that for a dof in a patch WITHOUT dofs that have artificial bcs gives the */
2174         /* the index in the patch with all dofs */
2175         ierr = ISGetIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
2176 
2177         ierr = PetscSectionGetDof(patch->gtolCounts, p, &numPatchDofs);CHKERRQ(ierr);
2178         if (numPatchDofs == 0) {
2179           patch->dofMappingWithoutToWithArtificial[p-pStart] = NULL;
2180           continue;
2181         }
2182 
2183         ierr = PetscSectionGetOffset(patch->gtolCounts, p, &offset);CHKERRQ(ierr);
2184         ierr = ISGetIndices(patch->gtolWithArtificial, &gtolArrayWithArtificial);CHKERRQ(ierr);
2185         ierr = PetscSectionGetDof(patch->gtolCountsWithArtificial, p, &numPatchDofsWithArtificial);CHKERRQ(ierr);
2186         ierr = PetscSectionGetOffset(patch->gtolCountsWithArtificial, p, &offsetWithArtificial);CHKERRQ(ierr);
2187 
2188         ierr = PetscMalloc1(numPatchDofs, &patchWithoutArtificialToWithArtificialArray);CHKERRQ(ierr);
2189         for (i=0; i<numPatchDofsWithArtificial; i++) {
2190           if (gtolArrayWithArtificial[i+offsetWithArtificial] == gtolArray[offset+dofWithoutArtificialCounter]) {
2191             patchWithoutArtificialToWithArtificialArray[dofWithoutArtificialCounter] = i;
2192             dofWithoutArtificialCounter++;
2193             if (dofWithoutArtificialCounter == numPatchDofs)
2194               break;
2195           }
2196         }
2197         ierr = ISCreateGeneral(PETSC_COMM_SELF, numPatchDofs, patchWithoutArtificialToWithArtificialArray, PETSC_OWN_POINTER, &patch->dofMappingWithoutToWithArtificial[p-pStart]);CHKERRQ(ierr);
2198         ierr = ISRestoreIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
2199         ierr = ISRestoreIndices(patch->gtolWithArtificial, &gtolArrayWithArtificial);CHKERRQ(ierr);
2200       }
2201       if (isNonlinear) {
2202         const PetscInt    *gtolArray, *gtolArrayWithAll = NULL;
2203         PetscInt           numPatchDofs, offset;
2204         PetscInt           numPatchDofsWithAll, offsetWithAll;
2205         PetscInt           dofWithoutAllCounter = 0;
2206         PetscInt          *patchWithoutAllToWithAllArray;
2207 
2208         /* Now build the mapping that for a dof in a patch WITHOUT dofs that have artificial bcs gives the */
2209         /* the index in the patch with all dofs */
2210         ierr = ISGetIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
2211 
2212         ierr = PetscSectionGetDof(patch->gtolCounts, p, &numPatchDofs);CHKERRQ(ierr);
2213         if (numPatchDofs == 0) {
2214           patch->dofMappingWithoutToWithAll[p-pStart] = NULL;
2215           continue;
2216         }
2217 
2218         ierr = PetscSectionGetOffset(patch->gtolCounts, p, &offset);CHKERRQ(ierr);
2219         ierr = ISGetIndices(patch->gtolWithAll, &gtolArrayWithAll);CHKERRQ(ierr);
2220         ierr = PetscSectionGetDof(patch->gtolCountsWithAll, p, &numPatchDofsWithAll);CHKERRQ(ierr);
2221         ierr = PetscSectionGetOffset(patch->gtolCountsWithAll, p, &offsetWithAll);CHKERRQ(ierr);
2222 
2223         ierr = PetscMalloc1(numPatchDofs, &patchWithoutAllToWithAllArray);CHKERRQ(ierr);
2224 
2225         for (i=0; i<numPatchDofsWithAll; i++) {
2226           if (gtolArrayWithAll[i+offsetWithAll] == gtolArray[offset+dofWithoutAllCounter]) {
2227             patchWithoutAllToWithAllArray[dofWithoutAllCounter] = i;
2228             dofWithoutAllCounter++;
2229             if (dofWithoutAllCounter == numPatchDofs)
2230               break;
2231           }
2232         }
2233         ierr = ISCreateGeneral(PETSC_COMM_SELF, numPatchDofs, patchWithoutAllToWithAllArray, PETSC_OWN_POINTER, &patch->dofMappingWithoutToWithAll[p-pStart]);CHKERRQ(ierr);
2234         ierr = ISRestoreIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
2235         ierr = ISRestoreIndices(patch->gtolWithAll, &gtolArrayWithAll);CHKERRQ(ierr);
2236       }
2237     }
2238     if (patch->save_operators) {
2239       ierr = PetscMalloc1(patch->npatch, &patch->mat);CHKERRQ(ierr);
2240       for (i = 0; i < patch->npatch; ++i) {
2241         ierr = PCPatchCreateMatrix_Private(pc, i, &patch->mat[i], PETSC_FALSE);CHKERRQ(ierr);
2242       }
2243     }
2244     ierr = PetscLogEventEnd(PC_Patch_CreatePatches, pc, 0, 0, 0);CHKERRQ(ierr);
2245 
2246     /* If desired, calculate weights for dof multiplicity */
2247     if (patch->partition_of_unity) {
2248       PetscScalar *input = NULL;
2249       PetscScalar *output = NULL;
2250       Vec global;
2251 
2252       ierr = VecDuplicate(patch->localRHS, &patch->dof_weights);CHKERRQ(ierr);
2253       if(patch->local_composition_type == PC_COMPOSITE_ADDITIVE) {
2254         for (i = 0; i < patch->npatch; ++i) {
2255           PetscInt dof;
2256 
2257           ierr = PetscSectionGetDof(patch->gtolCounts, i+pStart, &dof);CHKERRQ(ierr);
2258           if (dof <= 0) continue;
2259           ierr = VecSet(patch->patchRHS[i], 1.0);CHKERRQ(ierr);
2260           ierr = PCPatch_ScatterLocal_Private(pc, i+pStart, patch->patchRHS[i], patch->dof_weights, ADD_VALUES, SCATTER_REVERSE, SCATTER_INTERIOR);CHKERRQ(ierr);
2261         }
2262       } else {
2263         /* multiplicative is actually only locally multiplicative and globally additive. need the pou where the mesh decomposition overlaps */
2264         ierr = VecSet(patch->dof_weights, 1.0);CHKERRQ(ierr);
2265       }
2266 
2267       VecDuplicate(patch->dof_weights, &global);
2268       VecSet(global, 0.);
2269 
2270       ierr = VecGetArray(patch->dof_weights, &input);CHKERRQ(ierr);
2271       ierr = VecGetArray(global, &output);CHKERRQ(ierr);
2272       ierr = PetscSFReduceBegin(patch->defaultSF, MPIU_SCALAR, input, output, MPI_SUM);CHKERRQ(ierr);
2273       ierr = PetscSFReduceEnd(patch->defaultSF, MPIU_SCALAR, input, output, MPI_SUM);CHKERRQ(ierr);
2274       ierr = VecRestoreArray(patch->dof_weights, &input);CHKERRQ(ierr);
2275       ierr = VecRestoreArray(global, &output);CHKERRQ(ierr);
2276 
2277       ierr = VecReciprocal(global);CHKERRQ(ierr);
2278 
2279       ierr = VecGetArray(patch->dof_weights, &output);CHKERRQ(ierr);
2280       ierr = VecGetArray(global, &input);CHKERRQ(ierr);
2281       ierr = PetscSFBcastBegin(patch->defaultSF, MPIU_SCALAR, input, output);CHKERRQ(ierr);
2282       ierr = PetscSFBcastEnd(patch->defaultSF, MPIU_SCALAR, input, output);CHKERRQ(ierr);
2283       ierr = VecRestoreArray(patch->dof_weights, &output);CHKERRQ(ierr);
2284       ierr = VecRestoreArray(global, &input);CHKERRQ(ierr);
2285       ierr = VecDestroy(&global);CHKERRQ(ierr);
2286     }
2287     if(patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE && patch->save_operators) {
2288       ierr = PetscMalloc1(patch->npatch, &patch->matWithArtificial);CHKERRQ(ierr);
2289     }
2290   }
2291   ierr = (*patch->setupsolver)(pc);CHKERRQ(ierr);
2292   PetscFunctionReturn(0);
2293 }
2294 
2295 static PetscErrorCode PCApply_PATCH_Linear(PC pc, PetscInt i, Vec x, Vec y)
2296 {
2297   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2298   KSP            ksp   = (KSP) patch->solver[i];
2299   PetscErrorCode ierr;
2300 
2301   PetscFunctionBegin;
2302   if (!patch->save_operators) {
2303     Mat mat;
2304 
2305     ierr = PCPatchCreateMatrix_Private(pc, i, &mat, PETSC_FALSE);CHKERRQ(ierr);
2306     /* Populate operator here. */
2307     ierr = PCPatchComputeOperator_Internal(pc, NULL, mat, i, PETSC_FALSE);CHKERRQ(ierr);
2308     ierr = KSPSetOperators(ksp, mat, mat);CHKERRQ(ierr);
2309     /* Drop reference so the KSPSetOperators below will blow it away. */
2310     ierr = MatDestroy(&mat);CHKERRQ(ierr);
2311   }
2312   ierr = PetscLogEventBegin(PC_Patch_Solve, pc, 0, 0, 0);CHKERRQ(ierr);
2313   if (!ksp->setfromoptionscalled) {
2314     ierr = KSPSetFromOptions(ksp);CHKERRQ(ierr);
2315   }
2316   ierr = KSPSolve(ksp, x, y);CHKERRQ(ierr);
2317   ierr = KSPCheckSolve(ksp, pc, y);CHKERRQ(ierr);
2318   ierr = PetscLogEventEnd(PC_Patch_Solve, pc, 0, 0, 0);CHKERRQ(ierr);
2319   if (!patch->save_operators) {
2320     PC pc;
2321     ierr = KSPSetOperators(ksp, NULL, NULL);CHKERRQ(ierr);
2322     ierr = KSPGetPC(ksp, &pc);CHKERRQ(ierr);
2323     /* Destroy PC context too, otherwise the factored matrix hangs around. */
2324     ierr = PCReset(pc);CHKERRQ(ierr);
2325   }
2326   PetscFunctionReturn(0);
2327 }
2328 
2329 static PetscErrorCode PCUpdateMultiplicative_PATCH_Linear(PC pc, PetscInt i, PetscInt pStart)
2330 {
2331   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2332   Mat multMat;
2333   PetscErrorCode ierr;
2334 
2335   PetscFunctionBegin;
2336 
2337   if (patch->save_operators) {
2338     multMat = patch->matWithArtificial[i];
2339   } else {
2340     /*Very inefficient, hopefully we can just assemble the rectangular matrix in the first place.*/
2341     Mat matSquare;
2342     PetscInt dof;
2343     IS rowis;
2344     ierr = PCPatchCreateMatrix_Private(pc, i, &matSquare, PETSC_TRUE);CHKERRQ(ierr);
2345     ierr = MatZeroEntries(matSquare);CHKERRQ(ierr);
2346     ierr = PCPatchComputeOperator_Internal(pc, NULL, matSquare, i, PETSC_TRUE);CHKERRQ(ierr);
2347     ierr = MatGetSize(matSquare, &dof, NULL);CHKERRQ(ierr);
2348     ierr = ISCreateStride(PETSC_COMM_SELF, dof, 0, 1, &rowis); CHKERRQ(ierr);
2349     ierr = MatCreateSubMatrix(matSquare, rowis, patch->dofMappingWithoutToWithArtificial[i], MAT_INITIAL_MATRIX, &multMat); CHKERRQ(ierr);
2350     ierr = MatDestroy(&matSquare);CHKERRQ(ierr);
2351     ierr = ISDestroy(&rowis); CHKERRQ(ierr);
2352   }
2353   ierr = MatMult(multMat, patch->patchUpdate[i], patch->patchRHSWithArtificial[i]); CHKERRQ(ierr);
2354   ierr = VecScale(patch->patchRHSWithArtificial[i], -1.0); CHKERRQ(ierr);
2355   ierr = PCPatch_ScatterLocal_Private(pc, i + pStart, patch->patchRHSWithArtificial[i], patch->localRHS, ADD_VALUES, SCATTER_REVERSE, SCATTER_WITHARTIFICIAL); CHKERRQ(ierr);
2356   if (!patch->save_operators) {
2357     ierr = MatDestroy(&multMat); CHKERRQ(ierr);
2358   }
2359   PetscFunctionReturn(0);
2360 }
2361 
2362 static PetscErrorCode PCApply_PATCH(PC pc, Vec x, Vec y)
2363 {
2364   PC_PATCH          *patch    = (PC_PATCH *) pc->data;
2365   const PetscScalar *globalRHS  = NULL;
2366   PetscScalar       *localRHS   = NULL;
2367   PetscScalar       *globalUpdate  = NULL;
2368   const PetscInt    *bcNodes  = NULL;
2369   PetscInt           nsweep   = patch->symmetrise_sweep ? 2 : 1;
2370   PetscInt           start[2] = {0, 0};
2371   PetscInt           end[2]   = {-1, -1};
2372   const PetscInt     inc[2]   = {1, -1};
2373   const PetscScalar *localUpdate;
2374   const PetscInt    *iterationSet;
2375   PetscInt           pStart, numBcs, n, sweep, bc, j;
2376   PetscErrorCode     ierr;
2377 
2378   PetscFunctionBegin;
2379   ierr = PetscLogEventBegin(PC_Patch_Apply, pc, 0, 0, 0);CHKERRQ(ierr);
2380   ierr = PetscOptionsPushGetViewerOff(PETSC_TRUE);CHKERRQ(ierr);
2381   /* start, end, inc have 2 entries to manage a second backward sweep if we symmetrize */
2382   end[0]   = patch->npatch;
2383   start[1] = patch->npatch-1;
2384   if (patch->user_patches) {
2385     ierr = ISGetLocalSize(patch->iterationSet, &end[0]);CHKERRQ(ierr);
2386     start[1] = end[0] - 1;
2387     ierr = ISGetIndices(patch->iterationSet, &iterationSet);CHKERRQ(ierr);
2388   }
2389   /* Scatter from global space into overlapped local spaces */
2390   ierr = VecGetArrayRead(x, &globalRHS);CHKERRQ(ierr);
2391   ierr = VecGetArray(patch->localRHS, &localRHS);CHKERRQ(ierr);
2392   ierr = PetscSFBcastBegin(patch->defaultSF, MPIU_SCALAR, globalRHS, localRHS);CHKERRQ(ierr);
2393   ierr = PetscSFBcastEnd(patch->defaultSF, MPIU_SCALAR, globalRHS, localRHS);CHKERRQ(ierr);
2394   ierr = VecRestoreArrayRead(x, &globalRHS);CHKERRQ(ierr);
2395   ierr = VecRestoreArray(patch->localRHS, &localRHS);CHKERRQ(ierr);
2396 
2397   ierr = VecSet(patch->localUpdate, 0.0);CHKERRQ(ierr);
2398   ierr = PetscSectionGetChart(patch->gtolCounts, &pStart, NULL);CHKERRQ(ierr);
2399   for (sweep = 0; sweep < nsweep; sweep++) {
2400     for (j = start[sweep]; j*inc[sweep] < end[sweep]*inc[sweep]; j += inc[sweep]) {
2401       PetscInt i       = patch->user_patches ? iterationSet[j] : j;
2402       PetscInt start, len;
2403 
2404       ierr = PetscSectionGetDof(patch->gtolCounts, i+pStart, &len);CHKERRQ(ierr);
2405       ierr = PetscSectionGetOffset(patch->gtolCounts, i+pStart, &start);CHKERRQ(ierr);
2406       /* TODO: Squash out these guys in the setup as well. */
2407       if (len <= 0) continue;
2408       /* TODO: Do we need different scatters for X and Y? */
2409       ierr = PCPatch_ScatterLocal_Private(pc, i+pStart, patch->localRHS, patch->patchRHS[i], INSERT_VALUES, SCATTER_FORWARD, SCATTER_INTERIOR);CHKERRQ(ierr);
2410       ierr = (*patch->applysolver)(pc, i, patch->patchRHS[i], patch->patchUpdate[i]);CHKERRQ(ierr);
2411       ierr = PCPatch_ScatterLocal_Private(pc, i+pStart, patch->patchUpdate[i], patch->localUpdate, ADD_VALUES, SCATTER_REVERSE, SCATTER_INTERIOR);CHKERRQ(ierr);
2412       if(patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
2413         ierr = (*patch->updatemultiplicative)(pc, i, pStart);CHKERRQ(ierr);
2414       }
2415     }
2416   }
2417   if (patch->user_patches) {ierr = ISRestoreIndices(patch->iterationSet, &iterationSet);CHKERRQ(ierr);}
2418   /* XXX: should we do this on the global vector? */
2419   if (patch->partition_of_unity) {
2420     ierr = VecPointwiseMult(patch->localUpdate, patch->localUpdate, patch->dof_weights);CHKERRQ(ierr);
2421   }
2422   /* Now patch->localUpdate contains the solution of the patch solves, so we need to combine them all. */
2423   ierr = VecSet(y, 0.0);CHKERRQ(ierr);
2424   ierr = VecGetArray(y, &globalUpdate);CHKERRQ(ierr);
2425   ierr = VecGetArrayRead(patch->localUpdate, &localUpdate);CHKERRQ(ierr);
2426   ierr = PetscSFReduceBegin(patch->defaultSF, MPIU_SCALAR, localUpdate, globalUpdate, MPI_SUM);CHKERRQ(ierr);
2427   ierr = PetscSFReduceEnd(patch->defaultSF, MPIU_SCALAR, localUpdate, globalUpdate, MPI_SUM);CHKERRQ(ierr);
2428   ierr = VecRestoreArrayRead(patch->localUpdate, &localUpdate);CHKERRQ(ierr);
2429 
2430   /* Now we need to send the global BC values through */
2431   ierr = VecGetArrayRead(x, &globalRHS);CHKERRQ(ierr);
2432   ierr = ISGetSize(patch->globalBcNodes, &numBcs);CHKERRQ(ierr);
2433   ierr = ISGetIndices(patch->globalBcNodes, &bcNodes);CHKERRQ(ierr);
2434   ierr = VecGetLocalSize(x, &n);CHKERRQ(ierr);
2435   for (bc = 0; bc < numBcs; ++bc) {
2436     const PetscInt idx = bcNodes[bc];
2437     if (idx < n) globalUpdate[idx] = globalRHS[idx];
2438   }
2439 
2440   ierr = ISRestoreIndices(patch->globalBcNodes, &bcNodes);CHKERRQ(ierr);
2441   ierr = VecRestoreArrayRead(x, &globalRHS);CHKERRQ(ierr);
2442   ierr = VecRestoreArray(y, &globalUpdate);CHKERRQ(ierr);
2443 
2444   ierr = PetscOptionsPopGetViewerOff();CHKERRQ(ierr);
2445   ierr = PetscLogEventEnd(PC_Patch_Apply, pc, 0, 0, 0);CHKERRQ(ierr);
2446   PetscFunctionReturn(0);
2447 }
2448 
2449 static PetscErrorCode PCReset_PATCH_Linear(PC pc)
2450 {
2451   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2452   PetscInt       i;
2453   PetscErrorCode ierr;
2454 
2455   PetscFunctionBegin;
2456   if (patch->solver) {
2457     for (i = 0; i < patch->npatch; ++i) {ierr = KSPReset((KSP) patch->solver[i]);CHKERRQ(ierr);}
2458   }
2459   PetscFunctionReturn(0);
2460 }
2461 
2462 static PetscErrorCode PCReset_PATCH(PC pc)
2463 {
2464   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2465   PetscInt       i;
2466   PetscErrorCode ierr;
2467 
2468   PetscFunctionBegin;
2469   /* TODO: Get rid of all these ifs */
2470   ierr = PetscSFDestroy(&patch->defaultSF);CHKERRQ(ierr);
2471   ierr = PetscSectionDestroy(&patch->cellCounts);CHKERRQ(ierr);
2472   ierr = PetscSectionDestroy(&patch->pointCounts);CHKERRQ(ierr);
2473   ierr = PetscSectionDestroy(&patch->cellNumbering);CHKERRQ(ierr);
2474   ierr = PetscSectionDestroy(&patch->gtolCounts);CHKERRQ(ierr);
2475   ierr = ISDestroy(&patch->gtol);CHKERRQ(ierr);
2476   ierr = ISDestroy(&patch->cells);CHKERRQ(ierr);
2477   ierr = ISDestroy(&patch->points);CHKERRQ(ierr);
2478   ierr = ISDestroy(&patch->dofs);CHKERRQ(ierr);
2479   ierr = ISDestroy(&patch->offs);CHKERRQ(ierr);
2480   ierr = PetscSectionDestroy(&patch->patchSection);CHKERRQ(ierr);
2481   ierr = ISDestroy(&patch->ghostBcNodes);CHKERRQ(ierr);
2482   ierr = ISDestroy(&patch->globalBcNodes);CHKERRQ(ierr);
2483   ierr = PetscSectionDestroy(&patch->gtolCountsWithArtificial);CHKERRQ(ierr);
2484   ierr = ISDestroy(&patch->gtolWithArtificial);CHKERRQ(ierr);
2485   ierr = ISDestroy(&patch->dofsWithArtificial);CHKERRQ(ierr);
2486   ierr = ISDestroy(&patch->offsWithArtificial);CHKERRQ(ierr);
2487   ierr = PetscSectionDestroy(&patch->gtolCountsWithAll);CHKERRQ(ierr);
2488   ierr = ISDestroy(&patch->gtolWithAll);CHKERRQ(ierr);
2489   ierr = ISDestroy(&patch->dofsWithAll);CHKERRQ(ierr);
2490   ierr = ISDestroy(&patch->offsWithAll);CHKERRQ(ierr);
2491 
2492 
2493   if (patch->dofSection) for (i = 0; i < patch->nsubspaces; i++) {ierr = PetscSectionDestroy(&patch->dofSection[i]);CHKERRQ(ierr);}
2494   ierr = PetscFree(patch->dofSection);CHKERRQ(ierr);
2495   ierr = PetscFree(patch->bs);CHKERRQ(ierr);
2496   ierr = PetscFree(patch->nodesPerCell);CHKERRQ(ierr);
2497   if (patch->cellNodeMap) for (i = 0; i < patch->nsubspaces; i++) {ierr = PetscFree(patch->cellNodeMap[i]);CHKERRQ(ierr);}
2498   ierr = PetscFree(patch->cellNodeMap);CHKERRQ(ierr);
2499   ierr = PetscFree(patch->subspaceOffsets);CHKERRQ(ierr);
2500 
2501   ierr = (*patch->resetsolver)(pc);CHKERRQ(ierr);
2502 
2503   if (patch->subspaces_to_exclude) {
2504     PetscHSetIDestroy(&patch->subspaces_to_exclude);
2505   }
2506 
2507   ierr = VecDestroy(&patch->localRHS);CHKERRQ(ierr);
2508   ierr = VecDestroy(&patch->localUpdate);CHKERRQ(ierr);
2509   if (patch->patchRHS) {
2510     for (i = 0; i < patch->npatch; ++i) {ierr = VecDestroy(&patch->patchRHS[i]);CHKERRQ(ierr);}
2511     ierr = PetscFree(patch->patchRHS);CHKERRQ(ierr);
2512   }
2513   if (patch->patchUpdate) {
2514     for (i = 0; i < patch->npatch; ++i) {ierr = VecDestroy(&patch->patchUpdate[i]);CHKERRQ(ierr);}
2515     ierr = PetscFree(patch->patchUpdate);CHKERRQ(ierr);
2516   }
2517   ierr = VecDestroy(&patch->dof_weights);CHKERRQ(ierr);
2518   if (patch->patch_dof_weights) {
2519     for (i = 0; i < patch->npatch; ++i) {ierr = VecDestroy(&patch->patch_dof_weights[i]);CHKERRQ(ierr);}
2520     ierr = PetscFree(patch->patch_dof_weights);CHKERRQ(ierr);
2521   }
2522   if (patch->mat) {
2523     for (i = 0; i < patch->npatch; ++i) {ierr = MatDestroy(&patch->mat[i]);CHKERRQ(ierr);}
2524     ierr = PetscFree(patch->mat);CHKERRQ(ierr);
2525   }
2526   if (patch->matWithArtificial) {
2527     for (i = 0; i < patch->npatch; ++i) {ierr = MatDestroy(&patch->matWithArtificial[i]);CHKERRQ(ierr);}
2528     ierr = PetscFree(patch->matWithArtificial);CHKERRQ(ierr);
2529   }
2530   if (patch->patchRHSWithArtificial) {
2531     for (i = 0; i < patch->npatch; ++i) {ierr = VecDestroy(&patch->patchRHSWithArtificial[i]);CHKERRQ(ierr);}
2532     ierr = PetscFree(patch->patchRHSWithArtificial);CHKERRQ(ierr);
2533   }
2534   if(patch->dofMappingWithoutToWithArtificial) {
2535     for (i = 0; i < patch->npatch; ++i) {ierr = ISDestroy(&patch->dofMappingWithoutToWithArtificial[i]);CHKERRQ(ierr);}
2536     ierr = PetscFree(patch->dofMappingWithoutToWithArtificial);CHKERRQ(ierr);
2537 
2538   }
2539   if(patch->dofMappingWithoutToWithAll) {
2540     for (i = 0; i < patch->npatch; ++i) {ierr = ISDestroy(&patch->dofMappingWithoutToWithAll[i]);CHKERRQ(ierr);}
2541     ierr = PetscFree(patch->dofMappingWithoutToWithAll);CHKERRQ(ierr);
2542 
2543   }
2544   ierr = PetscFree(patch->sub_mat_type);CHKERRQ(ierr);
2545   if (patch->userIS) {
2546     for (i = 0; i < patch->npatch; ++i) {ierr = ISDestroy(&patch->userIS[i]);CHKERRQ(ierr);}
2547     ierr = PetscFree(patch->userIS);CHKERRQ(ierr);
2548   }
2549   patch->bs          = 0;
2550   patch->cellNodeMap = NULL;
2551   patch->nsubspaces  = 0;
2552   ierr = ISDestroy(&patch->iterationSet);CHKERRQ(ierr);
2553 
2554   ierr = PetscViewerDestroy(&patch->viewerSection);CHKERRQ(ierr);
2555   PetscFunctionReturn(0);
2556 }
2557 
2558 static PetscErrorCode PCDestroy_PATCH_Linear(PC pc)
2559 {
2560   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2561   PetscInt       i;
2562   PetscErrorCode ierr;
2563 
2564   PetscFunctionBegin;
2565   if (patch->solver) {
2566     for (i = 0; i < patch->npatch; ++i) {ierr = KSPDestroy((KSP *) &patch->solver[i]);CHKERRQ(ierr);}
2567     ierr = PetscFree(patch->solver);CHKERRQ(ierr);
2568   }
2569   PetscFunctionReturn(0);
2570 }
2571 
2572 static PetscErrorCode PCDestroy_PATCH(PC pc)
2573 {
2574   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2575   PetscErrorCode ierr;
2576 
2577   PetscFunctionBegin;
2578   ierr = PCReset_PATCH(pc);CHKERRQ(ierr);
2579   ierr = (*patch->destroysolver)(pc);CHKERRQ(ierr);
2580   ierr = PetscFree(pc->data);CHKERRQ(ierr);
2581   PetscFunctionReturn(0);
2582 }
2583 
2584 static PetscErrorCode PCSetFromOptions_PATCH(PetscOptionItems *PetscOptionsObject, PC pc)
2585 {
2586   PC_PATCH            *patch = (PC_PATCH *) pc->data;
2587   PCPatchConstructType patchConstructionType = PC_PATCH_STAR;
2588   char                 sub_mat_type[PETSC_MAX_PATH_LEN];
2589   char                 option[PETSC_MAX_PATH_LEN];
2590   const char          *prefix;
2591   PetscBool            flg, dimflg, codimflg;
2592   MPI_Comm             comm;
2593   PetscInt            *ifields, nfields, k;
2594   PetscErrorCode       ierr;
2595   PCCompositeType loctype = PC_COMPOSITE_ADDITIVE;
2596 
2597   PetscFunctionBegin;
2598   ierr = PetscObjectGetComm((PetscObject) pc, &comm);CHKERRQ(ierr);
2599   ierr = PetscObjectGetOptionsPrefix((PetscObject) pc, &prefix);CHKERRQ(ierr);
2600   ierr = PetscOptionsHead(PetscOptionsObject, "Patch solver options");CHKERRQ(ierr);
2601 
2602   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_save_operators", patch->classname);
2603   ierr = PetscOptionsBool(option,  "Store all patch operators for lifetime of object?", "PCPatchSetSaveOperators", patch->save_operators, &patch->save_operators, &flg);CHKERRQ(ierr);
2604 
2605   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_partition_of_unity", patch->classname);
2606   ierr = PetscOptionsBool(option, "Weight contributions by dof multiplicity?", "PCPatchSetPartitionOfUnity", patch->partition_of_unity, &patch->partition_of_unity, &flg);CHKERRQ(ierr);
2607 
2608   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_local_type", patch->classname);
2609   ierr = PetscOptionsEnum(option,"Type of local solver composition (additive or multiplicative)","PCPatchSetLocalComposition",PCCompositeTypes,(PetscEnum)loctype,(PetscEnum*)&loctype,&flg);CHKERRQ(ierr);
2610   if(flg) { ierr = PCPatchSetLocalComposition(pc, loctype);CHKERRQ(ierr);}
2611 
2612   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_construct_dim", patch->classname);
2613   ierr = PetscOptionsInt(option, "What dimension of mesh point to construct patches by? (0 = vertices)", "PCPATCH", patch->dim, &patch->dim, &dimflg);CHKERRQ(ierr);
2614   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_construct_codim", patch->classname);
2615   ierr = PetscOptionsInt(option, "What co-dimension of mesh point to construct patches by? (0 = cells)", "PCPATCH", patch->codim, &patch->codim, &codimflg);CHKERRQ(ierr);
2616   if (dimflg && codimflg) {SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Can only set one of dimension or co-dimension");CHKERRQ(ierr);}
2617 
2618   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_construct_type", patch->classname);
2619   ierr = PetscOptionsEnum(option, "How should the patches be constructed?", "PCPatchSetConstructType", PCPatchConstructTypes, (PetscEnum) patchConstructionType, (PetscEnum *) &patchConstructionType, &flg);CHKERRQ(ierr);
2620   if (flg) {ierr = PCPatchSetConstructType(pc, patchConstructionType, NULL, NULL);CHKERRQ(ierr);}
2621 
2622   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_vanka_dim", patch->classname);
2623   ierr = PetscOptionsInt(option, "Topological dimension of entities for Vanka to ignore", "PCPATCH", patch->vankadim, &patch->vankadim, &flg);CHKERRQ(ierr);
2624 
2625   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_ignore_dim", patch->classname);
2626   ierr = PetscOptionsInt(option, "Topological dimension of entities for completion to ignore", "PCPATCH", patch->ignoredim, &patch->ignoredim, &flg);CHKERRQ(ierr);
2627 
2628   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_pardecomp_overlap", patch->classname);
2629   ierr = PetscOptionsInt(option, "What overlap should we use in construct type pardecomp?", "PCPATCH", patch->pardecomp_overlap, &patch->pardecomp_overlap, &flg);CHKERRQ(ierr);
2630 
2631   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_sub_mat_type", patch->classname);
2632   ierr = PetscOptionsFList(option, "Matrix type for patch solves", "PCPatchSetSubMatType", MatList, NULL, sub_mat_type, PETSC_MAX_PATH_LEN, &flg);CHKERRQ(ierr);
2633   if (flg) {ierr = PCPatchSetSubMatType(pc, sub_mat_type);CHKERRQ(ierr);}
2634 
2635   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_symmetrise_sweep", patch->classname);
2636   ierr = PetscOptionsBool(option, "Go start->end, end->start?", "PCPATCH", patch->symmetrise_sweep, &patch->symmetrise_sweep, &flg);CHKERRQ(ierr);
2637 
2638   /* If the user has set the number of subspaces, use that for the buffer size,
2639      otherwise use a large number */
2640   if (patch->nsubspaces <= 0) {
2641     nfields = 128;
2642   } else {
2643     nfields = patch->nsubspaces;
2644   }
2645   ierr = PetscMalloc1(nfields, &ifields);CHKERRQ(ierr);
2646   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_exclude_subspaces", patch->classname);
2647   ierr = PetscOptionsGetIntArray(((PetscObject)pc)->options,((PetscObject)pc)->prefix,option,ifields,&nfields,&flg);CHKERRQ(ierr);
2648   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");
2649   if (flg) {
2650     PetscHSetIClear(patch->subspaces_to_exclude);
2651     for (k = 0; k < nfields; k++) {
2652       PetscHSetIAdd(patch->subspaces_to_exclude, ifields[k]);
2653     }
2654   }
2655   ierr = PetscFree(ifields);CHKERRQ(ierr);
2656 
2657   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_patches_view", patch->classname);CHKERRQ(ierr);
2658   ierr = PetscOptionsBool(option, "Print out information during patch construction", "PCPATCH", patch->viewPatches, &patch->viewPatches, &flg);CHKERRQ(ierr);
2659   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_cells_view", patch->classname);CHKERRQ(ierr);
2660   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options, prefix, option, &patch->viewerCells, &patch->formatCells, &patch->viewCells);CHKERRQ(ierr);
2661   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_interior_facets_view", patch->classname);CHKERRQ(ierr);
2662   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options, prefix, option, &patch->viewerIntFacets, &patch->formatIntFacets, &patch->viewIntFacets);CHKERRQ(ierr);
2663   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_exterior_facets_view", patch->classname);CHKERRQ(ierr);
2664   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options, prefix, option, &patch->viewerExtFacets, &patch->formatExtFacets, &patch->viewExtFacets);CHKERRQ(ierr);
2665   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_points_view", patch->classname);CHKERRQ(ierr);
2666   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options, prefix, option, &patch->viewerPoints, &patch->formatPoints, &patch->viewPoints);CHKERRQ(ierr);
2667   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_section_view", patch->classname);CHKERRQ(ierr);
2668   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options, prefix, option, &patch->viewerSection, &patch->formatSection, &patch->viewSection);CHKERRQ(ierr);
2669   ierr = PetscSNPrintf(option, PETSC_MAX_PATH_LEN, "-%s_patch_mat_view", patch->classname);CHKERRQ(ierr);
2670   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options, prefix, option, &patch->viewerMatrix, &patch->formatMatrix, &patch->viewMatrix);CHKERRQ(ierr);
2671   ierr = PetscOptionsTail();CHKERRQ(ierr);
2672   patch->optionsSet = PETSC_TRUE;
2673   PetscFunctionReturn(0);
2674 }
2675 
2676 static PetscErrorCode PCSetUpOnBlocks_PATCH(PC pc)
2677 {
2678   PC_PATCH          *patch = (PC_PATCH*) pc->data;
2679   KSPConvergedReason reason;
2680   PetscInt           i;
2681   PetscErrorCode     ierr;
2682 
2683   PetscFunctionBegin;
2684   if (!patch->save_operators) {
2685     /* Can't do this here because the sub KSPs don't have an operator attached yet. */
2686     PetscFunctionReturn(0);
2687   }
2688   for (i = 0; i < patch->npatch; ++i) {
2689     if (!((KSP) patch->solver[i])->setfromoptionscalled) {
2690       ierr = KSPSetFromOptions((KSP) patch->solver[i]);CHKERRQ(ierr);
2691     }
2692     ierr = KSPSetUp((KSP) patch->solver[i]);CHKERRQ(ierr);
2693     ierr = KSPGetConvergedReason((KSP) patch->solver[i], &reason);CHKERRQ(ierr);
2694     if (reason == KSP_DIVERGED_PC_FAILED) pc->failedreason = PC_SUBPC_ERROR;
2695   }
2696   PetscFunctionReturn(0);
2697 }
2698 
2699 static PetscErrorCode PCView_PATCH(PC pc, PetscViewer viewer)
2700 {
2701   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2702   PetscViewer    sviewer;
2703   PetscBool      isascii;
2704   PetscMPIInt    rank;
2705   PetscErrorCode ierr;
2706 
2707   PetscFunctionBegin;
2708   /* TODO Redo tabbing with set tbas in new style */
2709   ierr = PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);CHKERRQ(ierr);
2710   if (!isascii) PetscFunctionReturn(0);
2711   ierr = MPI_Comm_rank(PetscObjectComm((PetscObject) pc), &rank);CHKERRQ(ierr);
2712   ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
2713   ierr = PetscViewerASCIIPrintf(viewer, "Subspace Correction preconditioner with %d patches\n", patch->npatch);CHKERRQ(ierr);
2714   if(patch->local_composition_type == PC_COMPOSITE_MULTIPLICATIVE) {
2715     ierr = PetscViewerASCIIPrintf(viewer, "Schwarz type: multiplicative\n");CHKERRQ(ierr);
2716   } else {
2717     ierr = PetscViewerASCIIPrintf(viewer, "Schwarz type: additive\n");CHKERRQ(ierr);
2718   }
2719   if (patch->partition_of_unity) {ierr = PetscViewerASCIIPrintf(viewer, "Weighting by partition of unity\n");CHKERRQ(ierr);}
2720   else                           {ierr = PetscViewerASCIIPrintf(viewer, "Not weighting by partition of unity\n");CHKERRQ(ierr);}
2721   if (patch->symmetrise_sweep) {ierr = PetscViewerASCIIPrintf(viewer, "Symmetrising sweep (start->end, then end->start)\n");CHKERRQ(ierr);}
2722   else                         {ierr = PetscViewerASCIIPrintf(viewer, "Not symmetrising sweep\n");CHKERRQ(ierr);}
2723   if (!patch->save_operators) {ierr = PetscViewerASCIIPrintf(viewer, "Not saving patch operators (rebuilt every PCApply)\n");CHKERRQ(ierr);}
2724   else                        {ierr = PetscViewerASCIIPrintf(viewer, "Saving patch operators (rebuilt every PCSetUp)\n");CHKERRQ(ierr);}
2725   if (patch->patchconstructop == PCPatchConstruct_Star)       {ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: star\n");CHKERRQ(ierr);}
2726   else if (patch->patchconstructop == PCPatchConstruct_Vanka) {ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: Vanka\n");CHKERRQ(ierr);}
2727   else if (patch->patchconstructop == PCPatchConstruct_User)  {ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: user-specified\n");CHKERRQ(ierr);}
2728   else                                                        {ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: unknown\n");CHKERRQ(ierr);}
2729 
2730   if (patch->isNonlinear) {
2731     ierr = PetscViewerASCIIPrintf(viewer, "SNES on patches (all same):\n");CHKERRQ(ierr);
2732   } else {
2733     ierr = PetscViewerASCIIPrintf(viewer, "KSP on patches (all same):\n");CHKERRQ(ierr);
2734   }
2735   if (patch->solver) {
2736     ierr = PetscViewerGetSubViewer(viewer, PETSC_COMM_SELF, &sviewer);CHKERRQ(ierr);
2737     if (!rank) {
2738       ierr = PetscViewerASCIIPushTab(sviewer);CHKERRQ(ierr);
2739       ierr = PetscObjectView(patch->solver[0], sviewer);CHKERRQ(ierr);
2740       ierr = PetscViewerASCIIPopTab(sviewer);CHKERRQ(ierr);
2741     }
2742     ierr = PetscViewerRestoreSubViewer(viewer, PETSC_COMM_SELF, &sviewer);CHKERRQ(ierr);
2743   } else {
2744     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
2745     ierr = PetscViewerASCIIPrintf(viewer, "Solver not yet set.\n");CHKERRQ(ierr);
2746     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
2747   }
2748   ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
2749   PetscFunctionReturn(0);
2750 }
2751 
2752 /*MC
2753   PCPATCH - A PC object that encapsulates flexible definition of blocks for overlapping and non-overlapping
2754             small block additive preconditioners. Block definition is based on topology from
2755             a DM and equation numbering from a PetscSection.
2756 
2757   Options Database Keys:
2758 + -pc_patch_cells_view   - Views the process local cell numbers for each patch
2759 . -pc_patch_points_view  - Views the process local mesh point numbers for each patch
2760 . -pc_patch_g2l_view     - Views the map between global dofs and patch local dofs for each patch
2761 . -pc_patch_patches_view - Views the global dofs associated with each patch and its boundary
2762 - -pc_patch_sub_mat_view - Views the matrix associated with each patch
2763 
2764   Level: intermediate
2765 
2766 .seealso: PCType, PCCreate(), PCSetType()
2767 M*/
2768 PETSC_EXTERN PetscErrorCode PCCreate_Patch(PC pc)
2769 {
2770   PC_PATCH      *patch;
2771   PetscErrorCode ierr;
2772 
2773   PetscFunctionBegin;
2774   ierr = PetscNewLog(pc, &patch);CHKERRQ(ierr);
2775 
2776   if (patch->subspaces_to_exclude) {
2777     PetscHSetIDestroy(&patch->subspaces_to_exclude);
2778   }
2779   PetscHSetICreate(&patch->subspaces_to_exclude);
2780 
2781   patch->classname = "pc";
2782   patch->isNonlinear = PETSC_FALSE;
2783 
2784   /* Set some defaults */
2785   patch->combined           = PETSC_FALSE;
2786   patch->save_operators     = PETSC_TRUE;
2787   patch->local_composition_type = PC_COMPOSITE_ADDITIVE;
2788   patch->partition_of_unity = PETSC_FALSE;
2789   patch->codim              = -1;
2790   patch->dim                = -1;
2791   patch->vankadim           = -1;
2792   patch->ignoredim          = -1;
2793   patch->pardecomp_overlap  = 0;
2794   patch->patchconstructop   = PCPatchConstruct_Star;
2795   patch->symmetrise_sweep   = PETSC_FALSE;
2796   patch->npatch             = 0;
2797   patch->userIS             = NULL;
2798   patch->optionsSet         = PETSC_FALSE;
2799   patch->iterationSet       = NULL;
2800   patch->user_patches       = PETSC_FALSE;
2801   ierr = PetscStrallocpy(MATDENSE, (char **) &patch->sub_mat_type);CHKERRQ(ierr);
2802   patch->viewPatches        = PETSC_FALSE;
2803   patch->viewCells          = PETSC_FALSE;
2804   patch->viewPoints         = PETSC_FALSE;
2805   patch->viewSection        = PETSC_FALSE;
2806   patch->viewMatrix         = PETSC_FALSE;
2807   patch->setupsolver        = PCSetUp_PATCH_Linear;
2808   patch->applysolver        = PCApply_PATCH_Linear;
2809   patch->resetsolver        = PCReset_PATCH_Linear;
2810   patch->destroysolver      = PCDestroy_PATCH_Linear;
2811   patch->updatemultiplicative = PCUpdateMultiplicative_PATCH_Linear;
2812   patch->dofMappingWithoutToWithArtificial = NULL;
2813   patch->dofMappingWithoutToWithAll = NULL;
2814 
2815   pc->data                 = (void *) patch;
2816   pc->ops->apply           = PCApply_PATCH;
2817   pc->ops->applytranspose  = 0; /* PCApplyTranspose_PATCH; */
2818   pc->ops->setup           = PCSetUp_PATCH;
2819   pc->ops->reset           = PCReset_PATCH;
2820   pc->ops->destroy         = PCDestroy_PATCH;
2821   pc->ops->setfromoptions  = PCSetFromOptions_PATCH;
2822   pc->ops->setuponblocks   = PCSetUpOnBlocks_PATCH;
2823   pc->ops->view            = PCView_PATCH;
2824   pc->ops->applyrichardson = 0;
2825 
2826   PetscFunctionReturn(0);
2827 }
2828