Actual source code: plexland.c

  1: #include <../src/mat/impls/aij/seq/aij.h>
  2: #include <petsc/private/dmpleximpl.h>
  3: #include <petsclandau.h>
  4: #include <petscts.h>
  5: #include <petscdmforest.h>
  6: #include <petscdmcomposite.h>

  8: /* Landau collision operator */

 10: /* relativistic terms */
 11: #if PetscDefined(USE_REAL_SINGLE)
 12:   #define SPEED_OF_LIGHT 2.99792458e8F
 13:   #define C_0(v0)        (SPEED_OF_LIGHT / v0) /* needed for relativistic tensor on all architectures */
 14: #else
 15:   #define SPEED_OF_LIGHT 2.99792458e8
 16:   #define C_0(v0)        (SPEED_OF_LIGHT / v0) /* needed for relativistic tensor on all architectures */
 17: #endif

 19: #include "land_tensors.h"

 21: #if PetscDefined(HAVE_OPENMP)
 22:   #include <omp.h>
 23: #endif

 25: static PetscErrorCode LandauGPUMapsDestroy(PetscCtxRt ptr)
 26: {
 27:   P4estVertexMaps *maps = *(P4estVertexMaps **)ptr;

 29:   PetscFunctionBegin;
 30:   // free device data
 31:   if (maps[0].deviceType != LANDAU_CPU) {
 32: #if PetscDefined(HAVE_KOKKOS)
 33:     if (maps[0].deviceType == LANDAU_KOKKOS) PetscCall(LandauKokkosDestroyMatMaps(maps, maps[0].numgrids)); // implies Kokkos does
 34: #endif
 35:   }
 36:   // free host data
 37:   for (PetscInt grid = 0; grid < maps[0].numgrids; grid++) {
 38:     PetscCall(PetscFree(maps[grid].c_maps));
 39:     PetscCall(PetscFree(maps[grid].gIdx));
 40:   }
 41:   PetscCall(PetscFree(maps));
 42:   PetscFunctionReturn(PETSC_SUCCESS);
 43: }
 44: static PetscErrorCode energy_f(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf_dummy, PetscScalar *u, void *actx)
 45: {
 46:   PetscReal v2 = 0;

 48:   PetscFunctionBegin;
 49:   /* compute v^2 / 2 */
 50:   for (PetscInt i = 0; i < dim; ++i) v2 += x[i] * x[i];
 51:   /* evaluate the Maxwellian */
 52:   u[0] = v2 / 2;
 53:   PetscFunctionReturn(PETSC_SUCCESS);
 54: }

 56: /* needs double */
 57: static PetscErrorCode gamma_m1_f(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf_dummy, PetscScalar *u, void *actx)
 58: {
 59:   PetscReal *c2_0_arr = ((PetscReal *)actx);
 60:   double     u2 = 0, c02 = (double)*c2_0_arr, xx;

 62:   PetscFunctionBegin;
 63:   /* compute u^2 / 2 */
 64:   for (PetscInt i = 0; i < dim; ++i) u2 += x[i] * x[i];
 65:   /* gamma - 1 = g_eps, for conditioning and we only take derivatives */
 66:   xx = u2 / c02;
 67:   if (PetscDefined(USE_DEBUG)) u[0] = PetscSqrtReal(1. + xx);
 68:   else u[0] = xx / (PetscSqrtReal(1. + xx) + 1.) - 1.; // better conditioned. -1 might help condition and only used for derivative
 69:   PetscFunctionReturn(PETSC_SUCCESS);
 70: }

 72: /* Evaluates Jacobian matrix; fills JacP, does not create it */
 73: static PetscErrorCode LandauFormJacobian_Internal(Vec a_X, Mat JacP, const PetscInt dim, PetscReal shift, void *a_ctx)
 74: {
 75:   LandauCtx         *ctx = (LandauCtx *)a_ctx;
 76:   PetscInt           numCells[LANDAU_MAX_GRIDS], Nq, Nb;
 77:   PetscQuadrature    quad;
 78:   PetscReal          Eq_m[LANDAU_MAX_SPECIES]; // could be static data w/o quench (ex2)
 79:   PetscScalar       *cellClosure = NULL;
 80:   const PetscScalar *xdata       = NULL;
 81:   PetscDS            prob;
 82:   PetscContainer     container;
 83:   P4estVertexMaps   *maps;
 84:   Mat                subJ[LANDAU_MAX_GRIDS * LANDAU_MAX_BATCH_SZ];

 86:   PetscFunctionBegin;
 89:   PetscAssertPointer(ctx, 5);
 90:   /* check for matrix container for GPU assembly. Support CPU assembly for debugging */
 91:   PetscCheck(ctx->plex[0] != NULL, ctx->comm, PETSC_ERR_ARG_WRONG, "Plex not created");
 92:   PetscCall(PetscLogEventBegin(ctx->events[10], 0, 0, 0, 0));
 93:   PetscCall(DMGetDS(ctx->plex[0], &prob)); // same DS for all grids
 94:   PetscCall(PetscObjectQuery((PetscObject)JacP, "assembly_maps", (PetscObject *)&container));
 95:   if (container) {
 96:     PetscCheck(ctx->gpu_assembly, ctx->comm, PETSC_ERR_ARG_WRONG, "maps but no GPU assembly");
 97:     PetscCall(PetscContainerGetPointer(container, &maps));
 98:     PetscCheck(maps, ctx->comm, PETSC_ERR_ARG_WRONG, "empty GPU matrix container");
 99:     for (PetscInt i = 0; i < ctx->num_grids * ctx->batch_sz; i++) subJ[i] = NULL;
100:   } else {
101:     PetscCheck(!ctx->gpu_assembly, ctx->comm, PETSC_ERR_ARG_WRONG, "No maps but GPU assembly");
102:     for (PetscInt tid = 0; tid < ctx->batch_sz; tid++) {
103:       for (PetscInt grid = 0; grid < ctx->num_grids; grid++) PetscCall(DMCreateMatrix(ctx->plex[grid], &subJ[LAND_PACK_IDX(tid, grid)]));
104:     }
105:     maps = NULL;
106:   }
107:   // get dynamic data (Eq is odd, for quench and Spitzer test) for CPU assembly and raw data for Jacobian GPU assembly. Get host numCells[], Nq (yuck)
108:   PetscCall(PetscFEGetQuadrature(ctx->fe[0], &quad));
109:   PetscCall(PetscQuadratureGetData(quad, NULL, NULL, &Nq, NULL, NULL));
110:   PetscCall(PetscFEGetDimension(ctx->fe[0], &Nb));
111:   PetscCheck(Nq <= LANDAU_MAX_NQND, ctx->comm, PETSC_ERR_ARG_WRONG, "Order too high. Nq = %" PetscInt_FMT " > LANDAU_MAX_NQND (%d)", Nq, LANDAU_MAX_NQND);
112:   PetscCheck(Nb <= LANDAU_MAX_NQND, ctx->comm, PETSC_ERR_ARG_WRONG, "Order too high. Nb = %" PetscInt_FMT " > LANDAU_MAX_NQND (%d)", Nb, LANDAU_MAX_NQND);
113:   // get metadata for collecting dynamic data
114:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
115:     PetscInt cStart, cEnd;
116:     PetscCheck(ctx->plex[grid] != NULL, ctx->comm, PETSC_ERR_ARG_WRONG, "Plex not created");
117:     PetscCall(DMPlexGetHeightStratum(ctx->plex[grid], 0, &cStart, &cEnd));
118:     numCells[grid] = cEnd - cStart; // grids can have different topology
119:   }
120:   PetscCall(PetscLogEventEnd(ctx->events[10], 0, 0, 0, 0));
121:   if (shift == 0) { /* create dynamic point data: f_alpha for closure of each cell (cellClosure[nbatch,ngrids,ncells[g],f[Nb,ns[g]]]) or xdata */
122:     DM pack;
123:     PetscCall(VecGetDM(a_X, &pack));
124:     PetscCheck(pack, PETSC_COMM_SELF, PETSC_ERR_PLIB, "pack has no DM");
125:     PetscCall(PetscLogEventBegin(ctx->events[1], 0, 0, 0, 0));
126:     for (PetscInt fieldA = 0; fieldA < ctx->num_species; fieldA++) {
127:       Eq_m[fieldA] = ctx->Ez * ctx->t_0 * ctx->charges[fieldA] / (ctx->v_0 * ctx->masses[fieldA]); /* normalize dimensionless */
128:       if (dim == 2) Eq_m[fieldA] *= 2 * PETSC_PI;                                                  /* add the 2pi term that is not in Landau */
129:     }
130:     if (!ctx->gpu_assembly) {
131:       Vec         *locXArray, *globXArray;
132:       PetscScalar *cellClosure_it;
133:       PetscInt     cellClosure_sz = 0, nDMs, Nf[LANDAU_MAX_GRIDS];
134:       PetscSection section[LANDAU_MAX_GRIDS], globsection[LANDAU_MAX_GRIDS];
135:       for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
136:         PetscCall(DMGetLocalSection(ctx->plex[grid], &section[grid]));
137:         PetscCall(DMGetGlobalSection(ctx->plex[grid], &globsection[grid]));
138:         PetscCall(PetscSectionGetNumFields(section[grid], &Nf[grid]));
139:       }
140:       /* count cellClosure size */
141:       PetscCall(DMCompositeGetNumberDM(pack, &nDMs));
142:       for (PetscInt grid = 0; grid < ctx->num_grids; grid++) cellClosure_sz += Nb * Nf[grid] * numCells[grid];
143:       PetscCall(PetscMalloc1(cellClosure_sz * ctx->batch_sz, &cellClosure));
144:       cellClosure_it = cellClosure;
145:       PetscCall(PetscMalloc(sizeof(*locXArray) * nDMs, &locXArray));
146:       PetscCall(PetscMalloc(sizeof(*globXArray) * nDMs, &globXArray));
147:       PetscCall(DMCompositeGetLocalAccessArray(pack, a_X, nDMs, NULL, locXArray));
148:       PetscCall(DMCompositeGetAccessArray(pack, a_X, nDMs, NULL, globXArray));
149:       for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) { // OpenMP (once)
150:         for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
151:           Vec      locX = locXArray[LAND_PACK_IDX(b_id, grid)], globX = globXArray[LAND_PACK_IDX(b_id, grid)], locX2;
152:           PetscInt cStart, cEnd, ei;
153:           PetscCall(VecDuplicate(locX, &locX2));
154:           PetscCall(DMGlobalToLocalBegin(ctx->plex[grid], globX, INSERT_VALUES, locX2));
155:           PetscCall(DMGlobalToLocalEnd(ctx->plex[grid], globX, INSERT_VALUES, locX2));
156:           PetscCall(DMPlexGetHeightStratum(ctx->plex[grid], 0, &cStart, &cEnd));
157:           for (ei = cStart; ei < cEnd; ++ei) {
158:             PetscScalar *coef = NULL;
159:             PetscCall(DMPlexVecGetClosure(ctx->plex[grid], section[grid], locX2, ei, NULL, &coef));
160:             PetscCall(PetscMemcpy(cellClosure_it, coef, Nb * Nf[grid] * sizeof(*cellClosure_it))); /* change if LandauIPReal != PetscScalar */
161:             PetscCall(DMPlexVecRestoreClosure(ctx->plex[grid], section[grid], locX2, ei, NULL, &coef));
162:             cellClosure_it += Nb * Nf[grid];
163:           }
164:           PetscCall(VecDestroy(&locX2));
165:         }
166:       }
167:       PetscCheck(cellClosure_it - cellClosure == cellClosure_sz * ctx->batch_sz, PETSC_COMM_SELF, PETSC_ERR_PLIB, "iteration wrong %" PetscCount_FMT " != cellClosure_sz = %" PetscInt_FMT, cellClosure_it - cellClosure, cellClosure_sz * ctx->batch_sz);
168:       PetscCall(DMCompositeRestoreLocalAccessArray(pack, a_X, nDMs, NULL, locXArray));
169:       PetscCall(DMCompositeRestoreAccessArray(pack, a_X, nDMs, NULL, globXArray));
170:       PetscCall(PetscFree(locXArray));
171:       PetscCall(PetscFree(globXArray));
172:       xdata = NULL;
173:     } else {
174:       PetscMemType mtype;
175:       if (ctx->jacobian_field_major_order) { // get data in batch ordering
176:         PetscCall(VecScatterBegin(ctx->plex_batch, a_X, ctx->work_vec, INSERT_VALUES, SCATTER_FORWARD));
177:         PetscCall(VecScatterEnd(ctx->plex_batch, a_X, ctx->work_vec, INSERT_VALUES, SCATTER_FORWARD));
178:         PetscCall(VecGetArrayReadAndMemType(ctx->work_vec, &xdata, &mtype));
179:       } else {
180:         PetscCall(VecGetArrayReadAndMemType(a_X, &xdata, &mtype));
181:       }
182:       PetscCheck(mtype == PETSC_MEMTYPE_HOST || ctx->deviceType != LANDAU_CPU, ctx->comm, PETSC_ERR_ARG_WRONG, "CPU run with device data: use -mat_type aij");
183:       cellClosure = NULL;
184:     }
185:     PetscCall(PetscLogEventEnd(ctx->events[1], 0, 0, 0, 0));
186:   } else xdata = cellClosure = NULL;

