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