xref: /petsc/src/ksp/pc/impls/patch/pcpatch.c (revision bc6a89d73dbf56b65c2d7efe9d5cd6a8a1733b62)
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 /* The user's already set the patches in patch->userIS. Build the hash tables */
80 static PetscErrorCode PCPatchConstruct_User(void *vpatch, DM dm, PetscInt point, PetscHSetI ht)
81 {
82   PC_PATCH       *patch   = (PC_PATCH *) vpatch;
83   IS              patchis = patch->userIS[point];
84   PetscInt        n;
85   const PetscInt *patchdata;
86   PetscInt        pStart, pEnd, i;
87   PetscErrorCode  ierr;
88 
89   PetscFunctionBegin;
90   ierr = PetscHSetIClear(ht);CHKERRQ(ierr);
91   ierr = DMPlexGetChart(dm, &pStart, &pEnd);CHKERRQ(ierr);
92   ierr = ISGetLocalSize(patchis, &n);CHKERRQ(ierr);
93   ierr = ISGetIndices(patchis, &patchdata);CHKERRQ(ierr);
94   for (i = 0; i < n; ++i) {
95     const PetscInt ownedpoint = patchdata[i];
96 
97     if (ownedpoint < pStart || ownedpoint >= pEnd) {
98       SETERRQ3(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_OUTOFRANGE, "Mesh point %D was not in [%D, %D)", ownedpoint, pStart, pEnd);
99     }
100     ierr = PetscHSetIAdd(ht, ownedpoint);CHKERRQ(ierr);
101   }
102   ierr = ISRestoreIndices(patchis, &patchdata);CHKERRQ(ierr);
103   PetscFunctionReturn(0);
104 }
105 
106 static PetscErrorCode PCPatchCreateDefaultSF_Private(PC pc, PetscInt n, const PetscSF *sf, const PetscInt *bs)
107 {
108   PC_PATCH      *patch = (PC_PATCH *) pc->data;
109   PetscInt       i;
110   PetscErrorCode ierr;
111 
112   PetscFunctionBegin;
113   if (n == 1 && bs[0] == 1) {
114     patch->defaultSF = sf[0];
115     ierr = PetscObjectReference((PetscObject) patch->defaultSF);CHKERRQ(ierr);
116   } else {
117     PetscInt     allRoots = 0, allLeaves = 0;
118     PetscInt     leafOffset = 0;
119     PetscInt    *ilocal = NULL;
120     PetscSFNode *iremote = NULL;
121     PetscInt    *remoteOffsets = NULL;
122     PetscInt     index = 0;
123     PetscHMapI   rankToIndex;
124     PetscInt     numRanks = 0;
125     PetscSFNode *remote = NULL;
126     PetscSF      rankSF;
127     PetscInt    *ranks = NULL;
128     PetscInt    *offsets = NULL;
129     MPI_Datatype contig;
130     PetscHSetI   ranksUniq;
131 
132     /* First figure out how many dofs there are in the concatenated numbering.
133      * allRoots: number of owned global dofs;
134      * allLeaves: number of visible dofs (global + ghosted).
135      */
136     for (i = 0; i < n; ++i) {
137       PetscInt nroots, nleaves;
138 
139       ierr = PetscSFGetGraph(sf[i], &nroots, &nleaves, NULL, NULL);CHKERRQ(ierr);
140       allRoots  += nroots * bs[i];
141       allLeaves += nleaves * bs[i];
142     }
143     ierr = PetscMalloc1(allLeaves, &ilocal);CHKERRQ(ierr);
144     ierr = PetscMalloc1(allLeaves, &iremote);CHKERRQ(ierr);
145     /* Now build an SF that just contains process connectivity. */
146     ierr = PetscHSetICreate(&ranksUniq);CHKERRQ(ierr);
147     for (i = 0; i < n; ++i) {
148       const PetscMPIInt *ranks = NULL;
149       PetscInt           nranks, j;
150 
151       ierr = PetscSFSetUp(sf[i]);CHKERRQ(ierr);
152       ierr = PetscSFGetRanks(sf[i], &nranks, &ranks, NULL, NULL, NULL);CHKERRQ(ierr);
153       /* These are all the ranks who communicate with me. */
154       for (j = 0; j < nranks; ++j) {
155         ierr = PetscHSetIAdd(ranksUniq, (PetscInt) ranks[j]);CHKERRQ(ierr);
156       }
157     }
158     ierr = PetscHSetIGetSize(ranksUniq, &numRanks);CHKERRQ(ierr);
159     ierr = PetscMalloc1(numRanks, &remote);CHKERRQ(ierr);
160     ierr = PetscMalloc1(numRanks, &ranks);CHKERRQ(ierr);
161     ierr = PetscHSetIGetElems(ranksUniq, &index, ranks);CHKERRQ(ierr);
162 
163     ierr = PetscHMapICreate(&rankToIndex);CHKERRQ(ierr);
164     for (i = 0; i < numRanks; ++i) {
165       remote[i].rank  = ranks[i];
166       remote[i].index = 0;
167       ierr = PetscHMapISet(rankToIndex, ranks[i], i);CHKERRQ(ierr);
168     }
169     ierr = PetscFree(ranks);CHKERRQ(ierr);
170     ierr = PetscHSetIDestroy(&ranksUniq);CHKERRQ(ierr);
171     ierr = PetscSFCreate(PetscObjectComm((PetscObject) pc), &rankSF);CHKERRQ(ierr);
172     ierr = PetscSFSetGraph(rankSF, 1, numRanks, NULL, PETSC_OWN_POINTER, remote, PETSC_OWN_POINTER);CHKERRQ(ierr);
173     ierr = PetscSFSetUp(rankSF);CHKERRQ(ierr);
174     /* OK, use it to communicate the root offset on the remote
175      * processes for each subspace. */
176     ierr = PetscMalloc1(n, &offsets);CHKERRQ(ierr);
177     ierr = PetscMalloc1(n*numRanks, &remoteOffsets);CHKERRQ(ierr);
178 
179     offsets[0] = 0;
180     for (i = 1; i < n; ++i) {
181       PetscInt nroots;
182 
183       ierr = PetscSFGetGraph(sf[i-1], &nroots, NULL, NULL, NULL);CHKERRQ(ierr);
184       offsets[i] = offsets[i-1] + nroots*bs[i-1];
185     }
186     /* Offsets are the offsets on the current process of the
187      * global dof numbering for the subspaces. */
188     ierr = MPI_Type_contiguous(n, MPIU_INT, &contig);CHKERRQ(ierr);
189     ierr = MPI_Type_commit(&contig);CHKERRQ(ierr);
190 
191     ierr = PetscSFBcastBegin(rankSF, contig, offsets, remoteOffsets);CHKERRQ(ierr);
192     ierr = PetscSFBcastEnd(rankSF, contig, offsets, remoteOffsets);CHKERRQ(ierr);
193     ierr = MPI_Type_free(&contig);CHKERRQ(ierr);
194     ierr = PetscFree(offsets);CHKERRQ(ierr);
195     ierr = PetscSFDestroy(&rankSF);CHKERRQ(ierr);
196     /* Now remoteOffsets contains the offsets on the remote
197      * processes who communicate with me.  So now we can
198      * concatenate the list of SFs into a single one. */
199     index = 0;
200     for (i = 0; i < n; ++i) {
201       const PetscSFNode *remote = NULL;
202       const PetscInt    *local  = NULL;
203       PetscInt           nroots, nleaves, j;
204 
205       ierr = PetscSFGetGraph(sf[i], &nroots, &nleaves, &local, &remote);CHKERRQ(ierr);
206       for (j = 0; j < nleaves; ++j) {
207         PetscInt rank = remote[j].rank;
208         PetscInt idx, rootOffset, k;
209 
210         ierr = PetscHMapIGet(rankToIndex, rank, &idx);CHKERRQ(ierr);
211         if (idx == -1) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Didn't find rank, huh?");
212         /* Offset on given rank for ith subspace */
213         rootOffset = remoteOffsets[n*idx + i];
214         for (k = 0; k < bs[i]; ++k) {
215           ilocal[index]        = (local ? local[j] : j)*bs[i] + k + leafOffset;
216           iremote[index].rank  = remote[j].rank;
217           iremote[index].index = remote[j].index*bs[i] + k + rootOffset;
218           ++index;
219         }
220       }
221       leafOffset += nleaves * bs[i];
222     }
223     ierr = PetscHMapIDestroy(&rankToIndex);CHKERRQ(ierr);
224     ierr = PetscFree(remoteOffsets);CHKERRQ(ierr);
225     ierr = PetscSFCreate(PetscObjectComm((PetscObject)pc), &patch->defaultSF);CHKERRQ(ierr);
226     ierr = PetscSFSetGraph(patch->defaultSF, allRoots, allLeaves, ilocal, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER);CHKERRQ(ierr);
227   }
228   PetscFunctionReturn(0);
229 }
230 
231 /* TODO: Docs */
232 PetscErrorCode PCPatchSetIgnoreDim(PC pc, PetscInt dim)
233 {
234   PC_PATCH *patch = (PC_PATCH *) pc->data;
235   PetscFunctionBegin;
236   patch->ignoredim = dim;
237   PetscFunctionReturn(0);
238 }
239 
240 /* TODO: Docs */
241 PetscErrorCode PCPatchGetIgnoreDim(PC pc, PetscInt *dim)
242 {
243   PC_PATCH *patch = (PC_PATCH *) pc->data;
244   PetscFunctionBegin;
245   *dim = patch->ignoredim;
246   PetscFunctionReturn(0);
247 }
248 
249 /* TODO: Docs */
250 PetscErrorCode PCPatchSetSaveOperators(PC pc, PetscBool flg)
251 {
252   PC_PATCH *patch = (PC_PATCH *) pc->data;
253   PetscFunctionBegin;
254   patch->save_operators = flg;
255   PetscFunctionReturn(0);
256 }
257 
258 /* TODO: Docs */
259 PetscErrorCode PCPatchGetSaveOperators(PC pc, PetscBool *flg)
260 {
261   PC_PATCH *patch = (PC_PATCH *) pc->data;
262   PetscFunctionBegin;
263   *flg = patch->save_operators;
264   PetscFunctionReturn(0);
265 }
266 
267 /* TODO: Docs */
268 PetscErrorCode PCPatchSetPartitionOfUnity(PC pc, PetscBool flg)
269 {
270     PC_PATCH *patch = (PC_PATCH *) pc->data;
271     PetscFunctionBegin;
272     patch->partition_of_unity = flg;
273     PetscFunctionReturn(0);
274 }
275 
276 /* TODO: Docs */
277 PetscErrorCode PCPatchGetPartitionOfUnity(PC pc, PetscBool *flg)
278 {
279     PC_PATCH *patch = (PC_PATCH *) pc->data;
280     PetscFunctionBegin;
281     *flg = patch->partition_of_unity;
282     PetscFunctionReturn(0);
283 }
284 
285 /* TODO: Docs */
286 PetscErrorCode PCPatchSetMultiplicative(PC pc, PetscBool flg)
287 {
288   PC_PATCH *patch = (PC_PATCH *) pc->data;
289   PetscFunctionBegin;
290   patch->multiplicative = flg;
291   PetscFunctionReturn(0);
292 }
293 
294 /* TODO: Docs */
295 PetscErrorCode PCPatchGetMultiplicative(PC pc, PetscBool *flg)
296 {
297   PC_PATCH *patch = (PC_PATCH *) pc->data;
298   PetscFunctionBegin;
299   *flg = patch->multiplicative;
300   PetscFunctionReturn(0);
301 }
302 
303 /* TODO: Docs */
304 PetscErrorCode PCPatchSetSubMatType(PC pc, MatType sub_mat_type)
305 {
306   PC_PATCH      *patch = (PC_PATCH *) pc->data;
307   PetscErrorCode ierr;
308 
309   PetscFunctionBegin;
310   if (patch->sub_mat_type) {ierr = PetscFree(patch->sub_mat_type);CHKERRQ(ierr);}
311   ierr = PetscStrallocpy(sub_mat_type, (char **) &patch->sub_mat_type);CHKERRQ(ierr);
312   PetscFunctionReturn(0);
313 }
314 
315 /* TODO: Docs */
316 PetscErrorCode PCPatchGetSubMatType(PC pc, MatType *sub_mat_type)
317 {
318   PC_PATCH *patch = (PC_PATCH *) pc->data;
319   PetscFunctionBegin;
320   *sub_mat_type = patch->sub_mat_type;
321   PetscFunctionReturn(0);
322 }
323 
324 /* TODO: Docs */
325 PetscErrorCode PCPatchSetCellNumbering(PC pc, PetscSection cellNumbering)
326 {
327   PC_PATCH      *patch = (PC_PATCH *) pc->data;
328   PetscErrorCode ierr;
329 
330   PetscFunctionBegin;
331   patch->cellNumbering = cellNumbering;
332   ierr = PetscObjectReference((PetscObject) cellNumbering);CHKERRQ(ierr);
333   PetscFunctionReturn(0);
334 }
335 
336 /* TODO: Docs */
337 PetscErrorCode PCPatchGetCellNumbering(PC pc, PetscSection *cellNumbering)
338 {
339   PC_PATCH *patch = (PC_PATCH *) pc->data;
340   PetscFunctionBegin;
341   *cellNumbering = patch->cellNumbering;
342   PetscFunctionReturn(0);
343 }
344 
345 /* TODO: Docs */
346 PetscErrorCode PCPatchSetConstructType(PC pc, PCPatchConstructType ctype, PetscErrorCode (*func)(PC, PetscInt *, IS **, IS *, void *), void *ctx)
347 {
348   PC_PATCH *patch = (PC_PATCH *) pc->data;
349 
350   PetscFunctionBegin;
351   patch->ctype = ctype;
352   switch (ctype) {
353   case PC_PATCH_STAR:
354     patch->user_patches     = PETSC_FALSE;
355     patch->patchconstructop = PCPatchConstruct_Star;
356     break;
357   case PC_PATCH_VANKA:
358     patch->user_patches     = PETSC_FALSE;
359     patch->patchconstructop = PCPatchConstruct_Vanka;
360     break;
361   case PC_PATCH_USER:
362   case PC_PATCH_PYTHON:
363     patch->user_patches     = PETSC_TRUE;
364     patch->patchconstructop = PCPatchConstruct_User;
365     if (func) {
366       patch->userpatchconstructionop = func;
367       patch->userpatchconstructctx   = ctx;
368     }
369     break;
370   default:
371     SETERRQ1(PetscObjectComm((PetscObject) pc), PETSC_ERR_USER, "Unknown patch construction type %D", (PetscInt) patch->ctype);
372   }
373   PetscFunctionReturn(0);
374 }
375 
376 /* TODO: Docs */
377 PetscErrorCode PCPatchGetConstructType(PC pc, PCPatchConstructType *ctype, PetscErrorCode (**func)(PC, PetscInt *, IS **, IS *, void *), void **ctx)
378 {
379   PC_PATCH *patch = (PC_PATCH *) pc->data;
380 
381   PetscFunctionBegin;
382   *ctype = patch->ctype;
383   switch (patch->ctype) {
384   case PC_PATCH_STAR:
385   case PC_PATCH_VANKA:
386     break;
387   case PC_PATCH_USER:
388   case PC_PATCH_PYTHON:
389     *func = patch->userpatchconstructionop;
390     *ctx  = patch->userpatchconstructctx;
391     break;
392   default:
393     SETERRQ1(PetscObjectComm((PetscObject) pc), PETSC_ERR_USER, "Unknown patch construction type %D", (PetscInt) patch->ctype);
394   }
395   PetscFunctionReturn(0);
396 }
397 
398 /* TODO: Docs */
399 PetscErrorCode PCPatchSetDiscretisationInfo(PC pc, PetscInt nsubspaces, DM *dms, PetscInt *bs, PetscInt *nodesPerCell, const PetscInt **cellNodeMap,
400                                             const PetscInt *subspaceOffsets, PetscInt numGhostBcs, const PetscInt *ghostBcNodes, PetscInt numGlobalBcs, const PetscInt *globalBcNodes)
401 {
402   PC_PATCH      *patch = (PC_PATCH *) pc->data;
403   DM             dm;
404   PetscSF       *sfs;
405   PetscInt       cStart, cEnd, i, j;
406   PetscErrorCode ierr;
407 
408   PetscFunctionBegin;
409   ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
410   ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);
411   ierr = PetscMalloc1(nsubspaces, &sfs);CHKERRQ(ierr);
412   ierr = PetscMalloc1(nsubspaces, &patch->dofSection);CHKERRQ(ierr);
413   ierr = PetscMalloc1(nsubspaces, &patch->bs);CHKERRQ(ierr);
414   ierr = PetscMalloc1(nsubspaces, &patch->nodesPerCell);CHKERRQ(ierr);
415   ierr = PetscMalloc1(nsubspaces, &patch->cellNodeMap);CHKERRQ(ierr);
416   ierr = PetscMalloc1(nsubspaces+1, &patch->subspaceOffsets);CHKERRQ(ierr);
417 
418   patch->nsubspaces       = nsubspaces;
419   patch->totalDofsPerCell = 0;
420   for (i = 0; i < nsubspaces; ++i) {
421     ierr = DMGetDefaultSection(dms[i], &patch->dofSection[i]);CHKERRQ(ierr);
422     ierr = PetscObjectReference((PetscObject) patch->dofSection[i]);CHKERRQ(ierr);
423     ierr = DMGetDefaultSF(dms[i], &sfs[i]);CHKERRQ(ierr);
424     patch->bs[i]              = bs[i];
425     patch->nodesPerCell[i]    = nodesPerCell[i];
426     patch->totalDofsPerCell  += nodesPerCell[i]*bs[i];
427     ierr = PetscMalloc1((cEnd-cStart)*nodesPerCell[i]*bs[i], &patch->cellNodeMap[i]);CHKERRQ(ierr);
428     for (j = 0; j < (cEnd-cStart)*nodesPerCell[i]*bs[i]; ++j) patch->cellNodeMap[i][j] = cellNodeMap[i][j];
429     patch->subspaceOffsets[i] = subspaceOffsets[i];
430   }
431   ierr = PCPatchCreateDefaultSF_Private(pc, nsubspaces, sfs, patch->bs);CHKERRQ(ierr);
432   ierr = PetscFree(sfs);CHKERRQ(ierr);
433 
434   patch->subspaceOffsets[nsubspaces] = subspaceOffsets[nsubspaces];
435   ierr = ISCreateGeneral(PETSC_COMM_SELF, numGhostBcs, ghostBcNodes, PETSC_COPY_VALUES, &patch->ghostBcNodes);CHKERRQ(ierr);
436   ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalBcs, globalBcNodes, PETSC_COPY_VALUES, &patch->globalBcNodes);CHKERRQ(ierr);
437   PetscFunctionReturn(0);
438 }
439 
440 /* TODO: Docs */
441 PetscErrorCode PCPatchSetDiscretisationInfoCombined(PC pc, DM dm, PetscInt *nodesPerCell, const PetscInt **cellNodeMap, PetscInt numGhostBcs, const PetscInt *ghostBcNodes, PetscInt numGlobalBcs, const PetscInt *globalBcNodes)
442 {
443   PC_PATCH      *patch = (PC_PATCH *) pc->data;
444   PetscInt       cStart, cEnd, i, j;
445   PetscErrorCode ierr;
446 
447   PetscFunctionBegin;
448   patch->combined = PETSC_TRUE;
449   ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);
450   ierr = DMGetNumFields(dm, &patch->nsubspaces);CHKERRQ(ierr);
451   ierr = PetscCalloc1(patch->nsubspaces, &patch->dofSection);CHKERRQ(ierr);
452   ierr = PetscMalloc1(patch->nsubspaces, &patch->bs);CHKERRQ(ierr);
453   ierr = PetscMalloc1(patch->nsubspaces, &patch->nodesPerCell);CHKERRQ(ierr);
454   ierr = PetscMalloc1(patch->nsubspaces, &patch->cellNodeMap);CHKERRQ(ierr);
455   ierr = PetscCalloc1(patch->nsubspaces+1, &patch->subspaceOffsets);CHKERRQ(ierr);
456   ierr = DMGetDefaultSection(dm, &patch->dofSection[0]);CHKERRQ(ierr);
457   ierr = PetscObjectReference((PetscObject) patch->dofSection[0]);CHKERRQ(ierr);
458   ierr = PetscSectionGetStorageSize(patch->dofSection[0], &patch->subspaceOffsets[patch->nsubspaces]);CHKERRQ(ierr);
459   patch->totalDofsPerCell = 0;
460   for (i = 0; i < patch->nsubspaces; ++i) {
461     patch->bs[i]             = 1;
462     patch->nodesPerCell[i]   = nodesPerCell[i];
463     patch->totalDofsPerCell += nodesPerCell[i];
464     ierr = PetscMalloc1((cEnd-cStart)*nodesPerCell[i], &patch->cellNodeMap[i]);CHKERRQ(ierr);
465     for (j = 0; j < (cEnd-cStart)*nodesPerCell[i]; ++j) patch->cellNodeMap[i][j] = cellNodeMap[i][j];
466   }
467   ierr = DMGetDefaultSF(dm, &patch->defaultSF);CHKERRQ(ierr);
468   ierr = PetscObjectReference((PetscObject) patch->defaultSF);CHKERRQ(ierr);
469   ierr = ISCreateGeneral(PETSC_COMM_SELF, numGhostBcs, ghostBcNodes, PETSC_COPY_VALUES, &patch->ghostBcNodes);CHKERRQ(ierr);
470   ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalBcs, globalBcNodes, PETSC_COPY_VALUES, &patch->globalBcNodes);CHKERRQ(ierr);
471   PetscFunctionReturn(0);
472 }
473 
474 /*@C
475 
476   PCPatchSetComputeOperator - Set the callback used to compute patch matrices
477 
478   Input Parameters:
479 + pc   - The PC
480 . func - The callback
481 - ctx  - The user context
482 
483   Level: advanced
484 
485   Note:
486   The callback has signature:
487 +  usercomputeop(pc, point, mat, cellIS, n, u, ctx)
488 +  pc     - The PC
489 +  point  - The point
490 +  mat    - The patch matrix
491 +  cellIS - An array of the cell numbers
492 +  n      - The size of g2l
493 +  g2l    - The global to local dof translation table
494 +  ctx    - The user context
495   and can assume that the matrix entries have been set to zero before the call.
496 
497 .seealso: PCPatchGetComputeOperator(), PCPatchSetDiscretisationInfo()
498 @*/
499 PetscErrorCode PCPatchSetComputeOperator(PC pc, PetscErrorCode (*func)(PC, PetscInt, Mat, IS, PetscInt, const PetscInt *, void *), void *ctx)
500 {
501   PC_PATCH *patch = (PC_PATCH *) pc->data;
502 
503   PetscFunctionBegin;
504   patch->usercomputeop  = func;
505   patch->usercomputectx = ctx;
506   PetscFunctionReturn(0);
507 }
508 
509 /* On entry, ht contains the topological entities whose dofs we are responsible for solving for;
510    on exit, cht contains all the topological entities we need to compute their residuals.
511    In full generality this should incorporate knowledge of the sparsity pattern of the matrix;
512    here we assume a standard FE sparsity pattern.*/
513 /* TODO: Use DMPlexGetAdjacency() */
514 static PetscErrorCode PCPatchCompleteCellPatch(PC pc, PetscHSetI ht, PetscHSetI cht)
515 {
516   DM             dm;
517   PetscHashIter  hi;
518   PetscInt       point;
519   PetscInt      *star = NULL, *closure = NULL;
520   PetscInt       ignoredim, iStart = 0, iEnd = -1, starSize, closureSize, si, ci;
521   PetscErrorCode ierr;
522 
523   PetscFunctionBegin;
524   ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
525   ierr = PCPatchGetIgnoreDim(pc, &ignoredim);CHKERRQ(ierr);
526   if (ignoredim >= 0) {ierr = DMPlexGetDepthStratum(dm, ignoredim, &iStart, &iEnd);CHKERRQ(ierr);}
527   ierr = PetscHSetIClear(cht);CHKERRQ(ierr);
528   PetscHashIterBegin(ht, hi);
529   while (!PetscHashIterAtEnd(ht, hi)) {
530 
531     PetscHashIterGetKey(ht, hi, point);
532     PetscHashIterNext(ht, hi);
533 
534     /* Loop over all the cells that this point connects to */
535     ierr = DMPlexGetTransitiveClosure(dm, point, PETSC_FALSE, &starSize, &star);CHKERRQ(ierr);
536     for (si = 0; si < starSize*2; si += 2) {
537       const PetscInt ownedpoint = star[si];
538       /* TODO Check for point in cht before running through closure again */
539       /* now loop over all entities in the closure of that cell */
540       ierr = DMPlexGetTransitiveClosure(dm, ownedpoint, PETSC_TRUE, &closureSize, &closure);CHKERRQ(ierr);
541       for (ci = 0; ci < closureSize*2; ci += 2) {
542         const PetscInt seenpoint = closure[ci];
543         if (ignoredim >= 0 && seenpoint >= iStart && seenpoint < iEnd) continue;
544         ierr = PetscHSetIAdd(cht, seenpoint);CHKERRQ(ierr);
545       }
546     }
547   }
548   ierr = DMPlexRestoreTransitiveClosure(dm, 0, PETSC_TRUE, NULL, &closure);CHKERRQ(ierr);
549   ierr = DMPlexRestoreTransitiveClosure(dm, 0, PETSC_FALSE, NULL, &star);CHKERRQ(ierr);
550   PetscFunctionReturn(0);
551 }
552 
553 static PetscErrorCode PCPatchGetGlobalDofs(PC pc, PetscSection dofSection[], PetscInt f, PetscBool combined, PetscInt p, PetscInt *dof, PetscInt *off)
554 {
555   PetscErrorCode ierr;
556 
557   PetscFunctionBegin;
558   if (combined) {
559     if (f < 0) {
560       if (dof) {ierr = PetscSectionGetDof(dofSection[0], p, dof);CHKERRQ(ierr);}
561       if (off) {ierr = PetscSectionGetOffset(dofSection[0], p, off);CHKERRQ(ierr);}
562     } else {
563       if (dof) {ierr = PetscSectionGetFieldDof(dofSection[0], p, f, dof);CHKERRQ(ierr);}
564       if (off) {ierr = PetscSectionGetFieldOffset(dofSection[0], p, f, off);CHKERRQ(ierr);}
565     }
566   } else {
567     if (f < 0) {
568       PC_PATCH *patch = (PC_PATCH *) pc->data;
569       PetscInt  fdof, g;
570 
571       if (dof) {
572         *dof = 0;
573         for (g = 0; g < patch->nsubspaces; ++g) {
574           ierr = PetscSectionGetDof(dofSection[g], p, &fdof);CHKERRQ(ierr);
575           *dof += fdof;
576         }
577       }
578       if (off) {
579         *off = 0;
580         for (g = 0; g < patch->nsubspaces; ++g) {
581           ierr = PetscSectionGetOffset(dofSection[g], p, &fdof);CHKERRQ(ierr);
582           *off += fdof;
583         }
584       }
585     } else {
586       if (dof) {ierr = PetscSectionGetDof(dofSection[f], p, dof);CHKERRQ(ierr);}
587       if (off) {ierr = PetscSectionGetOffset(dofSection[f], p, off);CHKERRQ(ierr);}
588     }
589   }
590   PetscFunctionReturn(0);
591 }
592 
593 /* Given a hash table with a set of topological entities (pts), compute the degrees of
594    freedom in global concatenated numbering on those entities.
595    For Vanka smoothing, this needs to do something special: ignore dofs of the
596    constraint subspace on entities that aren't the base entity we're building the patch
597    around. */
598 static PetscErrorCode PCPatchGetPointDofs(PC pc, PetscHSetI pts, PetscHSetI dofs, PetscInt base, PetscHSetI* subspaces_to_exclude)
599 {
600   PC_PATCH      *patch = (PC_PATCH *) pc->data;
601   PetscHashIter  hi;
602   PetscInt       ldof, loff;
603   PetscInt       k, p;
604   PetscErrorCode ierr;
605 
606   PetscFunctionBegin;
607   ierr = PetscHSetIClear(dofs);CHKERRQ(ierr);
608   for (k = 0; k < patch->nsubspaces; ++k) {
609     PetscInt subspaceOffset = patch->subspaceOffsets[k];
610     PetscInt bs             = patch->bs[k];
611     PetscInt j, l;
612 
613     if (subspaces_to_exclude != NULL) {
614       PetscBool should_exclude_k = PETSC_FALSE;
615       PetscHSetIHas(*subspaces_to_exclude, k, &should_exclude_k);
616       if (should_exclude_k) {
617         /* only get this subspace dofs at the base entity, not any others */
618         ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, k, patch->combined, base, &ldof, &loff);CHKERRQ(ierr);
619         if (0 == ldof) continue;
620         for (j = loff; j < ldof + loff; ++j) {
621           for (l = 0; l < bs; ++l) {
622             PetscInt dof = bs*j + l + subspaceOffset;
623             ierr = PetscHSetIAdd(dofs, dof);CHKERRQ(ierr);
624           }
625         }
626         continue; /* skip the other dofs of this subspace */
627       }
628     }
629 
630     PetscHashIterBegin(pts, hi);
631     while (!PetscHashIterAtEnd(pts, hi)) {
632       PetscHashIterGetKey(pts, hi, p);
633       PetscHashIterNext(pts, hi);
634       ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, k, patch->combined, p, &ldof, &loff);CHKERRQ(ierr);
635       if (0 == ldof) continue;
636       for (j = loff; j < ldof + loff; ++j) {
637         for (l = 0; l < bs; ++l) {
638           PetscInt dof = bs*j + l + subspaceOffset;
639           ierr = PetscHSetIAdd(dofs, dof);CHKERRQ(ierr);
640         }
641       }
642     }
643   }
644   PetscFunctionReturn(0);
645 }
646 
647 /* Given two hash tables A and B, compute the keys in B that are not in A, and put them in C */
648 static PetscErrorCode PCPatchComputeSetDifference_Private(PetscHSetI A, PetscHSetI B, PetscHSetI C)
649 {
650   PetscHashIter  hi;
651   PetscInt       key;
652   PetscBool      flg;
653   PetscErrorCode ierr;
654 
655   PetscFunctionBegin;
656   ierr = PetscHSetIClear(C);CHKERRQ(ierr);
657   PetscHashIterBegin(B, hi);
658   while (!PetscHashIterAtEnd(B, hi)) {
659     PetscHashIterGetKey(B, hi, key);
660     PetscHashIterNext(B, hi);
661     ierr = PetscHSetIHas(A, key, &flg);CHKERRQ(ierr);
662     if (!flg) {ierr = PetscHSetIAdd(C, key);CHKERRQ(ierr);}
663   }
664   PetscFunctionReturn(0);
665 }
666 
667 /*
668  * PCPatchCreateCellPatches - create patches.
669  *
670  * Input Parameters:
671  * + dm - The DMPlex object defining the mesh
672  *
673  * Output Parameters:
674  * + cellCounts  - Section with counts of cells around each vertex
675  * . cells       - IS of the cell point indices of cells in each patch
676  * . pointCounts - Section with counts of cells around each vertex
677  * - point       - IS of the cell point indices of cells in each patch
678  */
679 static PetscErrorCode PCPatchCreateCellPatches(PC pc)
680 {
681   PC_PATCH       *patch = (PC_PATCH *) pc->data;
682   DMLabel         ghost = NULL;
683   DM              dm, plex;
684   PetscHSetI      ht, cht;
685   PetscSection    cellCounts,  pointCounts;
686   PetscInt       *cellsArray, *pointsArray;
687   PetscInt        numCells,    numPoints;
688   const PetscInt *leaves;
689   PetscInt        nleaves, pStart, pEnd, cStart, cEnd, vStart, vEnd, v;
690   PetscBool       isFiredrake;
691   PetscErrorCode  ierr;
692 
693   PetscFunctionBegin;
694   /* Used to keep track of the cells in the patch. */
695   ierr = PetscHSetICreate(&ht);CHKERRQ(ierr);
696   ierr = PetscHSetICreate(&cht);CHKERRQ(ierr);
697 
698   ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
699   if (!dm) SETERRQ(PetscObjectComm((PetscObject) pc), PETSC_ERR_ARG_WRONGSTATE, "DM not yet set on patch PC\n");
700   ierr = DMConvert(dm, DMPLEX, &plex);CHKERRQ(ierr);
701   ierr = DMPlexGetChart(plex, &pStart, &pEnd);CHKERRQ(ierr);
702   ierr = DMPlexGetHeightStratum(plex, 0, &cStart, &cEnd);CHKERRQ(ierr);
703 
704   if (patch->user_patches) {
705     ierr = patch->userpatchconstructionop(pc, &patch->npatch, &patch->userIS, &patch->iterationSet, patch->userpatchconstructctx);CHKERRQ(ierr);
706     vStart = 0; vEnd = patch->npatch;
707   } else if (patch->codim < 0) {
708     if (patch->dim < 0) {ierr = DMPlexGetDepthStratum(plex,  0,            &vStart, &vEnd);CHKERRQ(ierr);}
709     else                {ierr = DMPlexGetDepthStratum(plex,  patch->dim,   &vStart, &vEnd);CHKERRQ(ierr);}
710   } else                {ierr = DMPlexGetHeightStratum(plex, patch->codim, &vStart, &vEnd);CHKERRQ(ierr);}
711   patch->npatch = vEnd - vStart;
712 
713   /* These labels mark the owned points.  We only create patches around points that this process owns. */
714   ierr = DMHasLabel(dm, "pyop2_ghost", &isFiredrake);CHKERRQ(ierr);
715   if (isFiredrake) {
716     ierr = DMGetLabel(dm, "pyop2_ghost", &ghost);CHKERRQ(ierr);
717     ierr = DMLabelCreateIndex(ghost, pStart, pEnd);CHKERRQ(ierr);
718   } else {
719     PetscSF sf;
720 
721     ierr = DMGetPointSF(dm, &sf);CHKERRQ(ierr);
722     ierr = PetscSFGetGraph(sf, NULL, &nleaves, &leaves, NULL);CHKERRQ(ierr);
723     nleaves = PetscMax(nleaves, 0);
724   }
725 
726   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->cellCounts);CHKERRQ(ierr);
727   ierr = PetscObjectSetName((PetscObject) patch->cellCounts, "Patch Cell Layout");CHKERRQ(ierr);
728   cellCounts = patch->cellCounts;
729   ierr = PetscSectionSetChart(cellCounts, vStart, vEnd);CHKERRQ(ierr);
730   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->pointCounts);CHKERRQ(ierr);
731   ierr = PetscObjectSetName((PetscObject) patch->pointCounts, "Patch Point Layout");CHKERRQ(ierr);
732   pointCounts = patch->pointCounts;
733   ierr = PetscSectionSetChart(pointCounts, vStart, vEnd);CHKERRQ(ierr);
734   /* Count cells and points in the patch surrounding each entity */
735   for (v = vStart; v < vEnd; ++v) {
736     PetscHashIter hi;
737     PetscInt       chtSize, loc = -1;
738     PetscBool      flg;
739 
740     if (!patch->user_patches) {
741       if (ghost) {ierr = DMLabelHasPoint(ghost, v, &flg);CHKERRQ(ierr);}
742       else       {ierr = PetscFindInt(v, nleaves, leaves, &loc);CHKERRQ(ierr); flg = loc >=0 ? PETSC_TRUE : PETSC_FALSE;}
743       /* Not an owned entity, don't make a cell patch. */
744       if (flg) continue;
745     }
746 
747     ierr = patch->patchconstructop((void *) patch, dm, v, ht);CHKERRQ(ierr);
748     ierr = PCPatchCompleteCellPatch(pc, ht, cht);CHKERRQ(ierr);
749     ierr = PetscHSetIGetSize(cht, &chtSize);CHKERRQ(ierr);
750     /* empty patch, continue */
751     if (chtSize == 0) continue;
752 
753     /* safe because size(cht) > 0 from above */
754     PetscHashIterBegin(cht, hi);
755     while (!PetscHashIterAtEnd(cht, hi)) {
756       PetscInt point, pdof;
757 
758       PetscHashIterGetKey(cht, hi, point);
759       ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, -1, patch->combined, point, &pdof, NULL);CHKERRQ(ierr);
760       if (pdof)                            {ierr = PetscSectionAddDof(pointCounts, v, 1);CHKERRQ(ierr);}
761       if (point >= cStart && point < cEnd) {ierr = PetscSectionAddDof(cellCounts, v, 1);CHKERRQ(ierr);}
762       PetscHashIterNext(cht, hi);
763     }
764   }
765   if (isFiredrake) {ierr = DMLabelDestroyIndex(ghost);CHKERRQ(ierr);}
766 
767   ierr = PetscSectionSetUp(cellCounts);CHKERRQ(ierr);
768   ierr = PetscSectionGetStorageSize(cellCounts, &numCells);CHKERRQ(ierr);
769   ierr = PetscMalloc1(numCells, &cellsArray);CHKERRQ(ierr);
770   ierr = PetscSectionSetUp(pointCounts);CHKERRQ(ierr);
771   ierr = PetscSectionGetStorageSize(pointCounts, &numPoints);CHKERRQ(ierr);
772   ierr = PetscMalloc1(numPoints, &pointsArray);CHKERRQ(ierr);
773 
774   /* Now that we know how much space we need, run through again and actually remember the cells. */
775   for (v = vStart; v < vEnd; v++ ) {
776     PetscHashIter hi;
777     PetscInt       dof, off, cdof, coff, pdof, n = 0, cn = 0;
778 
779     ierr = PetscSectionGetDof(pointCounts, v, &dof);CHKERRQ(ierr);
780     ierr = PetscSectionGetOffset(pointCounts, v, &off);CHKERRQ(ierr);
781     ierr = PetscSectionGetDof(cellCounts, v, &cdof);CHKERRQ(ierr);
782     ierr = PetscSectionGetOffset(cellCounts, v, &coff);CHKERRQ(ierr);
783     if (dof <= 0) continue;
784     ierr = patch->patchconstructop((void *) patch, dm, v, ht);CHKERRQ(ierr);
785     ierr = PCPatchCompleteCellPatch(pc, ht, cht);CHKERRQ(ierr);
786     PetscHashIterBegin(cht, hi);
787     while (!PetscHashIterAtEnd(cht, hi)) {
788       PetscInt point;
789 
790       PetscHashIterGetKey(cht, hi, point);
791       ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, -1, patch->combined, point, &pdof, NULL);CHKERRQ(ierr);
792       if (pdof)                            {pointsArray[off + n++] = point;}
793       if (point >= cStart && point < cEnd) {cellsArray[coff + cn++] = point;}
794       PetscHashIterNext(cht, hi);
795     }
796     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);
797     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);
798   }
799   ierr = PetscHSetIDestroy(&ht);CHKERRQ(ierr);
800   ierr = PetscHSetIDestroy(&cht);CHKERRQ(ierr);
801   ierr = DMDestroy(&plex);CHKERRQ(ierr);
802 
803   ierr = ISCreateGeneral(PETSC_COMM_SELF, numCells,  cellsArray,  PETSC_OWN_POINTER, &patch->cells);CHKERRQ(ierr);
804   ierr = PetscObjectSetName((PetscObject) patch->cells,  "Patch Cells");CHKERRQ(ierr);
805   if (patch->viewCells) {
806     ierr = ObjectView((PetscObject) patch->cellCounts, patch->viewerCells, patch->formatCells);CHKERRQ(ierr);
807     ierr = ObjectView((PetscObject) patch->cells,      patch->viewerCells, patch->formatCells);CHKERRQ(ierr);
808   }
809   ierr = ISCreateGeneral(PETSC_COMM_SELF, numPoints, pointsArray, PETSC_OWN_POINTER, &patch->points);CHKERRQ(ierr);
810   ierr = PetscObjectSetName((PetscObject) patch->points, "Patch Points");CHKERRQ(ierr);
811   if (patch->viewPoints) {
812     ierr = ObjectView((PetscObject) patch->pointCounts, patch->viewerPoints, patch->formatPoints);CHKERRQ(ierr);
813     ierr = ObjectView((PetscObject) patch->points,      patch->viewerPoints, patch->formatPoints);CHKERRQ(ierr);
814   }
815   PetscFunctionReturn(0);
816 }
817 
818 /*
819  * PCPatchCreateCellPatchDiscretisationInfo - Build the dof maps for cell patches
820  *
821  * Input Parameters:
822  * + dm - The DMPlex object defining the mesh
823  * . cellCounts - Section with counts of cells around each vertex
824  * . cells - IS of the cell point indices of cells in each patch
825  * . cellNumbering - Section mapping plex cell points to Firedrake cell indices.
826  * . nodesPerCell - number of nodes per cell.
827  * - cellNodeMap - map from cells to node indices (nodesPerCell * numCells)
828  *
829  * Output Parameters:
830  * + dofs - IS of local dof numbers of each cell in the patch, where local is a patch local numbering
831  * . gtolCounts - Section with counts of dofs per cell patch
832  * - gtol - IS mapping from global dofs to local dofs for each patch.
833  */
834 static PetscErrorCode PCPatchCreateCellPatchDiscretisationInfo(PC pc)
835 {
836   PC_PATCH       *patch           = (PC_PATCH *) pc->data;
837   PetscSection    cellCounts      = patch->cellCounts;
838   PetscSection    pointCounts     = patch->pointCounts;
839   PetscSection    gtolCounts, gtolCountsWithArtificial;
840   IS              cells           = patch->cells;
841   IS              points          = patch->points;
842   PetscSection    cellNumbering   = patch->cellNumbering;
843   PetscInt        Nf              = patch->nsubspaces;
844   PetscInt        numCells, numPoints;
845   PetscInt        numDofs;
846   PetscInt        numGlobalDofs, numGlobalDofsWithArtificial;
847   PetscInt        totalDofsPerCell = patch->totalDofsPerCell;
848   PetscInt        vStart, vEnd, v;
849   const PetscInt *cellsArray, *pointsArray;
850   PetscInt       *newCellsArray   = NULL;
851   PetscInt       *dofsArray       = NULL;
852   PetscInt       *dofsArrayWithArtificial = NULL;
853   PetscInt       *offsArray       = NULL;
854   PetscInt       *offsArrayWithArtificial = NULL;
855   PetscInt       *asmArray        = NULL;
856   PetscInt       *asmArrayWithArtificial = NULL;
857   PetscInt       *globalDofsArray = NULL;
858   PetscInt       *globalDofsArrayWithArtificial = NULL;
859   PetscInt        globalIndex     = 0;
860   PetscInt        key             = 0;
861   PetscInt        asmKey          = 0;
862   DM              dm              = NULL;
863   const PetscInt *bcNodes         = NULL;
864   PetscHMapI      ht;
865   PetscHMapI      htWithArtificial;
866   PetscHSetI      globalBcs;
867   PetscInt        numBcs;
868   PetscHSetI      ownedpts, seenpts, owneddofs, seendofs, artificialbcs;
869   PetscInt        pStart, pEnd, p, i;
870   PetscErrorCode  ierr;
871 
872   PetscFunctionBegin;
873 
874   ierr = PCGetDM(pc, &dm); CHKERRQ(ierr);
875   /* dofcounts section is cellcounts section * dofPerCell */
876   ierr = PetscSectionGetStorageSize(cellCounts, &numCells);CHKERRQ(ierr);
877   ierr = PetscSectionGetStorageSize(patch->pointCounts, &numPoints);CHKERRQ(ierr);
878   numDofs = numCells * totalDofsPerCell;
879   ierr = PetscMalloc1(numDofs, &dofsArray);CHKERRQ(ierr);
880   ierr = PetscMalloc1(numPoints*Nf, &offsArray);CHKERRQ(ierr);
881   ierr = PetscMalloc1(numPoints*Nf, &offsArrayWithArtificial);CHKERRQ(ierr);
882   ierr = PetscMalloc1(numDofs, &asmArray);CHKERRQ(ierr);
883   ierr = PetscMalloc1(numCells, &newCellsArray);CHKERRQ(ierr);
884   ierr = PetscSectionGetChart(cellCounts, &vStart, &vEnd);CHKERRQ(ierr);
885   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->gtolCounts);CHKERRQ(ierr);
886   gtolCounts = patch->gtolCounts;
887   ierr = PetscSectionSetChart(gtolCounts, vStart, vEnd);CHKERRQ(ierr);
888   ierr = PetscObjectSetName((PetscObject) patch->gtolCounts, "Patch Global Index Section");CHKERRQ(ierr);
889 
890   if(patch->multiplicative)
891   {
892     ierr = PetscMalloc1(numDofs, &asmArrayWithArtificial);CHKERRQ(ierr);
893     ierr = PetscMalloc1(numDofs, &dofsArrayWithArtificial);CHKERRQ(ierr);
894     ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->gtolCountsWithArtificial);CHKERRQ(ierr);
895     gtolCountsWithArtificial = patch->gtolCountsWithArtificial;
896     ierr = PetscSectionSetChart(gtolCountsWithArtificial, vStart, vEnd);CHKERRQ(ierr);
897     ierr = PetscObjectSetName((PetscObject) patch->gtolCountsWithArtificial, "Patch Global Index Section Including Artificial BCs");CHKERRQ(ierr);
898   }
899 
900   /* Outside the patch loop, get the dofs that are globally-enforced Dirichlet
901    conditions */
902   ierr = PetscHSetICreate(&globalBcs);CHKERRQ(ierr);
903   ierr = ISGetIndices(patch->ghostBcNodes, &bcNodes); CHKERRQ(ierr);
904   ierr = ISGetSize(patch->ghostBcNodes, &numBcs); CHKERRQ(ierr);
905   for (i = 0; i < numBcs; ++i) {
906     ierr = PetscHSetIAdd(globalBcs, bcNodes[i]);CHKERRQ(ierr); /* these are already in concatenated numbering */
907   }
908   ierr = ISRestoreIndices(patch->ghostBcNodes, &bcNodes); CHKERRQ(ierr);
909   ierr = ISDestroy(&patch->ghostBcNodes); CHKERRQ(ierr); /* memory optimisation */
910 
911   /* Hash tables for artificial BC construction */
912   ierr = PetscHSetICreate(&ownedpts);CHKERRQ(ierr);
913   ierr = PetscHSetICreate(&seenpts);CHKERRQ(ierr);
914   ierr = PetscHSetICreate(&owneddofs);CHKERRQ(ierr);
915   ierr = PetscHSetICreate(&seendofs);CHKERRQ(ierr);
916   ierr = PetscHSetICreate(&artificialbcs);CHKERRQ(ierr);
917 
918   ierr = ISGetIndices(cells, &cellsArray);CHKERRQ(ierr);
919   ierr = ISGetIndices(points, &pointsArray);CHKERRQ(ierr);
920   ierr = PetscHMapICreate(&ht);CHKERRQ(ierr);
921   ierr = PetscHMapICreate(&htWithArtificial);CHKERRQ(ierr);
922   for (v = vStart; v < vEnd; ++v) {
923     PetscInt localIndex = 0;
924     PetscInt localIndexWithArtificial = 0;
925     PetscInt dof, off, i, j, k, l;
926 
927     ierr = PetscHMapIClear(ht);CHKERRQ(ierr);
928     ierr = PetscHMapIClear(htWithArtificial);CHKERRQ(ierr);
929     ierr = PetscSectionGetDof(cellCounts, v, &dof);CHKERRQ(ierr);
930     ierr = PetscSectionGetOffset(cellCounts, v, &off);CHKERRQ(ierr);
931     if (dof <= 0) continue;
932 
933     /* Calculate the global numbers of the artificial BC dofs here first */
934     ierr = patch->patchconstructop((void*)patch, dm, v, ownedpts); CHKERRQ(ierr);
935     ierr = PCPatchCompleteCellPatch(pc, ownedpts, seenpts); CHKERRQ(ierr);
936     ierr = PCPatchGetPointDofs(pc, ownedpts, owneddofs, v, &patch->subspaces_to_exclude); CHKERRQ(ierr);
937     ierr = PCPatchGetPointDofs(pc, seenpts, seendofs, v, NULL); CHKERRQ(ierr);
938     ierr = PCPatchComputeSetDifference_Private(owneddofs, seendofs, artificialbcs); CHKERRQ(ierr);
939     if (patch->viewPatches) {
940       PetscHSetI globalbcdofs;
941       PetscHashIter hi;
942       MPI_Comm comm = PetscObjectComm((PetscObject)pc);
943 
944       ierr = PetscHSetICreate(&globalbcdofs);CHKERRQ(ierr);
945       ierr = PetscSynchronizedPrintf(comm, "Patch %d: owned dofs:\n", v); CHKERRQ(ierr);
946       PetscHashIterBegin(owneddofs, hi);
947       while (!PetscHashIterAtEnd(owneddofs, hi)) {
948         PetscInt globalDof;
949 
950         PetscHashIterGetKey(owneddofs, hi, globalDof);
951         PetscHashIterNext(owneddofs, hi);
952         ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof); CHKERRQ(ierr);
953       }
954       ierr = PetscSynchronizedPrintf(comm, "\n"); CHKERRQ(ierr);
955       ierr = PetscSynchronizedPrintf(comm, "Patch %d: seen dofs:\n", v); CHKERRQ(ierr);
956       PetscHashIterBegin(seendofs, hi);
957       while (!PetscHashIterAtEnd(seendofs, hi)) {
958         PetscInt globalDof;
959         PetscBool flg;
960 
961         PetscHashIterGetKey(seendofs, hi, globalDof);
962         PetscHashIterNext(seendofs, hi);
963         ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof); CHKERRQ(ierr);
964 
965         ierr = PetscHSetIHas(globalBcs, globalDof, &flg);CHKERRQ(ierr);
966         if (flg) {ierr = PetscHSetIAdd(globalbcdofs, globalDof);CHKERRQ(ierr);}
967       }
968       ierr = PetscSynchronizedPrintf(comm, "\n"); CHKERRQ(ierr);
969       ierr = PetscSynchronizedPrintf(comm, "Patch %d: global BCs:\n", v); CHKERRQ(ierr);
970       ierr = PetscHSetIGetSize(globalbcdofs, &numBcs);CHKERRQ(ierr);
971       if (numBcs > 0) {
972         PetscHashIterBegin(globalbcdofs, hi);
973         while (!PetscHashIterAtEnd(globalbcdofs, hi)) {
974           PetscInt globalDof;
975           PetscHashIterGetKey(globalbcdofs, hi, globalDof);
976           PetscHashIterNext(globalbcdofs, hi);
977           ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof);CHKERRQ(ierr);
978         }
979       }
980       ierr = PetscSynchronizedPrintf(comm, "\n");CHKERRQ(ierr);
981       ierr = PetscSynchronizedPrintf(comm, "Patch %d: artificial BCs:\n", v);CHKERRQ(ierr);
982       ierr = PetscHSetIGetSize(artificialbcs, &numBcs);CHKERRQ(ierr);
983       if (numBcs > 0) {
984         PetscHashIterBegin(artificialbcs, hi);
985         while (!PetscHashIterAtEnd(artificialbcs, hi)) {
986           PetscInt globalDof;
987           PetscHashIterGetKey(artificialbcs, hi, globalDof);
988           PetscHashIterNext(artificialbcs, hi);
989           ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof); CHKERRQ(ierr);
990         }
991       }
992       ierr = PetscSynchronizedPrintf(comm, "\n\n"); CHKERRQ(ierr);
993       ierr = PetscHSetIDestroy(&globalbcdofs);CHKERRQ(ierr);
994     }
995    for (k = 0; k < patch->nsubspaces; ++k) {
996       const PetscInt *cellNodeMap    = patch->cellNodeMap[k];
997       PetscInt        nodesPerCell   = patch->nodesPerCell[k];
998       PetscInt        subspaceOffset = patch->subspaceOffsets[k];
999       PetscInt        bs             = patch->bs[k];
1000 
1001       for (i = off; i < off + dof; ++i) {
1002         /* Walk over the cells in this patch. */
1003         const PetscInt c    = cellsArray[i];
1004         PetscInt       cell = c;
1005 
1006         /* TODO Change this to an IS */
1007         if (cellNumbering) {
1008           ierr = PetscSectionGetDof(cellNumbering, c, &cell);CHKERRQ(ierr);
1009           if (cell <= 0) SETERRQ1(PetscObjectComm((PetscObject) pc), PETSC_ERR_ARG_OUTOFRANGE, "Cell %D doesn't appear in cell numbering map", c);
1010           ierr = PetscSectionGetOffset(cellNumbering, c, &cell);CHKERRQ(ierr);
1011         }
1012         newCellsArray[i] = cell;
1013         for (j = 0; j < nodesPerCell; ++j) {
1014           /* For each global dof, map it into contiguous local storage. */
1015           const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + subspaceOffset;
1016           /* finally, loop over block size */
1017           for (l = 0; l < bs; ++l) {
1018             PetscInt  localDof;
1019             PetscBool isGlobalBcDof, isArtificialBcDof;
1020 
1021             /* first, check if this is either a globally enforced or locally enforced BC dof */
1022             ierr = PetscHSetIHas(globalBcs, globalDof + l, &isGlobalBcDof);CHKERRQ(ierr);
1023             ierr = PetscHSetIHas(artificialbcs, globalDof + l, &isArtificialBcDof);CHKERRQ(ierr);
1024 
1025             /* if it's either, don't ever give it a local dof number */
1026             if (isGlobalBcDof || isArtificialBcDof) {
1027               dofsArray[globalIndex] = -1; /* don't use this in assembly in this patch */
1028             } else {
1029               ierr = PetscHMapIGet(ht, globalDof + l, &localDof);CHKERRQ(ierr);
1030               if (localDof == -1) {
1031                 localDof = localIndex++;
1032                 ierr = PetscHMapISet(ht, globalDof + l, localDof);CHKERRQ(ierr);
1033               }
1034               if ( globalIndex >= numDofs ) SETERRQ2(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "Found more dofs %D than expected %D", globalIndex+1, numDofs);
1035               /* And store. */
1036               dofsArray[globalIndex] = localDof;
1037             }
1038 
1039             if(patch->multiplicative)
1040             {
1041               if (isGlobalBcDof) {
1042                 dofsArrayWithArtificial[globalIndex] = -1; /* don't use this in assembly in this patch */
1043               } else {
1044                 ierr = PetscHMapIGet(htWithArtificial, globalDof + l, &localDof);CHKERRQ(ierr);
1045                 if (localDof == -1) {
1046                   localDof = localIndexWithArtificial++;
1047                   ierr = PetscHMapISet(htWithArtificial, globalDof + l, localDof);CHKERRQ(ierr);
1048                 }
1049                 if ( globalIndex >= numDofs ) SETERRQ2(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "Found more dofs %D than expected %D", globalIndex+1, numDofs);
1050                 /* And store.*/
1051                 dofsArrayWithArtificial[globalIndex] = localDof;
1052               }
1053             }
1054             globalIndex++;
1055           }
1056         }
1057       }
1058     }
1059      /*How many local dofs in this patch? */
1060     if(patch->multiplicative) {
1061         ierr = PetscHMapIGetSize(htWithArtificial, &dof);CHKERRQ(ierr);
1062         ierr = PetscSectionSetDof(gtolCountsWithArtificial, v, dof);CHKERRQ(ierr);
1063     }
1064     ierr = PetscHMapIGetSize(ht, &dof);CHKERRQ(ierr);
1065     ierr = PetscSectionSetDof(gtolCounts, v, dof);CHKERRQ(ierr);
1066   }
1067   if (globalIndex != numDofs) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Expected number of dofs (%d) doesn't match found number (%d)", numDofs, globalIndex);
1068   ierr = PetscSectionSetUp(gtolCounts);CHKERRQ(ierr);
1069   ierr = PetscSectionGetStorageSize(gtolCounts, &numGlobalDofs);CHKERRQ(ierr);
1070   ierr = PetscMalloc1(numGlobalDofs, &globalDofsArray);CHKERRQ(ierr);
1071 
1072   if(patch->multiplicative) {
1073     ierr = PetscSectionSetUp(gtolCountsWithArtificial);CHKERRQ(ierr);
1074     ierr = PetscSectionGetStorageSize(gtolCountsWithArtificial, &numGlobalDofsWithArtificial);CHKERRQ(ierr);
1075     ierr = PetscMalloc1(numGlobalDofsWithArtificial, &globalDofsArrayWithArtificial);CHKERRQ(ierr);
1076   }
1077   /* Now populate the global to local map.  This could be merged into the above loop if we were willing to deal with reallocs. */
1078   for (v = vStart; v < vEnd; ++v) {
1079     PetscHashIter hi;
1080     PetscInt      dof, off, Np, ooff, i, j, k, l;
1081 
1082     ierr = PetscHMapIClear(ht);CHKERRQ(ierr);
1083     ierr = PetscHMapIClear(htWithArtificial);CHKERRQ(ierr);
1084     ierr = PetscSectionGetDof(cellCounts, v, &dof);CHKERRQ(ierr);
1085     ierr = PetscSectionGetOffset(cellCounts, v, &off);CHKERRQ(ierr);
1086     ierr = PetscSectionGetDof(pointCounts, v, &Np);CHKERRQ(ierr);
1087     ierr = PetscSectionGetOffset(pointCounts, v, &ooff);CHKERRQ(ierr);
1088     if (dof <= 0) continue;
1089 
1090     for (k = 0; k < patch->nsubspaces; ++k) {
1091       const PetscInt *cellNodeMap    = patch->cellNodeMap[k];
1092       PetscInt        nodesPerCell   = patch->nodesPerCell[k];
1093       PetscInt        subspaceOffset = patch->subspaceOffsets[k];
1094       PetscInt        bs             = patch->bs[k];
1095       PetscInt        goff;
1096 
1097       for (i = off; i < off + dof; ++i) {
1098         /* Reconstruct mapping of global-to-local on this patch. */
1099         const PetscInt c    = cellsArray[i];
1100         PetscInt       cell = c;
1101 
1102         if (cellNumbering) {ierr = PetscSectionGetOffset(cellNumbering, c, &cell);CHKERRQ(ierr);}
1103         for (j = 0; j < nodesPerCell; ++j) {
1104           for (l = 0; l < bs; ++l) {
1105             const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + l + subspaceOffset;
1106             const PetscInt localDof  = dofsArray[key];
1107             if (localDof >= 0) {ierr = PetscHMapISet(ht, globalDof, localDof);CHKERRQ(ierr);}
1108             if(patch->multiplicative) {
1109               const PetscInt localDofWithArtificial = dofsArrayWithArtificial[key];
1110               if (localDofWithArtificial >= 0) {
1111                 ierr = PetscHMapISet(htWithArtificial, globalDof, localDofWithArtificial);CHKERRQ(ierr);
1112               }
1113             }
1114             key++;
1115           }
1116         }
1117       }
1118 
1119       /* Shove it in the output data structure. */
1120       ierr = PetscSectionGetOffset(gtolCounts, v, &goff);CHKERRQ(ierr);
1121       PetscHashIterBegin(ht, hi);
1122       while (!PetscHashIterAtEnd(ht, hi)) {
1123         PetscInt globalDof, localDof;
1124 
1125         PetscHashIterGetKey(ht, hi, globalDof);
1126         PetscHashIterGetVal(ht, hi, localDof);
1127         if (globalDof >= 0) globalDofsArray[goff + localDof] = globalDof;
1128         PetscHashIterNext(ht, hi);
1129       }
1130 
1131       if(patch->multiplicative) {
1132         ierr = PetscSectionGetOffset(gtolCountsWithArtificial, v, &goff);CHKERRQ(ierr);
1133         PetscHashIterBegin(htWithArtificial, hi);
1134         while (!PetscHashIterAtEnd(htWithArtificial, hi)) {
1135           PetscInt globalDof, localDof;
1136           PetscHashIterGetKey(htWithArtificial, hi, globalDof);
1137           PetscHashIterGetVal(htWithArtificial, hi, localDof);
1138           if (globalDof >= 0) globalDofsArrayWithArtificial[goff + localDof] = globalDof;
1139           PetscHashIterNext(htWithArtificial, hi);
1140         }
1141       }
1142 
1143       for (p = 0; p < Np; ++p) {
1144         const PetscInt point = pointsArray[ooff + p];
1145         PetscInt       globalDof, localDof;
1146 
1147         ierr = PCPatchGetGlobalDofs(pc, patch->dofSection, k, patch->combined, point, NULL, &globalDof);CHKERRQ(ierr);
1148         ierr = PetscHMapIGet(ht, globalDof, &localDof);CHKERRQ(ierr);
1149         offsArray[(ooff + p)*Nf + k] = localDof;
1150         if(patch->multiplicative) {
1151           ierr = PetscHMapIGet(htWithArtificial, globalDof, &localDof);CHKERRQ(ierr);
1152           offsArrayWithArtificial[(ooff + p)*Nf + k] = localDof;
1153         }
1154       }
1155     }
1156 
1157     ierr = PetscHSetIDestroy(&globalBcs);CHKERRQ(ierr);
1158     ierr = PetscHSetIDestroy(&ownedpts);CHKERRQ(ierr);
1159     ierr = PetscHSetIDestroy(&seenpts);CHKERRQ(ierr);
1160     ierr = PetscHSetIDestroy(&owneddofs);CHKERRQ(ierr);
1161     ierr = PetscHSetIDestroy(&seendofs);CHKERRQ(ierr);
1162     ierr = PetscHSetIDestroy(&artificialbcs);CHKERRQ(ierr);
1163 
1164       /* At this point, we have a hash table ht built that maps globalDof -> localDof.
1165      We need to create the dof table laid out cellwise first, then by subspace,
1166      as the assembler assembles cell-wise and we need to stuff the different
1167      contributions of the different function spaces to the right places. So we loop
1168      over cells, then over subspaces. */
1169     if (patch->nsubspaces > 1) { /* for nsubspaces = 1, data we need is already in dofsArray */
1170       for (i = off; i < off + dof; ++i) {
1171         const PetscInt c    = cellsArray[i];
1172         PetscInt       cell = c;
1173 
1174         if (cellNumbering) {ierr = PetscSectionGetOffset(cellNumbering, c, &cell);CHKERRQ(ierr);}
1175         for (k = 0; k < patch->nsubspaces; ++k) {
1176           const PetscInt *cellNodeMap    = patch->cellNodeMap[k];
1177           PetscInt        nodesPerCell   = patch->nodesPerCell[k];
1178           PetscInt        subspaceOffset = patch->subspaceOffsets[k];
1179           PetscInt        bs             = patch->bs[k];
1180 
1181           for (j = 0; j < nodesPerCell; ++j) {
1182             for (l = 0; l < bs; ++l) {
1183               const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + l + subspaceOffset;
1184               PetscInt       localDof;
1185 
1186               ierr = PetscHMapIGet(ht, globalDof, &localDof);CHKERRQ(ierr);
1187               /* If it's not in the hash table, i.e. is a BC dof,
1188                then the PetscHSetIMap above gives -1, which matches
1189                exactly the convention for PETSc's matrix assembly to
1190                ignore the dof. So we don't need to do anything here */
1191               asmArray[asmKey] = localDof;
1192               if(patch->multiplicative) {
1193                 ierr = PetscHMapIGet(htWithArtificial, globalDof, &localDof);CHKERRQ(ierr);
1194                 asmArrayWithArtificial[asmKey] = localDof;
1195               }
1196               asmKey++;
1197             }
1198           }
1199         }
1200       }
1201     }
1202   }
1203   if (1 == patch->nsubspaces) {
1204     ierr = PetscMemcpy(asmArray, dofsArray, numDofs * sizeof(PetscInt));CHKERRQ(ierr);
1205     if(patch->multiplicative) {
1206       ierr = PetscMemcpy(asmArrayWithArtificial, dofsArrayWithArtificial, numDofs * sizeof(PetscInt));CHKERRQ(ierr);
1207     }
1208   }
1209 
1210   ierr = PetscHMapIDestroy(&ht);CHKERRQ(ierr);
1211   ierr = PetscHMapIDestroy(&htWithArtificial);CHKERRQ(ierr);
1212   ierr = ISRestoreIndices(cells, &cellsArray);CHKERRQ(ierr);
1213   ierr = ISRestoreIndices(points, &pointsArray);CHKERRQ(ierr);
1214   ierr = PetscFree(dofsArray);CHKERRQ(ierr);
1215   if(patch->multiplicative) {
1216     ierr = PetscFree(dofsArrayWithArtificial);CHKERRQ(ierr);
1217   }
1218   /* Create placeholder section for map from points to patch dofs */
1219   ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->patchSection);CHKERRQ(ierr);
1220   ierr = PetscSectionSetNumFields(patch->patchSection, patch->nsubspaces);CHKERRQ(ierr);
1221   if (patch->combined) {
1222     PetscInt numFields;
1223     ierr = PetscSectionGetNumFields(patch->dofSection[0], &numFields);CHKERRQ(ierr);
1224     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);
1225     ierr = PetscSectionGetChart(patch->dofSection[0], &pStart, &pEnd);CHKERRQ(ierr);
1226     ierr = PetscSectionSetChart(patch->patchSection, pStart, pEnd);CHKERRQ(ierr);
1227     for (p = pStart; p < pEnd; ++p) {
1228       PetscInt dof, fdof, f;
1229 
1230       ierr = PetscSectionGetDof(patch->dofSection[0], p, &dof);CHKERRQ(ierr);
1231       ierr = PetscSectionSetDof(patch->patchSection, p, dof);CHKERRQ(ierr);
1232       for (f = 0; f < patch->nsubspaces; ++f) {
1233         ierr = PetscSectionGetFieldDof(patch->dofSection[0], p, f, &fdof);CHKERRQ(ierr);
1234         ierr = PetscSectionSetFieldDof(patch->patchSection, p, f, fdof);CHKERRQ(ierr);
1235       }
1236     }
1237   } else {
1238     PetscInt pStartf, pEndf, f;
1239     pStart = PETSC_MAX_INT;
1240     pEnd = PETSC_MIN_INT;
1241     for (f = 0; f < patch->nsubspaces; ++f) {
1242       ierr = PetscSectionGetChart(patch->dofSection[f], &pStartf, &pEndf);CHKERRQ(ierr);
1243       pStart = PetscMin(pStart, pStartf);
1244       pEnd = PetscMax(pEnd, pEndf);
1245     }
1246     ierr = PetscSectionSetChart(patch->patchSection, pStart, pEnd);CHKERRQ(ierr);
1247     for (f = 0; f < patch->nsubspaces; ++f) {
1248       ierr = PetscSectionGetChart(patch->dofSection[f], &pStartf, &pEndf);CHKERRQ(ierr);
1249       for (p = pStartf; p < pEndf; ++p) {
1250         PetscInt fdof;
1251         ierr = PetscSectionGetDof(patch->dofSection[f], p, &fdof);CHKERRQ(ierr);
1252         ierr = PetscSectionAddDof(patch->patchSection, p, fdof);CHKERRQ(ierr);
1253         ierr = PetscSectionSetFieldDof(patch->patchSection, p, f, fdof);CHKERRQ(ierr);
1254       }
1255     }
1256   }
1257   ierr = PetscSectionSetUp(patch->patchSection);CHKERRQ(ierr);
1258   ierr = PetscSectionSetUseFieldOffsets(patch->patchSection, PETSC_TRUE);CHKERRQ(ierr);
1259   /* Replace cell indices with firedrake-numbered ones. */
1260   ierr = ISGeneralSetIndices(cells, numCells, (const PetscInt *) newCellsArray, PETSC_OWN_POINTER);CHKERRQ(ierr);
1261   ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalDofs, globalDofsArray, PETSC_OWN_POINTER, &patch->gtol);CHKERRQ(ierr);
1262   ierr = PetscObjectSetName((PetscObject) patch->gtol, "Global Indices");CHKERRQ(ierr);
1263   ierr = PetscSectionViewFromOptions(patch->gtolCounts, (PetscObject) pc, "-pc_patch_g2l_view");CHKERRQ(ierr);
1264   ierr = ISViewFromOptions(patch->gtol, (PetscObject) pc, "-pc_patch_g2l_view");CHKERRQ(ierr);
1265   ierr = ISCreateGeneral(PETSC_COMM_SELF, numDofs, asmArray, PETSC_OWN_POINTER, &patch->dofs);CHKERRQ(ierr);
1266   ierr = ISCreateGeneral(PETSC_COMM_SELF, numPoints*Nf, offsArray, PETSC_OWN_POINTER, &patch->offs);CHKERRQ(ierr);
1267   if(patch->multiplicative) {
1268     ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalDofsWithArtificial, globalDofsArrayWithArtificial, PETSC_OWN_POINTER, &patch->gtolWithArtificial);CHKERRQ(ierr);
1269     ierr = ISCreateGeneral(PETSC_COMM_SELF, numDofs, asmArrayWithArtificial, PETSC_OWN_POINTER, &patch->dofsWithArtificial);CHKERRQ(ierr);
1270     ierr = ISCreateGeneral(PETSC_COMM_SELF, numPoints*Nf, offsArrayWithArtificial, PETSC_OWN_POINTER, &patch->offsWithArtificial);CHKERRQ(ierr);
1271   }
1272   PetscFunctionReturn(0);
1273 }
1274 
1275 static PetscErrorCode PCPatchZeroFillMatrix_Private(Mat mat, const PetscInt ncell, const PetscInt ndof, const PetscInt *dof)
1276 {
1277   PetscScalar    *values = NULL;
1278   PetscInt        rows, c, i;
1279   PetscErrorCode  ierr;
1280 
1281   PetscFunctionBegin;
1282   ierr = PetscCalloc1(ndof*ndof, &values);CHKERRQ(ierr);
1283   for (c = 0; c < ncell; ++c) {
1284     const PetscInt *idx = &dof[ndof*c];
1285     ierr = MatSetValues(mat, ndof, idx, ndof, idx, values, INSERT_VALUES);CHKERRQ(ierr);
1286   }
1287   ierr = MatGetLocalSize(mat, &rows, NULL);CHKERRQ(ierr);
1288   for (i = 0; i < rows; ++i) {
1289     ierr = MatSetValues(mat, 1, &i, 1, &i, values, INSERT_VALUES);CHKERRQ(ierr);
1290   }
1291   ierr = MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
1292   ierr = MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
1293   ierr = PetscFree(values);CHKERRQ(ierr);
1294   PetscFunctionReturn(0);
1295 }
1296 
1297 static PetscErrorCode PCPatchCreateMatrix_Private(PC pc, PetscInt point, Mat *mat, PetscBool withArtificial)
1298 {
1299   PC_PATCH      *patch = (PC_PATCH *) pc->data;
1300   Vec            x, y;
1301   PetscBool      flg;
1302   PetscInt       csize, rsize;
1303   const char    *prefix = NULL;
1304   PetscErrorCode ierr;
1305 
1306   PetscFunctionBegin;
1307   if(withArtificial) {
1308     /* would be nice if we could create a rectangular matrix of size numDofsWithArtificial x numDofs here */
1309     x = patch->patchXWithArtificial[point];
1310     y = patch->patchXWithArtificial[point];
1311   }
1312   else {
1313     x = patch->patchX[point];
1314     y = patch->patchY[point];
1315   }
1316 
1317   ierr = VecGetSize(x, &csize);CHKERRQ(ierr);
1318   ierr = VecGetSize(y, &rsize);CHKERRQ(ierr);
1319   ierr = MatCreate(PETSC_COMM_SELF, mat);CHKERRQ(ierr);
1320   ierr = PCGetOptionsPrefix(pc, &prefix);CHKERRQ(ierr);
1321   ierr = MatSetOptionsPrefix(*mat, prefix);CHKERRQ(ierr);
1322   ierr = MatAppendOptionsPrefix(*mat, "pc_patch_sub_");CHKERRQ(ierr);
1323   if (patch->sub_mat_type)       {ierr = MatSetType(*mat, patch->sub_mat_type);CHKERRQ(ierr);}
1324   else if (!patch->sub_mat_type) {ierr = MatSetType(*mat, MATDENSE);CHKERRQ(ierr);}
1325   ierr = MatSetSizes(*mat, rsize, csize, rsize, csize);CHKERRQ(ierr);
1326   ierr = PetscObjectTypeCompare((PetscObject) *mat, MATDENSE, &flg);CHKERRQ(ierr);
1327   if (!flg) {ierr = PetscObjectTypeCompare((PetscObject)*mat, MATSEQDENSE, &flg);CHKERRQ(ierr);}
1328   /* Sparse patch matrices */
1329   if (!flg) {
1330     PetscBT         bt;
1331     PetscInt       *dnnz      = NULL;
1332     const PetscInt *dofsArray = NULL;
1333     PetscInt        pStart, pEnd, ncell, offset, c, i, j;
1334 
1335     if(withArtificial) {
1336       ierr = ISGetIndices(patch->dofsWithArtificial, &dofsArray);CHKERRQ(ierr);
1337     }
1338     else {
1339       ierr = ISGetIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
1340     }
1341     ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd);CHKERRQ(ierr);
1342     point += pStart;
1343     if (point >= pEnd) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Operator point %D not in [%D, %D)\n", point, pStart, pEnd);CHKERRQ(ierr);
1344     ierr = PetscSectionGetDof(patch->cellCounts, point, &ncell);CHKERRQ(ierr);
1345     ierr = PetscSectionGetOffset(patch->cellCounts, point, &offset);CHKERRQ(ierr);
1346     ierr = PetscCalloc1(rsize, &dnnz);CHKERRQ(ierr);
1347     ierr = PetscLogEventBegin(PC_Patch_Prealloc, pc, 0, 0, 0);CHKERRQ(ierr);
1348     /* XXX: This uses N^2 bits to store the sparsity pattern on a
1349      * patch.  This is probably OK if the patches are not too big,
1350      * but could use quite a bit of memory for planes in 3D.
1351      * Should we switch based on the value of rsize to a
1352      * hash-table (slower, but more memory efficient) approach? */
1353     ierr = PetscBTCreate(rsize*rsize, &bt);CHKERRQ(ierr);
1354     for (c = 0; c < ncell; ++c) {
1355       const PetscInt *idx = dofsArray + (offset + c)*patch->totalDofsPerCell;
1356       for (i = 0; i < patch->totalDofsPerCell; ++i) {
1357         const PetscInt row = idx[i];
1358         if (row < 0) continue;
1359         for (j = 0; j < patch->totalDofsPerCell; ++j) {
1360           const PetscInt col = idx[j];
1361           const PetscInt key = row*rsize + col;
1362           if (col < 0) continue;
1363           if (!PetscBTLookupSet(bt, key)) ++dnnz[row];
1364         }
1365       }
1366     }
1367     ierr = PetscBTDestroy(&bt);CHKERRQ(ierr);
1368     ierr = MatXAIJSetPreallocation(*mat, 1, dnnz, NULL, NULL, NULL);CHKERRQ(ierr);
1369     ierr = PetscFree(dnnz);CHKERRQ(ierr);
1370     ierr = PCPatchZeroFillMatrix_Private(*mat, ncell, patch->totalDofsPerCell, &dofsArray[offset*patch->totalDofsPerCell]);CHKERRQ(ierr);
1371     ierr = PetscLogEventEnd(PC_Patch_Prealloc, pc, 0, 0, 0);CHKERRQ(ierr);
1372     if(withArtificial) {
1373       ierr = ISRestoreIndices(patch->dofsWithArtificial, &dofsArray);CHKERRQ(ierr);
1374     } else {
1375       ierr = ISRestoreIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
1376     }
1377   }
1378   ierr = MatSetUp(*mat);CHKERRQ(ierr);
1379   PetscFunctionReturn(0);
1380 }
1381 
1382 static PetscErrorCode PCPatchComputeOperator_DMPlex_Private(PC pc, PetscInt patchNum, Mat J, IS cellIS, PetscInt n, const PetscInt *l2p, void *ctx)
1383 {
1384   PC_PATCH       *patch = (PC_PATCH *) pc->data;
1385   DM              dm;
1386   PetscSection    s;
1387   const PetscInt *parray, *oarray;
1388   PetscInt        Nf = patch->nsubspaces, Np, poff, p, f;
1389   PetscErrorCode  ierr;
1390 
1391   PetscFunctionBegin;
1392   ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
1393   ierr = DMGetDefaultSection(dm, &s);CHKERRQ(ierr);
1394   /* Set offset into patch */
1395   ierr = PetscSectionGetDof(patch->pointCounts, patchNum, &Np);CHKERRQ(ierr);
1396   ierr = PetscSectionGetOffset(patch->pointCounts, patchNum, &poff);CHKERRQ(ierr);
1397   ierr = ISGetIndices(patch->points, &parray);CHKERRQ(ierr);
1398   ierr = ISGetIndices(patch->offs,   &oarray);CHKERRQ(ierr);
1399   for (f = 0; f < Nf; ++f) {
1400     for (p = 0; p < Np; ++p) {
1401       const PetscInt point = parray[poff+p];
1402       PetscInt       dof;
1403 
1404       ierr = PetscSectionGetFieldDof(patch->patchSection, point, f, &dof);CHKERRQ(ierr);
1405       ierr = PetscSectionSetFieldOffset(patch->patchSection, point, f, oarray[(poff+p)*Nf+f]);CHKERRQ(ierr);
1406       if (patch->nsubspaces == 1) {ierr = PetscSectionSetOffset(patch->patchSection, point, oarray[(poff+p)*Nf+f]);CHKERRQ(ierr);}
1407       else                        {ierr = PetscSectionSetOffset(patch->patchSection, point, -1);CHKERRQ(ierr);}
1408     }
1409   }
1410   ierr = ISRestoreIndices(patch->points, &parray);CHKERRQ(ierr);
1411   ierr = ISRestoreIndices(patch->offs,   &oarray);CHKERRQ(ierr);
1412   if (patch->viewSection) {ierr = ObjectView((PetscObject) patch->patchSection, patch->viewerSection, patch->formatSection);CHKERRQ(ierr);}
1413   /* TODO Shut off MatViewFromOptions() in MatAssemblyEnd() here */
1414   ierr = DMPlexComputeJacobian_Patch_Internal(pc->dm, patch->patchSection, patch->patchSection, cellIS, 0.0, 0.0, NULL, NULL, J, J, ctx);CHKERRQ(ierr);
1415   PetscFunctionReturn(0);
1416 }
1417 
1418 static PetscErrorCode PCPatchComputeOperator_Private(PC pc, Mat mat, PetscInt point, PetscBool withArtificial)
1419 {
1420   PC_PATCH       *patch = (PC_PATCH *) pc->data;
1421   const PetscInt *dofsArray;
1422   const PetscInt *cellsArray;
1423   PetscInt        ncell, offset, pStart, pEnd;
1424   PetscErrorCode  ierr;
1425 
1426   PetscFunctionBegin;
1427   ierr = PetscLogEventBegin(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
1428   if (!patch->usercomputeop) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call PCPatchSetComputeOperator() to set user callback\n");
1429   if(withArtificial) {
1430     ierr = ISGetIndices(patch->dofsWithArtificial, &dofsArray);CHKERRQ(ierr);
1431   } else {
1432     ierr = ISGetIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
1433   }
1434   ierr = ISGetIndices(patch->cells, &cellsArray);CHKERRQ(ierr);
1435   ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd);CHKERRQ(ierr);
1436 
1437   point += pStart;
1438   if (point >= pEnd) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Operator point %D not in [%D, %D)\n", point, pStart, pEnd);CHKERRQ(ierr);
1439 
1440   ierr = PetscSectionGetDof(patch->cellCounts, point, &ncell);CHKERRQ(ierr);
1441   ierr = PetscSectionGetOffset(patch->cellCounts, point, &offset);CHKERRQ(ierr);
1442   if (ncell <= 0) {
1443     ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
1444     PetscFunctionReturn(0);
1445   }
1446   PetscStackPush("PCPatch user callback");
1447   /* Cannot reuse the same IS because the geometry info is being cached in it */
1448   ierr = ISCreateGeneral(PETSC_COMM_SELF, ncell, cellsArray + offset, PETSC_USE_POINTER, &patch->cellIS);CHKERRQ(ierr);
1449   ierr = patch->usercomputeop(pc, point, mat, patch->cellIS, ncell*patch->totalDofsPerCell, dofsArray + offset*patch->totalDofsPerCell, patch->usercomputectx);CHKERRQ(ierr);
1450   PetscStackPop;
1451   ierr = ISDestroy(&patch->cellIS);CHKERRQ(ierr);
1452   if(withArtificial)
1453   {
1454     ierr = ISRestoreIndices(patch->dofsWithArtificial, &dofsArray);CHKERRQ(ierr);
1455   } else {
1456     ierr = ISRestoreIndices(patch->dofs, &dofsArray);CHKERRQ(ierr);
1457   }
1458   ierr = ISRestoreIndices(patch->cells, &cellsArray);CHKERRQ(ierr);
1459   if (patch->viewMatrix) {
1460     char name[PETSC_MAX_PATH_LEN];
1461 
1462     ierr = PetscSNPrintf(name, PETSC_MAX_PATH_LEN-1, "Patch matrix for Point %D", point);CHKERRQ(ierr);
1463     ierr = PetscObjectSetName((PetscObject) mat, name);CHKERRQ(ierr);
1464     ierr = ObjectView((PetscObject) mat, patch->viewerMatrix, patch->formatMatrix);CHKERRQ(ierr);
1465   }
1466   ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0);CHKERRQ(ierr);
1467   PetscFunctionReturn(0);
1468 }
1469 
1470 static PetscErrorCode PCPatch_ScatterLocal_Private(PC pc, PetscInt p, Vec x, Vec y, InsertMode mode, ScatterMode scat, PetscBool withArtificial)
1471 {
1472   PC_PATCH          *patch     = (PC_PATCH *) pc->data;
1473   const PetscScalar *xArray    = NULL;
1474   PetscScalar       *yArray    = NULL;
1475   const PetscInt    *gtolArray = NULL;
1476   PetscInt           dof, offset, lidx;
1477   PetscErrorCode     ierr;
1478 
1479   PetscFunctionBeginHot;
1480   ierr = PetscLogEventBegin(PC_Patch_Scatter, pc, 0, 0, 0);CHKERRQ(ierr);
1481   ierr = VecGetArrayRead(x, &xArray);CHKERRQ(ierr);
1482   ierr = VecGetArray(y, &yArray);CHKERRQ(ierr);
1483   if(withArtificial) {
1484     ierr = PetscSectionGetDof(patch->gtolCountsWithArtificial, p, &dof);CHKERRQ(ierr);
1485     ierr = PetscSectionGetOffset(patch->gtolCountsWithArtificial, p, &offset);CHKERRQ(ierr);
1486     ierr = ISGetIndices(patch->gtolWithArtificial, &gtolArray);CHKERRQ(ierr);
1487   } else {
1488     ierr = PetscSectionGetDof(patch->gtolCounts, p, &dof);CHKERRQ(ierr);
1489     ierr = PetscSectionGetOffset(patch->gtolCounts, p, &offset);CHKERRQ(ierr);
1490     ierr = ISGetIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
1491   }
1492   if (mode == INSERT_VALUES && scat != SCATTER_FORWARD) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Can't insert if not scattering forward\n");
1493   if (mode == ADD_VALUES    && scat != SCATTER_REVERSE) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Can't add if not scattering reverse\n");
1494   for (lidx = 0; lidx < dof; ++lidx) {
1495     const PetscInt gidx = gtolArray[offset+lidx];
1496 
1497     if (mode == INSERT_VALUES) yArray[lidx]  = xArray[gidx]; /* Forward */
1498     else                       yArray[gidx] += xArray[lidx]; /* Reverse */
1499   }
1500   if(withArtificial) {
1501     ierr = ISRestoreIndices(patch->gtolWithArtificial, &gtolArray);CHKERRQ(ierr);
1502   } else {
1503     ierr = ISRestoreIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
1504   }
1505   ierr = VecRestoreArrayRead(x, &xArray);CHKERRQ(ierr);
1506   ierr = VecRestoreArray(y, &yArray);CHKERRQ(ierr);
1507   ierr = PetscLogEventEnd(PC_Patch_Scatter, pc, 0, 0, 0);CHKERRQ(ierr);
1508   PetscFunctionReturn(0);
1509 }
1510 
1511 static PetscErrorCode PCSetUp_PATCH(PC pc)
1512 {
1513   PC_PATCH       *patch   = (PC_PATCH *) pc->data;
1514   PetscInt        i;
1515   const char     *prefix;
1516   PetscErrorCode  ierr;
1517 
1518   PetscFunctionBegin;
1519   if (!pc->setupcalled) {
1520     PetscInt pStart, pEnd, p;
1521     PetscInt localSize;
1522 
1523     ierr = PetscLogEventBegin(PC_Patch_CreatePatches, pc, 0, 0, 0);CHKERRQ(ierr);
1524 
1525     if (!patch->nsubspaces) {
1526       DM           dm;
1527       PetscDS      prob;
1528       PetscSection s;
1529       PetscInt     cStart, cEnd, c, Nf, f, numGlobalBcs = 0, *globalBcs, *Nb, totNb = 0, **cellDofs;
1530 
1531       ierr = PCGetDM(pc, &dm);CHKERRQ(ierr);
1532       if (!dm) SETERRQ(PetscObjectComm((PetscObject) pc), PETSC_ERR_ARG_WRONG, "Must set DM for PCPATCH or call PCPatchSetDiscretisationInfo()");
1533       ierr = DMGetDefaultSection(dm, &s);CHKERRQ(ierr);
1534       ierr = PetscSectionGetNumFields(s, &Nf);CHKERRQ(ierr);
1535       ierr = PetscSectionGetChart(s, &pStart, &pEnd);CHKERRQ(ierr);
1536       for (p = pStart; p < pEnd; ++p) {
1537         PetscInt cdof;
1538         ierr = PetscSectionGetConstraintDof(s, p, &cdof);CHKERRQ(ierr);
1539         numGlobalBcs += cdof;
1540       }
1541       ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);
1542       ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
1543       ierr = PetscMalloc3(Nf, &Nb, Nf, &cellDofs, numGlobalBcs, &globalBcs);CHKERRQ(ierr);
1544       for (f = 0; f < Nf; ++f) {
1545         PetscFE        fe;
1546         PetscDualSpace sp;
1547         PetscInt       cdoff = 0;
1548 
1549         ierr = PetscDSGetDiscretization(prob, f, (PetscObject *) &fe);CHKERRQ(ierr);
1550         /* ierr = PetscFEGetNumComponents(fe, &Nc[f]);CHKERRQ(ierr); */
1551         ierr = PetscFEGetDualSpace(fe, &sp);CHKERRQ(ierr);
1552         ierr = PetscDualSpaceGetDimension(sp, &Nb[f]);CHKERRQ(ierr);
1553         totNb += Nb[f];
1554 
1555         ierr = PetscMalloc1((cEnd-cStart)*Nb[f], &cellDofs[f]);CHKERRQ(ierr);
1556         for (c = cStart; c < cEnd; ++c) {
1557           PetscInt *closure = NULL;
1558           PetscInt  clSize  = 0, cl;
1559 
1560           ierr = DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure);CHKERRQ(ierr);
1561           for (cl = 0; cl < clSize*2; cl += 2) {
1562             const PetscInt p = closure[cl];
1563             PetscInt       fdof, d, foff;
1564 
1565             ierr = PetscSectionGetFieldDof(s, p, f, &fdof);CHKERRQ(ierr);
1566             ierr = PetscSectionGetFieldOffset(s, p, f, &foff);CHKERRQ(ierr);
1567             for (d = 0; d < fdof; ++d, ++cdoff) cellDofs[f][cdoff] = foff + d;
1568           }
1569           ierr = DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure);CHKERRQ(ierr);
1570         }
1571         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]);
1572       }
1573       numGlobalBcs = 0;
1574       for (p = pStart; p < pEnd; ++p) {
1575         const PetscInt *ind;
1576         PetscInt        off, cdof, d;
1577 
1578         ierr = PetscSectionGetOffset(s, p, &off);CHKERRQ(ierr);
1579         ierr = PetscSectionGetConstraintDof(s, p, &cdof);CHKERRQ(ierr);
1580         ierr = PetscSectionGetConstraintIndices(s, p, &ind);CHKERRQ(ierr);
1581         for (d = 0; d < cdof; ++d) globalBcs[numGlobalBcs++] = off + ind[d];
1582       }
1583 
1584       ierr = PCPatchSetDiscretisationInfoCombined(pc, dm, Nb, (const PetscInt **) cellDofs, numGlobalBcs, globalBcs, numGlobalBcs, globalBcs);CHKERRQ(ierr);
1585       for (f = 0; f < Nf; ++f) {
1586         ierr = PetscFree(cellDofs[f]);CHKERRQ(ierr);
1587       }
1588       ierr = PetscFree3(Nb, cellDofs, globalBcs);CHKERRQ(ierr);
1589       ierr = PCPatchSetComputeOperator(pc, PCPatchComputeOperator_DMPlex_Private, NULL);CHKERRQ(ierr);
1590     }
1591 
1592     localSize = patch->subspaceOffsets[patch->nsubspaces];
1593     ierr = VecCreateSeq(PETSC_COMM_SELF, localSize, &patch->localX);CHKERRQ(ierr);
1594     ierr = VecSetUp(patch->localX);CHKERRQ(ierr);
1595     ierr = VecDuplicate(patch->localX, &patch->localY);CHKERRQ(ierr);
1596     ierr = PCPatchCreateCellPatches(pc);CHKERRQ(ierr);
1597     ierr = PCPatchCreateCellPatchDiscretisationInfo(pc);CHKERRQ(ierr);
1598 
1599     /* OK, now build the work vectors */
1600     ierr = PetscSectionGetChart(patch->gtolCounts, &pStart, &pEnd);CHKERRQ(ierr);
1601     ierr = PetscMalloc1(patch->npatch, &patch->patchX);CHKERRQ(ierr);
1602     ierr = PetscMalloc1(patch->npatch, &patch->patchY);CHKERRQ(ierr);
1603 
1604     if(patch->multiplicative) {
1605       ierr = PetscMalloc1(patch->npatch, &patch->patchXWithArtificial);CHKERRQ(ierr);
1606       ierr = PetscMalloc1(patch->npatch, &patch->dofMappingWithoutToWithArtificial);CHKERRQ(ierr);
1607     }
1608     for (p = pStart; p < pEnd; ++p) {
1609       PetscInt dof;
1610 
1611       ierr = PetscSectionGetDof(patch->gtolCounts, p, &dof);CHKERRQ(ierr);
1612       ierr = VecCreateSeq(PETSC_COMM_SELF, dof, &patch->patchX[p-pStart]);CHKERRQ(ierr);
1613       ierr = VecSetUp(patch->patchX[p-pStart]);CHKERRQ(ierr);
1614       ierr = VecCreateSeq(PETSC_COMM_SELF, dof, &patch->patchY[p-pStart]);CHKERRQ(ierr);
1615       ierr = VecSetUp(patch->patchY[p-pStart]);CHKERRQ(ierr);
1616       if(patch->multiplicative) {
1617         ierr = PetscSectionGetDof(patch->gtolCountsWithArtificial, p, &dof);CHKERRQ(ierr);
1618         ierr = VecCreateSeq(PETSC_COMM_SELF, dof, &patch->patchXWithArtificial[p-pStart]);CHKERRQ(ierr);
1619         ierr = VecSetUp(patch->patchXWithArtificial[p-pStart]);CHKERRQ(ierr);
1620 
1621         /* Now build the mapping that for a dof in a patch WITHOUT dofs that have artificial bcs gives the */
1622         /* the index in the patch with all dofs */
1623         const PetscInt    *gtolArray, *gtolArrayWithArtificial = NULL;
1624         PetscInt           numPatchDofs, offset;
1625         PetscInt           numPatchDofsWithArtificial, offsetWithArtificial;
1626         ierr = ISGetIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
1627 
1628         ierr = PetscSectionGetDof(patch->gtolCounts, p, &numPatchDofs);CHKERRQ(ierr);
1629 
1630         ierr = PetscSectionGetOffset(patch->gtolCounts, p, &offset);CHKERRQ(ierr);
1631         ierr = ISGetIndices(patch->gtolWithArtificial, &gtolArrayWithArtificial);CHKERRQ(ierr);
1632         ierr = PetscSectionGetDof(patch->gtolCountsWithArtificial, p, &numPatchDofsWithArtificial);CHKERRQ(ierr);
1633         ierr = PetscSectionGetOffset(patch->gtolCountsWithArtificial, p, &offsetWithArtificial);CHKERRQ(ierr);
1634 
1635         PetscInt dofWithoutArtificialCounter = 0;
1636         PetscInt *patchWithoutArtificialToWithArtificialArray;
1637         ierr = PetscMalloc1(numPatchDofs, &patchWithoutArtificialToWithArtificialArray);CHKERRQ(ierr);
1638 
1639         ISCreateGeneral(PETSC_COMM_SELF, numPatchDofs, patchWithoutArtificialToWithArtificialArray, PETSC_OWN_POINTER, &patch->dofMappingWithoutToWithArtificial[p-pStart]);
1640         if (numPatchDofs == 0) continue;
1641         for(PetscInt i=0; i<numPatchDofsWithArtificial; i++) {
1642           if(gtolArrayWithArtificial[i+offsetWithArtificial] == gtolArray[offset+dofWithoutArtificialCounter]) {
1643             patchWithoutArtificialToWithArtificialArray[dofWithoutArtificialCounter] = i;
1644             dofWithoutArtificialCounter++;
1645             if(dofWithoutArtificialCounter == numPatchDofs)
1646               break;
1647           }
1648         }
1649         ierr = ISRestoreIndices(patch->gtol, &gtolArray);CHKERRQ(ierr);
1650         ierr = ISRestoreIndices(patch->gtolWithArtificial, &gtolArrayWithArtificial);CHKERRQ(ierr);
1651       }
1652     }
1653     ierr = PetscMalloc1(patch->npatch, &patch->ksp);CHKERRQ(ierr);
1654     ierr = PCGetOptionsPrefix(pc, &prefix);CHKERRQ(ierr);
1655     for (i = 0; i < patch->npatch; ++i) {
1656       PC subpc;
1657 
1658       ierr = KSPCreate(PETSC_COMM_SELF, &patch->ksp[i]);CHKERRQ(ierr);
1659       ierr = KSPSetOptionsPrefix(patch->ksp[i], prefix);CHKERRQ(ierr);
1660       ierr = KSPAppendOptionsPrefix(patch->ksp[i], "sub_");CHKERRQ(ierr);
1661       ierr = PetscObjectIncrementTabLevel((PetscObject) patch->ksp[i], (PetscObject) pc, 1);CHKERRQ(ierr);
1662       ierr = KSPGetPC(patch->ksp[i], &subpc);CHKERRQ(ierr);
1663       ierr = PetscObjectIncrementTabLevel((PetscObject) subpc, (PetscObject) pc, 1);CHKERRQ(ierr);
1664       ierr = PetscLogObjectParent((PetscObject) pc, (PetscObject) patch->ksp[i]);CHKERRQ(ierr);
1665     }
1666     if (patch->save_operators) {
1667       ierr = PetscMalloc1(patch->npatch, &patch->mat);CHKERRQ(ierr);
1668       for (i = 0; i < patch->npatch; ++i) {
1669         ierr = PCPatchCreateMatrix_Private(pc, i, &patch->mat[i], PETSC_FALSE);CHKERRQ(ierr);
1670       }
1671     }
1672     ierr = PetscLogEventEnd(PC_Patch_CreatePatches, pc, 0, 0, 0);CHKERRQ(ierr);
1673 
1674     /* If desired, calculate weights for dof multiplicity */
1675     if (patch->partition_of_unity) {
1676       ierr = VecDuplicate(patch->localX, &patch->dof_weights);CHKERRQ(ierr);
1677       if(!patch->multiplicative) {
1678         for (i = 0; i < patch->npatch; ++i) {
1679           PetscInt dof;
1680 
1681           ierr = PetscSectionGetDof(patch->gtolCounts, i+pStart, &dof);CHKERRQ(ierr);
1682           if (dof <= 0) continue;
1683           ierr = VecSet(patch->patchX[i], 1.0);CHKERRQ(ierr);
1684           ierr = PCPatch_ScatterLocal_Private(pc, i+pStart, patch->patchX[i], patch->dof_weights, ADD_VALUES, SCATTER_REVERSE, PETSC_FALSE);CHKERRQ(ierr);
1685         }
1686       } else {
1687         /* multiplicative is actually only locally multiplicative and globally additive. need the pou where the mesh decomposition overlaps */
1688         ierr = VecSet(patch->dof_weights, 1.0);CHKERRQ(ierr);
1689       }
1690 
1691       PetscScalar *input = NULL;
1692       PetscScalar *output = NULL;
1693       Vec global;
1694       VecDuplicate(patch->dof_weights, &global);
1695       VecSet(global, 0.);
1696 
1697       ierr = VecGetArray(patch->dof_weights, &input);CHKERRQ(ierr);
1698       ierr = VecGetArray(global, &output);CHKERRQ(ierr);
1699       ierr = PetscSFReduceBegin(patch->defaultSF, MPIU_SCALAR, input, output, MPI_SUM);CHKERRQ(ierr);
1700       ierr = PetscSFReduceEnd(patch->defaultSF, MPIU_SCALAR, input, output, MPI_SUM);CHKERRQ(ierr);
1701       ierr = VecRestoreArray(patch->dof_weights, &input);CHKERRQ(ierr);
1702       ierr = VecRestoreArray(global, &output);CHKERRQ(ierr);
1703 
1704       ierr = VecReciprocal(global);CHKERRQ(ierr);
1705 
1706       ierr = VecGetArray(patch->dof_weights, &output);CHKERRQ(ierr);
1707       ierr = VecGetArray(global, &input);CHKERRQ(ierr);
1708       ierr = PetscSFBcastBegin(patch->defaultSF, MPIU_SCALAR, input, output);CHKERRQ(ierr);
1709       ierr = PetscSFBcastEnd(patch->defaultSF, MPIU_SCALAR, input, output);CHKERRQ(ierr);
1710       ierr = VecRestoreArray(patch->dof_weights, &output);CHKERRQ(ierr);
1711       ierr = VecRestoreArray(global, &input);CHKERRQ(ierr);
1712       ierr = VecDestroy(&global);CHKERRQ(ierr);
1713     }
1714     if(patch->multiplicative && patch->save_operators) {
1715       ierr = PetscMalloc1(patch->npatch, &patch->matWithArtificial);CHKERRQ(ierr);
1716     }
1717   }
1718   if (patch->save_operators) {
1719     for (i = 0; i < patch->npatch; ++i) {
1720       ierr = MatZeroEntries(patch->mat[i]);CHKERRQ(ierr);
1721       ierr = PCPatchComputeOperator_Private(pc, patch->mat[i], i, PETSC_FALSE);CHKERRQ(ierr);
1722       ierr = KSPSetOperators(patch->ksp[i], patch->mat[i], patch->mat[i]);CHKERRQ(ierr);
1723     }
1724     if(patch->multiplicative) {
1725       for (i = 0; i < patch->npatch; ++i) {
1726         /* Instead of padding patch->patchY with zeros to get */
1727         /* patch->patchYWithArtificial and then multiplying with the matrix, */
1728         /* just get rid of the columns that correspond to the dofs with */
1729         /* artificial bcs. That's of course fairly inefficient, hopefully we */
1730         /* can just assemble the rectangular matrix in the first place. */
1731         Mat matSquare;
1732         IS rowis;
1733         PetscInt dof;
1734 
1735         ierr = MatGetSize(patch->mat[i], &dof, NULL);CHKERRQ(ierr);
1736         if (dof == 0) continue;
1737 
1738         ierr = PCPatchCreateMatrix_Private(pc, i, &matSquare, PETSC_TRUE);CHKERRQ(ierr);
1739         ierr = MatZeroEntries(matSquare);CHKERRQ(ierr);
1740         ierr = PCPatchComputeOperator_Private(pc, matSquare, i, PETSC_TRUE);CHKERRQ(ierr);
1741 
1742         ierr = MatGetSize(matSquare, &dof, NULL);CHKERRQ(ierr);
1743         ierr = ISCreateStride(PETSC_COMM_SELF, dof, 0, 1, &rowis); CHKERRQ(ierr);
1744         if(pc->setupcalled) {
1745           ierr = MatCreateSubMatrix(matSquare, rowis, patch->dofMappingWithoutToWithArtificial[i], MAT_REUSE_MATRIX, &patch->matWithArtificial[i]); CHKERRQ(ierr);
1746         } else {
1747           ierr = MatCreateSubMatrix(matSquare, rowis, patch->dofMappingWithoutToWithArtificial[i], MAT_INITIAL_MATRIX, &patch->matWithArtificial[i]); CHKERRQ(ierr);
1748         }
1749         ierr = ISDestroy(&rowis); CHKERRQ(ierr);
1750         ierr = MatDestroy(&matSquare);CHKERRQ(ierr);
1751       }
1752     }
1753   }
1754   PetscFunctionReturn(0);
1755 }
1756 
1757 static PetscErrorCode PCApply_PATCH(PC pc, Vec x, Vec y)
1758 {
1759   PC_PATCH          *patch    = (PC_PATCH *) pc->data;
1760   const PetscScalar *globalX  = NULL;
1761   PetscScalar       *localX   = NULL;
1762   PetscScalar       *globalY  = NULL;
1763   const PetscInt    *bcNodes  = NULL;
1764   PetscInt           nsweep   = patch->symmetrise_sweep ? 2 : 1;
1765   PetscInt           start[2] = {0, 0};
1766   PetscInt           end[2]   = {-1, -1};
1767   const PetscInt     inc[2]   = {1, -1};
1768   const PetscScalar *localY;
1769   const PetscInt    *iterationSet;
1770   PetscInt           pStart, numBcs, n, sweep, bc, j;
1771   PetscErrorCode     ierr;
1772 
1773   PetscFunctionBegin;
1774   ierr = PetscLogEventBegin(PC_Patch_Apply, pc, 0, 0, 0);CHKERRQ(ierr);
1775   ierr = PetscOptionsPushGetViewerOff(PETSC_TRUE);CHKERRQ(ierr);
1776   end[0]   = patch->npatch;
1777   start[1] = patch->npatch-1;
1778   if (patch->user_patches) {
1779     ierr = ISGetLocalSize(patch->iterationSet, &end[0]);CHKERRQ(ierr);
1780     start[1] = end[0] - 1;
1781     ierr = ISGetIndices(patch->iterationSet, &iterationSet);CHKERRQ(ierr);
1782   }
1783   /* Scatter from global space into overlapped local spaces */
1784   ierr = VecGetArrayRead(x, &globalX);CHKERRQ(ierr);
1785   ierr = VecGetArray(patch->localX, &localX);CHKERRQ(ierr);
1786   ierr = PetscSFBcastBegin(patch->defaultSF, MPIU_SCALAR, globalX, localX);CHKERRQ(ierr);
1787   ierr = PetscSFBcastEnd(patch->defaultSF, MPIU_SCALAR, globalX, localX);CHKERRQ(ierr);
1788   ierr = VecRestoreArrayRead(x, &globalX);CHKERRQ(ierr);
1789   ierr = VecRestoreArray(patch->localX, &localX);CHKERRQ(ierr);
1790 
1791   ierr = VecSet(patch->localY, 0.0);CHKERRQ(ierr);
1792   ierr = PetscSectionGetChart(patch->gtolCounts, &pStart, NULL);CHKERRQ(ierr);
1793   for (sweep = 0; sweep < nsweep; sweep++) {
1794     for (j = start[sweep]; j*inc[sweep] < end[sweep]*inc[sweep]; j += inc[sweep]) {
1795       PetscInt i       = patch->user_patches ? iterationSet[j] : j;
1796       PetscInt start, len;
1797 
1798       ierr = PetscSectionGetDof(patch->gtolCounts, i+pStart, &len);CHKERRQ(ierr);
1799       ierr = PetscSectionGetOffset(patch->gtolCounts, i+pStart, &start);CHKERRQ(ierr);
1800       /* TODO: Squash out these guys in the setup as well. */
1801       if (len <= 0) continue;
1802       /* TODO: Do we need different scatters for X and Y? */
1803       ierr = PCPatch_ScatterLocal_Private(pc, i+pStart, patch->localX, patch->patchX[i], INSERT_VALUES, SCATTER_FORWARD, PETSC_FALSE);CHKERRQ(ierr);
1804       if (!patch->save_operators) {
1805         Mat mat;
1806 
1807         ierr = PCPatchCreateMatrix_Private(pc, i, &mat, PETSC_FALSE);CHKERRQ(ierr);
1808         /* Populate operator here. */
1809         ierr = PCPatchComputeOperator_Private(pc, mat, i, PETSC_FALSE);CHKERRQ(ierr);
1810         ierr = KSPSetOperators(patch->ksp[i], mat, mat);CHKERRQ(ierr);
1811         /* Drop reference so the KSPSetOperators below will blow it away. */
1812         ierr = MatDestroy(&mat);CHKERRQ(ierr);
1813       }
1814       ierr = PetscLogEventBegin(PC_Patch_Solve, pc, 0, 0, 0);CHKERRQ(ierr);
1815       if (!patch->ksp[i]->setfromoptionscalled) {
1816         ierr = KSPSetFromOptions(patch->ksp[i]);CHKERRQ(ierr);
1817       }
1818       ierr = KSPSolve(patch->ksp[i], patch->patchX[i], patch->patchY[i]);CHKERRQ(ierr);
1819       ierr = PetscLogEventEnd(PC_Patch_Solve, pc, 0, 0, 0);CHKERRQ(ierr);
1820 
1821       if (!patch->save_operators) {
1822         PC pc;
1823         ierr = KSPSetOperators(patch->ksp[i], NULL, NULL);CHKERRQ(ierr);
1824         ierr = KSPGetPC(patch->ksp[i], &pc);CHKERRQ(ierr);
1825         /* Destroy PC context too, otherwise the factored matrix hangs around. */
1826         ierr = PCReset(pc);CHKERRQ(ierr);
1827       }
1828 
1829       ierr = PCPatch_ScatterLocal_Private(pc, i+pStart, patch->patchY[i], patch->localY, ADD_VALUES, SCATTER_REVERSE, PETSC_FALSE);CHKERRQ(ierr);
1830       if(patch->multiplicative){
1831         Mat multMat;
1832         if (patch->save_operators) {
1833           multMat = patch->matWithArtificial[i];
1834         } else {
1835           /*Very inefficient, hopefully we can just assemble the rectangular matrix in the first place.*/
1836           Mat matSquare;
1837           PetscInt dof;
1838           IS rowis;
1839           ierr = PCPatchCreateMatrix_Private(pc, i, &matSquare, PETSC_TRUE);CHKERRQ(ierr);
1840           ierr = MatZeroEntries(matSquare);CHKERRQ(ierr);
1841           ierr = PCPatchComputeOperator_Private(pc, matSquare, i, PETSC_TRUE);CHKERRQ(ierr);
1842           ierr = MatGetSize(matSquare, &dof, NULL);CHKERRQ(ierr);
1843           ierr = ISCreateStride(PETSC_COMM_SELF, dof, 0, 1, &rowis); CHKERRQ(ierr);
1844           ierr = MatCreateSubMatrix(matSquare, rowis, patch->dofMappingWithoutToWithArtificial[i], MAT_INITIAL_MATRIX, &multMat); CHKERRQ(ierr);
1845           ierr = MatDestroy(&matSquare);CHKERRQ(ierr);
1846           ierr = ISDestroy(&rowis); CHKERRQ(ierr);
1847         }
1848         ierr = MatMult(multMat, patch->patchY[i], patch->patchXWithArtificial[i]); CHKERRQ(ierr);
1849         ierr = VecScale(patch->patchXWithArtificial[i], -1.0); CHKERRQ(ierr);
1850         ierr = PCPatch_ScatterLocal_Private(pc, i + pStart, patch->patchXWithArtificial[i], patch->localX, ADD_VALUES, SCATTER_REVERSE, PETSC_TRUE); CHKERRQ(ierr);
1851         if (!patch->save_operators) {
1852           ierr = MatDestroy(&multMat); CHKERRQ(ierr);
1853         }
1854       }
1855     }
1856   }
1857   if (patch->user_patches) {ierr = ISRestoreIndices(patch->iterationSet, &iterationSet);CHKERRQ(ierr);}
1858   /* XXX: should we do this on the global vector? */
1859   if (patch->partition_of_unity) {
1860     ierr = VecPointwiseMult(patch->localY, patch->localY, patch->dof_weights);CHKERRQ(ierr);
1861   }
1862   /* Now patch->localY contains the solution of the patch solves, so we need to combine them all. */
1863   ierr = VecSet(y, 0.0);CHKERRQ(ierr);
1864   ierr = VecGetArray(y, &globalY);CHKERRQ(ierr);
1865   ierr = VecGetArrayRead(patch->localY, &localY);CHKERRQ(ierr);
1866   ierr = PetscSFReduceBegin(patch->defaultSF, MPIU_SCALAR, localY, globalY, MPI_SUM);CHKERRQ(ierr);
1867   ierr = PetscSFReduceEnd(patch->defaultSF, MPIU_SCALAR, localY, globalY, MPI_SUM);CHKERRQ(ierr);
1868   ierr = VecRestoreArrayRead(patch->localY, &localY);CHKERRQ(ierr);
1869 
1870   /* Now we need to send the global BC values through */
1871   ierr = VecGetArrayRead(x, &globalX);CHKERRQ(ierr);
1872   ierr = ISGetSize(patch->globalBcNodes, &numBcs);CHKERRQ(ierr);
1873   ierr = ISGetIndices(patch->globalBcNodes, &bcNodes);CHKERRQ(ierr);
1874   ierr = VecGetLocalSize(x, &n);CHKERRQ(ierr);
1875   for (bc = 0; bc < numBcs; ++bc) {
1876     const PetscInt idx = bcNodes[bc];
1877     if (idx < n) globalY[idx] = globalX[idx];
1878   }
1879 
1880   ierr = ISRestoreIndices(patch->globalBcNodes, &bcNodes);CHKERRQ(ierr);
1881   ierr = VecRestoreArrayRead(x, &globalX);CHKERRQ(ierr);
1882   ierr = VecRestoreArray(y, &globalY);CHKERRQ(ierr);
1883 
1884   ierr = PetscOptionsPopGetViewerOff();CHKERRQ(ierr);
1885   ierr = PetscLogEventEnd(PC_Patch_Apply, pc, 0, 0, 0);CHKERRQ(ierr);
1886   PetscFunctionReturn(0);
1887 }
1888 
1889 static PetscErrorCode PCReset_PATCH(PC pc)
1890 {
1891   PC_PATCH      *patch = (PC_PATCH *) pc->data;
1892   PetscInt       i;
1893   PetscErrorCode ierr;
1894 
1895   PetscFunctionBegin;
1896   /* TODO: Get rid of all these ifs */
1897   ierr = PetscSFDestroy(&patch->defaultSF);CHKERRQ(ierr);
1898   ierr = PetscSectionDestroy(&patch->cellCounts);CHKERRQ(ierr);
1899   ierr = PetscSectionDestroy(&patch->pointCounts);CHKERRQ(ierr);
1900   ierr = PetscSectionDestroy(&patch->cellNumbering);CHKERRQ(ierr);
1901   ierr = PetscSectionDestroy(&patch->gtolCounts);CHKERRQ(ierr);
1902   ierr = ISDestroy(&patch->gtol);CHKERRQ(ierr);
1903   ierr = ISDestroy(&patch->cells);CHKERRQ(ierr);
1904   ierr = ISDestroy(&patch->points);CHKERRQ(ierr);
1905   ierr = ISDestroy(&patch->dofs);CHKERRQ(ierr);
1906   ierr = ISDestroy(&patch->offs);CHKERRQ(ierr);
1907   ierr = PetscSectionDestroy(&patch->patchSection);CHKERRQ(ierr);
1908   ierr = ISDestroy(&patch->ghostBcNodes);CHKERRQ(ierr);
1909   ierr = ISDestroy(&patch->globalBcNodes);CHKERRQ(ierr);
1910   ierr = PetscSectionDestroy(&patch->gtolCountsWithArtificial);CHKERRQ(ierr);
1911   ierr = ISDestroy(&patch->gtolWithArtificial);CHKERRQ(ierr);
1912   ierr = ISDestroy(&patch->dofsWithArtificial);CHKERRQ(ierr);
1913   ierr = ISDestroy(&patch->offsWithArtificial);CHKERRQ(ierr);
1914 
1915 
1916   if (patch->dofSection) for (i = 0; i < patch->nsubspaces; i++) {ierr = PetscSectionDestroy(&patch->dofSection[i]);CHKERRQ(ierr);}
1917   ierr = PetscFree(patch->dofSection);CHKERRQ(ierr);
1918   ierr = PetscFree(patch->bs);CHKERRQ(ierr);
1919   ierr = PetscFree(patch->nodesPerCell);CHKERRQ(ierr);
1920   if (patch->cellNodeMap) for (i = 0; i < patch->nsubspaces; i++) {ierr = PetscFree(patch->cellNodeMap[i]);CHKERRQ(ierr);}
1921   ierr = PetscFree(patch->cellNodeMap);CHKERRQ(ierr);
1922   ierr = PetscFree(patch->subspaceOffsets);CHKERRQ(ierr);
1923 
1924   if (patch->ksp) {
1925     for (i = 0; i < patch->npatch; ++i) {ierr = KSPReset(patch->ksp[i]);CHKERRQ(ierr);}
1926   }
1927 
1928   if (patch->subspaces_to_exclude) {
1929     PetscHSetIDestroy(&patch->subspaces_to_exclude);
1930   }
1931 
1932   ierr = VecDestroy(&patch->localX);CHKERRQ(ierr);
1933   ierr = VecDestroy(&patch->localY);CHKERRQ(ierr);
1934   if (patch->patchX) {
1935     for (i = 0; i < patch->npatch; ++i) {ierr = VecDestroy(&patch->patchX[i]);CHKERRQ(ierr);}
1936     ierr = PetscFree(patch->patchX);CHKERRQ(ierr);
1937   }
1938   if (patch->patchY) {
1939     for (i = 0; i < patch->npatch; ++i) {ierr = VecDestroy(&patch->patchY[i]);CHKERRQ(ierr);}
1940     ierr = PetscFree(patch->patchY);CHKERRQ(ierr);
1941   }
1942   ierr = VecDestroy(&patch->dof_weights);CHKERRQ(ierr);
1943   if (patch->patch_dof_weights) {
1944     for (i = 0; i < patch->npatch; ++i) {ierr = VecDestroy(&patch->patch_dof_weights[i]);CHKERRQ(ierr);}
1945     ierr = PetscFree(patch->patch_dof_weights);CHKERRQ(ierr);
1946   }
1947   if (patch->mat) {
1948     for (i = 0; i < patch->npatch; ++i) {ierr = MatDestroy(&patch->mat[i]);CHKERRQ(ierr);}
1949     ierr = PetscFree(patch->mat);CHKERRQ(ierr);
1950   }
1951   if (patch->matWithArtificial) {
1952     for (i = 0; i < patch->npatch; ++i) {ierr = MatDestroy(&patch->matWithArtificial[i]);CHKERRQ(ierr);}
1953     ierr = PetscFree(patch->matWithArtificial);CHKERRQ(ierr);
1954   }
1955   if (patch->patchXWithArtificial) {
1956     for (i = 0; i < patch->npatch; ++i) {ierr = VecDestroy(&patch->patchXWithArtificial[i]);CHKERRQ(ierr);}
1957     ierr = PetscFree(patch->patchXWithArtificial);CHKERRQ(ierr);
1958   }
1959   if(patch->dofMappingWithoutToWithArtificial) {
1960     for (i = 0; i < patch->npatch; ++i) {ierr = ISDestroy(&patch->dofMappingWithoutToWithArtificial[i]);CHKERRQ(ierr);}
1961     ierr = PetscFree(patch->dofMappingWithoutToWithArtificial);CHKERRQ(ierr);
1962 
1963   }
1964   ierr = PetscFree(patch->sub_mat_type);CHKERRQ(ierr);
1965   if (patch->userIS) {
1966     for (i = 0; i < patch->npatch; ++i) {ierr = ISDestroy(&patch->userIS[i]);CHKERRQ(ierr);}
1967     ierr = PetscFree(patch->userIS);CHKERRQ(ierr);
1968   }
1969   patch->bs          = 0;
1970   patch->cellNodeMap = NULL;
1971   patch->nsubspaces  = 0;
1972   ierr = ISDestroy(&patch->iterationSet);CHKERRQ(ierr);
1973 
1974   ierr = PetscViewerDestroy(&patch->viewerSection);CHKERRQ(ierr);
1975   PetscFunctionReturn(0);
1976 }
1977 
1978 static PetscErrorCode PCDestroy_PATCH(PC pc)
1979 {
1980   PC_PATCH      *patch = (PC_PATCH *) pc->data;
1981   PetscInt       i;
1982   PetscErrorCode ierr;
1983 
1984   PetscFunctionBegin;
1985   ierr = PCReset_PATCH(pc);CHKERRQ(ierr);
1986   if (patch->ksp) {
1987     for (i = 0; i < patch->npatch; ++i) {ierr = KSPDestroy(&patch->ksp[i]);CHKERRQ(ierr);}
1988     ierr = PetscFree(patch->ksp);CHKERRQ(ierr);
1989   }
1990   ierr = PetscFree(pc->data);CHKERRQ(ierr);
1991   PetscFunctionReturn(0);
1992 }
1993 
1994 static PetscErrorCode PCSetFromOptions_PATCH(PetscOptionItems *PetscOptionsObject, PC pc)
1995 {
1996   PC_PATCH            *patch = (PC_PATCH *) pc->data;
1997   PCPatchConstructType patchConstructionType = PC_PATCH_STAR;
1998   char                 sub_mat_type[PETSC_MAX_PATH_LEN];
1999   const char          *prefix;
2000   PetscBool            flg, dimflg, codimflg;
2001   MPI_Comm             comm;
2002   PetscInt            *ifields, nfields, k;
2003   PetscErrorCode       ierr;
2004 
2005   PetscFunctionBegin;
2006   ierr = PetscObjectGetComm((PetscObject) pc, &comm);CHKERRQ(ierr);
2007   ierr = PetscObjectGetOptionsPrefix((PetscObject) pc, &prefix);CHKERRQ(ierr);
2008   ierr = PetscOptionsHead(PetscOptionsObject, "Vertex-patch Additive Schwarz options");CHKERRQ(ierr);
2009   ierr = PetscOptionsBool("-pc_patch_save_operators",  "Store all patch operators for lifetime of PC?", "PCPatchSetSaveOperators", patch->save_operators, &patch->save_operators, &flg);CHKERRQ(ierr);
2010   ierr = PetscOptionsBool("-pc_patch_partition_of_unity", "Weight contributions by dof multiplicity?", "PCPatchSetPartitionOfUnity", patch->partition_of_unity, &patch->partition_of_unity, &flg);CHKERRQ(ierr);
2011   ierr = PetscOptionsBool("-pc_patch_multiplicative", "Gauss-Seidel instead of Jacobi?", "PCPatchSetMultiplicative", patch->multiplicative, &patch->multiplicative, &flg);CHKERRQ(ierr);
2012   ierr = PetscOptionsInt("-pc_patch_construct_dim", "What dimension of mesh point to construct patches by? (0 = vertices)", "PCPATCH", patch->dim, &patch->dim, &dimflg);CHKERRQ(ierr);
2013   ierr = PetscOptionsInt("-pc_patch_construct_codim", "What co-dimension of mesh point to construct patches by? (0 = cells)", "PCPATCH", patch->codim, &patch->codim, &codimflg);CHKERRQ(ierr);
2014   if (dimflg && codimflg) SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Can only set one of dimension or co-dimension");CHKERRQ(ierr);
2015   ierr = PetscOptionsEnum("-pc_patch_construct_type", "How should the patches be constructed?", "PCPatchSetConstructType", PCPatchConstructTypes, (PetscEnum) patchConstructionType, (PetscEnum *) &patchConstructionType, &flg);CHKERRQ(ierr);
2016   if (flg) {ierr = PCPatchSetConstructType(pc, patchConstructionType, NULL, NULL);CHKERRQ(ierr);}
2017   ierr = PetscOptionsInt("-pc_patch_vanka_dim", "Topological dimension of entities for Vanka to ignore", "PCPATCH", patch->vankadim, &patch->vankadim, &flg);CHKERRQ(ierr);
2018   ierr = PetscOptionsInt("-pc_patch_ignore_dim", "Topological dimension of entities for completion to ignore", "PCPATCH", patch->ignoredim, &patch->ignoredim, &flg);CHKERRQ(ierr);
2019   ierr = PetscOptionsFList("-pc_patch_sub_mat_type", "Matrix type for patch solves", "PCPatchSetSubMatType", MatList, NULL, sub_mat_type, PETSC_MAX_PATH_LEN, &flg);CHKERRQ(ierr);
2020   if (flg) {ierr = PCPatchSetSubMatType(pc, sub_mat_type);CHKERRQ(ierr);}
2021   ierr = PetscOptionsBool("-pc_patch_symmetrise_sweep", "Go start->end, end->start?", "PCPATCH", patch->symmetrise_sweep, &patch->symmetrise_sweep, &flg);CHKERRQ(ierr);
2022 
2023   /* If the user has set the number of subspaces, use that for the buffer size,
2024      otherwise use a large number */
2025   if (patch->nsubspaces <= 0) {
2026     nfields = 128;
2027   } else {
2028     nfields = patch->nsubspaces;
2029   }
2030   ierr = PetscMalloc1(nfields, &ifields);CHKERRQ(ierr);
2031   ierr = PetscOptionsGetIntArray(((PetscObject)pc)->options,((PetscObject)pc)->prefix,"-pc_patch_exclude_subspaces",ifields,&nfields,&flg);CHKERRQ(ierr);
2032   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");
2033   if (flg) {
2034     PetscHSetIClear(patch->subspaces_to_exclude);
2035     for (k = 0; k < nfields; k++) {
2036       PetscHSetIAdd(patch->subspaces_to_exclude, ifields[k]);
2037     }
2038   }
2039   ierr = PetscFree(ifields);CHKERRQ(ierr);
2040 
2041   ierr = PetscOptionsBool("-pc_patch_patches_view", "Print out information during patch construction", "PCPATCH", patch->viewPatches, &patch->viewPatches, &flg);CHKERRQ(ierr);
2042   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options,prefix, "-pc_patch_cells_view",   &patch->viewerCells,   &patch->formatCells,   &patch->viewCells);CHKERRQ(ierr);
2043   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options,prefix, "-pc_patch_points_view",  &patch->viewerPoints,  &patch->formatPoints,  &patch->viewPoints);CHKERRQ(ierr);
2044   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options,prefix, "-pc_patch_section_view", &patch->viewerSection, &patch->formatSection, &patch->viewSection);CHKERRQ(ierr);
2045   ierr = PetscOptionsGetViewer(comm,((PetscObject) pc)->options,prefix, "-pc_patch_mat_view",     &patch->viewerMatrix,  &patch->formatMatrix,  &patch->viewMatrix);CHKERRQ(ierr);
2046   ierr = PetscOptionsTail();CHKERRQ(ierr);
2047   patch->optionsSet = PETSC_TRUE;
2048   PetscFunctionReturn(0);
2049 }
2050 
2051 static PetscErrorCode PCSetUpOnBlocks_PATCH(PC pc)
2052 {
2053   PC_PATCH          *patch = (PC_PATCH*) pc->data;
2054   KSPConvergedReason reason;
2055   PetscInt           i;
2056   PetscErrorCode     ierr;
2057 
2058   PetscFunctionBegin;
2059   if (!patch->save_operators) {
2060     /* Can't do this here because the sub KSPs don't have an operator attached yet. */
2061     PetscFunctionReturn(0);
2062   }
2063   for (i = 0; i < patch->npatch; ++i) {
2064     if (!patch->ksp[i]->setfromoptionscalled) {
2065       ierr = KSPSetFromOptions(patch->ksp[i]);CHKERRQ(ierr);
2066     }
2067     ierr = KSPSetUp(patch->ksp[i]);CHKERRQ(ierr);
2068     ierr = KSPGetConvergedReason(patch->ksp[i], &reason);CHKERRQ(ierr);
2069     if (reason == KSP_DIVERGED_PCSETUP_FAILED) pc->failedreason = PC_SUBPC_ERROR;
2070   }
2071   PetscFunctionReturn(0);
2072 }
2073 
2074 static PetscErrorCode PCView_PATCH(PC pc, PetscViewer viewer)
2075 {
2076   PC_PATCH      *patch = (PC_PATCH *) pc->data;
2077   PetscViewer    sviewer;
2078   PetscBool      isascii;
2079   PetscMPIInt    rank;
2080   PetscErrorCode ierr;
2081 
2082   PetscFunctionBegin;
2083   /* TODO Redo tabbing with set tbas in new style */
2084   ierr = PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &isascii);CHKERRQ(ierr);
2085   if (!isascii) PetscFunctionReturn(0);
2086   ierr = MPI_Comm_rank(PetscObjectComm((PetscObject) pc), &rank);CHKERRQ(ierr);
2087   ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
2088   ierr = PetscViewerASCIIPrintf(viewer, "Subspace Correction preconditioner with %d patches\n", patch->npatch);CHKERRQ(ierr);
2089   if(patch->multiplicative) {
2090     ierr = PetscViewerASCIIPrintf(viewer, "Schwarz type: multiplicative\n");CHKERRQ(ierr);
2091   } else {
2092     ierr = PetscViewerASCIIPrintf(viewer, "Schwarz type: additive\n");CHKERRQ(ierr);
2093   }
2094   if (patch->partition_of_unity) {ierr = PetscViewerASCIIPrintf(viewer, "Weighting by partition of unity\n");CHKERRQ(ierr);}
2095   else                           {ierr = PetscViewerASCIIPrintf(viewer, "Not weighting by partition of unity\n");CHKERRQ(ierr);}
2096   if (patch->symmetrise_sweep) {ierr = PetscViewerASCIIPrintf(viewer, "Symmetrising sweep (start->end, then end->start)\n");CHKERRQ(ierr);}
2097   else                         {ierr = PetscViewerASCIIPrintf(viewer, "Not symmetrising sweep\n");CHKERRQ(ierr);}
2098   if (!patch->save_operators) {ierr = PetscViewerASCIIPrintf(viewer, "Not saving patch operators (rebuilt every PCApply)\n");CHKERRQ(ierr);}
2099   else                        {ierr = PetscViewerASCIIPrintf(viewer, "Saving patch operators (rebuilt every PCSetUp)\n");CHKERRQ(ierr);}
2100   if (patch->patchconstructop == PCPatchConstruct_Star)       {ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: star\n");CHKERRQ(ierr);}
2101   else if (patch->patchconstructop == PCPatchConstruct_Vanka) {ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: Vanka\n");CHKERRQ(ierr);}
2102   else if (patch->patchconstructop == PCPatchConstruct_User)  {ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: user-specified\n");CHKERRQ(ierr);}
2103   else                                                        {ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: unknown\n");CHKERRQ(ierr);}
2104   ierr = PetscViewerASCIIPrintf(viewer, "KSP on patches (all same):\n");CHKERRQ(ierr);
2105   if (patch->ksp) {
2106     ierr = PetscViewerGetSubViewer(viewer, PETSC_COMM_SELF, &sviewer);CHKERRQ(ierr);
2107     if (!rank) {
2108       ierr = PetscViewerASCIIPushTab(sviewer);CHKERRQ(ierr);
2109       ierr = KSPView(patch->ksp[0], sviewer);CHKERRQ(ierr);
2110       ierr = PetscViewerASCIIPopTab(sviewer);CHKERRQ(ierr);
2111     }
2112     ierr = PetscViewerRestoreSubViewer(viewer, PETSC_COMM_SELF, &sviewer);CHKERRQ(ierr);
2113   } else {
2114     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
2115     ierr = PetscViewerASCIIPrintf(viewer, "KSP not yet set.\n");CHKERRQ(ierr);
2116     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
2117   }
2118   ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
2119   PetscFunctionReturn(0);
2120 }
2121 
2122 /*MC
2123   PCPATCH - A PC object that encapsulates flexible definition of blocks for overlapping and non-overlapping
2124             small block additive preconditioners. Block definition is based on topology from
2125             a DM and equation numbering from a PetscSection.
2126 
2127   Options Database Keys:
2128 + -pc_patch_cells_view   - Views the process local cell numbers for each patch
2129 . -pc_patch_points_view  - Views the process local mesh point numbers for each patch
2130 . -pc_patch_g2l_view     - Views the map between global dofs and patch local dofs for each patch
2131 . -pc_patch_patches_view - Views the global dofs associated with each patch and its boundary
2132 - -pc_patch_sub_mat_view - Views the matrix associated with each patch
2133 
2134   Level: intermediate
2135 
2136 .seealso: PCType, PCCreate(), PCSetType()
2137 M*/
2138 PETSC_EXTERN PetscErrorCode PCCreate_Patch(PC pc)
2139 {
2140   PC_PATCH      *patch;
2141   PetscErrorCode ierr;
2142 
2143   PetscFunctionBegin;
2144   ierr = PetscNewLog(pc, &patch);CHKERRQ(ierr);
2145 
2146   if (patch->subspaces_to_exclude) {
2147     PetscHSetIDestroy(&patch->subspaces_to_exclude);
2148   }
2149   PetscHSetICreate(&patch->subspaces_to_exclude);
2150 
2151   /* Set some defaults */
2152   patch->combined           = PETSC_FALSE;
2153   patch->save_operators     = PETSC_TRUE;
2154   patch->multiplicative     = PETSC_FALSE;
2155   patch->partition_of_unity = PETSC_FALSE;
2156   patch->codim              = -1;
2157   patch->dim                = -1;
2158   patch->vankadim           = -1;
2159   patch->ignoredim          = -1;
2160   patch->patchconstructop   = PCPatchConstruct_Star;
2161   patch->symmetrise_sweep   = PETSC_FALSE;
2162   patch->npatch             = 0;
2163   patch->userIS             = NULL;
2164   patch->optionsSet         = PETSC_FALSE;
2165   patch->iterationSet       = NULL;
2166   patch->user_patches       = PETSC_FALSE;
2167   ierr = PetscStrallocpy(MATDENSE, (char **) &patch->sub_mat_type);CHKERRQ(ierr);
2168   patch->viewPatches        = PETSC_FALSE;
2169   patch->viewCells          = PETSC_FALSE;
2170   patch->viewPoints         = PETSC_FALSE;
2171   patch->viewSection        = PETSC_FALSE;
2172   patch->viewMatrix         = PETSC_FALSE;
2173 
2174   pc->data                 = (void *) patch;
2175   pc->ops->apply           = PCApply_PATCH;
2176   pc->ops->applytranspose  = 0; /* PCApplyTranspose_PATCH; */
2177   pc->ops->setup           = PCSetUp_PATCH;
2178   pc->ops->reset           = PCReset_PATCH;
2179   pc->ops->destroy         = PCDestroy_PATCH;
2180   pc->ops->setfromoptions  = PCSetFromOptions_PATCH;
2181   pc->ops->setuponblocks   = PCSetUpOnBlocks_PATCH;
2182   pc->ops->view            = PCView_PATCH;
2183   pc->ops->applyrichardson = 0;
2184 
2185   PetscFunctionReturn(0);
2186 }
2187