188:   /* do it */
189:   if (ctx->deviceType == LANDAU_KOKKOS) {
190: #if PetscDefined(HAVE_KOKKOS)
191:     PetscCall(LandauKokkosJacobian(ctx->plex, Nq, Nb, ctx->batch_sz, ctx->num_grids, numCells, Eq_m, cellClosure, xdata, &ctx->SData_d, shift, ctx->events, ctx->mat_offset, ctx->species_offset, subJ, JacP));
192: #else
193:     SETERRQ(ctx->comm, PETSC_ERR_ARG_WRONG, "-landau_device_type %s not built", "kokkos");
194: #endif
195:   } else {               /* CPU version */
196:     PetscTabulation *Tf; // used for CPU and print info. Same on all grids and all species
197:     PetscInt         ip_offset[LANDAU_MAX_GRIDS + 1], ipf_offset[LANDAU_MAX_GRIDS + 1], elem_offset[LANDAU_MAX_GRIDS + 1], IPf_sz_glb, IPf_sz_tot, num_grids = ctx->num_grids, Nf[LANDAU_MAX_GRIDS];
198:     PetscReal       *ff, *dudx, *dudy, *dudz, *invJ_a = (PetscReal *)ctx->SData_d.invJ, *xx = (PetscReal *)ctx->SData_d.x, *yy = (PetscReal *)ctx->SData_d.y, *zz = (PetscReal *)ctx->SData_d.z, *ww = (PetscReal *)ctx->SData_d.w;
199:     PetscReal       *nu_alpha = (PetscReal *)ctx->SData_d.alpha, *nu_beta = (PetscReal *)ctx->SData_d.beta, *invMass = (PetscReal *)ctx->SData_d.invMass;
200:     PetscReal (*lambdas)[LANDAU_MAX_GRIDS][LANDAU_MAX_GRIDS] = (PetscReal (*)[LANDAU_MAX_GRIDS][LANDAU_MAX_GRIDS])ctx->SData_d.lambdas;
201:     PetscSection section[LANDAU_MAX_GRIDS], globsection[LANDAU_MAX_GRIDS];
202:     PetscScalar *coo_vals = NULL;
203:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
204:       PetscCall(DMGetLocalSection(ctx->plex[grid], &section[grid]));
205:       PetscCall(DMGetGlobalSection(ctx->plex[grid], &globsection[grid]));
206:       PetscCall(PetscSectionGetNumFields(section[grid], &Nf[grid]));
207:     }
208:     /* count IPf size, etc */
209:     PetscCall(PetscDSGetTabulation(prob, &Tf)); // Bf, &Df same for all grids
210:     const PetscReal *const BB = Tf[0]->T[0], *const DD = Tf[0]->T[1];
211:     ip_offset[0] = ipf_offset[0] = elem_offset[0] = 0;
212:     for (PetscInt grid = 0; grid < num_grids; grid++) {
213:       PetscInt nfloc        = ctx->species_offset[grid + 1] - ctx->species_offset[grid];
214:       elem_offset[grid + 1] = elem_offset[grid] + numCells[grid];
215:       ip_offset[grid + 1]   = ip_offset[grid] + numCells[grid] * Nq;
216:       ipf_offset[grid + 1]  = ipf_offset[grid] + Nq * nfloc * numCells[grid];
217:     }
218:     IPf_sz_glb = ipf_offset[num_grids];
219:     IPf_sz_tot = IPf_sz_glb * ctx->batch_sz;
220:     // prep COO
221:     PetscCall(PetscMalloc1(ctx->SData_d.coo_size, &coo_vals)); // allocate every time?
222:     if (shift == 0.0) {                                        /* compute dynamic data f and df and init data for Jacobian */
223: #if PetscDefined(HAVE_THREADSAFETY)
224:       double starttime, endtime;
225:       starttime = MPI_Wtime();
226: #endif
227:       PetscCall(PetscLogEventBegin(ctx->events[8], 0, 0, 0, 0));
228:       PetscCall(PetscMalloc4(IPf_sz_tot, &ff, IPf_sz_tot, &dudx, IPf_sz_tot, &dudy, (dim == 3 ? IPf_sz_tot : 0), &dudz));
229:       // F df/dx
230:       for (PetscInt tid = 0; tid < ctx->batch_sz * elem_offset[num_grids]; tid++) {                        // for each element
231:         const PetscInt b_Nelem = elem_offset[num_grids], b_elem_idx = tid % b_Nelem, b_id = tid / b_Nelem; // b_id == OMP thd_id in batch
232:         // find my grid:
233:         PetscInt grid = 0;
234:         while (b_elem_idx >= elem_offset[grid + 1]) grid++; // yuck search for grid
235:         {
236:           const PetscInt loc_nip = numCells[grid] * Nq, loc_Nf = ctx->species_offset[grid + 1] - ctx->species_offset[grid], loc_elem = b_elem_idx - elem_offset[grid];
237:           const PetscInt moffset = LAND_MOFFSET(b_id, grid, ctx->batch_sz, ctx->num_grids, ctx->mat_offset); //b_id*b_N + ctx->mat_offset[grid];
238:           PetscScalar   *coef, coef_buff[LANDAU_MAX_SPECIES * LANDAU_MAX_NQND];
239:           PetscReal     *invJe = &invJ_a[(ip_offset[grid] + loc_elem * Nq) * dim * dim]; // ingJ is static data on batch 0
240:           PetscInt       b, f, q;
241:           if (cellClosure) {
242:             coef = &cellClosure[b_id * IPf_sz_glb + ipf_offset[grid] + loc_elem * Nb * loc_Nf]; // this is const
243:           } else {
244:             coef = coef_buff;
245:             for (f = 0; f < loc_Nf; ++f) {
246:               LandauIdx *const Idxs = &maps[grid].gIdx[loc_elem][f][0];
247:               for (b = 0; b < Nb; ++b) {
248:                 PetscInt idx = Idxs[b];
249:                 if (idx >= 0) {
250:                   coef[f * Nb + b] = xdata[idx + moffset];
251:                 } else {
252:                   idx              = -idx - 1;
253:                   coef[f * Nb + b] = 0;
254:                   for (q = 0; q < maps[grid].num_face; q++) {
255:                     PetscInt    id    = maps[grid].c_maps[idx][q].gid;
256:                     PetscScalar scale = maps[grid].c_maps[idx][q].scale;
257:                     coef[f * Nb + b] += scale * xdata[id + moffset];
258:                   }
259:                 }
260:               }
261:             }
262:           }
263:           /* get f and df */
264:           for (PetscInt qi = 0; qi < Nq; qi++) {
265:             const PetscReal *invJ = &invJe[qi * dim * dim];
266:             const PetscReal *Bq   = &BB[qi * Nb];
267:             const PetscReal *Dq   = &DD[qi * Nb * dim];
268:             PetscReal        u_x[LANDAU_DIM];
269:             /* get f & df */
270:             for (f = 0; f < loc_Nf; ++f) {
271:               const PetscInt idx = b_id * IPf_sz_glb + ipf_offset[grid] + f * loc_nip + loc_elem * Nq + qi;
272:               PetscInt       e;
273:               PetscReal      refSpaceDer[LANDAU_DIM];
274:               ff[idx] = 0.0;
275:               for (PetscInt d = 0; d < LANDAU_DIM; ++d) refSpaceDer[d] = 0.0;
276:               for (PetscInt b = 0; b < Nb; ++b) {
277:                 const PetscInt cidx = b;
278:                 ff[idx] += Bq[cidx] * PetscRealPart(coef[f * Nb + cidx]);
279:                 for (PetscInt d = 0; d < dim; ++d) refSpaceDer[d] += Dq[cidx * dim + d] * PetscRealPart(coef[f * Nb + cidx]);
280:               }
281:               for (PetscInt d = 0; d < LANDAU_DIM; ++d) {
282:                 for (e = 0, u_x[d] = 0.0; e < LANDAU_DIM; ++e) u_x[d] += invJ[e * dim + d] * refSpaceDer[e];
283:               }
284:               dudx[idx] = u_x[0];
285:               dudy[idx] = u_x[1];
286: #if LANDAU_DIM == 3
287:               dudz[idx] = u_x[2];
288: #endif
289:             }
290:           } // q
291:         } // grid
292:       } // grid*batch
293:       PetscCall(PetscLogEventEnd(ctx->events[8], 0, 0, 0, 0));
294: #if PetscDefined(HAVE_THREADSAFETY)
295:       endtime = MPI_Wtime();
296:       if (ctx->stage) ctx->times[LANDAU_F_DF] += (endtime - starttime);
297: #endif
298:     } // Jacobian setup
299:     // assemble Jacobian (or mass)
300:     for (PetscInt tid = 0; tid < ctx->batch_sz * elem_offset[num_grids]; tid++) { // for each element
301:       const PetscInt b_Nelem      = elem_offset[num_grids];
302:       const PetscInt glb_elem_idx = tid % b_Nelem, b_id = tid / b_Nelem;
303:       PetscInt       grid = 0;
304: #if PetscDefined(HAVE_THREADSAFETY)
305:       double starttime, endtime;
306:       starttime = MPI_Wtime();
307: #endif
308:       while (glb_elem_idx >= elem_offset[grid + 1]) grid++;
309:       {
310:         const PetscInt   loc_Nf = ctx->species_offset[grid + 1] - ctx->species_offset[grid], loc_elem = glb_elem_idx - elem_offset[grid];
311:         const PetscInt   moffset = LAND_MOFFSET(b_id, grid, ctx->batch_sz, ctx->num_grids, ctx->mat_offset), totDim = loc_Nf * Nq, elemMatSize = totDim * totDim;
312:         PetscScalar     *elemMat;
313:         const PetscReal *invJe = &invJ_a[(ip_offset[grid] + loc_elem * Nq) * dim * dim];
314:         PetscCall(PetscMalloc1(elemMatSize, &elemMat));
315:         PetscCall(PetscMemzero(elemMat, elemMatSize * sizeof(*elemMat)));
316:         if (shift == 0.0) { // Jacobian
317:           PetscCall(PetscLogEventBegin(ctx->events[4], 0, 0, 0, 0));
318:         } else { // mass
319:           PetscCall(PetscLogEventBegin(ctx->events[16], 0, 0, 0, 0));
320:         }
321:         for (PetscInt qj = 0; qj < Nq; ++qj) {
322:           const PetscInt jpidx_glb = ip_offset[grid] + qj + loc_elem * Nq;
323:           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
324:           PetscInt       d, d2, dp, d3, IPf_idx;
325:           if (shift == 0.0) { // Jacobian
326:             const PetscReal *const invJj = &invJe[qj * dim * dim];
327:             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];
328:             const PetscReal        vj[3] = {xx[jpidx_glb], yy[jpidx_glb], zz ? zz[jpidx_glb] : 0}, wj = ww[jpidx_glb];
329:             // create g2 & g3
330:             for (d = 0; d < LANDAU_DIM; d++) { // clear accumulation data D & K
331:               gg2_temp[d] = 0;
332:               for (d2 = 0; d2 < LANDAU_DIM; d2++) gg3_temp[d][d2] = 0;
333:             }
334:             /* inner beta reduction */
335:             IPf_idx = 0;
336:             for (PetscInt grid_r = 0, f_off = 0, ipidx = 0; grid_r < ctx->num_grids; grid_r++, f_off = ctx->species_offset[grid_r]) { // IPf_idx += nip_loc_r*Nfloc_r
337:               PetscInt nip_loc_r = numCells[grid_r] * Nq, Nfloc_r = Nf[grid_r];
338:               for (PetscInt ei_r = 0; ei_r < numCells[grid_r]; ++ei_r) {
339:                 for (PetscInt qi = 0; qi < Nq; qi++, ipidx++) {
340:                   const PetscReal wi = ww[ipidx], x = xx[ipidx], y = yy[ipidx];
341:                   PetscReal       temp1[3] = {0, 0, 0}, temp2 = 0;
342: #if LANDAU_DIM == 2
343:                   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.;
344:                   LandauTensor2D(vj, x, y, Ud, Uk, mask);
345: #else
346:                   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.;
347:                   if (ctx->use_relativistic_corrections) {
348:                     LandauTensor3DRelativistic(vj, x, y, z, U, mask, C_0(ctx->v_0));
349:                   } else {
350:                     LandauTensor3D(vj, x, y, z, U, mask);
351:                   }
352: #endif
353:                   for (PetscInt f = 0; f < Nfloc_r; ++f) {
354:                     const PetscInt idx = b_id * IPf_sz_glb + ipf_offset[grid_r] + f * nip_loc_r + ei_r * Nq + qi;

356:                     temp1[0] += dudx[idx] * nu_beta[f + f_off] * invMass[f + f_off] * (*lambdas)[grid][grid_r];
357:                     temp1[1] += dudy[idx] * nu_beta[f + f_off] * invMass[f + f_off] * (*lambdas)[grid][grid_r];
358: #if LANDAU_DIM == 3
359:                     temp1[2] += dudz[idx] * nu_beta[f + f_off] * invMass[f + f_off] * (*lambdas)[grid][grid_r];
360: #endif
361:                     temp2 += ff[idx] * nu_beta[f + f_off] * (*lambdas)[grid][grid_r];
362:                   }
363:                   temp1[0] *= wi;
364:                   temp1[1] *= wi;
365: #if LANDAU_DIM == 3
366:                   temp1[2] *= wi;
367: #endif
368:                   temp2 *= wi;
369: #if LANDAU_DIM == 2
370:                   for (d2 = 0; d2 < 2; d2++) {
371:                     for (d3 = 0; d3 < 2; ++d3) {
372:                       /* K = U * grad(f): g2=e: i,A */
373:                       gg2_temp[d2] += Uk[d2][d3] * temp1[d3];
374:                       /* D = -U * (I \kron (fx)): g3=f: i,j,A */
375:                       gg3_temp[d2][d3] += Ud[d2][d3] * temp2;
376:                     }
377:                   }
378: #else
379:                   for (d2 = 0; d2 < 3; ++d2) {
380:                     for (d3 = 0; d3 < 3; ++d3) {
381:                       /* K = U * grad(f): g2 = e: i,A */
382:                       gg2_temp[d2] += U[d2][d3] * temp1[d3];
383:                       /* D = -U * (I \kron (fx)): g3 = f: i,j,A */
384:                       gg3_temp[d2][d3] += U[d2][d3] * temp2;
385:                     }
386:                   }
387: #endif
388:                 } // qi
389:               } // ei_r
390:               IPf_idx += nip_loc_r * Nfloc_r;
391:             } /* grid_r - IPs */
392:             PetscCheck(IPf_idx == IPf_sz_glb, PETSC_COMM_SELF, PETSC_ERR_PLIB, "IPf_idx != IPf_sz %" PetscInt_FMT " %" PetscInt_FMT, IPf_idx, IPf_sz_glb);
393:             // add alpha and put in gg2/3
394:             for (PetscInt fieldA = 0, f_off = ctx->species_offset[grid]; fieldA < loc_Nf; ++fieldA) {
395:               for (d2 = 0; d2 < LANDAU_DIM; d2++) {
396:                 gg2[fieldA][d2] = gg2_temp[d2] * nu_alpha[fieldA + f_off];
397:                 for (d3 = 0; d3 < LANDAU_DIM; d3++) gg3[fieldA][d2][d3] = -gg3_temp[d2][d3] * nu_alpha[fieldA + f_off] * invMass[fieldA + f_off];
398:               }
399:             }
400:             /* add electric field term once per IP */
401:             for (PetscInt fieldA = 0, f_off = ctx->species_offset[grid]; fieldA < loc_Nf; ++fieldA) gg2[fieldA][LANDAU_DIM - 1] += Eq_m[fieldA + f_off];
402:             /* Jacobian transform - g2, g3 */
403:             for (PetscInt fieldA = 0; fieldA < loc_Nf; ++fieldA) {
404:               for (d = 0; d < dim; ++d) {
405:                 g2[fieldA][d] = 0.0;
406:                 for (d2 = 0; d2 < dim; ++d2) {
407:                   g2[fieldA][d] += invJj[d * dim + d2] * gg2[fieldA][d2];
408:                   g3[fieldA][d][d2] = 0.0;
409:                   for (d3 = 0; d3 < dim; ++d3) {
410:                     for (dp = 0; dp < dim; ++dp) g3[fieldA][d][d2] += invJj[d * dim + d3] * gg3[fieldA][d3][dp] * invJj[d2 * dim + dp];
411:                   }
412:                   g3[fieldA][d][d2] *= wj;
413:                 }
414:                 g2[fieldA][d] *= wj;
415:               }
416:             }
417:           } else { // mass
418:             PetscReal wj = ww[jpidx_glb];
419:             /* Jacobian transform - g0 */
420:             for (PetscInt fieldA = 0; fieldA < loc_Nf; ++fieldA) {
421:               if (dim == 2) {
422:                 g0[fieldA] = wj * shift * 2. * PETSC_PI; // move this to below and remove g0
423:               } else {
424:                 g0[fieldA] = wj * shift; // move this to below and remove g0
425:               }
426:             }
427:           }
428:           /* FE matrix construction */
429:           {
430:             PetscInt         fieldA, d, f, d2, g;
431:             const PetscReal *BJq = &BB[qj * Nb], *DIq = &DD[qj * Nb * dim];
432:             /* assemble - on the diagonal (I,I) */
433:             for (fieldA = 0; fieldA < loc_Nf; fieldA++) {
434:               for (f = 0; f < Nb; f++) {
435:                 const PetscInt i = fieldA * Nb + f; /* Element matrix row */
436:                 for (g = 0; g < Nb; ++g) {
437:                   const PetscInt j    = fieldA * Nb + g; /* Element matrix column */
438:                   const PetscInt fOff = i * totDim + j;
439:                   if (shift == 0.0) {
440:                     for (d = 0; d < dim; ++d) {
441:                       elemMat[fOff] += DIq[f * dim + d] * g2[fieldA][d] * BJq[g];
442:                       for (d2 = 0; d2 < dim; ++d2) elemMat[fOff] += DIq[f * dim + d] * g3[fieldA][d][d2] * DIq[g * dim + d2];
443:                     }
444:                   } else { // mass
445:                     elemMat[fOff] += BJq[f] * g0[fieldA] * BJq[g];
446:                   }
447:                 }
448:               }
449:             }
450:           }
451:         } /* qj loop */
452:         if (shift == 0.0) { // Jacobian
453:           PetscCall(PetscLogEventEnd(ctx->events[4], 0, 0, 0, 0));
454:         } else {
455:           PetscCall(PetscLogEventEnd(ctx->events[16], 0, 0, 0, 0));
456:         }
457: #if PetscDefined(HAVE_THREADSAFETY)
458:         endtime = MPI_Wtime();
459:         if (ctx->stage) ctx->times[LANDAU_KERNEL] += (endtime - starttime);
460: #endif
461:         /* assemble matrix */
462:         if (!container) {
463:           PetscInt cStart;
464:           PetscCall(PetscLogEventBegin(ctx->events[6], 0, 0, 0, 0));
465:           PetscCall(DMPlexGetHeightStratum(ctx->plex[grid], 0, &cStart, NULL));
466:           PetscCall(DMPlexMatSetClosure(ctx->plex[grid], section[grid], globsection[grid], subJ[LAND_PACK_IDX(b_id, grid)], loc_elem + cStart, elemMat, ADD_VALUES));
467:           PetscCall(PetscLogEventEnd(ctx->events[6], 0, 0, 0, 0));
468:         } else { // GPU like assembly for debugging
469:           PetscInt    fieldA, q, f, g, d, nr, nc, rows0[LANDAU_MAX_Q_FACE] = {0}, cols0[LANDAU_MAX_Q_FACE] = {0}, rows[LANDAU_MAX_Q_FACE], cols[LANDAU_MAX_Q_FACE];
470:           PetscScalar vals[LANDAU_MAX_Q_FACE * LANDAU_MAX_Q_FACE] = {0}, row_scale[LANDAU_MAX_Q_FACE] = {0}, col_scale[LANDAU_MAX_Q_FACE] = {0};
471:           LandauIdx *coo_elem_offsets = (LandauIdx *)ctx->SData_d.coo_elem_offsets, *coo_elem_fullNb = (LandauIdx *)ctx->SData_d.coo_elem_fullNb, (*coo_elem_point_offsets)[LANDAU_MAX_NQND + 1] = (LandauIdx(*)[LANDAU_MAX_NQND + 1]) ctx->SData_d.coo_elem_point_offsets;
472:           /* assemble - from the diagonal (I,I) in this format for DMPlexMatSetClosure */
473:           for (fieldA = 0; fieldA < loc_Nf; fieldA++) {
474:             LandauIdx *const Idxs = &maps[grid].gIdx[loc_elem][fieldA][0];
475:             for (f = 0; f < Nb; f++) {
476:               PetscInt idx = Idxs[f];
477:               if (idx >= 0) {
478:                 nr           = 1;
479:                 rows0[0]     = idx;
480:                 row_scale[0] = 1.;
481:               } else {
482:                 idx = -idx - 1;
483:                 for (q = 0, nr = 0; q < maps[grid].num_face; q++, nr++) {
484:                   if (maps[grid].c_maps[idx][q].gid < 0) break;
485:                   rows0[q]     = maps[grid].c_maps[idx][q].gid;
486:                   row_scale[q] = maps[grid].c_maps[idx][q].scale;
487:                 }
488:               }
489:               for (g = 0; g < Nb; ++g) {
490:                 idx = Idxs[g];
491:                 if (idx >= 0) {
492:                   nc           = 1;
493:                   cols0[0]     = idx;
494:                   col_scale[0] = 1.;
495:                 } else {
496:                   idx = -idx - 1;
497:                   nc  = maps[grid].num_face;
498:                   for (q = 0, nc = 0; q < maps[grid].num_face; q++, nc++) {
499:                     if (maps[grid].c_maps[idx][q].gid < 0) break;
500:                     cols0[q]     = maps[grid].c_maps[idx][q].gid;
501:                     col_scale[q] = maps[grid].c_maps[idx][q].scale;
502:                   }
503:                 }
504:                 const PetscInt    i   = fieldA * Nb + f; /* Element matrix row */
505:                 const PetscInt    j   = fieldA * Nb + g; /* Element matrix column */
506:                 const PetscScalar Aij = elemMat[i * totDim + j];
507:                 if (coo_vals) { // mirror (i,j) in CreateStaticGPUData
508:                   const PetscInt fullNb = coo_elem_fullNb[glb_elem_idx], fullNb2 = fullNb * fullNb;
509:                   const PetscInt idx0 = b_id * coo_elem_offsets[elem_offset[num_grids]] + coo_elem_offsets[glb_elem_idx] + fieldA * fullNb2 + fullNb * coo_elem_point_offsets[glb_elem_idx][f] + nr * coo_elem_point_offsets[glb_elem_idx][g];
510:                   for (PetscInt q = 0, idx2 = idx0; q < nr; q++) {
511:                     for (PetscInt d = 0; d < nc; d++, idx2++) coo_vals[idx2] = row_scale[q] * col_scale[d] * Aij;
512:                   }
513:                 } else {
514:                   for (q = 0; q < nr; q++) rows[q] = rows0[q] + moffset;
515:                   for (d = 0; d < nc; d++) cols[d] = cols0[d] + moffset;
516:                   for (q = 0; q < nr; q++) {
517:                     for (d = 0; d < nc; d++) vals[q * nc + d] = row_scale[q] * col_scale[d] * Aij;
518:                   }
519:                   PetscCall(MatSetValues(JacP, nr, rows, nc, cols, vals, ADD_VALUES));
520:                 }
521:               }
522:             }
523:           }
524:         }
525:         if (loc_elem == -1) {
526:           PetscCall(PetscPrintf(ctx->comm, "CPU Element matrix\n"));
527:           for (PetscInt d = 0; d < totDim; ++d) {
528:             for (PetscInt f = 0; f < totDim; ++f) PetscCall(PetscPrintf(ctx->comm, " %12.5e", (double)PetscRealPart(elemMat[d * totDim + f])));
529:             PetscCall(PetscPrintf(ctx->comm, "\n"));
530:           }
531:           exit(12);
532:         }
533:         PetscCall(PetscFree(elemMat));
534:       } /* grid */
535:     } /* outer element & batch loop */
536:     if (shift == 0.0) { // mass
537:       PetscCall(PetscFree4(ff, dudx, dudy, dudz));
538:     }
539:     if (!container) {                                         // 'CPU' assembly move nest matrix to global JacP
540:       for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) { // OpenMP
541:         for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
542:           const PetscInt     moffset = LAND_MOFFSET(b_id, grid, ctx->batch_sz, ctx->num_grids, ctx->mat_offset); // b_id*b_N + ctx->mat_offset[grid];
543:           PetscInt           nloc, nzl, colbuf[1024], row;
544:           const PetscInt    *cols;
545:           const PetscScalar *vals;
546:           Mat                B = subJ[LAND_PACK_IDX(b_id, grid)];
547:           PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
548:           PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
549:           PetscCall(MatGetSize(B, &nloc, NULL));
550:           for (PetscInt i = 0; i < nloc; i++) {
551:             PetscCall(MatGetRow(B, i, &nzl, &cols, &vals));
552:             PetscCheck(nzl <= 1024, PetscObjectComm((PetscObject)B), PETSC_ERR_PLIB, "Row too big: %" PetscInt_FMT, nzl);
553:             for (PetscInt j = 0; j < nzl; j++) colbuf[j] = moffset + cols[j];
554:             row = moffset + i;
555:             PetscCall(MatSetValues(JacP, 1, &row, nzl, colbuf, vals, ADD_VALUES));
556:             PetscCall(MatRestoreRow(B, i, &nzl, &cols, &vals));
557:           }
558:           PetscCall(MatDestroy(&B));
559:         }
560:       }
561:     }
562:     if (coo_vals) {
563:       PetscCall(MatSetValuesCOO(JacP, coo_vals, ADD_VALUES));
564:       PetscCall(PetscFree(coo_vals));
565:     }
566:   } /* CPU version */
567:   PetscCall(MatAssemblyBegin(JacP, MAT_FINAL_ASSEMBLY));
568:   PetscCall(MatAssemblyEnd(JacP, MAT_FINAL_ASSEMBLY));
569:   /* clean up */
570:   PetscCall(PetscFree(cellClosure));
571:   if (xdata) PetscCall(VecRestoreArrayReadAndMemType(a_X, &xdata));
572:   PetscFunctionReturn(PETSC_SUCCESS);
573: }

575: /* create DMComposite of meshes for each species group */
576: static PetscErrorCode LandauDMCreateVMeshes(MPI_Comm comm_self, const PetscInt dim, const char prefix[], LandauCtx *ctx, DM pack)
577: {
578:   PetscFunctionBegin;
579:   /* p4est, quads */
580:   /* Create plex mesh of Landau domain */
581:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
582:     PetscReal par_radius = ctx->radius_par[grid], perp_radius = ctx->radius_perp[grid];
583:     if (!ctx->sphere && !ctx->simplex) { // 2 or 3D (only 3D option)
584:       PetscReal      lo[] = {-perp_radius, -par_radius, -par_radius}, hi[] = {perp_radius, par_radius, par_radius};
585:       DMBoundaryType periodicity[3] = {DM_BOUNDARY_NONE, dim == 2 ? DM_BOUNDARY_NONE : DM_BOUNDARY_NONE, DM_BOUNDARY_NONE};
586:       if (dim == 2) lo[0] = 0;
587:       else {
588:         lo[1] = -perp_radius;
589:         hi[1] = perp_radius; // 3D y is a perp
590:       }
591:       PetscCall(DMPlexCreateBoxMesh(comm_self, dim, PETSC_FALSE, ctx->cells0, lo, hi, periodicity, PETSC_TRUE, 0, PETSC_TRUE, &ctx->plex[grid])); // TODO: make composite and create dm[grid] here
592:       PetscCall(DMLocalizeCoordinates(ctx->plex[grid]));                                                                                          /* needed for periodic */
593:       if (dim == 3) PetscCall(PetscObjectSetName((PetscObject)ctx->plex[grid], "cube"));
594:       else PetscCall(PetscObjectSetName((PetscObject)ctx->plex[grid], "half-plane"));
595:     } else if (dim == 2) {
596:       size_t len;
597:       PetscCall(PetscStrlen(ctx->filename, &len));
598:       if (len) {
599:         Vec          coords;
600:         PetscScalar *x;
601:         PetscInt     N;
602:         char         str[] = "-dm_landau_view_file_0";
603:         str[21] += grid;
604:         PetscCall(DMPlexCreateFromFile(comm_self, ctx->filename, "plexland.c", PETSC_TRUE, &ctx->plex[grid]));
605:         PetscCall(DMPlexOrient(ctx->plex[grid]));
606:         PetscCall(DMGetCoordinatesLocal(ctx->plex[grid], &coords));
607:         PetscCall(VecGetSize(coords, &N));
608:         PetscCall(VecGetArray(coords, &x));
609:         /* scale by domain size */
610:         for (PetscInt i = 0; i < N; i += 2) {
611:           x[i + 0] *= ctx->radius_perp[grid];
612:           x[i + 1] *= ctx->radius_par[grid];
613:         }
614:         PetscCall(VecRestoreArray(coords, &x));
615:         PetscCall(PetscObjectSetName((PetscObject)ctx->plex[grid], ctx->filename));
616:         PetscCall(PetscInfo(ctx->plex[grid], "%" PetscInt_FMT ") Read %s mesh file (%s)\n", grid, ctx->filename, str));
617:         PetscCall(DMViewFromOptions(ctx->plex[grid], NULL, str));
618:       } else { // simplex forces a sphere
619:         PetscInt       numCells = ctx->simplex ? 12 : 6, cell_size = ctx->simplex ? 3 : 4, j;
620:         const PetscInt numVerts    = 11;
621:         PetscInt       cellsT[][4] = {
622:           {0,  1, 6, 5 },
623:           {1,  2, 7, 6 },
624:           {2,  3, 8, 7 },
625:           {3,  4, 9, 8 },
626:           {5,  6, 7, 10},
627:           {10, 7, 8, 9 }
628:         };
629:         PetscInt cellsS[][3] = {
630:           {0,  1, 6 },
631:           {1,  2, 6 },
632:           {6,  2, 7 },
633:           {7,  2, 8 },
634:           {8,  2, 3 },
635:           {8,  3, 4 },
636:           {0,  6, 5 },
637:           {5,  6, 7 },
638:           {5,  7, 10},
639:           {10, 7, 9 },
640:           {9,  7, 8 },
641:           {9,  8, 4 }
642:         };
643:         const PetscInt *pcell = (const PetscInt *)(ctx->simplex ? &cellsS[0][0] : &cellsT[0][0]);
644:         PetscReal       coords[11][2], *flatCoords = &coords[0][0];
645:         PetscReal       rad = ctx->radius[grid];
646:         for (j = 0; j < 5; j++) { // outside edge
647:           PetscReal z, r, theta = -PETSC_PI / 2 + (j % 5) * PETSC_PI / 4;
648:           r            = rad * PetscCosReal(theta);
649:           coords[j][0] = r;
650:           z            = rad * PetscSinReal(theta);
651:           coords[j][1] = z;
652:         }
653:         coords[j][0]   = 0;
654:         coords[j++][1] = -rad * ctx->sphere_inner_radius_90degree[grid];
655:         coords[j][0]   = rad * ctx->sphere_inner_radius_45degree[grid] * 0.707106781186548;
656:         coords[j++][1] = -rad * ctx->sphere_inner_radius_45degree[grid] * 0.707106781186548;
657:         coords[j][0]   = rad * ctx->sphere_inner_radius_90degree[grid];
658:         coords[j++][1] = 0;
659:         coords[j][0]   = rad * ctx->sphere_inner_radius_45degree[grid] * 0.707106781186548;
660:         coords[j++][1] = rad * ctx->sphere_inner_radius_45degree[grid] * 0.707106781186548;
661:         coords[j][0]   = 0;
662:         coords[j++][1] = rad * ctx->sphere_inner_radius_90degree[grid];
663:         coords[j][0]   = 0;
664:         coords[j++][1] = 0;
665:         PetscCall(DMPlexCreateFromCellListPetsc(comm_self, 2, numCells, numVerts, cell_size, ctx->interpolate, pcell, 2, flatCoords, &ctx->plex[grid]));
666:         PetscCall(PetscObjectSetName((PetscObject)ctx->plex[grid], "semi-circle"));
667:         PetscCall(PetscInfo(ctx->plex[grid], "\t%" PetscInt_FMT ") Make circle %s mesh\n", grid, ctx->simplex ? "simplex" : "tensor"));
668:       }
669:     } else {
670:       PetscCheck(dim == 3 && ctx->sphere && !ctx->simplex, ctx->comm, PETSC_ERR_ARG_WRONG, "not: dim == 3 && ctx->sphere && !ctx->simplex");
671:       PetscReal      rad = ctx->radius[grid], inner_rad = rad * ctx->sphere_inner_radius_90degree[grid], outer_rad = rad;
672:       const PetscInt numCells = 7, cell_size = 8, numVerts = 16;
673:       const PetscInt cells[][8] = {
674:         {0, 3, 2, 1, 4,  5,  6,  7 },
675:         {0, 4, 5, 1, 8,  9,  13, 12},
676:         {1, 5, 6, 2, 9,  10, 14, 13},
677:         {2, 6, 7, 3, 10, 11, 15, 14},
678:         {0, 3, 7, 4, 8,  12, 15, 11},
679:         {0, 1, 2, 3, 8,  11, 10, 9 },
680:         {4, 7, 6, 5, 12, 13, 14, 15}
681:       };
682:       PetscReal coords[16 /* numVerts */][3];
683:       for (PetscInt j = 0; j < 4; j++) { // inner edge, low
684:         coords[j][0] = inner_rad * (j == 0 || j == 3 ? 1 : -1);
685:         coords[j][1] = inner_rad * (j / 2 < 1 ? 1 : -1);
686:         coords[j][2] = inner_rad * -1;
687:       }
688:       for (PetscInt j = 0, jj = 4; j < 4; j++, jj++) { // inner edge, hi
689:         coords[jj][0] = inner_rad * (j == 0 || j == 3 ? 1 : -1);
690:         coords[jj][1] = inner_rad * (j / 2 < 1 ? 1 : -1);
691:         coords[jj][2] = inner_rad * 1;
692:       }
693:       for (PetscInt j = 0, jj = 8; j < 4; j++, jj++) { // outer edge, low
694:         coords[jj][0] = outer_rad * (j == 0 || j == 3 ? 1 : -1);
695:         coords[jj][1] = outer_rad * (j / 2 < 1 ? 1 : -1);
696:         coords[jj][2] = outer_rad * -1;
697:       }
698:       for (PetscInt j = 0, jj = 12; j < 4; j++, jj++) { // outer edge, hi
699:         coords[jj][0] = outer_rad * (j == 0 || j == 3 ? 1 : -1);
700:         coords[jj][1] = outer_rad * (j / 2 < 1 ? 1 : -1);
701:         coords[jj][2] = outer_rad * 1;
702:       }
703:       PetscCall(DMPlexCreateFromCellListPetsc(comm_self, 3, numCells, numVerts, cell_size, ctx->interpolate, (const PetscInt *)cells, 3, (const PetscReal *)coords, &ctx->plex[grid]));
704:       PetscCall(PetscObjectSetName((PetscObject)ctx->plex[grid], "cubed sphere"));
705:       PetscCall(PetscInfo(ctx->plex[grid], "\t%" PetscInt_FMT ") Make cubed sphere %s mesh\n", grid, ctx->simplex ? "simplex" : "tensor"));
706:     }
707:     PetscCall(DMSetOptionsPrefix(ctx->plex[grid], prefix));
708:     PetscCall(DMSetFromOptions(ctx->plex[grid]));
709:   } // grid loop
710:   PetscCall(DMSetOptionsPrefix(pack, prefix));
711:   { /* convert to p4est (or whatever), wait for discretization to create pack */
712:     char      convType[256];
713:     PetscBool flg;

715:     PetscOptionsBegin(ctx->comm, prefix, "Mesh conversion options", "DMPLEX");
716:     PetscCall(PetscOptionsFList("-dm_landau_type", "Convert DMPlex to another format (p4est)", "plexland.c", DMList, DMPLEX, convType, 256, &flg));
717:     PetscOptionsEnd();
718:     if (flg) {
719:       ctx->use_p4est = PETSC_TRUE; /* flag for Forest */
720:       for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
721:         DM        dmforest;
722:         PetscBool isForest;

724:         PetscCall(DMConvert(ctx->plex[grid], convType, &dmforest));
725:         PetscCheck(dmforest, ctx->comm, PETSC_ERR_PLIB, "Convert failed?");
726:         PetscCall(DMSetOptionsPrefix(dmforest, prefix));
727:         PetscCall(DMIsForest(dmforest, &isForest));
728:         PetscCheck(isForest, ctx->comm, PETSC_ERR_PLIB, "Converted to non Forest?");
729:         PetscCall(DMDestroy(&ctx->plex[grid]));
730:         ctx->plex[grid] = dmforest; // Forest for adaptivity
731:       }
732:     } else ctx->use_p4est = PETSC_FALSE; /* flag for Forest */
733:   }
734:   PetscCall(DMSetDimension(pack, dim));
735:   PetscCall(PetscObjectSetName((PetscObject)pack, "Mesh"));
736:   PetscCall(DMSetApplicationContext(pack, ctx));
737:   PetscFunctionReturn(PETSC_SUCCESS);
738: }

740: static PetscErrorCode SetupDS(DM pack, PetscInt dim, PetscInt grid, const char prefix[], LandauCtx *ctx)
741: {
742:   PetscInt     ii, i0;
743:   char         buf[256];
744:   PetscSection section;

746:   PetscFunctionBegin;
747:   for (ii = ctx->species_offset[grid], i0 = 0; ii < ctx->species_offset[grid + 1]; ii++, i0++) {
748:     if (ii == 0) PetscCall(PetscSNPrintf(buf, sizeof(buf), "e"));
749:     else PetscCall(PetscSNPrintf(buf, sizeof(buf), "i%" PetscInt_FMT, ii));
750:     /* Setup Discretization - FEM */
751:     PetscCall(PetscFECreateDefault(PETSC_COMM_SELF, dim, 1, ctx->simplex, prefix, PETSC_DECIDE, &ctx->fe[ii]));
752:     PetscCall(PetscObjectSetName((PetscObject)ctx->fe[ii], buf));
753:     PetscCall(DMSetField(ctx->plex[grid], i0, NULL, (PetscObject)ctx->fe[ii]));
754:   }
755:   PetscCall(DMCreateDS(ctx->plex[grid]));
756:   PetscCall(DMGetLocalSection(ctx->plex[grid], &section));
757:   for (PetscInt ii = ctx->species_offset[grid], i0 = 0; ii < ctx->species_offset[grid + 1]; ii++, i0++) {
758:     if (ii == 0) PetscCall(PetscSNPrintf(buf, sizeof(buf), "se"));
759:     else PetscCall(PetscSNPrintf(buf, sizeof(buf), "si%" PetscInt_FMT, ii));
760:     PetscCall(PetscSectionSetComponentName(section, i0, 0, buf));
761:   }
762:   PetscFunctionReturn(PETSC_SUCCESS);
763: }

