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 defined(PETSC_USE_REAL_SINGLE)
     12:   #define SPEED_OF_LIGHT 2.99792458e8F
     13:   #define C_0(v0)        (SPEED_OF_LIGHT / v0) /* needed for relativistic tensor on all architectures */
     14: #else
     15:   #define SPEED_OF_LIGHT 2.99792458e8
     16:   #define C_0(v0)        (SPEED_OF_LIGHT / v0) /* needed for relativistic tensor on all architectures */
     17: #endif

     19: #include "land_tensors.h"

     21: #if defined(PETSC_HAVE_OPENMP)
     22:   #include <omp.h>
     23: #endif

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

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

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

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

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

     77: /*
     78:  LandauFormJacobian_Internal - Evaluates Jacobian matrix.

     80:  Input Parameters:
     81:  .  globX - input vector
     82:  .  actx - optional user-defined context
     83:  .  dim - dimension

     85:  Output Parameter:
     86:  .  J0acP - Jacobian matrix filled, not created
     87:  */
     88: static PetscErrorCode LandauFormJacobian_Internal(Vec a_X, Mat JacP, const PetscInt dim, PetscReal shift, void *a_ctx)
     89: {
     90:   LandauCtx         *ctx = (LandauCtx *)a_ctx;
     91:   PetscInt           numCells[LANDAU_MAX_GRIDS], Nq, Nb;
     92:   PetscQuadrature    quad;
     93:   PetscReal          Eq_m[LANDAU_MAX_SPECIES]; // could be static data w/o quench (ex2)
     94:   PetscScalar       *cellClosure = NULL;
     95:   const PetscScalar *xdata       = NULL;
     96:   PetscDS            prob;
     97:   PetscContainer     container;
     98:   P4estVertexMaps   *maps;
     99:   Mat                subJ[LANDAU_MAX_GRIDS * LANDAU_MAX_BATCH_SZ];

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

    204:   /* do it */
    205:   if (ctx->deviceType == LANDAU_KOKKOS) {
    206: #if defined(PETSC_HAVE_KOKKOS)
    207:     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));
    208: #else
    209:     SETERRQ(ctx->comm, PETSC_ERR_ARG_WRONG, "-landau_device_type %s not built", "kokkos");
    210: #endif
    211:   } else {               /* CPU version */
    212:     PetscTabulation *Tf; // used for CPU and print info. Same on all grids and all species
    213:     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];
    214:     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;
    215:     PetscReal       *nu_alpha = (PetscReal *)ctx->SData_d.alpha, *nu_beta = (PetscReal *)ctx->SData_d.beta, *invMass = (PetscReal *)ctx->SData_d.invMass;
    216:     PetscReal(*lambdas)[LANDAU_MAX_GRIDS][LANDAU_MAX_GRIDS] = (PetscReal(*)[LANDAU_MAX_GRIDS][LANDAU_MAX_GRIDS])ctx->SData_d.lambdas;
    217:     PetscSection section[LANDAU_MAX_GRIDS], globsection[LANDAU_MAX_GRIDS];
    218:     PetscScalar *coo_vals = NULL;
    219:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    220:       PetscCall(DMGetLocalSection(ctx->plex[grid], &section[grid]));
    221:       PetscCall(DMGetGlobalSection(ctx->plex[grid], &globsection[grid]));
    222:       PetscCall(PetscSectionGetNumFields(section[grid], &Nf[grid]));
    223:     }
    224:     /* count IPf size, etc */
    225:     PetscCall(PetscDSGetTabulation(prob, &Tf)); // Bf, &Df same for all grids
    226:     const PetscReal *const BB = Tf[0]->T[0], *const DD = Tf[0]->T[1];
    227:     ip_offset[0] = ipf_offset[0] = elem_offset[0] = 0;
    228:     for (PetscInt grid = 0; grid < num_grids; grid++) {
    229:       PetscInt nfloc        = ctx->species_offset[grid + 1] - ctx->species_offset[grid];
    230:       elem_offset[grid + 1] = elem_offset[grid] + numCells[grid];
    231:       ip_offset[grid + 1]   = ip_offset[grid] + numCells[grid] * Nq;
    232:       ipf_offset[grid + 1]  = ipf_offset[grid] + Nq * nfloc * numCells[grid];
    233:     }
    234:     IPf_sz_glb = ipf_offset[num_grids];
    235:     IPf_sz_tot = IPf_sz_glb * ctx->batch_sz;
    236:     // prep COO
    237:     PetscCall(PetscMalloc1(ctx->SData_d.coo_size, &coo_vals)); // allocate every time?
    238:     if (shift == 0.0) {                                        /* compute dynamic data f and df and init data for Jacobian */
    239: #if defined(PETSC_HAVE_THREADSAFETY)
    240:       double starttime, endtime;
    241:       starttime = MPI_Wtime();
    242: #endif
    243:       PetscCall(PetscLogEventBegin(ctx->events[8], 0, 0, 0, 0));
    244:       PetscCall(PetscMalloc4(IPf_sz_tot, &ff, IPf_sz_tot, &dudx, IPf_sz_tot, &dudy, (dim == 3 ? IPf_sz_tot : 0), &dudz));
    245:       // F df/dx
    246:       for (PetscInt tid = 0; tid < ctx->batch_sz * elem_offset[num_grids]; tid++) {                        // for each element
    247:         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
    248:         // find my grid:
    249:         PetscInt grid = 0;
    250:         while (b_elem_idx >= elem_offset[grid + 1]) grid++; // yuck search for grid
    251:         {
    252:           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];
    253:           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];
    254:           PetscScalar   *coef, coef_buff[LANDAU_MAX_SPECIES * LANDAU_MAX_NQND];
    255:           PetscReal     *invJe = &invJ_a[(ip_offset[grid] + loc_elem * Nq) * dim * dim]; // ingJ is static data on batch 0
    256:           PetscInt       b, f, q;
    257:           if (cellClosure) {
    258:             coef = &cellClosure[b_id * IPf_sz_glb + ipf_offset[grid] + loc_elem * Nb * loc_Nf]; // this is const
    259:           } else {
    260:             coef = coef_buff;
    261:             for (f = 0; f < loc_Nf; ++f) {
    262:               LandauIdx *const Idxs = &maps[grid].gIdx[loc_elem][f][0];
    263:               for (b = 0; b < Nb; ++b) {
    264:                 PetscInt idx = Idxs[b];
    265:                 if (idx >= 0) {
    266:                   coef[f * Nb + b] = xdata[idx + moffset];
    267:                 } else {
    268:                   idx              = -idx - 1;
    269:                   coef[f * Nb + b] = 0;
    270:                   for (q = 0; q < maps[grid].num_face; q++) {
    271:                     PetscInt    id    = maps[grid].c_maps[idx][q].gid;
    272:                     PetscScalar scale = maps[grid].c_maps[idx][q].scale;
    273:                     coef[f * Nb + b] += scale * xdata[id + moffset];
    274:                   }
    275:                 }
    276:               }
    277:             }
    278:           }
    279:           /* get f and df */
    280:           for (PetscInt qi = 0; qi < Nq; qi++) {
    281:             const PetscReal *invJ = &invJe[qi * dim * dim];
    282:             const PetscReal *Bq   = &BB[qi * Nb];
    283:             const PetscReal *Dq   = &DD[qi * Nb * dim];
    284:             PetscReal        u_x[LANDAU_DIM];
    285:             /* get f & df */
    286:             for (f = 0; f < loc_Nf; ++f) {
    287:               const PetscInt idx = b_id * IPf_sz_glb + ipf_offset[grid] + f * loc_nip + loc_elem * Nq + qi;
    288:               PetscInt       b, e;
    289:               PetscReal      refSpaceDer[LANDAU_DIM];
    290:               ff[idx] = 0.0;
    291:               for (PetscInt d = 0; d < LANDAU_DIM; ++d) refSpaceDer[d] = 0.0;
    292:               for (b = 0; b < Nb; ++b) {
    293:                 const PetscInt cidx = b;
    294:                 ff[idx] += Bq[cidx] * PetscRealPart(coef[f * Nb + cidx]);
    295:                 for (PetscInt d = 0; d < dim; ++d) refSpaceDer[d] += Dq[cidx * dim + d] * PetscRealPart(coef[f * Nb + cidx]);
    296:               }
    297:               for (PetscInt d = 0; d < LANDAU_DIM; ++d) {
    298:                 for (e = 0, u_x[d] = 0.0; e < LANDAU_DIM; ++e) u_x[d] += invJ[e * dim + d] * refSpaceDer[e];
    299:               }
    300:               dudx[idx] = u_x[0];
    301:               dudy[idx] = u_x[1];
    302: #if LANDAU_DIM == 3
    303:               dudz[idx] = u_x[2];
    304: #endif
    305:             }
    306:           } // q
    307:         } // grid
    308:       } // grid*batch
    309:       PetscCall(PetscLogEventEnd(ctx->events[8], 0, 0, 0, 0));
    310: #if defined(PETSC_HAVE_THREADSAFETY)
    311:       endtime = MPI_Wtime();
    312:       if (ctx->stage) ctx->times[LANDAU_F_DF] += (endtime - starttime);
    313: #endif
    314:     } // Jacobian setup
    315:     // assemble Jacobian (or mass)
    316:     for (PetscInt tid = 0; tid < ctx->batch_sz * elem_offset[num_grids]; tid++) { // for each element
    317:       const PetscInt b_Nelem      = elem_offset[num_grids];
    318:       const PetscInt glb_elem_idx = tid % b_Nelem, b_id = tid / b_Nelem;
    319:       PetscInt       grid = 0;
    320: #if defined(PETSC_HAVE_THREADSAFETY)
    321:       double starttime, endtime;
    322:       starttime = MPI_Wtime();
    323: #endif
    324:       while (glb_elem_idx >= elem_offset[grid + 1]) grid++;
    325:       {
    326:         const PetscInt   loc_Nf = ctx->species_offset[grid + 1] - ctx->species_offset[grid], loc_elem = glb_elem_idx - elem_offset[grid];
    327:         const PetscInt   moffset = LAND_MOFFSET(b_id, grid, ctx->batch_sz, ctx->num_grids, ctx->mat_offset), totDim = loc_Nf * Nq, elemMatSize = totDim * totDim;
    328:         PetscScalar     *elemMat;
    329:         const PetscReal *invJe = &invJ_a[(ip_offset[grid] + loc_elem * Nq) * dim * dim];
    330:         PetscCall(PetscMalloc1(elemMatSize, &elemMat));
    331:         PetscCall(PetscMemzero(elemMat, elemMatSize * sizeof(*elemMat)));
    332:         if (shift == 0.0) { // Jacobian
    333:           PetscCall(PetscLogEventBegin(ctx->events[4], 0, 0, 0, 0));
    334:         } else { // mass
    335:           PetscCall(PetscLogEventBegin(ctx->events[16], 0, 0, 0, 0));
    336:         }
    337:         for (PetscInt qj = 0; qj < Nq; ++qj) {
    338:           const PetscInt jpidx_glb = ip_offset[grid] + qj + loc_elem * Nq;
    339:           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
    340:           PetscInt       d, d2, dp, d3, IPf_idx;
    341:           if (shift == 0.0) { // Jacobian
    342:             const PetscReal *const invJj = &invJe[qj * dim * dim];
    343:             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];
    344:             const PetscReal        vj[3] = {xx[jpidx_glb], yy[jpidx_glb], zz ? zz[jpidx_glb] : 0}, wj = ww[jpidx_glb];
    345:             // create g2 & g3
    346:             for (d = 0; d < LANDAU_DIM; d++) { // clear accumulation data D & K
    347:               gg2_temp[d] = 0;
    348:               for (d2 = 0; d2 < LANDAU_DIM; d2++) gg3_temp[d][d2] = 0;
    349:             }
    350:             /* inner beta reduction */
    351:             IPf_idx = 0;
    352:             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
    353:               PetscInt nip_loc_r = numCells[grid_r] * Nq, Nfloc_r = Nf[grid_r];
    354:               for (PetscInt ei_r = 0, loc_fdf_idx = 0; ei_r < numCells[grid_r]; ++ei_r) {
    355:                 for (PetscInt qi = 0; qi < Nq; qi++, ipidx++, loc_fdf_idx++) {
    356:                   const PetscReal wi = ww[ipidx], x = xx[ipidx], y = yy[ipidx];
    357:                   PetscReal       temp1[3] = {0, 0, 0}, temp2 = 0;
    358: #if LANDAU_DIM == 2
    359:                   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.;
    360:                   LandauTensor2D(vj, x, y, Ud, Uk, mask);
    361: #else
    362:                   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.;
    363:                   if (ctx->use_relativistic_corrections) {
    364:                     LandauTensor3DRelativistic(vj, x, y, z, U, mask, C_0(ctx->v_0));
    365:                   } else {
    366:                     LandauTensor3D(vj, x, y, z, U, mask);
    367:                   }
    368: #endif
    369:                   for (PetscInt f = 0; f < Nfloc_r; ++f) {
    370:                     const PetscInt idx = b_id * IPf_sz_glb + ipf_offset[grid_r] + f * nip_loc_r + ei_r * Nq + qi; // IPf_idx + f*nip_loc_r + loc_fdf_idx;
    371:                     temp1[0] += dudx[idx] * nu_beta[f + f_off] * invMass[f + f_off] * (*lambdas)[grid][grid_r];
    372:                     temp1[1] += dudy[idx] * nu_beta[f + f_off] * invMass[f + f_off] * (*lambdas)[grid][grid_r];
    373: #if LANDAU_DIM == 3
    374:                     temp1[2] += dudz[idx] * nu_beta[f + f_off] * invMass[f + f_off] * (*lambdas)[grid][grid_r];
    375: #endif
    376:                     temp2 += ff[idx] * nu_beta[f + f_off] * (*lambdas)[grid][grid_r];
    377:                   }
    378:                   temp1[0] *= wi;
    379:                   temp1[1] *= wi;
    380: #if LANDAU_DIM == 3
    381:                   temp1[2] *= wi;
    382: #endif
    383:                   temp2 *= wi;
    384: #if LANDAU_DIM == 2
    385:                   for (d2 = 0; d2 < 2; d2++) {
    386:                     for (d3 = 0; d3 < 2; ++d3) {
    387:                       /* K = U * grad(f): g2=e: i,A */
    388:                       gg2_temp[d2] += Uk[d2][d3] * temp1[d3];
    389:                       /* D = -U * (I \kron (fx)): g3=f: i,j,A */
    390:                       gg3_temp[d2][d3] += Ud[d2][d3] * temp2;
    391:                     }
    392:                   }
    393: #else
    394:                   for (d2 = 0; d2 < 3; ++d2) {
    395:                     for (d3 = 0; d3 < 3; ++d3) {
    396:                       /* K = U * grad(f): g2 = e: i,A */
    397:                       gg2_temp[d2] += U[d2][d3] * temp1[d3];
    398:                       /* D = -U * (I \kron (fx)): g3 = f: i,j,A */
    399:                       gg3_temp[d2][d3] += U[d2][d3] * temp2;
    400:                     }
    401:                   }
    402: #endif
    403:                 } // qi
    404:               } // ei_r
    405:               IPf_idx += nip_loc_r * Nfloc_r;
    406:             } /* grid_r - IPs */
    407:             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);
    408:             // add alpha and put in gg2/3
    409:             for (PetscInt fieldA = 0, f_off = ctx->species_offset[grid]; fieldA < loc_Nf; ++fieldA) {
    410:               for (d2 = 0; d2 < LANDAU_DIM; d2++) {
    411:                 gg2[fieldA][d2] = gg2_temp[d2] * nu_alpha[fieldA + f_off];
    412:                 for (d3 = 0; d3 < LANDAU_DIM; d3++) gg3[fieldA][d2][d3] = -gg3_temp[d2][d3] * nu_alpha[fieldA + f_off] * invMass[fieldA + f_off];
    413:               }
    414:             }
    415:             /* add electric field term once per IP */
    416:             for (PetscInt fieldA = 0, f_off = ctx->species_offset[grid]; fieldA < loc_Nf; ++fieldA) gg2[fieldA][LANDAU_DIM - 1] += Eq_m[fieldA + f_off];
    417:             /* Jacobian transform - g2, g3 */
    418:             for (PetscInt fieldA = 0; fieldA < loc_Nf; ++fieldA) {
    419:               for (d = 0; d < dim; ++d) {
    420:                 g2[fieldA][d] = 0.0;
    421:                 for (d2 = 0; d2 < dim; ++d2) {
    422:                   g2[fieldA][d] += invJj[d * dim + d2] * gg2[fieldA][d2];
    423:                   g3[fieldA][d][d2] = 0.0;
    424:                   for (d3 = 0; d3 < dim; ++d3) {
    425:                     for (dp = 0; dp < dim; ++dp) g3[fieldA][d][d2] += invJj[d * dim + d3] * gg3[fieldA][d3][dp] * invJj[d2 * dim + dp];
    426:                   }
    427:                   g3[fieldA][d][d2] *= wj;
    428:                 }
    429:                 g2[fieldA][d] *= wj;
    430:               }
    431:             }
    432:           } else { // mass
    433:             PetscReal wj = ww[jpidx_glb];
    434:             /* Jacobian transform - g0 */
    435:             for (PetscInt fieldA = 0; fieldA < loc_Nf; ++fieldA) {
    436:               if (dim == 2) {
    437:                 g0[fieldA] = wj * shift * 2. * PETSC_PI; // move this to below and remove g0
    438:               } else {
    439:                 g0[fieldA] = wj * shift; // move this to below and remove g0
    440:               }
    441:             }
    442:           }
    443:           /* FE matrix construction */
    444:           {
    445:             PetscInt         fieldA, d, f, d2, g;
    446:             const PetscReal *BJq = &BB[qj * Nb], *DIq = &DD[qj * Nb * dim];
    447:             /* assemble - on the diagonal (I,I) */
    448:             for (fieldA = 0; fieldA < loc_Nf; fieldA++) {
    449:               for (f = 0; f < Nb; f++) {
    450:                 const PetscInt i = fieldA * Nb + f; /* Element matrix row */
    451:                 for (g = 0; g < Nb; ++g) {
    452:                   const PetscInt j    = fieldA * Nb + g; /* Element matrix column */
    453:                   const PetscInt fOff = i * totDim + j;
    454:                   if (shift == 0.0) {
    455:                     for (d = 0; d < dim; ++d) {
    456:                       elemMat[fOff] += DIq[f * dim + d] * g2[fieldA][d] * BJq[g];
    457:                       for (d2 = 0; d2 < dim; ++d2) elemMat[fOff] += DIq[f * dim + d] * g3[fieldA][d][d2] * DIq[g * dim + d2];
    458:                     }
    459:                   } else { // mass
    460:                     elemMat[fOff] += BJq[f] * g0[fieldA] * BJq[g];
    461:                   }
    462:                 }
    463:               }
    464:             }
    465:           }
    466:         } /* qj loop */
    467:         if (shift == 0.0) { // Jacobian
    468:           PetscCall(PetscLogEventEnd(ctx->events[4], 0, 0, 0, 0));
    469:         } else {
    470:           PetscCall(PetscLogEventEnd(ctx->events[16], 0, 0, 0, 0));
    471:         }
    472: #if defined(PETSC_HAVE_THREADSAFETY)
    473:         endtime = MPI_Wtime();
    474:         if (ctx->stage) ctx->times[LANDAU_KERNEL] += (endtime - starttime);
    475: #endif
    476:         /* assemble matrix */
    477:         if (!container) {
    478:           PetscInt cStart;
    479:           PetscCall(PetscLogEventBegin(ctx->events[6], 0, 0, 0, 0));
    480:           PetscCall(DMPlexGetHeightStratum(ctx->plex[grid], 0, &cStart, NULL));
    481:           PetscCall(DMPlexMatSetClosure(ctx->plex[grid], section[grid], globsection[grid], subJ[LAND_PACK_IDX(b_id, grid)], loc_elem + cStart, elemMat, ADD_VALUES));
    482:           PetscCall(PetscLogEventEnd(ctx->events[6], 0, 0, 0, 0));
    483:         } else { // GPU like assembly for debugging
    484:           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];
    485:           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};
    486:           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;
    487:           /* assemble - from the diagonal (I,I) in this format for DMPlexMatSetClosure */
    488:           for (fieldA = 0; fieldA < loc_Nf; fieldA++) {
    489:             LandauIdx *const Idxs = &maps[grid].gIdx[loc_elem][fieldA][0];
    490:             for (f = 0; f < Nb; f++) {
    491:               PetscInt idx = Idxs[f];
    492:               if (idx >= 0) {
    493:                 nr           = 1;
    494:                 rows0[0]     = idx;
    495:                 row_scale[0] = 1.;
    496:               } else {
    497:                 idx = -idx - 1;
    498:                 for (q = 0, nr = 0; q < maps[grid].num_face; q++, nr++) {
    499:                   if (maps[grid].c_maps[idx][q].gid < 0) break;
    500:                   rows0[q]     = maps[grid].c_maps[idx][q].gid;
    501:                   row_scale[q] = maps[grid].c_maps[idx][q].scale;
    502:                 }
    503:               }
    504:               for (g = 0; g < Nb; ++g) {
    505:                 idx = Idxs[g];
    506:                 if (idx >= 0) {
    507:                   nc           = 1;
    508:                   cols0[0]     = idx;
    509:                   col_scale[0] = 1.;
    510:                 } else {
    511:                   idx = -idx - 1;
    512:                   nc  = maps[grid].num_face;
    513:                   for (q = 0, nc = 0; q < maps[grid].num_face; q++, nc++) {
    514:                     if (maps[grid].c_maps[idx][q].gid < 0) break;
    515:                     cols0[q]     = maps[grid].c_maps[idx][q].gid;
    516:                     col_scale[q] = maps[grid].c_maps[idx][q].scale;
    517:                   }
    518:                 }
    519:                 const PetscInt    i   = fieldA * Nb + f; /* Element matrix row */
    520:                 const PetscInt    j   = fieldA * Nb + g; /* Element matrix column */
    521:                 const PetscScalar Aij = elemMat[i * totDim + j];
    522:                 if (coo_vals) { // mirror (i,j) in CreateStaticGPUData
    523:                   const PetscInt fullNb = coo_elem_fullNb[glb_elem_idx], fullNb2 = fullNb * fullNb;
    524:                   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];
    525:                   for (PetscInt q = 0, idx2 = idx0; q < nr; q++) {
    526:                     for (PetscInt d = 0; d < nc; d++, idx2++) coo_vals[idx2] = row_scale[q] * col_scale[d] * Aij;
    527:                   }
    528:                 } else {
    529:                   for (q = 0; q < nr; q++) rows[q] = rows0[q] + moffset;
    530:                   for (d = 0; d < nc; d++) cols[d] = cols0[d] + moffset;
    531:                   for (q = 0; q < nr; q++) {
    532:                     for (d = 0; d < nc; d++) vals[q * nc + d] = row_scale[q] * col_scale[d] * Aij;
    533:                   }
    534:                   PetscCall(MatSetValues(JacP, nr, rows, nc, cols, vals, ADD_VALUES));
    535:                 }
    536:               }
    537:             }
    538:           }
    539:         }
    540:         if (loc_elem == -1) {
    541:           PetscCall(PetscPrintf(ctx->comm, "CPU Element matrix\n"));
    542:           for (PetscInt d = 0; d < totDim; ++d) {
    543:             for (PetscInt f = 0; f < totDim; ++f) PetscCall(PetscPrintf(ctx->comm, " %12.5e", (double)PetscRealPart(elemMat[d * totDim + f])));
    544:             PetscCall(PetscPrintf(ctx->comm, "\n"));
    545:           }
    546:           exit(12);
    547:         }
    548:         PetscCall(PetscFree(elemMat));
    549:       } /* grid */
    550:     } /* outer element & batch loop */
    551:     if (shift == 0.0) { // mass
    552:       PetscCall(PetscFree4(ff, dudx, dudy, dudz));
    553:     }
    554:     if (!container) {                                         // 'CPU' assembly move nest matrix to global JacP
    555:       for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) { // OpenMP
    556:         for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    557:           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];
    558:           PetscInt           nloc, nzl, colbuf[1024], row;
    559:           const PetscInt    *cols;
    560:           const PetscScalar *vals;
    561:           Mat                B = subJ[LAND_PACK_IDX(b_id, grid)];
    562:           PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
    563:           PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
    564:           PetscCall(MatGetSize(B, &nloc, NULL));
    565:           for (PetscInt i = 0; i < nloc; i++) {
    566:             PetscCall(MatGetRow(B, i, &nzl, &cols, &vals));
    567:             PetscCheck(nzl <= 1024, PetscObjectComm((PetscObject)B), PETSC_ERR_PLIB, "Row too big: %" PetscInt_FMT, nzl);
    568:             for (PetscInt j = 0; j < nzl; j++) colbuf[j] = moffset + cols[j];
    569:             row = moffset + i;
    570:             PetscCall(MatSetValues(JacP, 1, &row, nzl, colbuf, vals, ADD_VALUES));
    571:             PetscCall(MatRestoreRow(B, i, &nzl, &cols, &vals));
    572:           }
    573:           PetscCall(MatDestroy(&B));
    574:         }
    575:       }
    576:     }
    577:     if (coo_vals) {
    578:       PetscCall(MatSetValuesCOO(JacP, coo_vals, ADD_VALUES));
    579:       PetscCall(PetscFree(coo_vals));
    580:     }
    581:   } /* CPU version */
    582:   PetscCall(MatAssemblyBegin(JacP, MAT_FINAL_ASSEMBLY));
    583:   PetscCall(MatAssemblyEnd(JacP, MAT_FINAL_ASSEMBLY));
    584:   /* clean up */
    585:   if (cellClosure) PetscCall(PetscFree(cellClosure));
    586:   if (xdata) PetscCall(VecRestoreArrayReadAndMemType(a_X, &xdata));
    587:   PetscFunctionReturn(PETSC_SUCCESS);
    588: }

    590: static PetscErrorCode GeometryDMLandau(DM base, PetscInt point, PetscInt dim, const PetscReal abc[], PetscReal xyz[], void *a_ctx)
    591: {
    592:   PetscReal  r = abc[0], z = abc[1];
    593:   LandauCtx *ctx = (LandauCtx *)a_ctx;

    595:   PetscFunctionBegin;
    596:   if (ctx->sphere && dim == 3) { // make sphere: works for one AMR and Q2
    597:     PetscInt nzero = 0, idx = 0;
    598:     xyz[0] = r;
    599:     xyz[1] = z;
    600:     xyz[2] = abc[2];
    601:     for (PetscInt i = 0; i < 3; i++) {
    602:       if (PetscAbs(xyz[i]) < PETSC_SQRT_MACHINE_EPSILON) nzero++;
    603:       else idx = i;
    604:     }
    605:     if (nzero == 2) xyz[idx] *= 1.732050807568877; // sqrt(3)
    606:     else if (nzero == 1) {
    607:       for (PetscInt i = 0; i < 3; i++) xyz[i] *= 1.224744871391589; // sqrt(3/2)
    608:     }
    609:   } else {
    610:     xyz[0] = r;
    611:     xyz[1] = z;
    612:     if (dim == 3) xyz[2] = abc[2];
    613:   }
    614:   PetscFunctionReturn(PETSC_SUCCESS);
    615: }

    617: /* create DMComposite of meshes for each species group */
    618: static PetscErrorCode LandauDMCreateVMeshes(MPI_Comm comm_self, const PetscInt dim, const char prefix[], LandauCtx *ctx, DM pack)
    619: {
    620:   PetscFunctionBegin;
    621:   { /* p4est, quads */
    622:     /* Create plex mesh of Landau domain */
    623:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    624:       PetscReal par_radius = ctx->radius_par[grid], perp_radius = ctx->radius_perp[grid];
    625:       if (!ctx->sphere && !ctx->simplex) { // 2 or 3D (only 3D option)
    626:         PetscReal      lo[] = {-perp_radius, -par_radius, -par_radius}, hi[] = {perp_radius, par_radius, par_radius};
    627:         DMBoundaryType periodicity[3] = {DM_BOUNDARY_NONE, dim == 2 ? DM_BOUNDARY_NONE : DM_BOUNDARY_NONE, DM_BOUNDARY_NONE};
    628:         if (dim == 2) lo[0] = 0;
    629:         else {
    630:           lo[1] = -perp_radius;
    631:           hi[1] = perp_radius; // 3D y is a perp
    632:         }
    633:         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
    634:         PetscCall(DMLocalizeCoordinates(ctx->plex[grid]));                                                                                          /* needed for periodic */
    635:         if (dim == 3) PetscCall(PetscObjectSetName((PetscObject)ctx->plex[grid], "cube"));
    636:         else PetscCall(PetscObjectSetName((PetscObject)ctx->plex[grid], "half-plane"));
    637:       } else if (dim == 2) {
    638:         size_t len;
    639:         PetscCall(PetscStrlen(ctx->filename, &len));
    640:         if (len) {
    641:           Vec          coords;
    642:           PetscScalar *x;
    643:           PetscInt     N;
    644:           char         str[] = "-dm_landau_view_file_0";
    645:           str[21] += grid;
    646:           PetscCall(DMPlexCreateFromFile(comm_self, ctx->filename, "plexland.c", PETSC_TRUE, &ctx->plex[grid]));
    647:           PetscCall(DMPlexOrient(ctx->plex[grid]));
    648:           PetscCall(DMGetCoordinatesLocal(ctx->plex[grid], &coords));
    649:           PetscCall(VecGetSize(coords, &N));
    650:           PetscCall(VecGetArray(coords, &x));
    651:           /* scale by domain size */
    652:           for (PetscInt i = 0; i < N; i += 2) {
    653:             x[i + 0] *= ctx->radius_perp[grid];
    654:             x[i + 1] *= ctx->radius_par[grid];
    655:           }
    656:           PetscCall(VecRestoreArray(coords, &x));
    657:           PetscCall(PetscObjectSetName((PetscObject)ctx->plex[grid], ctx->filename));
    658:           PetscCall(PetscInfo(ctx->plex[grid], "%d) Read %s mesh file (%s)\n", (int)grid, ctx->filename, str));
    659:           PetscCall(DMViewFromOptions(ctx->plex[grid], NULL, str));
    660:         } else { // simplex forces a sphere
    661:           PetscInt       numCells = ctx->simplex ? 12 : 6, cell_size = ctx->simplex ? 3 : 4, j;
    662:           const PetscInt numVerts    = 11;
    663:           PetscInt       cellsT[][4] = {
    664:             {0,  1, 6, 5 },
    665:             {1,  2, 7, 6 },
    666:             {2,  3, 8, 7 },
    667:             {3,  4, 9, 8 },
    668:             {5,  6, 7, 10},
    669:             {10, 7, 8, 9 }
    670:           };
    671:           PetscInt cellsS[][3] = {
    672:             {0,  1, 6 },
    673:             {1,  2, 6 },
    674:             {6,  2, 7 },
    675:             {7,  2, 8 },
    676:             {8,  2, 3 },
    677:             {8,  3, 4 },
    678:             {0,  6, 5 },
    679:             {5,  6, 7 },
    680:             {5,  7, 10},
    681:             {10, 7, 9 },
    682:             {9,  7, 8 },
    683:             {9,  8, 4 }
    684:           };
    685:           const PetscInt *pcell = (const PetscInt *)(ctx->simplex ? &cellsS[0][0] : &cellsT[0][0]);
    686:           PetscReal       coords[11][2], *flatCoords = (PetscReal *)&coords[0][0];
    687:           PetscReal       rad = ctx->radius[grid];
    688:           for (j = 0; j < 5; j++) { // outside edge
    689:             PetscReal z, r, theta = -PETSC_PI / 2 + (j % 5) * PETSC_PI / 4;
    690:             r            = rad * PetscCosReal(theta);
    691:             coords[j][0] = r;
    692:             z            = rad * PetscSinReal(theta);
    693:             coords[j][1] = z;
    694:           }
    695:           coords[j][0]   = 0;
    696:           coords[j++][1] = -rad * ctx->sphere_inner_radius_90degree[grid];
    697:           coords[j][0]   = rad * ctx->sphere_inner_radius_45degree[grid] * 0.707106781186548;
    698:           coords[j++][1] = -rad * ctx->sphere_inner_radius_45degree[grid] * 0.707106781186548;
    699:           coords[j][0]   = rad * ctx->sphere_inner_radius_90degree[grid];
    700:           coords[j++][1] = 0;
    701:           coords[j][0]   = rad * ctx->sphere_inner_radius_45degree[grid] * 0.707106781186548;
    702:           coords[j++][1] = rad * ctx->sphere_inner_radius_45degree[grid] * 0.707106781186548;
    703:           coords[j][0]   = 0;
    704:           coords[j++][1] = rad * ctx->sphere_inner_radius_90degree[grid];
    705:           coords[j][0]   = 0;
    706:           coords[j++][1] = 0;
    707:           PetscCall(DMPlexCreateFromCellListPetsc(comm_self, 2, numCells, numVerts, cell_size, ctx->interpolate, pcell, 2, flatCoords, &ctx->plex[grid]));
    708:           PetscCall(PetscObjectSetName((PetscObject)ctx->plex[grid], "semi-circle"));
    709:           PetscCall(PetscInfo(ctx->plex[grid], "\t%" PetscInt_FMT ") Make circle %s mesh\n", grid, ctx->simplex ? "simplex" : "tensor"));
    710:         }
    711:       } else {
    712:         PetscCheck(dim == 3 && ctx->sphere && !ctx->simplex, ctx->comm, PETSC_ERR_ARG_WRONG, "not: dim == 3 && ctx->sphere && !ctx->simplex");
    713:         PetscReal      rad = ctx->radius[grid] / 1.732050807568877, inner_rad = rad * ctx->sphere_inner_radius_45degree[grid], outer_rad = rad;
    714:         const PetscInt numCells = 7, cell_size = 8, numVerts = 16;
    715:         const PetscInt cells[][8] = {
    716:           {0, 3, 2, 1, 4,  5,  6,  7 },
    717:           {0, 4, 5, 1, 8,  9,  13, 12},
    718:           {1, 5, 6, 2, 9,  10, 14, 13},
    719:           {2, 6, 7, 3, 10, 11, 15, 14},
    720:           {0, 3, 7, 4, 8,  12, 15, 11},
    721:           {0, 1, 2, 3, 8,  11, 10, 9 },
    722:           {4, 7, 6, 5, 12, 13, 14, 15}
    723:         };
    724:         PetscReal coords[16 /* numVerts */][3];
    725:         for (PetscInt j = 0; j < 4; j++) { // inner edge, low
    726:           coords[j][0] = inner_rad * (j == 0 || j == 3 ? 1 : -1);
    727:           coords[j][1] = inner_rad * (j / 2 < 1 ? 1 : -1);
    728:           coords[j][2] = inner_rad * -1;
    729:         }
    730:         for (PetscInt j = 0, jj = 4; j < 4; j++, jj++) { // inner edge, hi
    731:           coords[jj][0] = inner_rad * (j == 0 || j == 3 ? 1 : -1);
    732:           coords[jj][1] = inner_rad * (j / 2 < 1 ? 1 : -1);
    733:           coords[jj][2] = inner_rad * 1;
    734:         }
    735:         for (PetscInt j = 0, jj = 8; j < 4; j++, jj++) { // outer edge, low
    736:           coords[jj][0] = outer_rad * (j == 0 || j == 3 ? 1 : -1);
    737:           coords[jj][1] = outer_rad * (j / 2 < 1 ? 1 : -1);
    738:           coords[jj][2] = outer_rad * -1;
    739:         }
    740:         for (PetscInt j = 0, jj = 12; j < 4; j++, jj++) { // outer edge, hi
    741:           coords[jj][0] = outer_rad * (j == 0 || j == 3 ? 1 : -1);
    742:           coords[jj][1] = outer_rad * (j / 2 < 1 ? 1 : -1);
    743:           coords[jj][2] = outer_rad * 1;
    744:         }
    745:         PetscCall(DMPlexCreateFromCellListPetsc(comm_self, 3, numCells, numVerts, cell_size, ctx->interpolate, (const PetscInt *)cells, 3, (const PetscReal *)coords, &ctx->plex[grid]));
    746:         PetscCall(PetscObjectSetName((PetscObject)ctx->plex[grid], "cubed sphere"));
    747:         PetscCall(PetscInfo(ctx->plex[grid], "\t%" PetscInt_FMT ") Make cubed sphere %s mesh\n", grid, ctx->simplex ? "simplex" : "tensor"));
    748:       }
    749:       PetscCall(DMSetFromOptions(ctx->plex[grid]));
    750:     } // grid loop
    751:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)pack, prefix));
    752:     { /* convert to p4est (or whatever), wait for discretization to create pack */
    753:       char      convType[256];
    754:       PetscBool flg;

    756:       PetscOptionsBegin(ctx->comm, prefix, "Mesh conversion options", "DMPLEX");
    757:       PetscCall(PetscOptionsFList("-dm_landau_type", "Convert DMPlex to another format (p4est)", "plexland.c", DMList, DMPLEX, convType, 256, &flg));
    758:       PetscOptionsEnd();
    759:       if (flg) {
    760:         ctx->use_p4est = PETSC_TRUE; /* flag for Forest */
    761:         for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    762:           DM dmforest;
    763:           PetscCall(DMConvert(ctx->plex[grid], convType, &dmforest));
    764:           if (dmforest) {
    765:             PetscBool isForest;
    766:             PetscCall(PetscObjectSetOptionsPrefix((PetscObject)dmforest, prefix));
    767:             PetscCall(DMIsForest(dmforest, &isForest));
    768:             if (isForest) {
    769:               if (ctx->sphere) PetscCall(DMForestSetBaseCoordinateMapping(dmforest, GeometryDMLandau, ctx));
    770:               PetscCall(DMDestroy(&ctx->plex[grid]));
    771:               ctx->plex[grid] = dmforest; // Forest for adaptivity
    772:             } else SETERRQ(ctx->comm, PETSC_ERR_PLIB, "Converted to non Forest?");
    773:           } else SETERRQ(ctx->comm, PETSC_ERR_PLIB, "Convert failed?");
    774:         }
    775:       } else ctx->use_p4est = PETSC_FALSE; /* flag for Forest */
    776:     }
    777:   } /* non-file */
    778:   PetscCall(DMSetDimension(pack, dim));
    779:   PetscCall(PetscObjectSetName((PetscObject)pack, "Mesh"));
    780:   PetscCall(DMSetApplicationContext(pack, ctx));
    781:   PetscFunctionReturn(PETSC_SUCCESS);
    782: }

    784: static PetscErrorCode SetupDS(DM pack, PetscInt dim, PetscInt grid, LandauCtx *ctx)
    785: {
    786:   PetscInt     ii, i0;
    787:   char         buf[256];
    788:   PetscSection section;

    790:   PetscFunctionBegin;
    791:   for (ii = ctx->species_offset[grid], i0 = 0; ii < ctx->species_offset[grid + 1]; ii++, i0++) {
    792:     if (ii == 0) PetscCall(PetscSNPrintf(buf, sizeof(buf), "e"));
    793:     else PetscCall(PetscSNPrintf(buf, sizeof(buf), "i%" PetscInt_FMT, ii));
    794:     /* Setup Discretization - FEM */
    795:     PetscCall(PetscFECreateDefault(PETSC_COMM_SELF, dim, 1, ctx->simplex, NULL, PETSC_DECIDE, &ctx->fe[ii]));
    796:     PetscCall(PetscObjectSetName((PetscObject)ctx->fe[ii], buf));
    797:     PetscCall(DMSetField(ctx->plex[grid], i0, NULL, (PetscObject)ctx->fe[ii]));
    798:   }
    799:   PetscCall(DMCreateDS(ctx->plex[grid]));
    800:   PetscCall(DMGetSection(ctx->plex[grid], &section));
    801:   for (PetscInt ii = ctx->species_offset[grid], i0 = 0; ii < ctx->species_offset[grid + 1]; ii++, i0++) {
    802:     if (ii == 0) PetscCall(PetscSNPrintf(buf, sizeof(buf), "se"));
    803:     else PetscCall(PetscSNPrintf(buf, sizeof(buf), "si%" PetscInt_FMT, ii));
    804:     PetscCall(PetscSectionSetComponentName(section, i0, 0, buf));
    805:   }
    806:   PetscFunctionReturn(PETSC_SUCCESS);
    807: }

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

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

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

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

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

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

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

    826: typedef struct {
    827:   PetscReal v_0;
    828:   PetscReal kT_m;
    829:   PetscReal n;
    830:   PetscReal shift;
    831: } MaxwellianCtx;

    833: static PetscErrorCode maxwellian(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf_dummy, PetscScalar *u, void *actx)
    834: {
    835:   MaxwellianCtx *mctx = (MaxwellianCtx *)actx;
    836:   PetscInt       i;
    837:   PetscReal      v2 = 0, theta = 2 * mctx->kT_m / (mctx->v_0 * mctx->v_0), shift; /* theta = 2kT/mc^2 */

    839:   PetscFunctionBegin;
    840:   /* compute the exponents, v^2 */
    841:   for (i = 0; i < dim; ++i) v2 += x[i] * x[i];
    842:   /* evaluate the Maxwellian */
    843:   if (mctx->shift < 0) shift = -mctx->shift;
    844:   else {
    845:     u[0]  = mctx->n * PetscPowReal(PETSC_PI * theta, -1.5) * (PetscExpReal(-v2 / theta));
    846:     shift = mctx->shift;
    847:   }
    848:   if (shift != 0.) {
    849:     v2 = 0;
    850:     for (i = 0; i < dim - 1; ++i) v2 += x[i] * x[i];
    851:     v2 += (x[dim - 1] - shift) * (x[dim - 1] - shift);
    852:     /* evaluate the shifted Maxwellian */
    853:     u[0] += mctx->n * PetscPowReal(PETSC_PI * theta, -1.5) * (PetscExpReal(-v2 / theta));
    854:   }
    855:   PetscFunctionReturn(PETSC_SUCCESS);
    856: }

    858: /*@
    859:   DMPlexLandauAddMaxwellians - Add a Maxwellian distribution to a state

    861:   Collective

    863:   Input Parameters:
    864: + dm      - The mesh (local)
    865: . time    - Current time
    866: . temps   - Temperatures of each species (global)
    867: . ns      - Number density of each species (global)
    868: . grid    - index into current grid - just used for offset into `temp` and `ns`
    869: . b_id    - batch index
    870: . n_batch - number of batches
    871: - actx    - Landau context

    873:   Output Parameter:
    874: . X - The state (local to this grid)

    876:   Level: beginner

    878: .seealso: `DMPlexLandauCreateVelocitySpace()`
    879:  @*/
    880: PetscErrorCode DMPlexLandauAddMaxwellians(DM dm, Vec X, PetscReal time, PetscReal temps[], PetscReal ns[], PetscInt grid, PetscInt b_id, PetscInt n_batch, void *actx)
    881: {
    882:   LandauCtx *ctx = (LandauCtx *)actx;
    883:   PetscErrorCode (*initu[LANDAU_MAX_SPECIES])(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
    884:   PetscInt       dim;
    885:   MaxwellianCtx *mctxs[LANDAU_MAX_SPECIES], data[LANDAU_MAX_SPECIES];

    887:   PetscFunctionBegin;
    888:   PetscCall(DMGetDimension(dm, &dim));
    889:   if (!ctx) PetscCall(DMGetApplicationContext(dm, &ctx));
    890:   for (PetscInt ii = ctx->species_offset[grid], i0 = 0; ii < ctx->species_offset[grid + 1]; ii++, i0++) {
    891:     mctxs[i0]      = &data[i0];
    892:     data[i0].v_0   = ctx->v_0;                             // v_0 same for all grids
    893:     data[i0].kT_m  = ctx->k * temps[ii] / ctx->masses[ii]; /* kT/m */
    894:     data[i0].n     = ns[ii];
    895:     initu[i0]      = maxwellian;
    896:     data[i0].shift = 0;
    897:   }
    898:   data[0].shift = ctx->electronShift;
    899:   /* need to make ADD_ALL_VALUES work - TODO */
    900:   PetscCall(DMProjectFunction(dm, time, initu, (void **)mctxs, INSERT_ALL_VALUES, X));
    901:   PetscFunctionReturn(PETSC_SUCCESS);
    902: }

    904: /*
    905:  LandauSetInitialCondition - Adds Maxwellians with context

    907:  Collective

    909:  Input Parameters:
    910:  .   dm - The mesh
    911:  -   grid - index into current grid - just used for offset into temp and ns
    912:  .   b_id - batch index
    913:  -   n_batch - number of batches
    914:  +   actx - Landau context with T and n

    916:  Output Parameter:
    917:  .   X  - The state

    919:  Level: beginner

    921: .seealso: `DMPlexLandauCreateVelocitySpace()`, `DMPlexLandauAddMaxwellians()`
    922:  */
    923: static PetscErrorCode LandauSetInitialCondition(DM dm, Vec X, PetscInt grid, PetscInt b_id, PetscInt n_batch, void *actx)
    924: {
    925:   LandauCtx *ctx = (LandauCtx *)actx;

    927:   PetscFunctionBegin;
    928:   if (!ctx) PetscCall(DMGetApplicationContext(dm, &ctx));
    929:   PetscCall(VecZeroEntries(X));
    930:   PetscCall(DMPlexLandauAddMaxwellians(dm, X, 0.0, ctx->thermal_temps, ctx->n, grid, b_id, n_batch, ctx));
    931:   PetscFunctionReturn(PETSC_SUCCESS);
    932: }

    934: // adapt a level once. Forest in/out
    935: #if defined(PETSC_USE_INFO)
    936: static const char *s_refine_names[] = {"RE", "Z1", "Origin", "Z2", "Uniform"};
    937: #endif
    938: static PetscErrorCode adaptToleranceFEM(PetscFE fem, Vec sol, PetscInt type, PetscInt grid, LandauCtx *ctx, DM *newForest)
    939: {
    940:   DM              forest, plex, adaptedDM = NULL;
    941:   PetscDS         prob;
    942:   PetscBool       isForest;
    943:   PetscQuadrature quad;
    944:   PetscInt        Nq, Nb, *Nb2, cStart, cEnd, c, dim, qj, k;
    945:   DMLabel         adaptLabel = NULL;

    947:   PetscFunctionBegin;
    948:   forest = ctx->plex[grid];
    949:   PetscCall(DMCreateDS(forest));
    950:   PetscCall(DMGetDS(forest, &prob));
    951:   PetscCall(DMGetDimension(forest, &dim));
    952:   PetscCall(DMIsForest(forest, &isForest));
    953:   PetscCheck(isForest, ctx->comm, PETSC_ERR_ARG_WRONG, "! Forest");
    954:   PetscCall(DMConvert(forest, DMPLEX, &plex));
    955:   PetscCall(DMPlexGetHeightStratum(plex, 0, &cStart, &cEnd));
    956:   PetscCall(DMLabelCreate(PETSC_COMM_SELF, "adapt", &adaptLabel));
    957:   PetscCall(PetscFEGetQuadrature(fem, &quad));
    958:   PetscCall(PetscQuadratureGetData(quad, NULL, NULL, &Nq, NULL, NULL));
    959:   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);
    960:   PetscCall(PetscFEGetDimension(ctx->fe[0], &Nb));
    961:   PetscCall(PetscDSGetDimensions(prob, &Nb2));
    962:   PetscCheck(Nb2[0] == Nb, ctx->comm, PETSC_ERR_ARG_WRONG, " Nb = %" PetscInt_FMT " != Nb (%d)", Nb, (int)Nb2[0]);
    963:   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);
    964:   PetscCall(PetscInfo(sol, "%" PetscInt_FMT ") Refine phase: %s\n", grid, s_refine_names[type]));
    965:   if (type == 4) {
    966:     for (c = cStart; c < cEnd; c++) PetscCall(DMLabelSetValue(adaptLabel, c, DM_ADAPT_REFINE));
    967:   } else if (type == 2) {
    968:     PetscInt  rCellIdx[8], nr = 0, nrmax = (dim == 3) ? 8 : 2;
    969:     PetscReal minRad = PETSC_INFINITY, r;
    970:     for (c = cStart; c < cEnd; c++) {
    971:       PetscReal tt, v0[LANDAU_MAX_NQND * 3], J[LANDAU_MAX_NQND * 9], invJ[LANDAU_MAX_NQND * 9], detJ[LANDAU_MAX_NQND];
    972:       PetscCall(DMPlexComputeCellGeometryFEM(plex, c, quad, v0, J, invJ, detJ));
    973:       (void)J;
    974:       (void)invJ;
    975:       for (qj = 0; qj < Nq; ++qj) {
    976:         tt = PetscSqr(v0[dim * qj + 0]) + PetscSqr(v0[dim * qj + 1]) + PetscSqr((dim == 3) ? v0[dim * qj + 2] : 0);
    977:         r  = PetscSqrtReal(tt);
    978:         if (r < minRad - PETSC_SQRT_MACHINE_EPSILON * 10.) {
    979:           minRad         = r;
    980:           nr             = 0;
    981:           rCellIdx[nr++] = c;
    982:           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));
    983:         } else if ((r - minRad) < PETSC_SQRT_MACHINE_EPSILON * 100. && nr < nrmax) {
    984:           for (k = 0; k < nr; k++)
    985:             if (c == rCellIdx[k]) break;
    986:           if (k == nr) {
    987:             rCellIdx[nr++] = c;
    988:             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)));
    989:           }
    990:         }
    991:       }
    992:     }
    993:     for (k = 0; k < nr; k++) PetscCall(DMLabelSetValue(adaptLabel, rCellIdx[k], DM_ADAPT_REFINE));
    994:     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));
    995:   } else if (type == 0 || type == 1 || type == 3) { /* refine along r=0 axis */
    996:     PetscScalar *coef = NULL;
    997:     Vec          coords;
    998:     PetscInt     csize, Nv, d, nz, nrefined = 0;
    999:     DM           cdm;
    1000:     PetscSection cs;
    1001:     PetscCall(DMGetCoordinatesLocal(forest, &coords));
    1002:     PetscCall(DMGetCoordinateDM(forest, &cdm));
    1003:     PetscCall(DMGetLocalSection(cdm, &cs));
    1004:     for (c = cStart; c < cEnd; c++) {
    1005:       PetscInt doit = 0, outside = 0;
    1006:       PetscCall(DMPlexVecGetClosure(cdm, cs, coords, c, &csize, &coef));
    1007:       Nv = csize / dim;
    1008:       for (nz = d = 0; d < Nv; d++) {
    1009:         PetscReal z = PetscRealPart(coef[d * dim + (dim - 1)]), x = PetscSqr(PetscRealPart(coef[d * dim + 0])) + ((dim == 3) ? PetscSqr(PetscRealPart(coef[d * dim + 1])) : 0);
    1010:         x = PetscSqrtReal(x);
    1011:         if (type == 0) {
    1012:           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 */
    1013:         } else if (type == 1 && (z > ctx->vperp0_radius1 || z < -ctx->vperp0_radius1)) {
    1014:           outside++; /* don't refine outside electron refine radius */
    1015:           PetscCall(PetscInfo(sol, "\t%" PetscInt_FMT ") (debug) found %s cells\n", grid, s_refine_names[type]));
    1016:         } else if (type == 3 && (z > ctx->vperp0_radius2 || z < -ctx->vperp0_radius2)) {
    1017:           outside++; /* refine r=0 cells on refinement front */
    1018:           PetscCall(PetscInfo(sol, "\t%" PetscInt_FMT ") (debug) found %s cells\n", grid, s_refine_names[type]));
    1019:         }
    1020:         if (x < PETSC_MACHINE_EPSILON * 10. && (type != 0 || ctx->re_radius > PETSC_SQRT_MACHINE_EPSILON)) nz++;
    1021:       }
    1022:       PetscCall(DMPlexVecRestoreClosure(cdm, cs, coords, c, &csize, &coef));
    1023:       if (doit || (outside < Nv && nz)) {
    1024:         PetscCall(DMLabelSetValue(adaptLabel, c, DM_ADAPT_REFINE));
    1025:         nrefined++;
    1026:       }
    1027:     }
    1028:     PetscCall(PetscInfo(sol, "\t%" PetscInt_FMT ") Refined %" PetscInt_FMT " cells\n", grid, nrefined));
    1029:   }
    1030:   PetscCall(DMDestroy(&plex));
    1031:   PetscCall(DMAdaptLabel(forest, adaptLabel, &adaptedDM));
    1032:   PetscCall(DMLabelDestroy(&adaptLabel));
    1033:   *newForest = adaptedDM;
    1034:   if (adaptedDM) {
    1035:     if (isForest) {
    1036:       PetscCall(DMForestSetAdaptivityForest(adaptedDM, NULL)); // ????
    1037:     }
    1038:     PetscCall(DMConvert(adaptedDM, DMPLEX, &plex));
    1039:     PetscCall(DMPlexGetHeightStratum(plex, 0, &cStart, &cEnd));
    1040:     PetscCall(PetscInfo(sol, "\t\t\t\t%" PetscInt_FMT ") %" PetscInt_FMT " cells, %" PetscInt_FMT " total quadrature points\n", grid, cEnd - cStart, Nq * (cEnd - cStart)));
    1041:     PetscCall(DMDestroy(&plex));
    1042:   } else *newForest = NULL;
    1043:   PetscFunctionReturn(PETSC_SUCCESS);
    1044: }

    1046: // forest goes in (ctx->plex[grid]), plex comes out
    1047: static PetscErrorCode adapt(PetscInt grid, LandauCtx *ctx, Vec *uu)
    1048: {
    1049:   PetscInt adaptIter;

    1051:   PetscFunctionBegin;
    1052:   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]};
    1053:   for (type = 0; type < 5; type++) {
    1054:     for (adaptIter = 0; adaptIter < limits[type]; adaptIter++) {
    1055:       DM newForest = NULL;
    1056:       PetscCall(adaptToleranceFEM(ctx->fe[0], *uu, type, grid, ctx, &newForest));
    1057:       if (newForest) {
    1058:         PetscCall(DMDestroy(&ctx->plex[grid]));
    1059:         PetscCall(VecDestroy(uu));
    1060:         PetscCall(DMCreateGlobalVector(newForest, uu));
    1061:         PetscCall(LandauSetInitialCondition(newForest, *uu, grid, 0, 1, ctx));
    1062:         ctx->plex[grid] = newForest;
    1063:       } else {
    1064:         PetscCall(PetscInfo(*uu, "No refinement\n"));
    1065:       }
    1066:     }
    1067:   }
    1068:   PetscCall(PetscObjectSetName((PetscObject)*uu, "uAMR"));
    1069:   PetscFunctionReturn(PETSC_SUCCESS);
    1070: }

    1072: // make log(Lambdas) from NRL Plasma formulary
    1073: static PetscErrorCode makeLambdas(LandauCtx *ctx)
    1074: {
    1075:   PetscFunctionBegin;
    1076:   for (PetscInt gridi = 0; gridi < ctx->num_grids; gridi++) {
    1077:     PetscInt  iii   = ctx->species_offset[gridi];
    1078:     PetscReal Ti_ev = (ctx->thermal_temps[iii] / 1.1604525e7) * 1000; // convert (back) to eV
    1079:     PetscReal ni    = ctx->n[iii] * ctx->n_0;
    1080:     for (PetscInt gridj = gridi; gridj < ctx->num_grids; gridj++) {
    1081:       PetscInt  jjj = ctx->species_offset[gridj];
    1082:       PetscReal Zj  = ctx->charges[jjj] / 1.6022e-19;
    1083:       if (gridi == 0) {
    1084:         if (gridj == 0) { // lam_ee
    1085:           ctx->lambdas[gridi][gridj] = 23.5 - PetscLogReal(PetscSqrtReal(ni) * PetscPowReal(Ti_ev, -1.25)) - PetscSqrtReal(1e-5 + PetscSqr(PetscLogReal(Ti_ev) - 2) / 16);
    1086:         } else { // lam_ei == lam_ie
    1087:           if (10 * Zj * Zj > Ti_ev) {
    1088:             ctx->lambdas[gridi][gridj] = ctx->lambdas[gridj][gridi] = 23 - PetscLogReal(PetscSqrtReal(ni) * Zj * PetscPowReal(Ti_ev, -1.5));
    1089:           } else {
    1090:             ctx->lambdas[gridi][gridj] = ctx->lambdas[gridj][gridi] = 24 - PetscLogReal(PetscSqrtReal(ni) / Ti_ev);
    1091:           }
    1092:         }
    1093:       } else { // lam_ii'
    1094:         PetscReal mui = ctx->masses[iii] / 1.6720e-27, Zi = ctx->charges[iii] / 1.6022e-19;
    1095:         PetscReal Tj_ev            = (ctx->thermal_temps[jjj] / 1.1604525e7) * 1000; // convert (back) to eV
    1096:         PetscReal muj              = ctx->masses[jjj] / 1.6720e-27;
    1097:         PetscReal nj               = ctx->n[jjj] * ctx->n_0;
    1098:         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));
    1099:       }
    1100:     }
    1101:   }
    1102:   //PetscReal v0 = PetscSqrtReal(ctx->k * ctx->thermal_temps[iii] / ctx->masses[iii]); /* arbitrary units for non-dimensionalization: plasma formulary def */
    1103:   PetscFunctionReturn(PETSC_SUCCESS);
    1104: }

    1106: static PetscErrorCode ProcessOptions(LandauCtx *ctx, const char prefix[])
    1107: {
    1108:   PetscBool flg, fileflg;
    1109:   PetscInt  ii, nt, nm, nc, num_species_grid[LANDAU_MAX_GRIDS], non_dim_grid;
    1110:   PetscReal lnLam = 10;
    1111:   DM        dummy;

    1113:   PetscFunctionBegin;
    1114:   PetscCall(DMCreate(ctx->comm, &dummy));
    1115:   /* get options - initialize context */
    1116:   ctx->verbose        = 1; // should be 0 for silent compliance
    1117:   ctx->batch_sz       = 1;
    1118:   ctx->batch_view_idx = 0;
    1119:   ctx->interpolate    = PETSC_TRUE;
    1120:   ctx->gpu_assembly   = PETSC_TRUE;
    1121:   ctx->norm_state     = 0;
    1122:   ctx->electronShift  = 0;
    1123:   ctx->M              = NULL;
    1124:   ctx->J              = NULL;
    1125:   /* geometry and grids */
    1126:   ctx->sphere    = PETSC_FALSE;
    1127:   ctx->use_p4est = PETSC_FALSE;
    1128:   ctx->simplex   = PETSC_FALSE;
    1129:   for (PetscInt grid = 0; grid < LANDAU_MAX_GRIDS; grid++) {
    1130:     ctx->radius[grid]             = 5.; /* thermal radius (velocity) */
    1131:     ctx->radius_perp[grid]        = 5.; /* thermal radius (velocity) */
    1132:     ctx->radius_par[grid]         = 5.; /* thermal radius (velocity) */
    1133:     ctx->numAMRRefine[grid]       = 0;
    1134:     ctx->postAMRRefine[grid]      = 0;
    1135:     ctx->species_offset[grid + 1] = 1; // one species default
    1136:     num_species_grid[grid]        = 0;
    1137:     ctx->plex[grid]               = NULL; /* cache as expensive to Convert */
    1138:   }
    1139:   ctx->species_offset[0] = 0;
    1140:   ctx->re_radius         = 0.;
    1141:   ctx->vperp0_radius1    = 0;
    1142:   ctx->vperp0_radius2    = 0;
    1143:   ctx->nZRefine1         = 0;
    1144:   ctx->nZRefine2         = 0;
    1145:   ctx->numRERefine       = 0;
    1146:   num_species_grid[0]    = 1; // one species default
    1147:   /* species - [0] electrons, [1] one ion species eg, duetarium, [2] heavy impurity ion, ... */
    1148:   ctx->charges[0]       = -1;                       /* electron charge (MKS) */
    1149:   ctx->masses[0]        = 1 / 1835.469965278441013; /* temporary value in proton mass */
    1150:   ctx->n[0]             = 1;
    1151:   ctx->v_0              = 1; /* thermal velocity, we could start with a scale != 1 */
    1152:   ctx->thermal_temps[0] = 1;
    1153:   /* constants, etc. */
    1154:   ctx->epsilon0 = 8.8542e-12;     /* permittivity of free space (MKS) F/m */
    1155:   ctx->k        = 1.38064852e-23; /* Boltzmann constant (MKS) J/K */
    1156:   ctx->n_0      = 1.e20;          /* typical plasma n, but could set it to 1 */
    1157:   ctx->Ez       = 0;
    1158:   for (PetscInt grid = 0; grid < LANDAU_NUM_TIMERS; grid++) ctx->times[grid] = 0;
    1159:   for (PetscInt ii = 0; ii < LANDAU_DIM; ii++) ctx->cells0[ii] = 2;
    1160:   if (LANDAU_DIM == 2) ctx->cells0[0] = 1;
    1161:   ctx->use_matrix_mass                = PETSC_FALSE;
    1162:   ctx->use_relativistic_corrections   = PETSC_FALSE;
    1163:   ctx->use_energy_tensor_trick        = PETSC_FALSE; /* Use Eero's trick for energy conservation v --> grad(v^2/2) */
    1164:   ctx->SData_d.w                      = NULL;
    1165:   ctx->SData_d.x                      = NULL;
    1166:   ctx->SData_d.y                      = NULL;
    1167:   ctx->SData_d.z                      = NULL;
    1168:   ctx->SData_d.invJ                   = NULL;
    1169:   ctx->jacobian_field_major_order     = PETSC_FALSE;
    1170:   ctx->SData_d.coo_elem_offsets       = NULL;
    1171:   ctx->SData_d.coo_elem_point_offsets = NULL;
    1172:   ctx->SData_d.coo_elem_fullNb        = NULL;
    1173:   ctx->SData_d.coo_size               = 0;
    1174:   PetscOptionsBegin(ctx->comm, prefix, "Options for Fokker-Plank-Landau collision operator", "none");
    1175: #if defined(PETSC_HAVE_KOKKOS)
    1176:   ctx->deviceType = LANDAU_KOKKOS;
    1177:   PetscCall(PetscStrncpy(ctx->filename, "kokkos", sizeof(ctx->filename)));
    1178: #else
    1179:   ctx->deviceType = LANDAU_CPU;
    1180:   PetscCall(PetscStrncpy(ctx->filename, "cpu", sizeof(ctx->filename)));
    1181: #endif
    1182:   PetscCall(PetscOptionsString("-dm_landau_device_type", "Use kernels on 'cpu' 'kokkos'", "plexland.c", ctx->filename, ctx->filename, sizeof(ctx->filename), NULL));
    1183:   PetscCall(PetscStrcmp("cpu", ctx->filename, &flg));
    1184:   if (flg) {
    1185:     ctx->deviceType = LANDAU_CPU;
    1186:   } else {
    1187:     PetscCall(PetscStrcmp("kokkos", ctx->filename, &flg));
    1188:     if (flg) ctx->deviceType = LANDAU_KOKKOS;
    1189:     else SETERRQ(ctx->comm, PETSC_ERR_ARG_WRONG, "-dm_landau_device_type %s", ctx->filename);
    1190:   }
    1191:   ctx->filename[0] = '\0';
    1192:   PetscCall(PetscOptionsString("-dm_landau_filename", "file to read mesh from", "plexland.c", ctx->filename, ctx->filename, sizeof(ctx->filename), &fileflg));
    1193:   PetscCall(PetscOptionsReal("-dm_landau_electron_shift", "Shift in thermal velocity of electrons", "none", ctx->electronShift, &ctx->electronShift, NULL));
    1194:   PetscCall(PetscOptionsInt("-dm_landau_verbose", "Level of verbosity output", "plexland.c", ctx->verbose, &ctx->verbose, NULL));
    1195:   PetscCall(PetscOptionsInt("-dm_landau_batch_size", "Number of 'vertices' to batch", "ex2.c", ctx->batch_sz, &ctx->batch_sz, NULL));
    1196:   PetscCheck(LANDAU_MAX_BATCH_SZ >= ctx->batch_sz, ctx->comm, PETSC_ERR_ARG_WRONG, "LANDAU_MAX_BATCH_SZ %" PetscInt_FMT " < ctx->batch_sz %" PetscInt_FMT, (PetscInt)LANDAU_MAX_BATCH_SZ, ctx->batch_sz);
    1197:   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));
    1198:   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);
    1199:   PetscCall(PetscOptionsReal("-dm_landau_Ez", "Initial parallel electric field in unites of Conner-Hastie critical field", "plexland.c", ctx->Ez, &ctx->Ez, NULL));
    1200:   PetscCall(PetscOptionsReal("-dm_landau_n_0", "Normalization constant for number density", "plexland.c", ctx->n_0, &ctx->n_0, NULL));
    1201:   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));
    1202:   PetscCall(PetscOptionsBool("-dm_landau_use_relativistic_corrections", "Use relativistic corrections", "plexland.c", ctx->use_relativistic_corrections, &ctx->use_relativistic_corrections, NULL));
    1203:   PetscCall(PetscOptionsBool("-dm_landau_simplex", "Use simplex elements", "plexland.c", ctx->simplex, &ctx->simplex, NULL));
    1204:   PetscCall(PetscOptionsBool("-dm_landau_sphere", "use sphere/semi-circle domain instead of rectangle", "plexland.c", ctx->sphere, &ctx->sphere, NULL));
    1205:   if (LANDAU_DIM == 2 && ctx->use_relativistic_corrections) ctx->use_relativistic_corrections = PETSC_FALSE; // should warn
    1206:   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,
    1207:                              &ctx->use_energy_tensor_trick, NULL));

    1209:   /* get num species with temperature, set defaults */
    1210:   for (ii = 1; ii < LANDAU_MAX_SPECIES; ii++) {
    1211:     ctx->thermal_temps[ii] = 1;
    1212:     ctx->charges[ii]       = 1;
    1213:     ctx->masses[ii]        = 1;
    1214:     ctx->n[ii]             = 1;
    1215:   }
    1216:   nt = LANDAU_MAX_SPECIES;
    1217:   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));
    1218:   if (flg) {
    1219:     PetscCall(PetscInfo(dummy, "num_species set to number of thermal temps provided (%" PetscInt_FMT ")\n", nt));
    1220:     ctx->num_species = nt;
    1221:   } else SETERRQ(ctx->comm, PETSC_ERR_ARG_WRONG, "-dm_landau_thermal_temps ,t1,t2,.. must be provided to set the number of species");
    1222:   for (ii = 0; ii < ctx->num_species; ii++) ctx->thermal_temps[ii] *= 1.1604525e7; /* convert to Kelvin */
    1223:   nm = LANDAU_MAX_SPECIES - 1;
    1224:   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));
    1225:   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);
    1226:   nm = LANDAU_MAX_SPECIES;
    1227:   PetscCall(PetscOptionsRealArray("-dm_landau_n", "Number density of each species = n_s * n_0", "plexland.c", ctx->n, &nm, &flg));
    1228:   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);
    1229:   for (ii = 0; ii < LANDAU_MAX_SPECIES; ii++) ctx->masses[ii] *= 1.6720e-27; /* scale by proton mass kg */
    1230:   ctx->masses[0] = 9.10938356e-31;                                           /* electron mass kg (should be about right already) */
    1231:   nc             = LANDAU_MAX_SPECIES - 1;
    1232:   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));
    1233:   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);
    1234:   for (ii = 0; ii < LANDAU_MAX_SPECIES; ii++) ctx->charges[ii] *= 1.6022e-19; /* electron/proton charge (MKS) */
    1235:   /* geometry and grids */
    1236:   nt = LANDAU_MAX_GRIDS;
    1237:   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));
    1238:   if (flg) {
    1239:     ctx->num_grids = nt;
    1240:     for (ii = nt = 0; ii < ctx->num_grids; ii++) nt += num_species_grid[ii];
    1241:     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,
    1242:                ctx->num_grids, LANDAU_MAX_GRIDS);
    1243:   } else {
    1244:     if (ctx->num_species > LANDAU_MAX_GRIDS) {
    1245:       num_species_grid[0] = 1;
    1246:       num_species_grid[1] = ctx->num_species - 1;
    1247:       ctx->num_grids      = 2;
    1248:     } else {
    1249:       ctx->num_grids = ctx->num_species;
    1250:       for (ii = 0; ii < ctx->num_grids; ii++) num_species_grid[ii] = 1;
    1251:     }
    1252:   }
    1253:   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];
    1254:   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],
    1255:              ctx->num_species);
    1256:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    1257:     PetscInt iii             = ctx->species_offset[grid];                                          // normalize with first (arbitrary) species on grid
    1258:     ctx->thermal_speed[grid] = PetscSqrtReal(ctx->k * ctx->thermal_temps[iii] / ctx->masses[iii]); /* arbitrary units for non-dimensionalization: plasma formulary def */
    1259:   }
    1260:   // get lambdas here because we need them for t_0 etc
    1261:   PetscCall(PetscOptionsReal("-dm_landau_ln_lambda", "Universal cross section parameter. Default uses NRL formulas", "plexland.c", lnLam, &lnLam, &flg));
    1262:   if (flg) {
    1263:     for (PetscInt grid = 0; grid < LANDAU_MAX_GRIDS; grid++) {
    1264:       for (PetscInt gridj = 0; gridj < LANDAU_MAX_GRIDS; gridj++) ctx->lambdas[gridj][grid] = lnLam; /* cross section ratio large - small angle collisions */
    1265:     }
    1266:   } else {
    1267:     PetscCall(makeLambdas(ctx));
    1268:   }
    1269:   non_dim_grid = 0;
    1270:   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));
    1271:   if (non_dim_grid != 0) PetscCall(PetscInfo(dummy, "Normalization grid set to %" PetscInt_FMT ", but non-default not well verified\n", non_dim_grid));
    1272:   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);
    1273:   ctx->v_0 = ctx->thermal_speed[non_dim_grid]; /* arbitrary units for non dimensionalization: global mean velocity in 1D of electrons */
    1274:   ctx->m_0 = ctx->masses[non_dim_grid];        /* arbitrary reference mass, electrons */
    1275:   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 */
    1276:   /* domain */
    1277:   nt = LANDAU_MAX_GRIDS;
    1278:   PetscCall(PetscOptionsRealArray("-dm_landau_domain_radius", "Phase space size in units of thermal velocity of grid", "plexland.c", ctx->radius, &nt, &flg));
    1279:   if (flg) {
    1280:     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);
    1281:     while (nt--) ctx->radius_par[nt] = ctx->radius_perp[nt] = ctx->radius[nt];
    1282:   } else {
    1283:     nt = LANDAU_MAX_GRIDS;
    1284:     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));
    1285:     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);
    1286:     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));
    1287:     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);
    1288:   }
    1289:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    1290:     if (flg && ctx->radius[grid] <= 0) { /* negative is ratio of c - need to set par and perp with this -- todo */
    1291:       if (ctx->radius[grid] == 0) ctx->radius[grid] = 0.75;
    1292:       else ctx->radius[grid] = -ctx->radius[grid];
    1293:       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)
    1294:       PetscCall(PetscInfo(dummy, "Change domain radius to %g for grid %" PetscInt_FMT "\n", (double)ctx->radius[grid], grid));
    1295:     }
    1296:     ctx->radius[grid] *= ctx->thermal_speed[grid] / ctx->v_0;      // scale domain by thermal radius relative to v_0
    1297:     ctx->radius_perp[grid] *= ctx->thermal_speed[grid] / ctx->v_0; // scale domain by thermal radius relative to v_0
    1298:     ctx->radius_par[grid] *= ctx->thermal_speed[grid] / ctx->v_0;  // scale domain by thermal radius relative to v_0
    1299:   }
    1300:   /* amr parameters */
    1301:   if (!fileflg) {
    1302:     nt = LANDAU_MAX_GRIDS;
    1303:     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));
    1304:     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);
    1305:     nt = LANDAU_MAX_GRIDS;
    1306:     PetscCall(PetscOptionsIntArray("-dm_landau_amr_post_refine", "Number of levels to uniformly refine after AMR", "plexland.c", ctx->postAMRRefine, &nt, &flg));
    1307:     for (ii = 1; ii < ctx->num_grids; ii++) ctx->postAMRRefine[ii] = ctx->postAMRRefine[0]; // all grids the same now
    1308:     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));
    1309:     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));
    1310:     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));
    1311:     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));
    1312:     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));
    1313:     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));
    1314:     /* spherical domain */
    1315:     if (ctx->sphere || ctx->simplex) {
    1316:       ctx->sphere_uniform_normal = PETSC_FALSE;
    1317:       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));
    1318:       if (!ctx->sphere_uniform_normal) { // true
    1319:         nt = LANDAU_MAX_GRIDS;
    1320:         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));
    1321:         if (flg && nt < ctx->num_grids) {
    1322:           for (PetscInt grid = nt; grid < ctx->num_grids; grid++) ctx->sphere_inner_radius_90degree[grid] = ctx->sphere_inner_radius_90degree[0];
    1323:         } else if (!flg || nt == 0) {
    1324:           if (LANDAU_DIM == 2) {
    1325:             for (PetscInt grid = 0; grid < ctx->num_grids; grid++) ctx->sphere_inner_radius_90degree[grid] = 0.4; // optimized for R=5, Q4, AMR=0
    1326:           } else {
    1327:             for (PetscInt grid = 0; grid < ctx->num_grids; grid++) ctx->sphere_inner_radius_90degree[grid] = 0.577 * 0.40;
    1328:           }
    1329:         }
    1330:         nt = LANDAU_MAX_GRIDS;
    1331:         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));
    1332:         if (flg && nt < ctx->num_grids) {
    1333:           for (PetscInt grid = nt; grid < ctx->num_grids; grid++) ctx->sphere_inner_radius_45degree[grid] = ctx->sphere_inner_radius_45degree[0];
    1334:         } else if (!flg || nt == 0) {
    1335:           if (LANDAU_DIM == 2) {
    1336:             for (PetscInt grid = 0; grid < ctx->num_grids; grid++) ctx->sphere_inner_radius_45degree[grid] = 0.45; // optimized for R=5, Q4, AMR=0
    1337:           } else {
    1338:             for (PetscInt grid = 0; grid < ctx->num_grids; grid++) ctx->sphere_inner_radius_45degree[grid] = 0.4; // 3D sphere
    1339:           }
    1340:         }
    1341:         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]));
    1342:       } else {
    1343:         for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    1344:           switch (ctx->numAMRRefine[grid]) {
    1345:           case 0:
    1346:           case 1:
    1347:           case 2:
    1348:           case 3:
    1349:           default:
    1350:             if (LANDAU_DIM == 2) {
    1351:               ctx->sphere_inner_radius_90degree[grid] = 0.40;
    1352:               ctx->sphere_inner_radius_45degree[grid] = 0.45;
    1353:             } else {
    1354:               ctx->sphere_inner_radius_45degree[grid] = 0.25;
    1355:             }
    1356:           }
    1357:         }
    1358:       }
    1359:     } else {
    1360:       nt = LANDAU_DIM;
    1361:       PetscCall(PetscOptionsIntArray("-dm_landau_num_cells", "Number of cells in each dimension of base grid", "plexland.c", ctx->cells0, &nt, &flg));
    1362:     }
    1363:   }
    1364:   /* processing options */
    1365:   PetscCall(PetscOptionsBool("-dm_landau_gpu_assembly", "Assemble Jacobian on GPU", "plexland.c", ctx->gpu_assembly, &ctx->gpu_assembly, NULL));
    1366:   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));
    1367:   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");
    1368:   PetscCheck(!ctx->jacobian_field_major_order, ctx->comm, PETSC_ERR_ARG_WRONG, "-dm_landau_jacobian_field_major_order DEPRECATED");
    1369:   PetscOptionsEnd();

    1371:   for (ii = ctx->num_species; ii < LANDAU_MAX_SPECIES; ii++) ctx->masses[ii] = ctx->thermal_temps[ii] = ctx->charges[ii] = 0;
    1372:   if (ctx->verbose != 0) {
    1373:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "masses:        e=%10.3e; ions in proton mass units:   %10.3e %10.3e ...\n", (double)ctx->masses[0], (double)(ctx->masses[1] / 1.6720e-27), (double)(ctx->num_species > 2 ? ctx->masses[2] / 1.6720e-27 : 0)));
    1374:     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)));
    1375:     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)));
    1376:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "thermal T (K): e=%10.3e i=%10.3e %10.3e. Normalization grid %d: v_0=%10.3e (%10.3ec) n_0=%10.3e t_0=%10.3e %" PetscInt_FMT " batched, view batch %" PetscInt_FMT "\n", (double)ctx->thermal_temps[0],
    1377:                           (double)ctx->thermal_temps[1], (double)((ctx->num_species > 2) ? ctx->thermal_temps[2] : 0), (int)non_dim_grid, (double)ctx->v_0, (double)(ctx->v_0 / SPEED_OF_LIGHT), (double)ctx->n_0, (double)ctx->t_0, ctx->batch_sz, ctx->batch_view_idx));
    1378:     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]));
    1379:     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]));
    1380:     if (ctx->use_relativistic_corrections) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\nUse relativistic corrections\n"));
    1381:     else PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n"));
    1382:   }
    1383:   PetscCall(DMDestroy(&dummy));
    1384:   {
    1385:     PetscMPIInt rank;
    1386:     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
    1387:     ctx->stage = 0;
    1388:     PetscCall(PetscLogEventRegister("Landau Create", DM_CLASSID, &ctx->events[13]));   /* 13 */
    1389:     PetscCall(PetscLogEventRegister(" GPU ass. setup", DM_CLASSID, &ctx->events[2]));  /* 2 */
    1390:     PetscCall(PetscLogEventRegister(" Build matrix", DM_CLASSID, &ctx->events[12]));   /* 12 */
    1391:     PetscCall(PetscLogEventRegister(" Assembly maps", DM_CLASSID, &ctx->events[15]));  /* 15 */
    1392:     PetscCall(PetscLogEventRegister("Landau Mass mat", DM_CLASSID, &ctx->events[14])); /* 14 */
    1393:     PetscCall(PetscLogEventRegister("Landau Operator", DM_CLASSID, &ctx->events[11])); /* 11 */
    1394:     PetscCall(PetscLogEventRegister("Landau Jacobian", DM_CLASSID, &ctx->events[0]));  /* 0 */
    1395:     PetscCall(PetscLogEventRegister("Landau Mass", DM_CLASSID, &ctx->events[9]));      /* 9 */
    1396:     PetscCall(PetscLogEventRegister(" Preamble", DM_CLASSID, &ctx->events[10]));       /* 10 */
    1397:     PetscCall(PetscLogEventRegister(" static IP Data", DM_CLASSID, &ctx->events[7]));  /* 7 */
    1398:     PetscCall(PetscLogEventRegister(" dynamic IP-Jac", DM_CLASSID, &ctx->events[1]));  /* 1 */
    1399:     PetscCall(PetscLogEventRegister(" Kernel-init", DM_CLASSID, &ctx->events[3]));     /* 3 */
    1400:     PetscCall(PetscLogEventRegister(" Jac-f-df (GPU)", DM_CLASSID, &ctx->events[8]));  /* 8 */
    1401:     PetscCall(PetscLogEventRegister(" J Kernel (GPU)", DM_CLASSID, &ctx->events[4]));  /* 4 */
    1402:     PetscCall(PetscLogEventRegister(" M Kernel (GPU)", DM_CLASSID, &ctx->events[16])); /* 16 */
    1403:     PetscCall(PetscLogEventRegister(" Copy to CPU", DM_CLASSID, &ctx->events[5]));     /* 5 */
    1404:     PetscCall(PetscLogEventRegister(" CPU assemble", DM_CLASSID, &ctx->events[6]));    /* 6 */

    1406:     if (rank) { /* turn off output stuff for duplicate runs - do we need to add the prefix to all this? */
    1407:       PetscCall(PetscOptionsClearValue(NULL, "-snes_converged_reason"));
    1408:       PetscCall(PetscOptionsClearValue(NULL, "-ksp_converged_reason"));
    1409:       PetscCall(PetscOptionsClearValue(NULL, "-snes_monitor"));
    1410:       PetscCall(PetscOptionsClearValue(NULL, "-ksp_monitor"));
    1411:       PetscCall(PetscOptionsClearValue(NULL, "-ts_monitor"));
    1412:       PetscCall(PetscOptionsClearValue(NULL, "-ts_view"));
    1413:       PetscCall(PetscOptionsClearValue(NULL, "-ts_adapt_monitor"));
    1414:       PetscCall(PetscOptionsClearValue(NULL, "-dm_landau_amr_dm_view"));
    1415:       PetscCall(PetscOptionsClearValue(NULL, "-dm_landau_amr_vec_view"));
    1416:       PetscCall(PetscOptionsClearValue(NULL, "-dm_landau_mass_dm_view"));
    1417:       PetscCall(PetscOptionsClearValue(NULL, "-dm_landau_mass_view"));
    1418:       PetscCall(PetscOptionsClearValue(NULL, "-dm_landau_jacobian_view"));
    1419:       PetscCall(PetscOptionsClearValue(NULL, "-dm_landau_mat_view"));
    1420:       PetscCall(PetscOptionsClearValue(NULL, "-pc_bjkokkos_ksp_converged_reason"));
    1421:       PetscCall(PetscOptionsClearValue(NULL, "-pc_bjkokkos_ksp_monitor"));
    1422:       PetscCall(PetscOptionsClearValue(NULL, "-"));
    1423:       PetscCall(PetscOptionsClearValue(NULL, "-info"));
    1424:     }
    1425:   }
    1426:   PetscFunctionReturn(PETSC_SUCCESS);
    1427: }

    1429: static PetscErrorCode CreateStaticData(PetscInt dim, IS grid_batch_is_inv[], LandauCtx *ctx)
    1430: {
    1431:   PetscSection     section[LANDAU_MAX_GRIDS], globsection[LANDAU_MAX_GRIDS];
    1432:   PetscQuadrature  quad;
    1433:   const PetscReal *quadWeights;
    1434:   PetscReal        invMass[LANDAU_MAX_SPECIES], nu_alpha[LANDAU_MAX_SPECIES], nu_beta[LANDAU_MAX_SPECIES];
    1435:   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;
    1436:   PetscTabulation *Tf;
    1437:   PetscDS          prob;

    1439:   PetscFunctionBegin;
    1440:   PetscCall(PetscFEGetDimension(ctx->fe[0], &Nb));
    1441:   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);
    1442:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    1443:     for (PetscInt ii = ctx->species_offset[grid]; ii < ctx->species_offset[grid + 1]; ii++) {
    1444:       invMass[ii]  = ctx->m_0 / ctx->masses[ii];
    1445:       nu_alpha[ii] = PetscSqr(ctx->charges[ii] / ctx->m_0) * ctx->m_0 / ctx->masses[ii];
    1446:       nu_beta[ii]  = PetscSqr(ctx->charges[ii] / ctx->epsilon0) / (8 * PETSC_PI) * ctx->t_0 * ctx->n_0 / PetscPowReal(ctx->v_0, 3);
    1447:     }
    1448:   }
    1449:   if (ctx->verbose == 4) {
    1450:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "nu_alpha: "));
    1451:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    1452:       PetscInt iii = ctx->species_offset[grid];
    1453:       for (PetscInt ii = iii; ii < ctx->species_offset[grid + 1]; ii++) PetscCall(PetscPrintf(PETSC_COMM_WORLD, " %e", (double)nu_alpha[ii]));
    1454:     }
    1455:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\nnu_beta: "));
    1456:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    1457:       PetscInt iii = ctx->species_offset[grid];
    1458:       for (PetscInt ii = iii; ii < ctx->species_offset[grid + 1]; ii++) PetscCall(PetscPrintf(PETSC_COMM_WORLD, " %e", (double)nu_beta[ii]));
    1459:     }
    1460:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\nnu_alpha[i]*nu_beta[j]*lambda[i][j]:\n"));
    1461:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    1462:       PetscInt iii = ctx->species_offset[grid];
    1463:       for (PetscInt ii = iii; ii < ctx->species_offset[grid + 1]; ii++) {
    1464:         for (PetscInt gridj = 0; gridj < ctx->num_grids; gridj++) {
    1465:           PetscInt jjj = ctx->species_offset[gridj];
    1466:           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])));
    1467:         }
    1468:         PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n"));
    1469:       }
    1470:     }
    1471:     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "lambda[i][j]:\n"));
    1472:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    1473:       PetscInt iii = ctx->species_offset[grid];
    1474:       for (PetscInt ii = iii; ii < ctx->species_offset[grid + 1]; ii++) {
    1475:         for (PetscInt gridj = 0; gridj < ctx->num_grids; gridj++) {
    1476:           PetscInt jjj = ctx->species_offset[gridj];
    1477:           for (PetscInt jj = jjj; jj < ctx->species_offset[gridj + 1]; jj++) PetscCall(PetscPrintf(PETSC_COMM_WORLD, " %14.9e", (double)ctx->lambdas[grid][gridj]));
    1478:         }
    1479:         PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n"));
    1480:       }
    1481:     }
    1482:   }
    1483:   PetscCall(DMGetDS(ctx->plex[0], &prob));    // same DS for all grids
    1484:   PetscCall(PetscDSGetTabulation(prob, &Tf)); // Bf, &Df same for all grids
    1485:   /* DS, Tab and quad is same on all grids */
    1486:   PetscCheck(ctx->plex[0], ctx->comm, PETSC_ERR_ARG_WRONG, "Plex not created");
    1487:   PetscCall(PetscFEGetQuadrature(ctx->fe[0], &quad));
    1488:   PetscCall(PetscQuadratureGetData(quad, NULL, NULL, &Nq, NULL, &quadWeights));
    1489:   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);
    1490:   /* setup each grid */
    1491:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    1492:     PetscInt cStart, cEnd;
    1493:     PetscCheck(ctx->plex[grid] != NULL, ctx->comm, PETSC_ERR_ARG_WRONG, "Plex not created");
    1494:     PetscCall(DMPlexGetHeightStratum(ctx->plex[grid], 0, &cStart, &cEnd));
    1495:     numCells[grid] = cEnd - cStart; // grids can have different topology
    1496:     PetscCall(DMGetLocalSection(ctx->plex[grid], &section[grid]));
    1497:     PetscCall(DMGetGlobalSection(ctx->plex[grid], &globsection[grid]));
    1498:     PetscCall(PetscSectionGetNumFields(section[grid], &Nf[grid]));
    1499:     ncellsTot += numCells[grid];
    1500:   }
    1501:   /* create GPU assembly data */
    1502:   if (ctx->gpu_assembly) { /* we need GPU object with GPU assembly */
    1503:     PetscContainer container;
    1504:     PetscScalar   *elemMatrix, *elMat;
    1505:     pointInterpolationP4est(*pointMaps)[LANDAU_MAX_Q_FACE];
    1506:     P4estVertexMaps *maps;
    1507:     const PetscInt  *plex_batch = NULL, elMatSz = Nb * Nb * ctx->num_species * ctx->num_species;
    1508:     LandauIdx       *coo_elem_offsets = NULL, *coo_elem_fullNb = NULL, (*coo_elem_point_offsets)[LANDAU_MAX_NQND + 1] = NULL;
    1509:     /* create GPU assembly data */
    1510:     PetscCall(PetscInfo(ctx->plex[0], "Make GPU maps %d\n", 1));
    1511:     PetscCall(PetscLogEventBegin(ctx->events[2], 0, 0, 0, 0));
    1512:     PetscCall(PetscMalloc(sizeof(*maps) * ctx->num_grids, &maps));
    1513:     PetscCall(PetscMalloc(sizeof(*pointMaps) * MAP_BF_SIZE, &pointMaps));
    1514:     PetscCall(PetscMalloc(sizeof(*elemMatrix) * elMatSz, &elemMatrix));

    1516:     {                                                                                                                             // setup COO assembly -- put COO metadata directly in ctx->SData_d
    1517:       PetscCall(PetscMalloc3(ncellsTot + 1, &coo_elem_offsets, ncellsTot, &coo_elem_fullNb, ncellsTot, &coo_elem_point_offsets)); // array of integer pointers
    1518:       coo_elem_offsets[0] = 0;                                                                                                    // finish later
    1519:       PetscCall(PetscInfo(ctx->plex[0], "COO initialization, %" PetscInt_FMT " cells\n", ncellsTot));
    1520:       ctx->SData_d.coo_n_cellsTot         = ncellsTot;
    1521:       ctx->SData_d.coo_elem_offsets       = (void *)coo_elem_offsets;
    1522:       ctx->SData_d.coo_elem_fullNb        = (void *)coo_elem_fullNb;
    1523:       ctx->SData_d.coo_elem_point_offsets = (void *)coo_elem_point_offsets;
    1524:     }

    1526:     ctx->SData_d.coo_max_fullnb = 0;
    1527:     for (PetscInt grid = 0, glb_elem_idx = 0; grid < ctx->num_grids; grid++) {
    1528:       PetscInt cStart, cEnd, Nfloc = Nf[grid], totDim = Nfloc * Nb;
    1529:       if (grid_batch_is_inv[grid]) PetscCall(ISGetIndices(grid_batch_is_inv[grid], &plex_batch));
    1530:       PetscCheck(!plex_batch, ctx->comm, PETSC_ERR_ARG_WRONG, "-dm_landau_jacobian_field_major_order DEPRECATED");
    1531:       PetscCall(DMPlexGetHeightStratum(ctx->plex[grid], 0, &cStart, &cEnd));
    1532:       // make maps
    1533:       maps[grid].d_self       = NULL;
    1534:       maps[grid].num_elements = numCells[grid];
    1535:       maps[grid].num_face     = (PetscInt)(pow(Nq, 1. / ((double)dim)) + .001);                 // Q
    1536:       maps[grid].num_face     = (PetscInt)(pow(maps[grid].num_face, (double)(dim - 1)) + .001); // Q^2
    1537:       maps[grid].num_reduced  = 0;
    1538:       maps[grid].deviceType   = ctx->deviceType;
    1539:       maps[grid].numgrids     = ctx->num_grids;
    1540:       // count reduced and get
    1541:       PetscCall(PetscMalloc(maps[grid].num_elements * sizeof(*maps[grid].gIdx), &maps[grid].gIdx));
    1542:       for (PetscInt ej = cStart, eidx = 0; ej < cEnd; ++ej, ++eidx, glb_elem_idx++) {
    1543:         if (coo_elem_offsets) coo_elem_offsets[glb_elem_idx + 1] = coo_elem_offsets[glb_elem_idx]; // start with last one, then add
    1544:         for (PetscInt fieldA = 0; fieldA < Nf[grid]; fieldA++) {
    1545:           PetscInt fullNb = 0;
    1546:           for (PetscInt q = 0; q < Nb; ++q) {
    1547:             PetscInt     numindices, *indices;
    1548:             PetscScalar *valuesOrig = elMat = elemMatrix;
    1549:             PetscCall(PetscArrayzero(elMat, totDim * totDim));
    1550:             elMat[(fieldA * Nb + q) * totDim + fieldA * Nb + q] = 1;
    1551:             PetscCall(DMPlexGetClosureIndices(ctx->plex[grid], section[grid], globsection[grid], ej, PETSC_TRUE, &numindices, &indices, NULL, (PetscScalar **)&elMat));
    1552:             if (ctx->simplex) {
    1553:               PetscCheck(numindices == Nb, ctx->comm, PETSC_ERR_ARG_WRONG, "numindices != Nb numindices=%d Nb=%d", (int)numindices, (int)Nb);
    1554:               for (PetscInt q = 0; q < numindices; ++q) { maps[grid].gIdx[eidx][fieldA][q] = (LandauIdx)indices[q]; }
    1555:               fullNb++;
    1556:             } else {
    1557:               for (PetscInt f = 0; f < numindices; ++f) { // look for a non-zero on the diagonal (is this too complicated for simplices?)
    1558:                 if (PetscAbs(PetscRealPart(elMat[f * numindices + f])) > PETSC_MACHINE_EPSILON) {
    1559:                   // found it
    1560:                   if (PetscAbs(PetscRealPart(elMat[f * numindices + f] - 1.)) < PETSC_MACHINE_EPSILON) { // normal vertex 1.0
    1561:                     if (plex_batch) {
    1562:                       maps[grid].gIdx[eidx][fieldA][q] = (LandauIdx)plex_batch[indices[f]];
    1563:                     } else {
    1564:                       maps[grid].gIdx[eidx][fieldA][q] = (LandauIdx)indices[f];
    1565:                     }
    1566:                     fullNb++;
    1567:                   } else { //found a constraint
    1568:                     PetscInt       jj                = 0;
    1569:                     PetscReal      sum               = 0;
    1570:                     const PetscInt ff                = f;
    1571:                     maps[grid].gIdx[eidx][fieldA][q] = -maps[grid].num_reduced - 1; // store (-)index: id = -(idx+1): idx = -id - 1
    1572:                     PetscCheck(!ctx->simplex, ctx->comm, PETSC_ERR_ARG_WRONG, "No constraints with simplex");
    1573:                     do {                                                                                              // constraints are continuous in Plex - exploit that here
    1574:                       PetscInt ii;                                                                                    // get 'scale'
    1575:                       for (ii = 0, pointMaps[maps[grid].num_reduced][jj].scale = 0; ii < maps[grid].num_face; ii++) { // sum row of outer product to recover vector value
    1576:                         if (ff + ii < numindices) {                                                                   // 3D has Q and Q^2 interps so might run off end. We could test that elMat[f*numindices + ff + ii] > 0, and break if not
    1577:                           pointMaps[maps[grid].num_reduced][jj].scale += PetscRealPart(elMat[f * numindices + ff + ii]);
    1578:                         }
    1579:                       }
    1580:                       sum += pointMaps[maps[grid].num_reduced][jj].scale; // diagnostic
    1581:                       // get 'gid'
    1582:                       if (pointMaps[maps[grid].num_reduced][jj].scale == 0) pointMaps[maps[grid].num_reduced][jj].gid = -1; // 3D has Q and Q^2 interps
    1583:                       else {
    1584:                         if (plex_batch) {
    1585:                           pointMaps[maps[grid].num_reduced][jj].gid = plex_batch[indices[f]];
    1586:                         } else {
    1587:                           pointMaps[maps[grid].num_reduced][jj].gid = indices[f];
    1588:                         }
    1589:                         fullNb++;
    1590:                       }
    1591:                     } while (++jj < maps[grid].num_face && ++f < numindices); // jj is incremented if we hit the end
    1592:                     while (jj < maps[grid].num_face) {
    1593:                       pointMaps[maps[grid].num_reduced][jj].scale = 0;
    1594:                       pointMaps[maps[grid].num_reduced][jj].gid   = -1;
    1595:                       jj++;
    1596:                     }
    1597:                     if (PetscAbs(sum - 1.0) > 10 * PETSC_MACHINE_EPSILON) { // debug
    1598:                       PetscInt  d, f;
    1599:                       PetscReal tmp = 0;
    1600:                       PetscCall(PetscPrintf(PETSC_COMM_SELF, "\t\t%d.%d.%d) ERROR total I = %22.16e (LANDAU_MAX_Q_FACE=%d, #face=%d)\n", (int)eidx, (int)q, (int)fieldA, (double)sum, LANDAU_MAX_Q_FACE, (int)maps[grid].num_face));
    1601:                       for (d = 0, tmp = 0; d < numindices; ++d) {
    1602:                         if (tmp != 0 && PetscAbs(tmp - 1.0) > 10 * PETSC_MACHINE_EPSILON) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "%3d) %3" PetscInt_FMT ": ", (int)d, indices[d]));
    1603:                         for (f = 0; f < numindices; ++f) tmp += PetscRealPart(elMat[d * numindices + f]);
    1604:                         if (tmp != 0) PetscCall(PetscPrintf(ctx->comm, " | %22.16e\n", (double)tmp));
    1605:                       }
    1606:                     }
    1607:                     maps[grid].num_reduced++;
    1608:                     PetscCheck(maps[grid].num_reduced < MAP_BF_SIZE, PETSC_COMM_SELF, PETSC_ERR_PLIB, "maps[grid].num_reduced %d > %" PetscInt_FMT, (int)maps[grid].num_reduced, MAP_BF_SIZE);
    1609:                   }
    1610:                   break;
    1611:                 }
    1612:               }
    1613:             } // !simplex
    1614:             // cleanup
    1615:             PetscCall(DMPlexRestoreClosureIndices(ctx->plex[grid], section[grid], globsection[grid], ej, PETSC_TRUE, &numindices, &indices, NULL, (PetscScalar **)&elMat));
    1616:             if (elMat != valuesOrig) PetscCall(DMRestoreWorkArray(ctx->plex[grid], numindices * numindices, MPIU_SCALAR, &elMat));
    1617:           }
    1618:           {                                                        // setup COO assembly
    1619:             coo_elem_offsets[glb_elem_idx + 1] += fullNb * fullNb; // one species block, adds a block for each species, on this element in this grid
    1620:             if (fieldA == 0) {                                     // cache full Nb for this element, on this grid per species
    1621:               coo_elem_fullNb[glb_elem_idx] = fullNb;
    1622:               if (fullNb > ctx->SData_d.coo_max_fullnb) ctx->SData_d.coo_max_fullnb = fullNb;
    1623:             } else PetscCheck(coo_elem_fullNb[glb_elem_idx] == fullNb, PETSC_COMM_SELF, PETSC_ERR_PLIB, "full element size change with species %d %d", (int)coo_elem_fullNb[glb_elem_idx], (int)fullNb);
    1624:           }
    1625:         } // field
    1626:       } // cell
    1627:       // allocate and copy point data maps[grid].gIdx[eidx][field][q]
    1628:       PetscCall(PetscMalloc(maps[grid].num_reduced * sizeof(*maps[grid].c_maps), &maps[grid].c_maps));
    1629:       for (PetscInt ej = 0; ej < maps[grid].num_reduced; ++ej) {
    1630:         for (PetscInt q = 0; q < maps[grid].num_face; ++q) {
    1631:           maps[grid].c_maps[ej][q].scale = pointMaps[ej][q].scale;
    1632:           maps[grid].c_maps[ej][q].gid   = pointMaps[ej][q].gid;
    1633:         }
    1634:       }
    1635: #if defined(PETSC_HAVE_KOKKOS)
    1636:       if (ctx->deviceType == LANDAU_KOKKOS) {
    1637:         PetscCall(LandauKokkosCreateMatMaps(maps, pointMaps, Nf, grid)); // implies Kokkos does
    1638:       }
    1639: #endif
    1640:       if (plex_batch) {
    1641:         PetscCall(ISRestoreIndices(grid_batch_is_inv[grid], &plex_batch));
    1642:         PetscCall(ISDestroy(&grid_batch_is_inv[grid])); // we are done with this
    1643:       }
    1644:     } /* grids */
    1645:     // finish COO
    1646:     { // setup COO assembly
    1647:       PetscInt *oor, *ooc;
    1648:       ctx->SData_d.coo_size = coo_elem_offsets[ncellsTot] * ctx->batch_sz;
    1649:       PetscCall(PetscMalloc2(ctx->SData_d.coo_size, &oor, ctx->SData_d.coo_size, &ooc));
    1650:       for (PetscInt i = 0; i < ctx->SData_d.coo_size; i++) oor[i] = ooc[i] = -1;
    1651:       // get
    1652:       for (PetscInt grid = 0, glb_elem_idx = 0; grid < ctx->num_grids; grid++) {
    1653:         for (PetscInt ej = 0; ej < numCells[grid]; ++ej, glb_elem_idx++) {
    1654:           const PetscInt         fullNb           = coo_elem_fullNb[glb_elem_idx];
    1655:           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
    1656:           coo_elem_point_offsets[glb_elem_idx][0] = 0;
    1657:           for (PetscInt f = 0, cnt2 = 0; f < Nb; f++) {
    1658:             PetscInt idx                                = Idxs[f];
    1659:             coo_elem_point_offsets[glb_elem_idx][f + 1] = coo_elem_point_offsets[glb_elem_idx][f]; // start at last
    1660:             if (idx >= 0) {
    1661:               cnt2++;
    1662:               coo_elem_point_offsets[glb_elem_idx][f + 1]++; // inc
    1663:             } else {
    1664:               idx = -idx - 1;
    1665:               for (PetscInt q = 0; q < maps[grid].num_face; q++) {
    1666:                 if (maps[grid].c_maps[idx][q].gid < 0) break;
    1667:                 cnt2++;
    1668:                 coo_elem_point_offsets[glb_elem_idx][f + 1]++; // inc
    1669:               }
    1670:             }
    1671:             PetscCheck(cnt2 <= fullNb, PETSC_COMM_SELF, PETSC_ERR_PLIB, "wrong count %d < %d", (int)fullNb, (int)cnt2);
    1672:           }
    1673:           PetscCheck(coo_elem_point_offsets[glb_elem_idx][Nb] == fullNb, PETSC_COMM_SELF, PETSC_ERR_PLIB, "coo_elem_point_offsets size %d != fullNb=%d", (int)coo_elem_point_offsets[glb_elem_idx][Nb], (int)fullNb);
    1674:         }
    1675:       }
    1676:       // set
    1677:       for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) {
    1678:         for (PetscInt grid = 0, glb_elem_idx = 0; grid < ctx->num_grids; grid++) {
    1679:           const PetscInt moffset = LAND_MOFFSET(b_id, grid, ctx->batch_sz, ctx->num_grids, ctx->mat_offset);
    1680:           for (PetscInt ej = 0; ej < numCells[grid]; ++ej, glb_elem_idx++) {
    1681:             const PetscInt fullNb = coo_elem_fullNb[glb_elem_idx], fullNb2 = fullNb * fullNb;
    1682:             // set (i,j)
    1683:             for (PetscInt fieldA = 0; fieldA < Nf[grid]; fieldA++) {
    1684:               const LandauIdx *const Idxs = &maps[grid].gIdx[ej][fieldA][0];
    1685:               PetscInt               rows[LANDAU_MAX_Q_FACE], cols[LANDAU_MAX_Q_FACE];
    1686:               for (PetscInt f = 0; f < Nb; ++f) {
    1687:                 const PetscInt nr = coo_elem_point_offsets[glb_elem_idx][f + 1] - coo_elem_point_offsets[glb_elem_idx][f];
    1688:                 if (nr == 1) rows[0] = Idxs[f];
    1689:                 else {
    1690:                   const PetscInt idx = -Idxs[f] - 1;
    1691:                   for (PetscInt q = 0; q < nr; q++) rows[q] = maps[grid].c_maps[idx][q].gid;
    1692:                 }
    1693:                 for (PetscInt g = 0; g < Nb; ++g) {
    1694:                   const PetscInt nc = coo_elem_point_offsets[glb_elem_idx][g + 1] - coo_elem_point_offsets[glb_elem_idx][g];
    1695:                   if (nc == 1) cols[0] = Idxs[g];
    1696:                   else {
    1697:                     const PetscInt idx = -Idxs[g] - 1;
    1698:                     for (PetscInt q = 0; q < nc; q++) cols[q] = maps[grid].c_maps[idx][q].gid;
    1699:                   }
    1700:                   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];
    1701:                   for (PetscInt q = 0, idx = idx0; q < nr; q++) {
    1702:                     for (PetscInt d = 0; d < nc; d++, idx++) {
    1703:                       oor[idx] = rows[q] + moffset;
    1704:                       ooc[idx] = cols[d] + moffset;
    1705:                     }
    1706:                   }
    1707:                 }
    1708:               }
    1709:             }
    1710:           } // cell
    1711:         } // grid
    1712:       } // batch
    1713:       PetscCall(MatSetPreallocationCOO(ctx->J, ctx->SData_d.coo_size, oor, ooc));
    1714:       PetscCall(PetscFree2(oor, ooc));
    1715:     }
    1716:     PetscCall(PetscFree(pointMaps));
    1717:     PetscCall(PetscFree(elemMatrix));
    1718:     PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
    1719:     PetscCall(PetscContainerSetPointer(container, (void *)maps));
    1720:     PetscCall(PetscContainerSetUserDestroy(container, LandauGPUMapsDestroy));
    1721:     PetscCall(PetscObjectCompose((PetscObject)ctx->J, "assembly_maps", (PetscObject)container));
    1722:     PetscCall(PetscContainerDestroy(&container));
    1723:     PetscCall(PetscLogEventEnd(ctx->events[2], 0, 0, 0, 0));
    1724:   } // end GPU assembly
    1725:   { /* create static point data, Jacobian called first, only one vertex copy */
    1726:     PetscReal *invJe, *ww, *xx, *yy, *zz = NULL, *invJ_a;
    1727:     PetscInt   outer_ipidx, outer_ej, grid, nip_glb = 0;
    1728:     PetscFE    fe;
    1729:     PetscCall(PetscLogEventBegin(ctx->events[7], 0, 0, 0, 0));
    1730:     PetscCall(PetscInfo(ctx->plex[0], "Initialize static data\n"));
    1731:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) nip_glb += Nq * numCells[grid];
    1732:     /* collect f data, first time is for Jacobian, but make mass now */
    1733:     if (ctx->verbose != 0) {
    1734:       PetscInt ncells = 0, N;
    1735:       MatInfo  info;
    1736:       PetscCall(MatGetInfo(ctx->J, MAT_LOCAL, &info));
    1737:       PetscCall(MatGetSize(ctx->J, &N, NULL));
    1738:       for (PetscInt grid = 0; grid < ctx->num_grids; grid++) ncells += numCells[grid];
    1739:       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,
    1740:                             ctx->num_species, Nb, dim, N, (PetscInt)info.nz_used));
    1741:     }
    1742:     PetscCall(PetscMalloc4(nip_glb, &ww, nip_glb, &xx, nip_glb, &yy, nip_glb * dim * dim, &invJ_a));
    1743:     if (dim == 3) PetscCall(PetscMalloc1(nip_glb, &zz));
    1744:     if (ctx->use_energy_tensor_trick) {
    1745:       PetscCall(PetscFECreateDefault(PETSC_COMM_SELF, dim, 1, ctx->simplex, NULL, PETSC_DECIDE, &fe));
    1746:       PetscCall(PetscObjectSetName((PetscObject)fe, "energy"));
    1747:     }
    1748:     /* init each grids static data - no batch */
    1749:     for (grid = 0, outer_ipidx = 0, outer_ej = 0; grid < ctx->num_grids; grid++) { // OpenMP (once)
    1750:       Vec          v2_2 = NULL;                                                    // projected function: v^2/2 for non-relativistic, gamma... for relativistic
    1751:       PetscSection e_section;
    1752:       DM           dmEnergy;
    1753:       PetscInt     cStart, cEnd, ej;

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

    1762:         PetscCall(DMClone(ctx->plex[grid], &dmEnergy));
    1763:         PetscCall(PetscObjectSetName((PetscObject)dmEnergy, "energy"));
    1764:         PetscCall(DMSetField(dmEnergy, 0, NULL, (PetscObject)fe));
    1765:         PetscCall(DMCreateDS(dmEnergy));
    1766:         PetscCall(DMGetSection(dmEnergy, &e_section));
    1767:         PetscCall(DMGetGlobalVector(dmEnergy, &glob_v2));
    1768:         PetscCall(PetscObjectSetName((PetscObject)glob_v2, "trick"));
    1769:         c2_0[0] = &data[0];
    1770:         PetscCall(DMProjectFunction(dmEnergy, 0., energyf, (void **)c2_0, INSERT_ALL_VALUES, glob_v2));
    1771:         PetscCall(DMGetLocalVector(dmEnergy, &v2_2));
    1772:         PetscCall(VecZeroEntries(v2_2)); /* zero BCs so don't set */
    1773:         PetscCall(DMGlobalToLocalBegin(dmEnergy, glob_v2, INSERT_VALUES, v2_2));
    1774:         PetscCall(DMGlobalToLocalEnd(dmEnergy, glob_v2, INSERT_VALUES, v2_2));
    1775:         PetscCall(DMViewFromOptions(dmEnergy, NULL, "-energy_dm_view"));
    1776:         PetscCall(VecViewFromOptions(glob_v2, NULL, "-energy_vec_view"));
    1777:         PetscCall(DMRestoreGlobalVector(dmEnergy, &glob_v2));
    1778:       }
    1779:       /* append part of the IP data for each grid */
    1780:       for (ej = 0; ej < numCells[grid]; ++ej, ++outer_ej) {
    1781:         PetscScalar *coefs = NULL;
    1782:         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);
    1783:         invJe = invJ_a + outer_ej * Nq * dim * dim;
    1784:         PetscCall(DMPlexComputeCellGeometryFEM(ctx->plex[grid], ej + cStart, quad, vj, Jdummy, invJe, detJj));
    1785:         if (ctx->use_energy_tensor_trick) PetscCall(DMPlexVecGetClosure(dmEnergy, e_section, v2_2, ej + cStart, NULL, &coefs));
    1786:         /* create static point data */
    1787:         for (PetscInt qj = 0; qj < Nq; qj++, outer_ipidx++) {
    1788:           const PetscInt   gidx = outer_ipidx;
    1789:           const PetscReal *invJ = &invJe[qj * dim * dim];
    1790:           ww[gidx]              = detJj[qj] * quadWeights[qj];
    1791:           if (dim == 2) ww[gidx] *= vj[qj * dim + 0]; /* cylindrical coordinate, w/o 2pi */
    1792:           // get xx, yy, zz
    1793:           if (ctx->use_energy_tensor_trick) {
    1794:             double                 refSpaceDer[3], eGradPhi[3];
    1795:             const PetscReal *const DD = Tf[0]->T[1];
    1796:             const PetscReal       *Dq = &DD[qj * Nb * dim];
    1797:             for (PetscInt d = 0; d < 3; ++d) refSpaceDer[d] = eGradPhi[d] = 0.0;
    1798:             for (PetscInt b = 0; b < Nb; ++b) {
    1799:               for (PetscInt d = 0; d < dim; ++d) refSpaceDer[d] += Dq[b * dim + d] * PetscRealPart(coefs[b]);
    1800:             }
    1801:             xx[gidx] = 1e10;
    1802:             if (ctx->use_relativistic_corrections) {
    1803:               double dg2_c2 = 0;
    1804:               //for (PetscInt d = 0; d < dim; ++d) refSpaceDer[d] *= c02;
    1805:               for (PetscInt d = 0; d < dim; ++d) dg2_c2 += PetscSqr(refSpaceDer[d]);
    1806:               dg2_c2 *= (double)c02;
    1807:               if (dg2_c2 >= .999) {
    1808:                 xx[gidx] = vj[qj * dim + 0]; /* coordinate */
    1809:                 yy[gidx] = vj[qj * dim + 1];
    1810:                 if (dim == 3) zz[gidx] = vj[qj * dim + 2];
    1811:                 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]));
    1812:               } else {
    1813:                 PetscReal fact = c02 / PetscSqrtReal(1. - dg2_c2);
    1814:                 for (PetscInt d = 0; d < dim; ++d) refSpaceDer[d] *= fact;
    1815:                 // could test with other point u' that (grad - grad') * U (refSpaceDer, refSpaceDer') == 0
    1816:               }
    1817:             }
    1818:             if (xx[gidx] == 1e10) {
    1819:               for (PetscInt d = 0; d < dim; ++d) {
    1820:                 for (PetscInt e = 0; e < dim; ++e) eGradPhi[d] += invJ[e * dim + d] * refSpaceDer[e];
    1821:               }
    1822:               xx[gidx] = eGradPhi[0];
    1823:               yy[gidx] = eGradPhi[1];
    1824:               if (dim == 3) zz[gidx] = eGradPhi[2];
    1825:             }
    1826:           } else {
    1827:             xx[gidx] = vj[qj * dim + 0]; /* coordinate */
    1828:             yy[gidx] = vj[qj * dim + 1];
    1829:             if (dim == 3) zz[gidx] = vj[qj * dim + 2];
    1830:           }
    1831:         } /* q */
    1832:         if (ctx->use_energy_tensor_trick) PetscCall(DMPlexVecRestoreClosure(dmEnergy, e_section, v2_2, ej + cStart, NULL, &coefs));
    1833:       } /* ej */
    1834:       if (ctx->use_energy_tensor_trick) {
    1835:         PetscCall(DMRestoreLocalVector(dmEnergy, &v2_2));
    1836:         PetscCall(DMDestroy(&dmEnergy));
    1837:       }
    1838:     } /* grid */
    1839:     if (ctx->use_energy_tensor_trick) PetscCall(PetscFEDestroy(&fe));
    1840:     /* cache static data */
    1841:     if (ctx->deviceType == LANDAU_KOKKOS) {
    1842: #if defined(PETSC_HAVE_KOKKOS)
    1843:       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));
    1844:       /* free */
    1845:       PetscCall(PetscFree4(ww, xx, yy, invJ_a));
    1846:       if (dim == 3) PetscCall(PetscFree(zz));
    1847: #else
    1848:       SETERRQ(ctx->comm, PETSC_ERR_ARG_WRONG, "-landau_device_type kokkos not built");
    1849: #endif
    1850:     } else {                                                                                                                                                                   /* CPU version, just copy in, only use part */
    1851:       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 ?
    1852:       ctx->SData_d.w    = (void *)ww;
    1853:       ctx->SData_d.x    = (void *)xx;
    1854:       ctx->SData_d.y    = (void *)yy;
    1855:       ctx->SData_d.z    = (void *)zz;
    1856:       ctx->SData_d.invJ = (void *)invJ_a;
    1857:       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));
    1858:       for (PetscInt ii = 0; ii < ctx->num_species; ii++) {
    1859:         nu_alpha_p[ii] = nu_alpha[ii];
    1860:         nu_beta_p[ii]  = nu_beta[ii];
    1861:         invMass_p[ii]  = invMass[ii];
    1862:       }
    1863:       ctx->SData_d.alpha   = (void *)nu_alpha_p;
    1864:       ctx->SData_d.beta    = (void *)nu_beta_p;
    1865:       ctx->SData_d.invMass = (void *)invMass_p;
    1866:       ctx->SData_d.lambdas = (void *)lambdas_p;
    1867:       for (PetscInt grid = 0; grid < LANDAU_MAX_GRIDS; grid++) {
    1868:         PetscReal(*lambdas)[LANDAU_MAX_GRIDS][LANDAU_MAX_GRIDS] = (PetscReal(*)[LANDAU_MAX_GRIDS][LANDAU_MAX_GRIDS])ctx->SData_d.lambdas;
    1869:         for (PetscInt gridj = 0; gridj < LANDAU_MAX_GRIDS; gridj++) { (*lambdas)[grid][gridj] = ctx->lambdas[grid][gridj]; }
    1870:       }
    1871:     }
    1872:     PetscCall(PetscLogEventEnd(ctx->events[7], 0, 0, 0, 0));
    1873:   } // initialize
    1874:   PetscFunctionReturn(PETSC_SUCCESS);
    1875: }

    1877: /* < v, u > */
    1878: 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[])
    1879: {
    1880:   g0[0] = 1.;
    1881: }

    1883: /* < v, u > */
    1884: 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[])
    1885: {
    1886:   static double ttt = 1e-12;
    1887:   g0[0]             = ttt++;
    1888: }

    1890: /* < v, u > */
    1891: 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[])
    1892: {
    1893:   g0[0] = 2. * PETSC_PI * x[0];
    1894: }

    1896: static PetscErrorCode MatrixNfDestroy(void *ptr)
    1897: {
    1898:   PetscInt *nf = (PetscInt *)ptr;

    1900:   PetscFunctionBegin;
    1901:   PetscCall(PetscFree(nf));
    1902:   PetscFunctionReturn(PETSC_SUCCESS);
    1903: }

    1905: /*
    1906:  LandauCreateJacobianMatrix - creates ctx->J with without real data. Hard to keep sparse.
    1907:   - Like DMPlexLandauCreateMassMatrix. Should remove one and combine
    1908:   - has old support for field major ordering
    1909:  */
    1910: static PetscErrorCode LandauCreateJacobianMatrix(MPI_Comm comm, Vec X, IS grid_batch_is_inv[LANDAU_MAX_GRIDS], LandauCtx *ctx)
    1911: {
    1912:   PetscInt *idxs = NULL;
    1913:   Mat       subM[LANDAU_MAX_GRIDS];

    1915:   PetscFunctionBegin;
    1916:   if (!ctx->gpu_assembly) { /* we need GPU object with GPU assembly */
    1917:     PetscFunctionReturn(PETSC_SUCCESS);
    1918:   }
    1919:   // get the RCM for this grid to separate out species into blocks -- create 'idxs' & 'ctx->batch_is' -- not used
    1920:   if (ctx->gpu_assembly && ctx->jacobian_field_major_order) PetscCall(PetscMalloc1(ctx->mat_offset[ctx->num_grids] * ctx->batch_sz, &idxs));
    1921:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    1922:     const PetscInt *values, n = ctx->mat_offset[grid + 1] - ctx->mat_offset[grid];
    1923:     Mat             gMat;
    1924:     DM              massDM;
    1925:     PetscDS         prob;
    1926:     Vec             tvec;
    1927:     // get "mass" matrix for reordering
    1928:     PetscCall(DMClone(ctx->plex[grid], &massDM));
    1929:     PetscCall(DMCopyFields(ctx->plex[grid], PETSC_DETERMINE, PETSC_DETERMINE, massDM));
    1930:     PetscCall(DMCreateDS(massDM));
    1931:     PetscCall(DMGetDS(massDM, &prob));
    1932:     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));
    1933:     PetscCall(PetscOptionsInsertString(NULL, "-dm_preallocate_only")); // this trick is need to both sparsify the matrix and avoid runtime error
    1934:     PetscCall(DMCreateMatrix(massDM, &gMat));
    1935:     PetscCall(PetscOptionsInsertString(NULL, "-dm_preallocate_only false"));
    1936:     PetscCall(MatSetOption(gMat, MAT_STRUCTURALLY_SYMMETRIC, PETSC_TRUE));
    1937:     PetscCall(MatSetOption(gMat, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE));
    1938:     PetscCall(DMCreateLocalVector(ctx->plex[grid], &tvec));
    1939:     PetscCall(DMPlexSNESComputeJacobianFEM(massDM, tvec, gMat, gMat, ctx));
    1940:     PetscCall(MatViewFromOptions(gMat, NULL, "-dm_landau_reorder_mat_view"));
    1941:     PetscCall(DMDestroy(&massDM));
    1942:     PetscCall(VecDestroy(&tvec));
    1943:     subM[grid] = gMat;
    1944:     if (ctx->gpu_assembly && ctx->jacobian_field_major_order) {
    1945:       MatOrderingType rtype = MATORDERINGRCM;
    1946:       IS              isrow, isicol;
    1947:       PetscCall(MatGetOrdering(gMat, rtype, &isrow, &isicol));
    1948:       PetscCall(ISInvertPermutation(isrow, PETSC_DECIDE, &grid_batch_is_inv[grid]));
    1949:       PetscCall(ISGetIndices(isrow, &values));
    1950:       for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) { // add batch size DMs for this species grid
    1951: #if !defined(LANDAU_SPECIES_MAJOR)
    1952:         PetscInt N = ctx->mat_offset[ctx->num_grids], n0 = ctx->mat_offset[grid] + b_id * N;
    1953:         for (PetscInt ii = 0; ii < n; ++ii) idxs[n0 + ii] = values[ii] + n0;
    1954: #else
    1955:         PetscInt n0 = ctx->mat_offset[grid] * ctx->batch_sz + b_id * n;
    1956:         for (PetscInt ii = 0; ii < n; ++ii) idxs[n0 + ii] = values[ii] + n0;
    1957: #endif
    1958:       }
    1959:       PetscCall(ISRestoreIndices(isrow, &values));
    1960:       PetscCall(ISDestroy(&isrow));
    1961:       PetscCall(ISDestroy(&isicol));
    1962:     }
    1963:   }
    1964:   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));
    1965:   // get a block matrix
    1966:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    1967:     Mat      B = subM[grid];
    1968:     PetscInt nloc, nzl, *colbuf, row, COL_BF_SIZE = 1024;
    1969:     PetscCall(PetscMalloc(sizeof(*colbuf) * COL_BF_SIZE, &colbuf));
    1970:     PetscCall(MatGetSize(B, &nloc, NULL));
    1971:     for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) {
    1972:       const PetscInt     moffset = LAND_MOFFSET(b_id, grid, ctx->batch_sz, ctx->num_grids, ctx->mat_offset);
    1973:       const PetscInt    *cols;
    1974:       const PetscScalar *vals;
    1975:       for (PetscInt i = 0; i < nloc; i++) {
    1976:         PetscCall(MatGetRow(B, i, &nzl, NULL, NULL));
    1977:         if (nzl > COL_BF_SIZE) {
    1978:           PetscCall(PetscFree(colbuf));
    1979:           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));
    1980:           COL_BF_SIZE = nzl;
    1981:           PetscCall(PetscMalloc(sizeof(*colbuf) * COL_BF_SIZE, &colbuf));
    1982:         }
    1983:         PetscCall(MatGetRow(B, i, &nzl, &cols, &vals));
    1984:         for (PetscInt j = 0; j < nzl; j++) colbuf[j] = cols[j] + moffset;
    1985:         row = i + moffset;
    1986:         PetscCall(MatSetValues(ctx->J, 1, &row, nzl, colbuf, vals, INSERT_VALUES));
    1987:         PetscCall(MatRestoreRow(B, i, &nzl, &cols, &vals));
    1988:       }
    1989:     }
    1990:     PetscCall(PetscFree(colbuf));
    1991:   }
    1992:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) PetscCall(MatDestroy(&subM[grid]));
    1993:   PetscCall(MatAssemblyBegin(ctx->J, MAT_FINAL_ASSEMBLY));
    1994:   PetscCall(MatAssemblyEnd(ctx->J, MAT_FINAL_ASSEMBLY));

    1996:   // debug
    1997:   PetscCall(MatViewFromOptions(ctx->J, NULL, "-dm_landau_mat_view"));
    1998:   if (ctx->gpu_assembly && ctx->jacobian_field_major_order) {
    1999:     Mat mat_block_order;
    2000:     PetscCall(MatCreateSubMatrix(ctx->J, ctx->batch_is, ctx->batch_is, MAT_INITIAL_MATRIX, &mat_block_order)); // use MatPermute
    2001:     PetscCall(MatViewFromOptions(mat_block_order, NULL, "-dm_landau_mat_view"));
    2002:     PetscCall(MatDestroy(&mat_block_order));
    2003:     PetscCall(VecScatterCreate(X, ctx->batch_is, X, NULL, &ctx->plex_batch));
    2004:     PetscCall(VecDuplicate(X, &ctx->work_vec));
    2005:   }
    2006:   PetscFunctionReturn(PETSC_SUCCESS);
    2007: }

    2009: PetscErrorCode DMPlexLandauCreateMassMatrix(DM pack, Mat *Amat);
    2010: /*@C
    2011:   DMPlexLandauCreateVelocitySpace - Create a `DMPLEX` velocity space mesh

    2013:   Collective

    2015:   Input Parameters:
    2016: + comm   - The MPI communicator
    2017: . dim    - velocity space dimension (2 for axisymmetric, 3 for full 3X + 3V solver)
    2018: - prefix - prefix for options (not tested)

    2020:   Output Parameters:
    2021: + pack - The `DM` object representing the mesh
    2022: . X    - A vector (user destroys)
    2023: - J    - Optional matrix (object destroys)

    2025:   Level: beginner

    2027: .seealso: `DMPlexCreate()`, `DMPlexLandauDestroyVelocitySpace()`
    2028:  @*/
    2029: PetscErrorCode DMPlexLandauCreateVelocitySpace(MPI_Comm comm, PetscInt dim, const char prefix[], Vec *X, Mat *J, DM *pack)
    2030: {
    2031:   LandauCtx *ctx;
    2032:   Vec        Xsub[LANDAU_MAX_GRIDS];
    2033:   IS         grid_batch_is_inv[LANDAU_MAX_GRIDS];

    2035:   PetscFunctionBegin;
    2036:   PetscCheck(dim == 2 || dim == 3, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Only 2D and 3D supported");
    2037:   PetscCheck(LANDAU_DIM == dim, PETSC_COMM_SELF, PETSC_ERR_PLIB, "dim %" PetscInt_FMT " != LANDAU_DIM %d", dim, LANDAU_DIM);
    2038:   PetscCall(PetscNew(&ctx));
    2039:   ctx->comm = comm; /* used for diagnostics and global errors */
    2040:   /* process options */
    2041:   PetscCall(ProcessOptions(ctx, prefix));
    2042:   if (dim == 2) ctx->use_relativistic_corrections = PETSC_FALSE;
    2043:   /* Create Mesh */
    2044:   PetscCall(DMCompositeCreate(PETSC_COMM_SELF, pack));
    2045:   PetscCall(PetscLogEventBegin(ctx->events[13], 0, 0, 0, 0));
    2046:   PetscCall(PetscLogEventBegin(ctx->events[15], 0, 0, 0, 0));
    2047:   PetscCall(LandauDMCreateVMeshes(PETSC_COMM_SELF, dim, prefix, ctx, *pack)); // creates grids (Forest of AMR)
    2048:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    2049:     /* create FEM */
    2050:     PetscCall(SetupDS(ctx->plex[grid], dim, grid, ctx));
    2051:     /* set initial state */
    2052:     PetscCall(DMCreateGlobalVector(ctx->plex[grid], &Xsub[grid]));
    2053:     PetscCall(PetscObjectSetName((PetscObject)Xsub[grid], "u_orig"));
    2054:     /* initial static refinement, no solve */
    2055:     PetscCall(LandauSetInitialCondition(ctx->plex[grid], Xsub[grid], grid, 0, 1, ctx));
    2056:     /* forest refinement - forest goes in (if forest), plex comes out */
    2057:     if (ctx->use_p4est) {
    2058:       DM plex;
    2059:       PetscCall(adapt(grid, ctx, &Xsub[grid])); // forest goes in, plex comes out
    2060:       if (grid == 0) {
    2061:         PetscCall(DMViewFromOptions(ctx->plex[grid], NULL, "-dm_landau_amr_dm_view")); // need to differentiate - todo
    2062:         PetscCall(VecViewFromOptions(Xsub[grid], NULL, "-dm_landau_amr_vec_view"));
    2063:       }
    2064:       // convert to plex, all done with this level
    2065:       PetscCall(DMConvert(ctx->plex[grid], DMPLEX, &plex));
    2066:       PetscCall(DMDestroy(&ctx->plex[grid]));
    2067:       ctx->plex[grid] = plex;
    2068:     }
    2069: #if !defined(LANDAU_SPECIES_MAJOR)
    2070:     PetscCall(DMCompositeAddDM(*pack, ctx->plex[grid]));
    2071: #else
    2072:     for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) { // add batch size DMs for this species grid
    2073:       PetscCall(DMCompositeAddDM(*pack, ctx->plex[grid]));
    2074:     }
    2075: #endif
    2076:     PetscCall(DMSetApplicationContext(ctx->plex[grid], ctx));
    2077:   }
    2078: #if !defined(LANDAU_SPECIES_MAJOR)
    2079:   // stack the batched DMs, could do it all here!!! b_id=0
    2080:   for (PetscInt b_id = 1; b_id < ctx->batch_sz; b_id++) {
    2081:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) PetscCall(DMCompositeAddDM(*pack, ctx->plex[grid]));
    2082:   }
    2083: #endif
    2084:   // create ctx->mat_offset
    2085:   ctx->mat_offset[0] = 0;
    2086:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    2087:     PetscInt n;
    2088:     PetscCall(VecGetLocalSize(Xsub[grid], &n));
    2089:     ctx->mat_offset[grid + 1] = ctx->mat_offset[grid] + n;
    2090:   }
    2091:   // creat DM & Jac
    2092:   PetscCall(DMSetApplicationContext(*pack, ctx));
    2093:   PetscCall(PetscOptionsInsertString(NULL, "-dm_preallocate_only"));
    2094:   PetscCall(DMCreateMatrix(*pack, &ctx->J));
    2095:   PetscCall(PetscOptionsInsertString(NULL, "-dm_preallocate_only false"));
    2096:   PetscCall(MatSetOption(ctx->J, MAT_STRUCTURALLY_SYMMETRIC, PETSC_TRUE));
    2097:   PetscCall(MatSetOption(ctx->J, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE));
    2098:   PetscCall(PetscObjectSetName((PetscObject)ctx->J, "Jac"));
    2099:   // construct initial conditions in X
    2100:   PetscCall(DMCreateGlobalVector(*pack, X));
    2101:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    2102:     PetscInt n;
    2103:     PetscCall(VecGetLocalSize(Xsub[grid], &n));
    2104:     for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) {
    2105:       PetscScalar const *values;
    2106:       const PetscInt     moffset = LAND_MOFFSET(b_id, grid, ctx->batch_sz, ctx->num_grids, ctx->mat_offset);
    2107:       PetscCall(LandauSetInitialCondition(ctx->plex[grid], Xsub[grid], grid, b_id, ctx->batch_sz, ctx));
    2108:       PetscCall(VecGetArrayRead(Xsub[grid], &values)); // Drop whole grid in Plex ordering
    2109:       for (PetscInt i = 0, idx = moffset; i < n; i++, idx++) PetscCall(VecSetValue(*X, idx, values[i], INSERT_VALUES));
    2110:       PetscCall(VecRestoreArrayRead(Xsub[grid], &values));
    2111:     }
    2112:   }
    2113:   // cleanup
    2114:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) PetscCall(VecDestroy(&Xsub[grid]));
    2115:   /* check for correct matrix type */
    2116:   if (ctx->gpu_assembly) { /* we need GPU object with GPU assembly */
    2117:     PetscBool flg;
    2118:     if (ctx->deviceType == LANDAU_KOKKOS) {
    2119:       PetscCall(PetscObjectTypeCompareAny((PetscObject)ctx->J, &flg, MATSEQAIJKOKKOS, MATMPIAIJKOKKOS, MATAIJKOKKOS, ""));
    2120: #if defined(PETSC_HAVE_KOKKOS)
    2121:       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'");
    2122: #else
    2123:       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'");
    2124: #endif
    2125:     }
    2126:   }
    2127:   PetscCall(PetscLogEventEnd(ctx->events[15], 0, 0, 0, 0));

    2129:   // create field major ordering
    2130:   ctx->work_vec   = NULL;
    2131:   ctx->plex_batch = NULL;
    2132:   ctx->batch_is   = NULL;
    2133:   for (PetscInt i = 0; i < LANDAU_MAX_GRIDS; i++) grid_batch_is_inv[i] = NULL;
    2134:   PetscCall(PetscLogEventBegin(ctx->events[12], 0, 0, 0, 0));
    2135:   PetscCall(LandauCreateJacobianMatrix(comm, *X, grid_batch_is_inv, ctx));
    2136:   PetscCall(PetscLogEventEnd(ctx->events[12], 0, 0, 0, 0));

    2138:   // create AMR GPU assembly maps and static GPU data
    2139:   PetscCall(CreateStaticData(dim, grid_batch_is_inv, ctx));

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

    2143:   // create mass matrix
    2144:   PetscCall(DMPlexLandauCreateMassMatrix(*pack, NULL));

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

    2148:   if (ctx->gpu_assembly && ctx->jacobian_field_major_order) {
    2149:     PetscContainer container;
    2150:     // cache ctx for KSP with batch/field major Jacobian ordering -ksp_type gmres/etc -dm_landau_jacobian_field_major_order
    2151:     PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
    2152:     PetscCall(PetscContainerSetPointer(container, (void *)ctx));
    2153:     PetscCall(PetscObjectCompose((PetscObject)ctx->J, "LandauCtx", (PetscObject)container));
    2154:     PetscCall(PetscContainerDestroy(&container));
    2155:     // batch solvers need to map -- can batch solvers work
    2156:     PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
    2157:     PetscCall(PetscContainerSetPointer(container, (void *)ctx->plex_batch));
    2158:     PetscCall(PetscObjectCompose((PetscObject)ctx->J, "plex_batch_is", (PetscObject)container));
    2159:     PetscCall(PetscContainerDestroy(&container));
    2160:   }
    2161:   // for batch solvers
    2162:   {
    2163:     PetscContainer container;
    2164:     PetscInt      *pNf;
    2165:     PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
    2166:     PetscCall(PetscMalloc1(sizeof(*pNf), &pNf));
    2167:     *pNf = ctx->batch_sz;
    2168:     PetscCall(PetscContainerSetPointer(container, (void *)pNf));
    2169:     PetscCall(PetscContainerSetUserDestroy(container, MatrixNfDestroy));
    2170:     PetscCall(PetscObjectCompose((PetscObject)ctx->J, "batch size", (PetscObject)container));
    2171:     PetscCall(PetscContainerDestroy(&container));
    2172:   }
    2173:   PetscFunctionReturn(PETSC_SUCCESS);
    2174: }

    2176: /*@C
    2177:   DMPlexLandauAccess - Access to the distribution function with user callback

    2179:   Collective

    2181:   Input Parameters:
    2182: + pack     - the `DMCOMPOSITE`
    2183: . func     - call back function
    2184: - user_ctx - user context

    2186:   Input/Output Parameter:
    2187: . X - Vector to data to

    2189:   Level: advanced

    2191: .seealso: `DMPlexLandauCreateVelocitySpace()`
    2192:  @*/
    2193: PetscErrorCode DMPlexLandauAccess(DM pack, Vec X, PetscErrorCode (*func)(DM, Vec, PetscInt, PetscInt, PetscInt, void *), void *user_ctx)
    2194: {
    2195:   LandauCtx *ctx;

    2197:   PetscFunctionBegin;
    2198:   PetscCall(DMGetApplicationContext(pack, &ctx)); // uses ctx->num_grids; ctx->plex[grid]; ctx->batch_sz; ctx->mat_offset
    2199:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    2200:     PetscInt dim, n;
    2201:     PetscCall(DMGetDimension(pack, &dim));
    2202:     for (PetscInt sp = ctx->species_offset[grid], i0 = 0; sp < ctx->species_offset[grid + 1]; sp++, i0++) {
    2203:       Vec      vec;
    2204:       PetscInt vf[1] = {i0};
    2205:       IS       vis;
    2206:       DM       vdm;
    2207:       PetscCall(DMCreateSubDM(ctx->plex[grid], 1, vf, &vis, &vdm));
    2208:       PetscCall(DMSetApplicationContext(vdm, ctx)); // the user might want this
    2209:       PetscCall(DMCreateGlobalVector(vdm, &vec));
    2210:       PetscCall(VecGetSize(vec, &n));
    2211:       for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) {
    2212:         const PetscInt moffset = LAND_MOFFSET(b_id, grid, ctx->batch_sz, ctx->num_grids, ctx->mat_offset);
    2213:         PetscCall(VecZeroEntries(vec));
    2214:         /* Add your data with 'dm' for species 'sp' to 'vec' */
    2215:         PetscCall(func(vdm, vec, i0, grid, b_id, user_ctx));
    2216:         /* add to global */
    2217:         PetscScalar const *values;
    2218:         const PetscInt    *offsets;
    2219:         PetscCall(VecGetArrayRead(vec, &values));
    2220:         PetscCall(ISGetIndices(vis, &offsets));
    2221:         for (PetscInt i = 0; i < n; i++) PetscCall(VecSetValue(X, moffset + offsets[i], values[i], ADD_VALUES));
    2222:         PetscCall(VecRestoreArrayRead(vec, &values));
    2223:         PetscCall(ISRestoreIndices(vis, &offsets));
    2224:       } // batch
    2225:       PetscCall(VecDestroy(&vec));
    2226:       PetscCall(ISDestroy(&vis));
    2227:       PetscCall(DMDestroy(&vdm));
    2228:     }
    2229:   } // grid
    2230:   PetscFunctionReturn(PETSC_SUCCESS);
    2231: }

    2233: /*@
    2234:   DMPlexLandauDestroyVelocitySpace - Destroy a `DMPLEX` velocity space mesh

    2236:   Collective

    2238:   Input/Output Parameters:
    2239: . dm - the `DM` to destroy

    2241:   Level: beginner

    2243: .seealso: `DMPlexLandauCreateVelocitySpace()`
    2244:  @*/
    2245: PetscErrorCode DMPlexLandauDestroyVelocitySpace(DM *dm)
    2246: {
    2247:   LandauCtx *ctx;

    2249:   PetscFunctionBegin;
    2250:   PetscCall(DMGetApplicationContext(*dm, &ctx));
    2251:   PetscCall(MatDestroy(&ctx->M));
    2252:   PetscCall(MatDestroy(&ctx->J));
    2253:   for (PetscInt ii = 0; ii < ctx->num_species; ii++) PetscCall(PetscFEDestroy(&ctx->fe[ii]));
    2254:   PetscCall(ISDestroy(&ctx->batch_is));
    2255:   PetscCall(VecDestroy(&ctx->work_vec));
    2256:   PetscCall(VecScatterDestroy(&ctx->plex_batch));
    2257:   if (ctx->deviceType == LANDAU_KOKKOS) {
    2258: #if defined(PETSC_HAVE_KOKKOS)
    2259:     PetscCall(LandauKokkosStaticDataClear(&ctx->SData_d));
    2260: #else
    2261:     SETERRQ(ctx->comm, PETSC_ERR_ARG_WRONG, "-landau_device_type %s not built", "kokkos");
    2262: #endif
    2263:   } else {
    2264:     if (ctx->SData_d.x) { /* in a CPU run */
    2265:       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;
    2266:       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;
    2267:       PetscCall(PetscFree4(ww, xx, yy, invJ));
    2268:       if (zz) PetscCall(PetscFree(zz));
    2269:       if (coo_elem_offsets) {
    2270:         PetscCall(PetscFree3(coo_elem_offsets, coo_elem_fullNb, coo_elem_point_offsets)); // could be NULL
    2271:       }
    2272:       PetscCall(PetscFree4(ctx->SData_d.alpha, ctx->SData_d.beta, ctx->SData_d.invMass, ctx->SData_d.lambdas));
    2273:     }
    2274:   }

    2276:   if (ctx->times[LANDAU_MATRIX_TOTAL] > 0) { // OMP timings
    2277:     PetscCall(PetscPrintf(ctx->comm, "TSStep               N  1.0 %10.3e\n", ctx->times[LANDAU_EX2_TSSOLVE]));
    2278:     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));
    2279:     PetscCall(PetscPrintf(ctx->comm, "3:          Landau:  %10.3e\n", ctx->times[LANDAU_MATRIX_TOTAL]));
    2280:     PetscCall(PetscPrintf(ctx->comm, "Landau Jacobian       %" PetscInt_FMT " 1.0 %10.3e\n", (PetscInt)ctx->times[LANDAU_JACOBIAN_COUNT], ctx->times[LANDAU_JACOBIAN]));
    2281:     PetscCall(PetscPrintf(ctx->comm, "Landau Operator       N 1.0  %10.3e\n", ctx->times[LANDAU_OPERATOR]));
    2282:     PetscCall(PetscPrintf(ctx->comm, "Landau Mass           N 1.0  %10.3e\n", ctx->times[LANDAU_MASS]));
    2283:     PetscCall(PetscPrintf(ctx->comm, " Jac-f-df (GPU)       N 1.0  %10.3e\n", ctx->times[LANDAU_F_DF]));
    2284:     PetscCall(PetscPrintf(ctx->comm, " Kernel (GPU)         N 1.0  %10.3e\n", ctx->times[LANDAU_KERNEL]));
    2285:     PetscCall(PetscPrintf(ctx->comm, "MatLUFactorNum        X 1.0 %10.3e\n", ctx->times[KSP_FACTOR]));
    2286:     PetscCall(PetscPrintf(ctx->comm, "MatSolve              X 1.0 %10.3e\n", ctx->times[KSP_SOLVE]));
    2287:   }
    2288:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) PetscCall(DMDestroy(&ctx->plex[grid]));
    2289:   PetscCall(PetscFree(ctx));
    2290:   PetscCall(DMDestroy(dm));
    2291:   PetscFunctionReturn(PETSC_SUCCESS);
    2292: }

    2294: /* < v, ru > */
    2295: 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)
    2296: {
    2297:   PetscInt ii = (PetscInt)PetscRealPart(constants[0]);
    2298:   f0[0]       = u[ii];
    2299: }

    2301: /* < v, ru > */
    2302: 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)
    2303: {
    2304:   PetscInt ii = (PetscInt)PetscRealPart(constants[0]), jj = (PetscInt)PetscRealPart(constants[1]);
    2305:   f0[0] = x[jj] * u[ii]; /* x momentum */
    2306: }

    2308: 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)
    2309: {
    2310:   PetscInt i, ii = (PetscInt)PetscRealPart(constants[0]);
    2311:   double   tmp1 = 0.;
    2312:   for (i = 0; i < dim; ++i) tmp1 += x[i] * x[i];
    2313:   f0[0] = tmp1 * u[ii];
    2314: }

    2316: static PetscErrorCode gamma_n_f(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *actx)
    2317: {
    2318:   const PetscReal *c2_0_arr = ((PetscReal *)actx);
    2319:   const PetscReal  c02      = c2_0_arr[0];

    2321:   PetscFunctionBegin;
    2322:   for (PetscInt s = 0; s < Nf; s++) {
    2323:     PetscReal tmp1 = 0.;
    2324:     for (PetscInt i = 0; i < dim; ++i) tmp1 += x[i] * x[i];
    2325: #if defined(PETSC_USE_DEBUG)
    2326:     u[s] = PetscSqrtReal(1. + tmp1 / c02); //  u[0] = PetscSqrtReal(1. + xx);
    2327: #else
    2328:     {
    2329:       PetscReal xx = tmp1 / c02;
    2330:       u[s]         = xx / (PetscSqrtReal(1. + xx) + 1.); // better conditioned = xx/(PetscSqrtReal(1. + xx) + 1.)
    2331:     }
    2332: #endif
    2333:   }
    2334:   PetscFunctionReturn(PETSC_SUCCESS);
    2335: }

    2337: /* < v, ru > */
    2338: 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)
    2339: {
    2340:   PetscInt ii = (PetscInt)PetscRealPart(constants[0]);
    2341:   f0[0]       = 2. * PETSC_PI * x[0] * u[ii];
    2342: }

    2344: /* < v, ru > */
    2345: 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)
    2346: {
    2347:   PetscInt ii = (PetscInt)PetscRealPart(constants[0]);
    2348:   f0[0]       = 2. * PETSC_PI * x[0] * x[1] * u[ii];
    2349: }

    2351: 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)
    2352: {
    2353:   PetscInt ii = (PetscInt)PetscRealPart(constants[0]);
    2354:   f0[0]       = 2. * PETSC_PI * x[0] * (x[0] * x[0] + x[1] * x[1]) * u[ii];
    2355: }

    2357: /*@
    2358:   DMPlexLandauPrintNorms - collects moments and prints them

    2360:   Collective

    2362:   Input Parameters:
    2363: + X     - the state
    2364: - stepi - current step to print

    2366:   Level: beginner

    2368: .seealso: `DMPlexLandauCreateVelocitySpace()`
    2369:  @*/
    2370: PetscErrorCode DMPlexLandauPrintNorms(Vec X, PetscInt stepi)
    2371: {
    2372:   LandauCtx  *ctx;
    2373:   PetscDS     prob;
    2374:   DM          pack;
    2375:   PetscInt    cStart, cEnd, dim, ii, i0, nDMs;
    2376:   PetscScalar xmomentumtot = 0, ymomentumtot = 0, zmomentumtot = 0, energytot = 0, densitytot = 0, tt[LANDAU_MAX_SPECIES];
    2377:   PetscScalar xmomentum[LANDAU_MAX_SPECIES], ymomentum[LANDAU_MAX_SPECIES], zmomentum[LANDAU_MAX_SPECIES], energy[LANDAU_MAX_SPECIES], density[LANDAU_MAX_SPECIES];
    2378:   Vec        *globXArray;

    2380:   PetscFunctionBegin;
    2381:   PetscCall(VecGetDM(X, &pack));
    2382:   PetscCheck(pack, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Vector has no DM");
    2383:   PetscCall(DMGetDimension(pack, &dim));
    2384:   PetscCheck(dim == 2 || dim == 3, PETSC_COMM_SELF, PETSC_ERR_PLIB, "dim %" PetscInt_FMT " not in [2,3]", dim);
    2385:   PetscCall(DMGetApplicationContext(pack, &ctx));
    2386:   PetscCheck(ctx, PETSC_COMM_SELF, PETSC_ERR_PLIB, "no context");
    2387:   /* print momentum and energy */
    2388:   PetscCall(DMCompositeGetNumberDM(pack, &nDMs));
    2389:   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);
    2390:   PetscCall(PetscMalloc(sizeof(*globXArray) * nDMs, &globXArray));
    2391:   PetscCall(DMCompositeGetAccessArray(pack, X, nDMs, NULL, globXArray));
    2392:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    2393:     Vec Xloc = globXArray[LAND_PACK_IDX(ctx->batch_view_idx, grid)];
    2394:     PetscCall(DMGetDS(ctx->plex[grid], &prob));
    2395:     for (ii = ctx->species_offset[grid], i0 = 0; ii < ctx->species_offset[grid + 1]; ii++, i0++) {
    2396:       PetscScalar user[2] = {(PetscScalar)i0, (PetscScalar)ctx->charges[ii]};
    2397:       PetscCall(PetscDSSetConstants(prob, 2, user));
    2398:       if (dim == 2) { /* 2/3X + 3V (cylindrical coordinates) */
    2399:         PetscCall(PetscDSSetObjective(prob, 0, &f0_s_rden));
    2400:         PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
    2401:         density[ii] = tt[0] * ctx->n_0 * ctx->charges[ii];
    2402:         PetscCall(PetscDSSetObjective(prob, 0, &f0_s_rmom));
    2403:         PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
    2404:         zmomentum[ii] = tt[0] * ctx->n_0 * ctx->v_0 * ctx->masses[ii];
    2405:         PetscCall(PetscDSSetObjective(prob, 0, &f0_s_rv2));
    2406:         PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
    2407:         energy[ii] = tt[0] * 0.5 * ctx->n_0 * ctx->v_0 * ctx->v_0 * ctx->masses[ii];
    2408:         zmomentumtot += zmomentum[ii];
    2409:         energytot += energy[ii];
    2410:         densitytot += density[ii];
    2411:         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])));
    2412:       } else { /* 2/3Xloc + 3V */
    2413:         PetscCall(PetscDSSetObjective(prob, 0, &f0_s_den));
    2414:         PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
    2415:         density[ii] = tt[0] * ctx->n_0 * ctx->charges[ii];
    2416:         PetscCall(PetscDSSetObjective(prob, 0, &f0_s_mom));
    2417:         user[1] = 0;
    2418:         PetscCall(PetscDSSetConstants(prob, 2, user));
    2419:         PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
    2420:         xmomentum[ii] = tt[0] * ctx->n_0 * ctx->v_0 * ctx->masses[ii];
    2421:         user[1]       = 1;
    2422:         PetscCall(PetscDSSetConstants(prob, 2, user));
    2423:         PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
    2424:         ymomentum[ii] = tt[0] * ctx->n_0 * ctx->v_0 * ctx->masses[ii];
    2425:         user[1]       = 2;
    2426:         PetscCall(PetscDSSetConstants(prob, 2, user));
    2427:         PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
    2428:         zmomentum[ii] = tt[0] * ctx->n_0 * ctx->v_0 * ctx->masses[ii];
    2429:         if (ctx->use_relativistic_corrections) {
    2430:           /* gamma * M * f */
    2431:           if (ii == 0 && grid == 0) { // do all at once
    2432:             Vec Mf, globGamma, *globMfArray, *globGammaArray;
    2433:             PetscErrorCode (*gammaf[1])(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *) = {gamma_n_f};
    2434:             PetscReal *c2_0[1], data[1];

    2436:             PetscCall(VecDuplicate(X, &globGamma));
    2437:             PetscCall(VecDuplicate(X, &Mf));
    2438:             PetscCall(PetscMalloc(sizeof(*globMfArray) * nDMs, &globMfArray));
    2439:             PetscCall(PetscMalloc(sizeof(*globMfArray) * nDMs, &globGammaArray));
    2440:             /* M * f */
    2441:             PetscCall(MatMult(ctx->M, X, Mf));
    2442:             /* gamma */
    2443:             PetscCall(DMCompositeGetAccessArray(pack, globGamma, nDMs, NULL, globGammaArray));
    2444:             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
    2445:               Vec v1  = globGammaArray[LAND_PACK_IDX(ctx->batch_view_idx, grid)];
    2446:               data[0] = PetscSqr(C_0(ctx->v_0));
    2447:               c2_0[0] = &data[0];
    2448:               PetscCall(DMProjectFunction(ctx->plex[grid], 0., gammaf, (void **)c2_0, INSERT_ALL_VALUES, v1));
    2449:             }
    2450:             PetscCall(DMCompositeRestoreAccessArray(pack, globGamma, nDMs, NULL, globGammaArray));
    2451:             /* gamma * Mf */
    2452:             PetscCall(DMCompositeGetAccessArray(pack, globGamma, nDMs, NULL, globGammaArray));
    2453:             PetscCall(DMCompositeGetAccessArray(pack, Mf, nDMs, NULL, globMfArray));
    2454:             for (PetscInt grid = 0; grid < ctx->num_grids; grid++) { // yes a grid loop in a grid loop to print nice
    2455:               PetscInt Nf    = ctx->species_offset[grid + 1] - ctx->species_offset[grid], N, bs;
    2456:               Vec      Mfsub = globMfArray[LAND_PACK_IDX(ctx->batch_view_idx, grid)], Gsub = globGammaArray[LAND_PACK_IDX(ctx->batch_view_idx, grid)], v1, v2;
    2457:               // get each component
    2458:               PetscCall(VecGetSize(Mfsub, &N));
    2459:               PetscCall(VecCreate(ctx->comm, &v1));
    2460:               PetscCall(VecSetSizes(v1, PETSC_DECIDE, N / Nf));
    2461:               PetscCall(VecCreate(ctx->comm, &v2));
    2462:               PetscCall(VecSetSizes(v2, PETSC_DECIDE, N / Nf));
    2463:               PetscCall(VecSetFromOptions(v1)); // ???
    2464:               PetscCall(VecSetFromOptions(v2));
    2465:               // get each component
    2466:               PetscCall(VecGetBlockSize(Gsub, &bs));
    2467:               PetscCheck(bs == Nf, PETSC_COMM_SELF, PETSC_ERR_PLIB, "bs %" PetscInt_FMT " != num_species %" PetscInt_FMT " in Gsub", bs, Nf);
    2468:               PetscCall(VecGetBlockSize(Mfsub, &bs));
    2469:               PetscCheck(bs == Nf, PETSC_COMM_SELF, PETSC_ERR_PLIB, "bs %" PetscInt_FMT " != num_species %" PetscInt_FMT, bs, Nf);
    2470:               for (PetscInt i = 0, ix = ctx->species_offset[grid]; i < Nf; i++, ix++) {
    2471:                 PetscScalar val;
    2472:                 PetscCall(VecStrideGather(Gsub, i, v1, INSERT_VALUES)); // this is not right -- TODO
    2473:                 PetscCall(VecStrideGather(Mfsub, i, v2, INSERT_VALUES));
    2474:                 PetscCall(VecDot(v1, v2, &val));
    2475:                 energy[ix] = PetscRealPart(val) * ctx->n_0 * ctx->v_0 * ctx->v_0 * ctx->masses[ix];
    2476:               }
    2477:               PetscCall(VecDestroy(&v1));
    2478:               PetscCall(VecDestroy(&v2));
    2479:             } /* grids */
    2480:             PetscCall(DMCompositeRestoreAccessArray(pack, globGamma, nDMs, NULL, globGammaArray));
    2481:             PetscCall(DMCompositeRestoreAccessArray(pack, Mf, nDMs, NULL, globMfArray));
    2482:             PetscCall(PetscFree(globGammaArray));
    2483:             PetscCall(PetscFree(globMfArray));
    2484:             PetscCall(VecDestroy(&globGamma));
    2485:             PetscCall(VecDestroy(&Mf));
    2486:           }
    2487:         } else {
    2488:           PetscCall(PetscDSSetObjective(prob, 0, &f0_s_v2));
    2489:           PetscCall(DMPlexComputeIntegralFEM(ctx->plex[grid], Xloc, tt, ctx));
    2490:           energy[ii] = 0.5 * tt[0] * ctx->n_0 * ctx->v_0 * ctx->v_0 * ctx->masses[ii];
    2491:         }
    2492:         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])));
    2493:         xmomentumtot += xmomentum[ii];
    2494:         ymomentumtot += ymomentum[ii];
    2495:         zmomentumtot += zmomentum[ii];
    2496:         energytot += energy[ii];
    2497:         densitytot += density[ii];
    2498:       }
    2499:       if (ctx->num_species > 1) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n"));
    2500:     }
    2501:   }
    2502:   PetscCall(DMCompositeRestoreAccessArray(pack, X, nDMs, NULL, globXArray));
    2503:   PetscCall(PetscFree(globXArray));
    2504:   /* totals */
    2505:   PetscCall(DMPlexGetHeightStratum(ctx->plex[0], 0, &cStart, &cEnd));
    2506:   if (ctx->num_species > 1) {
    2507:     if (dim == 2) {
    2508:       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),
    2509:                             (double)(ctx->masses[1] / ctx->masses[0]), cEnd - cStart));
    2510:     } else {
    2511:       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),
    2512:                             (double)(ctx->masses[1] / ctx->masses[0]), cEnd - cStart));
    2513:     }
    2514:   } else PetscCall(PetscPrintf(PETSC_COMM_WORLD, " -- %" PetscInt_FMT " cells", cEnd - cStart));
    2515:   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n"));
    2516:   PetscFunctionReturn(PETSC_SUCCESS);
    2517: }

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

    2523:   Collective

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

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

    2531:   Level: beginner

    2533: .seealso: `DMPlexLandauCreateVelocitySpace()`
    2534:  @*/
    2535: PetscErrorCode DMPlexLandauCreateMassMatrix(DM pack, Mat *Amat)
    2536: {
    2537:   DM         mass_pack, massDM[LANDAU_MAX_GRIDS];
    2538:   PetscDS    prob;
    2539:   PetscInt   ii, dim, N1 = 1, N2;
    2540:   LandauCtx *ctx;
    2541:   Mat        packM, subM[LANDAU_MAX_GRIDS];

    2543:   PetscFunctionBegin;
    2545:   if (Amat) PetscAssertPointer(Amat, 2);
    2546:   PetscCall(DMGetApplicationContext(pack, &ctx));
    2547:   PetscCheck(ctx, PETSC_COMM_SELF, PETSC_ERR_PLIB, "no context");
    2548:   PetscCall(PetscLogEventBegin(ctx->events[14], 0, 0, 0, 0));
    2549:   PetscCall(DMGetDimension(pack, &dim));
    2550:   PetscCall(DMCompositeCreate(PetscObjectComm((PetscObject)pack), &mass_pack));
    2551:   /* create pack mass matrix */
    2552:   for (PetscInt grid = 0, ix = 0; grid < ctx->num_grids; grid++) {
    2553:     PetscCall(DMClone(ctx->plex[grid], &massDM[grid]));
    2554:     PetscCall(DMCopyFields(ctx->plex[grid], PETSC_DETERMINE, PETSC_DETERMINE, massDM[grid]));
    2555:     PetscCall(DMCreateDS(massDM[grid]));
    2556:     PetscCall(DMGetDS(massDM[grid], &prob));
    2557:     for (ix = 0, ii = ctx->species_offset[grid]; ii < ctx->species_offset[grid + 1]; ii++, ix++) {
    2558:       if (dim == 3) PetscCall(PetscDSSetJacobian(prob, ix, ix, g0_1, NULL, NULL, NULL));
    2559:       else PetscCall(PetscDSSetJacobian(prob, ix, ix, g0_r, NULL, NULL, NULL));
    2560:     }
    2561: #if !defined(LANDAU_SPECIES_MAJOR)
    2562:     PetscCall(DMCompositeAddDM(mass_pack, massDM[grid]));
    2563: #else
    2564:     for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) { // add batch size DMs for this species grid
    2565:       PetscCall(DMCompositeAddDM(mass_pack, massDM[grid]));
    2566:     }
    2567: #endif
    2568:     PetscCall(DMCreateMatrix(massDM[grid], &subM[grid]));
    2569:   }
    2570: #if !defined(LANDAU_SPECIES_MAJOR)
    2571:   // stack the batched DMs
    2572:   for (PetscInt b_id = 1; b_id < ctx->batch_sz; b_id++) {
    2573:     for (PetscInt grid = 0; grid < ctx->num_grids; grid++) PetscCall(DMCompositeAddDM(mass_pack, massDM[grid]));
    2574:   }
    2575: #endif
    2576:   PetscCall(PetscOptionsInsertString(NULL, "-dm_preallocate_only"));
    2577:   PetscCall(DMCreateMatrix(mass_pack, &packM));
    2578:   PetscCall(PetscOptionsInsertString(NULL, "-dm_preallocate_only false"));
    2579:   PetscCall(MatSetOption(packM, MAT_STRUCTURALLY_SYMMETRIC, PETSC_TRUE));
    2580:   PetscCall(MatSetOption(packM, MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE));
    2581:   PetscCall(DMDestroy(&mass_pack));
    2582:   /* make mass matrix for each block */
    2583:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    2584:     Vec locX;
    2585:     DM  plex = massDM[grid];
    2586:     PetscCall(DMGetLocalVector(plex, &locX));
    2587:     /* Mass matrix is independent of the input, so no need to fill locX */
    2588:     PetscCall(DMPlexSNESComputeJacobianFEM(plex, locX, subM[grid], subM[grid], ctx));
    2589:     PetscCall(DMRestoreLocalVector(plex, &locX));
    2590:     PetscCall(DMDestroy(&massDM[grid]));
    2591:   }
    2592:   PetscCall(MatGetSize(ctx->J, &N1, NULL));
    2593:   PetscCall(MatGetSize(packM, &N2, NULL));
    2594:   PetscCheck(N1 == N2, PetscObjectComm((PetscObject)pack), PETSC_ERR_PLIB, "Incorrect matrix sizes: |Jacobian| = %" PetscInt_FMT ", |Mass|=%" PetscInt_FMT, N1, N2);
    2595:   /* assemble block diagonals */
    2596:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) {
    2597:     Mat      B = subM[grid];
    2598:     PetscInt nloc, nzl, *colbuf, COL_BF_SIZE = 1024, row;
    2599:     PetscCall(PetscMalloc(sizeof(*colbuf) * COL_BF_SIZE, &colbuf));
    2600:     PetscCall(MatGetSize(B, &nloc, NULL));
    2601:     for (PetscInt b_id = 0; b_id < ctx->batch_sz; b_id++) {
    2602:       const PetscInt     moffset = LAND_MOFFSET(b_id, grid, ctx->batch_sz, ctx->num_grids, ctx->mat_offset);
    2603:       const PetscInt    *cols;
    2604:       const PetscScalar *vals;
    2605:       for (PetscInt i = 0; i < nloc; i++) {
    2606:         PetscCall(MatGetRow(B, i, &nzl, NULL, NULL));
    2607:         if (nzl > COL_BF_SIZE) {
    2608:           PetscCall(PetscFree(colbuf));
    2609:           PetscCall(PetscInfo(pack, "Realloc buffer %" PetscInt_FMT " to %" PetscInt_FMT " (row size %" PetscInt_FMT ") \n", COL_BF_SIZE, 2 * COL_BF_SIZE, nzl));
    2610:           COL_BF_SIZE = nzl;
    2611:           PetscCall(PetscMalloc(sizeof(*colbuf) * COL_BF_SIZE, &colbuf));
    2612:         }
    2613:         PetscCall(MatGetRow(B, i, &nzl, &cols, &vals));
    2614:         for (PetscInt j = 0; j < nzl; j++) colbuf[j] = cols[j] + moffset;
    2615:         row = i + moffset;
    2616:         PetscCall(MatSetValues(packM, 1, &row, nzl, colbuf, vals, INSERT_VALUES));
    2617:         PetscCall(MatRestoreRow(B, i, &nzl, &cols, &vals));
    2618:       }
    2619:     }
    2620:     PetscCall(PetscFree(colbuf));
    2621:   }
    2622:   // cleanup
    2623:   for (PetscInt grid = 0; grid < ctx->num_grids; grid++) PetscCall(MatDestroy(&subM[grid]));
    2624:   PetscCall(MatAssemblyBegin(packM, MAT_FINAL_ASSEMBLY));
    2625:   PetscCall(MatAssemblyEnd(packM, MAT_FINAL_ASSEMBLY));
    2626:   PetscCall(PetscObjectSetName((PetscObject)packM, "mass"));
    2627:   PetscCall(MatViewFromOptions(packM, NULL, "-dm_landau_mass_view"));
    2628:   ctx->M = packM;
    2629:   if (Amat) *Amat = packM;
    2630:   PetscCall(PetscLogEventEnd(ctx->events[14], 0, 0, 0, 0));
    2631:   PetscFunctionReturn(PETSC_SUCCESS);
    2632: }

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

    2637:   Collective

    2639:   Input Parameters:
    2640: + ts         - The time stepping context
    2641: . time_dummy - current time (not used)
    2642: . X          - Current state
    2643: . X_t        - Time derivative of current state
    2644: - actx       - Landau context

    2646:   Output Parameter:
    2647: . F - The residual

    2649:   Level: beginner

    2651: .seealso: `DMPlexLandauCreateVelocitySpace()`, `DMPlexLandauIJacobian()`
    2652:  @*/
    2653: PetscErrorCode DMPlexLandauIFunction(TS ts, PetscReal time_dummy, Vec X, Vec X_t, Vec F, void *actx)
    2654: {
    2655:   LandauCtx *ctx = (LandauCtx *)actx;
    2656:   PetscInt   dim;
    2657:   DM         pack;
    2658: #if defined(PETSC_HAVE_THREADSAFETY)
    2659:   double starttime, endtime;
    2660: #endif
    2661:   PetscObjectState state;

    2663:   PetscFunctionBegin;
    2664:   PetscCall(TSGetDM(ts, &pack));
    2665:   PetscCall(DMGetApplicationContext(pack, &ctx));
    2666:   PetscCheck(ctx, PETSC_COMM_SELF, PETSC_ERR_PLIB, "no context");
    2667:   if (ctx->stage) PetscCall(PetscLogStagePush(ctx->stage));
    2668:   PetscCall(PetscLogEventBegin(ctx->events[11], 0, 0, 0, 0));
    2669:   PetscCall(PetscLogEventBegin(ctx->events[0], 0, 0, 0, 0));
    2670: #if defined(PETSC_HAVE_THREADSAFETY)
    2671:   starttime = MPI_Wtime();
    2672: #endif
    2673:   PetscCall(DMGetDimension(pack, &dim));
    2674:   PetscCall(PetscObjectStateGet((PetscObject)ctx->J, &state));
    2675:   if (state != ctx->norm_state) {
    2676:     PetscCall(MatZeroEntries(ctx->J));
    2677:     PetscCall(LandauFormJacobian_Internal(X, ctx->J, dim, 0.0, (void *)ctx));
    2678:     PetscCall(MatViewFromOptions(ctx->J, NULL, "-dm_landau_jacobian_view"));
    2679:     PetscCall(PetscObjectStateGet((PetscObject)ctx->J, &state));
    2680:     ctx->norm_state = state;
    2681:   } else {
    2682:     PetscCall(PetscInfo(ts, "WARNING Skip forming Jacobian, has not changed %" PetscInt64_FMT "\n", state));
    2683:   }
    2684:   /* mat vec for op */
    2685:   PetscCall(MatMult(ctx->J, X, F)); /* C*f */
    2686:   /* add time term */
    2687:   if (X_t) PetscCall(MatMultAdd(ctx->M, X_t, F, F));
    2688: #if defined(PETSC_HAVE_THREADSAFETY)
    2689:   if (ctx->stage) {
    2690:     endtime = MPI_Wtime();
    2691:     ctx->times[LANDAU_OPERATOR] += (endtime - starttime);
    2692:     ctx->times[LANDAU_JACOBIAN] += (endtime - starttime);
    2693:     ctx->times[LANDAU_MATRIX_TOTAL] += (endtime - starttime);
    2694:     ctx->times[LANDAU_JACOBIAN_COUNT] += 1;
    2695:   }
    2696: #endif
    2697:   PetscCall(PetscLogEventEnd(ctx->events[0], 0, 0, 0, 0));
    2698:   PetscCall(PetscLogEventEnd(ctx->events[11], 0, 0, 0, 0));
    2699:   if (ctx->stage) PetscCall(PetscLogStagePop());
    2700:   PetscFunctionReturn(PETSC_SUCCESS);
    2701: }

    2703: /*@
    2704:   DMPlexLandauIJacobian - `TS` Jacobian construction, confusingly this adds mass

    2706:   Collective

    2708:   Input Parameters:
    2709: + ts         - The time stepping context
    2710: . time_dummy - current time (not used)
    2711: . X          - Current state
    2712: . U_tdummy   - Time derivative of current state (not used)
    2713: . shift      - shift for du/dt term
    2714: - actx       - Landau context

    2716:   Output Parameters:
    2717: + Amat - Jacobian
    2718: - Pmat - same as Amat

    2720:   Level: beginner

    2722: .seealso: `DMPlexLandauCreateVelocitySpace()`, `DMPlexLandauIFunction()`
    2723:  @*/
    2724: PetscErrorCode DMPlexLandauIJacobian(TS ts, PetscReal time_dummy, Vec X, Vec U_tdummy, PetscReal shift, Mat Amat, Mat Pmat, void *actx)
    2725: {
    2726:   LandauCtx *ctx = NULL;
    2727:   PetscInt   dim;
    2728:   DM         pack;
    2729: #if defined(PETSC_HAVE_THREADSAFETY)
    2730:   double starttime, endtime;
    2731: #endif
    2732:   PetscObjectState state;

    2734:   PetscFunctionBegin;
    2735:   PetscCall(TSGetDM(ts, &pack));
    2736:   PetscCall(DMGetApplicationContext(pack, &ctx));
    2737:   PetscCheck(ctx, PETSC_COMM_SELF, PETSC_ERR_PLIB, "no context");
    2738:   PetscCheck(Amat == Pmat && Amat == ctx->J, ctx->comm, PETSC_ERR_PLIB, "Amat!=Pmat || Amat!=ctx->J");
    2739:   PetscCall(DMGetDimension(pack, &dim));
    2740:   /* get collision Jacobian into A */
    2741:   if (ctx->stage) PetscCall(PetscLogStagePush(ctx->stage));
    2742:   PetscCall(PetscLogEventBegin(ctx->events[11], 0, 0, 0, 0));
    2743:   PetscCall(PetscLogEventBegin(ctx->events[9], 0, 0, 0, 0));
    2744: #if defined(PETSC_HAVE_THREADSAFETY)
    2745:   starttime = MPI_Wtime();
    2746: #endif
    2747:   PetscCheck(shift != 0.0, ctx->comm, PETSC_ERR_PLIB, "zero shift");
    2748:   PetscCall(PetscObjectStateGet((PetscObject)ctx->J, &state));
    2749:   PetscCheck(state == ctx->norm_state, ctx->comm, PETSC_ERR_PLIB, "wrong state, %" PetscInt64_FMT " %" PetscInt64_FMT, ctx->norm_state, state);
    2750:   if (!ctx->use_matrix_mass) {
    2751:     PetscCall(LandauFormJacobian_Internal(X, ctx->J, dim, shift, (void *)ctx));
    2752:   } else { /* add mass */
    2753:     PetscCall(MatAXPY(Pmat, shift, ctx->M, SAME_NONZERO_PATTERN));
    2754:   }
    2755: #if defined(PETSC_HAVE_THREADSAFETY)
    2756:   if (ctx->stage) {
    2757:     endtime = MPI_Wtime();
    2758:     ctx->times[LANDAU_OPERATOR] += (endtime - starttime);
    2759:     ctx->times[LANDAU_MASS] += (endtime - starttime);
    2760:     ctx->times[LANDAU_MATRIX_TOTAL] += (endtime - starttime);
    2761:   }
    2762: #endif
    2763:   PetscCall(PetscLogEventEnd(ctx->events[9], 0, 0, 0, 0));
    2764:   PetscCall(PetscLogEventEnd(ctx->events[11], 0, 0, 0, 0));
    2765:   if (ctx->stage) PetscCall(PetscLogStagePop());
    2766:   PetscFunctionReturn(PETSC_SUCCESS);
    2767: }