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