765: /* Define a Maxwellian function for testing out the operator. */

767: /* Using cartesian velocity space coordinates, the particle */
768: /* density, [1/m^3], is defined according to */

770: /* $$ n=\int_{R^3} dv^3 \left(\frac{m}{2\pi T}\right)^{3/2}\exp [- mv^2/(2T)] $$ */

772: /* Using some constant, c, we normalize the velocity vector into a */
773: /* dimensionless variable according to v=c*x. Thus the density, $n$, becomes */

775: /* $$ n=\int_{R^3} dx^3 \left(\frac{mc^2}{2\pi T}\right)^{3/2}\exp [- mc^2/(2T)*x^2] $$ */

777: /* Defining $\theta=2T/mc^2$, we thus find that the probability density */
778: /* for finding the particle within the interval in a box dx^3 around x is */

780: /* f(x;\theta)=\left(\frac{1}{\pi\theta}\right)^{3/2} \exp [ -x^2/\theta ] */

782: typedef struct {
783:   PetscReal v_0;
784:   PetscReal kT_m;
785:   PetscReal n;
786:   PetscReal shift;
787: } MaxwellianCtx;

789: static PetscErrorCode maxwellian(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf_dummy, PetscScalar *u, void *actx)
790: {
791:   MaxwellianCtx *mctx = (MaxwellianCtx *)actx;
792:   PetscReal      v2 = 0, theta = 2 * mctx->kT_m / (mctx->v_0 * mctx->v_0), shift; /* theta = 2kT/mc^2 */

794:   PetscFunctionBegin;
795:   /* compute the exponents, v^2 */
796:   for (PetscInt i = 0; i < dim; ++i) v2 += x[i] * x[i];
797:   /* evaluate the Maxwellian */
798:   if (mctx->shift < 0) shift = -mctx->shift;
799:   else {
800:     u[0]  = mctx->n * PetscPowReal(PETSC_PI * theta, -1.5) * (PetscExpReal(-v2 / theta));
801:     shift = mctx->shift;
802:   }
803:   if (shift != 0.) {
804:     v2 = 0;
805:     for (PetscInt i = 0; i < dim - 1; ++i) v2 += x[i] * x[i];
806:     v2 += (x[dim - 1] - shift) * (x[dim - 1] - shift);
807:     /* evaluate the shifted Maxwellian */
808:     u[0] += mctx->n * PetscPowReal(PETSC_PI * theta, -1.5) * (PetscExpReal(-v2 / theta));
809:   }
810:   PetscFunctionReturn(PETSC_SUCCESS);
811: }

813: /*@
814:   DMPlexLandauAddMaxwellians - Add a Maxwellian distribution to a state

816:   Collective

818:   Input Parameters:
819: + dm      - The mesh (local)
820: . time    - Current time
821: . temps   - Temperatures of each species (global)
822: . ns      - Number density of each species (global)
823: . grid    - index into current grid - just used for offset into `temp` and `ns`
824: . b_id    - batch index
825: . n_batch - number of batches
826: - actx    - Landau context

828:   Output Parameter:
829: . X - The state (local to this grid)

831:   Level: beginner

833: .seealso: `DMPlexLandauCreateVelocitySpace()`
834:  @*/
835: PetscErrorCode DMPlexLandauAddMaxwellians(DM dm, Vec X, PetscReal time, PetscReal temps[], PetscReal ns[], PetscInt grid, PetscInt b_id, PetscInt n_batch, void *actx)
836: {
837:   LandauCtx *ctx = (LandauCtx *)actx;
838:   PetscErrorCode (*initu[LANDAU_MAX_SPECIES])(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
839:   PetscInt       dim;
840:   MaxwellianCtx *mctxs[LANDAU_MAX_SPECIES], data[LANDAU_MAX_SPECIES];

842:   PetscFunctionBegin;
843:   PetscCall(DMGetDimension(dm, &dim));
844:   if (!ctx) PetscCall(DMGetApplicationContext(dm, &ctx));
845:   for (PetscInt ii = ctx->species_offset[grid], i0 = 0; ii < ctx->species_offset[grid + 1]; ii++, i0++) {
846:     mctxs[i0]      = &data[i0];
847:     data[i0].v_0   = ctx->v_0;                             // v_0 same for all grids
848:     data[i0].kT_m  = ctx->k * temps[ii] / ctx->masses[ii]; /* kT/m */
849:     data[i0].n     = ns[ii];
850:     initu[i0]      = maxwellian;
851:     data[i0].shift = 0;
852:   }
853:   data[0].shift = ctx->electronShift;
854:   /* need to make ADD_ALL_VALUES work - TODO */
855:   PetscCall(DMProjectFunction(dm, time, initu, (void **)mctxs, INSERT_ALL_VALUES, X));
856:   PetscFunctionReturn(PETSC_SUCCESS);
857: }

859: /* Adds Maxwellians to X for the given grid and batch using temperatures and densities from actx */
860: static PetscErrorCode LandauSetInitialCondition(DM dm, Vec X, PetscInt grid, PetscInt b_id, PetscInt n_batch, void *actx)
861: {
862:   LandauCtx *ctx = (LandauCtx *)actx;

864:   PetscFunctionBegin;
865:   if (!ctx) PetscCall(DMGetApplicationContext(dm, &ctx));
866:   PetscCall(VecZeroEntries(X));
867:   PetscCall(DMPlexLandauAddMaxwellians(dm, X, 0.0, ctx->thermal_temps, ctx->n, grid, b_id, n_batch, ctx));
868:   PetscFunctionReturn(PETSC_SUCCESS);
869: }

871: // adapt a level once. Forest in/out
872: #if PetscDefined(USE_INFO)
873: static const char *s_refine_names[] = {"RE", "Z1", "Origin", "Z2", "Uniform"};
874: #endif
875: static PetscErrorCode adaptToleranceFEM(PetscFE fem, Vec sol, PetscInt type, PetscInt grid, LandauCtx *ctx, DM *newForest)
876: {
877:   DM              forest, plex, adaptedDM = NULL;
878:   PetscDS         prob;
879:   PetscBool       isForest;
880:   PetscQuadrature quad;
881:   PetscInt        Nq, Nb, *Nb2, cStart, cEnd, c, dim, qj, k;
882:   DMLabel         adaptLabel = NULL;

884:   PetscFunctionBegin;
885:   forest = ctx->plex[grid];
886:   PetscCall(DMCreateDS(forest));
887:   PetscCall(DMGetDS(forest, &prob));
888:   PetscCall(DMGetDimension(forest, &dim));
889:   PetscCall(DMIsForest(forest, &isForest));
890:   PetscCheck(isForest, ctx->comm, PETSC_ERR_ARG_WRONG, "! Forest");
891:   PetscCall(DMConvert(forest, DMPLEX, &plex));
892:   PetscCall(DMPlexGetHeightStratum(plex, 0, &cStart, &cEnd));
893:   PetscCall(DMLabelCreate(PETSC_COMM_SELF, "adapt", &adaptLabel));
894:   PetscCall(PetscFEGetQuadrature(fem, &quad));
895:   PetscCall(PetscQuadratureGetData(quad, NULL, NULL, &Nq, NULL, NULL));
896:   PetscCheck(Nq <= LANDAU_MAX_NQND, ctx->comm, PETSC_ERR_ARG_WRONG, "Order too high. Nq = %" PetscInt_FMT " > LANDAU_MAX_NQND (%d)", Nq, LANDAU_MAX_NQND);
897:   PetscCall(PetscFEGetDimension(ctx->fe[0], &Nb));
898:   PetscCall(PetscDSGetDimensions(prob, &Nb2));
899:   PetscCheck(Nb2[0] == Nb, ctx->comm, PETSC_ERR_ARG_WRONG, " Nb = %" PetscInt_FMT " != Nb (%" PetscInt_FMT ")", Nb, Nb2[0]);
900:   PetscCheck(Nb <= LANDAU_MAX_NQND, ctx->comm, PETSC_ERR_ARG_WRONG, "Order too high. Nb = %" PetscInt_FMT " > LANDAU_MAX_NQND (%d)", Nb, LANDAU_MAX_NQND);
901:   PetscCall(PetscInfo(sol, "%" PetscInt_FMT ") Refine phase: %s\n", grid, s_refine_names[type]));
902:   if (type == 4) {
903:     for (c = cStart; c < cEnd; c++) PetscCall(DMLabelSetValue(adaptLabel, c, DM_ADAPT_REFINE));
904:   } else if (type == 2) {
905:     PetscInt  rCellIdx[8], nr = 0, nrmax = (dim == 3) ? 8 : 2;
906:     PetscReal minRad = PETSC_INFINITY, r;
907:     for (c = cStart; c < cEnd; c++) {
908:       PetscReal tt, v0[LANDAU_MAX_NQND * 3], J[LANDAU_MAX_NQND * 9], invJ[LANDAU_MAX_NQND * 9], detJ[LANDAU_MAX_NQND];
909:       PetscCall(DMPlexComputeCellGeometryFEM(plex, c, quad, v0, J, invJ, detJ));
910:       (void)J;
911:       (void)invJ;
912:       for (qj = 0; qj < Nq; ++qj) {
913:         tt = PetscSqr(v0[dim * qj + 0]) + PetscSqr(v0[dim * qj + 1]) + PetscSqr((dim == 3) ? v0[dim * qj + 2] : 0);
914:         r  = PetscSqrtReal(tt);
915:         if (r < minRad - PETSC_SQRT_MACHINE_EPSILON * 10.) {
916:           minRad         = r;
917:           nr             = 0;
918:           rCellIdx[nr++] = c;
919:           PetscCall(PetscInfo(sol, "\t\t%" PetscInt_FMT ") Found first inner r=%e, cell %" PetscInt_FMT ", qp %" PetscInt_FMT "/%" PetscInt_FMT "\n", grid, (double)r, c, qj + 1, Nq));
920:         } else if ((r - minRad) < PETSC_SQRT_MACHINE_EPSILON * 100. && nr < nrmax) {
921:           for (k = 0; k < nr; k++)
922:             if (c == rCellIdx[k]) break;
923:           if (k == nr) {
924:             rCellIdx[nr++] = c;
925:             PetscCall(PetscInfo(sol, "\t\t\t%" PetscInt_FMT ") Found another inner r=%e, cell %" PetscInt_FMT ", qp %" PetscInt_FMT "/%" PetscInt_FMT ", d=%e\n", grid, (double)r, c, qj + 1, Nq, (double)(r - minRad)));
926:           }
927:         }
928:       }
929:     }
930:     for (k = 0; k < nr; k++) PetscCall(DMLabelSetValue(adaptLabel, rCellIdx[k], DM_ADAPT_REFINE));
931:     PetscCall(PetscInfo(sol, "\t\t\t%" PetscInt_FMT ") Refined %" PetscInt_FMT " origin cells %" PetscInt_FMT ",%" PetscInt_FMT " r=%g\n", grid, nr, rCellIdx[0], rCellIdx[1], (double)minRad));
932:   } else if (type == 0 || type == 1 || type == 3) { /* refine along r=0 axis */
933:     PetscScalar *coef = NULL;
934:     Vec          coords;
935:     PetscInt     csize, Nv, d, nz, nrefined = 0;
936:     DM           cdm;
937:     PetscSection cs;
938:     PetscCall(DMGetCoordinatesLocal(forest, &coords));
939:     PetscCall(DMGetCoordinateDM(forest, &cdm));
940:     PetscCall(DMGetLocalSection(cdm, &cs));
941:     for (c = cStart; c < cEnd; c++) {
942:       PetscInt doit = 0, outside = 0;
943:       PetscCall(DMPlexVecGetClosure(cdm, cs, coords, c, &csize, &coef));
944:       Nv = csize / dim;
945:       for (nz = d = 0; d < Nv; d++) {
946:         PetscReal z = PetscRealPart(coef[d * dim + (dim - 1)]), x = PetscSqr(PetscRealPart(coef[d * dim + 0])) + ((dim == 3) ? PetscSqr(PetscRealPart(coef[d * dim + 1])) : 0);
947:         x = PetscSqrtReal(x);
948:         if (type == 0) {
949:           if (ctx->re_radius > PETSC_SQRT_MACHINE_EPSILON && (z < -PETSC_MACHINE_EPSILON * 10. || z > ctx->re_radius + PETSC_MACHINE_EPSILON * 10.)) outside++; /* first pass don't refine bottom */
950:         } else if (type == 1 && (z > ctx->vperp0_radius1 || z < -ctx->vperp0_radius1)) {
951:           outside++; /* don't refine outside electron refine radius */
952:           PetscCall(PetscInfo(sol, "\t%" PetscInt_FMT ") (debug) found %s cells\n", grid, s_refine_names[type]));
953:         } else if (type == 3 && (z > ctx->vperp0_radius2 || z < -ctx->vperp0_radius2)) {
954:           outside++; /* refine r=0 cells on refinement front */
955:           PetscCall(PetscInfo(sol, "\t%" PetscInt_FMT ") (debug) found %s cells\n", grid, s_refine_names[type]));
956:         }
957:         if (x < PETSC_MACHINE_EPSILON * 10. && (type != 0 || ctx->re_radius > PETSC_SQRT_MACHINE_EPSILON)) nz++;
958:       }
959:       PetscCall(DMPlexVecRestoreClosure(cdm, cs, coords, c, &csize, &coef));
960:       if (doit || (outside < Nv && nz)) {
961:         PetscCall(DMLabelSetValue(adaptLabel, c, DM_ADAPT_REFINE));
962:         nrefined++;
963:       }
964:     }
965:     PetscCall(PetscInfo(sol, "\t%" PetscInt_FMT ") Refined %" PetscInt_FMT " cells\n", grid, nrefined));
966:   }
967:   PetscCall(DMDestroy(&plex));
968:   PetscCall(DMAdaptLabel(forest, adaptLabel, &adaptedDM));
969:   PetscCall(DMLabelDestroy(&adaptLabel));
970:   *newForest = adaptedDM;
971:   if (adaptedDM) {
972:     if (isForest) PetscCall(DMForestSetAdaptivityForest(adaptedDM, NULL)); // ????
973:     PetscCall(DMConvert(adaptedDM, DMPLEX, &plex));
974:     PetscCall(DMPlexGetHeightStratum(plex, 0, &cStart, &cEnd));
975:     PetscCall(PetscInfo(sol, "\t\t\t\t%" PetscInt_FMT ") %" PetscInt_FMT " cells, %" PetscInt_FMT " total quadrature points\n", grid, cEnd - cStart, Nq * (cEnd - cStart)));
976:     PetscCall(DMDestroy(&plex));
977:   } else *newForest = NULL;
978:   PetscFunctionReturn(PETSC_SUCCESS);
979: }

981: // forest goes in (ctx->plex[grid]), plex comes out
982: static PetscErrorCode adapt(PetscInt grid, LandauCtx *ctx, Vec *uu)
983: {
984:   PetscFunctionBegin;
985:   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]};
986:   for (type = 0; type < 5; type++) {
987:     for (PetscInt adaptIter = 0; adaptIter < limits[type]; adaptIter++) {
988:       DM newForest = NULL;
989:       PetscCall(adaptToleranceFEM(ctx->fe[0], *uu, type, grid, ctx, &newForest));
990:       if (newForest) {
991:         PetscCall(DMDestroy(&ctx->plex[grid]));
992:         PetscCall(VecDestroy(uu));
993:         PetscCall(DMCreateGlobalVector(newForest, uu));
994:         PetscCall(LandauSetInitialCondition(newForest, *uu, grid, 0, 1, ctx));
995:         ctx->plex[grid] = newForest;
996:       } else {
997:         PetscCall(PetscInfo(*uu, "No refinement\n"));
998:       }
999:     }
1000:   }
1001:   PetscCall(PetscObjectSetName((PetscObject)*uu, "uAMR"));
1002:   PetscFunctionReturn(PETSC_SUCCESS);
1003: }

1005: // make log(Lambdas) from NRL Plasma formulary
1006: static PetscErrorCode makeLambdas(LandauCtx *ctx)
1007: {
1008:   PetscFunctionBegin;
1009:   for (PetscInt gridi = 0; gridi < ctx->num_grids; gridi++) {
1010:     PetscInt  iii   = ctx->species_offset[gridi];
1011:     PetscReal Ti_ev = (ctx->thermal_temps[iii] / 1.1604525e7) * 1000; // convert (back) to eV
1012:     PetscReal ni    = ctx->n[iii] * ctx->n_0;
1013:     for (PetscInt gridj = gridi; gridj < ctx->num_grids; gridj++) {
1014:       PetscInt  jjj = ctx->species_offset[gridj];
1015:       PetscReal Zj  = ctx->charges[jjj] / 1.6022e-19;
1016:       if (gridi == 0) {
1017:         if (gridj == 0) { // lam_ee
1018:           ctx->lambdas[gridi][gridj] = 23.5 - PetscLogReal(PetscSqrtReal(ni) * PetscPowReal(Ti_ev, -1.25)) - PetscSqrtReal(1e-5 + PetscSqr(PetscLogReal(Ti_ev) - 2) / 16);
1019:         } else { // lam_ei == lam_ie
1020:           if (10 * Zj * Zj > Ti_ev) {
1021:             ctx->lambdas[gridi][gridj] = ctx->lambdas[gridj][gridi] = 23 - PetscLogReal(PetscSqrtReal(ni) * Zj * PetscPowReal(Ti_ev, -1.5));
1022:           } else {
1023:             ctx->lambdas[gridi][gridj] = ctx->lambdas[gridj][gridi] = 24 - PetscLogReal(PetscSqrtReal(ni) / Ti_ev);
1024:           }
1025:         }
1026:       } else { // lam_ii'
1027:         PetscReal mui = ctx->masses[iii] / 1.6720e-27, Zi = ctx->charges[iii] / 1.6022e-19;
1028:         PetscReal Tj_ev            = (ctx->thermal_temps[jjj] / 1.1604525e7) * 1000; // convert (back) to eV
1029:         PetscReal muj              = ctx->masses[jjj] / 1.6720e-27;
1030:         PetscReal nj               = ctx->n[jjj] * ctx->n_0;
1031:         ctx->lambdas[gridi][gridj] = ctx->lambdas[gridj][gridi] = 23 - PetscLogReal(Zi * Zj * (mui + muj) / (mui * Tj_ev + muj * Ti_ev) * PetscSqrtReal(ni * Zi * Zi / Ti_ev + nj * Zj * Zj / Tj_ev));
1032:       }
1033:     }
1034:   }
1035:   //PetscReal v0 = PetscSqrtReal(ctx->k * ctx->thermal_temps[iii] / ctx->masses[iii]); /* arbitrary units for non-dimensionalization: plasma formulary def */
1036:   PetscFunctionReturn(PETSC_SUCCESS);
1037: }

