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