xref: /petsc/src/ts/utils/dmplexlandau/plexland.c (revision ed5e4e85792117e4bf875eb7efb50a9b8564ac26)
1 #include <petsc/private/dmpleximpl.h>   /*I "petscdmplex.h" I*/
2 #include <petsclandau.h>                /*I "petsclandau.h"   I*/
3 #include <petscts.h>
4 #include <petscdmforest.h>
5 #include <petscdmcomposite.h>
6 
7 /* Landau collision operator */
8 
9 /* relativistic terms */
10 #if defined(PETSC_USE_REAL_SINGLE)
11 #define SPEED_OF_LIGHT 2.99792458e8F
12 #define C_0(v0) (SPEED_OF_LIGHT/v0) /* needed for relativistic tensor on all architectures */
13 #else
14 #define SPEED_OF_LIGHT 2.99792458e8
15 #define C_0(v0) (SPEED_OF_LIGHT/v0) /* needed for relativistic tensor on all architectures */
16 #endif
17 
18 #define PETSC_THREAD_SYNC
19 #include "land_tensors.h"
20 
21 #if defined(PETSC_HAVE_OPENMP)
22 #include <omp.h>
23 #endif
24 
25 /* vector padding not supported */
26 #define LANDAU_VL  1
27 
28 static PetscErrorCode LandauGPUMapsDestroy(void *ptr)
29 {
30   P4estVertexMaps *maps = (P4estVertexMaps*)ptr;
31   PetscErrorCode  ierr;
32   PetscFunctionBegin;
33   // free device data
34   if (maps[0].deviceType != LANDAU_CPU) {
35 #if defined(PETSC_HAVE_KOKKOS_KERNELS)
36     if (maps[0].deviceType == LANDAU_KOKKOS) {
37       ierr = LandauKokkosDestroyMatMaps(maps,  maps[0].numgrids);CHKERRQ(ierr); // imples Kokkos does
38     } // else could be CUDA
39 #elif defined(PETSC_HAVE_CUDA)
40     if (maps[0].deviceType == LANDAU_CUDA) {
41       ierr = LandauCUDADestroyMatMaps(maps, maps[0].numgrids);CHKERRQ(ierr);
42     } else SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_PLIB, "maps->deviceType %D ?????",maps->deviceType);
43 #endif
44   }
45   // free host data
46   for (PetscInt grid=0 ; grid < maps[0].numgrids ; grid++) {
47     ierr = PetscFree(maps[grid].c_maps);CHKERRQ(ierr);
48     ierr = PetscFree(maps[grid].gIdx);CHKERRQ(ierr);
49   }
50   ierr = PetscFree(maps);CHKERRQ(ierr);
51 
52   PetscFunctionReturn(0);
53 }
54 static PetscErrorCode energy_f(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf_dummy, PetscScalar *u, void *actx)
55 {
56   PetscReal     v2 = 0;
57   PetscFunctionBegin;
58   /* compute v^2 / 2 */
59   for (int i = 0; i < dim; ++i) v2 += x[i]*x[i];
60   /* evaluate the Maxwellian */
61   u[0] = v2/2;
62   PetscFunctionReturn(0);
63 }
64 
65 /* needs double */
66 static PetscErrorCode gamma_m1_f(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf_dummy, PetscScalar *u, void *actx)
67 {
68   PetscReal     *c2_0_arr = ((PetscReal*)actx);
69   double        u2 = 0, c02 = (double)*c2_0_arr, xx;
70 
71   PetscFunctionBegin;
72   /* compute u^2 / 2 */
73   for (int i = 0; i < dim; ++i) u2 += x[i]*x[i];
74   /* gamma - 1 = g_eps, for conditioning and we only take derivatives */
75   xx = u2/c02;
76 #if defined(PETSC_USE_DEBUG)
77   u[0] = PetscSqrtReal(1. + xx);
78 #else
79   u[0] = xx/(PetscSqrtReal(1. + xx) + 1.) - 1.; // better conditioned. -1 might help condition and only used for derivative
80 #endif
81   PetscFunctionReturn(0);
82 }
83 
84 /*
85  LandauFormJacobian_Internal - Evaluates Jacobian matrix.
86 
87  Input Parameters:
88  .  globX - input vector
89  .  actx - optional user-defined context
90  .  dim - dimension
91 
92  Output Parameters:
93  .  J0acP - Jacobian matrix filled, not created
94  */
95 static PetscErrorCode LandauFormJacobian_Internal(Vec a_X, Mat JacP, const PetscInt dim, PetscReal shift, void *a_ctx)
96 {
97   LandauCtx         *ctx = (LandauCtx*)a_ctx;
98   PetscErrorCode    ierr;
99   PetscInt          numCells[LANDAU_MAX_GRIDS],Nq,Nb,Nf[LANDAU_MAX_GRIDS],N;
100   PetscQuadrature   quad;
101   const PetscReal   *quadWeights;
102   PetscTabulation   *Tf; // used for CPU and print info. Same on all grids and all species
103   PetscReal         Eq_m[LANDAU_MAX_SPECIES], m_0=ctx->m_0; /* normalize mass -- not needed! */
104   PetscScalar       *cellClosure=NULL;
105   const PetscScalar *xdata=NULL;
106   PetscDS           prob;
107   //PetscLogDouble    flops;
108   PetscContainer    container;
109   P4estVertexMaps   *maps;
110   PetscSection      section[LANDAU_MAX_GRIDS],globsection[LANDAU_MAX_GRIDS];
111   Mat               subJ[LANDAU_MAX_GRIDS*LANDAU_MAX_BATCH_SZ];
112 
113   PetscFunctionBegin;
114   PetscValidHeaderSpecific(a_X,VEC_CLASSID,1);
115   PetscValidHeaderSpecific(JacP,MAT_CLASSID,2);
116   PetscValidPointer(ctx,5);
117   /* check for matrix container for GPU assembly */
118   ierr = PetscLogEventBegin(ctx->events[10],0,0,0,0);CHKERRQ(ierr);
119   ierr = DMGetDS(ctx->plex[0], &prob);CHKERRQ(ierr); // same DS for all grids
120   ierr = PetscDSGetTabulation(prob, &Tf);CHKERRQ(ierr); // Bf, &Df same for all grids
121   ierr = PetscObjectQuery((PetscObject) JacP, "assembly_maps", (PetscObject *) &container);CHKERRQ(ierr);
122   if (container) {
123     if (!ctx->gpu_assembly) SETERRQ(ctx->comm,PETSC_ERR_ARG_WRONG,"GPU matrix container but no GPU assembly");
124     ierr = PetscContainerGetPointer(container, (void **) &maps);CHKERRQ(ierr);
125     if (!maps) SETERRQ(ctx->comm,PETSC_ERR_ARG_WRONG,"empty GPU matrix container");
126     for (PetscInt i=0;i<ctx->num_grids*ctx->batch_sz;i++) subJ[i] = NULL;
127   } else {
128     for (PetscInt tid=0 ; tid<ctx->batch_sz ; tid++) {
129       for (PetscInt grid=0;grid<ctx->num_grids;grid++) {
130         ierr = DMCreateMatrix(ctx->plex[grid], &subJ[ LAND_PACK_IDX(tid,grid) ]);CHKERRQ(ierr);
131       }
132     }
133     maps = NULL;
134   }
135   /* DS, Tab and quad is same on all grids */
136   if (ctx->plex[0] == NULL) SETERRQ(ctx->comm,PETSC_ERR_ARG_WRONG,"Plex not created");
137   ierr = PetscFEGetQuadrature(ctx->fe[0], &quad);CHKERRQ(ierr);
138   ierr = PetscQuadratureGetData(quad, NULL, NULL, &Nq, NULL, &quadWeights);CHKERRQ(ierr); Nb = Nq;
139   if (Nq >LANDAU_MAX_NQ) SETERRQ2(ctx->comm,PETSC_ERR_ARG_WRONG,"Order too high. Nq = %D > LANDAU_MAX_NQ (%D)",Nq,LANDAU_MAX_NQ);
140   if (LANDAU_DIM != dim) SETERRQ2(ctx->comm, PETSC_ERR_PLIB, "dim %D != LANDAU_DIM %d",dim,LANDAU_DIM);
141   /* setup each grid */
142   for (PetscInt grid=0;grid<ctx->num_grids;grid++) {
143     PetscInt cStart, cEnd;
144     if (ctx->plex[grid] == NULL) SETERRQ(ctx->comm,PETSC_ERR_ARG_WRONG,"Plex not created");
145     ierr = DMPlexGetHeightStratum(ctx->plex[grid], 0, &cStart, &cEnd);CHKERRQ(ierr);
146     numCells[grid] = cEnd - cStart; // grids can have different topology
147     ierr = DMGetLocalSection(ctx->plex[grid], &section[grid]);CHKERRQ(ierr);
148     ierr = DMGetGlobalSection(ctx->plex[grid], &globsection[grid]);CHKERRQ(ierr);
149     ierr = PetscSectionGetNumFields(section[grid], &Nf[grid]);CHKERRQ(ierr);
150   }
151   ierr = VecGetSize(a_X,&N);CHKERRQ(ierr);
152   ierr = PetscLogEventEnd(ctx->events[10],0,0,0,0);CHKERRQ(ierr);
153   if (!ctx->initialized) { /* create static point data, Jacobian called first, only one vertex copy */
154     PetscReal       *invJe,*ww,*xx,*yy,*zz=NULL,*invJ_a;
155     PetscInt        outer_ipidx, outer_ej,grid, nip_glb = 0;
156     PetscFE         fe;
157 
158     ierr = PetscLogEventBegin(ctx->events[7],0,0,0,0);CHKERRQ(ierr);
159     ierr = PetscInfo(ctx->plex[0], "Initialize static data\n");CHKERRQ(ierr);
160     for (PetscInt grid=0;grid<ctx->num_grids;grid++) nip_glb += Nq*numCells[grid];
161     /* collect f data, first time is for Jacobian, but make mass now */
162     if (ctx->verbose > 0) {
163       PetscInt ncells = 0;
164       for (PetscInt grid=0;grid<ctx->num_grids;grid++) ncells += numCells[grid];
165       ierr = PetscPrintf(ctx->comm,"%D) %s %D IPs, %D cells total, Nb=%D, Nq=%D, dim=%D, Tab: Nb=%D Nf=%D Np=%D cdim=%D N=%D\n",
166                          0,"FormLandau",nip_glb,ncells, Nb, Nq, dim, Tf[0]->Nb, ctx->num_species, Tf[0]->Np, Tf[0]->cdim, N);CHKERRQ(ierr);
167     }
168     ierr = PetscMalloc4(nip_glb,&ww,nip_glb,&xx,nip_glb,&yy,nip_glb*dim*dim,&invJ_a);CHKERRQ(ierr);
169     if (dim==3) {
170       ierr = PetscMalloc1(nip_glb,&zz);CHKERRQ(ierr);
171     }
172     if (ctx->use_energy_tensor_trick) {
173       ierr = PetscFECreateDefault(PETSC_COMM_SELF, dim, 1, PETSC_FALSE, NULL, PETSC_DECIDE, &fe);CHKERRQ(ierr);
174       ierr = PetscObjectSetName((PetscObject) fe, "energy");CHKERRQ(ierr);
175     }
176     /* init each grids static data - no batch */
177     for (grid=0, outer_ipidx=0, outer_ej=0 ; grid < ctx->num_grids ; grid++) { // OpenMP (once)
178       Vec             v2_2 = NULL; // projected function: v^2/2 for non-relativistic, gamma... for relativistic
179       PetscSection    e_section;
180       DM              dmEnergy;
181       PetscInt        cStart, cEnd, ej;
182 
183       ierr = DMPlexGetHeightStratum(ctx->plex[grid], 0, &cStart, &cEnd);CHKERRQ(ierr);
184       // prep energy trick, get v^2 / 2 vector
185       if (ctx->use_energy_tensor_trick) {
186         PetscErrorCode (*energyf[1])(PetscInt, PetscReal, const PetscReal [], PetscInt, PetscScalar [], void *) = {ctx->use_relativistic_corrections ? gamma_m1_f : energy_f};
187         Vec            glob_v2;
188         PetscReal      *c2_0[1], data[1] = {PetscSqr(C_0(ctx->v_0))};
189 
190         ierr = DMClone(ctx->plex[grid], &dmEnergy);CHKERRQ(ierr);
191         ierr = PetscObjectSetName((PetscObject) dmEnergy, "energy");CHKERRQ(ierr);
192         ierr = DMSetField(dmEnergy, 0, NULL, (PetscObject)fe);CHKERRQ(ierr);
193         ierr = DMCreateDS(dmEnergy);CHKERRQ(ierr);
194         ierr = DMGetSection(dmEnergy, &e_section);CHKERRQ(ierr);
195         ierr = DMGetGlobalVector(dmEnergy,&glob_v2);CHKERRQ(ierr);
196         ierr = PetscObjectSetName((PetscObject) glob_v2, "trick");CHKERRQ(ierr);
197         c2_0[0] = &data[0];
198         ierr = DMProjectFunction(dmEnergy, 0., energyf, (void**)c2_0, INSERT_ALL_VALUES, glob_v2);CHKERRQ(ierr);
199         ierr = DMGetLocalVector(dmEnergy, &v2_2);CHKERRQ(ierr);
200         ierr = VecZeroEntries(v2_2);CHKERRQ(ierr); /* zero BCs so don't set */
201         ierr = DMGlobalToLocalBegin(dmEnergy, glob_v2, INSERT_VALUES, v2_2);CHKERRQ(ierr);
202         ierr = DMGlobalToLocalEnd  (dmEnergy, glob_v2, INSERT_VALUES, v2_2);CHKERRQ(ierr);
203         ierr = DMViewFromOptions(dmEnergy,NULL, "-energy_dm_view");CHKERRQ(ierr);
204         ierr = VecViewFromOptions(glob_v2,NULL, "-energy_vec_view");CHKERRQ(ierr);
205         ierr = DMRestoreGlobalVector(dmEnergy, &glob_v2);CHKERRQ(ierr);
206       }
207       /* append part of the IP data for each grid */
208       for (ej = 0 ; ej < numCells[grid]; ++ej, ++outer_ej) {
209         PetscScalar *coefs = NULL;
210         PetscReal    vj[LANDAU_MAX_NQ*LANDAU_DIM],detJj[LANDAU_MAX_NQ], Jdummy[LANDAU_MAX_NQ*LANDAU_DIM*LANDAU_DIM], c0 = C_0(ctx->v_0), c02 = PetscSqr(c0);
211         invJe = invJ_a + outer_ej*Nq*dim*dim;
212         ierr = DMPlexComputeCellGeometryFEM(ctx->plex[grid], ej+cStart, quad, vj, Jdummy, invJe, detJj);CHKERRQ(ierr);
213         if (ctx->use_energy_tensor_trick) {
214           ierr = DMPlexVecGetClosure(dmEnergy, e_section, v2_2, ej+cStart, NULL, &coefs);CHKERRQ(ierr);
215         }
216         /* create static point data */
217         for (PetscInt qj = 0; qj < Nq; qj++, outer_ipidx++) {
218           const PetscInt  gidx = outer_ipidx;
219           const PetscReal *invJ = &invJe[qj*dim*dim];
220           ww    [gidx] = detJj[qj] * quadWeights[qj];
221           if (dim==2) ww    [gidx] *=              vj[qj * dim + 0];  /* cylindrical coordinate, w/o 2pi */
222           // get xx, yy, zz
223           if (ctx->use_energy_tensor_trick) {
224             double                  refSpaceDer[3],eGradPhi[3];
225             const PetscReal * const DD = Tf[0]->T[1];
226             const PetscReal         *Dq = &DD[qj*Nb*dim];
227             for (int d = 0; d < 3; ++d) refSpaceDer[d] = eGradPhi[d] = 0.0;
228             for (int b = 0; b < Nb; ++b) {
229               for (int d = 0; d < dim; ++d) refSpaceDer[d] += Dq[b*dim+d]*PetscRealPart(coefs[b]);
230             }
231             xx[gidx] = 1e10;
232             if (ctx->use_relativistic_corrections) {
233               double dg2_c2 = 0;
234               //for (int d = 0; d < dim; ++d) refSpaceDer[d] *= c02;
235               for (int d = 0; d < dim; ++d) dg2_c2 += PetscSqr(refSpaceDer[d]);
236               dg2_c2 *= (double)c02;
237               if (dg2_c2 >= .999) {
238                 xx[gidx] = vj[qj * dim + 0]; /* coordinate */
239                 yy[gidx] = vj[qj * dim + 1];
240                 if (dim==3) zz[gidx] = vj[qj * dim + 2];
241                 PetscPrintf(ctx->comm,"Error: %12.5e %D.%D) dg2/c02 = %12.5e x= %12.5e %12.5e %12.5e\n",PetscSqrtReal(xx[gidx]*xx[gidx] + yy[gidx]*yy[gidx] + zz[gidx]*zz[gidx]), ej, qj, dg2_c2, xx[gidx],yy[gidx],zz[gidx]);
242               } else {
243                 PetscReal fact = c02/PetscSqrtReal(1. - dg2_c2);
244                 for (int d = 0; d < dim; ++d) refSpaceDer[d] *= fact;
245                 // could test with other point u' that (grad - grad') * U (refSpaceDer, refSpaceDer') == 0
246               }
247             }
248             if (xx[gidx] == 1e10) {
249               for (int d = 0; d < dim; ++d) {
250                 for (int e = 0 ; e < dim; ++e) {
251                   eGradPhi[d] += invJ[e*dim+d]*refSpaceDer[e];
252                 }
253               }
254               xx[gidx] = eGradPhi[0];
255               yy[gidx] = eGradPhi[1];
256               if (dim==3) zz[gidx] = eGradPhi[2];
257             }
258           } else {
259             xx[gidx] = vj[qj * dim + 0]; /* coordinate */
260             yy[gidx] = vj[qj * dim + 1];
261             if (dim==3) zz[gidx] = vj[qj * dim + 2];
262           }
263         } /* q */
264         if (ctx->use_energy_tensor_trick) {
265           ierr = DMPlexVecRestoreClosure(dmEnergy, e_section, v2_2, ej+cStart, NULL, &coefs);CHKERRQ(ierr);
266         }
267       } /* ej */
268       if (ctx->use_energy_tensor_trick) {
269         ierr = DMRestoreLocalVector(dmEnergy, &v2_2);CHKERRQ(ierr);
270         ierr = DMDestroy(&dmEnergy);CHKERRQ(ierr);
271       }
272     } /* grid */
273     if (ctx->use_energy_tensor_trick) {
274       ierr = PetscFEDestroy(&fe);CHKERRQ(ierr);
275     }
276     /* cache static data */
277     if (ctx->deviceType == LANDAU_CUDA || ctx->deviceType == LANDAU_KOKKOS) {
278 #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_KOKKOS_KERNELS)
279       PetscReal invMass[LANDAU_MAX_SPECIES],nu_alpha[LANDAU_MAX_SPECIES], nu_beta[LANDAU_MAX_SPECIES];
280       for (PetscInt grid = 0; grid < ctx->num_grids ; grid++) {
281         for (PetscInt ii=ctx->species_offset[grid];ii<ctx->species_offset[grid+1];ii++) {
282           invMass[ii] = m_0/ctx->masses[ii];
283           nu_alpha[ii] = PetscSqr(ctx->charges[ii]/m_0)*m_0/ctx->masses[ii];
284           nu_beta[ii] = PetscSqr(ctx->charges[ii]/ctx->epsilon0)*ctx->lnLam / (8*PETSC_PI) * ctx->t_0*ctx->n_0/PetscPowReal(ctx->v_0,3);
285         }
286       }
287       if (ctx->deviceType == LANDAU_CUDA) {
288 #if defined(PETSC_HAVE_CUDA)
289         ierr = LandauCUDAStaticDataSet(ctx->plex[0], Nq, ctx->batch_sz, ctx->num_grids, numCells, ctx->species_offset, ctx->mat_offset,
290                                        nu_alpha, nu_beta, invMass, invJ_a, xx, yy, zz, ww, &ctx->SData_d);CHKERRQ(ierr);
291 #else
292         SETERRQ1(ctx->comm,PETSC_ERR_ARG_WRONG,"-landau_device_type %s not built","cuda");
293 #endif
294       } else if (ctx->deviceType == LANDAU_KOKKOS) {
295 #if defined(PETSC_HAVE_KOKKOS_KERNELS)
296         ierr = LandauKokkosStaticDataSet(ctx->plex[0], Nq, ctx->batch_sz, ctx->num_grids, numCells, ctx->species_offset, ctx->mat_offset,
297                                          nu_alpha, nu_beta, invMass,invJ_a,xx,yy,zz,ww,&ctx->SData_d);CHKERRQ(ierr);
298 #else
299         SETERRQ1(ctx->comm,PETSC_ERR_ARG_WRONG,"-landau_device_type %s not built","kokkos");
300 #endif
301       }
302 #endif
303       /* free */
304       ierr = PetscFree4(ww,xx,yy,invJ_a);CHKERRQ(ierr);
305       if (dim==3) {
306         ierr = PetscFree(zz);CHKERRQ(ierr);
307       }
308     } else { /* CPU version, just copy in, only use part */
309       ctx->SData_d.w = (void*)ww;
310       ctx->SData_d.x = (void*)xx;
311       ctx->SData_d.y = (void*)yy;
312       ctx->SData_d.z = (void*)zz;
313       ctx->SData_d.invJ = (void*)invJ_a;
314     }
315     ctx->initialized = PETSC_TRUE;
316     ierr = PetscLogEventEnd(ctx->events[7],0,0,0,0);CHKERRQ(ierr);
317   } // initialize
318   if (shift==0) { /* create dynamic point data: f_alpha for closure of each cell (cellClosure[nbatch,ngrids,ncells[g],f[Nb,ns[g]]]) or xdata */
319     DM pack;
320     ierr = VecGetDM(a_X, &pack);CHKERRQ(ierr);
321     if (!pack) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "pack has no DM");
322     ierr = PetscLogEventBegin(ctx->events[1],0,0,0,0);CHKERRQ(ierr);
323     ierr = MatZeroEntries(JacP);CHKERRQ(ierr);
324     for (PetscInt fieldA=0;fieldA<ctx->num_species;fieldA++) {
325       Eq_m[fieldA] = ctx->Ez * ctx->t_0 * ctx->charges[fieldA] / (ctx->v_0 * ctx->masses[fieldA]); /* normalize dimensionless */
326       if (dim==2) Eq_m[fieldA] *=  2 * PETSC_PI; /* add the 2pi term that is not in Landau */
327     }
328     if (!ctx->gpu_assembly || !container) {
329       Vec         *locXArray,*globXArray;
330       PetscScalar *cellClosure_it;
331       PetscInt    cellClosure_sz=0,nDMs;
332       /* count cellClosure size */
333       ierr = DMCompositeGetNumberDM(pack,&nDMs);CHKERRQ(ierr);
334       for (PetscInt grid=0 ; grid<ctx->num_grids ; grid++) cellClosure_sz += Nb*Nf[grid]*numCells[grid];
335       ierr = PetscMalloc1(cellClosure_sz*ctx->batch_sz,&cellClosure);CHKERRQ(ierr);
336       cellClosure_it = cellClosure;
337       ierr = PetscMalloc(sizeof(*locXArray)*nDMs, &locXArray);CHKERRQ(ierr);
338       ierr = PetscMalloc(sizeof(*globXArray)*nDMs, &globXArray);CHKERRQ(ierr);
339       ierr = DMCompositeGetLocalAccessArray(pack, a_X, nDMs, NULL, locXArray);CHKERRQ(ierr);
340       ierr = DMCompositeGetAccessArray(pack, a_X, nDMs, NULL, globXArray);CHKERRQ(ierr);
341       for (PetscInt b_id = 0 ; b_id < ctx->batch_sz ; b_id++) { // OpenMP (once)
342         for (PetscInt grid=0 ; grid<ctx->num_grids ; grid++) {
343           Vec         locX = locXArray[ LAND_PACK_IDX(b_id,grid) ], globX = globXArray[ LAND_PACK_IDX(b_id,grid) ], locX2;
344           PetscInt    cStart, cEnd, ei;
345           ierr = VecDuplicate(locX,&locX2);CHKERRQ(ierr);
346           ierr = DMGlobalToLocalBegin(ctx->plex[grid], globX, INSERT_VALUES, locX2);CHKERRQ(ierr);
347           ierr = DMGlobalToLocalEnd  (ctx->plex[grid], globX, INSERT_VALUES, locX2);CHKERRQ(ierr);
348           ierr = DMPlexGetHeightStratum(ctx->plex[grid], 0, &cStart, &cEnd);CHKERRQ(ierr);
349           for (ei = cStart ; ei < cEnd; ++ei) {
350             PetscScalar *coef = NULL;
351             ierr = DMPlexVecGetClosure(ctx->plex[grid], section[grid], locX2, ei, NULL, &coef);CHKERRQ(ierr);
352             ierr = PetscMemcpy(cellClosure_it,coef,Nb*Nf[grid]*sizeof(*cellClosure_it));CHKERRQ(ierr); /* change if LandauIPReal != PetscScalar */
353             ierr = DMPlexVecRestoreClosure(ctx->plex[grid], section[grid], locX2, ei, NULL, &coef);CHKERRQ(ierr);
354             cellClosure_it += Nb*Nf[grid];
355           }
356           ierr = VecDestroy(&locX2);CHKERRQ(ierr);
357         }
358       }
359       if (cellClosure_it-cellClosure != cellClosure_sz*ctx->batch_sz) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "iteration wrong %D != cellClosure_sz = %D",cellClosure_it-cellClosure,cellClosure_sz*ctx->batch_sz);
360       ierr = DMCompositeRestoreLocalAccessArray(pack, a_X, nDMs, NULL, locXArray);CHKERRQ(ierr);
361       ierr = DMCompositeRestoreAccessArray(pack, a_X, nDMs, NULL, globXArray);CHKERRQ(ierr);
362       ierr = PetscFree(locXArray);CHKERRQ(ierr);
363       ierr = PetscFree(globXArray);CHKERRQ(ierr);
364       xdata = NULL;
365     } else {
366       PetscMemType mtype;
367       ierr = VecGetArrayReadAndMemType(a_X,&xdata,&mtype);CHKERRQ(ierr);
368       if (mtype!=PETSC_MEMTYPE_HOST && ctx->deviceType == LANDAU_CPU) {
369         SETERRQ(ctx->comm,PETSC_ERR_ARG_WRONG,"CPU run with device data: use -mat_type aij");
370       }
371       cellClosure = NULL;
372     }
373     ierr = PetscLogEventEnd(ctx->events[1],0,0,0,0);CHKERRQ(ierr);
374   } else xdata = cellClosure = NULL;
375 
376   /* do it */
377   if (ctx->deviceType == LANDAU_CUDA || ctx->deviceType == LANDAU_KOKKOS) {
378     if (ctx->deviceType == LANDAU_CUDA) {
379 #if defined(PETSC_HAVE_CUDA)
380       ierr = LandauCUDAJacobian(ctx->plex,Nq,ctx->batch_sz,ctx->num_grids,numCells,Eq_m,cellClosure,N,xdata,&ctx->SData_d,ctx->subThreadBlockSize,shift,ctx->events,ctx->mat_offset, ctx->species_offset, subJ, JacP);CHKERRQ(ierr);
381 #else
382       SETERRQ1(ctx->comm,PETSC_ERR_ARG_WRONG,"-landau_device_type %s not built","cuda");
383 #endif
384     } else if (ctx->deviceType == LANDAU_KOKKOS) {
385 #if defined(PETSC_HAVE_KOKKOS_KERNELS)
386       ierr = LandauKokkosJacobian(ctx->plex,Nq,ctx->batch_sz,ctx->num_grids,numCells,Eq_m,cellClosure,N,xdata,&ctx->SData_d,ctx->subThreadBlockSize,shift,ctx->events,ctx->mat_offset, ctx->species_offset, subJ,JacP);CHKERRQ(ierr);
387 #else
388       SETERRQ1(ctx->comm,PETSC_ERR_ARG_WRONG,"-landau_device_type %s not built","kokkos");
389 #endif
390     }
391   } else {   /* CPU version */
392     PetscInt        ip_offset[LANDAU_MAX_GRIDS+1], ipf_offset[LANDAU_MAX_GRIDS+1], elem_offset[LANDAU_MAX_GRIDS+1],IPf_sz_glb,IPf_sz_tot,num_grids=ctx->num_grids;
393     PetscReal       *ff, *dudx, *dudy, *dudz, *invJ_a = (PetscReal*)ctx->SData_d.invJ, *xx = (PetscReal*)ctx->SData_d.x, *yy = (PetscReal*)ctx->SData_d.y, *zz = (PetscReal*)ctx->SData_d.z, *ww = (PetscReal*)ctx->SData_d.w;
394     const PetscReal *const BB = Tf[0]->T[0], * const DD = Tf[0]->T[1];
395     PetscReal       Eq_m[LANDAU_MAX_SPECIES], invMass[LANDAU_MAX_SPECIES], nu_alpha[LANDAU_MAX_SPECIES], nu_beta[LANDAU_MAX_SPECIES];
396     /* count IPf size, etc */
397     ip_offset[0] = ipf_offset[0] = elem_offset[0] = 0;
398     for (PetscInt grid=0 ; grid<num_grids ; grid++) {
399       PetscInt nfloc = ctx->species_offset[grid+1] - ctx->species_offset[grid];
400       elem_offset[grid+1] = elem_offset[grid] + numCells[grid];
401       ip_offset[grid+1]   = ip_offset[grid]   + numCells[grid]*Nq;
402       ipf_offset[grid+1]  = ipf_offset[grid]  + Nq*nfloc*numCells[grid];
403     }
404     IPf_sz_glb = ipf_offset[num_grids];
405     IPf_sz_tot = IPf_sz_glb*ctx->batch_sz;
406     if (shift==0.0) { /* compute dynamic data f and df and init data for Jacobian */
407 #if defined(PETSC_HAVE_THREADSAFETY)
408       double         starttime, endtime;
409       starttime = MPI_Wtime();
410 #endif
411       ierr = PetscLogEventBegin(ctx->events[8],0,0,0,0);CHKERRQ(ierr);
412       for (PetscInt fieldA=0;fieldA<ctx->num_species;fieldA++) {
413         invMass[fieldA] = m_0/ctx->masses[fieldA];
414         Eq_m[fieldA] = ctx->Ez * ctx->t_0 * ctx->charges[fieldA] / (ctx->v_0 * ctx->masses[fieldA]); /* normalize dimensionless */
415         if (dim==2) Eq_m[fieldA] *=  2 * PETSC_PI; /* add the 2pi term that is not in Landau */
416         nu_alpha[fieldA] = PetscSqr(ctx->charges[fieldA]/m_0)*m_0/ctx->masses[fieldA];
417         nu_beta[fieldA] = PetscSqr(ctx->charges[fieldA]/ctx->epsilon0)*ctx->lnLam / (8*PETSC_PI) * ctx->t_0*ctx->n_0/PetscPowReal(ctx->v_0,3);
418       }
419       ierr = PetscMalloc4(IPf_sz_tot, &ff, IPf_sz_tot, &dudx, IPf_sz_tot, &dudy, dim==3 ? IPf_sz_tot : 0, &dudz);CHKERRQ(ierr);
420       // F df/dx
421       for (PetscInt tid = 0 ; tid < ctx->batch_sz*elem_offset[num_grids] ; tid++) { // for each element
422         const PetscInt b_Nelem = elem_offset[num_grids], b_elem_idx = tid%b_Nelem, b_id = tid/b_Nelem; // b_id == OMP thd_id in batch
423         // find my grid:
424         PetscInt       grid = 0;
425         while (b_elem_idx >= elem_offset[grid+1]) grid++; // yuck search for grid
426         {
427           const PetscInt     loc_nip = numCells[grid]*Nq, loc_Nf = ctx->species_offset[grid+1] - ctx->species_offset[grid], loc_elem = b_elem_idx - elem_offset[grid];
428           const PetscInt     moffset = LAND_MOFFSET(b_id,grid,ctx->batch_sz,ctx->num_grids,ctx->mat_offset); //b_id*b_N + ctx->mat_offset[grid];
429           PetscScalar        *coef, coef_buff[LANDAU_MAX_SPECIES*LANDAU_MAX_NQ];
430           PetscReal          *invJe = &invJ_a[(ip_offset[grid] + loc_elem*Nq)*dim*dim]; // ingJ is static data on batch 0
431           PetscInt           b,f,q;
432           if (cellClosure) {
433             coef = &cellClosure[b_id*IPf_sz_glb + ipf_offset[grid] + loc_elem*Nb*loc_Nf]; // this is const
434           } else {
435             coef = coef_buff;
436             for (f = 0; f < loc_Nf; ++f) {
437               LandauIdx *const Idxs = &maps[grid].gIdx[loc_elem][f][0];
438               for (b = 0; b < Nb; ++b) {
439                 PetscInt idx = Idxs[b];
440                 if (idx >= 0) {
441                   coef[f*Nb+b] = xdata[idx+moffset];
442                 } else {
443                   idx = -idx - 1;
444                   coef[f*Nb+b] = 0;
445                   for (q = 0; q < maps[grid].num_face; q++) {
446                     PetscInt    id = maps[grid].c_maps[idx][q].gid;
447                     PetscScalar scale = maps[grid].c_maps[idx][q].scale;
448                     coef[f*Nb+b] += scale*xdata[id+moffset];
449                   }
450                 }
451               }
452             }
453           }
454           /* get f and df */
455           for (PetscInt qi = 0; qi < Nq; qi++) {
456             const PetscReal  *invJ = &invJe[qi*dim*dim];
457             const PetscReal  *Bq = &BB[qi*Nb];
458             const PetscReal  *Dq = &DD[qi*Nb*dim];
459             PetscReal        u_x[LANDAU_DIM];
460             /* get f & df */
461             for (f = 0; f < loc_Nf; ++f) {
462               const PetscInt idx = b_id*IPf_sz_glb + ipf_offset[grid] + f*loc_nip + loc_elem*Nq + qi;
463               PetscInt       b, e;
464               PetscReal      refSpaceDer[LANDAU_DIM];
465               ff[idx] = 0.0;
466               for (int d = 0; d < LANDAU_DIM; ++d) refSpaceDer[d] = 0.0;
467               for (b = 0; b < Nb; ++b) {
468                 const PetscInt    cidx = b;
469                 ff[idx] += Bq[cidx]*PetscRealPart(coef[f*Nb+cidx]);
470                 for (int d = 0; d < dim; ++d) {
471                   refSpaceDer[d] += Dq[cidx*dim+d]*PetscRealPart(coef[f*Nb+cidx]);
472                 }
473               }
474               for (int d = 0; d < dim; ++d) {
475                 for (e = 0, u_x[d] = 0.0; e < dim; ++e) {
476                   u_x[d] += invJ[e*dim+d]*refSpaceDer[e];
477                 }
478               }
479               dudx[idx] = u_x[0];
480               dudy[idx] = u_x[1];
481  #if LANDAU_DIM==3
482               dudz[idx] = u_x[2];
483 #endif
484             }
485           } // q
486         } // grid
487       } // grid*batch
488       ierr = PetscLogEventEnd(ctx->events[8],0,0,0,0);CHKERRQ(ierr);
489 #if defined(PETSC_HAVE_THREADSAFETY)
490       endtime = MPI_Wtime();
491       if (ctx->stage) ctx->times[LANDAU_F_DF] += (endtime - starttime);
492 #endif
493     } // Jacobian setup
494     /* doit it */
495     for (PetscInt tid = 0 ; tid < ctx->batch_sz*elem_offset[num_grids] ; tid++) { // for each element
496       const PetscInt b_Nelem = elem_offset[num_grids];
497       const PetscInt b_elem_idx = tid%b_Nelem, b_id = tid/b_Nelem;
498       PetscInt       grid = 0;
499 #if defined(PETSC_HAVE_THREADSAFETY)
500       double         starttime, endtime;
501       starttime = MPI_Wtime();
502 #endif
503       while (b_elem_idx >= elem_offset[grid+1]) grid++;
504       {
505         const PetscInt     loc_Nf = ctx->species_offset[grid+1] - ctx->species_offset[grid], loc_elem = b_elem_idx - elem_offset[grid];
506         const PetscInt     moffset = LAND_MOFFSET(b_id,grid,ctx->batch_sz,ctx->num_grids,ctx->mat_offset)/* ; b_id*b_N + ctx->mat_offset[grid] */, totDim = loc_Nf*Nq, elemMatSize = totDim*totDim;
507         PetscScalar        *elemMat;
508          const PetscReal   *invJe = &invJ_a[(ip_offset[grid] + loc_elem*Nq)*dim*dim];
509         ierr = PetscMalloc1(elemMatSize, &elemMat);CHKERRQ(ierr);
510         ierr = PetscMemzero(elemMat, elemMatSize*sizeof(*elemMat));CHKERRQ(ierr);
511         ierr = PetscLogEventBegin(ctx->events[4],0,0,0,0);CHKERRQ(ierr);
512         for (PetscInt qj = 0; qj < Nq; ++qj) {
513           const PetscInt   jpidx_glb = ip_offset[grid] + qj + loc_elem * Nq;
514           PetscReal        g0[LANDAU_MAX_SPECIES], g2[LANDAU_MAX_SPECIES][LANDAU_DIM], g3[LANDAU_MAX_SPECIES][LANDAU_DIM][LANDAU_DIM]; // could make a LANDAU_MAX_SPECIES_GRID ~ number of ions - 1
515           PetscInt         d,d2,dp,d3,IPf_idx;
516           if (shift==0.0) { // Jacobian
517             const PetscReal * const invJj = &invJe[qj*dim*dim];
518             PetscReal               gg2[LANDAU_MAX_SPECIES][LANDAU_DIM],gg3[LANDAU_MAX_SPECIES][LANDAU_DIM][LANDAU_DIM], gg2_temp[LANDAU_DIM], gg3_temp[LANDAU_DIM][LANDAU_DIM];
519             const PetscReal         vj[3] = {xx[jpidx_glb], yy[jpidx_glb], zz ? zz[jpidx_glb] : 0}, wj = ww[jpidx_glb];
520             // create g2 & g3
521             for (d=0;d<dim;d++) { // clear accumulation data D & K
522               gg2_temp[d] = 0;
523               for (d2=0;d2<dim;d2++) gg3_temp[d][d2] = 0;
524             }
525             /* inner beta reduction */
526             IPf_idx = 0;
527             for (PetscInt grid_r = 0, f_off = 0, ipidx = 0; grid_r < ctx->num_grids ; grid_r++, f_off = ctx->species_offset[grid_r]) { // IPf_idx += nip_loc_r*Nfloc_r
528               PetscInt  nip_loc_r = numCells[grid_r]*Nq, Nfloc_r = Nf[grid_r];
529               for (PetscInt ei_r = 0, loc_fdf_idx = 0; ei_r < numCells[grid_r]; ++ei_r) {
530                 for (PetscInt qi = 0; qi < Nq; qi++, ipidx++, loc_fdf_idx++) {
531                   const PetscReal wi = ww[ipidx], x = xx[ipidx], y = yy[ipidx];
532                   PetscReal       temp1[3] = {0, 0, 0}, temp2 = 0;
533 #if LANDAU_DIM==2
534                   PetscReal       Ud[2][2], Uk[2][2], mask = (PetscAbs(vj[0]-x) < 100*PETSC_SQRT_MACHINE_EPSILON && PetscAbs(vj[1]-y) < 100*PETSC_SQRT_MACHINE_EPSILON) ? 0. : 1.;
535                   LandauTensor2D(vj, x, y, Ud, Uk, mask);
536 #else
537                   PetscReal U[3][3], z = zz[ipidx], mask = (PetscAbs(vj[0]-x) < 100*PETSC_SQRT_MACHINE_EPSILON && PetscAbs(vj[1]-y) < 100*PETSC_SQRT_MACHINE_EPSILON && PetscAbs(vj[2]-z) < 100*PETSC_SQRT_MACHINE_EPSILON) ? 0. : 1.;
538                   if (ctx->use_relativistic_corrections) {
539                     LandauTensor3DRelativistic(vj, x, y, z, U, mask, C_0(ctx->v_0));
540                   } else {
541                     LandauTensor3D(vj, x, y, z, U, mask);
542                   }
543 #endif
544                   for (int f = 0; f < Nfloc_r ; ++f) {
545                     const PetscInt idx = b_id*IPf_sz_glb + ipf_offset[grid_r] + f*nip_loc_r + ei_r*Nq + qi;  // IPf_idx + f*nip_loc_r + loc_fdf_idx;
546                     temp1[0] += dudx[idx]*nu_beta[f+f_off]*invMass[f+f_off];
547                     temp1[1] += dudy[idx]*nu_beta[f+f_off]*invMass[f+f_off];
548 #if LANDAU_DIM==3
549                     temp1[2] += dudz[idx]*nu_beta[f+f_off]*invMass[f+f_off];
550 #endif
551                     temp2    += ff[idx]*nu_beta[f+f_off];
552                   }
553                   temp1[0] *= wi;
554                   temp1[1] *= wi;
555 #if LANDAU_DIM==3
556                   temp1[2] *= wi;
557 #endif
558                   temp2    *= wi;
559 #if LANDAU_DIM==2
560                   for (d2 = 0; d2 < 2; d2++) {
561                     for (d3 = 0; d3 < 2; ++d3) {
562                       /* K = U * grad(f): g2=e: i,A */
563                       gg2_temp[d2] += Uk[d2][d3]*temp1[d3];
564                       /* D = -U * (I \kron (fx)): g3=f: i,j,A */
565                       gg3_temp[d2][d3] += Ud[d2][d3]*temp2;
566                     }
567                   }
568 #else
569                   for (d2 = 0; d2 < 3; ++d2) {
570                     for (d3 = 0; d3 < 3; ++d3) {
571                       /* K = U * grad(f): g2 = e: i,A */
572                       gg2_temp[d2] += U[d2][d3]*temp1[d3];
573                       /* D = -U * (I \kron (fx)): g3 = f: i,j,A */
574                       gg3_temp[d2][d3] += U[d2][d3]*temp2;
575                     }
576                   }
577 #endif
578                 } // qi
579               } // ei_r
580               IPf_idx += nip_loc_r*Nfloc_r;
581             } /* grid_r - IPs */
582             if (IPf_idx != IPf_sz_glb) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "IPf_idx != IPf_sz %D %D",IPf_idx,IPf_sz_glb);
583             // add alpha and put in gg2/3
584             for (PetscInt fieldA = 0, f_off = ctx->species_offset[grid]; fieldA < loc_Nf; ++fieldA) {
585               for (d2 = 0; d2 < dim; d2++) {
586                 gg2[fieldA][d2] = gg2_temp[d2]*nu_alpha[fieldA+f_off];
587                 for (d3 = 0; d3 < dim; d3++) {
588                   gg3[fieldA][d2][d3] = -gg3_temp[d2][d3]*nu_alpha[fieldA+f_off]*invMass[fieldA+f_off];
589                 }
590               }
591             }
592             /* add electric field term once per IP */
593             for (PetscInt fieldA = 0, f_off = ctx->species_offset[grid] ; fieldA < loc_Nf; ++fieldA) {
594               gg2[fieldA][dim-1] += Eq_m[fieldA+f_off];
595             }
596             /* Jacobian transform - g2, g3 */
597             for (PetscInt fieldA = 0; fieldA < loc_Nf; ++fieldA) {
598               for (d = 0; d < dim; ++d) {
599                 g2[fieldA][d] = 0.0;
600                 for (d2 = 0; d2 < dim; ++d2) {
601                   g2[fieldA][d] += invJj[d*dim+d2]*gg2[fieldA][d2];
602                   g3[fieldA][d][d2] = 0.0;
603                   for (d3 = 0; d3 < dim; ++d3) {
604                     for (dp = 0; dp < dim; ++dp) {
605                       g3[fieldA][d][d2] += invJj[d*dim + d3]*gg3[fieldA][d3][dp]*invJj[d2*dim + dp];
606                     }
607                   }
608                   g3[fieldA][d][d2] *= wj;
609                 }
610                 g2[fieldA][d] *= wj;
611               }
612             }
613           } else { // mass
614             PetscReal wj = ww[jpidx_glb];
615             /* Jacobian transform - g0 */
616             for (PetscInt fieldA = 0; fieldA < loc_Nf ; ++fieldA) {
617               if (dim==2) {
618                 g0[fieldA] = wj * shift * 2. * PETSC_PI; // move this to below and remove g0
619               } else {
620                 g0[fieldA] = wj * shift; // move this to below and remove g0
621               }
622             }
623           }
624           /* FE matrix construction */
625           {
626             PetscInt  fieldA,d,f,d2,g;
627             const PetscReal *BJq = &BB[qj*Nb], *DIq = &DD[qj*Nb*dim];
628             /* assemble - on the diagonal (I,I) */
629             for (fieldA = 0; fieldA < loc_Nf ; fieldA++) {
630               for (f = 0; f < Nb ; f++) {
631                 const PetscInt i = fieldA*Nb + f; /* Element matrix row */
632                 for (g = 0; g < Nb; ++g) {
633                   const PetscInt j    = fieldA*Nb + g; /* Element matrix column */
634                   const PetscInt fOff = i*totDim + j;
635                   if (shift==0.0) {
636                     for (d = 0; d < dim; ++d) {
637                       elemMat[fOff] += DIq[f*dim+d]*g2[fieldA][d]*BJq[g];
638                       for (d2 = 0; d2 < dim; ++d2) {
639                         elemMat[fOff] += DIq[f*dim + d]*g3[fieldA][d][d2]*DIq[g*dim + d2];
640                       }
641                     }
642                   } else { // mass
643                     elemMat[fOff] += BJq[f]*g0[fieldA]*BJq[g];
644                   }
645                 }
646               }
647             }
648           }
649         } /* qj loop */
650         ierr = PetscLogEventEnd(ctx->events[4],0,0,0,0);CHKERRQ(ierr);
651 #if defined(PETSC_HAVE_THREADSAFETY)
652         endtime = MPI_Wtime();
653         if (ctx->stage) ctx->times[LANDAU_KERNEL] += (endtime - starttime);
654 #endif
655         /* assemble matrix */
656         ierr = PetscLogEventBegin(ctx->events[6],0,0,0,0);CHKERRQ(ierr);
657         if (!container) {
658           PetscInt cStart;
659           ierr = DMPlexGetHeightStratum(ctx->plex[grid], 0, &cStart, NULL);CHKERRQ(ierr);
660           ierr = DMPlexMatSetClosure(ctx->plex[grid], section[grid], globsection[grid], subJ[ LAND_PACK_IDX(b_id,grid) ], loc_elem + cStart, elemMat, ADD_VALUES);CHKERRQ(ierr);
661         } else {  // GPU like assembly for debugging
662           PetscInt      fieldA,idx,q,f,g,d,nr,nc,rows0[LANDAU_MAX_Q_FACE],cols0[LANDAU_MAX_Q_FACE]={0},rows[LANDAU_MAX_Q_FACE],cols[LANDAU_MAX_Q_FACE];
663           PetscScalar   vals[LANDAU_MAX_Q_FACE*LANDAU_MAX_Q_FACE],row_scale[LANDAU_MAX_Q_FACE],col_scale[LANDAU_MAX_Q_FACE]={0};
664           /* assemble - from the diagonal (I,I) in this format for DMPlexMatSetClosure */
665           for (fieldA = 0; fieldA < loc_Nf ; fieldA++) {
666             LandauIdx *const Idxs = &maps[grid].gIdx[loc_elem][fieldA][0];
667             for (f = 0; f < Nb ; f++) {
668               idx = Idxs[f];
669               if (idx >= 0) {
670                 nr = 1;
671                 rows0[0] = idx;
672                 row_scale[0] = 1.;
673               } else {
674                 idx = -idx - 1;
675                 nr = maps[grid].num_face;
676                 for (q = 0; q < maps[grid].num_face; q++) {
677                   rows0[q]     = maps[grid].c_maps[idx][q].gid;
678                   row_scale[q] = maps[grid].c_maps[idx][q].scale;
679                 }
680               }
681               for (g = 0; g < Nb; ++g) {
682                 idx = Idxs[g];
683                 if (idx >= 0) {
684                   nc = 1;
685                   cols0[0] = idx;
686                   col_scale[0] = 1.;
687                 } else {
688                   idx = -idx - 1;
689                   nc = maps[grid].num_face;
690                   for (q = 0; q < maps[grid].num_face; q++) {
691                     cols0[q]     = maps[grid].c_maps[idx][q].gid;
692                     col_scale[q] = maps[grid].c_maps[idx][q].scale;
693                   }
694                 }
695                 const PetscInt    i = fieldA*Nb + f; /* Element matrix row */
696                 const PetscInt    j = fieldA*Nb + g; /* Element matrix column */
697                 const PetscScalar Aij = elemMat[i*totDim + j];
698                 for (q = 0; q < nr; q++) rows[q] = rows0[q] + moffset;
699                 for (d = 0; d < nc; d++) cols[d] = cols0[d] + moffset;
700                 for (q = 0; q < nr; q++) {
701                   for (d = 0; d < nc; d++) {
702                     vals[q*nc + d] = row_scale[q]*col_scale[d]*Aij;
703                   }
704                 }
705                 ierr = MatSetValues(JacP,nr,rows,nc,cols,vals,ADD_VALUES);CHKERRQ(ierr);
706               }
707             }
708           }
709         }
710         if (loc_elem==-1) {
711           PetscErrorCode    ierr2;
712           ierr2 = PetscPrintf(ctx->comm,"CPU Element matrix\n");CHKERRQ(ierr2);
713           for (int d = 0; d < totDim; ++d) {
714             for (int f = 0; f < totDim; ++f) {ierr2 = PetscPrintf(ctx->comm," %12.5e",  PetscRealPart(elemMat[d*totDim + f]));CHKERRQ(ierr2);}
715             ierr2 = PetscPrintf(ctx->comm,"\n");CHKERRQ(ierr2);
716           }
717           exit(12);
718         }
719         ierr = PetscFree(elemMat);CHKERRQ(ierr);
720         ierr = PetscLogEventEnd(ctx->events[6],0,0,0,0);CHKERRQ(ierr);
721       } /* grid */
722     } /* outer element & batch loop */
723     if (shift==0.0) { // mass
724       ierr = PetscFree4(ff, dudx, dudy, dudz);CHKERRQ(ierr);
725     }
726     if (!container) {   // move nest matrix to global JacP
727       for (PetscInt b_id = 0 ; b_id < ctx->batch_sz ; b_id++) { // OpenMP
728         for (PetscInt grid=0 ; grid<ctx->num_grids ; grid++) {
729           const PetscInt    moffset = LAND_MOFFSET(b_id,grid,ctx->batch_sz,ctx->num_grids,ctx->mat_offset); // b_id*b_N + ctx->mat_offset[grid];
730           PetscInt          nloc, nzl, colbuf[1024], row;
731           const PetscInt    *cols;
732           const PetscScalar *vals;
733           Mat               B = subJ[ LAND_PACK_IDX(b_id,grid) ];
734           ierr = MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
735           ierr = MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
736           ierr = MatGetSize(B, &nloc, NULL);CHKERRQ(ierr);
737           for (int i=0 ; i<nloc ; i++) {
738             ierr = MatGetRow(B,i,&nzl,&cols,&vals);CHKERRQ(ierr);
739             if (nzl>1024) SETERRQ1(PetscObjectComm((PetscObject) B), PETSC_ERR_PLIB, "Row too big: %D",nzl);
740             for (int j=0; j<nzl; j++) colbuf[j] = cols[j] + moffset;
741             row = i + moffset;
742             ierr = MatSetValues(JacP,1,&row,nzl,colbuf,vals,ADD_VALUES);CHKERRQ(ierr);
743             ierr = MatRestoreRow(B,i,&nzl,&cols,&vals);CHKERRQ(ierr);
744           }
745           ierr = MatDestroy(&B);CHKERRQ(ierr);
746         }
747       }
748     }
749   } /* CPU version */
750 
751   ierr = MatAssemblyBegin(JacP, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
752   ierr = MatAssemblyEnd(JacP, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
753   // create maps of needed
754 #define MAP_BF_SIZE (64*LANDAU_DIM*LANDAU_DIM*LANDAU_MAX_Q_FACE*LANDAU_MAX_SPECIES)
755   if (ctx->gpu_assembly && !container) {
756     PetscScalar             elemMatrix[LANDAU_MAX_NQ*LANDAU_MAX_NQ*LANDAU_MAX_SPECIES*LANDAU_MAX_SPECIES], *elMat;
757     pointInterpolationP4est pointMaps[MAP_BF_SIZE][LANDAU_MAX_Q_FACE];
758     PetscInt                q,eidx,fieldA;
759     ierr = PetscInfo1(ctx->plex[0], "Make GPU maps %D\n",1);CHKERRQ(ierr);
760     ierr = PetscLogEventBegin(ctx->events[2],0,0,0,0);CHKERRQ(ierr);
761     ierr = PetscMalloc(sizeof(*maps)*ctx->num_grids, &maps);CHKERRQ(ierr);
762     ierr = PetscContainerCreate(PETSC_COMM_SELF, &container);CHKERRQ(ierr);
763     ierr = PetscContainerSetPointer(container, (void *)maps);CHKERRQ(ierr);
764     ierr = PetscContainerSetUserDestroy(container, LandauGPUMapsDestroy);CHKERRQ(ierr);
765     ierr = PetscObjectCompose((PetscObject) JacP, "assembly_maps", (PetscObject) container);CHKERRQ(ierr);
766     ierr = PetscContainerDestroy(&container);CHKERRQ(ierr);
767 
768     for (PetscInt grid=0;grid<ctx->num_grids;grid++) {
769       PetscInt cStart, cEnd, ej, Nfloc = Nf[grid], totDim = Nfloc*Nq;
770       ierr = DMPlexGetHeightStratum(ctx->plex[grid], 0, &cStart, &cEnd);CHKERRQ(ierr);
771       // make maps
772       maps[grid].d_self = NULL;
773       maps[grid].num_elements = numCells[grid];
774       maps[grid].num_face = (PetscInt)(pow(Nq,1./((double)dim))+.001); // Q
775       maps[grid].num_face = (PetscInt)(pow(maps[grid].num_face,(double)(dim-1))+.001); // Q^2
776       maps[grid].num_reduced = 0;
777       maps[grid].deviceType = ctx->deviceType;
778       maps[grid].numgrids = ctx->num_grids;
779       // count reduced and get
780       ierr = PetscMalloc(maps[grid].num_elements * sizeof(*maps[grid].gIdx), &maps[grid].gIdx);CHKERRQ(ierr);
781       for (fieldA=0;fieldA<Nf[grid];fieldA++) {
782         for (ej = cStart, eidx = 0 ; ej < cEnd; ++ej, ++eidx) {
783           for (q = 0; q < Nb; ++q) {
784             PetscInt    numindices,*indices;
785             PetscScalar *valuesOrig = elMat = elemMatrix;
786             ierr = PetscMemzero(elMat, totDim*totDim*sizeof(*elMat));CHKERRQ(ierr);
787             elMat[ (fieldA*Nb + q)*totDim + fieldA*Nb + q] = 1;
788             ierr = DMPlexGetClosureIndices(ctx->plex[grid], section[grid], globsection[grid], ej, PETSC_TRUE, &numindices, &indices, NULL, (PetscScalar **) &elMat);CHKERRQ(ierr);
789             for (PetscInt f = 0 ; f < numindices ; ++f) { // look for a non-zero on the diagonal
790               if (PetscAbs(PetscRealPart(elMat[f*numindices + f])) > PETSC_MACHINE_EPSILON) {
791                 // found it
792                 if (PetscAbs(PetscRealPart(elMat[f*numindices + f] - 1.)) < PETSC_MACHINE_EPSILON) {
793                   maps[grid].gIdx[eidx][fieldA][q] = (LandauIdx)indices[f]; // normal vertex 1.0
794                 } else { //found a constraint
795                   int       jj = 0;
796                   PetscReal sum = 0;
797                   const PetscInt ff = f;
798                   maps[grid].gIdx[eidx][fieldA][q] = -maps[grid].num_reduced - 1; // gid = -(idx+1): idx = -gid - 1
799                   do {  // constraints are continous in Plex - exploit that here
800                     int ii;
801                     for (ii = 0, pointMaps[maps[grid].num_reduced][jj].scale = 0; ii < maps[grid].num_face; ii++) { // DMPlex puts them all together
802                       if (ff + ii < numindices) {
803                         pointMaps[maps[grid].num_reduced][jj].scale += PetscRealPart(elMat[f*numindices + ff + ii]);
804                       }
805                     }
806                     sum += pointMaps[maps[grid].num_reduced][jj].scale;
807                     if (pointMaps[maps[grid].num_reduced][jj].scale == 0) pointMaps[maps[grid].num_reduced][jj].gid = -1; // 3D has Q and Q^2 interps -- all contiguous???
808                     else                                                  pointMaps[maps[grid].num_reduced][jj].gid = indices[f];
809                   } while (++jj < maps[grid].num_face && ++f < numindices); // jj is incremented if we hit the end
810                   while (jj++ < maps[grid].num_face) {
811                     pointMaps[maps[grid].num_reduced][jj].scale = 0;
812                     pointMaps[maps[grid].num_reduced][jj].gid = -1;
813                   }
814                   if (PetscAbs(sum-1.0) > 10*PETSC_MACHINE_EPSILON) { // debug
815                     int       d,f;
816                     PetscReal tmp = 0;
817                     PetscPrintf(PETSC_COMM_SELF,"\t\t%D.%D.%D) ERROR total I = %22.16e (LANDAU_MAX_Q_FACE=%d, #face=%D)\n",eidx,q,fieldA,sum,LANDAU_MAX_Q_FACE,maps[grid].num_face);
818                     for (d = 0, tmp = 0; d < numindices; ++d) {
819                       if (tmp!=0 && PetscAbs(tmp-1.0) > 10*PETSC_MACHINE_EPSILON) {ierr = PetscPrintf(PETSC_COMM_WORLD,"%3D) %3D: ",d,indices[d]);CHKERRQ(ierr);}
820                       for (f = 0; f < numindices; ++f) {
821                         tmp += PetscRealPart(elMat[d*numindices + f]);
822                       }
823                       if (tmp!=0) {ierr = PetscPrintf(ctx->comm," | %22.16e\n",tmp);CHKERRQ(ierr);}
824                     }
825                   }
826                   maps[grid].num_reduced++;
827                   if (maps[grid].num_reduced>=MAP_BF_SIZE) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "maps[grid].num_reduced %d > %d",maps[grid].num_reduced,MAP_BF_SIZE);
828                 }
829                 break;
830               }
831             }
832             // cleanup
833             ierr = DMPlexRestoreClosureIndices(ctx->plex[grid], section[grid], globsection[grid], ej, PETSC_TRUE, &numindices, &indices, NULL, (PetscScalar **) &elMat);CHKERRQ(ierr);
834             if (elMat != valuesOrig) {ierr = DMRestoreWorkArray(ctx->plex[grid], numindices*numindices, MPIU_SCALAR, &elMat);CHKERRQ(ierr);}
835           }
836         }
837       }
838       // allocate and copy point datamaps[grid].gIdx[eidx][field][q]
839       ierr = PetscMalloc(maps[grid].num_reduced * sizeof(*maps[grid].c_maps), &maps[grid].c_maps);CHKERRQ(ierr);
840       for (ej = 0; ej < maps[grid].num_reduced; ++ej) {
841         for (q = 0; q < maps[grid].num_face; ++q) {
842           maps[grid].c_maps[ej][q].scale = pointMaps[ej][q].scale;
843           maps[grid].c_maps[ej][q].gid   = pointMaps[ej][q].gid;
844         }
845       }
846 #if defined(PETSC_HAVE_KOKKOS_KERNELS)
847       if (ctx->deviceType == LANDAU_KOKKOS) {
848         ierr = LandauKokkosCreateMatMaps(maps, pointMaps, Nf, Nq, grid);CHKERRQ(ierr); // imples Kokkos does
849       } // else could be CUDA
850 #endif
851 #if defined(PETSC_HAVE_CUDA)
852       if (ctx->deviceType == LANDAU_CUDA) {
853         ierr = LandauCUDACreateMatMaps(maps, pointMaps, Nf, Nq, grid);CHKERRQ(ierr);
854       }
855 #endif
856     } /* grids */
857     ierr = PetscLogEventEnd(ctx->events[2],0,0,0,0);CHKERRQ(ierr);
858   } /* first pass with GPU assembly */
859   /* clean up */
860   if (cellClosure) {
861     ierr = PetscFree(cellClosure);CHKERRQ(ierr);
862   }
863   if (xdata) {
864     ierr = VecRestoreArrayReadAndMemType(a_X,&xdata);CHKERRQ(ierr);
865   }
866   PetscFunctionReturn(0);
867 }
868 
869 #if defined(LANDAU_ADD_BCS)
870 static void zero_bc(PetscInt dim, PetscInt Nf, PetscInt NfAux,
871                     const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
872                     const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
873                     PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar uexact[])
874 {
875   uexact[0] = 0;
876 }
877 #endif
878 
879 #define MATVEC2(__a,__x,__p) {int i,j; for (i=0.; i<2; i++) {__p[i] = 0; for (j=0.; j<2; j++) __p[i] += __a[i][j]*__x[j]; }}
880 static void CircleInflate(PetscReal r1, PetscReal r2, PetscReal r0, PetscInt num_sections, PetscReal x, PetscReal y,
881                           PetscReal *outX, PetscReal *outY)
882 {
883   PetscReal rr = PetscSqrtReal(x*x + y*y), outfact, efact;
884   if (rr < r1 + PETSC_SQRT_MACHINE_EPSILON) {
885     *outX = x; *outY = y;
886   } else {
887     const PetscReal xy[2] = {x,y}, sinphi=y/rr, cosphi=x/rr;
888     PetscReal       cth,sth,xyprime[2],Rth[2][2],rotcos,newrr;
889     if (num_sections==2) {
890       rotcos = 0.70710678118654;
891       outfact = 1.5; efact = 2.5;
892       /* rotate normalized vector into [-pi/4,pi/4) */
893       if (sinphi >= 0.) {         /* top cell, -pi/2 */
894         cth = 0.707106781186548; sth = -0.707106781186548;
895       } else {                    /* bottom cell -pi/8 */
896         cth = 0.707106781186548; sth = .707106781186548;
897       }
898     } else if (num_sections==3) {
899       rotcos = 0.86602540378443;
900       outfact = 1.5; efact = 2.5;
901       /* rotate normalized vector into [-pi/6,pi/6) */
902       if (sinphi >= 0.5) {         /* top cell, -pi/3 */
903         cth = 0.5; sth = -0.866025403784439;
904       } else if (sinphi >= -.5) {  /* mid cell 0 */
905         cth = 1.; sth = .0;
906       } else { /* bottom cell +pi/3 */
907         cth = 0.5; sth = 0.866025403784439;
908       }
909     } else if (num_sections==4) {
910       rotcos = 0.9238795325112;
911       outfact = 1.5; efact = 3;
912       /* rotate normalized vector into [-pi/8,pi/8) */
913       if (sinphi >= 0.707106781186548) {         /* top cell, -3pi/8 */
914         cth = 0.38268343236509; sth = -0.923879532511287;
915       } else if (sinphi >= 0.) {                 /* mid top cell -pi/8 */
916         cth = 0.923879532511287; sth = -.38268343236509;
917       } else if (sinphi >= -0.707106781186548) { /* mid bottom cell + pi/8 */
918         cth = 0.923879532511287; sth = 0.38268343236509;
919       } else {                                   /* bottom cell + 3pi/8 */
920         cth = 0.38268343236509; sth = .923879532511287;
921       }
922     } else {
923       cth = 0.; sth = 0.; rotcos = 0; efact = 0;
924     }
925     Rth[0][0] = cth; Rth[0][1] =-sth;
926     Rth[1][0] = sth; Rth[1][1] = cth;
927     MATVEC2(Rth,xy,xyprime);
928     if (num_sections==2) {
929       newrr = xyprime[0]/rotcos;
930     } else {
931       PetscReal newcosphi=xyprime[0]/rr, rin = r1, rout = rr - rin;
932       PetscReal routmax = r0*rotcos/newcosphi - rin, nroutmax = r0 - rin, routfrac = rout/routmax;
933       newrr = rin + routfrac*nroutmax;
934     }
935     *outX = cosphi*newrr; *outY = sinphi*newrr;
936     /* grade */
937     PetscReal fact,tt,rs,re, rr = PetscSqrtReal(PetscSqr(*outX) + PetscSqr(*outY));
938     if (rr > r2) { rs = r2; re = r0; fact = outfact;} /* outer zone */
939     else {         rs = r1; re = r2; fact = efact;} /* electron zone */
940     tt = (rs + PetscPowReal((rr - rs)/(re - rs),fact) * (re-rs)) / rr;
941     *outX *= tt;
942     *outY *= tt;
943   }
944 }
945 
946 static PetscErrorCode GeometryDMLandau(DM base, PetscInt point, PetscInt dim, const PetscReal abc[], PetscReal xyz[], void *a_ctx)
947 {
948   LandauCtx   *ctx = (LandauCtx*)a_ctx;
949   PetscReal   r = abc[0], z = abc[1];
950   if (ctx->inflate) {
951     PetscReal absR, absZ;
952     absR = PetscAbs(r);
953     absZ = PetscAbs(z);
954     CircleInflate(ctx->i_radius[0],ctx->e_radius,ctx->radius[0],ctx->num_sections,absR,absZ,&absR,&absZ); // wrong: how do I know what grid I am on?
955     r = (r > 0) ? absR : -absR;
956     z = (z > 0) ? absZ : -absZ;
957   }
958   xyz[0] = r;
959   xyz[1] = z;
960   if (dim==3) xyz[2] = abc[2];
961 
962   PetscFunctionReturn(0);
963 }
964 
965 /* create DMComposite of meshes for each species group */
966 static PetscErrorCode LandauDMCreateVMeshes(MPI_Comm comm_self, const PetscInt dim, const char prefix[], LandauCtx *ctx, DM *pack)
967 {
968   PetscErrorCode ierr;
969   size_t         len;
970   char           fname[128] = ""; /* we can add a file if we want, for each grid */
971   char           plex_name[128] = ""; /* name of the mesh in the file */
972 
973   PetscFunctionBegin;
974   /* create DM */
975   ierr = PetscStrlen(fname, &len);CHKERRQ(ierr);
976   if (len) { // not used, need to loop over grids
977     PetscInt dim2;
978 
979     ierr = DMPlexCreateFromFile(comm_self, fname, plex_name, ctx->interpolate, pack);CHKERRQ(ierr);
980     ierr = DMGetDimension(*pack, &dim2);CHKERRQ(ierr);
981     if (LANDAU_DIM != dim2) SETERRQ2(comm_self, PETSC_ERR_PLIB, "dim %D != LANDAU_DIM %d",dim2,LANDAU_DIM);
982   } else { /* p4est, quads */
983     ierr = DMCompositeCreate(comm_self,pack);CHKERRQ(ierr);
984     /* Create plex mesh of Landau domain */
985     for (PetscInt grid=0;grid<ctx->num_grids;grid++) {
986       PetscReal radius = ctx->radius[grid];
987       if (!ctx->sphere) {
988         PetscInt       cells[] = {2,2,2};
989         PetscReal      lo[] = {-radius,-radius,-radius}, hi[] = {radius,radius,radius};
990         DMBoundaryType periodicity[3] = {DM_BOUNDARY_NONE, dim==2 ? DM_BOUNDARY_NONE : DM_BOUNDARY_NONE, DM_BOUNDARY_NONE};
991         if (dim==2) { lo[0] = 0; cells[0] = /* cells[1] = */ 1; }
992         ierr = DMPlexCreateBoxMesh(comm_self, dim, PETSC_FALSE, cells, lo, hi, periodicity, PETSC_TRUE, &ctx->plex[grid]);CHKERRQ(ierr); // todo: make composite and create dm[grid] here
993         ierr = DMLocalizeCoordinates(ctx->plex[grid]);CHKERRQ(ierr); /* needed for periodic */
994         if (dim==3) {ierr = PetscObjectSetName((PetscObject) ctx->plex[grid], "cube");CHKERRQ(ierr);}
995         else {ierr = PetscObjectSetName((PetscObject) ctx->plex[grid], "half-plane");CHKERRQ(ierr);}
996       } else if (dim==2) { // sphere is all wrong. should just have one inner radius
997         PetscInt       numCells,cells[16][4],i,j;
998         PetscInt       numVerts;
999         PetscReal      inner_radius1 = ctx->i_radius[grid], inner_radius2 = ctx->e_radius;
1000         PetscReal      *flatCoords = NULL;
1001         PetscInt       *flatCells = NULL, *pcell;
1002         if (ctx->num_sections==2) {
1003 #if 1
1004           numCells = 5;
1005           numVerts = 10;
1006           int cells2[][4] = { {0,1,4,3},
1007                               {1,2,5,4},
1008                               {3,4,7,6},
1009                               {4,5,8,7},
1010                               {6,7,8,9} };
1011           for (i = 0; i < numCells; i++) for (j = 0; j < 4; j++) cells[i][j] = cells2[i][j];
1012           ierr = PetscMalloc2(numVerts * 2, &flatCoords, numCells * 4, &flatCells);CHKERRQ(ierr);
1013           {
1014             PetscReal (*coords)[2] = (PetscReal (*) [2]) flatCoords;
1015             for (j = 0; j < numVerts-1; j++) {
1016               PetscReal z, r, theta = -PETSC_PI/2 + (j%3) * PETSC_PI/2;
1017               PetscReal rad = (j >= 6) ? inner_radius1 : (j >= 3) ? inner_radius2 : ctx->radius[grid];
1018               z = rad * PetscSinReal(theta);
1019               coords[j][1] = z;
1020               r = rad * PetscCosReal(theta);
1021               coords[j][0] = r;
1022             }
1023             coords[numVerts-1][0] = coords[numVerts-1][1] = 0;
1024           }
1025 #else
1026           numCells = 4;
1027           numVerts = 8;
1028           static int     cells2[][4] = {{0,1,2,3},
1029                                         {4,5,1,0},
1030                                         {5,6,2,1},
1031                                         {6,7,3,2}};
1032           for (i = 0; i < numCells; i++) for (j = 0; j < 4; j++) cells[i][j] = cells2[i][j];
1033           ierr = loc2(numVerts * 2, &flatCoords, numCells * 4, &flatCells);CHKERRQ(ierr);
1034           {
1035             PetscReal (*coords)[2] = (PetscReal (*) [2]) flatCoords;
1036             PetscInt j;
1037             for (j = 0; j < 8; j++) {
1038               PetscReal z, r;
1039               PetscReal theta = -PETSC_PI/2 + (j%4) * PETSC_PI/3.;
1040               PetscReal rad = ctx->radius[grid] * ((j < 4) ? 0.5 : 1.0);
1041               z = rad * PetscSinReal(theta);
1042               coords[j][1] = z;
1043               r = rad * PetscCosReal(theta);
1044               coords[j][0] = r;
1045             }
1046           }
1047 #endif
1048         } else if (ctx->num_sections==3) {
1049           numCells = 7;
1050           numVerts = 12;
1051           int cells2[][4] = { {0,1,5,4},
1052                               {1,2,6,5},
1053                               {2,3,7,6},
1054                               {4,5,9,8},
1055                               {5,6,10,9},
1056                               {6,7,11,10},
1057                               {8,9,10,11} };
1058           for (i = 0; i < numCells; i++) for (j = 0; j < 4; j++) cells[i][j] = cells2[i][j];
1059           ierr = PetscMalloc2(numVerts * 2, &flatCoords, numCells * 4, &flatCells);CHKERRQ(ierr);
1060           {
1061             PetscReal (*coords)[2] = (PetscReal (*) [2]) flatCoords;
1062             for (j = 0; j < numVerts; j++) {
1063               PetscReal z, r, theta = -PETSC_PI/2 + (j%4) * PETSC_PI/3;
1064               PetscReal rad = (j >= 8) ? inner_radius1 : (j >= 4) ? inner_radius2 : ctx->radius[grid];
1065               z = rad * PetscSinReal(theta);
1066               coords[j][1] = z;
1067               r = rad * PetscCosReal(theta);
1068               coords[j][0] = r;
1069             }
1070           }
1071         } else if (ctx->num_sections==4) {
1072           numCells = 10;
1073           numVerts = 16;
1074           int cells2[][4] = { {0,1,6,5},
1075                               {1,2,7,6},
1076                               {2,3,8,7},
1077                               {3,4,9,8},
1078                               {5,6,11,10},
1079                               {6,7,12,11},
1080                               {7,8,13,12},
1081                               {8,9,14,13},
1082                               {10,11,12,15},
1083                               {12,13,14,15}};
1084           for (i = 0; i < numCells; i++) for (j = 0; j < 4; j++) cells[i][j] = cells2[i][j];
1085           ierr = PetscMalloc2(numVerts * 2, &flatCoords, numCells * 4, &flatCells);CHKERRQ(ierr);
1086           {
1087             PetscReal (*coords)[2] = (PetscReal (*) [2]) flatCoords;
1088             for (j = 0; j < numVerts-1; j++) {
1089               PetscReal z, r, theta = -PETSC_PI/2 + (j%5) * PETSC_PI/4;
1090               PetscReal rad = (j >= 10) ? inner_radius1 : (j >= 5) ? inner_radius2 : ctx->radius[grid];
1091               z = rad * PetscSinReal(theta);
1092               coords[j][1] = z;
1093               r = rad * PetscCosReal(theta);
1094               coords[j][0] = r;
1095             }
1096             coords[numVerts-1][0] = coords[numVerts-1][1] = 0;
1097           }
1098         } else {
1099           numCells = 0;
1100           numVerts = 0;
1101         }
1102         for (j = 0, pcell = flatCells; j < numCells; j++, pcell += 4) {
1103           pcell[0] = cells[j][0]; pcell[1] = cells[j][1];
1104           pcell[2] = cells[j][2]; pcell[3] = cells[j][3];
1105         }
1106         ierr = DMPlexCreateFromCellListPetsc(comm_self,2,numCells,numVerts,4,ctx->interpolate,flatCells,2,flatCoords,&ctx->plex[grid]);CHKERRQ(ierr);
1107         ierr = PetscFree2(flatCoords,flatCells);CHKERRQ(ierr);
1108         ierr = PetscObjectSetName((PetscObject) ctx->plex[grid], "semi-circle");CHKERRQ(ierr);
1109       } else SETERRQ(ctx->comm, PETSC_ERR_PLIB, "Velocity space meshes does not support cubed sphere");
1110 
1111       ierr = DMSetFromOptions(ctx->plex[grid]);CHKERRQ(ierr);
1112     } // grid loop
1113     ierr = PetscObjectSetOptionsPrefix((PetscObject)*pack,prefix);CHKERRQ(ierr);
1114     ierr = DMSetFromOptions(*pack);CHKERRQ(ierr);
1115 
1116     { /* convert to p4est (or whatever), wait for discretization to create pack */
1117       char      convType[256];
1118       PetscBool flg;
1119       ierr = PetscOptionsBegin(ctx->comm, prefix, "Mesh conversion options", "DMPLEX");CHKERRQ(ierr);
1120       ierr = PetscOptionsFList("-dm_landau_type","Convert DMPlex to another format (p4est)","plexland.c",DMList,DMPLEX,convType,256,&flg);CHKERRQ(ierr);
1121       ierr = PetscOptionsEnd();CHKERRQ(ierr);
1122       if (flg) {
1123         ctx->use_p4est = PETSC_TRUE; /* flag for Forest */
1124         for (PetscInt grid=0;grid<ctx->num_grids;grid++) {
1125           DM dmforest;
1126           ierr = DMConvert(ctx->plex[grid],convType,&dmforest);CHKERRQ(ierr);
1127           if (dmforest) {
1128             PetscBool isForest;
1129             ierr = PetscObjectSetOptionsPrefix((PetscObject)dmforest,prefix);CHKERRQ(ierr);
1130             ierr = DMIsForest(dmforest,&isForest);CHKERRQ(ierr);
1131             if (isForest) {
1132               if (ctx->sphere && ctx->inflate) {
1133                 ierr = DMForestSetBaseCoordinateMapping(dmforest,GeometryDMLandau,ctx);CHKERRQ(ierr);
1134               }
1135               if (dmforest->prealloc_only != ctx->plex[grid]->prealloc_only) SETERRQ(PetscObjectComm((PetscObject)dmforest),PETSC_ERR_PLIB,"plex->prealloc_only != dm->prealloc_only");
1136               ierr = DMDestroy(&ctx->plex[grid]);CHKERRQ(ierr);
1137               ctx->plex[grid] = dmforest; // Forest for adaptivity
1138             } else SETERRQ(ctx->comm, PETSC_ERR_PLIB, "Converted to non Forest?");
1139           } else SETERRQ(ctx->comm, PETSC_ERR_PLIB, "Convert failed?");
1140         }
1141       } else ctx->use_p4est = PETSC_FALSE; /* flag for Forest */
1142     }
1143   } /* non-file */
1144   ierr = DMSetDimension(*pack, dim);CHKERRQ(ierr);
1145   ierr = PetscObjectSetName((PetscObject) *pack, "Mesh");CHKERRQ(ierr);
1146   ierr = DMSetApplicationContext(*pack, ctx);CHKERRQ(ierr);
1147 
1148   PetscFunctionReturn(0);
1149 }
1150 
1151 static PetscErrorCode SetupDS(DM pack, PetscInt dim, PetscInt grid, LandauCtx *ctx)
1152 {
1153   PetscErrorCode  ierr;
1154   PetscInt        ii,i0;
1155   char            buf[256];
1156   PetscSection    section;
1157 
1158   PetscFunctionBegin;
1159   for (ii = ctx->species_offset[grid], i0 = 0 ; ii < ctx->species_offset[grid+1] ; ii++, i0++) {
1160     if (ii==0) ierr = PetscSNPrintf(buf, 256, "e");
1161     else {ierr = PetscSNPrintf(buf, 256, "i%D", ii);CHKERRQ(ierr);}
1162     /* Setup Discretization - FEM */
1163     ierr = PetscFECreateDefault(PETSC_COMM_SELF, dim, 1, PETSC_FALSE, NULL, PETSC_DECIDE, &ctx->fe[ii]);CHKERRQ(ierr);
1164     ierr = PetscObjectSetName((PetscObject) ctx->fe[ii], buf);CHKERRQ(ierr);
1165     ierr = DMSetField(ctx->plex[grid], i0, NULL, (PetscObject) ctx->fe[ii]);CHKERRQ(ierr);
1166   }
1167   ierr = DMCreateDS(ctx->plex[grid]);CHKERRQ(ierr);
1168   ierr = DMGetSection(ctx->plex[grid], &section);CHKERRQ(ierr);
1169   for (PetscInt ii = ctx->species_offset[grid], i0 = 0 ; ii < ctx->species_offset[grid+1] ; ii++, i0++) {
1170     if (ii==0) ierr = PetscSNPrintf(buf, 256, "se");
1171     else ierr = PetscSNPrintf(buf, 256, "si%D", ii);
1172     ierr = PetscSectionSetComponentName(section, i0, 0, buf);CHKERRQ(ierr);
1173   }
1174   PetscFunctionReturn(0);
1175 }
1176 
1177 /* Define a Maxwellian function for testing out the operator. */
1178 
1179 /* Using cartesian velocity space coordinates, the particle */
1180 /* density, [1/m^3], is defined according to */
1181 
1182 /* $$ n=\int_{R^3} dv^3 \left(\frac{m}{2\pi T}\right)^{3/2}\exp [- mv^2/(2T)] $$ */
1183 
1184 /* Using some constant, c, we normalize the velocity vector into a */
1185 /* dimensionless variable according to v=c*x. Thus the density, $n$, becomes */
1186 
1187 /* $$ n=\int_{R^3} dx^3 \left(\frac{mc^2}{2\pi T}\right)^{3/2}\exp [- mc^2/(2T)*x^2] $$ */
1188 
1189 /* Defining $\theta=2T/mc^2$, we thus find that the probability density */
1190 /* for finding the particle within the interval in a box dx^3 around x is */
1191 
1192 /* f(x;\theta)=\left(\frac{1}{\pi\theta}\right)^{3/2} \exp [ -x^2/\theta ] */
1193 
1194 typedef struct {
1195   PetscReal v_0;
1196   PetscReal kT_m;
1197   PetscReal n;
1198   PetscReal shift;
1199 } MaxwellianCtx;
1200 
1201 static PetscErrorCode maxwellian(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf_dummy, PetscScalar *u, void *actx)
1202 {
1203   MaxwellianCtx *mctx = (MaxwellianCtx*)actx;
1204   PetscInt      i;
1205   PetscReal     v2 = 0, theta = 2*mctx->kT_m/(mctx->v_0*mctx->v_0); /* theta = 2kT/mc^2 */
1206   PetscFunctionBegin;
1207   /* compute the exponents, v^2 */
1208   for (i = 0; i < dim; ++i) v2 += x[i]*x[i];
1209   /* evaluate the Maxwellian */
1210   u[0] = mctx->n*PetscPowReal(PETSC_PI*theta,-1.5)*(PetscExpReal(-v2/theta));
1211   if (mctx->shift!=0.) {
1212     v2 = 0;
1213     for (i = 0; i < dim-1; ++i) v2 += x[i]*x[i];
1214     v2 += (x[dim-1]-mctx->shift)*(x[dim-1]-mctx->shift);
1215     /* evaluate the shifted Maxwellian */
1216     u[0] += mctx->n*PetscPowReal(PETSC_PI*theta,-1.5)*(PetscExpReal(-v2/theta));
1217   }
1218   PetscFunctionReturn(0);
1219 }
1220 
1221 /*@
1222  LandauAddMaxwellians - Add a Maxwellian distribution to a state
1223 
1224  Collective on X
1225 
1226  Input Parameters:
1227  .   dm - The mesh (local)
1228  +   time - Current time
1229  -   temps - Temperatures of each species (global)
1230  .   ns - Number density of each species (global)
1231  -   grid - index into current grid - just used for offset into temp and ns
1232  +   actx - Landau context
1233 
1234  Output Parameter:
1235  .   X  - The state (local to this grid)
1236 
1237  Level: beginner
1238 
1239  .keywords: mesh
1240  .seealso: LandauCreateVelocitySpace()
1241  @*/
1242 PetscErrorCode LandauAddMaxwellians(DM dm, Vec X, PetscReal time, PetscReal temps[], PetscReal ns[], PetscInt grid, PetscInt b_id, void *actx)
1243 {
1244   LandauCtx      *ctx = (LandauCtx*)actx;
1245   PetscErrorCode (*initu[LANDAU_MAX_SPECIES])(PetscInt, PetscReal, const PetscReal [], PetscInt, PetscScalar [], void *);
1246   PetscErrorCode ierr,ii,i0;
1247   PetscInt       dim;
1248   MaxwellianCtx  *mctxs[LANDAU_MAX_SPECIES], data[LANDAU_MAX_SPECIES];
1249 
1250   PetscFunctionBegin;
1251   ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);
1252   if (!ctx) { ierr = DMGetApplicationContext(dm, &ctx);CHKERRQ(ierr); }
1253   for (ii = ctx->species_offset[grid], i0 = 0 ; ii < ctx->species_offset[grid+1] ; ii++, i0++) {
1254     mctxs[i0] = &data[i0];
1255     data[i0].v_0 = ctx->v_0; // v_0 same for all grids
1256     data[i0].kT_m = ctx->k*temps[ii]/ctx->masses[ii]; /* kT/m */
1257     data[i0].n = ns[ii] * (1+(double)b_id/10.0); // make solves a little different to mimic application, n[0] use for Conner-Hastie
1258     //printf(">>>>>>>> %d.%d) ctx->n[%d]=%g ctx->electronShift=%e\n",b_id,grid,ii,data[i0].n,ctx->electronShift);
1259     initu[i0] = maxwellian;
1260     data[i0].shift = 0;
1261   }
1262   data[0].shift = ctx->electronShift;
1263   /* need to make ADD_ALL_VALUES work - TODO */
1264   ierr = DMProjectFunction(dm, time, initu, (void**)mctxs, INSERT_ALL_VALUES, X);CHKERRQ(ierr);
1265   PetscFunctionReturn(0);
1266 }
1267 
1268 /*
1269  LandauSetInitialCondition - Addes Maxwellians with context
1270 
1271  Collective on X
1272 
1273  Input Parameters:
1274  .   dm - The mesh
1275  -   grid - index into current grid - just used for offset into temp and ns
1276  +   actx - Landau context with T and n
1277 
1278  Output Parameter:
1279  .   X  - The state
1280 
1281  Level: beginner
1282 
1283  .keywords: mesh
1284  .seealso: LandauCreateVelocitySpace(), LandauAddMaxwellians()
1285  */
1286 static PetscErrorCode LandauSetInitialCondition(DM dm, Vec X, PetscInt grid, PetscInt b_id, void *actx)
1287 {
1288   LandauCtx        *ctx = (LandauCtx*)actx;
1289   PetscErrorCode ierr;
1290   PetscFunctionBegin;
1291   if (!ctx) { ierr = DMGetApplicationContext(dm, &ctx);CHKERRQ(ierr); }
1292   ierr = VecZeroEntries(X);CHKERRQ(ierr);
1293   ierr = LandauAddMaxwellians(dm, X, 0.0, ctx->thermal_temps, ctx->n, grid, b_id, ctx);CHKERRQ(ierr);
1294   PetscFunctionReturn(0);
1295 }
1296 
1297 // adapt a level once. Forest in/out
1298 static PetscErrorCode adaptToleranceFEM(PetscFE fem, Vec sol, PetscInt type, PetscInt grid, LandauCtx *ctx, DM *newForest)
1299 {
1300   DM               forest, plex, adaptedDM = NULL;
1301   PetscDS          prob;
1302   PetscBool        isForest;
1303   PetscQuadrature  quad;
1304   PetscInt         Nq, *Nb, cStart, cEnd, c, dim, qj, k;
1305   DMLabel          adaptLabel = NULL;
1306   PetscErrorCode   ierr;
1307 
1308   PetscFunctionBegin;
1309   forest = ctx->plex[grid];
1310   ierr = DMCreateDS(forest);CHKERRQ(ierr);
1311   ierr = DMGetDS(forest, &prob);CHKERRQ(ierr);
1312   ierr = DMGetDimension(forest, &dim);CHKERRQ(ierr);
1313   ierr = DMIsForest(forest, &isForest);CHKERRQ(ierr);
1314   if (!isForest) SETERRQ(ctx->comm,PETSC_ERR_ARG_WRONG,"! Forest");
1315   ierr = DMConvert(forest, DMPLEX, &plex);CHKERRQ(ierr);
1316   ierr = DMPlexGetHeightStratum(plex,0,&cStart,&cEnd);CHKERRQ(ierr);
1317   ierr = DMLabelCreate(PETSC_COMM_SELF,"adapt",&adaptLabel);CHKERRQ(ierr);
1318   ierr = PetscFEGetQuadrature(fem, &quad);CHKERRQ(ierr);
1319   ierr = PetscQuadratureGetData(quad, NULL, NULL, &Nq, NULL, NULL);CHKERRQ(ierr);
1320   if (Nq >LANDAU_MAX_NQ) SETERRQ2(ctx->comm,PETSC_ERR_ARG_WRONG,"Order too high. Nq = %D > LANDAU_MAX_NQ (%D)",Nq,LANDAU_MAX_NQ);
1321   ierr = PetscDSGetDimensions(prob, &Nb);CHKERRQ(ierr);
1322   if (type==4) {
1323     for (c = cStart; c < cEnd; c++) {
1324       ierr = DMLabelSetValue(adaptLabel, c, DM_ADAPT_REFINE);CHKERRQ(ierr);
1325     }
1326     ierr = PetscInfo1(sol, "Phase:%s: Uniform refinement\n","adaptToleranceFEM");CHKERRQ(ierr);
1327   } else if (type==2) {
1328     PetscInt  rCellIdx[8], eCellIdx[64], iCellIdx[64], eMaxIdx = -1, iMaxIdx = -1, nr = 0, nrmax = (dim==3) ? 8 : 2;
1329     PetscReal minRad = PETSC_INFINITY, r, eMinRad = PETSC_INFINITY, iMinRad = PETSC_INFINITY;
1330     for (c = 0; c < 64; c++) { eCellIdx[c] = iCellIdx[c] = -1; }
1331     for (c = cStart; c < cEnd; c++) {
1332       PetscReal    tt, v0[LANDAU_MAX_NQ*3], detJ[LANDAU_MAX_NQ];
1333       ierr = DMPlexComputeCellGeometryFEM(plex, c, quad, v0, NULL, NULL, detJ);CHKERRQ(ierr);
1334       for (qj = 0; qj < Nq; ++qj) {
1335         tt = PetscSqr(v0[dim*qj+0]) + PetscSqr(v0[dim*qj+1]) + PetscSqr(((dim==3) ? v0[dim*qj+2] : 0));
1336         r = PetscSqrtReal(tt);
1337         if (r < minRad - PETSC_SQRT_MACHINE_EPSILON*10.) {
1338           minRad = r;
1339           nr = 0;
1340           rCellIdx[nr++]= c;
1341           ierr = PetscInfo4(sol, "\t\tPhase: adaptToleranceFEM Found first inner r=%e, cell %D, qp %D/%D\n", r, c, qj+1, Nq);CHKERRQ(ierr);
1342         } else if ((r-minRad) < PETSC_SQRT_MACHINE_EPSILON*100. && nr < nrmax) {
1343           for (k=0;k<nr;k++) if (c == rCellIdx[k]) break;
1344           if (k==nr) {
1345             rCellIdx[nr++]= c;
1346             ierr = PetscInfo5(sol, "\t\t\tPhase: adaptToleranceFEM Found another inner r=%e, cell %D, qp %D/%D, d=%e\n", r, c, qj+1, Nq, r-minRad);CHKERRQ(ierr);
1347           }
1348         }
1349         if (ctx->sphere) {
1350           if ((tt=r-ctx->e_radius) > 0) {
1351             PetscInfo2(sol, "\t\t\t %D cell r=%g\n",c,tt);
1352             if (tt < eMinRad - PETSC_SQRT_MACHINE_EPSILON*100.) {
1353               eMinRad = tt;
1354               eMaxIdx = 0;
1355               eCellIdx[eMaxIdx++] = c;
1356             } else if (eMaxIdx > 0 && (tt-eMinRad) <= PETSC_SQRT_MACHINE_EPSILON && c != eCellIdx[eMaxIdx-1]) {
1357               eCellIdx[eMaxIdx++] = c;
1358             }
1359           }
1360           if ((tt=r-ctx->i_radius[grid]) > 0) {
1361             if (tt < iMinRad - 1.e-5) {
1362               iMinRad = tt;
1363               iMaxIdx = 0;
1364               iCellIdx[iMaxIdx++] = c;
1365             } else if (iMaxIdx > 0 && (tt-iMinRad) <= PETSC_SQRT_MACHINE_EPSILON && c != iCellIdx[iMaxIdx-1]) {
1366               iCellIdx[iMaxIdx++] = c;
1367             }
1368           }
1369         }
1370       }
1371     }
1372     for (k=0;k<nr;k++) {
1373       ierr = DMLabelSetValue(adaptLabel, rCellIdx[k], DM_ADAPT_REFINE);CHKERRQ(ierr);
1374     }
1375     if (ctx->sphere) {
1376       for (c = 0; c < eMaxIdx; c++) {
1377         ierr = DMLabelSetValue(adaptLabel, eCellIdx[c], DM_ADAPT_REFINE);CHKERRQ(ierr);
1378         ierr = PetscInfo3(sol, "\t\tPhase:%s: refine sphere e cell %D r=%g\n","adaptToleranceFEM",eCellIdx[c],eMinRad);CHKERRQ(ierr);
1379       }
1380       for (c = 0; c < iMaxIdx; c++) {
1381         ierr = DMLabelSetValue(adaptLabel, iCellIdx[c], DM_ADAPT_REFINE);CHKERRQ(ierr);
1382         ierr = PetscInfo3(sol, "\t\tPhase:%s: refine sphere i cell %D r=%g\n","adaptToleranceFEM",iCellIdx[c],iMinRad);CHKERRQ(ierr);
1383       }
1384     }
1385     ierr = PetscInfo4(sol, "Phase:%s: Adaptive refine origin cells %D,%D r=%g\n","adaptToleranceFEM",rCellIdx[0],rCellIdx[1],minRad);CHKERRQ(ierr);
1386   } else if (type==0 || type==1 || type==3) { /* refine along r=0 axis */
1387     PetscScalar  *coef = NULL;
1388     Vec          coords;
1389     PetscInt     csize,Nv,d,nz;
1390     DM           cdm;
1391     PetscSection cs;
1392     ierr = DMGetCoordinatesLocal(forest, &coords);CHKERRQ(ierr);
1393     ierr = DMGetCoordinateDM(forest, &cdm);CHKERRQ(ierr);
1394     ierr = DMGetLocalSection(cdm, &cs);CHKERRQ(ierr);
1395     for (c = cStart; c < cEnd; c++) {
1396       PetscInt doit = 0, outside = 0;
1397       ierr = DMPlexVecGetClosure(cdm, cs, coords, c, &csize, &coef);CHKERRQ(ierr);
1398       Nv = csize/dim;
1399       for (nz = d = 0; d < Nv; d++) {
1400         PetscReal z = PetscRealPart(coef[d*dim + (dim-1)]), x = PetscSqr(PetscRealPart(coef[d*dim + 0])) + ((dim==3) ? PetscSqr(PetscRealPart(coef[d*dim + 1])) : 0);
1401         x = PetscSqrtReal(x);
1402         if (x < PETSC_MACHINE_EPSILON*10. && PetscAbs(z)<PETSC_MACHINE_EPSILON*10.) doit = 1;             /* refine origin */
1403         else if (type==0 && (z < -PETSC_MACHINE_EPSILON*10. || z > ctx->re_radius+PETSC_MACHINE_EPSILON*10.)) outside++;   /* first pass don't refine bottom */
1404         else if (type==1 && (z > ctx->vperp0_radius1 || z < -ctx->vperp0_radius1)) outside++; /* don't refine outside electron refine radius */
1405         else if (type==3 && (z > ctx->vperp0_radius2 || z < -ctx->vperp0_radius2)) outside++; /* don't refine outside ion refine radius */
1406         if (x < PETSC_MACHINE_EPSILON*10.) nz++;
1407       }
1408       ierr = DMPlexVecRestoreClosure(cdm, cs, coords, c, &csize, &coef);CHKERRQ(ierr);
1409       if (doit || (outside<Nv && nz)) {
1410         ierr = DMLabelSetValue(adaptLabel, c, DM_ADAPT_REFINE);CHKERRQ(ierr);
1411       }
1412     }
1413     ierr = PetscInfo1(sol, "Phase:%s: RE refinement\n","adaptToleranceFEM");CHKERRQ(ierr);
1414   }
1415   ierr = DMDestroy(&plex);CHKERRQ(ierr);
1416   ierr = DMAdaptLabel(forest, adaptLabel, &adaptedDM);CHKERRQ(ierr);
1417   ierr = DMLabelDestroy(&adaptLabel);CHKERRQ(ierr);
1418   *newForest = adaptedDM;
1419   if (adaptedDM) {
1420     if (isForest) {
1421       ierr = DMForestSetAdaptivityForest(adaptedDM,NULL);CHKERRQ(ierr); // ????
1422     } else exit(33); // ???????
1423     ierr = DMConvert(adaptedDM, DMPLEX, &plex);CHKERRQ(ierr);
1424     ierr = DMPlexGetHeightStratum(plex,0,&cStart,&cEnd);CHKERRQ(ierr);
1425     ierr = PetscInfo2(sol, "\tPhase: adaptToleranceFEM: %D cells, %d total quadrature points\n",cEnd-cStart,Nq*(cEnd-cStart));CHKERRQ(ierr);
1426     ierr = DMDestroy(&plex);CHKERRQ(ierr);
1427   } else  *newForest = NULL;
1428   PetscFunctionReturn(0);
1429 }
1430 
1431 // forest goes in (ctx->plex[grid]), plex comes out
1432 static PetscErrorCode adapt(PetscInt grid, LandauCtx *ctx, Vec *uu)
1433 {
1434   PetscErrorCode  ierr;
1435   PetscInt        adaptIter;
1436 
1437   PetscFunctionBegin;
1438   PetscInt  type, limits[5] = {(grid==0) ? ctx->numRERefine : 0, (grid==0) ? ctx->nZRefine1 : 0, ctx->numAMRRefine[grid], (grid==0) ? ctx->nZRefine2 : 0,ctx->postAMRRefine[grid]};
1439   for (type=0;type<5;type++) {
1440     for (adaptIter = 0; adaptIter<limits[type];adaptIter++) {
1441       DM  newForest = NULL;
1442       ierr = adaptToleranceFEM(ctx->fe[0], *uu, type, grid, ctx, &newForest);CHKERRQ(ierr);
1443       if (newForest)  {
1444         ierr = DMDestroy(&ctx->plex[grid]);CHKERRQ(ierr);
1445         ierr = VecDestroy(uu);CHKERRQ(ierr);
1446         ierr = DMCreateGlobalVector(newForest,uu);CHKERRQ(ierr);
1447         ierr = PetscObjectSetName((PetscObject) *uu, "uAMR");CHKERRQ(ierr);
1448         ierr = LandauSetInitialCondition(newForest, *uu, grid, 0, ctx);CHKERRQ(ierr);
1449         ctx->plex[grid] = newForest;
1450       } else {
1451         exit(4); // can happen with no AMR and post refinement
1452       }
1453     }
1454   }
1455   PetscFunctionReturn(0);
1456 }
1457 
1458 static PetscErrorCode ProcessOptions(LandauCtx *ctx, const char prefix[])
1459 {
1460   PetscErrorCode    ierr;
1461   PetscBool         flg, sph_flg;
1462   PetscInt          ii,nt,nm,nc,num_species_grid[LANDAU_MAX_GRIDS];
1463   PetscReal         v0_grid[LANDAU_MAX_GRIDS];
1464   DM                dummy;
1465 
1466   PetscFunctionBegin;
1467   ierr = DMCreate(ctx->comm,&dummy);CHKERRQ(ierr);
1468   /* get options - initialize context */
1469   ctx->verbose = 1;
1470 #if defined(PETSC_HAVE_THREADSAFETY)
1471   ctx->batch_sz = PetscNumOMPThreads;
1472 #else
1473   ctx->batch_sz = 1;
1474 #endif
1475   ctx->batch_view_idx = 0;
1476   ctx->interpolate = PETSC_TRUE;
1477   ctx->gpu_assembly = PETSC_TRUE;
1478   ctx->aux_bool = PETSC_FALSE;
1479   ctx->electronShift = 0;
1480   ctx->M = NULL;
1481   ctx->J = NULL;
1482   /* geometry and grids */
1483   ctx->sphere = PETSC_FALSE;
1484   ctx->inflate = PETSC_FALSE;
1485   ctx->aux_bool = PETSC_FALSE;
1486   ctx->use_p4est = PETSC_FALSE;
1487   ctx->num_sections = 3; /* 2, 3 or 4 */
1488   for (PetscInt grid=0;grid<LANDAU_MAX_GRIDS;grid++) {
1489     ctx->radius[grid] = 5.; /* thermal radius (velocity) */
1490     ctx->numAMRRefine[grid] = 5;
1491     ctx->postAMRRefine[grid] = 0;
1492     ctx->species_offset[grid+1] = 1; // one species default
1493     num_species_grid[grid] = 0;
1494     ctx->plex[grid] = NULL;     /* cache as expensive to Convert */
1495   }
1496   ctx->species_offset[0] = 0;
1497   ctx->re_radius = 0.;
1498   ctx->vperp0_radius1 = 0;
1499   ctx->vperp0_radius2 = 0;
1500   ctx->nZRefine1 = 0;
1501   ctx->nZRefine2 = 0;
1502   ctx->numRERefine = 0;
1503   num_species_grid[0] = 1; // one species default
1504   /* species - [0] electrons, [1] one ion species eg, duetarium, [2] heavy impurity ion, ... */
1505   ctx->charges[0] = -1;  /* electron charge (MKS) */
1506   ctx->masses[0] = 1/1835.469965278441013; /* temporary value in proton mass */
1507   ctx->n[0] = 1;
1508   ctx->v_0 = 1; /* thermal velocity, we could start with a scale != 1 */
1509   ctx->thermal_temps[0] = 1;
1510   /* constants, etc. */
1511   ctx->epsilon0 = 8.8542e-12; /* permittivity of free space (MKS) F/m */
1512   ctx->k = 1.38064852e-23; /* Boltzmann constant (MKS) J/K */
1513   ctx->lnLam = 10;         /* cross section ratio large - small angle collisions */
1514   ctx->n_0 = 1.e20;        /* typical plasma n, but could set it to 1 */
1515   ctx->Ez = 0;
1516   ctx->subThreadBlockSize = 1; /* for device and maybe OMP */
1517   ctx->numConcurrency = 0; /* for device (matrix solver hint) */
1518   for (PetscInt grid=0;grid<LANDAU_NUM_TIMERS;grid++) ctx->times[grid] = 0;
1519   ctx->initialized = PETSC_FALSE; // doit first time
1520   ctx->use_matrix_mass = PETSC_FALSE; /* fast but slightly fragile */
1521   ctx->use_relativistic_corrections = PETSC_FALSE;
1522   ctx->use_energy_tensor_trick = PETSC_FALSE; /* Use Eero's trick for energy conservation v --> grad(v^2/2) */
1523   ctx->SData_d.w = NULL;
1524   ctx->SData_d.x = NULL;
1525   ctx->SData_d.y = NULL;
1526   ctx->SData_d.z = NULL;
1527   ctx->SData_d.invJ = NULL;
1528   ierr = PetscOptionsBegin(ctx->comm, prefix, "Options for Fokker-Plank-Landau collision operator", "none");CHKERRQ(ierr);
1529   {
1530     char opstring[256];
1531 #if defined(PETSC_HAVE_KOKKOS_KERNELS)
1532     ctx->deviceType = LANDAU_KOKKOS;
1533     ierr = PetscStrcpy(opstring,"kokkos");CHKERRQ(ierr);
1534 #if defined(PETSC_HAVE_CUDA)
1535     ctx->subThreadBlockSize = 16;
1536 #endif
1537 #elif defined(PETSC_HAVE_CUDA)
1538     ctx->deviceType = LANDAU_CUDA;
1539     ierr = PetscStrcpy(opstring,"cuda");CHKERRQ(ierr);
1540 #else
1541     ctx->deviceType = LANDAU_CPU;
1542     ierr = PetscStrcpy(opstring,"cpu");CHKERRQ(ierr);
1543     ctx->subThreadBlockSize = 0;
1544 #endif
1545     ierr = PetscOptionsString("-dm_landau_device_type","Use kernels on 'cpu', 'cuda', or 'kokkos'","plexland.c",opstring,opstring,256,NULL);CHKERRQ(ierr);
1546     ierr = PetscStrcmp("cpu",opstring,&flg);CHKERRQ(ierr);
1547     if (flg) {
1548       ctx->deviceType = LANDAU_CPU;
1549       ctx->subThreadBlockSize = 0;
1550     } else {
1551       ierr = PetscStrcmp("cuda",opstring,&flg);CHKERRQ(ierr);
1552       if (flg) {
1553         ctx->deviceType = LANDAU_CUDA;
1554         ctx->subThreadBlockSize = 0;
1555       } else {
1556         ierr = PetscStrcmp("kokkos",opstring,&flg);CHKERRQ(ierr);
1557         if (flg) ctx->deviceType = LANDAU_KOKKOS;
1558         else SETERRQ1(ctx->comm,PETSC_ERR_ARG_WRONG,"-dm_landau_device_type %s",opstring);
1559       }
1560     }
1561   }
1562   ierr = PetscOptionsReal("-dm_landau_electron_shift","Shift in thermal velocity of electrons","none",ctx->electronShift,&ctx->electronShift, NULL);CHKERRQ(ierr);
1563   ierr = PetscOptionsInt("-dm_landau_verbose", "Level of verbosity output", "plexland.c", ctx->verbose, &ctx->verbose, NULL);CHKERRQ(ierr);
1564   ierr = PetscOptionsInt("-dm_landau_batch_size", "Number of 'vertices' to batch", "ex2.c", ctx->batch_sz, &ctx->batch_sz, NULL);CHKERRQ(ierr);
1565   if (LANDAU_MAX_BATCH_SZ < ctx->batch_sz) SETERRQ2(ctx->comm,PETSC_ERR_ARG_WRONG,"LANDAU_MAX_BATCH_SZ %D < ctx->batch_sz %D",LANDAU_MAX_BATCH_SZ,ctx->batch_sz);
1566   ierr = PetscOptionsInt("-dm_landau_batch_view_idx", "Index of batch for diagnostics like plotting", "ex2.c", ctx->batch_view_idx, &ctx->batch_view_idx, NULL);CHKERRQ(ierr);
1567   if (ctx->batch_view_idx >= ctx->batch_sz) SETERRQ2(ctx->comm,PETSC_ERR_ARG_WRONG,"-ctx->batch_view_idx %D > ctx->batch_sz %D",ctx->batch_view_idx,ctx->batch_sz);
1568   ierr = PetscOptionsReal("-dm_landau_Ez","Initial parallel electric field in unites of Conner-Hastie critical field","plexland.c",ctx->Ez,&ctx->Ez, NULL);CHKERRQ(ierr);
1569   ierr = PetscOptionsReal("-dm_landau_n_0","Normalization constant for number density","plexland.c",ctx->n_0,&ctx->n_0, NULL);CHKERRQ(ierr);
1570   ierr = PetscOptionsReal("-dm_landau_ln_lambda","Cross section parameter","plexland.c",ctx->lnLam,&ctx->lnLam, NULL);CHKERRQ(ierr);
1571   ierr = PetscOptionsBool("-dm_landau_use_mataxpy_mass", "Use fast but slightly fragile MATAXPY to add mass term", "plexland.c", ctx->use_matrix_mass, &ctx->use_matrix_mass, NULL);CHKERRQ(ierr);
1572   ierr = PetscOptionsBool("-dm_landau_use_relativistic_corrections", "Use relativistic corrections", "plexland.c", ctx->use_relativistic_corrections, &ctx->use_relativistic_corrections, NULL);CHKERRQ(ierr);
1573   ierr = PetscOptionsBool("-dm_landau_use_energy_tensor_trick", "Use Eero's trick of using grad(v^2/2) instead of v as args to Landau tensor to conserve energy with relativistic corrections and Q1 elements", "plexland.c", ctx->use_energy_tensor_trick, &ctx->use_energy_tensor_trick, NULL);CHKERRQ(ierr);
1574 
1575   /* get num species with temperature, set defaults */
1576   for (ii=1;ii<LANDAU_MAX_SPECIES;ii++) {
1577     ctx->thermal_temps[ii] = 1;
1578     ctx->charges[ii] = 1;
1579     ctx->masses[ii] = 1;
1580     ctx->n[ii] = 1;
1581   }
1582   nt = LANDAU_MAX_SPECIES;
1583   ierr = PetscOptionsRealArray("-dm_landau_thermal_temps", "Temperature of each species [e,i_0,i_1,...] in keV (must be set to set number of species)", "plexland.c", ctx->thermal_temps, &nt, &flg);CHKERRQ(ierr);
1584   if (flg) {
1585     PetscInfo1(dummy, "num_species set to number of thermal temps provided (%D)\n",nt);
1586     ctx->num_species = nt;
1587   } else SETERRQ(ctx->comm,PETSC_ERR_ARG_WRONG,"-dm_landau_thermal_temps ,t1,t2,.. must be provided to set the number of species");
1588   for (ii=0;ii<ctx->num_species;ii++) ctx->thermal_temps[ii] *= 1.1604525e7; /* convert to Kelvin */
1589   nm = LANDAU_MAX_SPECIES-1;
1590   ierr = PetscOptionsRealArray("-dm_landau_ion_masses", "Mass of each species in units of proton mass [i_0=2,i_1=40...]", "plexland.c", &ctx->masses[1], &nm, &flg);CHKERRQ(ierr);
1591   if (flg && nm != ctx->num_species-1) {
1592     SETERRQ2(ctx->comm,PETSC_ERR_ARG_WRONG,"num ion masses %D != num species %D",nm,ctx->num_species-1);
1593   }
1594   nm = LANDAU_MAX_SPECIES;
1595   ierr = PetscOptionsRealArray("-dm_landau_n", "Number density of each species = n_s * n_0", "plexland.c", ctx->n, &nm, &flg);CHKERRQ(ierr);
1596   if (flg && nm != ctx->num_species) SETERRQ2(ctx->comm,PETSC_ERR_ARG_WRONG,"wrong num n: %D != num species %D",nm,ctx->num_species);
1597   for (ii=0;ii<LANDAU_MAX_SPECIES;ii++) ctx->masses[ii] *= 1.6720e-27; /* scale by proton mass kg */
1598   ctx->masses[0] = 9.10938356e-31; /* electron mass kg (should be about right already) */
1599   ctx->m_0 = ctx->masses[0]; /* arbitrary reference mass, electrons */
1600   nc = LANDAU_MAX_SPECIES-1;
1601   ierr = PetscOptionsRealArray("-dm_landau_ion_charges", "Charge of each species in units of proton charge [i_0=2,i_1=18,...]", "plexland.c", &ctx->charges[1], &nc, &flg);CHKERRQ(ierr);
1602   if (flg && nc != ctx->num_species-1) SETERRQ2(ctx->comm,PETSC_ERR_ARG_WRONG,"num charges %D != num species %D",nc,ctx->num_species-1);
1603   for (ii=0;ii<LANDAU_MAX_SPECIES;ii++) ctx->charges[ii] *= 1.6022e-19; /* electron/proton charge (MKS) */
1604   /* geometry and grids */
1605   nt = LANDAU_MAX_GRIDS;
1606   ierr = PetscOptionsIntArray("-dm_landau_num_species_grid","Number of species on each grid: [ 1, ....] or [S, 0 ....] for single grid","plexland.c", num_species_grid, &nt, &flg);CHKERRQ(ierr);
1607   if (flg) {
1608     ctx->num_grids = nt;
1609     for (ii=nt=0;ii<ctx->num_grids;ii++) nt += num_species_grid[ii];
1610     if (ctx->num_species != nt) SETERRQ4(ctx->comm,PETSC_ERR_ARG_WRONG,"-dm_landau_num_species_grid: sum %D != num_species = %D. %D grids (check that number of grids <= LANDAU_MAX_GRIDS = %D)",nt,ctx->num_species,ctx->num_grids,LANDAU_MAX_GRIDS);
1611   } else {
1612     ctx->num_grids = 1; // go back to a single grid run
1613     num_species_grid[0] = ctx->num_species;
1614   }
1615   for (ctx->species_offset[0] = ii = 0; ii < ctx->num_grids ; ii++) ctx->species_offset[ii+1] = ctx->species_offset[ii] + num_species_grid[ii];
1616   if (ctx->species_offset[ctx->num_grids] != ctx->num_species) SETERRQ2(ctx->comm,PETSC_ERR_ARG_WRONG,"ctx->species_offset[ctx->num_grids] %D != ctx->num_species = %D ???????????",ctx->species_offset[ctx->num_grids],ctx->num_species);
1617   for (PetscInt grid = 0; grid < ctx->num_grids ; grid++) {
1618     int iii = ctx->species_offset[grid]; // normalize with first (arbitrary) species on grid
1619     v0_grid[grid] = PetscSqrtReal(ctx->k*ctx->thermal_temps[iii]/ctx->masses[iii]); /* arbitrary units for non-dimensionalization: mean velocity in 1D of first species on grid */
1620   }
1621   ii = 0;
1622   ierr = PetscOptionsInt("-dm_landau_v0_grid", "Index of grid to use for setting v_0 (electrons are default). Not recommended to change", "plexland.c", ii, &ii, NULL);CHKERRQ(ierr);
1623   ctx->v_0 = v0_grid[ii]; /* arbitrary units for non dimensionalization: global mean velocity in 1D of electrons */
1624   ctx->t_0 = 8*PETSC_PI*PetscSqr(ctx->epsilon0*ctx->m_0/PetscSqr(ctx->charges[0]))/ctx->lnLam/ctx->n_0*PetscPowReal(ctx->v_0,3); /* note, this t_0 makes nu[0,0]=1 */
1625   /* domain */
1626   nt = LANDAU_MAX_GRIDS;
1627   ierr = PetscOptionsRealArray("-dm_landau_domain_radius","Phase space size in units of thermal velocity of grid","plexland.c",ctx->radius,&nt, &flg);CHKERRQ(ierr);
1628   if (flg && nt < ctx->num_grids) SETERRQ2(ctx->comm,PETSC_ERR_ARG_WRONG,"-dm_landau_domain_radius: given %D radius != number grids %D",nt,ctx->num_grids);
1629   for (PetscInt grid = 0; grid < ctx->num_grids ; grid++) {
1630     if (flg && ctx->radius[grid] <= 0) { /* negative is ratio of c */
1631       if (ctx->radius[grid] == 0) ctx->radius[grid] = 0.75;
1632       else ctx->radius[grid] = -ctx->radius[grid];
1633       ctx->radius[grid] = ctx->radius[grid]*SPEED_OF_LIGHT/ctx->v_0; // use any species on grid to normalize (v_0 same for all on grid)
1634       ierr = PetscInfo2(dummy, "Change domain radius to %g for grid %D\n",ctx->radius[grid],grid);CHKERRQ(ierr);
1635     }
1636     ctx->radius[grid] *= v0_grid[grid]/ctx->v_0; // scale domain by thermal radius relative to v_0
1637   }
1638   /* amr parametres */
1639   nt = LANDAU_MAX_GRIDS;
1640   ierr = PetscOptionsIntArray("-dm_landau_amr_levels_max", "Number of AMR levels of refinement around origin, after (RE) refinements along z", "plexland.c", ctx->numAMRRefine, &nt, &flg);CHKERRQ(ierr);
1641   if (flg && nt < ctx->num_grids) SETERRQ2(ctx->comm,PETSC_ERR_ARG_WRONG,"-dm_landau_amr_levels_max: given %D != number grids %D",nt,ctx->num_grids);
1642   nt = LANDAU_MAX_GRIDS;
1643   ierr = PetscOptionsIntArray("-dm_landau_amr_post_refine", "Number of levels to uniformly refine after AMR", "plexland.c", ctx->postAMRRefine, &nt, &flg);CHKERRQ(ierr);
1644   for (ii=1;ii<ctx->num_grids;ii++)  ctx->postAMRRefine[ii] = ctx->postAMRRefine[0]; // all grids the same now
1645   ierr = PetscOptionsInt("-dm_landau_amr_re_levels", "Number of levels to refine along v_perp=0, z>0", "plexland.c", ctx->numRERefine, &ctx->numRERefine, &flg);CHKERRQ(ierr);
1646   ierr = PetscOptionsInt("-dm_landau_amr_z_refine1",  "Number of levels to refine along v_perp=0", "plexland.c", ctx->nZRefine1, &ctx->nZRefine1, &flg);CHKERRQ(ierr);
1647   ierr = PetscOptionsInt("-dm_landau_amr_z_refine2",  "Number of levels to refine along v_perp=0", "plexland.c", ctx->nZRefine2, &ctx->nZRefine2, &flg);CHKERRQ(ierr);
1648   ierr = PetscOptionsReal("-dm_landau_re_radius","velocity range to refine on positive (z>0) r=0 axis for runaways","plexland.c",ctx->re_radius,&ctx->re_radius, &flg);CHKERRQ(ierr);
1649   ierr = PetscOptionsReal("-dm_landau_z_radius1","velocity range to refine r=0 axis (for electrons)","plexland.c",ctx->vperp0_radius1,&ctx->vperp0_radius1, &flg);CHKERRQ(ierr);
1650   ierr = PetscOptionsReal("-dm_landau_z_radius2","velocity range to refine r=0 axis (for ions) after origin AMR","plexland.c",ctx->vperp0_radius2, &ctx->vperp0_radius2, &flg);CHKERRQ(ierr);
1651   /* spherical domain (not used) */
1652   ierr = PetscOptionsInt("-dm_landau_num_sections", "Number of tangential section in (2D) grid, 2, 3, of 4", "plexland.c", ctx->num_sections, &ctx->num_sections, NULL);CHKERRQ(ierr);
1653   ierr = PetscOptionsBool("-dm_landau_sphere", "use sphere/semi-circle domain instead of rectangle", "plexland.c", ctx->sphere, &ctx->sphere, &sph_flg);CHKERRQ(ierr);
1654   ierr = PetscOptionsBool("-dm_landau_inflate", "With sphere, inflate for curved edges", "plexland.c", ctx->inflate, &ctx->inflate, &flg);CHKERRQ(ierr);
1655   ierr = PetscOptionsReal("-dm_landau_e_radius","Electron thermal velocity, used for circular meshes","plexland.c",ctx->e_radius, &ctx->e_radius, &flg);CHKERRQ(ierr);
1656   if (flg && !sph_flg) ctx->sphere = PETSC_TRUE; /* you gave me an e radius but did not set sphere, user error really */
1657   if (!flg) {
1658     ctx->e_radius = 1.5*PetscSqrtReal(8*ctx->k*ctx->thermal_temps[0]/ctx->masses[0]/PETSC_PI)/ctx->v_0;
1659   }
1660   nt = LANDAU_MAX_GRIDS;
1661   ierr = PetscOptionsRealArray("-dm_landau_i_radius","Ion thermal velocity, used for circular meshes","plexland.c",ctx->i_radius, &nt, &flg);CHKERRQ(ierr);
1662   if (flg && !sph_flg) ctx->sphere = PETSC_TRUE;
1663   if (!flg) {
1664     ctx->i_radius[0] = 1.5*PetscSqrtReal(8*ctx->k*ctx->thermal_temps[1]/ctx->masses[1]/PETSC_PI)/ctx->v_0; // need to correct for ion grid domain
1665   }
1666   if (flg && ctx->num_grids != nt) SETERRQ2(ctx->comm,PETSC_ERR_ARG_WRONG,"-dm_landau_i_radius: %D != num_species = %D",nt,ctx->num_grids);
1667   if (ctx->sphere && ctx->e_radius <= ctx->i_radius[0]) SETERRQ3(ctx->comm,PETSC_ERR_ARG_WRONG,"bad radii: %g < %g < %g",ctx->i_radius[0],ctx->e_radius,ctx->radius[0]);
1668   /* processing options */
1669   ierr = PetscOptionsInt("-dm_landau_sub_thread_block_size", "Number of threads in Kokkos integration point subblock", "plexland.c", ctx->subThreadBlockSize, &ctx->subThreadBlockSize, NULL);CHKERRQ(ierr);
1670   ierr = PetscOptionsBool("-dm_landau_gpu_assembly", "Assemble Jacobian on GPU", "plexland.c", ctx->gpu_assembly, &ctx->gpu_assembly, NULL);CHKERRQ(ierr);
1671   ierr = PetscOptionsInt("-dm_landau_mat_hint", "An integer hint attached to matrix for solvers", "plexland.c", ctx->numConcurrency, &ctx->numConcurrency, NULL);CHKERRQ(ierr);
1672 
1673   ierr = PetscOptionsEnd();CHKERRQ(ierr);
1674   for (ii=ctx->num_species;ii<LANDAU_MAX_SPECIES;ii++) ctx->masses[ii] = ctx->thermal_temps[ii]  = ctx->charges[ii] = 0;
1675   if (ctx->verbose > 0) {
1676     ierr = PetscPrintf(ctx->comm, "masses:        e=%10.3e; ions in proton mass units:   %10.3e %10.3e ...\n",ctx->masses[0],ctx->masses[1]/1.6720e-27,ctx->num_species>2 ? ctx->masses[2]/1.6720e-27 : 0);CHKERRQ(ierr);
1677     ierr = PetscPrintf(ctx->comm, "charges:       e=%10.3e; charges in elementary units: %10.3e %10.3e\n", ctx->charges[0],-ctx->charges[1]/ctx->charges[0],ctx->num_species>2 ? -ctx->charges[2]/ctx->charges[0] : 0);CHKERRQ(ierr);
1678     ierr = PetscPrintf(ctx->comm, "n:             e: %10.3e                           i: %10.3e %10.3e\n", ctx->n[0],ctx->n[1],ctx->num_species>2 ? ctx->n[2] : 0);CHKERRQ(ierr);
1679     ierr = PetscPrintf(ctx->comm, "thermal T (K): e=%10.3e i=%10.3e %10.3e. v_0=%10.3e (%10.3ec) n_0=%10.3e t_0=%10.3e, %s, %s, %D batched\n", ctx->thermal_temps[0], ctx->thermal_temps[1], (ctx->num_species>2) ? ctx->thermal_temps[2] : 0, ctx->v_0, ctx->v_0/SPEED_OF_LIGHT, ctx->n_0, ctx->t_0, ctx->use_relativistic_corrections ? "relativistic" : "classical", ctx->use_energy_tensor_trick ? "Use trick" : "Intuitive",ctx->batch_sz);CHKERRQ(ierr);
1680     ierr = PetscPrintf(ctx->comm, "Domain radius (AMR levels) grid %D: %g (%D) ",0,ctx->radius[0],ctx->numAMRRefine[0]);CHKERRQ(ierr);
1681     for (ii=1;ii<ctx->num_grids;ii++) PetscPrintf(ctx->comm, ", %D: %10.3e (%D) ",ii,ctx->radius[ii],ctx->numAMRRefine[ii]);
1682     ierr = PetscPrintf(ctx->comm,"\n");CHKERRQ(ierr);
1683   }
1684   ierr = DMDestroy(&dummy);CHKERRQ(ierr);
1685   {
1686     PetscMPIInt    rank;
1687     ierr = MPI_Comm_rank(ctx->comm, &rank);CHKERRMPI(ierr);
1688     ctx->stage = 0;
1689     ierr = PetscLogEventRegister("Landau Operator", DM_CLASSID, &ctx->events[11]);CHKERRQ(ierr); /* 11 */
1690     ierr = PetscLogEventRegister("Landau Jacobian", DM_CLASSID, &ctx->events[0]);CHKERRQ(ierr); /* 0 */
1691     ierr = PetscLogEventRegister("Landau Mass", DM_CLASSID, &ctx->events[9]);CHKERRQ(ierr); /* 9 */
1692     ierr = PetscLogEventRegister(" Preamble", DM_CLASSID, &ctx->events[10]);CHKERRQ(ierr); /* 10 */
1693     ierr = PetscLogEventRegister(" static IP Data", DM_CLASSID, &ctx->events[7]);CHKERRQ(ierr); /* 7 */
1694     ierr = PetscLogEventRegister(" dynamic IP-Jac", DM_CLASSID, &ctx->events[1]);CHKERRQ(ierr); /* 1 */
1695     ierr = PetscLogEventRegister(" Kernel-init", DM_CLASSID, &ctx->events[3]);CHKERRQ(ierr); /* 3 */
1696     ierr = PetscLogEventRegister(" Jac-f-df (GPU)", DM_CLASSID, &ctx->events[8]);CHKERRQ(ierr); /* 8 */
1697     ierr = PetscLogEventRegister(" Kernel (GPU)", DM_CLASSID, &ctx->events[4]);CHKERRQ(ierr); /* 4 */
1698     ierr = PetscLogEventRegister(" Copy to CPU", DM_CLASSID, &ctx->events[5]);CHKERRQ(ierr); /* 5 */
1699     ierr = PetscLogEventRegister(" Jac-assemble", DM_CLASSID, &ctx->events[6]);CHKERRQ(ierr); /* 6 */
1700     ierr = PetscLogEventRegister(" Jac asmbl setup", DM_CLASSID, &ctx->events[2]);CHKERRQ(ierr); /* 2 */
1701     ierr = PetscLogEventRegister(" Other", DM_CLASSID, &ctx->events[13]);CHKERRQ(ierr); /* 13 */
1702 
1703     if (rank) { /* turn off output stuff for duplicate runs - do we need to add the prefix to all this? */
1704       ierr = PetscOptionsClearValue(NULL,"-snes_converged_reason");CHKERRQ(ierr);
1705       ierr = PetscOptionsClearValue(NULL,"-ksp_converged_reason");CHKERRQ(ierr);
1706       ierr = PetscOptionsClearValue(NULL,"-snes_monitor");CHKERRQ(ierr);
1707       ierr = PetscOptionsClearValue(NULL,"-ksp_monitor");CHKERRQ(ierr);
1708       ierr = PetscOptionsClearValue(NULL,"-ts_monitor");CHKERRQ(ierr);
1709       ierr = PetscOptionsClearValue(NULL,"-ts_adapt_monitor");CHKERRQ(ierr);
1710       ierr = PetscOptionsClearValue(NULL,"-dm_landau_amr_dm_view");CHKERRQ(ierr);
1711       ierr = PetscOptionsClearValue(NULL,"-dm_landau_amr_vec_view");CHKERRQ(ierr);
1712       ierr = PetscOptionsClearValue(NULL,"-dm_landau_mass_dm_view");CHKERRQ(ierr);
1713       ierr = PetscOptionsClearValue(NULL,"-dm_landau_mass_view");CHKERRQ(ierr);
1714       ierr = PetscOptionsClearValue(NULL,"-dm_landau_jacobian_view");CHKERRQ(ierr);
1715       ierr = PetscOptionsClearValue(NULL,"-dm_landau_mat_view");CHKERRQ(ierr);
1716       ierr = PetscOptionsClearValue(NULL,"-");CHKERRQ(ierr);
1717       ierr = PetscOptionsClearValue(NULL,"-info");CHKERRQ(ierr);
1718     }
1719   }
1720   PetscFunctionReturn(0);
1721 }
1722 
1723 /*@C
1724  LandauCreateVelocitySpace - Create a DMPlex velocity space mesh
1725 
1726  Collective on comm
1727 
1728  Input Parameters:
1729  +   comm  - The MPI communicator
1730  .   dim - velocity space dimension (2 for axisymmetric, 3 for full 3X + 3V solver)
1731  -   prefix - prefix for options (not tested)
1732 
1733  Output Parameter:
1734  .   pack  - The DM object representing the mesh
1735  +   X - A vector (user destroys)
1736  -   J - Optional matrix (object destroys)
1737 
1738  Level: beginner
1739 
1740  .keywords: mesh
1741  .seealso: DMPlexCreate(), LandauDestroyVelocitySpace()
1742  @*/
1743 PetscErrorCode LandauCreateVelocitySpace(MPI_Comm comm, PetscInt dim, const char prefix[], Vec *X, Mat *J, DM *pack)
1744 {
1745   PetscErrorCode ierr;
1746   LandauCtx      *ctx;
1747   PetscBool      prealloc_only,flg;
1748   Vec            Xsub[LANDAU_MAX_GRIDS];
1749 
1750   PetscFunctionBegin;
1751   if (dim!=2 && dim!=3) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Only 2D and 3D supported");
1752   ierr = PetscNew(&ctx);CHKERRQ(ierr);
1753   ctx->comm = comm; /* used for diagnostics and global errors */
1754   /* process options */
1755   ierr = ProcessOptions(ctx,prefix);CHKERRQ(ierr);
1756   if (dim==2) ctx->use_relativistic_corrections = PETSC_FALSE;
1757   /* Create Mesh */
1758   ierr = LandauDMCreateVMeshes(PETSC_COMM_SELF, dim, prefix, ctx, pack);CHKERRQ(ierr); // creates grids (Forest of AMR)
1759   prealloc_only = (*pack)->prealloc_only;
1760   for (PetscInt grid=0;grid<ctx->num_grids;grid++) {
1761     /* create FEM */
1762     ierr = SetupDS(ctx->plex[grid],dim,grid,ctx);CHKERRQ(ierr);
1763     /* set initial state */
1764     ierr = DMCreateGlobalVector(ctx->plex[grid],&Xsub[grid]);CHKERRQ(ierr);
1765     ierr = PetscObjectSetName((PetscObject) Xsub[grid], "u_orig");CHKERRQ(ierr);
1766     /* initial static refinement, no solve */
1767     ierr = LandauSetInitialCondition(ctx->plex[grid], Xsub[grid], grid, 0, ctx);CHKERRQ(ierr);
1768     /* forest refinement - forest goes in (if forest), plex comes out */
1769     if (ctx->use_p4est) {
1770       DM plex;
1771       ierr = adapt(grid,ctx,&Xsub[grid]);CHKERRQ(ierr); // forest goes in, plex comes out
1772       if (ctx->plex[grid]->prealloc_only != prealloc_only) SETERRQ(PetscObjectComm((PetscObject)pack),PETSC_ERR_PLIB,"ctx->plex[grid]->prealloc_only != prealloc_only");
1773       ierr = DMViewFromOptions(ctx->plex[grid],NULL,"-dm_landau_amr_dm_view");CHKERRQ(ierr); // need to differentiate - todo
1774       ierr = VecViewFromOptions(Xsub[grid], NULL, "-dm_landau_amr_vec_view");CHKERRQ(ierr);
1775       // convert to plex, all done with this level
1776       ierr = DMConvert(ctx->plex[grid], DMPLEX, &plex);CHKERRQ(ierr);
1777       ierr = DMDestroy(&ctx->plex[grid]);CHKERRQ(ierr);
1778       ctx->plex[grid] = plex;
1779     }
1780 #if !defined(LANDAU_SPECIES_MAJOR)
1781     ierr = DMCompositeAddDM(*pack,ctx->plex[grid]);CHKERRQ(ierr);
1782 #else
1783     for (PetscInt b_id=0;b_id<ctx->batch_sz;b_id++) { // add batch size DMs for this species grid
1784       ierr = DMCompositeAddDM(*pack,ctx->plex[grid]);CHKERRQ(ierr);
1785     }
1786 #endif
1787     ierr = DMSetApplicationContext(ctx->plex[grid], ctx);CHKERRQ(ierr);
1788   }
1789 #if !defined(LANDAU_SPECIES_MAJOR)
1790   // stack the batched DMs, could do it all here!!! b_id=0
1791   for (PetscInt b_id=1;b_id<ctx->batch_sz;b_id++) {
1792     for (PetscInt grid=0;grid<ctx->num_grids;grid++) {
1793       ierr = DMCompositeAddDM(*pack,ctx->plex[grid]);CHKERRQ(ierr);
1794     }
1795   }
1796 #endif
1797   // create ctx->mat_offset
1798   ctx->mat_offset[0] = 0;
1799   for (PetscInt grid=0 ; grid < ctx->num_grids ; grid++) {
1800     PetscInt    n;
1801     ierr = VecGetLocalSize(Xsub[grid],&n);CHKERRQ(ierr);
1802     ctx->mat_offset[grid+1] = ctx->mat_offset[grid] + n;
1803   }
1804   // creat Jac
1805   ierr = DMSetApplicationContext(*pack, ctx);CHKERRQ(ierr);
1806   ierr = DMSetFromOptions(*pack);CHKERRQ(ierr);
1807   ierr = DMCreateMatrix(*pack, &ctx->J);CHKERRQ(ierr);
1808   ierr = MatSetOption(ctx->J, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE);CHKERRQ(ierr);
1809   ierr = MatSetOption(ctx->J, MAT_STRUCTURALLY_SYMMETRIC, PETSC_TRUE);CHKERRQ(ierr);
1810   ierr = PetscObjectSetName((PetscObject)ctx->J, "Jac");CHKERRQ(ierr);
1811   if (J) *J = ctx->J;
1812   // construct X, copy data in
1813   ierr = DMCreateGlobalVector(*pack,X);CHKERRQ(ierr);
1814   for (PetscInt grid=0 ; grid < ctx->num_grids ; grid++) {
1815     PetscInt n;
1816     ierr = VecGetLocalSize(Xsub[grid],&n);CHKERRQ(ierr);
1817     for (PetscInt b_id = 0 ; b_id < ctx->batch_sz ; b_id++) {
1818       PetscScalar const *values;
1819       const PetscInt    moffset = LAND_MOFFSET(b_id,grid,ctx->batch_sz,ctx->num_grids,ctx->mat_offset);
1820       ierr = LandauSetInitialCondition(ctx->plex[grid], Xsub[grid], grid, b_id, ctx);CHKERRQ(ierr);
1821       ierr = VecGetArrayRead(Xsub[grid],&values);CHKERRQ(ierr);
1822       for (int i=0, idx = moffset; i<n; i++, idx++) {
1823         ierr = VecSetValue(*X,idx,values[i],INSERT_VALUES);CHKERRQ(ierr);
1824       }
1825       ierr = VecRestoreArrayRead(Xsub[grid],&values);CHKERRQ(ierr);
1826     }
1827   }
1828   // cleanup
1829   for (PetscInt grid=0 ; grid < ctx->num_grids ; grid++) {
1830     ierr = VecDestroy(&Xsub[grid]);CHKERRQ(ierr);
1831   }
1832   /* check for types that we need */
1833   if (ctx->gpu_assembly) { /* we need GPU object with GPU assembly */
1834     if (ctx->deviceType == LANDAU_CUDA) {
1835       ierr = PetscObjectTypeCompareAny((PetscObject)ctx->J,&flg,MATSEQAIJCUSPARSE,MATMPIAIJCUSPARSE,MATAIJCUSPARSE,"");CHKERRQ(ierr);
1836       if (!flg) SETERRQ(ctx->comm,PETSC_ERR_ARG_WRONG,"must use '-dm_mat_type aijcusparse -dm_vec_type cuda' for GPU assembly and Cuda or use '-dm_landau_device_type cpu'");
1837     } else if (ctx->deviceType == LANDAU_KOKKOS) {
1838       ierr = PetscObjectTypeCompareAny((PetscObject)ctx->J,&flg,MATSEQAIJKOKKOS,MATMPIAIJKOKKOS,MATAIJKOKKOS,"");CHKERRQ(ierr);
1839 #if defined(PETSC_HAVE_KOKKOS_KERNELS)
1840       if (!flg) SETERRQ(ctx->comm,PETSC_ERR_ARG_WRONG,"must use '-dm_mat_type aijkokkos -dm_vec_type kokkos' for GPU assembly and Kokkos or use '-dm_landau_device_type cpu'");
1841 #else
1842       if (!flg) SETERRQ(ctx->comm,PETSC_ERR_ARG_WRONG,"must configure with '--download-kokkos-kernels' for GPU assembly and Kokkos or use '-dm_landau_device_type cpu'");
1843 #endif
1844     }
1845   }
1846   PetscFunctionReturn(0);
1847 }
1848 
1849 /*@
1850  LandauDestroyVelocitySpace - Destroy a DMPlex velocity space mesh
1851 
1852  Collective on dm
1853 
1854  Input/Output Parameters:
1855  .   dm - the dm to destroy
1856 
1857  Level: beginner
1858 
1859  .keywords: mesh
1860  .seealso: LandauCreateVelocitySpace()
1861  @*/
1862 PetscErrorCode LandauDestroyVelocitySpace(DM *dm)
1863 {
1864   PetscErrorCode ierr,ii;
1865   LandauCtx      *ctx;
1866   PetscContainer container = NULL;
1867   PetscFunctionBegin;
1868   ierr = DMGetApplicationContext(*dm, &ctx);CHKERRQ(ierr);
1869   ierr = PetscObjectQuery((PetscObject)ctx->J,"coloring", (PetscObject*)&container);CHKERRQ(ierr);
1870   if (container) {
1871     ierr = PetscContainerDestroy(&container);CHKERRQ(ierr);
1872   }
1873   ierr = MatDestroy(&ctx->M);CHKERRQ(ierr);
1874   ierr = MatDestroy(&ctx->J);CHKERRQ(ierr);
1875   for (ii=0;ii<ctx->num_species;ii++) {
1876     ierr = PetscFEDestroy(&ctx->fe[ii]);CHKERRQ(ierr);
1877   }
1878   if (ctx->deviceType == LANDAU_CUDA) {
1879 #if defined(PETSC_HAVE_CUDA)
1880     ierr = LandauCUDAStaticDataClear(&ctx->SData_d);CHKERRQ(ierr);
1881 #else
1882     SETERRQ1(ctx->comm,PETSC_ERR_ARG_WRONG,"-landau_device_type %s not built","cuda");
1883 #endif
1884   } else if (ctx->deviceType == LANDAU_KOKKOS) {
1885 #if defined(PETSC_HAVE_KOKKOS_KERNELS)
1886     ierr = LandauKokkosStaticDataClear(&ctx->SData_d);CHKERRQ(ierr);
1887 #else
1888     SETERRQ1(ctx->comm,PETSC_ERR_ARG_WRONG,"-landau_device_type %s not built","kokkos");
1889 #endif
1890   } else {
1891     if (ctx->SData_d.x) { /* in a CPU run */
1892       PetscReal *invJ = (PetscReal*)ctx->SData_d.invJ, *xx = (PetscReal*)ctx->SData_d.x, *yy = (PetscReal*)ctx->SData_d.y, *zz = (PetscReal*)ctx->SData_d.z, *ww = (PetscReal*)ctx->SData_d.w;
1893       ierr = PetscFree4(ww,xx,yy,invJ);CHKERRQ(ierr);
1894       if (zz) {
1895         ierr = PetscFree(zz);CHKERRQ(ierr);
1896       }
1897     }
1898   }
1899 
1900   if (ctx->times[LANDAU_MATRIX_TOTAL] > 0) { // OMP timings
1901     ierr = PetscPrintf(ctx->comm, "TSStep               N  1.0 %10.3e\n",ctx->times[LANDAU_EX2_TSSOLVE]);CHKERRQ(ierr);
1902     ierr = PetscPrintf(ctx->comm, "2:           Solve:  %10.3e with %D threads\n",ctx->times[LANDAU_EX2_TSSOLVE] - ctx->times[LANDAU_MATRIX_TOTAL],ctx->batch_sz);CHKERRQ(ierr);
1903     ierr = PetscPrintf(ctx->comm, "3:          Landau:  %10.3e\n",ctx->times[LANDAU_MATRIX_TOTAL]);CHKERRQ(ierr);
1904     ierr = PetscPrintf(ctx->comm, "Landau Jacobian       %D 1.0 %10.3e\n",(PetscInt)ctx->times[LANDAU_JACOBIAN_COUNT],ctx->times[LANDAU_JACOBIAN]);CHKERRQ(ierr);
1905     ierr = PetscPrintf(ctx->comm, "Landau Operator       N 1.0  %10.3e\n",ctx->times[LANDAU_OPERATOR]);CHKERRQ(ierr);
1906     ierr = PetscPrintf(ctx->comm, "Landau Mass           N 1.0  %10.3e\n",ctx->times[LANDAU_MASS]);CHKERRQ(ierr);
1907     ierr = PetscPrintf(ctx->comm, " Jac-f-df (GPU)       N 1.0  %10.3e\n",ctx->times[LANDAU_F_DF]);CHKERRQ(ierr);
1908     ierr = PetscPrintf(ctx->comm, " Kernel (GPU)         N 1.0  %10.3e\n",ctx->times[LANDAU_KERNEL]);CHKERRQ(ierr);
1909     ierr = PetscPrintf(ctx->comm, "MatLUFactorNum        X 1.0 %10.3e\n",ctx->times[KSP_FACTOR]);CHKERRQ(ierr);
1910     ierr = PetscPrintf(ctx->comm, "MatSolve              X 1.0 %10.3e\n",ctx->times[KSP_SOLVE]);CHKERRQ(ierr);
1911   }
1912   for (PetscInt grid=0 ; grid < ctx->num_grids ; grid++) {
1913     ierr = DMDestroy(&ctx->plex[grid]);CHKERRQ(ierr);
1914   }
1915   PetscFree(ctx);
1916   ierr = DMDestroy(dm);CHKERRQ(ierr);
1917   PetscFunctionReturn(0);
1918 }
1919 
1920 /* < v, ru > */
1921 static void f0_s_den(PetscInt dim, PetscInt Nf, PetscInt NfAux,
1922                      const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
1923                      const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
1924                      PetscReal t, const PetscReal x[],  PetscInt numConstants, const PetscScalar constants[], PetscScalar *f0)
1925 {
1926   PetscInt ii = (PetscInt)PetscRealPart(constants[0]);
1927   f0[0] = u[ii];
1928 }
1929 
1930 /* < v, ru > */
1931 static void f0_s_mom(PetscInt dim, PetscInt Nf, PetscInt NfAux,
1932                      const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
1933                      const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
1934                      PetscReal t, const PetscReal x[],  PetscInt numConstants, const PetscScalar constants[], PetscScalar *f0)
1935 {
1936   PetscInt ii = (PetscInt)PetscRealPart(constants[0]), jj = (PetscInt)PetscRealPart(constants[1]);
1937   f0[0] = x[jj]*u[ii]; /* x momentum */
1938 }
1939 
1940 static void f0_s_v2(PetscInt dim, PetscInt Nf, PetscInt NfAux,
1941                     const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
1942                     const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
1943                     PetscReal t, const PetscReal x[],  PetscInt numConstants, const PetscScalar constants[], PetscScalar *f0)
1944 {
1945   PetscInt i, ii = (PetscInt)PetscRealPart(constants[0]);
1946   double tmp1 = 0.;
1947   for (i = 0; i < dim; ++i) tmp1 += x[i]*x[i];
1948   f0[0] = tmp1*u[ii];
1949 }
1950 
1951 static PetscErrorCode gamma_n_f(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *actx)
1952 {
1953   const PetscReal *c2_0_arr = ((PetscReal*)actx);
1954   const PetscReal c02 = c2_0_arr[0];
1955 
1956   PetscFunctionBegin;
1957   for (int s = 0 ; s < Nf ; s++) {
1958     PetscReal tmp1 = 0.;
1959     for (int i = 0; i < dim; ++i) tmp1 += x[i]*x[i];
1960 #if defined(PETSC_USE_DEBUG)
1961     u[s] = PetscSqrtReal(1. + tmp1/c02);//  u[0] = PetscSqrtReal(1. + xx);
1962 #else
1963     {
1964       PetscReal xx = tmp1/c02;
1965       u[s] = xx/(PetscSqrtReal(1. + xx) + 1.); // better conditioned = xx/(PetscSqrtReal(1. + xx) + 1.)
1966     }
1967 #endif
1968   }
1969   PetscFunctionReturn(0);
1970 }
1971 
1972 /* < v, ru > */
1973 static void f0_s_rden(PetscInt dim, PetscInt Nf, PetscInt NfAux,
1974                       const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
1975                       const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
1976                       PetscReal t, const PetscReal x[],  PetscInt numConstants, const PetscScalar constants[], PetscScalar *f0)
1977 {
1978   PetscInt ii = (PetscInt)PetscRealPart(constants[0]);
1979   f0[0] = 2.*PETSC_PI*x[0]*u[ii];
1980 }
1981 
1982 /* < v, ru > */
1983 static void f0_s_rmom(PetscInt dim, PetscInt Nf, PetscInt NfAux,
1984                       const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
1985                       const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
1986                       PetscReal t, const PetscReal x[],  PetscInt numConstants, const PetscScalar constants[], PetscScalar *f0)
1987 {
1988   PetscInt ii = (PetscInt)PetscRealPart(constants[0]);
1989   f0[0] = 2.*PETSC_PI*x[0]*x[1]*u[ii];
1990 }
1991 
1992 static void f0_s_rv2(PetscInt dim, PetscInt Nf, PetscInt NfAux,
1993                      const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
1994                      const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
1995                      PetscReal t, const PetscReal x[],  PetscInt numConstants, const PetscScalar constants[], PetscScalar *f0)
1996 {
1997   PetscInt ii = (PetscInt)PetscRealPart(constants[0]);
1998   f0[0] =  2.*PETSC_PI*x[0]*(x[0]*x[0] + x[1]*x[1])*u[ii];
1999 }
2000 
2001 /*@
2002  LandauPrintNorms - collects moments and prints them
2003 
2004  Collective on dm
2005 
2006  Input Parameters:
2007  +   X  - the state
2008  -   stepi - current step to print
2009 
2010  Level: beginner
2011 
2012  .keywords: mesh
2013  .seealso: LandauCreateVelocitySpace()
2014  @*/
2015 PetscErrorCode LandauPrintNorms(Vec X, PetscInt stepi)
2016 {
2017   PetscErrorCode ierr;
2018   LandauCtx      *ctx;
2019   PetscDS        prob;
2020   DM             pack;
2021   PetscInt       cStart, cEnd, dim, ii, i0, nDMs;
2022   PetscScalar    xmomentumtot=0, ymomentumtot=0, zmomentumtot=0, energytot=0, densitytot=0, tt[LANDAU_MAX_SPECIES];
2023   PetscScalar    xmomentum[LANDAU_MAX_SPECIES],  ymomentum[LANDAU_MAX_SPECIES],  zmomentum[LANDAU_MAX_SPECIES], energy[LANDAU_MAX_SPECIES], density[LANDAU_MAX_SPECIES];
2024   Vec            *globXArray;
2025 
2026   PetscFunctionBegin;
2027   ierr = VecGetDM(X, &pack);CHKERRQ(ierr);
2028   if (!pack) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Vector has no DM");
2029   ierr = DMGetDimension(pack, &dim);CHKERRQ(ierr);
2030   if (dim!=2 && dim!=3) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_PLIB, "dim= %D",dim);
2031   ierr = DMGetApplicationContext(pack, &ctx);CHKERRQ(ierr);
2032   if (!ctx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "no context");
2033   /* print momentum and energy */
2034   ierr = DMCompositeGetNumberDM(pack,&nDMs);CHKERRQ(ierr);
2035   if (nDMs != ctx->num_grids*ctx->batch_sz) SETERRQ2(PETSC_COMM_WORLD, PETSC_ERR_PLIB, "#DM wrong %D %D",nDMs,ctx->num_grids*ctx->batch_sz);
2036   ierr = PetscMalloc(sizeof(*globXArray)*nDMs, &globXArray);CHKERRQ(ierr);
2037   ierr = DMCompositeGetAccessArray(pack, X, nDMs, NULL, globXArray);CHKERRQ(ierr);
2038   for (PetscInt grid = 0; grid < ctx->num_grids ; grid++) {
2039     Vec Xloc = globXArray[ LAND_PACK_IDX(ctx->batch_view_idx,grid) ];
2040     ierr = DMGetDS(ctx->plex[grid], &prob);CHKERRQ(ierr);
2041     for (ii=ctx->species_offset[grid],i0=0;ii<ctx->species_offset[grid+1];ii++,i0++) {
2042       PetscScalar user[2] = { (PetscScalar)i0, (PetscScalar)ctx->charges[ii]};
2043       ierr = PetscDSSetConstants(prob, 2, user);CHKERRQ(ierr);
2044       if (dim==2) { /* 2/3X + 3V (cylindrical coordinates) */
2045         ierr = PetscDSSetObjective(prob, 0, &f0_s_rden);CHKERRQ(ierr);
2046         ierr = DMPlexComputeIntegralFEM(ctx->plex[grid],Xloc,tt,ctx);CHKERRQ(ierr);
2047         density[ii] = tt[0]*ctx->n_0*ctx->charges[ii];
2048         ierr = PetscDSSetObjective(prob, 0, &f0_s_rmom);CHKERRQ(ierr);
2049         ierr = DMPlexComputeIntegralFEM(ctx->plex[grid],Xloc,tt,ctx);CHKERRQ(ierr);
2050         zmomentum[ii] = tt[0]*ctx->n_0*ctx->v_0*ctx->masses[ii];
2051         ierr = PetscDSSetObjective(prob, 0, &f0_s_rv2);CHKERRQ(ierr);
2052         ierr = DMPlexComputeIntegralFEM(ctx->plex[grid],Xloc,tt,ctx);CHKERRQ(ierr);
2053         energy[ii] = tt[0]*0.5*ctx->n_0*ctx->v_0*ctx->v_0*ctx->masses[ii];
2054         zmomentumtot += zmomentum[ii];
2055         energytot  += energy[ii];
2056         densitytot += density[ii];
2057         ierr = PetscPrintf(ctx->comm, "%3D) species-%D: charge density= %20.13e z-momentum= %20.13e energy= %20.13e",stepi,ii,PetscRealPart(density[ii]),PetscRealPart(zmomentum[ii]),PetscRealPart(energy[ii]));CHKERRQ(ierr);
2058       } else { /* 2/3Xloc + 3V */
2059         ierr = PetscDSSetObjective(prob, 0, &f0_s_den);CHKERRQ(ierr);
2060         ierr = DMPlexComputeIntegralFEM(ctx->plex[grid],Xloc,tt,ctx);CHKERRQ(ierr);
2061         density[ii] = tt[0]*ctx->n_0*ctx->charges[ii];
2062         ierr = PetscDSSetObjective(prob, 0, &f0_s_mom);CHKERRQ(ierr);
2063         user[1] = 0;
2064         ierr = PetscDSSetConstants(prob, 2, user);CHKERRQ(ierr);
2065         ierr = DMPlexComputeIntegralFEM(ctx->plex[grid],Xloc,tt,ctx);CHKERRQ(ierr);
2066         xmomentum[ii]  = tt[0]*ctx->n_0*ctx->v_0*ctx->masses[ii];
2067         user[1] = 1;
2068         ierr = PetscDSSetConstants(prob, 2, user);CHKERRQ(ierr);
2069         ierr = DMPlexComputeIntegralFEM(ctx->plex[grid],Xloc,tt,ctx);CHKERRQ(ierr);
2070         ymomentum[ii] = tt[0]*ctx->n_0*ctx->v_0*ctx->masses[ii];
2071         user[1] = 2;
2072         ierr = PetscDSSetConstants(prob, 2, user);CHKERRQ(ierr);
2073         ierr = DMPlexComputeIntegralFEM(ctx->plex[grid],Xloc,tt,ctx);CHKERRQ(ierr);
2074         zmomentum[ii] = tt[0]*ctx->n_0*ctx->v_0*ctx->masses[ii];
2075         if (ctx->use_relativistic_corrections) {
2076           /* gamma * M * f */
2077           if (ii==0 && grid==0) { // do all at once
2078             Vec            Mf, globGamma, *globMfArray, *globGammaArray;
2079             PetscErrorCode (*gammaf[1])(PetscInt, PetscReal, const PetscReal [], PetscInt, PetscScalar [], void *) = {gamma_n_f};
2080             PetscReal      *c2_0[1], data[1];
2081 
2082             ierr = VecDuplicate(X,&globGamma);CHKERRQ(ierr);
2083             ierr = VecDuplicate(X,&Mf);CHKERRQ(ierr);
2084             ierr = PetscMalloc(sizeof(*globMfArray)*nDMs, &globMfArray);CHKERRQ(ierr);
2085             ierr = PetscMalloc(sizeof(*globMfArray)*nDMs, &globGammaArray);CHKERRQ(ierr);
2086             /* M * f */
2087             ierr = MatMult(ctx->M,X,Mf);CHKERRQ(ierr);
2088             /* gamma */
2089             ierr = DMCompositeGetAccessArray(pack, globGamma, nDMs, NULL, globGammaArray);CHKERRQ(ierr);
2090             for (PetscInt grid = 0; grid < ctx->num_grids ; grid++) { // yes a grid loop in a grid loop to print nice, need to fix for batching
2091               Vec v1 = globGammaArray[ LAND_PACK_IDX(ctx->batch_view_idx,grid) ];
2092               data[0] = PetscSqr(C_0(ctx->v_0));
2093               c2_0[0] = &data[0];
2094               ierr = DMProjectFunction(ctx->plex[grid], 0., gammaf, (void**)c2_0, INSERT_ALL_VALUES, v1);CHKERRQ(ierr);
2095             }
2096             ierr = DMCompositeRestoreAccessArray(pack, globGamma, nDMs, NULL, globGammaArray);CHKERRQ(ierr);
2097             /* gamma * Mf */
2098             ierr = DMCompositeGetAccessArray(pack, globGamma, nDMs, NULL, globGammaArray);CHKERRQ(ierr);
2099             ierr = DMCompositeGetAccessArray(pack, Mf, nDMs, NULL, globMfArray);CHKERRQ(ierr);
2100             for (PetscInt grid = 0; grid < ctx->num_grids ; grid++) { // yes a grid loop in a grid loop to print nice
2101               PetscInt Nf = ctx->species_offset[grid+1] - ctx->species_offset[grid], N, bs;
2102               Vec      Mfsub = globMfArray[ LAND_PACK_IDX(ctx->batch_view_idx,grid) ], Gsub = globGammaArray[ LAND_PACK_IDX(ctx->batch_view_idx,grid) ], v1, v2;
2103               // get each component
2104               ierr = VecGetSize(Mfsub,&N);CHKERRQ(ierr);
2105               ierr = VecCreate(ctx->comm,&v1);CHKERRQ(ierr);
2106               ierr = VecSetSizes(v1,PETSC_DECIDE,N/Nf);CHKERRQ(ierr);
2107               ierr = VecCreate(ctx->comm,&v2);CHKERRQ(ierr);
2108               ierr = VecSetSizes(v2,PETSC_DECIDE,N/Nf);CHKERRQ(ierr);
2109               ierr = VecSetFromOptions(v1);CHKERRQ(ierr); // ???
2110               ierr = VecSetFromOptions(v2);CHKERRQ(ierr);
2111               // get each component
2112               ierr = VecGetBlockSize(Gsub,&bs);CHKERRQ(ierr);
2113               if (bs != Nf) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "bs %D != num_species %D in Gsub",bs,Nf);
2114               ierr = VecGetBlockSize(Mfsub,&bs);CHKERRQ(ierr);
2115               if (bs != Nf) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "bs %D != num_species %D",bs,Nf);
2116               for (int i=0, ix=ctx->species_offset[grid] ; i<Nf ; i++, ix++) {
2117                 PetscScalar val;
2118                 ierr = VecStrideGather(Gsub,i,v1,INSERT_VALUES);CHKERRQ(ierr);
2119                 ierr = VecStrideGather(Mfsub,i,v2,INSERT_VALUES);CHKERRQ(ierr);
2120                 ierr = VecDot(v1,v2,&val);CHKERRQ(ierr);
2121                 energy[ix] = PetscRealPart(val)*ctx->n_0*ctx->v_0*ctx->v_0*ctx->masses[ix];
2122               }
2123               ierr = VecDestroy(&v1);CHKERRQ(ierr);
2124               ierr = VecDestroy(&v2);CHKERRQ(ierr);
2125             } /* grids */
2126             ierr = DMCompositeRestoreAccessArray(pack, globGamma, nDMs, NULL, globGammaArray);CHKERRQ(ierr);
2127             ierr = DMCompositeRestoreAccessArray(pack, Mf, nDMs, NULL, globMfArray);CHKERRQ(ierr);
2128             ierr = PetscFree(globGammaArray);CHKERRQ(ierr);
2129             ierr = PetscFree(globMfArray);CHKERRQ(ierr);
2130             ierr = VecDestroy(&globGamma);CHKERRQ(ierr);
2131             ierr = VecDestroy(&Mf);CHKERRQ(ierr);
2132           }
2133         } else {
2134           ierr = PetscDSSetObjective(prob, 0, &f0_s_v2);CHKERRQ(ierr);
2135           ierr = DMPlexComputeIntegralFEM(ctx->plex[grid],Xloc,tt,ctx);CHKERRQ(ierr);
2136           energy[ii]    = 0.5*tt[0]*ctx->n_0*ctx->v_0*ctx->v_0*ctx->masses[ii];
2137         }
2138         ierr = PetscPrintf( ctx->comm, "%3D) species %D: density=%20.13e, x-momentum=%20.13e, y-momentum=%20.13e, z-momentum=%20.13e, energy=%21.13e",
2139                             stepi,ii,PetscRealPart(density[ii]),PetscRealPart(xmomentum[ii]),PetscRealPart(ymomentum[ii]),PetscRealPart(zmomentum[ii]),PetscRealPart(energy[ii]));CHKERRQ(ierr);
2140         xmomentumtot += xmomentum[ii];
2141         ymomentumtot += ymomentum[ii];
2142         zmomentumtot += zmomentum[ii];
2143         energytot  += energy[ii];
2144         densitytot += density[ii];
2145       }
2146       if (ctx->num_species>1) PetscPrintf(ctx->comm, "\n");
2147     }
2148   }
2149   ierr = DMCompositeRestoreAccessArray(pack, X, nDMs, NULL, globXArray);CHKERRQ(ierr);
2150   ierr = PetscFree(globXArray);CHKERRQ(ierr);
2151   /* totals */
2152   ierr = DMPlexGetHeightStratum(ctx->plex[0],0,&cStart,&cEnd);CHKERRQ(ierr);
2153   if (ctx->num_species>1) {
2154     if (dim==2) {
2155       ierr = PetscPrintf(ctx->comm, "\t%3D) Total: charge density=%21.13e, momentum=%21.13e, energy=%21.13e (m_i[0]/m_e = %g, %D cells on electron grid)",
2156                          stepi,(double)PetscRealPart(densitytot),(double)PetscRealPart(zmomentumtot),(double)PetscRealPart(energytot),(double)(ctx->masses[1]/ctx->masses[0]),cEnd-cStart);CHKERRQ(ierr);
2157     } else {
2158       ierr = PetscPrintf(ctx->comm, "\t%3D) Total: charge density=%21.13e, x-momentum=%21.13e, y-momentum=%21.13e, z-momentum=%21.13e, energy=%21.13e (m_i[0]/m_e = %g, %D cells)",
2159                          stepi,(double)PetscRealPart(densitytot),(double)PetscRealPart(xmomentumtot),(double)PetscRealPart(ymomentumtot),(double)PetscRealPart(zmomentumtot),(double)PetscRealPart(energytot),(double)(ctx->masses[1]/ctx->masses[0]),cEnd-cStart);CHKERRQ(ierr);
2160     }
2161   } else {
2162     ierr = PetscPrintf(ctx->comm, " -- %D cells",cEnd-cStart);CHKERRQ(ierr);
2163   }
2164   if (ctx->verbose > 1) {ierr = PetscPrintf(ctx->comm,", %D sub (vector) threads\n",ctx->subThreadBlockSize);CHKERRQ(ierr);}
2165   else {ierr = PetscPrintf(ctx->comm,"\n");CHKERRQ(ierr);}
2166   PetscFunctionReturn(0);
2167 }
2168 
2169 // remove these 3 methods!!!!!!!!!!!
2170 static PetscErrorCode destroy_coloring (void *is)
2171 {
2172   ISColoring tmp = (ISColoring)is;
2173   return ISColoringDestroy(&tmp);
2174 }
2175 
2176 /*@
2177  LandauCreateColoring - create a coloring and add to matrix (Landau context used just for 'print' flag, should be in DMPlex)
2178 
2179  Collective on JacP
2180 
2181  Input Parameters:
2182  +   JacP  - matrix to add coloring to
2183  -   plex - The DM
2184 
2185  Output Parameter:
2186  .   container  - Container with coloring
2187 
2188  Level: beginner
2189 
2190  .keywords: mesh
2191  .seealso: LandauCreateVelocitySpace()
2192  @*/
2193 PetscErrorCode LandauCreateColoring(Mat JacP, DM plex, PetscContainer *container)
2194 {
2195   PetscErrorCode  ierr;
2196   PetscInt        dim,cell,i,ej,nc,Nv,totDim,numGCells,cStart,cEnd;
2197   ISColoring      iscoloring = NULL;
2198   Mat             G,Q;
2199   PetscScalar     ones[128];
2200   MatColoring     mc;
2201   IS             *is;
2202   PetscInt        csize,colour,j,k;
2203   const PetscInt *indices;
2204   PetscInt       numComp[1];
2205   PetscInt       numDof[4];
2206   PetscFE        fe;
2207   DM             colordm;
2208   PetscSection   csection, section, globalSection;
2209   PetscDS        prob;
2210   LandauCtx      *ctx;
2211 
2212   PetscFunctionBegin;
2213   ierr = DMGetApplicationContext(plex, &ctx);CHKERRQ(ierr);
2214   ierr = DMGetLocalSection(plex, &section);CHKERRQ(ierr);
2215   ierr = DMGetGlobalSection(plex, &globalSection);CHKERRQ(ierr);
2216   ierr = DMGetDimension(plex, &dim);CHKERRQ(ierr);
2217   ierr = DMGetDS(plex, &prob);CHKERRQ(ierr);
2218   ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
2219   ierr = DMPlexGetHeightStratum(plex,0,&cStart,&cEnd);CHKERRQ(ierr);
2220   numGCells = cEnd - cStart;
2221   /* create cell centered DM */
2222   ierr = DMClone(plex, &colordm);CHKERRQ(ierr);
2223   ierr = PetscFECreateDefault(PETSC_COMM_SELF, dim, 1, PETSC_FALSE, "color_", PETSC_DECIDE, &fe);CHKERRQ(ierr);
2224   ierr = PetscObjectSetName((PetscObject) fe, "color");CHKERRQ(ierr);
2225   ierr = DMSetField(colordm, 0, NULL, (PetscObject)fe);CHKERRQ(ierr);
2226   ierr = PetscFEDestroy(&fe);CHKERRQ(ierr);
2227   for (i = 0; i < (dim+1); ++i) numDof[i] = 0;
2228   numDof[dim] = 1;
2229   numComp[0] = 1;
2230   ierr = DMPlexCreateSection(colordm, NULL, numComp, numDof, 0, NULL, NULL, NULL, NULL, &csection);CHKERRQ(ierr);
2231   ierr = PetscSectionSetFieldName(csection, 0, "color");CHKERRQ(ierr);
2232   ierr = DMSetLocalSection(colordm, csection);CHKERRQ(ierr);
2233   ierr = DMViewFromOptions(colordm,NULL,"-color_dm_view");CHKERRQ(ierr);
2234   /* get vertex to element map Q and colroing graph G */
2235   ierr = MatGetSize(JacP,NULL,&Nv);CHKERRQ(ierr);
2236   ierr = MatCreateAIJ(PETSC_COMM_SELF,PETSC_DECIDE,PETSC_DECIDE,numGCells,Nv,totDim,NULL,0,NULL,&Q);CHKERRQ(ierr);
2237   for (i=0;i<128;i++) ones[i] = 1.0;
2238   for (cell = cStart, ej = 0 ; cell < cEnd; ++cell, ++ej) {
2239     PetscInt numindices,*indices;
2240     ierr = DMPlexGetClosureIndices(plex, section, globalSection, cell, PETSC_TRUE, &numindices, &indices, NULL, NULL);CHKERRQ(ierr);
2241     if (numindices>128) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "too many indices. %D > %D",numindices,128);
2242     ierr = MatSetValues(Q,1,&ej,numindices,indices,ones,ADD_VALUES);CHKERRQ(ierr);
2243     ierr = DMPlexRestoreClosureIndices(plex, section, globalSection, cell, PETSC_TRUE, &numindices, &indices, NULL, NULL);CHKERRQ(ierr);
2244   }
2245   ierr = MatAssemblyBegin(Q, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2246   ierr = MatAssemblyEnd(Q, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2247   ierr = MatMatTransposeMult(Q,Q,MAT_INITIAL_MATRIX,4.0,&G);CHKERRQ(ierr);
2248   ierr = PetscObjectSetName((PetscObject) Q, "Q");CHKERRQ(ierr);
2249   ierr = PetscObjectSetName((PetscObject) G, "coloring graph");CHKERRQ(ierr);
2250   ierr = MatViewFromOptions(G,NULL,"-coloring_mat_view");CHKERRQ(ierr);
2251   ierr = MatViewFromOptions(Q,NULL,"-coloring_mat_view");CHKERRQ(ierr);
2252   ierr = MatDestroy(&Q);CHKERRQ(ierr);
2253   /* coloring */
2254   ierr = MatColoringCreate(G,&mc);CHKERRQ(ierr);
2255   ierr = MatColoringSetDistance(mc,1);CHKERRQ(ierr);
2256   ierr = MatColoringSetType(mc,MATCOLORINGJP);CHKERRQ(ierr);
2257   ierr = MatColoringSetFromOptions(mc);CHKERRQ(ierr);
2258   ierr = MatColoringApply(mc,&iscoloring);CHKERRQ(ierr);
2259   ierr = MatColoringDestroy(&mc);CHKERRQ(ierr);
2260   /* view */
2261   ierr = ISColoringViewFromOptions(iscoloring,NULL,"-coloring_is_view");CHKERRQ(ierr);
2262   ierr = ISColoringGetIS(iscoloring,PETSC_USE_POINTER,&nc,&is);CHKERRQ(ierr);
2263   if (ctx && ctx->verbose > 2) {
2264     PetscViewer    viewer;
2265     Vec            color_vec, eidx_vec;
2266     ierr = DMGetGlobalVector(colordm, &color_vec);CHKERRQ(ierr);
2267     ierr = DMGetGlobalVector(colordm, &eidx_vec);CHKERRQ(ierr);
2268     for (colour=0; colour<nc; colour++) {
2269       ierr = ISGetLocalSize(is[colour],&csize);CHKERRQ(ierr);
2270       ierr = ISGetIndices(is[colour],&indices);CHKERRQ(ierr);
2271       for (j=0; j<csize; j++) {
2272         PetscScalar v = (PetscScalar)colour;
2273         k = indices[j];
2274         ierr = VecSetValues(color_vec,1,&k,&v,INSERT_VALUES);CHKERRQ(ierr);
2275         v = (PetscScalar)k;
2276         ierr = VecSetValues(eidx_vec,1,&k,&v,INSERT_VALUES);CHKERRQ(ierr);
2277       }
2278       ierr = ISRestoreIndices(is[colour],&indices);CHKERRQ(ierr);
2279     }
2280     /* view */
2281     ierr = PetscViewerVTKOpen(ctx->comm, "color.vtu", FILE_MODE_WRITE, &viewer);CHKERRQ(ierr);
2282     ierr = PetscObjectSetName((PetscObject) color_vec, "color");CHKERRQ(ierr);
2283     ierr = VecView(color_vec, viewer);CHKERRQ(ierr);
2284     ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
2285     ierr = PetscViewerVTKOpen(ctx->comm, "eidx.vtu", FILE_MODE_WRITE, &viewer);CHKERRQ(ierr);
2286     ierr = PetscObjectSetName((PetscObject) eidx_vec, "element-idx");CHKERRQ(ierr);
2287     ierr = VecView(eidx_vec, viewer);CHKERRQ(ierr);
2288     ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
2289     ierr = DMRestoreGlobalVector(colordm, &color_vec);CHKERRQ(ierr);
2290     ierr = DMRestoreGlobalVector(colordm, &eidx_vec);CHKERRQ(ierr);
2291   }
2292   ierr = PetscSectionDestroy(&csection);CHKERRQ(ierr);
2293   ierr = DMDestroy(&colordm);CHKERRQ(ierr);
2294   ierr = ISColoringRestoreIS(iscoloring,PETSC_USE_POINTER,&is);CHKERRQ(ierr);
2295   ierr = MatDestroy(&G);CHKERRQ(ierr);
2296   /* stash coloring */
2297   ierr = PetscContainerCreate(PETSC_COMM_SELF, container);CHKERRQ(ierr);
2298   ierr = PetscContainerSetPointer(*container,(void*)iscoloring);CHKERRQ(ierr);
2299   ierr = PetscContainerSetUserDestroy(*container, destroy_coloring);CHKERRQ(ierr);
2300   ierr = PetscObjectCompose((PetscObject)JacP,"coloring",(PetscObject)*container);CHKERRQ(ierr);
2301   if (ctx && ctx->verbose > 0) {
2302     ierr = PetscPrintf(ctx->comm, "Made coloring with %D colors\n", nc);CHKERRQ(ierr);
2303   }
2304   PetscFunctionReturn(0);
2305 }
2306 
2307 PetscErrorCode LandauAssembleOpenMP(PetscInt cStart, PetscInt cEnd, PetscInt totDim, DM plex, PetscSection section, PetscSection globalSection, Mat JacP, PetscScalar elemMats[], PetscContainer container)
2308 {
2309   PetscErrorCode  ierr;
2310   IS             *is;
2311   PetscInt        nc,colour,j;
2312   const PetscInt *clr_idxs;
2313   ISColoring      iscoloring;
2314   PetscFunctionBegin;
2315   ierr = PetscContainerGetPointer(container,(void**)&iscoloring);CHKERRQ(ierr);
2316   ierr = ISColoringGetIS(iscoloring,PETSC_USE_POINTER,&nc,&is);CHKERRQ(ierr);
2317   for (colour=0; colour<nc; colour++) {
2318     PetscInt    *idx_arr[1024]; /* need to make dynamic for general use */
2319     PetscScalar *new_el_mats[1024];
2320     PetscInt     idx_size[1024],csize;
2321     ierr = ISGetLocalSize(is[colour],&csize);CHKERRQ(ierr);
2322     if (csize>1024) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "too many elements in color. %D > %D",csize,1024);
2323     ierr = ISGetIndices(is[colour],&clr_idxs);CHKERRQ(ierr);
2324     /* get indices and mats */
2325     for (j=0; j<csize; j++) {
2326       PetscInt    cell = cStart + clr_idxs[j];
2327       PetscInt    numindices,*indices;
2328       PetscScalar *elMat = &elemMats[clr_idxs[j]*totDim*totDim];
2329       PetscScalar *valuesOrig = elMat;
2330       ierr = DMPlexGetClosureIndices(plex, section, globalSection, cell, PETSC_TRUE, &numindices, &indices, NULL, (PetscScalar **) &elMat);CHKERRQ(ierr);
2331       idx_size[j] = numindices;
2332       ierr = PetscMalloc2(numindices,&idx_arr[j],numindices*numindices,&new_el_mats[j]);CHKERRQ(ierr);
2333       ierr = PetscMemcpy(idx_arr[j],indices,numindices*sizeof(*idx_arr[j]));CHKERRQ(ierr);
2334       ierr = PetscMemcpy(new_el_mats[j],elMat,numindices*numindices*sizeof(*new_el_mats[j]));CHKERRQ(ierr);
2335       ierr = DMPlexRestoreClosureIndices(plex, section, globalSection, cell, PETSC_TRUE, &numindices, &indices, NULL, (PetscScalar **) &elMat);CHKERRQ(ierr);
2336       if (elMat != valuesOrig) {ierr = DMRestoreWorkArray(plex, numindices*numindices, MPIU_SCALAR, &elMat);CHKERRQ(ierr);}
2337     }
2338     /* assemble matrix */
2339     for (j=0; j<csize; j++) {
2340       PetscInt    numindices = idx_size[j], *indices = idx_arr[j];
2341       PetscScalar *elMat = new_el_mats[j];
2342       MatSetValues(JacP,numindices,indices,numindices,indices,elMat,ADD_VALUES);
2343     }
2344     /* free */
2345     ierr = ISRestoreIndices(is[colour],&clr_idxs);CHKERRQ(ierr);
2346     for (j=0; j<csize; j++) {
2347       ierr = PetscFree2(idx_arr[j],new_el_mats[j]);CHKERRQ(ierr);
2348     }
2349   }
2350   ierr = ISColoringRestoreIS(iscoloring,PETSC_USE_POINTER,&is);CHKERRQ(ierr);
2351   PetscFunctionReturn(0);
2352 }
2353 
2354 /* < v, u > */
2355 static void g0_1(PetscInt dim, PetscInt Nf, PetscInt NfAux,
2356                  const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
2357                  const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
2358                  PetscReal t, PetscReal u_tShift, const PetscReal x[],  PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[])
2359 {
2360   g0[0] = 1.;
2361 }
2362 
2363 /* < v, u > */
2364 static void g0_r(PetscInt dim, PetscInt Nf, PetscInt NfAux,
2365                  const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],
2366                  const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
2367                  PetscReal t, PetscReal u_tShift, const PetscReal x[],  PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[])
2368 {
2369   g0[0] = 2.*PETSC_PI*x[0];
2370 }
2371 
2372 /*@
2373  LandauCreateMassMatrix - Create mass matrix for Landau
2374 
2375  Collective on pack
2376 
2377  Input Parameters:
2378  . pack     - the DM object
2379 
2380  Output Parameters:
2381  . Amat - The mass matrix (optional), mass matrix is added to the DM context
2382 
2383  Level: beginner
2384 
2385  .keywords: mesh
2386  .seealso: LandauCreateVelocitySpace()
2387  @*/
2388 PetscErrorCode LandauCreateMassMatrix(DM pack, Mat *Amat)
2389 {
2390   DM             mass_pack,massDM[LANDAU_MAX_GRIDS];
2391   PetscDS        prob;
2392   PetscInt       ii,dim,N1=1,N2;
2393   PetscErrorCode ierr;
2394   LandauCtx      *ctx;
2395   Mat            packM,subM[LANDAU_MAX_GRIDS];
2396 
2397   PetscFunctionBegin;
2398   PetscValidHeaderSpecific(pack,DM_CLASSID,1);
2399   if (Amat) PetscValidPointer(Amat,2);
2400   ierr = DMGetApplicationContext(pack, &ctx);CHKERRQ(ierr);
2401   if (!ctx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "no context");
2402   ierr = DMGetDimension(pack, &dim);CHKERRQ(ierr);
2403   ierr = DMCompositeCreate(PetscObjectComm((PetscObject) pack),&mass_pack);CHKERRQ(ierr);
2404   /* create pack mass matrix */
2405   for (PetscInt grid=0, ix=0 ; grid<ctx->num_grids ; grid++) {
2406     ierr = DMClone(ctx->plex[grid], &massDM[grid]);CHKERRQ(ierr);
2407     ierr = DMCopyFields(ctx->plex[grid], massDM[grid]);CHKERRQ(ierr);
2408     ierr = DMCreateDS(massDM[grid]);CHKERRQ(ierr);
2409     ierr = DMGetDS(massDM[grid], &prob);CHKERRQ(ierr);
2410     for (ix=0, ii=ctx->species_offset[grid];ii<ctx->species_offset[grid+1];ii++,ix++) {
2411       if (dim==3) {ierr = PetscDSSetJacobian(prob, ix, ix, g0_1, NULL, NULL, NULL);CHKERRQ(ierr);}
2412       else        {ierr = PetscDSSetJacobian(prob, ix, ix, g0_r, NULL, NULL, NULL);CHKERRQ(ierr);}
2413     }
2414 #if !defined(LANDAU_SPECIES_MAJOR)
2415     ierr = DMCompositeAddDM(mass_pack,massDM[grid]);CHKERRQ(ierr);
2416 #else
2417     for (PetscInt b_id=0;b_id<ctx->batch_sz;b_id++) { // add batch size DMs for this species grid
2418       ierr = DMCompositeAddDM(mass_pack,massDM[grid]);CHKERRQ(ierr);
2419     }
2420 #endif
2421     ierr = DMCreateMatrix(massDM[grid], &subM[grid]);CHKERRQ(ierr);
2422   }
2423 #if !defined(LANDAU_SPECIES_MAJOR)
2424   // stack the batched DMs
2425   for (PetscInt b_id=1;b_id<ctx->batch_sz;b_id++) {
2426     for (PetscInt grid=0;grid<ctx->num_grids;grid++) {
2427       ierr = DMCompositeAddDM(mass_pack, massDM[grid]);CHKERRQ(ierr);
2428     }
2429   }
2430 #endif
2431   ierr = PetscOptionsInsertString(NULL,"-dm_preallocate_only");
2432   ierr = DMSetFromOptions(mass_pack);CHKERRQ(ierr);
2433   ierr = DMCreateMatrix(mass_pack, &packM);CHKERRQ(ierr);
2434   ierr = PetscOptionsInsertString(NULL,"-dm_preallocate_only false");
2435   ierr = MatSetOption(packM, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE);CHKERRQ(ierr);
2436   ierr = MatSetOption(packM, MAT_STRUCTURALLY_SYMMETRIC, PETSC_TRUE);CHKERRQ(ierr);
2437   ierr = DMViewFromOptions(mass_pack,NULL,"-dm_landau_mass_dm_view");CHKERRQ(ierr);
2438   ierr = DMDestroy(&mass_pack);CHKERRQ(ierr);
2439   /* make mass matrix for each block */
2440   for (PetscInt grid=0;grid<ctx->num_grids;grid++) {
2441     Vec locX;
2442     DM  plex = massDM[grid];
2443     ierr = DMGetLocalVector(plex, &locX);CHKERRQ(ierr);
2444     /* Mass matrix is independent of the input, so no need to fill locX */
2445     ierr = DMPlexSNESComputeJacobianFEM(plex, locX, subM[grid], subM[grid], ctx);CHKERRQ(ierr);
2446     ierr = DMRestoreLocalVector(plex, &locX);CHKERRQ(ierr);
2447     ierr = DMDestroy(&massDM[grid]);CHKERRQ(ierr);
2448   }
2449   ierr = MatGetSize(ctx->J, &N1, NULL);CHKERRQ(ierr);
2450   ierr = MatGetSize(packM, &N2, NULL);CHKERRQ(ierr);
2451   if (N1 != N2) SETERRQ2(PetscObjectComm((PetscObject) pack), PETSC_ERR_PLIB, "Incorrect matrix sizes: |Jacobian| = %D, |Mass|=%D",N1,N2);
2452   /* assemble block diagonals */
2453   for (PetscInt grid=0 ; grid<ctx->num_grids ; grid++) {
2454     Mat               B = subM[grid];
2455     PetscInt          nloc, nzl, colbuf[1024], row;
2456     ierr = MatGetSize(B, &nloc, NULL);CHKERRQ(ierr);
2457     for (PetscInt b_id = 0 ; b_id < ctx->batch_sz ; b_id++) {
2458       const PetscInt    moffset = LAND_MOFFSET(b_id,grid,ctx->batch_sz,ctx->num_grids,ctx->mat_offset);
2459       const PetscInt    *cols;
2460       const PetscScalar *vals;
2461       for (int i=0 ; i<nloc ; i++) {
2462         ierr = MatGetRow(B,i,&nzl,&cols,&vals);CHKERRQ(ierr);
2463         if (nzl>1024) SETERRQ1(PetscObjectComm((PetscObject) pack), PETSC_ERR_PLIB, "Row too big: %D",nzl);
2464         for (int j=0; j<nzl; j++) colbuf[j] = cols[j] + moffset;
2465         row = i + moffset;
2466         ierr = MatSetValues(packM,1,&row,nzl,colbuf,vals,INSERT_VALUES);CHKERRQ(ierr);
2467         ierr = MatRestoreRow(B,i,&nzl,&cols,&vals);CHKERRQ(ierr);
2468       }
2469     }
2470   }
2471   // cleanup
2472   for (PetscInt grid=0 ; grid<ctx->num_grids ; grid++) {
2473     ierr = MatDestroy(&subM[grid]);CHKERRQ(ierr);
2474   }
2475   ierr = MatAssemblyBegin(packM,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2476   ierr = MatAssemblyEnd(packM,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2477   ierr = PetscObjectSetName((PetscObject)packM, "mass");CHKERRQ(ierr);
2478   ierr = MatViewFromOptions(packM,NULL,"-dm_landau_mass_view");CHKERRQ(ierr);
2479   ctx->M = packM; /* this could be a noop, a = a */
2480   if (Amat) *Amat = packM;
2481   PetscFunctionReturn(0);
2482 }
2483 
2484 /*@
2485  LandauIFunction - TS residual calculation
2486 
2487  Collective on ts
2488 
2489  Input Parameters:
2490  +   TS  - The time stepping context
2491  .   time_dummy - current time (not used)
2492  -   X - Current state
2493  +   X_t - Time derivative of current state
2494  .   actx - Landau context
2495 
2496  Output Parameter:
2497  .   F  - The residual
2498 
2499  Level: beginner
2500 
2501  .keywords: mesh
2502  .seealso: LandauCreateVelocitySpace(), LandauIJacobian()
2503  @*/
2504 PetscErrorCode LandauIFunction(TS ts, PetscReal time_dummy, Vec X, Vec X_t, Vec F, void *actx)
2505 {
2506   PetscErrorCode ierr;
2507   LandauCtx      *ctx=(LandauCtx*)actx;
2508   PetscInt       dim;
2509   DM             pack;
2510 #if defined(PETSC_HAVE_THREADSAFETY)
2511   double         starttime, endtime;
2512 #endif
2513 
2514   PetscFunctionBegin;
2515   ierr = TSGetDM(ts,&pack);CHKERRQ(ierr);
2516   ierr = DMGetApplicationContext(pack, &ctx);CHKERRQ(ierr);
2517   if (!ctx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "no context");
2518   if (ctx->stage) {
2519     ierr = PetscLogStagePush(ctx->stage);CHKERRQ(ierr);
2520   }
2521   ierr = PetscLogEventBegin(ctx->events[11],0,0,0,0);CHKERRQ(ierr);
2522   ierr = PetscLogEventBegin(ctx->events[0],0,0,0,0);CHKERRQ(ierr);
2523 #if defined(PETSC_HAVE_THREADSAFETY)
2524   starttime = MPI_Wtime();
2525 #endif
2526   ierr = DMGetDimension(pack, &dim);CHKERRQ(ierr);
2527   if (!ctx->aux_bool) {
2528     ierr = PetscInfo3(ts, "Create Landau Jacobian t=%g X=%p %s\n",time_dummy,X_t,ctx->aux_bool ? " -- seems to be in line search" : "");CHKERRQ(ierr);
2529     ierr = LandauFormJacobian_Internal(X,ctx->J,dim,0.0,(void*)ctx);CHKERRQ(ierr);
2530     ierr = MatViewFromOptions(ctx->J, NULL, "-dm_landau_jacobian_view");CHKERRQ(ierr);
2531     ctx->aux_bool = PETSC_TRUE;
2532   } else {
2533     ierr = PetscInfo(ts, "Skip forming Jacobian, has not changed (should check norm)\n");CHKERRQ(ierr);
2534   }
2535   /* mat vec for op */
2536   ierr = MatMult(ctx->J,X,F);CHKERRQ(ierr);CHKERRQ(ierr); /* C*f */
2537   /* add time term */
2538   if (X_t) {
2539     ierr = MatMultAdd(ctx->M,X_t,F,F);CHKERRQ(ierr);
2540   }
2541 #if defined(PETSC_HAVE_THREADSAFETY)
2542   if (ctx->stage) {
2543     endtime = MPI_Wtime();
2544     ctx->times[LANDAU_OPERATOR] += (endtime - starttime);
2545     ctx->times[LANDAU_JACOBIAN] += (endtime - starttime);
2546     ctx->times[LANDAU_JACOBIAN_COUNT] += 1;
2547   }
2548 #endif
2549   ierr = PetscLogEventEnd(ctx->events[0],0,0,0,0);CHKERRQ(ierr);
2550   ierr = PetscLogEventEnd(ctx->events[11],0,0,0,0);CHKERRQ(ierr);
2551   if (ctx->stage) {
2552     ierr = PetscLogStagePop();CHKERRQ(ierr);
2553 #if defined(PETSC_HAVE_THREADSAFETY)
2554     ctx->times[LANDAU_MATRIX_TOTAL] += (endtime - starttime);
2555 #endif
2556   }
2557   PetscFunctionReturn(0);
2558 }
2559 
2560 static PetscErrorCode MatrixNfDestroy(void *ptr)
2561 {
2562   PetscInt *nf = (PetscInt *)ptr;
2563   PetscErrorCode  ierr;
2564   PetscFunctionBegin;
2565   ierr = PetscFree(nf);CHKERRQ(ierr);
2566   PetscFunctionReturn(0);
2567 }
2568 /*@
2569  LandauIJacobian - TS Jacobian construction
2570 
2571  Collective on ts
2572 
2573  Input Parameters:
2574  +   TS  - The time stepping context
2575  .   time_dummy - current time (not used)
2576  -   X - Current state
2577  +   U_tdummy - Time derivative of current state (not used)
2578  .   shift - shift for du/dt term
2579  -   actx - Landau context
2580 
2581  Output Parameter:
2582  .   Amat  - Jacobian
2583  +   Pmat  - same as Amat
2584 
2585  Level: beginner
2586 
2587  .keywords: mesh
2588  .seealso: LandauCreateVelocitySpace(), LandauIFunction()
2589  @*/
2590 PetscErrorCode LandauIJacobian(TS ts, PetscReal time_dummy, Vec X, Vec U_tdummy, PetscReal shift, Mat Amat, Mat Pmat, void *actx)
2591 {
2592   PetscErrorCode ierr;
2593   LandauCtx      *ctx=NULL;
2594   PetscInt       dim;
2595   DM             pack;
2596   PetscContainer container;
2597 #if defined(PETSC_HAVE_THREADSAFETY)
2598   double         starttime, endtime;
2599 #endif
2600   PetscFunctionBegin;
2601   ierr = TSGetDM(ts,&pack);CHKERRQ(ierr);
2602   ierr = DMGetApplicationContext(pack, &ctx);CHKERRQ(ierr);
2603   if (!ctx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "no context");
2604   if (Amat!=Pmat || Amat!=ctx->J) SETERRQ(ctx->comm, PETSC_ERR_PLIB, "Amat!=Pmat || Amat!=ctx->J");
2605   ierr = DMGetDimension(pack, &dim);CHKERRQ(ierr);
2606   /* get collision Jacobian into A */
2607   if (ctx->stage) {
2608     ierr = PetscLogStagePush(ctx->stage);CHKERRQ(ierr);
2609   }
2610   ierr = PetscLogEventBegin(ctx->events[11],0,0,0,0);CHKERRQ(ierr);
2611   ierr = PetscLogEventBegin(ctx->events[9],0,0,0,0);CHKERRQ(ierr);
2612 #if defined(PETSC_HAVE_THREADSAFETY)
2613   starttime = MPI_Wtime();
2614 #endif
2615   ierr = PetscInfo2(ts, "Adding just mass to Jacobian t=%g, shift=%g\n",(double)time_dummy,(double)shift);CHKERRQ(ierr);
2616   if (shift==0.0) SETERRQ(ctx->comm, PETSC_ERR_PLIB, "zero shift");
2617   if (!ctx->aux_bool) SETERRQ(ctx->comm, PETSC_ERR_PLIB, "wrong state");
2618   if (!ctx->use_matrix_mass) {
2619     ierr = LandauFormJacobian_Internal(X,ctx->J,dim,shift,(void*)ctx);CHKERRQ(ierr);
2620     ierr = MatViewFromOptions(ctx->J, NULL, "-dm_landau_mat_view");CHKERRQ(ierr);
2621   } else { /* add mass */
2622     ierr = MatAXPY(Pmat,shift,ctx->M,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
2623   }
2624   ctx->aux_bool = PETSC_FALSE;
2625   /* set number species in Jacobian */
2626   ierr = PetscObjectQuery((PetscObject) ctx->J, "Nf", (PetscObject *) &container);CHKERRQ(ierr);
2627   if (!container) {
2628     PetscInt *pNf;
2629     ierr = PetscContainerCreate(PETSC_COMM_SELF, &container);CHKERRQ(ierr);
2630     ierr = PetscMalloc(sizeof(*pNf), &pNf);CHKERRQ(ierr);
2631     *pNf = ctx->num_species + 100000*ctx->numConcurrency;
2632     ierr = PetscContainerSetPointer(container, (void *)pNf);CHKERRQ(ierr);
2633     ierr = PetscContainerSetUserDestroy(container, MatrixNfDestroy);CHKERRQ(ierr);
2634     ierr = PetscObjectCompose((PetscObject)ctx->J, "Nf", (PetscObject) container);CHKERRQ(ierr);
2635     ierr = PetscContainerDestroy(&container);CHKERRQ(ierr);
2636   }
2637 #if defined(PETSC_HAVE_THREADSAFETY)
2638   if (ctx->stage) {
2639     endtime = MPI_Wtime();
2640     ctx->times[LANDAU_OPERATOR] += (endtime - starttime);
2641     ctx->times[LANDAU_MASS] += (endtime - starttime);
2642   }
2643 #endif
2644   ierr = PetscLogEventEnd(ctx->events[9],0,0,0,0);CHKERRQ(ierr);
2645   ierr = PetscLogEventEnd(ctx->events[11],0,0,0,0);CHKERRQ(ierr);
2646   if (ctx->stage) {
2647     ierr = PetscLogStagePop();CHKERRQ(ierr);
2648 #if defined(PETSC_HAVE_THREADSAFETY)
2649     ctx->times[LANDAU_MATRIX_TOTAL] += (endtime - starttime);
2650 #endif
2651   }
2652   PetscFunctionReturn(0);
2653 }
2654