1039: static PetscErrorCode ProcessOptions(LandauCtx *ctx, const char prefix[])
1040: {
1041:   PetscBool flg, fileflg;
1042:   PetscInt  ii, nt, nm, nc, num_species_grid[LANDAU_MAX_GRIDS], non_dim_grid;
1043:   PetscReal lnLam = 10;
1044:   DM        dummy;

1046:   PetscFunctionBegin;
1047:   PetscCall(DMCreate(ctx->comm, &dummy));
1048:   /* get options - initialize context */
1049:   ctx->verbose        = 1; // should be 0 for silent compliance
1050:   ctx->batch_sz       = 1;
1051:   ctx->batch_view_idx = 0;
1052:   ctx->interpolate    = PETSC_TRUE;
1053:   ctx->gpu_assembly   = PETSC_TRUE;
1054:   ctx->norm_state     = 0;
1055:   ctx->electronShift  = 0;
1056:   ctx->M              = NULL;
1057:   ctx->J              = NULL;
1058:   /* geometry and grids */
1059:   ctx->sphere     = PETSC_FALSE;
1060:   ctx->map_sphere = PETSC_TRUE;
1061:   ctx->use_p4est  = PETSC_FALSE;
1062:   ctx->simplex    = PETSC_FALSE;
1063:   for (PetscInt grid = 0; grid < LANDAU_MAX_GRIDS; grid++) {
1064:     ctx->radius[grid]             = 5.; /* thermal radius (velocity) */
1065:     ctx->radius_perp[grid]        = 5.; /* thermal radius (velocity) */
1066:     ctx->radius_par[grid]         = 5.; /* thermal radius (velocity) */
1067:     ctx->numAMRRefine[grid]       = 0;
1068:     ctx->postAMRRefine[grid]      = 0;
1069:     ctx->species_offset[grid + 1] = 1; // one species default
1070:     num_species_grid[grid]        = 0;
1071:     ctx->plex[grid]               = NULL; /* cache as expensive to Convert */
1072:   }
1073:   ctx->species_offset[0] = 0;
1074:   ctx->re_radius         = 0.;
1075:   ctx->vperp0_radius1    = 0;
1076:   ctx->vperp0_radius2    = 0;
1077:   ctx->nZRefine1         = 0;
1078:   ctx->nZRefine2         = 0;
1079:   ctx->numRERefine       = 0;
1080:   num_species_grid[0]    = 1; // one species default
1081:   /* species - [0] electrons, [1] one ion species eg, duetarium, [2] heavy impurity ion, ... */
1082:   ctx->charges[0]       = -1;                       /* electron charge (MKS) */
1083:   ctx->masses[0]        = 1 / 1835.469965278441013; /* temporary value in proton mass */
1084:   ctx->n[0]             = 1;
1085:   ctx->v_0              = 1; /* thermal velocity, we could start with a scale != 1 */
1086:   ctx->thermal_temps[0] = 1;
1087:   /* constants, etc. */
1088:   ctx->epsilon0 = 8.8542e-12;     /* permittivity of free space (MKS) F/m */
1089:   ctx->k        = 1.38064852e-23; /* Boltzmann constant (MKS) J/K */
1090:   ctx->n_0      = 1.e20;          /* typical plasma n, but could set it to 1 */
1091:   ctx->Ez       = 0;
1092:   for (PetscInt grid = 0; grid < LANDAU_NUM_TIMERS; grid++) ctx->times[grid] = 0;
1093:   for (PetscInt ii = 0; ii < LANDAU_DIM; ii++) ctx->cells0[ii] = 2;
1094:   if (LANDAU_DIM == 2) ctx->cells0[0] = 1;
1095:   ctx->use_matrix_mass                = PETSC_FALSE;
1096:   ctx->use_relativistic_corrections   = PETSC_FALSE;
1097:   ctx->use_energy_tensor_trick        = PETSC_FALSE; /* Use Eero's trick for energy conservation v --> grad(v^2/2) */
1098:   ctx->SData_d.w                      = NULL;
1099:   ctx->SData_d.x                      = NULL;
1100:   ctx->SData_d.y                      = NULL;
1101:   ctx->SData_d.z                      = NULL;
1102:   ctx->SData_d.invJ                   = NULL;
1103:   ctx->jacobian_field_major_order     = PETSC_FALSE;
1104:   ctx->SData_d.coo_elem_offsets       = NULL;
1105:   ctx->SData_d.coo_elem_point_offsets = NULL;
1106:   ctx->SData_d.coo_elem_fullNb        = NULL;
1107:   ctx->SData_d.coo_size               = 0;
1108:   PetscOptionsBegin(ctx->comm, prefix, "Options for Fokker-Plank-Landau collision operator", "none");
1109: #if PetscDefined(HAVE_KOKKOS)
1110:   ctx->deviceType = LANDAU_KOKKOS;
1111:   PetscCall(PetscStrncpy(ctx->filename, "kokkos", sizeof(ctx->filename)));
1112: #else
1113:   ctx->deviceType = LANDAU_CPU;
1114:   PetscCall(PetscStrncpy(ctx->filename, "cpu", sizeof(ctx->filename)));
1115: #endif
1116:   PetscCall(PetscOptionsString("-dm_landau_device_type", "Use kernels on 'cpu' 'kokkos'", "plexland.c", ctx->filename, ctx->filename, sizeof(ctx->filename), NULL));
1117:   PetscCall(PetscStrcmp("cpu", ctx->filename, &flg));
1118:   if (flg) {
1119:     ctx->deviceType = LANDAU_CPU;
1120:   } else {
1121:     PetscCall(PetscStrcmp("kokkos", ctx->filename, &flg));
1122:     PetscCheck(flg, ctx->comm, PETSC_ERR_ARG_WRONG, "-dm_landau_device_type %s", ctx->filename);
1123:     ctx->deviceType = LANDAU_KOKKOS;
1124:   }
1125:   ctx->filename[0] = '\0';
1126:   PetscCall(PetscOptionsString("-dm_landau_filename", "file to read mesh from", "plexland.c", ctx->filename, ctx->filename, sizeof(ctx->filename), &fileflg));
1127:   PetscCall(PetscOptionsReal("-dm_landau_electron_shift", "Shift in thermal velocity of electrons", "none", ctx->electronShift, &ctx->electronShift, NULL));
1128:   PetscCall(PetscOptionsInt("-dm_landau_verbose", "Level of verbosity output", "plexland.c", ctx->verbose, &ctx->verbose, NULL));
1129:   PetscCall(PetscOptionsInt("-dm_landau_batch_size", "Number of 'vertices' to batch", "ex2.c", ctx->batch_sz, &ctx->batch_sz, NULL));
1130:   PetscCheck(LANDAU_MAX_BATCH_SZ >= ctx->batch_sz, ctx->comm, PETSC_ERR_ARG_WRONG, "LANDAU_MAX_BATCH_SZ %d < ctx->batch_sz %" PetscInt_FMT, LANDAU_MAX_BATCH_SZ, ctx->batch_sz);
1131:   PetscCall(PetscOptionsInt("-dm_landau_batch_view_idx", "Index of batch for diagnostics like plotting", "ex2.c", ctx->batch_view_idx, &ctx->batch_view_idx, NULL));
1132:   PetscCheck(ctx->batch_view_idx < ctx->batch_sz, ctx->comm, PETSC_ERR_ARG_WRONG, "-ctx->batch_view_idx %" PetscInt_FMT " > ctx->batch_sz %" PetscInt_FMT, ctx->batch_view_idx, ctx->batch_sz);
1133:   PetscCall(PetscOptionsReal("-dm_landau_Ez", "Initial parallel electric field in unites of Conner-Hastie critical field", "plexland.c", ctx->Ez, &ctx->Ez, NULL));
1134:   PetscCall(PetscOptionsReal("-dm_landau_n_0", "Normalization constant for number density", "plexland.c", ctx->n_0, &ctx->n_0, NULL));
1135:   PetscCall(PetscOptionsBool("-dm_landau_use_mataxpy_mass", "Use fast but slightly fragile MATAXPY to add mass term", "plexland.c", ctx->use_matrix_mass, &ctx->use_matrix_mass, NULL));
1136:   PetscCall(PetscOptionsBool("-dm_landau_use_relativistic_corrections", "Use relativistic corrections", "plexland.c", ctx->use_relativistic_corrections, &ctx->use_relativistic_corrections, NULL));
1137:   PetscCall(PetscOptionsBool("-dm_landau_simplex", "Use simplex elements", "plexland.c", ctx->simplex, &ctx->simplex, NULL));
1138:   PetscCall(PetscOptionsBool("-dm_landau_sphere", "use sphere/semi-circle domain instead of rectangle", "plexland.c", ctx->sphere, &ctx->sphere, NULL));
1139:   PetscCall(PetscOptionsBool("-dm_landau_map_sphere", "Map to sphere/semi-circle domain instead of rectangle", "plexland.c", ctx->map_sphere, &ctx->map_sphere, NULL));
1140:   if (LANDAU_DIM == 2 && ctx->use_relativistic_corrections) ctx->use_relativistic_corrections = PETSC_FALSE; // should warn
1141:   PetscCall(PetscOptionsBool("-dm_landau_use_energy_tensor_trick", "Use Eero's trick of using grad(v^2/2) instead of v as args to Landau tensor to conserve energy with relativistic corrections and Q1 elements", "plexland.c", ctx->use_energy_tensor_trick,
1142:                              &ctx->use_energy_tensor_trick, NULL));

1144:   /* get num species with temperature, set defaults */
1145:   for (ii = 1; ii < LANDAU_MAX_SPECIES; ii++) {
1146:     ctx->thermal_temps[ii] = 1;
1147:     ctx->charges[ii]       = 1;
1148:     ctx->masses[ii]        = 1;
1149:     ctx->n[ii]             = 1;
1150:   }
1151:   nt = LANDAU_MAX_SPECIES;
1152:   PetscCall(PetscOptionsRealArray("-dm_landau_thermal_temps", "Temperature of each species [e,i_0,i_1,...] in keV (must be set to set number of species)", "plexland.c", ctx->thermal_temps, &nt, &flg));
1153:   PetscCheck(flg, ctx->comm, PETSC_ERR_ARG_WRONG, "-dm_landau_thermal_temps ,t1,t2,.. must be provided to set the number of species");
1154:   PetscCall(PetscInfo(dummy, "num_species set to number of thermal temps provided (%" PetscInt_FMT ")\n", nt));
1155:   ctx->num_species = nt;
1156:   for (ii = 0; ii < ctx->num_species; ii++) ctx->thermal_temps[ii] *= 1.1604525e7; /* convert to Kelvin */
1157:   nm = LANDAU_MAX_SPECIES - 1;
1158:   PetscCall(PetscOptionsRealArray("-dm_landau_ion_masses", "Mass of each species in units of proton mass [i_0=2,i_1=40...]", "plexland.c", &ctx->masses[1], &nm, &flg));
1159:   PetscCheck(!flg || nm == ctx->num_species - 1, ctx->comm, PETSC_ERR_ARG_WRONG, "num ion masses %" PetscInt_FMT " != num species %" PetscInt_FMT, nm, ctx->num_species - 1);
1160:   nm = LANDAU_MAX_SPECIES;
1161:   PetscCall(PetscOptionsRealArray("-dm_landau_n", "Number density of each species = n_s * n_0", "plexland.c", ctx->n, &nm, &flg));
1162:   PetscCheck(!flg || nm == ctx->num_species, ctx->comm, PETSC_ERR_ARG_WRONG, "wrong num n: %" PetscInt_FMT " != num species %" PetscInt_FMT, nm, ctx->num_species);
1163:   for (ii = 0; ii < LANDAU_MAX_SPECIES; ii++) ctx->masses[ii] *= 1.6720e-27; /* scale by proton mass kg */
1164:   ctx->masses[0] = 9.10938356e-31;                                           /* electron mass kg (should be about right already) */
1165:   nc             = LANDAU_MAX_SPECIES - 1;
1166:   PetscCall(PetscOptionsRealArray("-dm_landau_ion_charges", "Charge of each species in units of proton charge [i_0=2,i_1=18,...]", "plexland.c", &ctx->charges[1], &nc, &flg));
1167:   if (flg) PetscCheck(nc == ctx->num_species - 1, ctx->comm, PETSC_ERR_ARG_WRONG, "num charges %" PetscInt_FMT " != num species %" PetscInt_FMT, nc, ctx->num_species - 1);
1168:   for (ii = 0; ii < LANDAU_MAX_SPECIES; ii++) ctx->charges[ii] *= 1.6022e-19; /* electron/proton charge (MKS) */
1169:   /* geometry and grids */
1170:   nt = LANDAU_MAX_GRIDS;
1171:   PetscCall(PetscOptionsIntArray("-dm_landau_num_species_grid", "Number of species on each grid: [ 1, ....] or [S, 0 ....] for single grid", "plexland.c", num_species_grid, &nt, &flg));
1172:   if (flg) {
1173:     ctx->num_grids = nt;
1174:     for (ii = nt = 0; ii < ctx->num_grids; ii++) nt += num_species_grid[ii];
1175:     PetscCheck(ctx->num_species == nt, ctx->comm, PETSC_ERR_ARG_WRONG, "-dm_landau_num_species_grid: sum %" PetscInt_FMT " != num_species = %" PetscInt_FMT ". %" PetscInt_FMT " grids (check that number of grids <= LANDAU_MAX_GRIDS = %d)", nt, ctx->num_species,
1176:                ctx->num_grids, LANDAU_MAX_GRIDS);
1177:   } else {
1178:     if (ctx->num_species > LANDAU_MAX_GRIDS) {
1179:       num_species_grid[0] = 1;
1180:       num_species_grid[1] = ctx->num_species - 1;
1181:       ctx->num_grids      = 2;
1182:     } else {
1183:       ctx->num_grids = ctx->num_species;
1184:       for (ii = 0; ii < ctx->num_grids; ii++) num_species_grid[ii] = 1;
1185:     }
1186:   }
1187:   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];
1188:   PetscCheck(ctx->species_offset[ctx->num_grids] == ctx->num_species, ctx->comm, PETSC_ERR_ARG_WRONG, "ctx->species_offset[ctx->num_grids] %" PetscInt_FMT " != ctx->num_species = %" PetscInt_FMT " ???????????", ctx->species_offset[ctx->num_grids],
1189:              ctx->num_species);
1190:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
1191:     PetscInt iii             = ctx->species_offset[grid];                                          // normalize with first (arbitrary) species on grid
1192:     ctx->thermal_speed[grid] = PetscSqrtReal(ctx->k * ctx->thermal_temps[iii] / ctx->masses[iii]); /* arbitrary units for non-dimensionalization: plasma formulary def */
1193:   }
1194:   // get lambdas here because we need them for t_0 etc
1195:   PetscCall(PetscOptionsReal("-dm_landau_ln_lambda", "Universal cross section parameter. Default uses NRL formulas", "plexland.c", lnLam, &lnLam, &flg));
1196:   if (flg) {
1197:     for (PetscInt grid = 0; grid < LANDAU_MAX_GRIDS; grid++) {
1198:       for (PetscInt gridj = 0; gridj < LANDAU_MAX_GRIDS; gridj++) ctx->lambdas[gridj][grid] = lnLam; /* cross section ratio large - small angle collisions */
1199:     }
1200:   } else {
1201:     PetscCall(makeLambdas(ctx));
1202:   }
1203:   non_dim_grid = 0;
1204:   PetscCall(PetscOptionsInt("-dm_landau_normalization_grid", "Index of grid to use for setting v_0, m_0, t_0. (Not recommended)", "plexland.c", non_dim_grid, &non_dim_grid, &flg));
1205:   if (non_dim_grid != 0) PetscCall(PetscInfo(dummy, "Normalization grid set to %" PetscInt_FMT ", but non-default not well verified\n", non_dim_grid));
1206:   PetscCheck(non_dim_grid >= 0 && non_dim_grid < ctx->num_species, ctx->comm, PETSC_ERR_ARG_WRONG, "Normalization grid wrong: %" PetscInt_FMT, non_dim_grid);
1207:   ctx->v_0 = ctx->thermal_speed[non_dim_grid]; /* arbitrary units for non dimensionalization: global mean velocity in 1D of electrons */
1208:   ctx->m_0 = ctx->masses[non_dim_grid];        /* arbitrary reference mass, electrons */
1209:   ctx->t_0 = 8 * PETSC_PI * PetscSqr(ctx->epsilon0 * ctx->m_0 / PetscSqr(ctx->charges[non_dim_grid])) / ctx->lambdas[non_dim_grid][non_dim_grid] / ctx->n_0 * PetscPowReal(ctx->v_0, 3); /* note, this t_0 makes nu[non_dim_grid,non_dim_grid]=1 */
1210:   /* domain */
1211:   nt = LANDAU_MAX_GRIDS;
1212:   PetscCall(PetscOptionsRealArray("-dm_landau_domain_radius", "Phase space size in units of thermal velocity of grid", "plexland.c", ctx->radius, &nt, &flg));
1213:   if (flg) {
1214:     PetscCheck(nt >= ctx->num_grids, ctx->comm, PETSC_ERR_ARG_WRONG, "-dm_landau_domain_radius: given %" PetscInt_FMT " radius != number grids %" PetscInt_FMT, nt, ctx->num_grids);
1215:     while (nt--) ctx->radius_par[nt] = ctx->radius_perp[nt] = ctx->radius[nt];
1216:   } else {
1217:     nt = LANDAU_MAX_GRIDS;
1218:     PetscCall(PetscOptionsRealArray("-dm_landau_domain_max_par", "Parallel velocity domain size in units of thermal velocity of grid", "plexland.c", ctx->radius_par, &nt, &flg));
1219:     if (flg) PetscCheck(nt >= ctx->num_grids, ctx->comm, PETSC_ERR_ARG_WRONG, "-dm_landau_domain_max_par: given %" PetscInt_FMT " radius != number grids %" PetscInt_FMT, nt, ctx->num_grids);
1220:     PetscCall(PetscOptionsRealArray("-dm_landau_domain_max_perp", "Perpendicular velocity domain size in units of thermal velocity of grid", "plexland.c", ctx->radius_perp, &nt, &flg));
1221:     if (flg) PetscCheck(nt >= ctx->num_grids, ctx->comm, PETSC_ERR_ARG_WRONG, "-dm_landau_domain_max_perp: given %" PetscInt_FMT " radius != number grids %" PetscInt_FMT, nt, ctx->num_grids);
1222:   }
1223:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
1224:     if (flg && ctx->radius[grid] <= 0) { /* negative is ratio of c - need to set par and perp with this -- todo */
1225:       if (ctx->radius[grid] == 0) ctx->radius[grid] = 0.75;
1226:       else ctx->radius[grid] = -ctx->radius[grid];
1227:       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)
1228:       PetscCall(PetscInfo(dummy, "Change domain radius to %g for grid %" PetscInt_FMT "\n", (double)ctx->radius[grid], grid));
1229:     }
1230:     ctx->radius[grid] *= ctx->thermal_speed[grid] / ctx->v_0;      // scale domain by thermal radius relative to v_0
1231:     ctx->radius_perp[grid] *= ctx->thermal_speed[grid] / ctx->v_0; // scale domain by thermal radius relative to v_0
1232:     ctx->radius_par[grid] *= ctx->thermal_speed[grid] / ctx->v_0;  // scale domain by thermal radius relative to v_0
1233:   }
1234:   /* amr parameters */
1235:   if (!fileflg) {
1236:     nt = LANDAU_MAX_GRIDS;
1237:     PetscCall(PetscOptionsIntArray("-dm_landau_amr_levels_max", "Number of AMR levels of refinement around origin, after (RE) refinements along z", "plexland.c", ctx->numAMRRefine, &nt, &flg));
1238:     PetscCheck(!flg || nt >= ctx->num_grids, ctx->comm, PETSC_ERR_ARG_WRONG, "-dm_landau_amr_levels_max: given %" PetscInt_FMT " != number grids %" PetscInt_FMT, nt, ctx->num_grids);
1239:     nt = LANDAU_MAX_GRIDS;
1240:     PetscCall(PetscOptionsIntArray("-dm_landau_amr_post_refine", "Number of levels to uniformly refine after AMR", "plexland.c", ctx->postAMRRefine, &nt, &flg));
1241:     for (ii = 1; ii < ctx->num_grids; ii++) ctx->postAMRRefine[ii] = ctx->postAMRRefine[0]; // all grids the same now
1242:     PetscCall(PetscOptionsInt("-dm_landau_amr_re_levels", "Number of levels to refine along v_perp=0, z>0", "plexland.c", ctx->numRERefine, &ctx->numRERefine, &flg));
1243:     PetscCall(PetscOptionsInt("-dm_landau_amr_z_refine_pre", "Number of levels to refine along v_perp=0 before origin refine", "plexland.c", ctx->nZRefine1, &ctx->nZRefine1, &flg));
1244:     PetscCall(PetscOptionsInt("-dm_landau_amr_z_refine_post", "Number of levels to refine along v_perp=0 after origin refine", "plexland.c", ctx->nZRefine2, &ctx->nZRefine2, &flg));
1245:     PetscCall(PetscOptionsReal("-dm_landau_re_radius", "velocity range to refine on positive (z>0) r=0 axis for runaways", "plexland.c", ctx->re_radius, &ctx->re_radius, &flg));
1246:     PetscCall(PetscOptionsReal("-dm_landau_z_radius_pre", "velocity range to refine r=0 axis (for electrons)", "plexland.c", ctx->vperp0_radius1, &ctx->vperp0_radius1, &flg));
1247:     PetscCall(PetscOptionsReal("-dm_landau_z_radius_post", "velocity range to refine r=0 axis (for electrons) after origin AMR", "plexland.c", ctx->vperp0_radius2, &ctx->vperp0_radius2, &flg));
1248:     /* spherical domain */
1249:     if (ctx->sphere || ctx->simplex) {
1250:       ctx->sphere_uniform_normal = PETSC_FALSE;
1251:       PetscCall(PetscOptionsBool("-dm_landau_sphere_uniform_normal", "Scaling of circle radius to get uniform particles per cell with Maxwellians (not used)", "plexland.c", ctx->sphere_uniform_normal, &ctx->sphere_uniform_normal, NULL));
1252:       if (!ctx->sphere_uniform_normal) { // true
1253:         nt = LANDAU_MAX_GRIDS;
1254:         PetscCall(PetscOptionsRealArray("-dm_landau_sphere_inner_radius_90degree_scale", "Scaling of radius for inner circle on 90 degree grid", "plexland.c", ctx->sphere_inner_radius_90degree, &nt, &flg));
1255:         if (flg && nt < ctx->num_grids) {
1256:           for (PetscInt grid = nt; grid < ctx->num_grids; grid++) ctx->sphere_inner_radius_90degree[grid] = ctx->sphere_inner_radius_90degree[0];
1257:         } else if (!flg || nt == 0) {
1258:           if (ctx->sphere && !ctx->simplex && LANDAU_DIM == 3) {
1259:             for (PetscInt grid = 0; grid < ctx->num_grids; grid++) ctx->sphere_inner_radius_90degree[grid] = 0.35; // optimized for R=6, Q4, AMR=0, 0 refinement
1260:           } else {
1261:             if (LANDAU_DIM == 2) {
1262:               for (PetscInt grid = 0; grid < ctx->num_grids; grid++) ctx->sphere_inner_radius_90degree[grid] = 0.4; // optimized for R=5, Q4, AMR=0
1263:             } else {
1264:               for (PetscInt grid = 0; grid < ctx->num_grids; grid++) ctx->sphere_inner_radius_90degree[grid] = 0.577 * 0.40;
1265:             }
1266:           }
1267:         }
1268:         nt = LANDAU_MAX_GRIDS;
1269:         PetscCall(PetscOptionsRealArray("-dm_landau_sphere_inner_radius_45degree_scale", "Scaling of radius for inner circle on 45 degree grid", "plexland.c", ctx->sphere_inner_radius_45degree, &nt, &flg));
1270:         if (flg && nt < ctx->num_grids) {
1271:           for (PetscInt grid = nt; grid < ctx->num_grids; grid++) ctx->sphere_inner_radius_45degree[grid] = ctx->sphere_inner_radius_45degree[0];
1272:         } else if (!flg || nt == 0) {
1273:           if (LANDAU_DIM == 2) {
1274:             for (PetscInt grid = 0; grid < ctx->num_grids; grid++) ctx->sphere_inner_radius_45degree[grid] = 0.45; // optimized for R=5, Q4, AMR=0
1275:           } else {
1276:             for (PetscInt grid = 0; grid < ctx->num_grids; grid++) ctx->sphere_inner_radius_45degree[grid] = 0.4; // 3D sphere
1277:           }
1278:         }
1279:         if (ctx->sphere) PetscCall(PetscInfo(ctx->plex[0], "sphere : , 45 degree scaling = %g; 90 degree scaling = %g\n", (double)ctx->sphere_inner_radius_45degree[0], (double)ctx->sphere_inner_radius_90degree[0]));
1280:       } else {
1281:         for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
1282:           switch (ctx->numAMRRefine[grid]) {
1283:           case 0:
1284:           case 1:
1285:           case 2:
1286:           case 3:
1287:           default:
1288:             if (LANDAU_DIM == 2) {
1289:               ctx->sphere_inner_radius_90degree[grid] = 0.40;
1290:               ctx->sphere_inner_radius_45degree[grid] = 0.45;
1291:             } else {
1292:               ctx->sphere_inner_radius_45degree[grid] = 0.25;
1293:             }
1294:           }
1295:         }
1296:       }
1297:     } else {
1298:       nt = LANDAU_DIM;
1299:       PetscCall(PetscOptionsIntArray("-dm_landau_num_cells", "Number of cells in each dimension of base grid", "plexland.c", ctx->cells0, &nt, &flg));
1300:     }
1301:   }
1302:   /* processing options */
1303:   PetscCall(PetscOptionsBool("-dm_landau_gpu_assembly", "Assemble Jacobian on GPU", "plexland.c", ctx->gpu_assembly, &ctx->gpu_assembly, NULL));
1304:   PetscCall(PetscOptionsBool("-dm_landau_jacobian_field_major_order", "Reorder Jacobian for GPU assembly with field major, or block diagonal, ordering (DEPRECATED)", "plexland.c", ctx->jacobian_field_major_order, &ctx->jacobian_field_major_order, NULL));
1305:   if (ctx->jacobian_field_major_order) PetscCheck(ctx->gpu_assembly, ctx->comm, PETSC_ERR_ARG_WRONG, "-dm_landau_jacobian_field_major_order requires -dm_landau_gpu_assembly");
1306:   PetscCheck(!ctx->jacobian_field_major_order, ctx->comm, PETSC_ERR_ARG_WRONG, "-dm_landau_jacobian_field_major_order DEPRECATED");
1307:   PetscOptionsEnd();

1309:   for (ii = ctx->num_species; ii < LANDAU_MAX_SPECIES; ii++) ctx->masses[ii] = ctx->thermal_temps[ii] = ctx->charges[ii] = 0;
1310:   if (ctx->verbose != 0) {
1311:     PetscReal pmassunit = PetscRealConstant(1.6720e-27);

1313:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "masses:        e=%10.3e; ions in proton mass units:   %10.3e %10.3e ...\n", (double)ctx->masses[0], (double)(ctx->masses[1] / pmassunit), (double)(ctx->num_species > 2 ? ctx->masses[2] / pmassunit : 0)));
1314:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "charges:       e=%10.3e; charges in elementary units: %10.3e %10.3e\n", (double)ctx->charges[0], (double)(-ctx->charges[1] / ctx->charges[0]), (double)(ctx->num_species > 2 ? -ctx->charges[2] / ctx->charges[0] : 0)));
1315:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "n:             e: %10.3e                           i: %10.3e %10.3e\n", (double)ctx->n[0], (double)ctx->n[1], (double)(ctx->num_species > 2 ? ctx->n[2] : 0)));
1316:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "thermal T (K): e=%10.3e i=%10.3e %10.3e. Normalization grid %" PetscInt_FMT ": v_0=%10.3e (%10.3ec) n_0=%10.3e t_0=%10.3e %" PetscInt_FMT " batched, view batch %" PetscInt_FMT "\n", (double)ctx->thermal_temps[0],
1317:                           (double)ctx->thermal_temps[1], (double)((ctx->num_species > 2) ? ctx->thermal_temps[2] : 0), non_dim_grid, (double)ctx->v_0, (double)(ctx->v_0 / SPEED_OF_LIGHT), (double)ctx->n_0, (double)ctx->t_0, ctx->batch_sz, ctx->batch_view_idx));
1318:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Domain radius (AMR levels) grid %d: par=%10.3e perp=%10.3e (%" PetscInt_FMT ") ", 0, (double)ctx->radius_par[0], (double)ctx->radius_perp[0], ctx->numAMRRefine[0]));
1319:     for (ii = 1; ii < ctx->num_grids; ii++) PetscCall(PetscPrintf(PETSC_COMM_WORLD, ", %" PetscInt_FMT ": par=%10.3e perp=%10.3e (%" PetscInt_FMT ") ", ii, (double)ctx->radius_par[ii], (double)ctx->radius_perp[ii], ctx->numAMRRefine[ii]));
1320:     if (ctx->use_relativistic_corrections) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\nUse relativistic corrections\n"));
1321:     else PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n"));
1322:   }
1323:   PetscCall(DMDestroy(&dummy));
1324:   {
1325:     PetscMPIInt rank;
1326:     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1327:     ctx->stage = 0;
1328:     PetscCall(PetscLogEventRegister("Landau Create", DM_CLASSID, &ctx->events[13]));   /* 13 */
1329:     PetscCall(PetscLogEventRegister(" GPU ass. setup", DM_CLASSID, &ctx->events[2]));  /* 2 */
1330:     PetscCall(PetscLogEventRegister(" Build matrix", DM_CLASSID, &ctx->events[12]));   /* 12 */
1331:     PetscCall(PetscLogEventRegister(" Assembly maps", DM_CLASSID, &ctx->events[15]));  /* 15 */
1332:     PetscCall(PetscLogEventRegister("Landau Mass mat", DM_CLASSID, &ctx->events[14])); /* 14 */
1333:     PetscCall(PetscLogEventRegister("Landau Operator", DM_CLASSID, &ctx->events[11])); /* 11 */
1334:     PetscCall(PetscLogEventRegister("Landau Jacobian", DM_CLASSID, &ctx->events[0]));  /* 0 */
1335:     PetscCall(PetscLogEventRegister("Landau Mass", DM_CLASSID, &ctx->events[9]));      /* 9 */
1336:     PetscCall(PetscLogEventRegister(" Preamble", DM_CLASSID, &ctx->events[10]));       /* 10 */
1337:     PetscCall(PetscLogEventRegister(" static IP Data", DM_CLASSID, &ctx->events[7]));  /* 7 */
1338:     PetscCall(PetscLogEventRegister(" dynamic IP-Jac", DM_CLASSID, &ctx->events[1]));  /* 1 */
1339:     PetscCall(PetscLogEventRegister(" Kernel-init", DM_CLASSID, &ctx->events[3]));     /* 3 */
1340:     PetscCall(PetscLogEventRegister(" Jac-f-df (GPU)", DM_CLASSID, &ctx->events[8]));  /* 8 */
1341:     PetscCall(PetscLogEventRegister(" J Kernel (GPU)", DM_CLASSID, &ctx->events[4]));  /* 4 */
1342:     PetscCall(PetscLogEventRegister(" M Kernel (GPU)", DM_CLASSID, &ctx->events[16])); /* 16 */
1343:     PetscCall(PetscLogEventRegister(" Copy to CPU", DM_CLASSID, &ctx->events[5]));     /* 5 */
1344:     PetscCall(PetscLogEventRegister(" CPU assemble", DM_CLASSID, &ctx->events[6]));    /* 6 */

1346:     if (rank) { /* turn off output stuff for duplicate runs - do we need to add the prefix to all this? */
1347:       PetscCall(PetscOptionsClearValue(NULL, "-snes_converged_reason"));
1348:       PetscCall(PetscOptionsClearValue(NULL, "-ksp_converged_reason"));
1349:       PetscCall(PetscOptionsClearValue(NULL, "-snes_monitor"));
1350:       PetscCall(PetscOptionsClearValue(NULL, "-ksp_monitor"));
1351:       PetscCall(PetscOptionsClearValue(NULL, "-ts_monitor"));
1352:       PetscCall(PetscOptionsClearValue(NULL, "-ts_view"));
1353:       PetscCall(PetscOptionsClearValue(NULL, "-ts_adapt_monitor"));
1354:       PetscCall(PetscOptionsClearValue(NULL, "-dm_landau_amr_dm_view"));
1355:       PetscCall(PetscOptionsClearValue(NULL, "-dm_landau_amr_vec_view"));
1356:       PetscCall(PetscOptionsClearValue(NULL, "-dm_landau_mass_dm_view"));
1357:       PetscCall(PetscOptionsClearValue(NULL, "-dm_landau_mass_view"));
1358:       PetscCall(PetscOptionsClearValue(NULL, "-dm_landau_jacobian_view"));
1359:       PetscCall(PetscOptionsClearValue(NULL, "-dm_landau_mat_view"));
1360:       PetscCall(PetscOptionsClearValue(NULL, "-pc_bjkokkos_ksp_converged_reason"));
1361:       PetscCall(PetscOptionsClearValue(NULL, "-pc_bjkokkos_ksp_monitor"));
1362:       PetscCall(PetscOptionsClearValue(NULL, "-"));
1363:       PetscCall(PetscOptionsClearValue(NULL, "-info"));
1364:     }
1365:   }
1366:   PetscFunctionReturn(PETSC_SUCCESS);
1367: }

