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