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