1369: /* Build c_maps and gIdx from PetscSection constraint data and cMat, replacing the probing strategy */
1370: static PetscErrorCode LandauBuildConstraintMaps_PetscSection(DM dm, PetscInt Nf_grid, PetscSection section, PetscSection globsection, P4estVertexMaps *maps, pointInterpolationP4est (*pointMaps)[LANDAU_MAX_Q_FACE], PetscInt MAP_BF_SIZE, LandauIdx *coo_elem_fullNb, LandauIdx *coo_elem_offsets, PetscInt glb_elem_idx_start)
1371: {
1372:   PetscDS          ds;
1373:   PetscSection     aSec, cSec;
1374:   IS               aIS, clpermIS = NULL;
1375:   Mat              cMat;
1376:   const PetscInt  *anchors = NULL, *clperm_arr = NULL;
1377:   PetscInt         cStart, cEnd, aStart, aEnd, sStart, sEnd;
1378:   const PetscInt **fieldPerms[LANDAU_MAX_SPECIES];
1379:   PetscInt         fieldFoffs[LANDAU_MAX_SPECIES]; /* running offset per field in natural order */
1380:   PetscInt         fullNb[LANDAU_MAX_SPECIES];     /* unconstrained DOF count per field for this element */
1381:   PetscInt         foffs[LANDAU_MAX_SPECIES + 1];  /* cumulative field offsets in natural closure order */
1382:   PetscInt         clTotDof;                       /* total closure DOFs (same for all cells, from DS) */

1384:   PetscFunctionBegin;
1385:   PetscCheck(Nf_grid <= LANDAU_MAX_SPECIES, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Nf_grid %" PetscInt_FMT " > LANDAU_MAX_SPECIES %d", Nf_grid, LANDAU_MAX_SPECIES);
1386:   PetscCall(DMGetDS(dm, &ds));
1387:   /* per-field offsets and total DOF count are stored in the DS; no need to recompute per cell */
1388:   for (PetscInt f = 0; f < Nf_grid; f++) PetscCall(PetscDSGetFieldOffset(ds, f, &foffs[f]));
1389:   PetscCall(PetscDSGetTotalDimension(ds, &clTotDof));
1390:   foffs[Nf_grid] = clTotDof;
1391:   PetscCall(DMGetDefaultConstraints(dm, &cSec, &cMat, NULL));
1392:   PetscCall(DMPlexGetAnchors(dm, &aSec, &aIS));
1393:   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
1394:   if (aSec) {
1395:     PetscCall(PetscSectionGetChart(aSec, &aStart, &aEnd));
1396:     PetscCall(ISGetIndices(aIS, &anchors));
1397:   } else {
1398:     aStart = aEnd = 0;
1399:     anchors       = NULL;
1400:   }
1401:   PetscCall(PetscSectionGetChart(section, &sStart, &sEnd));
1402:   /* Query closure inverse permutation once; identical for all height-0 cells. */
1403:   if (cStart < cEnd) {
1404:     PetscSection clSec = NULL;
1405:     PetscCall(PetscSectionGetClosureIndex(section, (PetscObject)dm, &clSec, NULL));
1406:     if (clSec) { /* closure permutation exists */
1407:       PetscInt depth0;
1408:       PetscCall(DMPlexGetPointDepth(dm, cStart, &depth0));
1409:       PetscCall(PetscSectionGetClosureInversePermutation(section, (PetscObject)dm, depth0, clTotDof, &clpermIS));
1410:       PetscCall(ISGetIndices(clpermIS, &clperm_arr));
1411:     }
1412:   }
1413:   for (PetscInt ej = cStart, eidx = 0; ej < cEnd; ++ej, ++eidx) {
1414:     PetscInt  glb_elem_idx = glb_elem_idx_start + eidx;
1415:     PetscInt *closure      = NULL;
1416:     PetscInt  closureSize;

1418:     if (coo_elem_offsets) coo_elem_offsets[glb_elem_idx + 1] = coo_elem_offsets[glb_elem_idx];
1419:     PetscCall(DMPlexGetTransitiveClosure(dm, ej, PETSC_TRUE, &closureSize, &closure));                                                       /* original closure */
1420:     for (PetscInt f = 0; f < Nf_grid; f++) PetscCall(PetscSectionGetFieldPointSyms(section, f, closureSize, closure, &fieldPerms[f], NULL)); /* orientation perms; flips affect sign only and are not needed for index assignment */
1421:     PetscCall(PetscArrayzero(fieldFoffs, LANDAU_MAX_SPECIES));
1422:     PetscCall(PetscArrayzero(fullNb, LANDAU_MAX_SPECIES));
1423:     for (PetscInt ci = 0; ci < closureSize; ci++) { /* fill gIdx / c_maps */
1424:       PetscInt p = closure[2 * ci];
1425:       if (p < sStart || p >= sEnd) continue;
1426:       for (PetscInt f = 0; f < Nf_grid; f++) {
1427:         const PetscInt *fcdofs = NULL;
1428:         const PetscInt *perm   = (fieldPerms[f] && fieldPerms[f][ci]) ? fieldPerms[f][ci] : NULL;
1429:         PetscInt        fdof = 0, cfdof = 0;
1430:         PetscInt        pGlobOff         = 0;
1431:         PetscInt        globFieldInPoint = 0; /* unconstrained DOF offset for field f at this point */
1432:         PetscInt        cind             = 0; /* index into fcdofs[] */

1434:         PetscCall(PetscSectionGetFieldDof(section, p, f, &fdof));
1435:         if (!fdof) continue;
1436:         PetscCall(PetscSectionGetFieldConstraintDof(section, p, f, &cfdof));
1437:         if (cfdof) PetscCall(PetscSectionGetFieldConstraintIndices(section, p, f, &fcdofs));
1438:         PetscCall(PetscSectionGetOffset(globsection, p, &pGlobOff));
1439:         for (PetscInt g = 0; g < f; g++) { /* unconstrained DOFs from earlier fields */
1440:           PetscInt gfdof = 0, gcfdof = 0;
1441:           PetscCall(PetscSectionGetFieldDof(section, p, g, &gfdof));
1442:           PetscCall(PetscSectionGetFieldConstraintDof(section, p, g, &gcfdof));
1443:           globFieldInPoint += gfdof - gcfdof;
1444:         }
1445:         for (PetscInt b = 0; b < fdof; b++) {
1446:           PetscInt  preind        = foffs[f] + fieldFoffs[f] + (perm ? perm[b] : b); /* natural order position */
1447:           PetscInt  q             = clperm_arr ? clperm_arr[preind] : preind;        /* permuted position */
1448:           PetscBool isConstrained = (cfdof > 0 && cind < cfdof && b == fcdofs[cind]) ? PETSC_TRUE : PETSC_FALSE;

1450:           q -= foffs[f];       /* subtract field base offset to get q within [0, Nb) */
1451:           if (isConstrained) { /* constrained DOF */
1452:             PetscInt    cOff, row, bDof = 0, bOff2 = 0;
1453:             PetscInt    nNonzero = 0;
1454:             PetscInt    trivGid  = -1;
1455:             PetscScalar trivVal  = 0;

1457:             PetscCheck(cSec, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Constrained DOF found but constraint section is NULL");
1458:             PetscCall(PetscSectionGetFieldOffset(cSec, p, f, &cOff));
1459:             row = cOff + cind;
1460:             if (aSec && p >= aStart && p < aEnd) {
1461:               PetscCall(PetscSectionGetDof(aSec, p, &bDof));
1462:               PetscCall(PetscSectionGetOffset(aSec, p, &bOff2));
1463:             }
1464:             PetscCheck(!bDof || anchors, PETSC_COMM_SELF, PETSC_ERR_PLIB, "constrained point has anchors but anchor array is NULL");
1465:             for (PetscInt ai = 0; ai < bDof; ai++) { /* scan cMat row for non-zeros */
1466:               PetscInt aLocOff, aGlobOff, aDof = 0;
1467:               PetscInt aGlobFieldInPoint = 0;
1468:               PetscInt a                 = anchors[bOff2 + ai];

1470:               if (a >= sStart && a < sEnd) PetscCall(PetscSectionGetFieldDof(section, a, f, &aDof));
1471:               if (!aDof) continue;
1472:               PetscCall(PetscSectionGetFieldOffset(section, a, f, &aLocOff));
1473:               PetscCall(PetscSectionGetOffset(globsection, a, &aGlobOff));
1474:               for (PetscInt g = 0; g < f; g++) {
1475:                 PetscInt agfdof = 0, agcfdof = 0;
1476:                 PetscCall(PetscSectionGetFieldDof(section, a, g, &agfdof));
1477:                 PetscCall(PetscSectionGetFieldConstraintDof(section, a, g, &agcfdof));
1478:                 aGlobFieldInPoint += agfdof - agcfdof;
1479:               }
1480:               for (PetscInt e = 0; e < aDof; e++) {
1481:                 PetscScalar val;
1482:                 PetscInt    col = aLocOff + e;
1483:                 PetscCall(MatGetValues(cMat, 1, &row, 1, &col, &val));
1484:                 if (PetscAbs(PetscRealPart(val)) > PETSC_MACHINE_EPSILON) {
1485:                   nNonzero++;
1486:                   trivVal = val;
1487:                   trivGid = aGlobOff + aGlobFieldInPoint + e;
1488:                 }
1489:               }
1490:             }
1491:             PetscCheck(nNonzero > 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "constrained DOF (cell %" PetscInt_FMT " field %" PetscInt_FMT ") has no anchor non-zeros in cMat", eidx, f);
1492:             if (nNonzero == 1 && PetscAbs(PetscRealPart(trivVal) - 1.0) < 10 * PETSC_MACHINE_EPSILON) { /* trivial constraint */
1493:               maps->gIdx[eidx][f][q] = trivGid;
1494:               fullNb[f]++;
1495:             } else { /* non-trivial constraint: build pointMap */
1496:               PetscInt jj = 0;

1498:               maps->gIdx[eidx][f][q] = -(maps->num_reduced + 1);
1499:               for (PetscInt ai = 0; ai < bDof && jj < maps->num_face; ai++) {
1500:                 PetscInt aLocOff, aGlobOff, aDof = 0;
1501:                 PetscInt aGlobFieldInPoint = 0;
1502:                 PetscInt a                 = anchors[bOff2 + ai];

1504:                 if (a >= sStart && a < sEnd) PetscCall(PetscSectionGetFieldDof(section, a, f, &aDof));
1505:                 if (!aDof) continue;
1506:                 PetscCall(PetscSectionGetFieldOffset(section, a, f, &aLocOff));
1507:                 PetscCall(PetscSectionGetOffset(globsection, a, &aGlobOff));
1508:                 for (PetscInt g = 0; g < f; g++) {
1509:                   PetscInt agfdof = 0, agcfdof = 0;
1510:                   PetscCall(PetscSectionGetFieldDof(section, a, g, &agfdof));
1511:                   PetscCall(PetscSectionGetFieldConstraintDof(section, a, g, &agcfdof));
1512:                   aGlobFieldInPoint += agfdof - agcfdof;
1513:                 }
1514:                 for (PetscInt e = 0; e < aDof && jj < maps->num_face; e++) {
1515:                   PetscScalar val;
1516:                   PetscReal   rval;
1517:                   PetscInt    col = aLocOff + e;

1519:                   PetscCall(MatGetValues(cMat, 1, &row, 1, &col, &val));
1520:                   rval = PetscRealPart(val);
1521:                   if (PetscAbs(rval) <= PETSC_MACHINE_EPSILON) rval = 0.0;
1522:                   pointMaps[maps->num_reduced][jj].scale = rval;
1523:                   pointMaps[maps->num_reduced][jj].gid   = (rval == 0.0) ? -1 : aGlobOff + aGlobFieldInPoint + e;
1524:                   if (rval != 0.0) fullNb[f]++;
1525:                   jj++;
1526:                 }
1527:               }
1528:               while (jj < maps->num_face) {
1529:                 pointMaps[maps->num_reduced][jj].scale = 0.0;
1530:                 pointMaps[maps->num_reduced][jj].gid   = -1;
1531:                 jj++;
1532:               }
1533:               maps->num_reduced++;
1534:               PetscCheck(maps->num_reduced < MAP_BF_SIZE, PETSC_COMM_SELF, PETSC_ERR_PLIB, "maps->num_reduced %" PetscInt_FMT " >= MAP_BF_SIZE %" PetscInt_FMT, maps->num_reduced, MAP_BF_SIZE);
1535:             }
1536:             cind++;
1537:           } else { /* unconstrained DOF */
1538:             PetscCheck(pGlobOff >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Landau per-grid plex must be on PETSC_COMM_SELF; got off-process global offset");
1539:             maps->gIdx[eidx][f][q] = pGlobOff + globFieldInPoint + b - cind;
1540:             fullNb[f]++;
1541:           }
1542:         }
1543:         fieldFoffs[f] += fdof;
1544:       }
1545:     }
1546:     for (PetscInt f = 0; f < Nf_grid; f++) PetscCall(PetscSectionRestoreFieldPointSyms(section, f, closureSize, closure, &fieldPerms[f], NULL));
1547:     PetscCall(DMPlexRestoreTransitiveClosure(dm, ej, PETSC_TRUE, &closureSize, &closure));
1548:     if (coo_elem_offsets) { /* COO offsets */
1549:       for (PetscInt f = 0; f < Nf_grid; f++) {
1550:         coo_elem_offsets[glb_elem_idx + 1] += fullNb[f] * fullNb[f];
1551:         if (f == 0) coo_elem_fullNb[glb_elem_idx] = fullNb[f];
1552:         else PetscCheck(coo_elem_fullNb[glb_elem_idx] == fullNb[f], PETSC_COMM_SELF, PETSC_ERR_PLIB, "full element size change with species %" PetscInt_FMT " %" PetscInt_FMT, coo_elem_fullNb[glb_elem_idx], fullNb[f]);
1553:       }
1554:     }
1555:   } /* cell */
1556:   if (clpermIS) {
1557:     PetscCall(ISRestoreIndices(clpermIS, &clperm_arr));
1558:     PetscCall(ISDestroy(&clpermIS));
1559:   }
1560:   if (aSec) PetscCall(ISRestoreIndices(aIS, &anchors));
1561:   PetscFunctionReturn(PETSC_SUCCESS);
1562: }

1564: static PetscErrorCode CreateStaticData(PetscInt dim, IS grid_batch_is_inv[], const char prefix[], LandauCtx *ctx)
1565: {
1566:   PetscSection     section[LANDAU_MAX_GRIDS], globsection[LANDAU_MAX_GRIDS];
1567:   PetscQuadrature  quad;
1568:   const PetscReal *quadWeights;
1569:   PetscReal        invMass[LANDAU_MAX_SPECIES], nu_alpha[LANDAU_MAX_SPECIES], nu_beta[LANDAU_MAX_SPECIES];
1570:   PetscInt         numCells[LANDAU_MAX_GRIDS], Nq, Nb, Nf[LANDAU_MAX_GRIDS], ncellsTot = 0, MAP_BF_SIZE = 64 * LANDAU_DIM * LANDAU_DIM * LANDAU_MAX_Q_FACE * LANDAU_MAX_SPECIES;
1571:   PetscTabulation *Tf;
1572:   PetscDS          prob;

1574:   PetscFunctionBegin;
1575:   PetscCall(PetscFEGetDimension(ctx->fe[0], &Nb));
1576:   PetscCheck(Nb <= LANDAU_MAX_NQND, ctx->comm, PETSC_ERR_ARG_WRONG, "Order too high. Nb = %" PetscInt_FMT " > LANDAU_MAX_NQND (%d)", Nb, LANDAU_MAX_NQND);
1577:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
1578:     for (PetscInt ii = ctx->species_offset[grid]; ii < ctx->species_offset[grid + 1]; ii++) {
1579:       invMass[ii]  = ctx->m_0 / ctx->masses[ii];
1580:       nu_alpha[ii] = PetscSqr(ctx->charges[ii] / ctx->m_0) * ctx->m_0 / ctx->masses[ii];
1581:       nu_beta[ii]  = PetscSqr(ctx->charges[ii] / ctx->epsilon0) / (8 * PETSC_PI) * ctx->t_0 * ctx->n_0 / PetscPowReal(ctx->v_0, 3);
1582:     }
1583:   }
1584:   if (ctx->verbose == 4) {
1585:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "nu_alpha: "));
1586:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
1587:       PetscInt iii = ctx->species_offset[grid];
1588:       for (PetscInt ii = iii; ii < ctx->species_offset[grid + 1]; ii++) PetscCall(PetscPrintf(PETSC_COMM_WORLD, " %e", (double)nu_alpha[ii]));
1589:     }
1590:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\nnu_beta: "));
1591:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
1592:       PetscInt iii = ctx->species_offset[grid];
1593:       for (PetscInt ii = iii; ii < ctx->species_offset[grid + 1]; ii++) PetscCall(PetscPrintf(PETSC_COMM_WORLD, " %e", (double)nu_beta[ii]));
1594:     }
1595:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\nnu_alpha[i]*nu_beta[j]*lambda[i][j]:\n"));
1596:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
1597:       PetscInt iii = ctx->species_offset[grid];
1598:       for (PetscInt ii = iii; ii < ctx->species_offset[grid + 1]; ii++) {
1599:         for (PetscInt gridj = 0; gridj < ctx->num_grids; gridj++) {
1600:           PetscInt jjj = ctx->species_offset[gridj];
1601:           for (PetscInt jj = jjj; jj < ctx->species_offset[gridj + 1]; jj++) PetscCall(PetscPrintf(PETSC_COMM_WORLD, " %14.9e", (double)(nu_alpha[ii] * nu_beta[jj] * ctx->lambdas[grid][gridj])));
1602:         }
1603:         PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n"));
1604:       }
1605:     }
1606:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "lambda[i][j]:\n"));
1607:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
1608:       PetscInt iii = ctx->species_offset[grid];
1609:       for (PetscInt ii = iii; ii < ctx->species_offset[grid + 1]; ii++) {
1610:         for (PetscInt gridj = 0; gridj < ctx->num_grids; gridj++) {
1611:           PetscInt jjj = ctx->species_offset[gridj];
1612:           for (PetscInt jj = jjj; jj < ctx->species_offset[gridj + 1]; jj++) PetscCall(PetscPrintf(PETSC_COMM_WORLD, " %14.9e", (double)ctx->lambdas[grid][gridj]));
1613:         }
1614:         PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n"));
1615:       }
1616:     }
1617:   }
1618:   PetscCall(DMGetDS(ctx->plex[0], &prob));    // same DS for all grids
1619:   PetscCall(PetscDSGetTabulation(prob, &Tf)); // Bf, &Df same for all grids
1620:   /* DS, Tab and quad is same on all grids */
1621:   PetscCheck(ctx->plex[0], ctx->comm, PETSC_ERR_ARG_WRONG, "Plex not created");
1622:   PetscCall(PetscFEGetQuadrature(ctx->fe[0], &quad));
1623:   PetscCall(PetscQuadratureGetData(quad, NULL, NULL, &Nq, NULL, &quadWeights));
1624:   PetscCheck(Nq <= LANDAU_MAX_NQND, ctx->comm, PETSC_ERR_ARG_WRONG, "Order too high. Nq = %" PetscInt_FMT " > LANDAU_MAX_NQND (%d)", Nq, LANDAU_MAX_NQND);
1625:   /* setup each grid */
1626:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
1627:     PetscInt cStart, cEnd;
1628:     PetscCheck(ctx->plex[grid] != NULL, ctx->comm, PETSC_ERR_ARG_WRONG, "Plex not created");
1629:     PetscCall(DMPlexGetHeightStratum(ctx->plex[grid], 0, &cStart, &cEnd));
1630:     numCells[grid] = cEnd - cStart; // grids can have different topology
1631:     PetscCall(DMGetLocalSection(ctx->plex[grid], &section[grid]));
1632:     PetscCall(DMGetGlobalSection(ctx->plex[grid], &globsection[grid]));
1633:     PetscCall(PetscSectionGetNumFields(section[grid], &Nf[grid]));
1634:     ncellsTot += numCells[grid];
1635:   }
1636:   /* create GPU assembly data */
1637:   if (ctx->gpu_assembly) { /* we need GPU object with GPU assembly */
1638:     PetscContainer container;
1639:     pointInterpolationP4est(*pointMaps)[LANDAU_MAX_Q_FACE];
1640:     P4estVertexMaps *maps;
1641:     const PetscInt  *plex_batch       = NULL;
1642:     LandauIdx       *coo_elem_offsets = NULL, *coo_elem_fullNb = NULL, (*coo_elem_point_offsets)[LANDAU_MAX_NQND + 1] = NULL;
1643:     PetscCall(PetscLogEventBegin(ctx->events[2], 0, 0, 0, 0));
1644:     PetscCall(PetscMalloc(sizeof(*maps) * ctx->num_grids, &maps));
1645:     PetscCall(PetscMalloc(sizeof(*pointMaps) * MAP_BF_SIZE, &pointMaps));

1647:     {                                                                                                                             // setup COO assembly -- put COO metadata directly in ctx->SData_d
1648:       PetscCall(PetscMalloc3(ncellsTot + 1, &coo_elem_offsets, ncellsTot, &coo_elem_fullNb, ncellsTot, &coo_elem_point_offsets)); // array of integer pointers
1649:       coo_elem_offsets[0] = 0;                                                                                                    // finish later
1650:       PetscCall(PetscInfo(ctx->plex[0], "COO initialization, %" PetscInt_FMT " cells\n", ncellsTot));
1651:       ctx->SData_d.coo_n_cellsTot         = ncellsTot;
1652:       ctx->SData_d.coo_elem_offsets       = (void *)coo_elem_offsets;
1653:       ctx->SData_d.coo_elem_fullNb        = (void *)coo_elem_fullNb;
1654:       ctx->SData_d.coo_elem_point_offsets = (void *)coo_elem_point_offsets;
1655:     }

1657:     ctx->SData_d.coo_max_fullnb = 0;
1658:     for (PetscInt grid = 0, glb_elem_idx = 0; grid < ctx->num_grids; grid++) {
1659:       if (grid_batch_is_inv[grid]) PetscCall(ISGetIndices(grid_batch_is_inv[grid], &plex_batch));
1660:       PetscCheck(!plex_batch, ctx->comm, PETSC_ERR_ARG_WRONG, "-dm_landau_jacobian_field_major_order DEPRECATED");
1661:       // make maps
1662:       maps[grid].d_self       = NULL;
1663:       maps[grid].num_elements = numCells[grid];
1664:       maps[grid].num_face     = (PetscInt)(pow(Nq, 1. / ((double)dim)) + .001);                 // Q
1665:       maps[grid].num_face     = (PetscInt)(pow(maps[grid].num_face, (double)(dim - 1)) + .001); // Q^2
1666:       maps[grid].num_reduced  = 0;
1667:       maps[grid].deviceType   = ctx->deviceType;
1668:       maps[grid].numgrids     = ctx->num_grids;
1669:       PetscCall(PetscMalloc(maps[grid].num_elements * sizeof(*maps[grid].gIdx), &maps[grid].gIdx));
1670:       PetscCall(LandauBuildConstraintMaps_PetscSection(ctx->plex[grid], Nf[grid], section[grid], globsection[grid], &maps[grid], pointMaps, MAP_BF_SIZE, coo_elem_fullNb, coo_elem_offsets, glb_elem_idx));
1671:       for (PetscInt ej = 0; ej < numCells[grid]; ej++) {
1672:         if (coo_elem_fullNb[glb_elem_idx + ej] > ctx->SData_d.coo_max_fullnb) ctx->SData_d.coo_max_fullnb = coo_elem_fullNb[glb_elem_idx + ej];
1673:       }
1674:       glb_elem_idx += numCells[grid];
1675:       // allocate and copy point data maps[grid].gIdx[eidx][field][q]
1676:       PetscCall(PetscMalloc(maps[grid].num_reduced * sizeof(*maps[grid].c_maps), &maps[grid].c_maps));
1677:       for (PetscInt ej = 0; ej < maps[grid].num_reduced; ++ej) {
1678:         for (PetscInt q = 0; q < maps[grid].num_face; ++q) {
1679:           maps[grid].c_maps[ej][q].scale = pointMaps[ej][q].scale;
1680:           maps[grid].c_maps[ej][q].gid   = pointMaps[ej][q].gid;
1681:         }
1682:       }
1683: #if PetscDefined(HAVE_KOKKOS)
1684:       if (ctx->deviceType == LANDAU_KOKKOS) PetscCall(LandauKokkosCreateMatMaps(maps, pointMaps, Nf, grid)); // implies Kokkos does
1685: #endif
1686:       if (plex_batch) {
1687:         PetscCall(ISRestoreIndices(grid_batch_is_inv[grid], &plex_batch));
1688:         PetscCall(ISDestroy(&grid_batch_is_inv[grid])); // we are done with this
1689:       }
1690:     } /* grids */
1691:     // finish COO
1692:     { // setup COO assembly
1693:       PetscInt *oor, *ooc;
1694:       ctx->SData_d.coo_size = (PetscCount)coo_elem_offsets[ncellsTot] * ctx->batch_sz;
1695:       PetscCall(PetscMalloc2(ctx->SData_d.coo_size, &oor, ctx->SData_d.coo_size, &ooc));
1696:       for (PetscCount i = 0; i < ctx->SData_d.coo_size; i++) oor[i] = ooc[i] = -1;
1697:       // get
1698:       for (PetscInt grid = 0, glb_elem_idx = 0; grid < ctx->num_grids; grid++) {
1699:         for (PetscInt ej = 0; ej < numCells[grid]; ++ej, glb_elem_idx++) {
1700:           const PetscInt         fullNb           = coo_elem_fullNb[glb_elem_idx];
1701:           const LandauIdx *const Idxs             = &maps[grid].gIdx[ej][0][0]; // just use field-0 maps, They should be the same but this is just for COO storage
1702:           coo_elem_point_offsets[glb_elem_idx][0] = 0;
1703:           for (PetscInt f = 0, cnt2 = 0; f < Nb; f++) {
1704:             PetscInt idx                                = Idxs[f];
1705:             coo_elem_point_offsets[glb_elem_idx][f + 1] = coo_elem_point_offsets[glb_elem_idx][f]; // start at last
1706:             if (idx >= 0) {
1707:               cnt2++;
1708:               coo_elem_point_offsets[glb_elem_idx][f + 1]++; // inc
1709:             } else {
1710:               idx = -idx - 1;
1711:               for (PetscInt q = 0; q < maps[grid].num_face; q++) {
1712:                 if (maps[grid].c_maps[idx][q].gid >= 0) { // skip zero-scale (gid=-1) entries; do not break - they may be non-contiguous in 3D AMR
1713:                   cnt2++;
1714:                   coo_elem_point_offsets[glb_elem_idx][f + 1]++; // inc
1715:                 }
1716:               }
1717:             }
1718:             PetscCheck(cnt2 <= fullNb, PETSC_COMM_SELF, PETSC_ERR_PLIB, "wrong count %" PetscInt_FMT " < %" PetscInt_FMT, fullNb, cnt2);
1719:           }
1720:           PetscCheck(coo_elem_point_offsets[glb_elem_idx][Nb] == fullNb, PETSC_COMM_SELF, PETSC_ERR_PLIB, "coo_elem_point_offsets size %" PetscInt_FMT " != fullNb=%" PetscInt_FMT, coo_elem_point_offsets[glb_elem_idx][Nb], fullNb);
1721:         }
1722:       }
1723:       // set
1724:       for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) {
1725:         for (PetscInt grid = 0, glb_elem_idx = 0; grid < ctx->num_grids; grid++) {
1726:           const PetscInt moffset = LAND_MOFFSET(b_id, grid, ctx->batch_sz, ctx->num_grids, ctx->mat_offset);
1727:           for (PetscInt ej = 0; ej < numCells[grid]; ++ej, glb_elem_idx++) {
1728:             const PetscInt fullNb = coo_elem_fullNb[glb_elem_idx], fullNb2 = fullNb * fullNb;
1729:             // set (i,j)
1730:             for (PetscInt fieldA = 0; fieldA < Nf[grid]; fieldA++) {
1731:               const LandauIdx *const Idxs = &maps[grid].gIdx[ej][fieldA][0];
1732:               PetscInt               rows[LANDAU_MAX_Q_FACE], cols[LANDAU_MAX_Q_FACE];
1733:               for (PetscInt f = 0; f < Nb; ++f) {
1734:                 const PetscInt nr = coo_elem_point_offsets[glb_elem_idx][f + 1] - coo_elem_point_offsets[glb_elem_idx][f];
1735:                 if (nr == 1) rows[0] = Idxs[f];
1736:                 else {
1737:                   const PetscInt idx = -Idxs[f] - 1;
1738:                   for (PetscInt q = 0, ri = 0; q < maps[grid].num_face; q++)
1739:                     if (maps[grid].c_maps[idx][q].gid >= 0) rows[ri++] = maps[grid].c_maps[idx][q].gid;
1740:                 }
1741:                 for (PetscInt g = 0; g < Nb; ++g) {
1742:                   const PetscInt nc = coo_elem_point_offsets[glb_elem_idx][g + 1] - coo_elem_point_offsets[glb_elem_idx][g];
1743:                   if (nc == 1) cols[0] = Idxs[g];
1744:                   else {
1745:                     const PetscInt idx = -Idxs[g] - 1;
1746:                     for (PetscInt q = 0, ci = 0; q < maps[grid].num_face; q++)
1747:                       if (maps[grid].c_maps[idx][q].gid >= 0) cols[ci++] = maps[grid].c_maps[idx][q].gid;
1748:                   }
1749:                   const PetscInt idx0 = b_id * coo_elem_offsets[ncellsTot] + coo_elem_offsets[glb_elem_idx] + fieldA * fullNb2 + fullNb * coo_elem_point_offsets[glb_elem_idx][f] + nr * coo_elem_point_offsets[glb_elem_idx][g];
1750:                   for (PetscInt q = 0, idx = idx0; q < nr; q++) {
1751:                     for (PetscInt d = 0; d < nc; d++, idx++) {
1752:                       oor[idx] = rows[q] + moffset;
1753:                       ooc[idx] = cols[d] + moffset;
1754:                     }
1755:                   }
1756:                 }
1757:               }
1758:             }
1759:           } // cell
1760:         } // grid
1761:       } // batch
1762:       PetscCall(MatSetPreallocationCOO(ctx->J, ctx->SData_d.coo_size, oor, ooc));
1763:       PetscCall(PetscFree2(oor, ooc));
1764:     }
1765:     PetscCall(PetscFree(pointMaps));
1766:     PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
1767:     PetscCall(PetscContainerSetPointer(container, (void *)maps));
1768:     PetscCall(PetscContainerSetCtxDestroy(container, LandauGPUMapsDestroy));
1769:     PetscCall(PetscObjectCompose((PetscObject)ctx->J, "assembly_maps", (PetscObject)container));
1770:     PetscCall(PetscContainerDestroy(&container));
1771:     PetscCall(PetscLogEventEnd(ctx->events[2], 0, 0, 0, 0));
1772:   } // end GPU assembly
1773:   { /* create static point data, Jacobian called first, only one vertex copy */
1774:     PetscReal *invJe, *ww, *xx, *yy, *zz = NULL, *invJ_a;
1775:     PetscInt   outer_ipidx, outer_ej, grid, nip_glb = 0;
1776:     PetscFE    fe;
1777:     PetscCall(PetscLogEventBegin(ctx->events[7], 0, 0, 0, 0));
1778:     PetscCall(PetscInfo(ctx->plex[0], "Initialize static data\n"));
1779:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) nip_glb += Nq * numCells[grid];
1780:     /* collect f data, first time is for Jacobian, but make mass now */
1781:     if (ctx->verbose != 0) {
1782:       PetscInt ncells = 0, N;
1783:       MatInfo  info;
1784:       PetscCall(MatGetInfo(ctx->J, MAT_LOCAL, &info));
1785:       PetscCall(MatGetSize(ctx->J, &N, NULL));
1786:       for (PetscInt grid = 0; grid < ctx->num_grids; grid++) ncells += numCells[grid];
1787:       PetscCall(PetscPrintf(PETSC_COMM_WORLD, "%d) %s %" PetscInt_FMT " IPs, %" PetscInt_FMT " cells total, Nb=%" PetscInt_FMT ", Nq=%" PetscInt_FMT ", dim=%" PetscInt_FMT ", Tab: Nb=%" PetscInt_FMT " Nf=%" PetscInt_FMT " Np=%" PetscInt_FMT " cdim=%" PetscInt_FMT " N=%" PetscInt_FMT " nnz= %" PetscInt_FMT "\n", 0, "FormLandau", nip_glb, ncells, Nb, Nq, dim, Nb,
1788:                             ctx->num_species, Nb, dim, N, (PetscInt)info.nz_used));
1789:     }
1790:     PetscCall(PetscMalloc4(nip_glb, &ww, nip_glb, &xx, nip_glb, &yy, nip_glb * dim * dim, &invJ_a));
1791:     if (dim == 3) PetscCall(PetscMalloc1(nip_glb, &zz));
1792:     if (ctx->use_energy_tensor_trick) {
1793:       PetscCall(PetscFECreateDefault(PETSC_COMM_SELF, dim, 1, ctx->simplex, prefix, PETSC_DECIDE, &fe));
1794:       PetscCall(PetscObjectSetName((PetscObject)fe, "energy"));
1795:     }
1796:     /* init each grids static data - no batch */
1797:     for (grid = 0, outer_ipidx = 0, outer_ej = 0; grid < ctx->num_grids; grid++) { // OpenMP (once)
1798:       Vec          v2_2 = NULL;                                                    // projected function: v^2/2 for non-relativistic, gamma... for relativistic
1799:       PetscSection e_section;
1800:       DM           dmEnergy;
1801:       PetscInt     cStart, cEnd, ej;

1803:       PetscCall(DMPlexGetHeightStratum(ctx->plex[grid], 0, &cStart, &cEnd));
1804:       // prep energy trick, get v^2 / 2 vector
1805:       if (ctx->use_energy_tensor_trick) {
1806:         PetscErrorCode (*energyf[1])(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *) = {ctx->use_relativistic_corrections ? gamma_m1_f : energy_f};
1807:         Vec        glob_v2;
1808:         PetscReal *c2_0[1], data[1] = {PetscSqr(C_0(ctx->v_0))};

1810:         PetscCall(DMClone(ctx->plex[grid], &dmEnergy));
1811:         PetscCall(PetscObjectSetName((PetscObject)dmEnergy, "energy"));
1812:         PetscCall(DMSetField(dmEnergy, 0, NULL, (PetscObject)fe));
1813:         PetscCall(DMCreateDS(dmEnergy));
1814:         PetscCall(DMGetLocalSection(dmEnergy, &e_section));
1815:         PetscCall(DMGetGlobalVector(dmEnergy, &glob_v2));
1816:         PetscCall(PetscObjectSetName((PetscObject)glob_v2, "trick"));
1817:         c2_0[0] = &data[0];
1818:         PetscCall(DMProjectFunction(dmEnergy, 0., energyf, (void **)c2_0, INSERT_ALL_VALUES, glob_v2));
1819:         PetscCall(DMGetLocalVector(dmEnergy, &v2_2));
1820:         PetscCall(VecZeroEntries(v2_2)); /* zero BCs so don't set */
1821:         PetscCall(DMGlobalToLocalBegin(dmEnergy, glob_v2, INSERT_VALUES, v2_2));
1822:         PetscCall(DMGlobalToLocalEnd(dmEnergy, glob_v2, INSERT_VALUES, v2_2));
1823:         PetscCall(DMViewFromOptions(dmEnergy, NULL, "-energy_dm_view"));
1824:         PetscCall(VecViewFromOptions(glob_v2, NULL, "-energy_vec_view"));
1825:         PetscCall(DMRestoreGlobalVector(dmEnergy, &glob_v2));
1826:       }
1827:       /* append part of the IP data for each grid */
1828:       for (ej = 0; ej < numCells[grid]; ++ej, ++outer_ej) {
1829:         PetscScalar *coefs = NULL;
1830:         PetscReal    vj[LANDAU_MAX_NQND * LANDAU_DIM], detJj[LANDAU_MAX_NQND], Jdummy[LANDAU_MAX_NQND * LANDAU_DIM * LANDAU_DIM], c0 = C_0(ctx->v_0), c02 = PetscSqr(c0);
1831:         invJe = invJ_a + outer_ej * Nq * dim * dim;
1832:         PetscCall(DMPlexComputeCellGeometryFEM(ctx->plex[grid], ej + cStart, quad, vj, Jdummy, invJe, detJj));
1833:         if (ctx->use_energy_tensor_trick) PetscCall(DMPlexVecGetClosure(dmEnergy, e_section, v2_2, ej + cStart, NULL, &coefs));
1834:         /* create static point data */
1835:         for (PetscInt qj = 0; qj < Nq; qj++, outer_ipidx++) {
1836:           const PetscInt   gidx = outer_ipidx;
1837:           const PetscReal *invJ = &invJe[qj * dim * dim];
1838:           ww[gidx]              = detJj[qj] * quadWeights[qj];
1839:           if (dim == 2) ww[gidx] *= vj[qj * dim + 0]; /* cylindrical coordinate, w/o 2pi */
1840:           // get xx, yy, zz
1841:           if (ctx->use_energy_tensor_trick) {
1842:             double                 refSpaceDer[3], eGradPhi[3];
1843:             const PetscReal *const DD = Tf[0]->T[1];
1844:             const PetscReal       *Dq = &DD[qj * Nb * dim];
1845:             for (PetscInt d = 0; d < 3; ++d) refSpaceDer[d] = eGradPhi[d] = 0.0;
1846:             for (PetscInt b = 0; b < Nb; ++b) {
1847:               for (PetscInt d = 0; d < dim; ++d) refSpaceDer[d] += Dq[b * dim + d] * PetscRealPart(coefs[b]);
1848:             }
1849:             xx[gidx] = 1e10;
1850:             if (ctx->use_relativistic_corrections) {
1851:               double dg2_c2 = 0;
1852:               //for (PetscInt d = 0; d < dim; ++d) refSpaceDer[d] *= c02;
1853:               for (PetscInt d = 0; d < dim; ++d) dg2_c2 += PetscSqr(refSpaceDer[d]);
1854:               dg2_c2 *= (double)c02;
1855:               if (dg2_c2 >= .999) {
1856:                 xx[gidx] = vj[qj * dim + 0]; /* coordinate */
1857:                 yy[gidx] = vj[qj * dim + 1];
1858:                 if (dim == 3) zz[gidx] = vj[qj * dim + 2];
1859:                 PetscCall(PetscPrintf(ctx->comm, "Error: %12.5e %" PetscInt_FMT ".%" PetscInt_FMT ") dg2/c02 = %12.5e x= %12.5e %12.5e %12.5e\n", (double)PetscSqrtReal(xx[gidx] * xx[gidx] + yy[gidx] * yy[gidx] + zz[gidx] * zz[gidx]), ej, qj, dg2_c2, (double)xx[gidx], (double)yy[gidx], (double)zz[gidx]));
1860:               } else {
1861:                 PetscReal fact = c02 / PetscSqrtReal(1. - dg2_c2);
1862:                 for (PetscInt d = 0; d < dim; ++d) refSpaceDer[d] *= fact;
1863:                 // could test with other point u' that (grad - grad') * U (refSpaceDer, refSpaceDer') == 0
1864:               }
1865:             }
1866:             if (xx[gidx] == 1e10) {
1867:               for (PetscInt d = 0; d < dim; ++d) {
1868:                 for (PetscInt e = 0; e < dim; ++e) eGradPhi[d] += invJ[e * dim + d] * refSpaceDer[e];
1869:               }
1870:               xx[gidx] = eGradPhi[0];
1871:               yy[gidx] = eGradPhi[1];
1872:               if (dim == 3) zz[gidx] = eGradPhi[2];
1873:             }
1874:           } else {
1875:             xx[gidx] = vj[qj * dim + 0]; /* coordinate */
1876:             yy[gidx] = vj[qj * dim + 1];
1877:             if (dim == 3) zz[gidx] = vj[qj * dim + 2];
1878:           }
1879:         } /* q */
1880:         if (ctx->use_energy_tensor_trick) PetscCall(DMPlexVecRestoreClosure(dmEnergy, e_section, v2_2, ej + cStart, NULL, &coefs));
1881:       } /* ej */
1882:       if (ctx->use_energy_tensor_trick) {
1883:         PetscCall(DMRestoreLocalVector(dmEnergy, &v2_2));
1884:         PetscCall(DMDestroy(&dmEnergy));
1885:       }
1886:     } /* grid */
1887:     if (ctx->use_energy_tensor_trick) PetscCall(PetscFEDestroy(&fe));
1888:     /* cache static data */
1889:     if (ctx->deviceType == LANDAU_KOKKOS) {
1890: #if PetscDefined(HAVE_KOKKOS)
1891:       PetscCall(LandauKokkosStaticDataSet(ctx->plex[0], Nq, Nb, ctx->batch_sz, ctx->num_grids, numCells, ctx->species_offset, ctx->mat_offset, nu_alpha, nu_beta, invMass, (PetscReal *)ctx->lambdas, invJ_a, xx, yy, zz, ww, &ctx->SData_d));
1892:       /* free */
1893:       PetscCall(PetscFree4(ww, xx, yy, invJ_a));
1894:       if (dim == 3) PetscCall(PetscFree(zz));
1895: #else
1896:       SETERRQ(ctx->comm, PETSC_ERR_ARG_WRONG, "-landau_device_type kokkos not built");
1897: #endif
1898:     } else {                                                                                                                                                                   /* CPU version, just copy in, only use part */
1899:       PetscReal *nu_alpha_p = (PetscReal *)ctx->SData_d.alpha, *nu_beta_p = (PetscReal *)ctx->SData_d.beta, *invMass_p = (PetscReal *)ctx->SData_d.invMass, *lambdas_p = NULL; // why set these ?
1900:       ctx->SData_d.w    = (void *)ww;
1901:       ctx->SData_d.x    = (void *)xx;
1902:       ctx->SData_d.y    = (void *)yy;
1903:       ctx->SData_d.z    = (void *)zz;
1904:       ctx->SData_d.invJ = (void *)invJ_a;
1905:       PetscCall(PetscMalloc4(ctx->num_species, &nu_alpha_p, ctx->num_species, &nu_beta_p, ctx->num_species, &invMass_p, LANDAU_MAX_GRIDS * LANDAU_MAX_GRIDS, &lambdas_p));
1906:       for (PetscInt ii = 0; ii < ctx->num_species; ii++) {
1907:         nu_alpha_p[ii] = nu_alpha[ii];
1908:         nu_beta_p[ii]  = nu_beta[ii];
1909:         invMass_p[ii]  = invMass[ii];
1910:       }
1911:       ctx->SData_d.alpha   = (void *)nu_alpha_p;
1912:       ctx->SData_d.beta    = (void *)nu_beta_p;
1913:       ctx->SData_d.invMass = (void *)invMass_p;
1914:       ctx->SData_d.lambdas = (void *)lambdas_p;
1915:       for (PetscInt grid = 0; grid < LANDAU_MAX_GRIDS; grid++) {
1916:         PetscReal (*lambdas)[LANDAU_MAX_GRIDS][LANDAU_MAX_GRIDS] = (PetscReal (*)[LANDAU_MAX_GRIDS][LANDAU_MAX_GRIDS])ctx->SData_d.lambdas;
1917:         for (PetscInt gridj = 0; gridj < LANDAU_MAX_GRIDS; gridj++) (*lambdas)[grid][gridj] = ctx->lambdas[grid][gridj];
1918:       }
1919:     }
1920:     PetscCall(PetscLogEventEnd(ctx->events[7], 0, 0, 0, 0));
1921:   } // initialize
1922:   PetscFunctionReturn(PETSC_SUCCESS);
1923: }

