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