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