1925: /* < v, u > */
1926: static void g0_1(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[])
1927: {
1928:   g0[0] = 1.;
1929: }

1931: /* < v, u > */
1932: static void g0_fake(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[])
1933: {
1934:   static double ttt = 1e-12;
1935:   g0[0]             = ttt++;
1936: }

1938: /* < v, u > */
1939: static void g0_r(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[])
1940: {
1941:   g0[0] = 2. * PETSC_PI * x[0];
1942: }

1944: /* Creates ctx->J sparsity pattern without real data; supports field-major ordering */
1945: static PetscErrorCode LandauCreateJacobianMatrix(MPI_Comm comm, Vec X, IS grid_batch_is_inv[LANDAU_MAX_GRIDS], LandauCtx *ctx)
1946: {
1947:   PetscInt *idxs = NULL;
1948:   Mat       subM[LANDAU_MAX_GRIDS];

1950:   PetscFunctionBegin;
1951:   if (!ctx->gpu_assembly) { /* we need GPU object with GPU assembly */
1952:     PetscFunctionReturn(PETSC_SUCCESS);
1953:   }
1954:   // get the RCM for this grid to separate out species into blocks -- create 'idxs' & 'ctx->batch_is' -- not used
1955:   if (ctx->gpu_assembly && ctx->jacobian_field_major_order) PetscCall(PetscMalloc1(ctx->mat_offset[ctx->num_grids] * ctx->batch_sz, &idxs));
1956:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
1957:     const PetscInt *values, n = ctx->mat_offset[grid + 1] - ctx->mat_offset[grid];
1958:     Mat             gMat;
1959:     DM              massDM;
1960:     PetscDS         prob;
1961:     Vec             tvec;
1962:     // get "mass" matrix for reordering
1963:     PetscCall(DMClone(ctx->plex[grid], &massDM));
1964:     PetscCall(DMCopyFields(ctx->plex[grid], PETSC_DETERMINE, PETSC_DETERMINE, massDM));
1965:     PetscCall(DMCreateDS(massDM));
1966:     PetscCall(DMGetDS(massDM, &prob));
1967:     for (PetscInt ix = 0, ii = ctx->species_offset[grid]; ii < ctx->species_offset[grid + 1]; ii++, ix++) PetscCall(PetscDSSetJacobian(prob, ix, ix, g0_fake, NULL, NULL, NULL));
1968:     PetscCall(PetscOptionsInsertString(NULL, "-dm_preallocate_only")); // this trick is need to both sparsify the matrix and avoid runtime error
1969:     PetscCall(DMCreateMatrix(massDM, &gMat));
1970:     PetscCall(PetscOptionsInsertString(NULL, "-dm_preallocate_only false"));
1971:     PetscCall(MatSetOption(gMat, MAT_STRUCTURALLY_SYMMETRIC, PETSC_TRUE));
1972:     PetscCall(MatSetOption(gMat, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE));
1973:     PetscCall(DMCreateLocalVector(ctx->plex[grid], &tvec));
1974:     PetscCall(DMPlexSNESComputeJacobianFEM(massDM, tvec, gMat, gMat, ctx));
1975:     PetscCall(MatViewFromOptions(gMat, NULL, "-dm_landau_reorder_mat_view"));
1976:     PetscCall(DMDestroy(&massDM));
1977:     PetscCall(VecDestroy(&tvec));
1978:     subM[grid] = gMat;
1979:     if (ctx->gpu_assembly && ctx->jacobian_field_major_order) {
1980:       MatOrderingType rtype = MATORDERINGRCM;
1981:       IS              isrow, isicol;
1982:       PetscCall(MatGetOrdering(gMat, rtype, &isrow, &isicol));
1983:       PetscCall(ISInvertPermutation(isrow, PETSC_DECIDE, &grid_batch_is_inv[grid]));
1984:       PetscCall(ISGetIndices(isrow, &values));
1985:       for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) { // add batch size DMs for this species grid
1986: #if !defined(LANDAU_SPECIES_MAJOR)
1987:         PetscInt N = ctx->mat_offset[ctx->num_grids], n0 = ctx->mat_offset[grid] + b_id * N;
1988:         for (PetscInt ii = 0; ii < n; ++ii) idxs[n0 + ii] = values[ii] + n0;
1989: #else
1990:         PetscInt n0 = ctx->mat_offset[grid] * ctx->batch_sz + b_id * n;
1991:         for (PetscInt ii = 0; ii < n; ++ii) idxs[n0 + ii] = values[ii] + n0;
1992: #endif
1993:       }
1994:       PetscCall(ISRestoreIndices(isrow, &values));
1995:       PetscCall(ISDestroy(&isrow));
1996:       PetscCall(ISDestroy(&isicol));
1997:     }
1998:   }
1999:   if (ctx->gpu_assembly && ctx->jacobian_field_major_order) PetscCall(ISCreateGeneral(comm, ctx->mat_offset[ctx->num_grids] * ctx->batch_sz, idxs, PETSC_OWN_POINTER, &ctx->batch_is));
2000:   // get a block matrix
2001:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
2002:     Mat      B = subM[grid];
2003:     PetscInt nloc, nzl, *colbuf, row, COL_BF_SIZE = 1024;
2004:     PetscCall(PetscMalloc(sizeof(*colbuf) * COL_BF_SIZE, &colbuf));
2005:     PetscCall(MatGetSize(B, &nloc, NULL));
2006:     for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) {
2007:       const PetscInt     moffset = LAND_MOFFSET(b_id, grid, ctx->batch_sz, ctx->num_grids, ctx->mat_offset);
2008:       const PetscInt    *cols;
2009:       const PetscScalar *vals;
2010:       for (PetscInt i = 0; i < nloc; i++) {
2011:         PetscCall(MatGetRow(B, i, &nzl, NULL, NULL));
2012:         if (nzl > COL_BF_SIZE) {
2013:           PetscCall(PetscFree(colbuf));
2014:           PetscCall(PetscInfo(ctx->plex[grid], "Realloc buffer %" PetscInt_FMT " to %" PetscInt_FMT " (row size %" PetscInt_FMT ") \n", COL_BF_SIZE, 2 * COL_BF_SIZE, nzl));
2015:           COL_BF_SIZE = nzl;
2016:           PetscCall(PetscMalloc(sizeof(*colbuf) * COL_BF_SIZE, &colbuf));
2017:         }
2018:         PetscCall(MatGetRow(B, i, &nzl, &cols, &vals));
2019:         for (PetscInt j = 0; j < nzl; j++) colbuf[j] = cols[j] + moffset;
2020:         row = i + moffset;
2021:         PetscCall(MatSetValues(ctx->J, 1, &row, nzl, colbuf, vals, INSERT_VALUES));
2022:         PetscCall(MatRestoreRow(B, i, &nzl, &cols, &vals));
2023:       }
2024:     }
2025:     PetscCall(PetscFree(colbuf));
2026:   }
2027:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) PetscCall(MatDestroy(&subM[grid]));
2028:   PetscCall(MatAssemblyBegin(ctx->J, MAT_FINAL_ASSEMBLY));
2029:   PetscCall(MatAssemblyEnd(ctx->J, MAT_FINAL_ASSEMBLY));

