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