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