2031:   // debug
2032:   PetscCall(MatViewFromOptions(ctx->J, NULL, "-dm_landau_mat_view"));
2033:   if (ctx->gpu_assembly && ctx->jacobian_field_major_order) {
2034:     Mat mat_block_order;
2035:     PetscCall(MatCreateSubMatrix(ctx->J, ctx->batch_is, ctx->batch_is, MAT_INITIAL_MATRIX, &mat_block_order)); // use MatPermute
2036:     PetscCall(MatViewFromOptions(mat_block_order, NULL, "-dm_landau_mat_view"));
2037:     PetscCall(MatDestroy(&mat_block_order));
2038:     PetscCall(VecScatterCreate(X, ctx->batch_is, X, NULL, &ctx->plex_batch));
2039:     PetscCall(VecDuplicate(X, &ctx->work_vec));
2040:   }
2041:   PetscFunctionReturn(PETSC_SUCCESS);
2042: }

2044: static void LandauSphereMapping(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f[])
2045: {
2046:   PetscReal u_max = 0, u_norm = 0, scale, square_inner_radius = PetscRealPart(constants[0]), square_radius = PetscRealPart(constants[1]);

2048:   for (PetscInt d = 0; d < dim; ++d) {
2049:     PetscReal val = PetscAbsReal(PetscRealPart(u[d]));
2050:     if (val > u_max) u_max = val;
2051:     u_norm += PetscRealPart(u[d]) * PetscRealPart(u[d]);
2052:   }
2053:   u_norm = PetscSqrtReal(u_norm);

2055:   if (u_max < square_inner_radius) {
2056:     for (PetscInt d = 0; d < dim; ++d) f[d] = u[d];
2057:     return;
2058:   }

2060:   /* Map rays linearly from inner cube (|u|=square_inner_radius) to outer cube (|u|=square_radius),
2061:      projecting outer-cube points onto the sphere of radius square_radius*sqrt(3). */
2062:   if (u_max > square_radius + 1e-5) (void)PetscPrintf(PETSC_COMM_SELF, "Error: Point outside outer radius: u_max %g > %g\n", (double)u_max, (double)square_radius);
2063:   /*  if (PetscAbsReal(u_max - square_inner_radius) < 1e-5 || PetscAbsReal(u_max - square_radius) < 1e-5) {
2064:     (void)PetscPrintf(PETSC_COMM_SELF, "Warning: Point near corner of inner and outer cube: u_max %g, inner %g, outer %g\n", (double)u_max, (double)square_inner_radius, (double)square_radius);
2065:   } */
2066:   {
2067:     PetscReal u_0_norm  = u_norm * square_inner_radius / u_max;
2068:     PetscReal R_max     = square_radius * PetscSqrtReal((PetscReal)dim);
2069:     PetscReal t         = (u_max - square_inner_radius) / (square_radius - square_inner_radius);
2070:     PetscReal rho_prime = (1.0 - t) * u_0_norm + t * R_max;
2071:     scale               = rho_prime / u_norm;
2072:   }
2073:   for (PetscInt d = 0; d < dim; ++d) f[d] = u[d] * scale;
2074: }

2076: static PetscErrorCode LandauSphereMesh(DM dm, PetscReal inner, PetscReal radius)
2077: {
2078:   DM          cdm;
2079:   PetscDS     cds;
2080:   PetscScalar consts[2];

2082:   PetscFunctionBegin;
2083:   consts[0] = inner;
2084:   consts[1] = radius;
2085:   PetscCall(DMGetCoordinateDM(dm, &cdm));
2086:   PetscCall(DMGetDS(cdm, &cds));
2087:   PetscCall(PetscDSSetConstants(cds, 2, consts));
2088:   PetscCall(DMPlexRemapGeometry(dm, 0.0, LandauSphereMapping));
2089:   PetscFunctionReturn(PETSC_SUCCESS);
2090: }

2092: PetscErrorCode DMPlexLandauCreateMassMatrix(DM pack, Mat *Amat);

2094: /*@C
2095:   DMPlexLandauCreateVelocitySpace - Create a `DMPLEX` velocity space mesh

2097:   Collective

2099:   Input Parameters:
2100: + comm   - The MPI communicator
2101: . dim    - velocity space dimension (2 for axisymmetric, 3 for full 3X + 3V solver)
2102: - prefix - prefix for options (not tested)

2104:   Output Parameters:
2105: + pack - The `DM` object representing the mesh
2106: . X    - A vector (user destroys)
2107: - J    - Optional matrix (object destroys)

2109:   Level: beginner

2111: .seealso: `DMPlexCreate()`, `DMPlexLandauDestroyVelocitySpace()`
2112:  @*/
2113: PetscErrorCode DMPlexLandauCreateVelocitySpace(MPI_Comm comm, PetscInt dim, const char prefix[], Vec *X, Mat *J, DM *pack)
2114: {
2115:   LandauCtx *ctx;
2116:   Vec        Xsub[LANDAU_MAX_GRIDS];
2117:   IS         grid_batch_is_inv[LANDAU_MAX_GRIDS];

2119:   PetscFunctionBegin;
2120:   PetscCheck(dim == 2 || dim == 3, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Only 2D and 3D supported");
2121:   PetscCheck(LANDAU_DIM == dim, PETSC_COMM_SELF, PETSC_ERR_PLIB, "dim %" PetscInt_FMT " != LANDAU_DIM %d", dim, LANDAU_DIM);
2122:   PetscCall(PetscNew(&ctx));
2123:   ctx->comm = comm; /* used for diagnostics and global errors */
2124:   /* process options */
2125:   PetscCall(ProcessOptions(ctx, prefix));
2126:   if (dim == 2) ctx->use_relativistic_corrections = PETSC_FALSE;
2127:   /* Create Mesh */
2128:   PetscCall(DMCompositeCreate(PETSC_COMM_SELF, pack));
2129:   PetscCall(PetscLogEventBegin(ctx->events[13], 0, 0, 0, 0));
2130:   PetscCall(PetscLogEventBegin(ctx->events[15], 0, 0, 0, 0));
2131:   PetscCall(LandauDMCreateVMeshes(PETSC_COMM_SELF, dim, prefix, ctx, *pack)); // creates grids (Forest of AMR)
2132:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
2133:     /* create FEM */
2134:     PetscCall(SetupDS(ctx->plex[grid], dim, grid, prefix, ctx));
2135:     /* set initial state */
2136:     PetscCall(DMCreateGlobalVector(ctx->plex[grid], &Xsub[grid]));
2137:     PetscCall(PetscObjectSetName((PetscObject)Xsub[grid], "u_orig"));
2138:     /* initial static refinement, no solve */
2139:     PetscCall(LandauSetInitialCondition(ctx->plex[grid], Xsub[grid], grid, 0, 1, ctx));
2140:     /* forest refinement - forest goes in (if forest), plex comes out */
2141:     if (ctx->use_p4est) {
2142:       DM plex;
2143:       PetscCall(adapt(grid, ctx, &Xsub[grid])); // forest goes in, plex comes out
2144:       // convert to plex, all done with this level
2145:       PetscCall(DMConvert(ctx->plex[grid], DMPLEX, &plex));
2146:       PetscCall(DMDestroy(&ctx->plex[grid]));
2147:       ctx->plex[grid] = plex;
2148:     } else if (ctx->sphere && dim == 3) {
2149:       if (ctx->map_sphere) PetscCall(LandauSphereMesh(ctx->plex[grid], ctx->radius[grid] * ctx->sphere_inner_radius_90degree[grid], ctx->radius[grid]));
2150:       PetscCall(LandauSetInitialCondition(ctx->plex[grid], Xsub[grid], grid, 0, 1, ctx));
2151:     }
2152:     if (grid == 0) {
2153:       PetscCall(DMViewFromOptions(ctx->plex[grid], NULL, "-dm_landau_amr_dm_view"));
2154:       PetscCall(VecSetOptionsPrefix(Xsub[grid], prefix));
2155:       PetscCall(VecViewFromOptions(Xsub[grid], NULL, "-dm_landau_amr_vec_view"));
2156:     }
2157: #if !defined(LANDAU_SPECIES_MAJOR)
2158:     PetscCall(DMCompositeAddDM(*pack, ctx->plex[grid]));
2159: #else
2160:     for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) { // add batch size DMs for this species grid
2161:       PetscCall(DMCompositeAddDM(*pack, ctx->plex[grid]));
2162:     }
2163: #endif
2164:     PetscCall(DMSetApplicationContext(ctx->plex[grid], ctx));
2165:   }
2166: #if !defined(LANDAU_SPECIES_MAJOR)
2167:   // stack the batched DMs, could do it all here!!! b_id=0
2168:   for (PetscInt b_id = 1; b_id < ctx->batch_sz; b_id++) {
2169:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) PetscCall(DMCompositeAddDM(*pack, ctx->plex[grid]));
2170:   }
2171: #endif
2172:   // create ctx->mat_offset
2173:   ctx->mat_offset[0] = 0;
2174:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
2175:     PetscInt n;
2176:     PetscCall(VecGetLocalSize(Xsub[grid], &n));
2177:     ctx->mat_offset[grid + 1] = ctx->mat_offset[grid] + n;
2178:   }
2179:   // creat DM & Jac
2180:   PetscCall(DMSetApplicationContext(*pack, ctx));
2181:   PetscCall(PetscOptionsInsertString(NULL, "-dm_preallocate_only"));
2182:   PetscCall(DMCreateMatrix(*pack, &ctx->J));
2183:   PetscCall(PetscOptionsInsertString(NULL, "-dm_preallocate_only false"));
2184:   PetscCall(MatSetOption(ctx->J, MAT_STRUCTURALLY_SYMMETRIC, PETSC_TRUE));
2185:   PetscCall(MatSetOption(ctx->J, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE));
2186:   PetscCall(PetscObjectSetName((PetscObject)ctx->J, "Jac"));
2187:   // construct initial conditions in X
2188:   PetscCall(DMCreateGlobalVector(*pack, X));
2189:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
2190:     PetscInt n;
2191:     PetscCall(VecGetLocalSize(Xsub[grid], &n));
2192:     for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) {
2193:       PetscScalar const *values;
2194:       const PetscInt     moffset = LAND_MOFFSET(b_id, grid, ctx->batch_sz, ctx->num_grids, ctx->mat_offset);
2195:       PetscCall(LandauSetInitialCondition(ctx->plex[grid], Xsub[grid], grid, b_id, ctx->batch_sz, ctx));
2196:       PetscCall(VecGetArrayRead(Xsub[grid], &values)); // Drop whole grid in Plex ordering
2197:       for (PetscInt i = 0, idx = moffset; i < n; i++, idx++) PetscCall(VecSetValue(*X, idx, values[i], INSERT_VALUES));
2198:       PetscCall(VecRestoreArrayRead(Xsub[grid], &values));
2199:     }
2200:   }
2201:   // cleanup
2202:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) PetscCall(VecDestroy(&Xsub[grid]));
2203:   /* check for correct matrix type */
2204:   if (ctx->gpu_assembly) { /* we need GPU object with GPU assembly */
2205:     PetscBool flg;
2206:     if (ctx->deviceType == LANDAU_KOKKOS) {
2207:       PetscCall(PetscObjectTypeCompareAny((PetscObject)ctx->J, &flg, MATSEQAIJKOKKOS, MATMPIAIJKOKKOS, MATAIJKOKKOS, ""));
2208: #if PetscDefined(HAVE_KOKKOS)
2209:       PetscCheck(flg, ctx->comm, PETSC_ERR_ARG_WRONG, "must use '-dm_mat_type aijkokkos -dm_vec_type kokkos' for GPU assembly and Kokkos or use '-dm_landau_device_type cpu'");
2210: #else
2211:       PetscCheck(flg, ctx->comm, PETSC_ERR_ARG_WRONG, "must configure with '--download-kokkos-kernels' for GPU assembly and Kokkos or use '-dm_landau_device_type cpu'");
2212: #endif
2213:     }
2214:   }
2215:   PetscCall(PetscLogEventEnd(ctx->events[15], 0, 0, 0, 0));

2217:   // create field major ordering
2218:   ctx->work_vec   = NULL;
2219:   ctx->plex_batch = NULL;
2220:   ctx->batch_is   = NULL;
2221:   for (PetscInt i = 0; i < LANDAU_MAX_GRIDS; i++) grid_batch_is_inv[i] = NULL;
2222:   PetscCall(PetscLogEventBegin(ctx->events[12], 0, 0, 0, 0));
2223:   PetscCall(LandauCreateJacobianMatrix(comm, *X, grid_batch_is_inv, ctx));
2224:   PetscCall(PetscLogEventEnd(ctx->events[12], 0, 0, 0, 0));

2226:   // create AMR GPU assembly maps and static GPU data
2227:   PetscCall(CreateStaticData(dim, grid_batch_is_inv, prefix, ctx));

2229:   PetscCall(PetscLogEventEnd(ctx->events[13], 0, 0, 0, 0));

2231:   // create mass matrix
2232:   PetscCall(DMPlexLandauCreateMassMatrix(*pack, NULL));

2234:   if (J) *J = ctx->J;

2236:   if (ctx->gpu_assembly && ctx->jacobian_field_major_order) {
2237:     PetscContainer container;
2238:     // cache ctx for KSP with batch/field major Jacobian ordering -ksp_type gmres/etc -dm_landau_jacobian_field_major_order
2239:     PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
2240:     PetscCall(PetscContainerSetPointer(container, (void *)ctx));
2241:     PetscCall(PetscObjectCompose((PetscObject)ctx->J, "LandauCtx", (PetscObject)container));
2242:     PetscCall(PetscContainerDestroy(&container));
2243:     // batch solvers need to map -- can batch solvers work
2244:     PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
2245:     PetscCall(PetscContainerSetPointer(container, (void *)ctx->plex_batch));
2246:     PetscCall(PetscObjectCompose((PetscObject)ctx->J, "plex_batch_is", (PetscObject)container));
2247:     PetscCall(PetscContainerDestroy(&container));
2248:   }
2249:   // for batch solvers
2250:   {
2251:     PetscContainer container;
2252:     PetscInt      *pNf;
2253:     PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
2254:     PetscCall(PetscMalloc1(sizeof(*pNf), &pNf));
2255:     *pNf = ctx->batch_sz;
2256:     PetscCall(PetscContainerSetPointer(container, (void *)pNf));
2257:     PetscCall(PetscContainerSetCtxDestroy(container, PetscCtxDestroyDefault));
2258:     PetscCall(PetscObjectCompose((PetscObject)ctx->J, "batch size", (PetscObject)container));
2259:     PetscCall(PetscContainerDestroy(&container));
2260:   }
2261:   PetscFunctionReturn(PETSC_SUCCESS);
2262: }

2264: /*@C
2265:   DMPlexLandauAccess - Access to the distribution function with user callback

2267:   Collective

2269:   Input Parameters:
2270: + pack     - the `DMCOMPOSITE`
2271: . func     - call back function
2272: - user_ctx - application context

2274:   Input/Output Parameter:
2275: . X - Vector to data to

2277:   Level: advanced

2279: .seealso: `DMPlexLandauCreateVelocitySpace()`
2280:  @*/
2281: PetscErrorCode DMPlexLandauAccess(DM pack, Vec X, PetscErrorCode (*func)(DM, Vec, PetscInt, PetscInt, PetscInt, void *), void *user_ctx)
2282: {
2283:   LandauCtx *ctx;

2285:   PetscFunctionBegin;
2286:   PetscCall(DMGetApplicationContext(pack, &ctx)); // uses ctx->num_grids; ctx->plex[grid]; ctx->batch_sz; ctx->mat_offset
2287:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
2288:     PetscInt dim, n;
2289:     PetscCall(DMGetDimension(pack, &dim));
2290:     for (PetscInt sp = ctx->species_offset[grid], i0 = 0; sp < ctx->species_offset[grid + 1]; sp++, i0++) {
2291:       Vec      vec;
2292:       PetscInt vf[1] = {i0};
2293:       IS       vis;
2294:       DM       vdm;
2295:       PetscCall(DMCreateSubDM(ctx->plex[grid], 1, vf, &vis, &vdm));
2296:       PetscCall(DMSetApplicationContext(vdm, ctx)); // the user might want this
2297:       PetscCall(DMCreateGlobalVector(vdm, &vec));
2298:       PetscCall(VecGetSize(vec, &n));
2299:       for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) {
2300:         const PetscInt moffset = LAND_MOFFSET(b_id, grid, ctx->batch_sz, ctx->num_grids, ctx->mat_offset);
2301:         PetscCall(VecZeroEntries(vec));
2302:         /* Add your data with 'dm' for species 'sp' to 'vec' */
2303:         PetscCall(func(vdm, vec, i0, grid, b_id, user_ctx));
2304:         /* add to global */
2305:         PetscScalar const *values;
2306:         const PetscInt    *offsets;
2307:         PetscCall(VecGetArrayRead(vec, &values));
2308:         PetscCall(ISGetIndices(vis, &offsets));
2309:         for (PetscInt i = 0; i < n; i++) PetscCall(VecSetValue(X, moffset + offsets[i], values[i], ADD_VALUES));
2310:         PetscCall(VecRestoreArrayRead(vec, &values));
2311:         PetscCall(ISRestoreIndices(vis, &offsets));
2312:       } // batch
2313:       PetscCall(VecDestroy(&vec));
2314:       PetscCall(ISDestroy(&vis));
2315:       PetscCall(DMDestroy(&vdm));
2316:     }
2317:   } // grid
2318:   PetscFunctionReturn(PETSC_SUCCESS);
2319: }

2321: /*@
2322:   DMPlexLandauDestroyVelocitySpace - Destroy a `DMPLEX` velocity space mesh

2324:   Collective

2326:   Input/Output Parameters:
2327: . dm - the `DM` to destroy

2329:   Level: beginner

2331: .seealso: `DMPlexLandauCreateVelocitySpace()`
2332:  @*/
2333: PetscErrorCode DMPlexLandauDestroyVelocitySpace(DM *dm)
2334: {
2335:   LandauCtx *ctx;

2337:   PetscFunctionBegin;
2338:   PetscCall(DMGetApplicationContext(*dm, &ctx));
2339:   PetscCall(MatDestroy(&ctx->M));
2340:   PetscCall(MatDestroy(&ctx->J));
2341:   for (PetscInt ii = 0; ii < ctx->num_species; ii++) PetscCall(PetscFEDestroy(&ctx->fe[ii]));
2342:   PetscCall(ISDestroy(&ctx->batch_is));
2343:   PetscCall(VecDestroy(&ctx->work_vec));
2344:   PetscCall(VecScatterDestroy(&ctx->plex_batch));
2345:   if (ctx->deviceType == LANDAU_KOKKOS) {
2346: #if PetscDefined(HAVE_KOKKOS)
2347:     PetscCall(LandauKokkosStaticDataClear(&ctx->SData_d));
2348: #else
2349:     SETERRQ(ctx->comm, PETSC_ERR_ARG_WRONG, "-landau_device_type %s not built", "kokkos");
2350: #endif
2351:   } else {
2352:     if (ctx->SData_d.x) { /* in a CPU run */
2353:       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;
2354:       LandauIdx *coo_elem_offsets = (LandauIdx *)ctx->SData_d.coo_elem_offsets, *coo_elem_fullNb = (LandauIdx *)ctx->SData_d.coo_elem_fullNb, (*coo_elem_point_offsets)[LANDAU_MAX_NQND + 1] = (LandauIdx(*)[LANDAU_MAX_NQND + 1]) ctx->SData_d.coo_elem_point_offsets;
2355:       PetscCall(PetscFree4(ww, xx, yy, invJ));
2356:       PetscCall(PetscFree(zz));
2357:       if (coo_elem_offsets) PetscCall(PetscFree3(coo_elem_offsets, coo_elem_fullNb, coo_elem_point_offsets)); // could be NULL
2358:       PetscCall(PetscFree4(ctx->SData_d.alpha, ctx->SData_d.beta, ctx->SData_d.invMass, ctx->SData_d.lambdas));
2359:     }
2360:   }

2362:   if (ctx->times[LANDAU_MATRIX_TOTAL] > 0) { // OMP timings
2363:     PetscCall(PetscPrintf(ctx->comm, "TSStep               N  1.0 %10.3e\n", ctx->times[LANDAU_EX2_TSSOLVE]));
2364:     PetscCall(PetscPrintf(ctx->comm, "2:           Solve:  %10.3e with %" PetscInt_FMT " threads\n", ctx->times[LANDAU_EX2_TSSOLVE] - ctx->times[LANDAU_MATRIX_TOTAL], ctx->batch_sz));
2365:     PetscCall(PetscPrintf(ctx->comm, "3:          Landau:  %10.3e\n", ctx->times[LANDAU_MATRIX_TOTAL]));
2366:     PetscCall(PetscPrintf(ctx->comm, "Landau Jacobian       %" PetscInt_FMT " 1.0 %10.3e\n", (PetscInt)ctx->times[LANDAU_JACOBIAN_COUNT], ctx->times[LANDAU_JACOBIAN]));
2367:     PetscCall(PetscPrintf(ctx->comm, "Landau Operator       N 1.0  %10.3e\n", ctx->times[LANDAU_OPERATOR]));
2368:     PetscCall(PetscPrintf(ctx->comm, "Landau Mass           N 1.0  %10.3e\n", ctx->times[LANDAU_MASS]));
2369:     PetscCall(PetscPrintf(ctx->comm, " Jac-f-df (GPU)       N 1.0  %10.3e\n", ctx->times[LANDAU_F_DF]));
2370:     PetscCall(PetscPrintf(ctx->comm, " Kernel (GPU)         N 1.0  %10.3e\n", ctx->times[LANDAU_KERNEL]));
2371:     PetscCall(PetscPrintf(ctx->comm, "MatLUFactorNum        X 1.0 %10.3e\n", ctx->times[KSP_FACTOR]));
2372:     PetscCall(PetscPrintf(ctx->comm, "MatSolve              X 1.0 %10.3e\n", ctx->times[KSP_SOLVE]));
2373:   }
2374:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) PetscCall(DMDestroy(&ctx->plex[grid]));
2375:   PetscCall(PetscFree(ctx));
2376:   PetscCall(DMDestroy(dm));
2377:   PetscFunctionReturn(PETSC_SUCCESS);
2378: }

2380: /* < v, ru > */
2381: static void f0_s_den(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar *f0)
2382: {
2383:   PetscInt ii = (PetscInt)PetscRealPart(constants[0]);
2384:   f0[0]       = u[ii];
2385: }

2387: /* < v, ru > */
2388: static void f0_s_mom(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar *f0)
2389: {
2390:   PetscInt ii = (PetscInt)PetscRealPart(constants[0]), jj = (PetscInt)PetscRealPart(constants[1]);
2391:   f0[0] = x[jj] * u[ii]; /* x momentum */
2392: }

2394: static void f0_s_v2(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar *f0)
2395: {
2396:   PetscInt i, ii = (PetscInt)PetscRealPart(constants[0]);
2397:   double   tmp1 = 0.;
2398:   for (i = 0; i < dim; ++i) tmp1 += x[i] * x[i];
2399:   f0[0] = tmp1 * u[ii];
2400: }

2402: static PetscErrorCode gamma_n_f(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *actx)
2403: {
2404:   const PetscReal *c2_0_arr = ((PetscReal *)actx);
2405:   const PetscReal  c02      = c2_0_arr[0];

2407:   PetscFunctionBegin;
2408:   for (PetscInt s = 0; s < Nf; s++) {
2409:     PetscReal tmp1 = 0.;
2410:     for (PetscInt i = 0; i < dim; ++i) tmp1 += x[i] * x[i];
2411:     if (PetscDefined(USE_DEBUG)) u[s] = PetscSqrtReal(1. + tmp1 / c02); //  u[0] = PetscSqrtReal(1. + xx);
2412:     else {
2413:       PetscReal xx = tmp1 / c02;
2414:       u[s]         = xx / (PetscSqrtReal(1. + xx) + 1.); // better conditioned = xx/(PetscSqrtReal(1. + xx) + 1.)
2415:     }
2416:   }
2417:   PetscFunctionReturn(PETSC_SUCCESS);
2418: }

2420: /* < v, ru > */
2421: static void f0_s_rden(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar *f0)
2422: {
2423:   PetscInt ii = (PetscInt)PetscRealPart(constants[0]);
2424:   f0[0]       = 2. * PETSC_PI * x[0] * u[ii];
2425: }

2427: /* < v, ru > */
2428: static void f0_s_rmom(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar *f0)
2429: {
2430:   PetscInt ii = (PetscInt)PetscRealPart(constants[0]);
2431:   f0[0]       = 2. * PETSC_PI * x[0] * x[1] * u[ii];
2432: }

2434: static void f0_s_rv2(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar *f0)
2435: {
2436:   PetscInt ii = (PetscInt)PetscRealPart(constants[0]);
2437:   f0[0]       = 2. * PETSC_PI * x[0] * (x[0] * x[0] + x[1] * x[1]) * u[ii];
2438: }

2440: /*@
2441:   DMPlexLandauPrintNorms - collects moments and prints them

2443:   Collective

2445:   Input Parameters:
2446: + X     - the state
2447: - stepi - current step to print

2449:   Level: beginner

2451: .seealso: `DMPlexLandauCreateVelocitySpace()`
2452:  @*/
2453: PetscErrorCode DMPlexLandauPrintNorms(Vec X, PetscInt stepi)
2454: {
2455:   LandauCtx  *ctx;
2456:   PetscDS     prob;
2457:   DM          pack;
2458:   PetscInt    cStart, cEnd, dim, ii, i0, nDMs;
2459:   PetscScalar xmomentumtot = 0, ymomentumtot = 0, zmomentumtot = 0, energytot = 0, densitytot = 0, tt[LANDAU_MAX_SPECIES];
2460:   PetscScalar xmomentum[LANDAU_MAX_SPECIES], ymomentum[LANDAU_MAX_SPECIES], zmomentum[LANDAU_MAX_SPECIES], energy[LANDAU_MAX_SPECIES], density[LANDAU_MAX_SPECIES];
2461:   Vec        *globXArray;

2463:   PetscFunctionBegin;
2464:   PetscCall(VecGetDM(X, &pack));
2465:   PetscCheck(pack, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Vector has no DM");
2466:   PetscCall(DMGetDimension(pack, &dim));
2467:   PetscCheck(dim == 2 || dim == 3, PETSC_COMM_SELF, PETSC_ERR_PLIB, "dim %" PetscInt_FMT " not in [2,3]", dim);
2468:   PetscCall(DMGetApplicationContext(pack, &ctx));
2469:   PetscCheck(ctx, PETSC_COMM_SELF, PETSC_ERR_PLIB, "no context");
2470:   /* print momentum and energy */
2471:   PetscCall(DMCompositeGetNumberDM(pack, &nDMs));
2472:   PetscCheck(nDMs == ctx->num_grids * ctx->batch_sz, PETSC_COMM_WORLD, PETSC_ERR_PLIB, "#DM wrong %" PetscInt_FMT " %" PetscInt_FMT, nDMs, ctx->num_grids * ctx->batch_sz);
2473:   PetscCall(PetscMalloc(sizeof(*globXArray) * nDMs, &globXArray));
2474:   PetscCall(DMCompositeGetAccessArray(pack, X, nDMs, NULL, globXArray));
2475:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
2476:     Vec Xloc = globXArray[LAND_PACK_IDX(ctx->batch_view_idx, grid)];
2477:     PetscCall(DMGetDS(ctx->plex[grid], &prob));
2478:     for (ii = ctx->species_offset[grid], i0 = 0; ii < ctx->species_offset[grid + 1]; ii++, i0++) {
2479:       PetscScalar user[2] = {(PetscScalar)i0, ctx->charges[ii]};
2480:       PetscCall(PetscDSSetConstants(prob, 2, user));
2481:       if (dim == 2) { /* 2/3X + 3V (cylindrical coordinates) */
2482:         PetscCall(PetscDSSetObjective(prob, 0, &f0_s_rden));
2483:         PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
2484:         density[ii] = tt[0] * ctx->n_0 * ctx->charges[ii];
2485:         PetscCall(PetscDSSetObjective(prob, 0, &f0_s_rmom));
2486:         PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
2487:         zmomentum[ii] = tt[0] * ctx->n_0 * ctx->v_0 * ctx->masses[ii];
2488:         PetscCall(PetscDSSetObjective(prob, 0, &f0_s_rv2));
2489:         PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
2490:         energy[ii] = tt[0] * 0.5 * ctx->n_0 * ctx->v_0 * ctx->v_0 * ctx->masses[ii];
2491:         zmomentumtot += zmomentum[ii];
2492:         energytot += energy[ii];
2493:         densitytot += density[ii];
2494:         PetscCall(PetscPrintf(PETSC_COMM_WORLD, "%3" PetscInt_FMT ") species-%" PetscInt_FMT ": charge density= %20.13e z-momentum= %20.13e energy= %20.13e", stepi, ii, (double)PetscRealPart(density[ii]), (double)PetscRealPart(zmomentum[ii]), (double)PetscRealPart(energy[ii])));
2495:       } else { /* 2/3Xloc + 3V */
2496:         PetscCall(PetscDSSetObjective(prob, 0, &f0_s_den));
2497:         PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
2498:         density[ii] = tt[0] * ctx->n_0 * ctx->charges[ii];
2499:         PetscCall(PetscDSSetObjective(prob, 0, &f0_s_mom));
2500:         user[1] = 0;
2501:         PetscCall(PetscDSSetConstants(prob, 2, user));
2502:         PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
2503:         xmomentum[ii] = tt[0] * ctx->n_0 * ctx->v_0 * ctx->masses[ii];
2504:         user[1]       = 1;
2505:         PetscCall(PetscDSSetConstants(prob, 2, user));
2506:         PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
2507:         ymomentum[ii] = tt[0] * ctx->n_0 * ctx->v_0 * ctx->masses[ii];
2508:         user[1]       = 2;
2509:         PetscCall(PetscDSSetConstants(prob, 2, user));
2510:         PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
2511:         zmomentum[ii] = tt[0] * ctx->n_0 * ctx->v_0 * ctx->masses[ii];
2512:         if (ctx->use_relativistic_corrections) {
2513:           /* gamma * M * f */
2514:           if (ii == 0 && grid == 0) { // do all at once
2515:             Vec Mf, globGamma, *globMfArray, *globGammaArray;
2516:             PetscErrorCode (*gammaf[1])(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *) = {gamma_n_f};
2517:             PetscReal *c2_0[1], data[1];

2519:             PetscCall(VecDuplicate(X, &globGamma));
2520:             PetscCall(VecDuplicate(X, &Mf));
2521:             PetscCall(PetscMalloc(sizeof(*globMfArray) * nDMs, &globMfArray));
2522:             PetscCall(PetscMalloc(sizeof(*globMfArray) * nDMs, &globGammaArray));
2523:             /* M * f */
2524:             PetscCall(MatMult(ctx->M, X, Mf));
2525:             /* gamma */
2526:             PetscCall(DMCompositeGetAccessArray(pack, globGamma, nDMs, NULL, globGammaArray));
2527:             for (PetscInt grid = 0; grid < ctx->num_grids; grid++) { // yes a grid loop in a grid loop to print nice, need to fix for batching
2528:               Vec v1  = globGammaArray[LAND_PACK_IDX(ctx->batch_view_idx, grid)];
2529:               data[0] = PetscSqr(C_0(ctx->v_0));
2530:               c2_0[0] = &data[0];
2531:               PetscCall(DMProjectFunction(ctx->plex[grid], 0., gammaf, (void **)c2_0, INSERT_ALL_VALUES, v1));
2532:             }
2533:             PetscCall(DMCompositeRestoreAccessArray(pack, globGamma, nDMs, NULL, globGammaArray));
2534:             /* gamma * Mf */
2535:             PetscCall(DMCompositeGetAccessArray(pack, globGamma, nDMs, NULL, globGammaArray));
2536:             PetscCall(DMCompositeGetAccessArray(pack, Mf, nDMs, NULL, globMfArray));
2537:             for (PetscInt grid = 0; grid < ctx->num_grids; grid++) { // yes a grid loop in a grid loop to print nice
2538:               PetscInt Nf    = ctx->species_offset[grid + 1] - ctx->species_offset[grid], N, bs;
2539:               Vec      Mfsub = globMfArray[LAND_PACK_IDX(ctx->batch_view_idx, grid)], Gsub = globGammaArray[LAND_PACK_IDX(ctx->batch_view_idx, grid)], v1, v2;
2540:               // get each component
2541:               PetscCall(VecGetSize(Mfsub, &N));
2542:               PetscCall(VecCreate(ctx->comm, &v1));
2543:               PetscCall(VecSetSizes(v1, PETSC_DECIDE, N / Nf));
2544:               PetscCall(VecCreate(ctx->comm, &v2));
2545:               PetscCall(VecSetSizes(v2, PETSC_DECIDE, N / Nf));
2546:               PetscCall(VecSetFromOptions(v1)); // ???
2547:               PetscCall(VecSetFromOptions(v2));
2548:               // get each component
2549:               PetscCall(VecGetBlockSize(Gsub, &bs));
2550:               PetscCheck(bs == Nf, PETSC_COMM_SELF, PETSC_ERR_PLIB, "bs %" PetscInt_FMT " != num_species %" PetscInt_FMT " in Gsub", bs, Nf);
2551:               PetscCall(VecGetBlockSize(Mfsub, &bs));
2552:               PetscCheck(bs == Nf, PETSC_COMM_SELF, PETSC_ERR_PLIB, "bs %" PetscInt_FMT " != num_species %" PetscInt_FMT, bs, Nf);
2553:               for (PetscInt i = 0, ix = ctx->species_offset[grid]; i < Nf; i++, ix++) {
2554:                 PetscScalar val;
2555:                 PetscCall(VecStrideGather(Gsub, i, v1, INSERT_VALUES)); // this is not right -- TODO
2556:                 PetscCall(VecStrideGather(Mfsub, i, v2, INSERT_VALUES));
2557:                 PetscCall(VecDot(v1, v2, &val));
2558:                 energy[ix] = PetscRealPart(val) * ctx->n_0 * ctx->v_0 * ctx->v_0 * ctx->masses[ix];
2559:               }
2560:               PetscCall(VecDestroy(&v1));
2561:               PetscCall(VecDestroy(&v2));
2562:             } /* grids */
2563:             PetscCall(DMCompositeRestoreAccessArray(pack, globGamma, nDMs, NULL, globGammaArray));
2564:             PetscCall(DMCompositeRestoreAccessArray(pack, Mf, nDMs, NULL, globMfArray));
2565:             PetscCall(PetscFree(globGammaArray));
2566:             PetscCall(PetscFree(globMfArray));
2567:             PetscCall(VecDestroy(&globGamma));
2568:             PetscCall(VecDestroy(&Mf));
2569:           }
2570:         } else {
2571:           PetscCall(PetscDSSetObjective(prob, 0, &f0_s_v2));
2572:           PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
2573:           energy[ii] = 0.5 * tt[0] * ctx->n_0 * ctx->v_0 * ctx->v_0 * ctx->masses[ii];
2574:         }
2575:         PetscCall(PetscPrintf(PETSC_COMM_WORLD, "%3" PetscInt_FMT ") species %" PetscInt_FMT ": density=%20.13e, x-momentum=%20.13e, y-momentum=%20.13e, z-momentum=%20.13e, energy=%21.13e", stepi, ii, (double)PetscRealPart(density[ii]), (double)PetscRealPart(xmomentum[ii]), (double)PetscRealPart(ymomentum[ii]), (double)PetscRealPart(zmomentum[ii]), (double)PetscRealPart(energy[ii])));
2576:         xmomentumtot += xmomentum[ii];
2577:         ymomentumtot += ymomentum[ii];
2578:         zmomentumtot += zmomentum[ii];
2579:         energytot += energy[ii];
2580:         densitytot += density[ii];
2581:       }
2582:       if (ctx->num_species > 1) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n"));
2583:     }
2584:   }
2585:   PetscCall(DMCompositeRestoreAccessArray(pack, X, nDMs, NULL, globXArray));
2586:   PetscCall(PetscFree(globXArray));
2587:   /* totals */
2588:   PetscCall(DMPlexGetHeightStratum(ctx->plex[0], 0, &cStart, &cEnd));
2589:   if (ctx->num_species > 1) {
2590:     if (dim == 2) {
2591:       PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\t%3" PetscInt_FMT ") Total: charge density=%21.13e, momentum=%21.13e, energy=%21.13e (m_i[0]/m_e = %g, %" PetscInt_FMT " cells on electron grid)", stepi, (double)PetscRealPart(densitytot), (double)PetscRealPart(zmomentumtot), (double)PetscRealPart(energytot),
2592:                             (double)(ctx->masses[1] / ctx->masses[0]), cEnd - cStart));
2593:     } else {
2594:       PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\t%3" PetscInt_FMT ") Total: charge density=%21.13e, x-momentum=%21.13e, y-momentum=%21.13e, z-momentum=%21.13e, energy=%21.13e (m_i[0]/m_e = %g, %" PetscInt_FMT " cells)", stepi, (double)PetscRealPart(densitytot), (double)PetscRealPart(xmomentumtot), (double)PetscRealPart(ymomentumtot), (double)PetscRealPart(zmomentumtot), (double)PetscRealPart(energytot),
2595:                             (double)(ctx->masses[1] / ctx->masses[0]), cEnd - cStart));
2596:     }
2597:   } else PetscCall(PetscPrintf(PETSC_COMM_WORLD, " -- %" PetscInt_FMT " cells", cEnd - cStart));
2598:   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n"));
2599:   PetscFunctionReturn(PETSC_SUCCESS);
2600: }

2602: /*@
2603:   DMPlexLandauCreateMassMatrix - Create mass matrix for Landau in Plex space (not field major order of Jacobian)
2604:   - puts mass matrix into ctx->M

2606:   Collective

2608:   Input Parameter:
2609: . pack - the `DM` object. Puts matrix in Landau context M field

2611:   Output Parameter:
2612: . Amat - The mass matrix (optional), mass matrix is added to the `DM` context

2614:   Level: beginner

2616: .seealso: `DMPlexLandauCreateVelocitySpace()`
2617:  @*/
2618: PetscErrorCode DMPlexLandauCreateMassMatrix(DM pack, Mat *Amat)
2619: {
2620:   DM         mass_pack, massDM[LANDAU_MAX_GRIDS];
2621:   PetscDS    prob;
2622:   PetscInt   ii, dim, N1 = 1, N2;
2623:   LandauCtx *ctx;
2624:   Mat        packM, subM[LANDAU_MAX_GRIDS];

2626:   PetscFunctionBegin;
2628:   if (Amat) PetscAssertPointer(Amat, 2);
2629:   PetscCall(DMGetApplicationContext(pack, &ctx));
2630:   PetscCheck(ctx, PETSC_COMM_SELF, PETSC_ERR_PLIB, "no context");
2631:   PetscCall(PetscLogEventBegin(ctx->events[14], 0, 0, 0, 0));
2632:   PetscCall(DMGetDimension(pack, &dim));
2633:   PetscCall(DMCompositeCreate(PetscObjectComm((PetscObject)pack), &mass_pack));
2634:   /* create pack mass matrix */
2635:   for (PetscInt grid = 0, ix = 0; grid < ctx->num_grids; grid++) {
2636:     PetscCall(DMClone(ctx->plex[grid], &massDM[grid]));
2637:     PetscCall(DMCopyFields(ctx->plex[grid], PETSC_DETERMINE, PETSC_DETERMINE, massDM[grid]));
2638:     PetscCall(DMCreateDS(massDM[grid]));
2639:     PetscCall(DMGetDS(massDM[grid], &prob));
2640:     for (ix = 0, ii = ctx->species_offset[grid]; ii < ctx->species_offset[grid + 1]; ii++, ix++) {
2641:       if (dim == 3) PetscCall(PetscDSSetJacobian(prob, ix, ix, g0_1, NULL, NULL, NULL));
2642:       else PetscCall(PetscDSSetJacobian(prob, ix, ix, g0_r, NULL, NULL, NULL));
2643:     }
2644: #if !defined(LANDAU_SPECIES_MAJOR)
2645:     PetscCall(DMCompositeAddDM(mass_pack, massDM[grid]));
2646: #else
2647:     for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) { // add batch size DMs for this species grid
2648:       PetscCall(DMCompositeAddDM(mass_pack, massDM[grid]));
2649:     }
2650: #endif
2651:     PetscCall(DMCreateMatrix(massDM[grid], &subM[grid]));
2652:   }
2653: #if !defined(LANDAU_SPECIES_MAJOR)
2654:   // stack the batched DMs
2655:   for (PetscInt b_id = 1; b_id < ctx->batch_sz; b_id++) {
2656:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) PetscCall(DMCompositeAddDM(mass_pack, massDM[grid]));
2657:   }
2658: #endif
2659:   PetscCall(PetscOptionsInsertString(NULL, "-dm_preallocate_only"));
2660:   PetscCall(DMCreateMatrix(mass_pack, &packM));
2661:   PetscCall(PetscOptionsInsertString(NULL, "-dm_preallocate_only false"));
2662:   PetscCall(MatSetOption(packM, MAT_STRUCTURALLY_SYMMETRIC, PETSC_TRUE));
2663:   PetscCall(MatSetOption(packM, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE));
2664:   PetscCall(DMDestroy(&mass_pack));
2665:   /* make mass matrix for each block */
2666:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
2667:     Vec locX;
2668:     DM  plex = massDM[grid];
2669:     PetscCall(DMGetLocalVector(plex, &locX));
2670:     /* Mass matrix is independent of the input, so no need to fill locX */
2671:     PetscCall(DMPlexSNESComputeJacobianFEM(plex, locX, subM[grid], subM[grid], ctx));
2672:     PetscCall(DMRestoreLocalVector(plex, &locX));
2673:     PetscCall(DMDestroy(&massDM[grid]));
2674:   }
2675:   PetscCall(MatGetSize(ctx->J, &N1, NULL));
2676:   PetscCall(MatGetSize(packM, &N2, NULL));
2677:   PetscCheck(N1 == N2, PetscObjectComm((PetscObject)pack), PETSC_ERR_PLIB, "Incorrect matrix sizes: |Jacobian| = %" PetscInt_FMT ", |Mass|=%" PetscInt_FMT, N1, N2);
2678:   /* assemble block diagonals */
2679:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
2680:     Mat      B = subM[grid];
2681:     PetscInt nloc, nzl, *colbuf, COL_BF_SIZE = 1024, row;
2682:     PetscCall(PetscMalloc(sizeof(*colbuf) * COL_BF_SIZE, &colbuf));
2683:     PetscCall(MatGetSize(B, &nloc, NULL));
2684:     for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) {
2685:       const PetscInt     moffset = LAND_MOFFSET(b_id, grid, ctx->batch_sz, ctx->num_grids, ctx->mat_offset);
2686:       const PetscInt    *cols;
2687:       const PetscScalar *vals;
2688:       for (PetscInt i = 0; i < nloc; i++) {
2689:         PetscCall(MatGetRow(B, i, &nzl, NULL, NULL));
2690:         if (nzl > COL_BF_SIZE) {
2691:           PetscCall(PetscFree(colbuf));
2692:           PetscCall(PetscInfo(pack, "Realloc buffer %" PetscInt_FMT " to %" PetscInt_FMT " (row size %" PetscInt_FMT ") \n", COL_BF_SIZE, 2 * COL_BF_SIZE, nzl));
2693:           COL_BF_SIZE = nzl;
2694:           PetscCall(PetscMalloc(sizeof(*colbuf) * COL_BF_SIZE, &colbuf));
2695:         }
2696:         PetscCall(MatGetRow(B, i, &nzl, &cols, &vals));
2697:         for (PetscInt j = 0; j < nzl; j++) colbuf[j] = cols[j] + moffset;
2698:         row = i + moffset;
2699:         PetscCall(MatSetValues(packM, 1, &row, nzl, colbuf, vals, INSERT_VALUES));
2700:         PetscCall(MatRestoreRow(B, i, &nzl, &cols, &vals));
2701:       }
2702:     }
2703:     PetscCall(PetscFree(colbuf));
2704:   }
2705:   // cleanup
2706:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) PetscCall(MatDestroy(&subM[grid]));
2707:   PetscCall(MatAssemblyBegin(packM, MAT_FINAL_ASSEMBLY));
2708:   PetscCall(MatAssemblyEnd(packM, MAT_FINAL_ASSEMBLY));
2709:   PetscCall(PetscObjectSetName((PetscObject)packM, "mass"));
2710:   PetscCall(MatViewFromOptions(packM, NULL, "-dm_landau_mass_view"));
2711:   ctx->M = packM;
2712:   if (Amat) *Amat = packM;
2713:   PetscCall(PetscLogEventEnd(ctx->events[14], 0, 0, 0, 0));
2714:   PetscFunctionReturn(PETSC_SUCCESS);
2715: }

2717: /*@
2718:   DMPlexLandauIFunction - `TS` residual calculation, confusingly this computes the Jacobian w/o mass

2720:   Collective

2722:   Input Parameters:
2723: + ts         - The time stepping context
2724: . time_dummy - current time (not used)
2725: . X          - Current state
2726: . X_t        - Time derivative of current state
2727: - actx       - Landau context

2729:   Output Parameter:
2730: . F - The residual

2732:   Level: beginner

2734: .seealso: `DMPlexLandauCreateVelocitySpace()`, `DMPlexLandauIJacobian()`
2735:  @*/
2736: PetscErrorCode DMPlexLandauIFunction(TS ts, PetscReal time_dummy, Vec X, Vec X_t, Vec F, void *actx)
2737: {
2738:   LandauCtx *ctx = (LandauCtx *)actx;
2739:   PetscInt   dim;
2740:   DM         pack;
2741: #if PetscDefined(HAVE_THREADSAFETY)
2742:   double starttime, endtime;
2743: #endif
2744:   PetscObjectState state;

2746:   PetscFunctionBegin;
2747:   PetscCall(TSGetDM(ts, &pack));
2748:   PetscCall(DMGetApplicationContext(pack, &ctx));
2749:   PetscCheck(ctx, PETSC_COMM_SELF, PETSC_ERR_PLIB, "no context");
2750:   if (ctx->stage) PetscCall(PetscLogStagePush(ctx->stage));
2751:   PetscCall(PetscLogEventBegin(ctx->events[11], 0, 0, 0, 0));
2752:   PetscCall(PetscLogEventBegin(ctx->events[0], 0, 0, 0, 0));
2753: #if PetscDefined(HAVE_THREADSAFETY)
2754:   starttime = MPI_Wtime();
2755: #endif
2756:   PetscCall(DMGetDimension(pack, &dim));
2757:   PetscCall(PetscObjectStateGet((PetscObject)ctx->J, &state));
2758:   if (state != ctx->norm_state) {
2759:     PetscCall(MatZeroEntries(ctx->J));
2760:     PetscCall(LandauFormJacobian_Internal(X, ctx->J, dim, 0.0, (void *)ctx));
2761:     PetscCall(MatViewFromOptions(ctx->J, NULL, "-dm_landau_jacobian_view"));
2762:     PetscCall(PetscObjectStateGet((PetscObject)ctx->J, &state));
2763:     ctx->norm_state = state;
2764:   } else {
2765:     PetscCall(PetscInfo(ts, "WARNING Skip forming Jacobian, has not changed %" PetscInt64_FMT "\n", state));
2766:   }
2767:   /* mat vec for op */
2768:   PetscCall(MatMult(ctx->J, X, F)); /* C*f */
2769:   /* add time term */
2770:   if (X_t) PetscCall(MatMultAdd(ctx->M, X_t, F, F));
2771: #if PetscDefined(HAVE_THREADSAFETY)
2772:   if (ctx->stage) {
2773:     endtime = MPI_Wtime();
2774:     ctx->times[LANDAU_OPERATOR] += (endtime - starttime);
2775:     ctx->times[LANDAU_JACOBIAN] += (endtime - starttime);
2776:     ctx->times[LANDAU_MATRIX_TOTAL] += (endtime - starttime);
2777:     ctx->times[LANDAU_JACOBIAN_COUNT] += 1;
2778:   }
2779: #endif
2780:   PetscCall(PetscLogEventEnd(ctx->events[0], 0, 0, 0, 0));
2781:   PetscCall(PetscLogEventEnd(ctx->events[11], 0, 0, 0, 0));
2782:   if (ctx->stage) PetscCall(PetscLogStagePop());
2783:   PetscFunctionReturn(PETSC_SUCCESS);
2784: }

2786: /*@
2787:   DMPlexLandauIJacobian - `TS` Jacobian construction, confusingly this adds mass

2789:   Collective

2791:   Input Parameters:
2792: + ts         - The time stepping context
2793: . time_dummy - current time (not used)
2794: . X          - Current state
2795: . U_tdummy   - Time derivative of current state (not used)
2796: . shift      - shift for du/dt term
2797: - actx       - Landau context

2799:   Output Parameters:
2800: + Amat - Jacobian
2801: - Pmat - same as Amat

2803:   Level: beginner

2805: .seealso: `DMPlexLandauCreateVelocitySpace()`, `DMPlexLandauIFunction()`
2806:  @*/
2807: PetscErrorCode DMPlexLandauIJacobian(TS ts, PetscReal time_dummy, Vec X, Vec U_tdummy, PetscReal shift, Mat Amat, Mat Pmat, void *actx)
2808: {
2809:   LandauCtx *ctx = NULL;
2810:   PetscInt   dim;
2811:   DM         pack;
2812: #if PetscDefined(HAVE_THREADSAFETY)
2813:   double starttime, endtime;
2814: #endif
2815:   PetscObjectState state;

2817:   PetscFunctionBegin;
2818:   PetscCall(TSGetDM(ts, &pack));
2819:   PetscCall(DMGetApplicationContext(pack, &ctx));
2820:   PetscCheck(ctx, PETSC_COMM_SELF, PETSC_ERR_PLIB, "no context");
2821:   PetscCheck(Amat == Pmat && Amat == ctx->J, ctx->comm, PETSC_ERR_PLIB, "Amat!=Pmat || Amat!=ctx->J");
2822:   PetscCall(DMGetDimension(pack, &dim));
2823:   /* get collision Jacobian into A */
2824:   if (ctx->stage) PetscCall(PetscLogStagePush(ctx->stage));
2825:   PetscCall(PetscLogEventBegin(ctx->events[11], 0, 0, 0, 0));
2826:   PetscCall(PetscLogEventBegin(ctx->events[9], 0, 0, 0, 0));
2827: #if PetscDefined(HAVE_THREADSAFETY)
2828:   starttime = MPI_Wtime();
2829: #endif
2830:   PetscCheck(shift != 0.0, ctx->comm, PETSC_ERR_PLIB, "zero shift");
2831:   PetscCall(PetscObjectStateGet((PetscObject)ctx->J, &state));
2832:   PetscCheck(state == ctx->norm_state, ctx->comm, PETSC_ERR_PLIB, "wrong state, %" PetscInt64_FMT " %" PetscInt64_FMT, ctx->norm_state, state);
2833:   if (!ctx->use_matrix_mass) {
2834:     PetscCall(LandauFormJacobian_Internal(X, ctx->J, dim, shift, (void *)ctx));
2835:   } else { /* add mass */
2836:     PetscCall(MatAXPY(Pmat, shift, ctx->M, SAME_NONZERO_PATTERN));
2837:   }
2838: #if PetscDefined(HAVE_THREADSAFETY)
2839:   if (ctx->stage) {
2840:     endtime = MPI_Wtime();
2841:     ctx->times[LANDAU_OPERATOR] += (endtime - starttime);
2842:     ctx->times[LANDAU_MASS] += (endtime - starttime);
2843:     ctx->times[LANDAU_MATRIX_TOTAL] += (endtime - starttime);
2844:   }
2845: #endif
2846:   PetscCall(PetscLogEventEnd(ctx->events[9], 0, 0, 0, 0));
2847:   PetscCall(PetscLogEventEnd(ctx->events[11], 0, 0, 0, 0));
2848:   if (ctx->stage) PetscCall(PetscLogStagePop());
2849:   PetscFunctionReturn(PETSC_SUCCESS);
2850: }