chombo-discharge
Loading...
Searching...
No Matches
CD_ItoKMCGodunovStepperImplem.H
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2021-2026 SINTEF Energy Research
3 *
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 */
6
12
13#ifndef CD_ITOKMCGODUNOVSTEPPERIMPLEM_H
14#define CD_ITOKMCGODUNOVSTEPPERIMPLEM_H
15
16// Chombo includes
17#include <ParmParse.H>
18
19// Our includes
21#include <CD_Timer.H>
22#include <CD_ParallelOps.H>
23#include <CD_DataOps.H>
24#include <CD_ParticleLoops.H>
25#include <CD_ParticleOps.H>
26#include <CD_Units.H>
27#include <CD_Photon.H>
28#include <CD_DischargeIO.H>
29#include <CD_NamespaceHeader.H>
30
31using namespace Physics::ItoKMC;
32
33namespace {
34// Deposit an SoA point-particle container's weight onto a_phi through the Ito solver's own deposition routine, so
35// that the point particles land on the mesh in the same normalization as the solver's own particles. Going through
36// the solver -- rather than calling AmrMesh::depositWeight directly -- is what picks up the solver's cut-cell
37// deposition flag and its redistribution, and what guarantees the realm and phase are the solver's own.
38//
39// No coarsenAndFillGhosts() here: every caller sums these deposits into rho or the cell conductivity and then
40// coarsens and fills ghost cells on that sum, so doing it per species would only produce values that are
41// immediately overwritten.
42inline void
43depositPointParticlesLikeSolver(const RefCountedPtr<ItoSolver>& a_solver,
44 EBAMRCellData& a_phi,
45 const ParticleContainer<NoPayload>& a_particles) noexcept
46{
47 a_solver->depositWeight(a_phi, a_particles, a_solver->getDeposition(), a_solver->getCoarseFineDeposition());
48}
49
50} // namespace
51
52template <typename I, typename C, typename R, typename F>
53ItoKMCGodunovStepper<I, C, R, F>::ItoKMCGodunovStepper(RefCountedPtr<ItoKMCPhysics>& a_physics, bool a_parseOptions)
54 : ItoKMCStepper<I, C, R, F>(a_physics)
55{
56 CH_TIME("ItoKMCGodunovStepper::ItoKMCGodunovStepper");
58 this->m_name = "ItoKMCGodunovStepper";
59 this->m_prevDt = 0.0;
60 this->m_writeCheckpointParticles = false;
61 this->m_readCheckpointParticles = false;
62 this->m_extendConductivityEB = false;
64 this->m_rhoDaggerHop = true;
66 this->m_prevDt = 0.0;
67 this->m_maxFieldAbort = std::numeric_limits<Real>::max();
68
69 if (a_parseOptions) {
70 this->parseOptions();
71 }
72}
73
74template <typename I, typename C, typename R, typename F>
76{
77 CH_TIME("ItoKMCGodunovStepper::~ItoKMCGodunovStepper");
78 if (this->m_verbosity > 5) {
79 pout() << "ItoKMCGodunovStepper::~ItoKMCGodunovStepper" << endl;
80 }
81}
82
83template <typename I, typename C, typename R, typename F>
84void
86{
87 CH_TIME("ItoKMCGodunovStepper::registerOperators");
88 if (this->m_verbosity > 5) {
89 pout() << "ItoKMCGodunovStepper::registerOperators" << endl;
90 }
91
94 // Register this because we must be able to deposit particles inside dielectrics (due to particle diffusion across the
95 // EB).
96 (this->m_amr)->registerOperator(s_particle_mesh, this->m_particleRealm, phase::solid);
97}
98
99template <typename I, typename C, typename R, typename F>
100void
102{
103 CH_TIME("ItoKMCGodunovStepper::allocate");
104 if (this->m_verbosity > 5) {
105 pout() << "ItoKMCGodunovStepper::allocate" << endl;
106 }
107
109
110 // Now allocate for the conductivity particles and rho^dagger particles. This is only done in the 'allocate' routine
111 // and not in 'allocateInternals' because that would discard the particles during regrids. That has definitely never
112 // happen, and there's no way I've spent countless hours tracking down such a bug.
113 const int numItoSpecies = this->m_physics->getNumItoSpecies();
114
115 m_conductivityParticles.resize(numItoSpecies);
116 m_irregularParticles.resize(numItoSpecies);
117 m_rhoDaggerParticles.resize(numItoSpecies);
118
119 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
120 const int idx = solverIt.index();
121
122 m_conductivityParticles[idx] = RefCountedPtr<ParticleContainer<NoPayload>>(new ParticleContainer<NoPayload>());
123 m_irregularParticles[idx] = RefCountedPtr<ParticleContainer<NoPayload>>(new ParticleContainer<NoPayload>());
124 m_rhoDaggerParticles[idx] = RefCountedPtr<ParticleContainer<NoPayload>>(new ParticleContainer<NoPayload>());
125
127 (this->m_amr)->allocate(*m_irregularParticles[idx], this->m_particleRealm);
128 (this->m_amr)->allocate(*m_rhoDaggerParticles[idx], this->m_particleRealm);
129 }
130}
131
132template <typename I, typename C, typename R, typename F>
133void
135{
136 CH_TIME("ItoKMCGodunovStepper::allocateInternals");
137 if (this->m_verbosity > 5) {
138 pout() << this->m_name + "::allocateInternals" << endl;
139 }
140
142
143 const int numCdrSpecies = this->m_physics->getNumCdrSpecies();
144
145 m_cdrDivD.resize(numCdrSpecies);
146 for (int i = 0; i < numCdrSpecies; i++) {
147 this->m_amr->allocate(m_cdrDivD[i], this->m_fluidRealm, this->m_plasmaPhase, 1);
148 }
149
150 this->m_amr->allocate(m_semiImplicitRhoCDR, this->m_fluidRealm, this->m_plasmaPhase, 1);
151 this->m_amr->allocate(m_semiImplicitConductivityCDR, this->m_fluidRealm, this->m_plasmaPhase, 1);
152
153 // AmrMesh::allocate does not initialize. Both fields are consumed by regrid(), which may run before an
154 // advance has filled them, so give them a defined value here. Later regrids overwrite them through
155 // interpToNewGrids.
158
159 // Holds the field the chemistry is evaluated at. This one needs no initialization -- advance() overwrites
160 // it from m_electricFieldFluid before anything reads it, and nothing else consumes it.
161 this->m_amr->allocate(m_reactiveElectricField, this->m_fluidRealm, this->m_plasmaPhase, SpaceDim);
162
163 // Accumulator for the per-species charge-weighted sums, so the cross-realm copy runs once rather than
164 // once per species. Zeroed by its users before they accumulate into it.
165 this->m_amr->allocate(m_particleScratchSum, this->m_particleRealm, this->m_plasmaPhase, 1);
166
167 // Solid-phase buffers for the space charge that gas-side particles carried into the dielectrics. These
168 // exist only when there is a dielectric to carry charge into; computeSemiImplicitRho() asks the same
169 // question before it touches them, and used to allocate them on every time step.
170 const RefCountedPtr<MultiFluidIndexSpace>& mfis = (this->m_computationalGeometry)->getMfIndexSpace();
171 const Vector<Dielectric>& dielectrics = (this->m_computationalGeometry)->getDielectrics();
172
173 if ((mfis->numPhases() > 1) && (dielectrics.size() > 0)) {
174 this->m_amr->allocate(m_particleScratchSolid, this->m_particleRealm, phase::solid, 1);
176 this->m_amr->allocate(m_fluidScratchSolid, this->m_fluidRealm, phase::solid, 1);
177 }
178}
179
180template <typename I, typename C, typename R, typename F>
181void
183{
184 CH_TIME("ItoKMCGodunovStepper::barrier");
185 if (this->m_verbosity > 5) {
186 pout() << this->m_name + "::barrier" << endl;
187 }
188
189 if ((this->m_profile)) {
191 }
192}
193
194template <typename I, typename C, typename R, typename F>
195void
197{
198 CH_TIME("ItoKMCGodunovStepper::parseOptions");
199 if (this->m_verbosity > 5) {
200 pout() << this->m_name + "::parseOptions" << endl;
201 }
202
204
205 this->parseAlgorithm();
206 this->parseFiltering();
209 this->parseDiffusiveDeposit();
210 this->parseRhoDaggerHop();
212}
213
214template <typename I, typename C, typename R, typename F>
215void
217{
218 CH_TIME("ItoKMCGodunovStepper::parseRuntimeOptions");
219 if (this->m_verbosity > 5) {
220 pout() << this->m_name + "::parseRuntimeOptions" << endl;
221 }
222
224
225 this->parseAlgorithm();
226 this->parseFiltering();
229 this->parseDiffusiveDeposit();
230 this->parseRhoDaggerHop();
232}
233
234template <typename I, typename C, typename R, typename F>
235void
237{
238 CH_TIME("ItoKMCGodunovStepper::parseAlgorithm");
239 if (this->m_verbosity > 5) {
240 pout() << this->m_name + "::parseAlgorithm" << endl;
241 }
242
243 ParmParse pp(this->m_name.c_str());
244 std::string str;
245
246 pp.get("extend_conductivity", m_extendConductivityEB);
247 pp.get("algorithm", str);
248 pp.get("abort_max_field", m_maxFieldAbort);
249
250 // Get algorithm
251 if (str == "euler_maruyama") {
252 m_algorithm = WhichAlgorithm::EulerMaruyama;
253 }
254 else {
255 MayDay::Abort("ItoKMCGodunovStepper::parseAlgorithm - unknown algorithm requested");
256 }
257}
258
259template <typename I, typename C, typename R, typename F>
260void
262{
263 CH_TIME("ItoKMCGodunovStepper::parseFiltering");
264 if (this->m_verbosity > 5) {
265 pout() << this->m_name + "::parseFiltering" << endl;
266 }
267
268 ParmParse pp(this->m_name.c_str());
269 std::string str;
270
271 m_rhoFilterNum = -1;
273 m_rhoFilterAlpha = 0.5;
274
275 m_condFilterNum = -1;
277 m_condFilterAlpha = 0.5;
278
279 pp.get("rho_filter_num", m_rhoFilterNum);
280 pp.get("rho_filter_max_stride", m_rhoFilterMaxStride);
281 pp.get("rho_filter_alpha", m_rhoFilterAlpha);
282
283 pp.get("cond_filter_num", m_condFilterNum);
284 pp.get("cond_filter_max_stride", m_condFilterMaxStride);
285 pp.get("cond_filter_alpha", m_condFilterAlpha);
286
287 if (m_rhoFilterAlpha <= 0.0 || m_rhoFilterAlpha >= 1.0) {
288 MayDay::Abort("ItoKMCGodunovStepper::parseFiltering -- cannot have alpha <= 0 or alpha >= 1 for rho_filter");
289 }
290 if (m_condFilterAlpha <= 0.0 || m_condFilterAlpha >= 1.0) {
291 MayDay::Abort("ItoKMCGodunovStepper::parseFiltering -- cannot have alpha <= 0 or alpha >= 1 for cond_filter");
292 }
293}
294
295template <typename I, typename C, typename R, typename F>
296void
298{
299 CH_TIME("ItoKMCGodunovStepper::parseCheckpointParticles");
300 if (this->m_verbosity > 5) {
301 pout() << this->m_name + "::parseCheckpointParticles" << endl;
302 }
303
304 ParmParse pp(this->m_name.c_str());
305
306 pp.query("checkpoint_particles", m_writeCheckpointParticles);
307}
308
309template <typename I, typename C, typename R, typename F>
310void
312{
313 CH_TIME("ItoKMCGodunovStepper::parseSecondaryEmissionSpecifiation");
314 if (this->m_verbosity > 5) {
315 pout() << this->m_name + "::parseSecondaryEmissionSpecification" << endl;
316 }
317
318 ParmParse pp(this->m_name.c_str());
319
320 std::string str;
321
322 pp.query("secondary_emission", str);
323
324 if (str == "before_reactions") {
326 }
327 else if (str == "after_reactions") {
329 }
330 else {
331 std::string err;
332
333 err = "ItoKMCGodunovStepper::parseSecondaryEmissionSpecification - expected 'before_reactions' or 'after_reactions'";
334 err += "but got" + str;
335
336 MayDay::Abort(err.c_str());
337 }
338}
339
340template <typename I, typename C, typename R, typename F>
341RealVect
343 const RealVect& a_disp,
344 const Real a_fOld,
345 const Real a_dx,
346 const EBIntersection a_intersectionAlg,
347 const Real a_bisectStep) const noexcept
348{
349 // One reflection places the particle in the fluid unless the surface curves back on it, so the second attempt is
350 // for concave corners and thin features. There is no third: the fallback is always available and always safe.
351 constexpr int numAttempts = 2;
352
353 // Ray-cast collision tolerance, relative to dx. Same value the solvers use for their own intersection tests.
354 constexpr Real raycastTolerance = 1.E-3;
355
356 const RefCountedPtr<BaseIF>& baseif = (this->m_amr)->getBaseImplicitFunction(this->m_plasmaPhase);
357
358 // Which sign of the implicit function is the fluid, taken from a position known to be in it. Nothing here assumes
359 // which side the implicit function calls positive.
360 const Real fluidSign = (a_fOld > 0.0) ? 1.0 : -1.0;
361 const Real h = 1.E-2 * a_dx;
362
363 const auto inFluid = [&](const RealVect& a_x) -> bool {
364 return fluidSign * baseif->value(a_x) > 0.0;
365 };
366
367 // The crossing point along [a_pos, a_end], located with whichever algorithm the owning solver was configured with
368 // so that reflection and the absorption test later in the advance agree on where the surface is.
369 const auto findCrossing = [&](const RealVect& a_end, Real& a_s) -> bool {
370 switch (a_intersectionAlg) {
371 case EBIntersection::Bisection: {
372 return ParticleOps::ebIntersectionBisect(baseif, a_pos, a_end, a_bisectStep, a_s);
373 }
374 case EBIntersection::Raycast: {
375 return ParticleOps::ebIntersectionRaycast(baseif, a_pos, a_end, raycastTolerance * a_dx, a_s);
376 }
377 default: {
378 MayDay::Abort("ItoKMCGodunovStepper::reflectDiffusionHop - unsupported EB intersection requested");
379
380 return false;
381 }
382 }
383 };
384
385 RealVect end = a_pos + a_disp;
386
387 for (int attempt = 0; attempt < numAttempts; attempt++) {
388 Real s = std::numeric_limits<Real>::max();
389
390 // Always bracketed from a_pos rather than from the previous crossing point. a_pos is in the fluid and the current
391 // end is not, so the bracket is valid on every attempt, and no search is started from a point on the surface --
392 // where both intersection routines would report a crossing at zero path length and reflect about it forever.
393 if (!findCrossing(end, s)) {
394
395 // No crossing on the segment. Either the reflected point is reachable without one, or the routine could not
396 // resolve the feature that put it inside; the implicit function decides which.
397 return inFluid(end) ? (end - a_pos) : RealVect::Zero;
398 }
399
400 const RealVect cross = a_pos + s * (end - a_pos);
401
402 // Surface normal from the gradient of the implicit function at the crossing point.
403 RealVect grad = RealVect::Zero;
404
405 for (int dir = 0; dir < SpaceDim; dir++) {
406 RealVect lo = cross;
407 RealVect hi = cross;
408
409 lo[dir] -= h;
410 hi[dir] += h;
411
412 grad[dir] = (baseif->value(hi) - baseif->value(lo)) / (2.0 * h);
413 }
414
415 const Real gradLen = grad.vectorLength();
416
417 if (gradLen <= 0.0) {
418 return RealVect::Zero;
419 }
420
421 const RealVect n = grad / gradLen;
422
423 // Mirror the part of the path that lies beyond the surface back across it, so a point that would have landed at
424 // depth d inside comes to rest at depth d outside.
425 const RealVect overshoot = end - cross;
426
427 end = cross + overshoot - 2.0 * overshoot.dotProduct(n) * n;
428
429 if (inFluid(end)) {
430 return end - a_pos;
431 }
432 }
433
434 return RealVect::Zero;
435}
436
437template <typename I, typename C, typename R, typename F>
438void
440{
441 CH_TIME("ItoKMCGodunovStepper::parseDiffusiveDeposit");
442 if (this->m_verbosity > 5) {
443 pout() << this->m_name + "::parseDiffusiveDeposit" << endl;
444 }
445
446 ParmParse pp(this->m_name.c_str());
448 std::string str;
449
450 pp.get("diffusive_deposit", str);
451
452 if (str == "inside") {
453 m_diffusiveDeposit = DiffusiveDeposit::Inside;
454 }
455 else if (str == "cancel") {
456 m_diffusiveDeposit = DiffusiveDeposit::Cancel;
457 }
458 else if (str == "reflect_rho") {
459 m_diffusiveDeposit = DiffusiveDeposit::ReflectRho;
460 }
461 else if (str == "reflect_ito") {
462 m_diffusiveDeposit = DiffusiveDeposit::ReflectIto;
463 }
464 else {
465 const std::string err = "ItoKMCGodunovStepper::parseDiffusiveDeposit - expected 'inside', 'cancel', "
466 "'reflect_rho' or 'reflect_ito' but got '" +
467 str + "'";
468
469 MayDay::Abort(err.c_str());
470 }
471}
473template <typename I, typename C, typename R, typename F>
474void
476{
477 CH_TIME("ItoKMCGodunovStepper::parseRhoDaggerHop");
478 if (this->m_verbosity > 5) {
479 pout() << this->m_name + "::parseRhoDaggerHop" << endl;
480 }
482 ParmParse pp(this->m_name.c_str());
483
484 pp.get("rho_dagger_hop", m_rhoDaggerHop);
485}
486
487template <typename I, typename C, typename R, typename F>
488void
490{
491 CH_TIME("ItoKMCGodunovStepper::parseReactiveFieldCentering");
492 if (this->m_verbosity > 5) {
493 pout() << this->m_name + "::parseReactiveFieldCentering" << endl;
494 }
495
496 ParmParse pp(this->m_name.c_str());
497
498 pp.get("reactive_E_centering", m_reactiveFieldCentering);
499
500 // Anything outside [0,1] extrapolates past the two fields that were actually solved for, which has no
501 // physical justification.
502 if (m_reactiveFieldCentering < 0.0 || m_reactiveFieldCentering > 1.0) {
503 MayDay::Abort("ItoKMCGodunovStepper::parseReactiveFieldCentering -- 'reactive_E_centering' must lie in [0,1]");
504 }
505}
506
507template <typename I, typename C, typename R, typename F>
508Real
510{
511 CH_TIME("ItoKMCGodunovStepper::computeDt");
512 if (this->m_verbosity > 5) {
513 pout() << this->m_name + "::computeDt" << endl;
515
517
518 if ((this->m_maxReducedField > m_maxFieldAbort) && (m_maxFieldAbort > 0.0)) {
519 pout() << this->m_name + " stopping because maximum field is too high (" << this->m_maxReducedField << ")" << endl;
520
521 this->m_keepGoing = false;
522 }
523
524 return dt;
526
527template <typename I, typename C, typename R, typename F>
528Real
530{
531 CH_TIME("ItoKMCGodunovStepper::advance");
532 if (this->m_verbosity > 5) {
533 pout() << this->m_name + "::advance" << endl;
534 }
535
536 // Special flag for telling the class that we have the necessary things in place for doing a regrid. This is
537 // an if-but-maybe situation where the user chose not to checkpoint the particles we need for regrids, yet tries
538 // to restart a simulation and regrid without all the prerequisites being in place. This flag is set to true
539 // because these requirements are checked during the regrid routine.
541
542 m_timer = Timer("ItoKMCGodunovStepper::advance");
543
544 // Previous time step is needed when regridding.
545 this->m_prevDt = a_dt;
547 // Store E^k -- the field the step starts from. The chemistry is later evaluated at an interpolant between
548 // this field and the one that comes out of the semi-implicit transport step. At theta == 1 that interpolant
549 // is E^(k+1) alone, so the buffer would only ever hold a copy that the blend below overwrites in full;
550 // advanceReactionNetwork is handed m_electricFieldFluid directly in that case and this is skipped.
551 m_timer.startEvent("Store E^k");
554 }
555 m_timer.stopEvent("Store E^k");
556
557 // ====== BEGIN TRANSPORT STEP ======
558 // Semi-implicitly advance the particles and the field.
559 switch (m_algorithm) {
560 case WhichAlgorithm::EulerMaruyama: {
561 this->advanceEulerMaruyama(a_dt);
562
563 break;
564 }
565 default: {
566 MayDay::Abort("ItoKMCGodunovStepper::advance - logic bust");
567
568 break;
569 }
570 }
571
572 // Do intersection test and remove particles that struck the EB or domain. Transfer them to appropriate containers.
573 // Then recompute the number of particles per cell.
574 this->barrier();
575 m_timer.startEvent("EB/Particle intersection");
576 if (m_extendConductivityEB) {
578 // clang-format off
579 // TLDR: This hook does a special intersection routine where instead of transferring the particles that were intersected, they
580 // are put in a separate data container. We want to do this in order to reduce artificial gradients in the particle
581 // densities near the EB. The way we do this is that we flag the particles during the intersection; particles that are flagged
582 // are transferred to a container which is added to the conductivity-related particles. The particles are later removed.
583 // clang-format on
584 const std::function<void(ParticleSoA<ItoParticle>&, std::size_t)> setFlag = [](ParticleSoA<ItoParticle>& leaf,
585 const std::size_t i) -> void {
586 leaf.template get<&ItoParticle::scratch>(i) = 1.0;
587 };
588 const std::function<void(ParticleSoA<ItoParticle>&, std::size_t)> nonDeletionModifier =
589 [](ParticleSoA<ItoParticle>& leaf, const std::size_t i) -> void {
590 leaf.template get<&ItoParticle::scratch>(i) = -1.0;
591 };
592
593 // Set flag for identifying which particles were intersected by not removed. Only the subset that the
594 // intersection below runs over can ever be flagged, so a stationary species' population is not walked
595 // here -- nor in the deletion sweep at the end of this block, which uses the same subset.
596 for (auto it = this->m_ito->iterator(); it.ok(); ++it) {
597 const RefCountedPtr<ItoSolver>& solver = it();
598
599 if (solver->isMobile() || solver->isDiffusive()) {
600 ParticleOps::setData(solver->getParticles(ItoSolver::WhichContainer::Bulk), setFlag);
601 }
602 }
603
604 // Intersect particles, but don't remove them. The particles were not remapped after the Euler-Maruyama step
605 // -- a remap drops every particle that left the domain -- so that the intersection test can put the ones
606 // that crossed the domain boundary in the domain containers. Remap the rest now.
607 const bool deleteParticles = false;
608 this->intersectParticles(SpeciesSubset::AllMobileOrDiffusive, deleteParticles, nonDeletionModifier);
610
611 // Particles that were not removed are copied to a separate data container.
612 for (auto it = this->m_ito->iterator(); it.ok(); ++it) {
613 const RefCountedPtr<ItoSolver>& solver = it();
614 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
615
616 const int idx = it.index();
617 const int Z = species->getChargeNumber();
618
620 ParticleContainer<ItoParticle>& ebParticles = solver->getParticles(ItoSolver::WhichContainer::EB);
621 ParticleContainer<ItoParticle>& bulkParticles = it()->getParticles(ItoSolver::WhichContainer::Bulk);
622
623 irregParticles.clearParticles();
624
625 if (Z != 0 && solver->isMobile()) {
626 for (int lvl = 0; lvl <= (this->m_amr)->getFinestLevel(); lvl++) {
627 const DisjointBoxLayout& dbl = (this->m_amr)->getGrids((this->m_particleRealm))[lvl];
628 const DataIterator& dit = dbl.dataIterator();
629
630 const int nbox = dit.size();
632#pragma omp parallel for schedule(runtime)
633 for (int mybox = 0; mybox < nbox; mybox++) {
634 const DataIndex& din = dit[mybox];
635
636 ParticleSoA<NoPayload>& pointParticles = irregParticles[lvl][din];
637 const ParticleSoA<ItoParticle>& leaf = bulkParticles[lvl][din];
638
639 for (std::size_t i = 0; i < leaf.size(); i++) {
640 if (leaf.template get<&ItoParticle::scratch>(i) < 0.0) {
641 const RealVect pos = leaf.position(i);
642 const Real weight = leaf.weight(i);
643 const Real mobility = leaf.template get<&ItoParticle::mobility>(i);
644
645 pointParticles.append(pos, weight * mobility);
646 }
647 }
648 }
649 }
650 }
651 }
652
653 // Finally, delete the original particles that were flagged (scratch < 0) via swap-and-pop on the SoA leaves.
654 for (auto it = this->m_ito->iterator(); it.ok(); ++it) {
655 const RefCountedPtr<ItoSolver>& solver = it();
656
657 if (!(solver->isMobile() || solver->isDiffusive())) {
658 continue;
659 }
660
661 ParticleContainer<ItoParticle>& bulkParticles = solver->getParticles(ItoSolver::WhichContainer::Bulk);
662
663 for (int lvl = 0; lvl <= (this->m_amr)->getFinestLevel(); lvl++) {
664 const DisjointBoxLayout& dbl = (this->m_amr)->getGrids((this->m_particleRealm))[lvl];
665 const DataIterator& dit = dbl.dataIterator();
666
667 const int nbox = dit.size();
668
669#pragma omp parallel for schedule(runtime)
670 for (int mybox = 0; mybox < nbox; mybox++) {
671 const DataIndex& din = dit[mybox];
672
673 ParticleSoA<ItoParticle>& leaf = bulkParticles[lvl][din];
674
675 std::size_t i = 0;
676 while (i < leaf.size()) {
677 if (leaf.template get<&ItoParticle::scratch>(i) < 0.0) {
678 leaf.remove(i);
679 }
680 else {
681 i++;
682 }
683 }
684 }
685 }
686 }
687 }
688 else {
689 const bool deleteParticles = true;
690
691 // See above for why the remap comes after the intersection test.
692 this->intersectParticles(SpeciesSubset::AllMobileOrDiffusive, deleteParticles);
693 this->remapParticles(SpeciesSubset::AllMobileOrDiffusive);
694 }
695
696 // The intersection tests above may not have caught all particles -- do a cleanup sweep where particles on the wrong
697 // side of the EB are put on the EB.
698 //
699 // Deliberately over every species, not just the ones that moved: the chemistry draws new particles at
700 // random positions within a cell, so a stationary species can acquire a particle on the solid side of a
701 // cut cell without ever taking a step. This sweep is the only thing that catches those -- the covered-cell
702 // removal below runs on AllMobileOrDiffusive.
703 for (auto it = this->m_ito->iterator(); it.ok(); ++it) {
704 const RefCountedPtr<ItoSolver>& solver = it();
705
706 ParticleContainer<ItoParticle>& ebParticles = solver->getParticles(ItoSolver::WhichContainer::EB);
707 ParticleContainer<ItoParticle>& bulkParticles = solver->getParticles(ItoSolver::WhichContainer::Bulk);
708
709 this->m_amr->transferIrregularParticles(ebParticles, bulkParticles, this->m_plasmaPhase);
710 }
711 m_timer.stopEvent("EB/Particle intersection");
712 // ====== END TRANSPORT STEP ======
713
714 // Photon transport
715 this->barrier();
716 m_timer.startEvent("Photon transport");
717 this->advancePhotons(a_dt);
718 m_timer.stopEvent("Photon transport");
719
720 // Compute the gradients of the various species densities - this is used in the KMC kernels.
721 if ((this->m_physics)->needGradients()) {
722 m_timer.startEvent("Gradient calculation");
723
724 // Only the species computeDensityGradients() actually differentiates. It skips the rest and zeroes
725 // their gradient slots, so depositing them here bought nothing but a halo deposit, a redistribution and
726 // a coarsen-and-fill-ghosts apiece -- and a chemistry typically corrects on one or two species out of
727 // the set. The mesh densities of the skipped species are stale until prePlot() re-deposits all of them,
728 // which is ahead of every reader that wants them current.
729 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
730 if ((this->m_physics)->needGradient(solverIt.index())) {
731 solverIt()->depositParticles();
732 }
733 }
734
735 this->computeDensityGradients();
736 m_timer.stopEvent("Gradient calculation");
737 }
738
739 // Resolve secondary emission. We have filled the relevant particles in the transport step -- this can be done
740 // either before or after the reactions.
741 if (m_emitSecondaryParticlesBeforeReactions) {
742 this->barrier();
743 m_timer.startEvent("EB particle injection");
744 if (this->needSecondaryEmissionEB()) {
745 this->fillSecondaryEmissionEB(a_dt);
746 this->resolveSecondaryEmissionEB(a_dt);
747 }
748 m_timer.stopEvent("EB particle injection");
749
750 m_timer.startEvent("Domain particle injection");
751 if (this->needSecondaryEmissionDomain()) {
752 this->fillSecondaryEmissionDomain(a_dt);
753 this->resolveSecondaryEmissionDomain();
754 }
755 m_timer.stopEvent("Domain particle injection");
756 }
757
758 // Sort the particles and photons per cell so we can call reaction algorithms
759 this->barrier();
760 m_timer.startEvent("Sort by cell");
761 (this->m_ito)->organizeParticlesByCell(ItoSolver::WhichContainer::Bulk);
762 this->sortPhotonsByCell(McPhoto::WhichContainer::Bulk);
763 this->sortPhotonsByCell(McPhoto::WhichContainer::Source);
764 m_timer.stopEvent("Sort by cell");
765
766 // Run the Kinetic Monte Carlo reaction kernels. These are evaluated at (1-theta)*E^k + theta*E^(k+1) rather
767 // than at the end-of-step field: in the semi-implicit formulation E^(k+1) is the already-screened field, so
768 // evaluating the whole reactive substep there biases the rate coefficients low wherever the plasma screens
769 // the field. m_reactiveElectricField holds E^k, and m_electricFieldFluid holds E^(k+1) at this point.
770 //
771 // NOTE: This centering applies to the reactions only. The drift update must keep using E^(k+1) with the
772 // lagged mobility mu^k because that is the pairing the semi-implicit Poisson operator was built for.
773 this->barrier();
774 m_timer.startEvent("Reaction network");
775 if (m_reactiveFieldCentering >= 1.0) {
776 // Pure E^(k+1). m_reactiveElectricField was never filled -- see "Store E^k" above.
777 this->advanceReactionNetwork(this->m_electricFieldFluid, a_dt);
778 }
779 else {
780 // Pure E^k needs no blending; m_reactiveElectricField already holds it.
781 if (m_reactiveFieldCentering > 0.0) {
782 DataOps::scale(m_reactiveElectricField, 1.0 - m_reactiveFieldCentering);
783 DataOps::incr(m_reactiveElectricField, this->m_electricFieldFluid, m_reactiveFieldCentering);
784 }
785
786 this->advanceReactionNetwork(m_reactiveElectricField, a_dt);
787 }
788 m_timer.stopEvent("Reaction network");
789
790 // Merge super-particles down to the target after the chemistry advance created/removed particles.
791 // Routed through the public ItoSolver::makeSuperparticles() so both per-cell and AMR-wide
792 // (nn_amr, any nn_search backend) merge algorithms run, chosen by ItoSolver.merge_method.
793 // makeSuperparticles() cell-sorts internally as needed and returns the container patch-organized.
794 this->barrier();
795 m_timer.startEvent("Make superparticles");
796 if (this->m_mergeInterval > 0 && (this->m_timeStep + 1) % this->m_mergeInterval == 0) {
797 (this->m_ito)->makeSuperparticles(ItoSolver::WhichContainer::Bulk);
798 }
799 m_timer.stopEvent("Make superparticles");
800
801 // Sort particles per patch.
802 this->barrier();
803 m_timer.startEvent("Sort by patch");
804 (this->m_ito)->organizeParticlesByPatch(ItoSolver::WhichContainer::Bulk);
805 this->sortPhotonsByPatch(McPhoto::WhichContainer::Bulk);
806 this->sortPhotonsByPatch(McPhoto::WhichContainer::Source);
807 m_timer.stopEvent("Sort by patch");
808
809 // Resolve secondary emission. We have filled the relevant particles in the transport step -- this can be done
810 // either before or after the reactions.
811 if (!m_emitSecondaryParticlesBeforeReactions) {
812 this->barrier();
813 m_timer.startEvent("EB particle injection");
814 if (this->needSecondaryEmissionEB()) {
815 this->fillSecondaryEmissionEB(a_dt);
816 this->resolveSecondaryEmissionEB(a_dt);
817 }
818 m_timer.stopEvent("EB particle injection");
819
820 m_timer.startEvent("Domain particle injection");
821 if (this->needSecondaryEmissionDomain()) {
822 this->fillSecondaryEmissionDomain(a_dt);
823 this->resolveSecondaryEmissionDomain();
824 }
825 m_timer.stopEvent("Domain particle injection");
826 }
827
828 // Remove particles that are inside the EB -- this is not a part of the algorithm, just a safety measure to make sure
829 // we don't do things with particles that lie inside the EB.
830 this->barrier();
831 m_timer.startEvent("Remove covered");
832 this->removeCoveredParticles(SpeciesSubset::AllMobileOrDiffusive, EBRepresentation::Discrete, this->m_toleranceEB);
833 m_timer.stopEvent("Remove covered");
834
835 // Clear BC data holders.
836 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
837 solverIt()->clear(ItoSolver::WhichContainer::EB);
838 solverIt()->clear(ItoSolver::WhichContainer::Domain);
839 }
840
841 // Prepare for the next time step. This is computeDriftVelocities() minus setItoVelocityFunctions():
842 // that call rebuilds the mesh field sgn(Z)*E from m_electricFieldParticle, and no Poisson solve has run
843 // since "Step-compute v" built exactly the same field from exactly the same E. interpolateVelocities()
844 // only reads it, so it is still valid; the particles moved, not the field.
845 //
846 // setCdrVelocityFunctions() is NOT redundant in the same way and is kept:
847 // multiplyCdrVelocitiesByMobilities() scales the CDR velocity in place, so the field has to be reset to
848 // sgn(Z)*E before each scaling or the mobility compounds across steps.
849 this->barrier();
850 m_timer.startEvent("Post-compute v");
851 this->setCdrVelocityFunctions();
852 this->computeMobilities();
853 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
854 solverIt()->interpolateVelocities();
855 }
856 this->multiplyCdrVelocitiesByMobilities();
857 m_timer.stopEvent("Post-compute v");
858
859 this->barrier();
860 m_timer.startEvent("Post-compute D");
861 this->computeDiffusionCoefficients();
862 m_timer.stopEvent("Post-compute D");
863
864 this->computePhysicsDt();
865
866 if ((this->m_profile)) {
867 m_timer.eventReport(pout(), false);
868 }
869
870 m_timer.clear();
871
872 // Compute the maximum field (in Townsend).
873 this->m_maxReducedField = this->computeMaxReducedElectricField(this->m_plasmaPhase);
874
875 return a_dt;
876}
877
878template <typename I, typename C, typename R, typename F>
879void
880ItoKMCGodunovStepper<I, C, R, F>::preRegrid(const int a_lmin, const int a_oldFinestLevel) noexcept
881{
882 CH_TIME("ItoKMCGodunovStepper::preRegrid");
883 if (this->m_verbosity > 5) {
884 pout() << "ItoKMCGodunovStepper::preRegrid" << endl;
885 }
886
887 const int numItoSpecies = (this->m_physics)->getNumItoSpecies();
888 const int numCdrSpecies = (this->m_physics)->getNumCdrSpecies();
889 const int numPlasmaSpecies = (this->m_physics)->getNumPlasmaSpecies();
890 const int numPhotonSpecies = (this->m_physics)->getNumPhotonSpecies();
891
892 ItoKMCStepper<I, C, R, F>::preRegrid(a_lmin, a_oldFinestLevel);
893
894 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
895 const int idx = solverIt.index();
896
897 m_conductivityParticles[idx]->preRegrid();
898 m_irregularParticles[idx]->preRegrid();
899 m_rhoDaggerParticles[idx]->preRegrid();
900 }
901
902 this->m_amr->allocate(m_scratchSemiImplicitRhoCDR, this->m_fluidRealm, this->m_plasmaPhase, 1);
904
907
908 // Release unnecessary storage.
909 for (int i = 0; i < numCdrSpecies; i++) {
910 m_cdrDivD[i].clear();
911 }
912
913 m_semiImplicitRhoCDR.clear();
915}
916
917template <typename I, typename C, typename R, typename F>
918void
920 const int a_oldFinestLevel,
921 const int a_newFinestLevel) noexcept
922{
923 CH_TIME("ItoKMCGodunovStepper::regrid");
924 if (this->m_verbosity > 5) {
925 pout() << "ItoKMCGodunovStepper::regrid" << endl;
926 }
927
928 m_timer = Timer("ItoKMCGodunovStepper::regrid");
929
930 // A special flag for aborting the simulation if the user did NOT put checkpoint particles in the checkpoint
931 // file but still try to regrid on restart.
933 const std::string baseErr = "ItoKMCGodunovStepper::regrid -- can't regrid because";
934 const std::string err1 = "checkpoint file does not contain particles. Set Driver.initial_regrids=0";
935
936 pout() << baseErr + err1 << endl;
937
938 MayDay::Error((baseErr + err1).c_str());
939 }
940
941 // Regrid solvers
942 m_timer.startEvent("Regrid ItoSolver");
943 (this->m_ito)->regrid(a_lmin, a_oldFinestLevel, a_newFinestLevel);
944 if (this->m_timeStep == 0) {
945 // Necessary because first time step is not semi-implicit, so it will use the densities from the
946 // Ito and CDr solvers. However, ItoSolver does not re-deposit the particles during regrid, so we
947 // enforce it here.
948 (this->m_ito)->depositParticles();
949 }
950 m_timer.stopEvent("Regrid ItoSolver");
951
952 m_timer.startEvent("Regrid CdrSolver");
953 (this->m_cdr)->regrid(a_lmin, a_oldFinestLevel, a_newFinestLevel);
954 m_timer.stopEvent("Regrid CdrSolver");
955
956 m_timer.startEvent("Regrid FieldSolver");
957 (this->m_fieldSolver)->regrid(a_lmin, a_oldFinestLevel, a_newFinestLevel);
958 m_timer.stopEvent("Regrid FieldSolver");
959
960 m_timer.startEvent("Regrid RTE");
961 (this->m_rte)->regrid(a_lmin, a_oldFinestLevel, a_newFinestLevel);
962 m_timer.stopEvent("Regrid RTE");
963
964 m_timer.startEvent("Regrid SurfaceODESolver");
965 this->m_sigmaSolver->regrid(a_lmin, a_oldFinestLevel, a_newFinestLevel);
966 m_timer.stopEvent("Regrid SurfaceODESolver");
967
968 // Allocate internal memory for ItoKMCGodunovStepper now....
969 m_timer.startEvent("Allocate internals");
970 this->allocateInternals();
971 m_timer.stopEvent("Allocate internals");
972
973 // We need to remap/regrid the stored data required for the semi-implicit update as well.
974 m_timer.startEvent("Remap algorithm-particles");
975 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
976 const int idx = solverIt.index();
977 (this->m_amr)->remapToNewGrids(*m_rhoDaggerParticles[idx], a_lmin, a_newFinestLevel);
978 (this->m_amr)->remapToNewGrids(*m_conductivityParticles[idx], a_lmin, a_newFinestLevel);
979 (this->m_amr)->remapToNewGrids(*m_irregularParticles[idx], a_lmin, a_newFinestLevel);
980 }
981 m_timer.stopEvent("Remap algorithm-particles");
982
983 // Also regrid the space charge density contribution from the CDR equations
984 this->m_amr->interpToNewGrids(m_semiImplicitRhoCDR,
986 this->m_plasmaPhase,
987 a_lmin,
988 a_oldFinestLevel,
989 a_newFinestLevel,
990 EBCoarseToFineInterp::Type::ConservativeMinMod);
991
992 this->m_amr->interpToNewGrids(m_semiImplicitConductivityCDR,
994 this->m_plasmaPhase,
995 a_lmin,
996 a_oldFinestLevel,
997 a_newFinestLevel,
998 EBCoarseToFineInterp::Type::ConservativeMinMod);
999
1000 // Set up the field solver with standard coefficients or with
1001 // modified coefficients if we are reusing data from the last time step.
1002 m_timer.startEvent("Setup field solver");
1003 (this->m_fieldSolver)->setupSolver();
1006 m_timer.stopEvent("Setup field solver");
1007
1008 // Solve the Poisson equation.
1009 m_timer.startEvent("Solve Poisson");
1010 if (this->m_timeStep == 0) {
1012 }
1013 else {
1015 this->computeSemiImplicitRho();
1016 }
1017
1018 const bool converged = this->solvePoisson();
1019
1020 if (!converged) {
1021 const std::string errMsg = "ItoKMCGodunovStepper::regrid - Poisson solve did not converge after regrid";
1022
1023 pout() << errMsg << endl;
1024
1025 if (this->m_abortOnFailure) {
1026 MayDay::Error(errMsg.c_str());
1027 }
1028 }
1029 m_timer.stopEvent("Solve Poisson");
1030
1031 // The regrid super-particle merge now runs inside ItoSolver::regrid() -- above, in the "Regrid Ito
1032 // solvers" event -- so that the de-refinement pile-up is merged while it is still held as the reduced
1033 // 53 B particle rather than the full 149 B ItoParticle. Two consequences worth knowing:
1034 //
1035 // - This timer loses its "Make superparticles" line for the regrid. The advance() one stays, since
1036 // merge_interval stays. Profile ItoSolver directly if the regrid merge needs attributing again;
1037 // it keeps its own CH_TIME.
1038 // - The merge now happens BEFORE the semi-implicit Poisson solve above rather than after it, which
1039 // is what the base ItoKMCStepper::regrid() already did. Only observable at m_timeStep == 0, where
1040 // computeSpaceChargeDensity() deposits the bulk particles; every later step solves from
1041 // m_rhoDaggerParticles, and the conductivity comes from m_conductivityParticles. A merge
1042 // conserves total weight, so the deposited density is preserved to the merge's spatial accuracy.
1043
1044 // Now let Ihe ito solver deposit its actual particles... In the above it deposit m_rhoDaggerParticles.
1045 m_timer.startEvent("Deposit particles");
1046 (this->m_ito)->depositParticles();
1047 m_timer.stopEvent("Deposit particles");
1048
1049 // Recompute new velocities and diffusion coefficients
1050 m_timer.startEvent("Prepare next step");
1052 this->computeDriftVelocities();
1053 m_timer.stopEvent("Prepare next step");
1054
1055 m_timer.eventReport(pout(), false);
1056
1057 // No reason to have these lying around.
1060
1061 // Fill the neutral density on the mesh
1062 this->fillNeutralDensity();
1063}
1064
1065template <typename I, typename C, typename R, typename F>
1066void
1068{
1069 CH_TIME("ItoKMCGodunovStepper::setOldPositions");
1070 if (this->m_verbosity > 5) {
1071 pout() << this->m_name + "::setOldPositions" << endl;
1072 }
1073
1074 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
1075 RefCountedPtr<ItoSolver>& solver = solverIt();
1076
1077 for (int lvl = 0; lvl <= (this->m_amr)->getFinestLevel(); lvl++) {
1078 const DisjointBoxLayout& dbl = (this->m_amr)->getGrids((this->m_particleRealm))[lvl];
1079 const DataIterator& dit = dbl.dataIterator();
1080
1081 auto& particles = solver->getParticles(ItoSolver::WhichContainer::Bulk)[lvl];
1082
1083 const int nbox = dit.size();
1084
1085#pragma omp parallel for schedule(runtime)
1086 for (int mybox = 0; mybox < nbox; mybox++) {
1087 const DataIndex& din = dit[mybox];
1088
1089 ParticleSoA<ItoParticle>& leaf = particles[din];
1090
1091 double* const pos[SpaceDim] = {D_DECL(leaf.positionColumn(0), leaf.positionColumn(1), leaf.positionColumn(2))};
1092 double* const oldPos[SpaceDim] = {D_DECL(leaf.template column<&ItoParticle::old_x>(),
1093 leaf.template column<&ItoParticle::old_y>(),
1094 leaf.template column<&ItoParticle::old_z>())};
1095
1096 ParticleLoops::loop(leaf, [&](const std::size_t i) {
1097 D_DECL(oldPos[0][i] = pos[0][i], oldPos[1][i] = pos[1][i], oldPos[2][i] = pos[2][i]);
1098 });
1099 }
1100 }
1101 }
1102}
1103
1104template <typename I, typename C, typename R, typename F>
1105void
1107 const SpeciesSubset a_subset) noexcept
1108{
1109 CH_TIME("ItoKMCGodunovStepper::remapPointParticles");
1110 if (this->m_verbosity > 5) {
1111 pout() << this->m_name + "::remapPointParticles" << endl;
1112 }
1113
1114 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
1115 RefCountedPtr<ItoSolver>& solver = solverIt();
1116 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
1117
1118 const int idx = solverIt.index();
1119
1120 const bool mobile = solver->isMobile();
1121 const bool diffusive = solver->isDiffusive();
1122 const bool charged = species->getChargeNumber() != 0;
1123
1124 switch (a_subset) {
1125 case SpeciesSubset::All: {
1126 a_particles[idx]->remap();
1127
1128 break;
1129 }
1131 if (mobile) {
1132 a_particles[idx]->remap();
1133 }
1134
1135 break;
1136 }
1138 if (diffusive) {
1139 a_particles[idx]->remap();
1140 }
1141
1142 break;
1143 }
1145 if (mobile || diffusive) {
1146 a_particles[idx]->remap();
1147 }
1148
1149 break;
1150 }
1152 if (mobile && diffusive) {
1153 a_particles[idx]->remap();
1154 }
1155
1156 break;
1157 }
1159 if (charged) {
1160 a_particles[idx]->remap();
1161 }
1162
1163 break;
1164 }
1166 if (charged && mobile) {
1167 a_particles[idx]->remap();
1168 }
1169
1170 break;
1171 }
1173 if (charged && diffusive) {
1174 a_particles[idx]->remap();
1175 }
1176
1177 break;
1178 }
1180 if (charged && (mobile || diffusive)) {
1181 a_particles[idx]->remap();
1182 }
1183
1184 break;
1185 }
1187 if (charged && (mobile && diffusive)) {
1188 a_particles[idx]->remap();
1189 }
1190
1191 break;
1192 }
1194 if (!mobile && !diffusive) {
1195 a_particles[idx]->remap();
1196 }
1197
1198 break;
1199 }
1200 default: {
1201 MayDay::Abort("ItoKMCGodunovStepper::remapPointParticles - logic bust");
1202
1203 break;
1204 }
1205 }
1206 }
1207}
1208
1209template <typename I, typename C, typename R, typename F>
1210void
1212 const Vector<RefCountedPtr<ParticleContainer<NoPayload>>>& a_particles,
1213 const SpeciesSubset a_subset) noexcept
1214{
1215 CH_TIME("ItoKMCGodunovStepper::depositPointParticles");
1216 if (this->m_verbosity > 5) {
1217 pout() << this->m_name + "::depositPointParticles" << endl;
1218 }
1219
1220 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
1221 RefCountedPtr<ItoSolver>& solver = solverIt();
1222 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
1223
1224 const int idx = solverIt.index();
1225
1226 const bool mobile = solver->isMobile();
1227 const bool diffusive = solver->isDiffusive();
1228 const bool charged = species->getChargeNumber() != 0;
1229
1230 switch (a_subset) {
1231 case SpeciesSubset::All: {
1232 depositPointParticlesLikeSolver(solver, solver->getPhi(), *a_particles[idx]);
1233
1234 break;
1235 }
1237 if (mobile) {
1238 depositPointParticlesLikeSolver(solver, solver->getPhi(), *a_particles[idx]);
1239 }
1240
1241 break;
1242 }
1244 if (diffusive) {
1245 depositPointParticlesLikeSolver(solver, solver->getPhi(), *a_particles[idx]);
1246 }
1247
1248 break;
1249 }
1251 if (mobile || diffusive) {
1252 depositPointParticlesLikeSolver(solver, solver->getPhi(), *a_particles[idx]);
1253 }
1254 break;
1255 }
1257 if (mobile && diffusive) {
1258 depositPointParticlesLikeSolver(solver, solver->getPhi(), *a_particles[idx]);
1259 }
1260 break;
1261 }
1263 if (charged) {
1264 depositPointParticlesLikeSolver(solver, solver->getPhi(), *a_particles[idx]);
1265 }
1266 break;
1267 }
1269 if (charged && mobile) {
1270 depositPointParticlesLikeSolver(solver, solver->getPhi(), *a_particles[idx]);
1271 }
1272 break;
1273 }
1275 if (charged && diffusive) {
1276 depositPointParticlesLikeSolver(solver, solver->getPhi(), *a_particles[idx]);
1277 }
1278
1279 break;
1280 }
1282 if (charged && (mobile || diffusive)) {
1283 depositPointParticlesLikeSolver(solver, solver->getPhi(), *a_particles[idx]);
1284 }
1285
1286 break;
1287 }
1289 if (charged && (mobile && diffusive)) {
1290 depositPointParticlesLikeSolver(solver, solver->getPhi(), *a_particles[idx]);
1291 }
1292
1293 break;
1294 }
1296 if (!mobile && !diffusive) {
1297 depositPointParticlesLikeSolver(solver, solver->getPhi(), *a_particles[idx]);
1298 }
1299
1300 break;
1301 }
1302 default: {
1303 MayDay::Abort("ItoKMCGodunovStepper::depositPointParticles - logic bust");
1304
1305 break;
1306 }
1307 }
1308 }
1309}
1310
1311template <typename I, typename C, typename R, typename F>
1312void
1314 const Vector<RefCountedPtr<ParticleContainer<NoPayload>>>& a_particles,
1315 const SpeciesSubset a_subset) noexcept
1316{
1317 CH_TIME("ItoKMCGodunovStepper::clearPointParticles");
1318 if (this->m_verbosity > 5) {
1319 pout() << this->m_name + "::clearPointParticles" << endl;
1320 }
1321
1322 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
1323 RefCountedPtr<ItoSolver>& solver = solverIt();
1324 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
1325
1326 const int idx = solverIt.index();
1327
1328 const bool mobile = solver->isMobile();
1329 const bool diffusive = solver->isDiffusive();
1330 const bool charged = species->getChargeNumber() != 0;
1331
1332 switch (a_subset) {
1333 case SpeciesSubset::All: {
1334 a_particles[idx]->clearParticles();
1335
1336 break;
1337 }
1339 if (mobile) {
1340 a_particles[idx]->clearParticles();
1341 }
1342
1343 break;
1344 }
1346 if (diffusive) {
1347 a_particles[idx]->clearParticles();
1348 }
1349
1350 break;
1351 }
1353 if (mobile || diffusive) {
1354 a_particles[idx]->clearParticles();
1355 }
1356
1357 break;
1358 }
1360 if (mobile && diffusive) {
1361 a_particles[idx]->clearParticles();
1362 }
1363
1364 break;
1365 }
1367 if (charged) {
1368 a_particles[idx]->clearParticles();
1369 }
1370
1371 break;
1372 }
1374 if (charged && mobile) {
1375 a_particles[idx]->clearParticles();
1376 }
1377
1378 break;
1379 }
1381 if (charged && diffusive) {
1382 a_particles[idx]->clearParticles();
1383 }
1384
1385 break;
1386 }
1388 if (charged && (mobile || diffusive)) {
1389 a_particles[idx]->clearParticles();
1390 }
1391
1392 break;
1393 }
1395 if (charged && (mobile && diffusive)) {
1396 a_particles[idx]->clearParticles();
1397 }
1398
1399 break;
1400 }
1402 if (!mobile && !diffusive) {
1403 a_particles[idx]->clearParticles();
1404 }
1405
1406 break;
1407 }
1408 default: {
1409 MayDay::Abort("ItoKMCGodunovStepper::clearPointParticles - logic bust");
1410
1411 break;
1412 }
1413 }
1414 }
1415}
1416
1417template <typename I, typename C, typename R, typename F>
1418void
1420{
1421 CH_TIME("ItoKMCGodunovStepper::computeCdrConductivity");
1422 if (this->m_verbosity > 5) {
1423 pout() << this->m_name + "::computeCdrConductivity" << endl;
1424 }
1425
1427
1428 for (auto solverIt = (this->m_cdr)->iterator(); solverIt.ok(); ++solverIt) {
1429 const RefCountedPtr<CdrSolver>& solver = solverIt();
1430 const RefCountedPtr<CdrSpecies>& species = solver->getSpecies();
1431
1432 const int index = solverIt.index();
1433 const int Z = species->getChargeNumber();
1434
1435 if (Z != 0 && solver->isMobile()) {
1436 const EBAMRCellData& phi = solver->getPhi();
1437 const EBAMRCellData& mu = this->m_cdrMobilities[index];
1438
1439 DataOps::copy(this->m_fluidScratch1, phi);
1441
1443 }
1444 }
1445}
1446
1447template <typename I, typename C, typename R, typename F>
1448void
1450 const Vector<RefCountedPtr<ParticleContainer<NoPayload>>>& a_particles,
1451 const bool a_useStoredCdrConductivity) noexcept
1452{
1453 CH_TIME("ItoKMCGodunovStepper::computeConductivities");
1454 if (this->m_verbosity > 5) {
1455 pout() << this->m_name + "::computeConductivities" << endl;
1456 }
1457
1458 this->computeCellConductivity((this->m_conductivityCell), a_particles, a_useStoredCdrConductivity);
1460}
1461
1462template <typename I, typename C, typename R, typename F>
1463void
1465 EBAMRCellData& a_conductivityCell,
1466 const Vector<RefCountedPtr<ParticleContainer<NoPayload>>>& a_particles,
1467 const bool a_useStoredCdrConductivity) noexcept
1468{
1469 CH_TIME("ItoKMCGodunovStepper::computeCellConductivity(EBAMRCellData, ParticleContainer)");
1470 if (this->m_verbosity > 5) {
1471 pout() << this->m_name + "::computeCellConductivity(EBAMRCellData, ParticleContainer)" << endl;
1472 }
1473
1474 DataOps::setValue(a_conductivityCell, 0.0);
1475
1476 // Contribution from Ito solvers. The |Z|-weighted sum is formed on the particle realm and crossed to the
1477 // fluid realm once: the deposit has to happen per species (each has its own container, and the deposit
1478 // resets its target rather than incrementing it), but the cross-realm copy does not, and under dual-grid
1479 // it is a Copier exchange over the whole hierarchy.
1481
1482 bool anyItoConductivity = false;
1483
1484 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
1485 RefCountedPtr<ItoSolver>& solver = solverIt();
1486 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
1487
1488 const int idx = solverIt.index();
1489 const int Z = species->getChargeNumber();
1490
1491 if (Z != 0 && solver->isMobile()) {
1492 // Deposit on the particle realm. No zeroing first -- the deposition resets a_phi itself.
1493 depositPointParticlesLikeSolver(solver, this->m_particleScratch1, *a_particles[idx]);
1494
1495 DataOps::incr(m_particleScratchSum, this->m_particleScratch1, 1.0 * std::abs(Z));
1496
1497 anyItoConductivity = true;
1498 }
1499 }
1500
1501 if (anyItoConductivity) {
1502 // Zeroed because the copy below fills the valid region only, and DataOps::incr adds the whole FAB. The
1503 // ghost cells that neither the copy nor the later coarsen/interpolate/exchange reaches -- the ones
1504 // outside the physical domain -- would otherwise carry whatever the last user of the scratch left there.
1506
1507 (this->m_amr)->copyData(this->m_fluidScratch1, m_particleScratchSum);
1508 DataOps::incr(a_conductivityCell, this->m_fluidScratch1, 1.0);
1509 }
1510
1511 // Contribution from the CDR solvers, always taken from m_semiImplicitConductivityCDR. The flag decides only
1512 // whether that buffer is refreshed from the solver states first, which it must not be inside regrid(), where
1513 // the mobilities it is built from are not valid for the current grids.
1514 if (!a_useStoredCdrConductivity) {
1515 this->computeCdrConductivity();
1516 }
1517
1518 DataOps::incr(a_conductivityCell, m_semiImplicitConductivityCDR, 1.0);
1519
1520 // Conductivity is mobility * weight * Q
1521 DataOps::scale(a_conductivityCell, Units::Qe);
1522
1523 // Coarsen, update ghost cells and interpolate to centroids. User can ask for bi/tri-linear filtering.
1524 (this->m_amr)->arithmeticAverage(a_conductivityCell, this->m_fluidRealm, (this->m_plasmaPhase));
1525 (this->m_amr)->interpGhostPwl(a_conductivityCell, this->m_fluidRealm, (this->m_plasmaPhase));
1526
1527 // User can choose to filter the conductivity. Need to sync after each smoothing.
1528 if (m_condFilterNum > 0 && m_condFilterMaxStride > 0) {
1529 for (int i = 0; i < m_condFilterNum; i++) {
1530 for (int curStride = 1; curStride <= m_condFilterMaxStride; curStride++) {
1531 DataOps::filterSmooth(a_conductivityCell, m_condFilterAlpha, curStride, true);
1532
1533 (this->m_amr)->arithmeticAverage(a_conductivityCell, this->m_fluidRealm, (this->m_plasmaPhase));
1534 (this->m_amr)->interpGhostPwl(a_conductivityCell, this->m_fluidRealm, (this->m_plasmaPhase));
1535 }
1536 }
1537 }
1538
1539 (this->m_amr)->interpToCentroids(a_conductivityCell, this->m_fluidRealm, (this->m_plasmaPhase));
1540
1541 // The sum itself is non-negative, but the CDR part is interpolated across regrids, filterSmooth may smooth
1542 // it, and interpToCentroids uses stencils with negative weights. Floor after the last of those so that the
1543 // bound holds where the data is consumed -- a negative conductivity enters the field solve as
1544 // eps + sigma*dt/eps0 < eps.
1545 DataOps::floor(a_conductivityCell, 0.0, (this->m_amr)->getVofIterator(this->m_fluidRealm, this->m_plasmaPhase));
1546}
1547
1548template <typename I, typename C, typename R, typename F>
1549void
1551{
1552 CH_TIME("ItoKMCGodunovStepper::computeFaceConductivity");
1553 if (this->m_verbosity > 5) {
1554 pout() << this->m_name + "::computeFaceConductivity" << endl;
1555 }
1556
1558 DataOps::setValue((this->m_conductivityEB), 0.0);
1559
1560 // Average the cell-centered conductivity to faces. Note that this includes one "ghost face", which we need
1561 // because the multigrid solver will interpolate face-centered conductivities to face centroids.
1562 const Average average = Average::Arithmetic;
1563 const int tanGhost = 1;
1564 const Interval interv(0, 0);
1565
1567 (this->m_conductivityFace),
1568 (this->m_conductivityCell),
1569 (this->m_amr)->getDomains(),
1570 tanGhost,
1571 interv,
1572 interv,
1573 average,
1574 (this->m_amr)->getFaceIteratorWithTangentialGhosts(this->m_fluidRealm, this->m_plasmaPhase));
1575
1576 // Set the EB conductivity.
1578 (this->m_conductivityCell),
1579 1.0,
1580 (this->m_amr)->getVofIterator(this->m_fluidRealm, this->m_plasmaPhase));
1581}
1582
1583template <typename I, typename C, typename R, typename F>
1584void
1586{
1587 CH_TIMERS("ItoKMCGodunovStepper::computeSemiImplicitRho");
1588 CH_TIMER("ItoKMCGodunovStepper::computeSemiImplicitRho::plasma_phase", t1);
1589 CH_TIMER("ItoKMCGodunovStepper::computeSemiImplicitRho::solid_phase", t2);
1590 CH_TIMER("ItoKMCGodunovStepper::computeSemiImplicitRho::filter", t3);
1591 if (this->m_verbosity > 5) {
1592 pout() << this->m_name + "::computeSemiImplicitRho" << endl;
1593 }
1594
1595 // Soft requirement?
1596 CH_assert(this->m_plasmaPhase == phase::gas);
1597
1598 const RefCountedPtr<MultiFluidIndexSpace>& mfis = (this->m_computationalGeometry)->getMfIndexSpace();
1599 const Vector<Dielectric>& dielectrics = (this->m_computationalGeometry)->getDielectrics();
1600
1601 const bool hasDielectrics = (mfis->numPhases() > 1) && (dielectrics.size() > 0);
1602
1603 MFAMRCellData& rho = this->m_fieldSolver->getRho();
1604 EBAMRCellData rhoGas = (this->m_amr)->alias(phase::gas, rho);
1605 EBAMRCellData rhoSolid;
1606
1607 if (hasDielectrics) {
1608 rhoSolid = (this->m_amr)->alias(phase::solid, rho);
1609 }
1610
1611 DataOps::setValue(rho, 0.0);
1612
1613 // Contribution from Ito solvers to the gas-side space charge density. The Z-weighted sum is formed on the
1614 // particle realm -- where every solver's density already lives -- and crossed to the fluid realm once
1615 // instead of once per species. See computeCellConductivity(), which does the same for the conductivity.
1616 CH_START(t1);
1618
1619 bool anyItoCharge = false;
1620
1621 for (auto solverIt = this->m_ito->iterator(); solverIt.ok(); ++solverIt) {
1622 const RefCountedPtr<ItoSolver>& solver = solverIt();
1623 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
1624 const int Z = species->getChargeNumber();
1625
1626 if (Z != 0) {
1627 // The per-species weight stays Z*Qe rather than being factored out of the loop: the terms are then
1628 // summed in the same order and with the same values as when each was incremented into rhoGas
1629 // separately, so the result is bit-for-bit what it was before the accumulation moved realms.
1630 DataOps::incr(m_particleScratchSum, solver->getPhi(), 1.0 * Z * Units::Qe);
1631
1632 anyItoCharge = true;
1633 }
1634 }
1635
1636 if (anyItoCharge) {
1637 // See computeCellConductivity() for why the landing buffer is zeroed first.
1639
1640 (this->m_amr)->copyData(this->m_fluidScratch1, m_particleScratchSum);
1641 DataOps::incr(rhoGas, this->m_fluidScratch1, 1.0);
1642 }
1643
1644 // Contribution from CDR equations to the gas-side space charge density.
1645 DataOps::incr(rhoGas, m_semiImplicitRhoCDR, 1.0);
1646 CH_STOP(t1);
1647
1648 // Contribution from gas-side particles that diffused into EBs. This might be necessary near dielectric EBs as a
1649 // comparatively small correction in the space charge density. There should be no contribution from the CDR solvers
1650 // because the diffusion-only divergence term was computed using homogeneous Neumann boundary conditions.
1651 if (hasDielectrics) {
1652 CH_START(t2);
1653
1654 // The buffers are members allocated once (see allocateInternals) rather than a pair of hierarchies built
1655 // and thrown away on every time step.
1657
1658 bool anySolidCharge = false;
1659
1660 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
1661 const RefCountedPtr<ItoSolver>& solver = solverIt();
1662 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
1663 const int Z = species->getChargeNumber();
1664
1665 if (Z != 0) {
1666 // The cut-cell strategy is a literal here, and must stay one: this deposits onto phase::solid, whose
1667 // ebisbox.normal() points into the SOLID. Routing a solver's own setting here would mirror across the
1668 // same embedded boundary with the fluid side swapped, pushing particles that were deliberately placed
1669 // inside the dielectric back out into the gas. NGP reproduces the historical behaviour exactly.
1670 //
1671 // No zeroing first -- the deposition resets its target itself.
1672 (this->m_amr)
1673 ->depositWeight(m_particleScratchSolid,
1674 this->m_particleRealm,
1676 *m_rhoDaggerParticles[solverIt.index()],
1677 DepositionType::CIC,
1678 CoarseFineDeposition::Halo,
1680
1681 // Weighted per species, not once at the end -- see the gas-phase loop above.
1683
1684 anySolidCharge = true;
1685 }
1686 }
1687
1688 if (anySolidCharge) {
1689 // See computeCellConductivity() for why the landing buffer is zeroed first.
1691
1693 DataOps::incr(rhoSolid, m_fluidScratchSolid, 1.0);
1694 }
1695
1696 CH_STOP(t2);
1697 }
1698
1699 // Sync across levels
1700 this->m_amr->arithmeticAverage(rho, this->m_fluidRealm);
1701 this->m_amr->interpGhostPwl(rho, this->m_fluidRealm);
1702
1703 // User can choose to filter the space charge density. Need to sync after each smoothing.
1704 if (m_rhoFilterNum > 0 && m_rhoFilterMaxStride > 0) {
1705 CH_START(t3);
1706 for (int i = 0; i < m_rhoFilterNum; i++) {
1707 for (int curStride = 1; curStride <= m_rhoFilterMaxStride; curStride++) {
1708
1709 DataOps::filterSmooth(rhoGas, m_rhoFilterAlpha, curStride, true);
1710
1711 this->m_amr->arithmeticAverage(rhoGas, this->m_fluidRealm, this->m_plasmaPhase);
1712 this->m_amr->interpGhost(rhoGas, this->m_fluidRealm, this->m_plasmaPhase);
1713 }
1714 }
1715 CH_STOP(t3);
1716 }
1717
1718 // Put data on centroids.
1719 this->m_amr->interpToCentroids(rhoGas, this->m_fluidRealm, phase::gas);
1720 if (hasDielectrics) {
1721 this->m_amr->interpToCentroids(rhoSolid, this->m_fluidRealm, phase::solid);
1722 }
1723}
1724
1725template <typename I, typename C, typename R, typename F>
1726void
1728{
1729 CH_TIME("ItoKMCGodunovStepper::setupSemiImplicitPoisson");
1730 if (this->m_verbosity > 5) {
1731 pout() << this->m_name + "::setupSemiImplicitPoisson" << endl;
1732 }
1733
1734 // Set coefficients as usual
1735 (this->m_fieldSolver)->setPermittivities();
1736
1737 // Get the permittivities
1738 MFAMRCellData& permCell = (this->m_fieldSolver)->getPermittivityCell();
1739 MFAMRFluxData& permFace = (this->m_fieldSolver)->getPermittivityFace();
1740 MFAMRIVData& permEB = (this->m_fieldSolver)->getPermittivityEB();
1741
1742 // Get handles to the gas-phase permittivities.
1743 EBAMRFluxData permFaceGas = (this->m_amr)->alias((this->m_plasmaPhase), permFace);
1744 EBAMRIVData permEBGas = (this->m_amr)->alias((this->m_plasmaPhase), permEB);
1745
1746 // Increment the field solver permittivities by a_factor*sigma. After this, the "permittivities" are
1747 // given by epsr + a_factor*sigma
1748 DataOps::incr(permFaceGas, (this->m_conductivityFace), a_dt / Units::eps0);
1749 DataOps::incr(permEBGas,
1750 (this->m_conductivityEB),
1751 a_dt / Units::eps0,
1752 (this->m_amr)->getVofIterator(this->m_fluidRealm, this->m_plasmaPhase));
1753
1754 // Coarsen coefficients.
1755 (this->m_amr)->arithmeticAverage(permFaceGas, this->m_fluidRealm, (this->m_plasmaPhase));
1756 (this->m_amr)->arithmeticAverage(permEBGas, this->m_fluidRealm, (this->m_plasmaPhase));
1757
1758 // Set up the solver with the "permittivities"
1759 (this->m_fieldSolver)->setSolverPermittivities(permCell, permFace, permEB);
1760}
1761
1762template <typename I, typename C, typename R, typename F>
1763void
1765 Vector<RefCountedPtr<ParticleContainer<NoPayload>>>& a_particles,
1766 const EBRepresentation a_representation,
1767 const Real a_tolerance) const noexcept
1768{
1769 CH_TIME("ItoKMCGodunovStepper::removeCoveredPointParticles");
1770 if (this->m_verbosity > 5) {
1771 pout() << this->m_name + "::removeCoveredPointParticles" << endl;
1772 }
1773
1774 for (int i = 0; i < a_particles.size(); i++) {
1775 if (a_particles[i] != nullptr) {
1776 ParticleContainer<NoPayload>& particles = *a_particles[i];
1777
1778 switch (a_representation) {
1779 case EBRepresentation::Discrete: {
1780 (this->m_amr)->removeCoveredParticlesDiscrete(particles, (this->m_plasmaPhase), a_tolerance);
1781
1782 break;
1783 }
1784 case EBRepresentation::ImplicitFunction: {
1785 (this->m_amr)->removeCoveredParticlesIF(particles, (this->m_plasmaPhase), a_tolerance);
1786
1787 break;
1788 }
1789 case EBRepresentation::Voxel: {
1790 (this->m_amr)->removeCoveredParticlesVoxels(particles, (this->m_plasmaPhase));
1791
1792 break;
1793 }
1794 default: {
1795 MayDay::Error("ItoKMCGodunovStepper::removeCoveredParticles - logic bust");
1796 }
1797 }
1798 }
1799 }
1800}
1801
1802template <typename I, typename C, typename R, typename F>
1803void
1805 Vector<RefCountedPtr<ParticleContainer<NoPayload>>>& a_conductivityParticles) noexcept
1806{
1807 CH_TIME("ItoKMCGodunovStepper::copyConductivityParticles");
1808 if (this->m_verbosity > 5) {
1809 pout() << this->m_name + "::copyConductivityParticles" << endl;
1810 }
1811
1812 // Clear particles first.
1813 this->clearPointParticles(a_conductivityParticles, SpeciesSubset::All);
1814
1815 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
1816 const RefCountedPtr<ItoSolver>& solver = solverIt();
1817 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
1818
1819 const int idx = solverIt.index();
1820 const int Z = species->getChargeNumber();
1821
1822 if (Z != 0 && solver->isMobile()) {
1823 const ParticleContainer<ItoParticle>& solverParticles = solver->getParticles(ItoSolver::WhichContainer::Bulk);
1824
1825 for (int lvl = 0; lvl <= (this->m_amr)->getFinestLevel(); lvl++) {
1826 const DisjointBoxLayout& dbl = (this->m_amr)->getGrids((this->m_particleRealm))[lvl];
1827 const DataIterator& dit = dbl.dataIterator();
1828
1829 const int nbox = dit.size();
1830
1831#pragma omp parallel for schedule(runtime)
1832 for (int mybox = 0; mybox < nbox; mybox++) {
1833 const DataIndex& din = dit[mybox];
1834
1835 const ParticleSoA<ItoParticle>& leaf = solverParticles[lvl][din];
1836
1837 ParticleSoA<NoPayload>& pointParticles = (*a_conductivityParticles[idx])[lvl][din];
1838 ParticleSoA<NoPayload>& irregParticles = (*m_irregularParticles[idx])[lvl][din];
1839
1840 // One point particle per particle, plus whatever the catenate below brings. Reserved in one go
1841 // because reserve() sizes the capacity exactly: reserving only the loop's own count would leave
1842 // the container full, and the catenate would immediately reallocate it.
1843 pointParticles.reserve(pointParticles.size() + leaf.size() + irregParticles.size());
1844
1845 for (std::size_t i = 0; i < leaf.size(); i++) {
1846 const RealVect pos = leaf.position(i);
1847 const Real weight = leaf.weight(i);
1848 const Real mobility = leaf.template get<&ItoParticle::mobility>(i);
1849
1850 pointParticles.append(pos, weight * mobility);
1851 }
1852
1853 pointParticles.catenate(irregParticles);
1854 }
1855 }
1856 }
1857 }
1858}
1859
1860template <typename I, typename C, typename R, typename F>
1861bool
1863{
1864 CH_TIME("ItoKMCGodunovStepper::solvePoisson()");
1865 if (this->m_verbosity > 5) {
1866 pout() << this->m_name + "::solvePoisson()" << endl;
1867 }
1868
1869 // Solve the Poisson equation and compute the cell-centered electric field.
1870 MFAMRCellData& phi = this->m_fieldSolver->getPotential();
1871 MFAMRCellData& rho = this->m_fieldSolver->getRho();
1872 EBAMRIVData& sigma = this->m_sigmaSolver->getPhi();
1873
1874 const bool converged = (this->m_fieldSolver)->solve(phi, rho, sigma, false);
1875
1877
1878 // Copy the electric field to appropriate data holders and perform center-to-centroid
1879 // interpolation.
1880 EBAMRCellData E;
1881 (this->m_amr)->allocatePointer(E, this->m_fluidRealm);
1882 (this->m_amr)->alias(E, this->m_plasmaPhase, (this->m_fieldSolver)->getElectricField());
1883
1884 // Fluid realm
1885 (this->m_amr)->copyData(this->m_electricFieldFluid, E);
1886 (this->m_amr)->conservativeAverage(this->m_electricFieldFluid, this->m_fluidRealm, this->m_plasmaPhase);
1887 (this->m_amr)->interpGhostPwl(this->m_electricFieldFluid, this->m_fluidRealm, this->m_plasmaPhase);
1888 (this->m_amr)->interpToCentroids(this->m_electricFieldFluid, this->m_fluidRealm, this->m_plasmaPhase);
1889
1890 // Particle realm
1891 (this->m_amr)->copyData(this->m_electricFieldParticle, E);
1892 (this->m_amr)->conservativeAverage(this->m_electricFieldParticle, this->m_particleRealm, this->m_plasmaPhase);
1893 (this->m_amr)->interpGhostPwl(this->m_electricFieldParticle, this->m_particleRealm, this->m_plasmaPhase);
1894 (this->m_amr)->interpToCentroids(this->m_electricFieldParticle, this->m_particleRealm, this->m_plasmaPhase);
1895
1896 return converged;
1897}
1898
1899template <typename I, typename C, typename R, typename F>
1900void
1902{
1903 CH_TIME("ItoKMCGodunovStepper::advanceEulerMaruyama");
1904 if (this->m_verbosity > 5) {
1905 pout() << this->m_name + "::advanceEulerMaruyama" << endl;
1906 }
1907
1908 // Store X^k positions.
1909 this->setOldPositions();
1910
1911 // Compute the explicit displacement -- the diffusion hop plus the lagged dt*grad(D) drift. This copies onto
1912 // m_rhoDaggerParticles and stores the displacement on the full particles. We need to remap the particle
1913 // species that moved.
1914 this->barrier();
1915 m_timer.startEvent("Diffuse particles");
1918 m_timer.stopEvent("Diffuse particles");
1919
1920 // Perform the diffusive CDR advance.
1921 this->barrier();
1922 m_timer.startEvent("Diffuse CDR");
1924 m_timer.stopEvent("Diffuse CDR");
1925
1926 // Compute the conductivity on the mesh. This deposits q_e * Z * w * mu on the mesh.
1927 this->barrier();
1928 m_timer.startEvent("Compute conductivities");
1931 m_timer.stopEvent("Compute conductivities");
1932
1933 // Set up the semi-implicit Poisson solver with the computed conductivities.
1934 this->barrier();
1935 m_timer.startEvent("Setup Poisson");
1936 this->setupSemiImplicitPoisson(a_dt);
1937 m_timer.stopEvent("Setup Poisson");
1938
1939 // Compute space charge density arising from the displaced particle positions X^k + sqrt(2*D*dt)*W + dt*grad(D).
1940 // Only need to do the diffusive and charged species.
1941 this->barrier();
1942 m_timer.startEvent("Deposit point particles");
1944 this->computeSemiImplicitRho();
1945 m_timer.stopEvent("Deposit point particles");
1946
1947 // Solve the semi-implicit Poisson equation.
1948 this->barrier();
1949 m_timer.startEvent("Solve Poisson");
1950 const bool converged = this->solvePoisson();
1951 if (!converged) {
1952 const std::string errMsg = "ItoKMCGodunovStepper::advanceEulerMaruyama - Poisson solve did not converge";
1953
1954 pout() << errMsg << endl;
1955
1956 if (this->m_abortOnFailure) {
1957 MayDay::Error(errMsg.c_str());
1958 }
1959 }
1960 m_timer.stopEvent("Solve Poisson");
1961
1962 // Recompute velocities with the new electric field. This interpolates the velocities to the current particle
1963 // positions, i.e. we compute V^(k+1)(X^k) = mu^k * E^(k+1)(X^k)
1964 this->barrier();
1965 m_timer.startEvent("Step-compute v");
1966#if 1 // This is what the algorithm says.
1969 (this->m_ito)->interpolateVelocities();
1971#else // Have to use this for LEA - need to debug.
1972 this->computeDriftVelocities();
1973#endif
1974 m_timer.stopEvent("Step-compute v");
1975
1976 // Finalize the Euler-Maruyama update.
1977 this->barrier();
1978 m_timer.startEvent("Euler-Maruyama step");
1979 this->stepEulerMaruyamaParticles(a_dt);
1980 this->stepEulerMaruyamaCDR(a_dt);
1981 m_timer.stopEvent("Euler-Maruyama step");
1982}
1983
1984template <typename I, typename C, typename R, typename F>
1985void
1987 Vector<RefCountedPtr<ParticleContainer<NoPayload>>>& a_rhoDaggerParticles,
1988 const Real a_dt) noexcept
1989{
1990 CH_TIME("ItoKMCGodunovStepper::diffuseParticlesEulerMaruyama");
1991 if (this->m_verbosity > 5) {
1992 pout() << this->m_name + "::diffuseParticlesEulerMaruyama" << endl;
1993 }
1994
1995 this->clearPointParticles(a_rhoDaggerParticles, SpeciesSubset::All);
1996
1997 // Hops that would have carried a particle, or its charge, inside the boundary and were corrected instead.
1998 long long numCrossings = 0;
1999 long long numTotalTested = 0;
2000 long long numReflectFailed = 0;
2001
2002 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
2003 RefCountedPtr<ItoSolver>& solver = solverIt();
2004 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
2005
2006 const int idx = solverIt.index();
2007
2008 const bool mobile = solver->isMobile();
2009 const bool diffusive = solver->isDiffusive();
2010 const int Z = species->getChargeNumber();
2011
2012 const auto& diffusionFunction = (this->m_physics)->getItoDiffusionFunctions()[idx];
2013
2014 // The grad(D) drift correction. An Ito-interpretation Euler-Maruyama update with a drift of v alone
2015 // transports the flux v*n - grad(D*n); the drift has to be v + grad(D) for the particles to transport
2016 // v*n - D*grad(n), which is what CdrSolver integrates.
2017 //
2018 // The correction belongs here, with the hop, and not in the particle velocities: it is lagged and
2019 // independent of E^(k+1), so it goes into the explicit half of the semi-implicit split, where the
2020 // rho^dagger deposit accounts for it exactly. Putting it in the velocities would add a term that is not
2021 // proportional to E^(k+1) to the implicit half, which is the half the semi-implicit Poisson operator was
2022 // built for. This mirrors what computeDiffusionTermCDR does with the explicit dt*div(D*grad(phi^k)).
2023 const bool gradientDrift = diffusive && solver->isDiffusionGradientDrift();
2024
2025 if (gradientDrift) {
2026 solver->computeDiffusionGradient();
2027 }
2028
2029 for (int lvl = 0; lvl <= (this->m_amr)->getFinestLevel(); lvl++) {
2030 const DisjointBoxLayout& dbl = (this->m_amr)->getGrids((this->m_particleRealm))[lvl];
2031 const DataIterator& dit = dbl.dataIterator();
2032
2033 // For the boundary test on the diffusion hop below. The intersection algorithm and its path-march length come
2034 // from the solver that owns the particles, so that the crossing point reflection mirrors about and the one the
2035 // absorption test finds later in the advance are located the same way.
2036 const RefCountedPtr<BaseIF>& baseif = (this->m_amr)->getBaseImplicitFunction(this->m_plasmaPhase);
2037 const Real dx = (this->m_amr)->getDx()[lvl];
2038 const EBIntersection intersectionAlg = solver->getIntersectionAlgorithm();
2039 const Real bisectStep = solver->getBisectionStep();
2040
2041 const bool checkEB = (m_diffusiveDeposit != DiffusiveDeposit::Inside) && !baseif.isNull();
2042
2043 // ReflectIto is the one setting that corrects the particle's displacement rather than only its deposit.
2044 const bool correctTrajectory = (m_diffusiveDeposit == DiffusiveDeposit::ReflectIto);
2045
2046 auto& particles = solver->getParticles(ItoSolver::WhichContainer::Bulk)[lvl];
2047
2048 const int nbox = dit.size();
2049
2050#pragma omp parallel for schedule(runtime) reduction(+ : numCrossings, numTotalTested, numReflectFailed)
2051 for (int mybox = 0; mybox < nbox; mybox++) {
2052 const DataIndex& din = dit[mybox];
2053
2054 ParticleSoA<ItoParticle>& leaf = particles[din];
2055 ParticleSoA<NoPayload>& pointParticles = (*a_rhoDaggerParticles[idx])[lvl][din];
2056
2057 // A depositing species produces exactly one point particle per particle -- in the first pass if its
2058 // displacement stayed in the fluid, otherwise in one of the two correction passes below, never both.
2059 // The count is therefore known here, and reserving it keeps the appends from walking the doubling
2060 // ladder: growing from 16 to a patch's population copies the arena roughly twice over, every step.
2061 if (Z != 0) {
2062 pointParticles.reserve(pointParticles.size() + leaf.size());
2063 }
2064
2065 // Puts (grad D)(X_p) on the scratch vector columns. Those columns are also where the total explicit
2066 // displacement ends up, so each particle's gradient is read into a local below before being
2067 // overwritten, within the same loop iteration.
2068 if (gradientDrift) {
2069 solver->interpolateDiffusionGradient(lvl, din);
2070 }
2071
2072 // The trajectory and the deposit are corrected independently, and are only the same correction when the
2073 // deposit carries the hop. Two crossing lists rather than one, because a particle can cross on one
2074 // displacement and not the other: with the hop left out of rho^dagger the deposit moves by dt*grad(D)
2075 // alone, which can land inside the solid on its own or fail to when the full hop would have. Only the
2076 // crossings are carried, so both stay empty -- and unallocated -- for every box away from the geometry.
2077 const bool depositFollowsHop = correctTrajectory && m_rhoDaggerHop;
2078
2079 // Particles whose own displacement crossed. Filled only when the trajectory is corrected.
2080 std::vector<std::size_t> hopCrossings;
2081 std::vector<Real> hopCrossingsFOld;
2082
2083 // Charged particles whose DEPOSIT displacement crossed, when the deposit does not simply follow the
2084 // corrected trajectory. Carries that displacement, which is not recoverable from the scratch columns.
2085 std::vector<std::size_t> depositCrossings;
2086 std::vector<Real> depositCrossingsFOld;
2087 std::vector<RealVect> depositCrossingsDisp;
2088
2089 // First pass: the displacement for every particle, and the cheap test for whether it crossed.
2090 for (std::size_t i = 0; i < leaf.size(); i++) {
2091 const Real weight = leaf.weight(i);
2092 const RealVect pos = leaf.position(i);
2093
2094 // Compute a particle hop and store it on the run-time storage. The DiffusionFunction reads payload
2095 // columns (diffusion/velocity/scratch), so materialize the payload via gather(). Note that the
2096 // scratch vector columns hold grad(D) at this point, which a custom diffusion model may use.
2097 const ItoParticle p = leaf.gather(i);
2098 const RealVect hop = diffusive ? diffusionFunction(p, a_dt) : RealVect::Zero;
2099
2100 const RealVect gradD = gradientDrift ? RealVect(D_DECL(p.scratch_x, p.scratch_y, p.scratch_z))
2101 : RealVect::Zero;
2102
2103 // The total explicit displacement: the stochastic hop plus the lagged grad(D) drift. Under ReflectIto the
2104 // second pass may correct this in place; under every other setting it is already final and the boundary
2105 // handling touches only where the charge is deposited.
2106 const RealVect disp = hop + a_dt * gradD;
2107
2108 D_DECL(leaf.template get<&ItoParticle::scratch_x>(i) = static_cast<ParticleReal>(disp[0]),
2109 leaf.template get<&ItoParticle::scratch_y>(i) = static_cast<ParticleReal>(disp[1]),
2110 leaf.template get<&ItoParticle::scratch_z>(i) = static_cast<ParticleReal>(disp[2]));
2111
2112 // What the rho^dagger deposit displaces by. The hop can be left out of it while the particle still takes
2113 // it; the grad(D) drift never is, being deterministic mean transport that the explicit half must account
2114 // for.
2115 const RealVect depositDisp = m_rhoDaggerHop ? disp : a_dt * gradD;
2116
2117 const bool deposits = (Z != 0);
2118
2119 if (!checkEB) {
2120 if (deposits) {
2121 pointParticles.append(pos + depositDisp, weight);
2122 }
2123
2124 continue;
2125 }
2126
2127 // A sign CHANGE rather than a sign, so nothing here assumes which side the implicit function calls
2128 // positive. pos is known to be in the fluid because the particle is there now.
2129 const Real fOld = baseif->value(pos);
2130
2131 const auto crosses = [&](const RealVect& a_disp) -> bool {
2132 return fOld * baseif->value(pos + a_disp) < 0.0;
2133 };
2134
2135 // The trajectory correction, which only ReflectIto applies, and which applies to every species rather
2136 // than only those that deposit.
2137 bool hopCrossed = false;
2138
2139 if (correctTrajectory) {
2140 numTotalTested++;
2141
2142 hopCrossed = crosses(disp);
2143
2144 if (hopCrossed) {
2145 hopCrossings.push_back(i);
2146 hopCrossingsFOld.push_back(fOld);
2147 }
2148 }
2149
2150 if (!deposits) {
2151 continue;
2152 }
2153
2154 // The deposit. It follows the corrected trajectory when it carries the hop, and is otherwise tested and
2155 // corrected on its own displacement -- which is the case the trajectory test cannot stand in for.
2156 if (depositFollowsHop) {
2157 if (!hopCrossed) {
2158 pointParticles.append(pos + depositDisp, weight);
2159 }
2160 }
2161 else {
2162
2163 // A second, genuinely distinct test when the deposit does not carry the hop, so it counts separately.
2164 numTotalTested++;
2165
2166 if (crosses(depositDisp)) {
2167 depositCrossings.push_back(i);
2168 depositCrossingsFOld.push_back(fOld);
2169 depositCrossingsDisp.push_back(depositDisp);
2170 }
2171 else {
2172 pointParticles.append(pos + depositDisp, weight);
2173 }
2174 }
2175 }
2176
2177 // Second pass, trajectories: mirror the particle's own displacement about the boundary. Zero is
2178 // unambiguous -- a displacement that crossed cannot reflect to exactly no displacement, so it is the
2179 // routine reporting that it could not place the particle back in the fluid, and cancelling the hop is
2180 // always safe from a position known to be there.
2181 for (std::size_t k = 0; k < hopCrossings.size(); k++) {
2182 const std::size_t i = hopCrossings[k];
2183 const Real fOld = hopCrossingsFOld[k];
2184
2185 const RealVect pos = leaf.position(i);
2186 const RealVect disp = RealVect(D_DECL(leaf.template get<&ItoParticle::scratch_x>(i),
2187 leaf.template get<&ItoParticle::scratch_y>(i),
2188 leaf.template get<&ItoParticle::scratch_z>(i)));
2189
2190 numCrossings++;
2191
2192 const RealVect correctedDisp = this->reflectDiffusionHop(pos, disp, fOld, dx, intersectionAlg, bisectStep);
2193
2194 if (correctedDisp == RealVect::Zero) {
2195 numReflectFailed++;
2196 }
2197
2198 D_DECL(leaf.template get<&ItoParticle::scratch_x>(i) = static_cast<ParticleReal>(correctedDisp[0]),
2199 leaf.template get<&ItoParticle::scratch_y>(i) = static_cast<ParticleReal>(correctedDisp[1]),
2200 leaf.template get<&ItoParticle::scratch_z>(i) = static_cast<ParticleReal>(correctedDisp[2]));
2201
2202 // The deposit rides along when it carries the hop; otherwise it was handled on its own displacement.
2203 if (Z != 0 && depositFollowsHop) {
2204 pointParticles.append(pos + correctedDisp, leaf.weight(i));
2205 }
2206 }
2207
2208 // Second pass, deposits: create the point particle at the position it keeps. Cancel deposits at the
2209 // pre-hop position, which conserves the charge but biases the density towards where it started, and a
2210 // reflection that could not reach the fluid falls through to the same place.
2211 for (std::size_t k = 0; k < depositCrossings.size(); k++) {
2212 const std::size_t i = depositCrossings[k];
2213 const Real fOld = depositCrossingsFOld[k];
2214 const RealVect depositDisp = depositCrossingsDisp[k];
2215
2216 const RealVect pos = leaf.position(i);
2217
2218 numCrossings++;
2219
2220 RealVect correctedDisp = RealVect::Zero;
2221
2223 correctedDisp = this->reflectDiffusionHop(pos, depositDisp, fOld, dx, intersectionAlg, bisectStep);
2224
2225 if (correctedDisp == RealVect::Zero) {
2226 numReflectFailed++;
2227 }
2228 }
2229
2230 pointParticles.append(pos + correctedDisp, leaf.weight(i));
2231 }
2232 }
2233 }
2234 }
2235
2236 // Reduced unconditionally: these are collectives and the condition below is not one.
2237 numCrossings = ParallelOps::sum(numCrossings);
2238 numTotalTested = ParallelOps::sum(numTotalTested);
2239 numReflectFailed = ParallelOps::sum(numReflectFailed);
2240
2241 if (this->m_verbosity > 5 && numTotalTested > 0) {
2242 const std::string what = (m_diffusiveDeposit == DiffusiveDeposit::ReflectIto) ? "particle hops"
2243 : "rho^dagger deposits";
2244
2245 pout() << this->m_name + "::diffuseParticlesEulerMaruyama - "
2246 << ((m_diffusiveDeposit == DiffusiveDeposit::Cancel) ? "cancelled " : "reflected ") << numCrossings << " of "
2247 << numTotalTested << " " << what << " (" << (100.0 * numCrossings) / numTotalTested
2248 << "%) that would have crossed the EB";
2249
2251 pout() << "; " << numReflectFailed << " could not be reflected into the fluid and were cancelled";
2252 }
2253
2254 pout() << endl;
2255 }
2256}
2257
2258template <typename I, typename C, typename R, typename F>
2259void
2260ItoKMCGodunovStepper<I, C, R, F>::computeDiffusionTermCDR(EBAMRCellData& a_semiImplicitRhoCDR, const Real a_dt) noexcept
2261{
2262 CH_TIME("ItoKMCGodunovStepper::diffuseCDREulerMaruyama");
2263 if (this->m_verbosity > 5) {
2264 pout() << this->m_name + "::diffuseCDREulerMaruyama" << endl;
2265 }
2266
2267 DataOps::setValue(a_semiImplicitRhoCDR, 0.0);
2268
2269 for (auto solverIt = this->m_cdr->iterator(); solverIt.ok(); ++solverIt) {
2270 const RefCountedPtr<CdrSolver>& solver = solverIt();
2271 const RefCountedPtr<CdrSpecies>& species = solver->getSpecies();
2272
2273 const int index = solverIt.index();
2274 const int Z = species->getChargeNumber();
2275
2276 const EBAMRCellData& phi = solver->getPhi();
2277
2278 // Compute the conservative finite-volume approximation to kappa*div(D*grad(phi)). It is stabilized together with
2279 // the advective term in stepEulerMaruyamaCDR, since the two enter the same update.
2280 if (solver->isDiffusive()) {
2281 solver->computeDivD(m_cdrDivD[index], solver->getPhi(), a_dt, true, false, false);
2282 }
2283
2284 // Update the space charge density arising from the update phi^dagger = phi^k + dt * div(D*grad(phi^k)), with the
2285 // diffusive term stabilized on its own. stepEulerMaruyamaCDR stabilizes the advective and diffusive terms together,
2286 // which with state redistribution is not the same as stabilizing them separately: the diffusive part of the update
2287 // differs from the one that the field solve sees by the difference of the stabilizations. Hybrid (volume)
2288 // redistribution is linear, so there the two agree up to round-off.
2289 if (Z != 0) {
2290 DataOps::incr(a_semiImplicitRhoCDR, phi, 1.0 * Z);
2291 if (solver->isDiffusive()) {
2293
2294 solver->redistributeDivergence(this->m_fluidScratch1, phi, -a_dt);
2295
2296 DataOps::incr(a_semiImplicitRhoCDR, this->m_fluidScratch1, 1.0 * Z * a_dt);
2297 }
2298 }
2299 }
2300
2301 DataOps::scale(a_semiImplicitRhoCDR, Units::Qe);
2302
2303 this->m_amr->arithmeticAverage(a_semiImplicitRhoCDR, this->m_fluidRealm, this->m_plasmaPhase);
2304 this->m_amr->interpGhostPwl(a_semiImplicitRhoCDR, this->m_fluidRealm, this->m_plasmaPhase);
2305}
2306
2307template <typename I, typename C, typename R, typename F>
2308void
2310{
2311 CH_TIME("ItoKMCGodunovStepper::stepEulerMaruyamaParticles");
2312 if (this->m_verbosity > 5) {
2313 pout() << this->m_name + "::stepEulerMaruyamaParticles" << endl;
2314 }
2315
2316 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
2317 RefCountedPtr<ItoSolver>& solver = solverIt();
2318
2319 const bool mobile = solver->isMobile();
2320 const bool diffusive = solver->isDiffusive();
2321
2322 const Real f = mobile ? a_dt : 0.0;
2323 const Real g = diffusive ? 1.0 : 0.0;
2324
2325 if (mobile || diffusive) {
2326 for (int lvl = 0; lvl <= (this->m_amr)->getFinestLevel(); lvl++) {
2327 const DisjointBoxLayout& dbl = (this->m_amr)->getGrids((this->m_particleRealm))[lvl];
2328 const DataIterator& dit = dbl.dataIterator();
2329
2330 auto& particles = solver->getParticles(ItoSolver::WhichContainer::Bulk)[lvl];
2331
2332 const int nbox = dit.size();
2333
2334#pragma omp parallel for schedule(runtime)
2335 for (int mybox = 0; mybox < nbox; mybox++) {
2336 const DataIndex& din = dit[mybox];
2337
2338 ParticleSoA<ItoParticle>& leaf = particles[din];
2339
2340 double* const pos[SpaceDim] = {
2341 D_DECL(leaf.positionColumn(0), leaf.positionColumn(1), leaf.positionColumn(2))};
2342 double* const oldPos[SpaceDim] = {D_DECL(leaf.template column<&ItoParticle::old_x>(),
2343 leaf.template column<&ItoParticle::old_y>(),
2344 leaf.template column<&ItoParticle::old_z>())};
2345 ParticleReal* const vel[SpaceDim] = {D_DECL(leaf.template column<&ItoParticle::vx>(),
2346 leaf.template column<&ItoParticle::vy>(),
2347 leaf.template column<&ItoParticle::vz>())};
2348 ParticleReal* const disp[SpaceDim] = {D_DECL(leaf.template column<&ItoParticle::scratch_x>(),
2349 leaf.template column<&ItoParticle::scratch_y>(),
2350 leaf.template column<&ItoParticle::scratch_z>())};
2351
2352 ParticleLoops::loop(leaf, [&](const std::size_t i) {
2353 // Add in the advective contribution and the explicit displacement (hop + dt*grad(D)).
2354 for (int dir = 0; dir < SpaceDim; dir++) {
2355 pos[dir][i] = oldPos[dir][i] + f * vel[dir][i] + g * disp[dir][i];
2356 }
2357 });
2358 }
2359 }
2360 }
2361 }
2362}
2363
2364template <typename I, typename C, typename R, typename F>
2365void
2367{
2368 CH_TIME("ItoKMCGodunovStepper::stepEulerMaruyamaCDR");
2369 if (this->m_verbosity > 5) {
2370 pout() << this->m_name + "::stepEulerMaruyamaCDR" << endl;
2371 }
2372
2373 for (auto solverIt = (this->m_cdr)->iterator(); solverIt.ok(); ++solverIt) {
2374 RefCountedPtr<CdrSolver>& solver = solverIt();
2375
2376 const int index = solverIt.index();
2377
2378 EBAMRCellData& phi = solver->getPhi();
2379
2380 // A diffusive solver arrives here already synchronized and does not pay for it again. Its coarse valid
2381 // cells were averaged after the last write to phi -- by coarsenCDRSolvers() at the end of the reaction
2382 // advance, or by resolveSecondaryEmissionEB(), or by CdrSolver::regrid()/initialData() on the entry
2383 // paths -- and its ghost cells were filled earlier in THIS step by CdrMultigrid::computeDivD(), which
2384 // interpolates them itself before differencing. Nothing writes phi in between. A solver that is mobile
2385 // but not diffusive gets no computeDivD, so it still needs the fill before computeDivF reads across
2386 // patch boundaries.
2387 if (!solver->isDiffusive()) {
2388 this->m_amr->conservativeAverage(phi, this->m_fluidRealm, this->m_plasmaPhase);
2389 this->m_amr->interpGhostPwl(phi, this->m_fluidRealm, this->m_plasmaPhase);
2390 }
2391
2392 // The update is phi^(k+1) = phi^k - dt*(div(F) - div(D*grad(phi))). The advective and diffusive terms are added
2393 // together as conservative divergences and then stabilized once, since the cut-cell stabilization of a sum is not
2394 // the sum of the stabilizations (see EBRedistribution).
2395 if (solver->isMobile() || solver->isDiffusive()) {
2397
2398 // Compute the FV approximation to kappa*div(F). If the underlying CDR solver is a CTU solver, we also add in the
2399 // transverse terms. The BC comes later.
2400 if (solver->isMobile()) {
2401 DataOps::setValue(solver->getEbFlux(), 0.0);
2402
2403 solver->computeDivF(this->m_fluidScratch1, phi, a_dt, a_dt, true, true, true);
2404 }
2405
2406 // Subtract kappa*div(D*grad(phi)) from computeDiffusionTermCDR.
2407 if (solver->isDiffusive()) {
2408 DataOps::incr(this->m_fluidScratch1, this->m_cdrDivD[index], -1.0);
2409 }
2410
2411 solver->redistributeDivergence(this->m_fluidScratch1, phi, a_dt);
2412
2413 DataOps::incr(phi, this->m_fluidScratch1, -a_dt);
2414 }
2415
2416 DataOps::floor(phi, 0.0, this->m_amr->getVofIterator(this->m_fluidRealm, this->m_plasmaPhase));
2417 }
2418
2419 this->coarsenCDRSolvers(true);
2420}
2421
2422#ifdef CH_USE_HDF5
2423template <typename I, typename C, typename R, typename F>
2424void
2425ItoKMCGodunovStepper<I, C, R, F>::writeCheckpointHeader(HDF5HeaderData& a_header) const noexcept
2426{
2427 CH_TIME("ItoKMCGodunovStepper::writeCheckpointHeader");
2428 if (this->m_verbosity > 5) {
2429 pout() << this->m_name + "::writeCheckpointHeader" << endl;
2430 }
2431
2432 a_header.m_real["prev_dt"] = this->m_prevDt;
2433 a_header.m_real["physics_dt"] = this->m_physicsDt;
2434 a_header.m_int["checkpoint_particles"] = m_writeCheckpointParticles ? 1 : 0;
2435}
2436#endif
2437
2438#ifdef CH_USE_HDF5
2439template <typename I, typename C, typename R, typename F>
2440void
2441ItoKMCGodunovStepper<I, C, R, F>::readCheckpointHeader(HDF5HeaderData& a_header) noexcept
2442{
2443 CH_TIME("ItoKMCGodunovStepper::readCheckpointHeader");
2444 if (this->m_verbosity > 5) {
2445 pout() << this->m_name + "::readCheckpointHeader" << endl;
2446 }
2447
2448 this->m_prevDt = a_header.m_real["prev_dt"];
2449 this->m_physicsDt = a_header.m_real["physics_dt"];
2450
2451 m_readCheckpointParticles = (a_header.m_int["checkpoint_particles"] != 0) ? true : false;
2452 m_canRegridOnRestart = m_readCheckpointParticles;
2453}
2454#endif
2455
2456#ifdef CH_USE_HDF5
2457template <typename I, typename C, typename R, typename F>
2458void
2459ItoKMCGodunovStepper<I, C, R, F>::writeCheckpointData(HDF5Handle& a_handle, const int a_lvl) const noexcept
2460{
2461 CH_TIME("ItoKMCGodunovStepper::writeCheckpointData");
2462 if (this->m_verbosity > 5) {
2463 pout() << this->m_name + "::writeCheckpointData" << endl;
2464 }
2465
2467
2468 // Write the point-particles.
2469 if (m_writeCheckpointParticles) {
2470 for (int i = 0; i < (this->m_physics)->getNumItoSpecies(); i++) {
2471 const std::string identifierSigma = "ItoKMCGodunovStepper::conductivityParticles_" + std::to_string(i);
2472 const std::string identifierRho = "ItoKMCGodunovStepper::spaceChargeParticles_" + std::to_string(i);
2473
2474 const ParticleContainer<NoPayload>& conductivityParticles = *m_conductivityParticles[i];
2475 const ParticleContainer<NoPayload>& rhoDaggerParticles = *m_rhoDaggerParticles[i];
2476
2477 DischargeIO::writeCheckParticlesToHDF(a_handle, conductivityParticles[a_lvl], identifierSigma);
2478 DischargeIO::writeCheckParticlesToHDF(a_handle, rhoDaggerParticles[a_lvl], identifierRho);
2479 }
2480 }
2481
2482 // Write data required for the semi-implicit regrid.
2483 if (this->m_physics->getNumCdrSpecies() > 0) {
2484 write(a_handle, *m_semiImplicitRhoCDR[a_lvl], "ItoKMCGodunovStepper::semiImplicitRhoCDR");
2485 write(a_handle, *m_semiImplicitConductivityCDR[a_lvl], "ItoKMCGodunovStepper::semiImplicitConductivityCDR");
2486 }
2487}
2488#endif
2489
2490#ifdef CH_USE_HDF5
2491template <typename I, typename C, typename R, typename F>
2492void
2493ItoKMCGodunovStepper<I, C, R, F>::readCheckpointData(HDF5Handle& a_handle, const int a_lvl) noexcept
2494{
2495 CH_TIME("ItoKMCGodunovStepper::readCheckpointData");
2496 if (this->m_verbosity > 5) {
2497 pout() << this->m_name + "::readCheckpointData" << endl;
2498 }
2499
2501
2502 // Write the point-particles.
2503 if (m_readCheckpointParticles) {
2504 for (int i = 0; i < (this->m_physics)->getNumItoSpecies(); i++) {
2505 const std::string identifierSigma = "ItoKMCGodunovStepper::conductivityParticles_" + std::to_string(i);
2506 const std::string identifierRho = "ItoKMCGodunovStepper::spaceChargeParticles_" + std::to_string(i);
2507
2508 ParticleContainer<NoPayload>& conductivityParticles = *m_conductivityParticles[i];
2509 ParticleContainer<NoPayload>& rhoDaggerParticles = *m_rhoDaggerParticles[i];
2510
2511 DischargeIO::readCheckParticlesFromHDF(a_handle, conductivityParticles[a_lvl], identifierSigma);
2512 DischargeIO::readCheckParticlesFromHDF(a_handle, rhoDaggerParticles[a_lvl], identifierRho);
2513 }
2514 }
2515
2516 // Read in data that is required for the semi-implicit regrid.
2517 if (this->m_physics->getNumCdrSpecies() > 0) {
2518 const Interval interv(0, 0);
2519
2520 read<EBCellFAB>(a_handle,
2521 *m_semiImplicitRhoCDR[a_lvl],
2522 "ItoKMCGodunovStepper::semiImplicitRhoCDR",
2523 this->m_amr->getGrids(this->m_fluidRealm)[a_lvl],
2524 interv,
2525 false);
2526
2527 read<EBCellFAB>(a_handle,
2528 *m_semiImplicitConductivityCDR[a_lvl],
2529 "ItoKMCGodunovStepper::semiImplicitConductivityCDR",
2530 this->m_amr->getGrids(this->m_fluidRealm)[a_lvl],
2531 interv,
2532 false);
2533 }
2534}
2535#endif
2536
2537template <typename I, typename C, typename R, typename F>
2538void
2540{
2541 CH_TIME("ItoKMCGodunovStepper::prePlot");
2542 if (this->m_verbosity > 5) {
2543 pout() << "ItoKMCGodunovStepper::prePlot" << endl;
2544 }
2545
2547
2548 // Deposit the photons that were absorbed on the mesh during the last advance. This used to run at the top
2549 // of every advance(); it belongs here because McPhoto's mesh density has exactly two readers, both of them
2550 // output paths (McPhoto::writePlotData and McPhoto::writeCheckpointLevel), and a full deposit is a halo
2551 // exchange plus a hybrid-divergence redistribution per photon species. The checkpoint writer has no
2552 // pre-write hook, so a checkpoint written on a non-plot step now records the density from the last plot
2553 // rather than from the last step -- nothing reads that field back on restart, where the photons are
2554 // restored from their own particle datasets.
2555 for (auto solverIt = (this->m_rte)->iterator(); solverIt.ok(); ++solverIt) {
2556 RefCountedPtr<McPhoto> solver = solverIt();
2557
2558 EBAMRCellData& phi = solver->getPhi();
2559 ParticleContainer<Photon>& photons = solver->getBulkPhotons();
2560
2561 solver->depositPhotons(phi, photons, DepositionType::NGP);
2562 }
2563}
2564
2565template <typename I, typename C, typename R, typename F>
2566void
2568{
2569 CH_TIME("ItoKMCGodunovStepper::postPlot");
2570 if (this->m_verbosity > 5) {
2571 pout() << this->m_name + "::postPlot" << endl;
2572 }
2573
2574 this->m_physicsPlotVariables.clear();
2575
2576 this->plotParticles();
2577}
2578
2579template <typename I, typename C, typename R, typename F>
2580void
2582{
2583 CH_TIME("ItoKMCGodunovStepper::plotParticles");
2584 if (this->m_verbosity > 2) {
2585 pout() << this->m_name + "::plotParticles" << endl;
2586 }
2587
2588 bool plotParticles = false;
2589
2590 ParmParse pp(this->m_name.c_str());
2591
2592 pp.query("plot_particles", plotParticles);
2593
2594 if (plotParticles) {
2595
2596 for (auto solverIt = (this->m_ito)->iterator(); solverIt.ok(); ++solverIt) {
2597 const RefCountedPtr<ItoSolver>& solver = solverIt();
2598 const ParticleContainer<ItoParticle>& particles = solver->getParticles(ItoSolver::WhichContainer::Bulk);
2599
2600 // Create the output folder
2601 // Quoted: a solver name containing a space would otherwise make the shell create one directory
2602 // per word, and the file open then fails with a bare MPI_ERR_NO_SUCH_FILE from inside HDF5.
2603 std::string cmd = "mkdir -p 'particles/" + solver->getName() + "'";
2604 int success = 0;
2605 if (procID() == 0) {
2606 success = system(cmd.c_str());
2607 }
2608
2609 if (success != 0) {
2610 MayDay::Error("ItoKMCGodunovStepper::plotParticles - could not create 'particles' directory");
2611 }
2612
2613 // Set plot file name
2614 const std::string prefix = "./particles/" + solver->getName() + "/" + solver->getName();
2615 char fileChar[1000];
2616 sprintf(fileChar, "%s.step%07d.%dd.h5part", prefix.c_str(), this->m_timeStep, SpaceDim);
2617
2618 // Plot the particles directly from the live SoA container. The output datasets (id, position, weight
2619 // and the selected ItoParticle payload columns) are derived from ParticleTraits<ItoParticle>::h5PartColumns.
2620 DischargeIO::writeH5Part(std::string(fileChar), particles, this->m_amr->getProbLo(), this->m_time);
2621 }
2622 }
2623}
2624
2625#include <CD_NamespaceFooter.H>
2626
2627#endif
Average
Various averaging methods.
Definition CD_Average.H:25
Agglomeration of useful data operations.
Silly, but useful functions that override standard Chombo HDF5 IO.
EBIntersection
Enum for putting some logic into how we think about intersection between particles and EBs.
Definition CD_EBIntersection.H:22
EBRepresentation
Enum for putting some logic into how we think about EBs. This is just a simply supporting class for v...
Definition CD_EBRepresentation.H:23
@ NGP
Put the particle's entire cloud in its own cell when that cell is a cut cell.
Definition CD_IrregularDeposition.H:48
Declaration of a class which uses a semi-implicit Godunov method for Ito plasma equations.
SpeciesSubset
Enum for selecting a subset of plasma species by mobility/diffusion/charge properties.
Definition CD_ItoKMCStepper.H:43
@ ChargedDiffusive
All charged, diffusive species.
Definition CD_ItoKMCStepper.H:51
@ AllMobileOrDiffusive
All species that are mobile or diffusive.
Definition CD_ItoKMCStepper.H:47
@ ChargedMobileAndDiffusive
All charged species that are both mobile and diffusive.
Definition CD_ItoKMCStepper.H:53
@ Stationary
All stationary (non-mobile, non-diffusive) species.
Definition CD_ItoKMCStepper.H:54
@ AllMobileAndDiffusive
All species that are both mobile and diffusive.
Definition CD_ItoKMCStepper.H:48
@ AllDiffusive
All species with nonzero diffusion coefficient.
Definition CD_ItoKMCStepper.H:46
@ AllMobile
All species with nonzero mobility.
Definition CD_ItoKMCStepper.H:45
@ Charged
All charged species (any mobility/diffusion).
Definition CD_ItoKMCStepper.H:49
@ All
All plasma species.
Definition CD_ItoKMCStepper.H:44
@ ChargedMobile
All charged, mobile species.
Definition CD_ItoKMCStepper.H:50
@ ChargedMobileOrDiffusive
All charged species that are mobile or diffusive.
Definition CD_ItoKMCStepper.H:52
Agglomeration of basic MPI reductions.
Declaration of a namespace for SIMD-decorated loops over SoA particles.
Declaration of a static class containing some common useful particle routines that would otherwise be...
CD_PARTICLE_REAL ParticleReal
Floating-point type a user may use for payload columns.
Definition CD_ParticleSoA.H:156
SoA payload for Monte Carlo radiative-transfer photons.
Implementation of CD_Timer.H.
Declaration of various useful units.
static void scale(MFAMRCellData &a_lhs, const Real &a_scale) noexcept
Scale data by factor.
Definition CD_DataOps.cpp:2564
static void floor(EBAMRCellData &a_lhs, const Real a_value, const Vector< RefCountedPtr< LayoutData< VoFIterator > > > &a_vofIter)
Floor values in data holder. This sets all values below a_value to a_value.
Definition CD_DataOps.cpp:1526
static void filterSmooth(EBAMRCellData &a_data, const Real a_alpha, const int a_stride, const bool a_zeroEB) noexcept
Apply a convolved filter phi = alpha * phi_i + 0.5*(1-alpha) * [phi_(i+s) + phi_(i-s)] in each direct...
Definition CD_DataOps.cpp:680
static void multiply(EBAMRCellData &a_lhs, const EBAMRCellData &a_rhs)
Multiply data holder by another data holder.
Definition CD_DataOps.cpp:2307
static void incr(MFAMRCellData &a_lhs, const MFAMRCellData &a_rhs, const Real a_scale) noexcept
Function which increments data in the form a_lhs = a_lhs + a_rhs*a_scale for all components.
Definition CD_DataOps.cpp:881
static void setValue(LevelData< MFInterfaceFAB< T > > &a_lhs, const T &a_value)
Set value in an MFInterfaceFAB data holder.
Definition CD_DataOpsImplem.H:24
static void copy(MFAMRCellData &a_dst, const MFAMRCellData &a_src)
Copy data from one data holder to another.
Definition CD_DataOps.cpp:1262
static void averageCellToFace(EBAMRFluxData &a_faceData, const EBAMRCellData &a_cellData, const Vector< ProblemDomain > &a_domains, Vector< RefCountedPtr< LayoutData< std::array< FaceIterator, SpaceDim > > > > &a_faceIter)
Average all components of the cell-centered data to faces (arithmetic, no tangential ghost faces).
Definition CD_DataOps.cpp:149
AMR-hierarchy container of computational particles, stored per patch in Struct-of-Arrays form.
Definition CD_ParticleContainer.H:123
void clearParticles()
Drop all valid particles on every level (keeps each leaf's arena capacity).
Definition CD_ParticleContainer.H:447
AMRParticlesSoA< P, Traits > & getParticles()
The valid particles on all levels.
Definition CD_ParticleContainer.H:322
static bool ebIntersectionRaycast(const RefCountedPtr< BaseIF > &a_impFunc, const RealVect &a_oldPos, const RealVect &a_newPos, const Real &a_tolerance, Real &a_s)
Compute the intersection point between a particle path and an implicit function using a ray-casting a...
Definition CD_ParticleOpsImplem.H:224
static bool ebIntersectionBisect(const RefCountedPtr< BaseIF > &a_impFunc, const RealVect &a_oldPos, const RealVect &a_newPos, const Real &a_bisectStep, Real &a_s)
Compute the intersection point between a particle path and an implicit function using a bisection alg...
Definition CD_ParticleOpsImplem.H:175
static void setData(ParticleContainer< P, Traits > &a_particles, const std::function< void(ParticleSoA< P, Traits > &, std::size_t)> &a_functor) noexcept
Set value function for SoA containers. Lets the user set particle parameters via a (leaf,...
Definition CD_ParticleOpsImplem.H:334
Arena-backed Struct-of-Arrays particle container for a single grid patch.
Definition CD_ParticleSoA.H:655
void append(const RealVect &a_position, const double a_weight)
Append one particle with a default-constructed payload.
Definition CD_ParticleSoA.H:962
RealVect position(const std::size_t a_index) const noexcept
Position of particle i as a RealVect (by value, assembled from the scalar columns).
Definition CD_ParticleSoA.H:1195
double & weight(const std::size_t a_index) noexcept
Weight of particle i.
Definition CD_ParticleSoA.H:1229
std::size_t size() const noexcept
Number of particles currently stored.
Definition CD_ParticleSoA.H:882
double * positionColumn(const int a_dir) noexcept
Raw position component column dir (double*, for SIMD kernels).
Definition CD_ParticleSoA.H:1144
P gather(const std::size_t a_index) const
Gather particle i's payload back into the AoS payload view.
Definition CD_ParticleSoA.H:1028
void catenate(ParticleSoA &a_other)
Move every particle of another container into this one, leaving a_other empty (catenate).
Definition CD_ParticleSoA.H:1009
void remove(const std::size_t a_index) noexcept
Remove particle i using swap-and-pop (O(1), does NOT preserve order).
Definition CD_ParticleSoA.H:1040
void reserve(const std::size_t a_capacity)
Ensure capacity for at least a_capacity particles (reallocates + moves on growth).
Definition CD_ParticleSoAImplem.H:88
Implementation of ItoKMCStepper that uses a semi-implicit split-step formalism for advancing the Ito-...
Definition CD_ItoKMCGodunovStepper.H:32
virtual void setupSemiImplicitPoisson(const Real a_dt) noexcept
Set up the semi-implicit Poisson solver.
Definition CD_ItoKMCGodunovStepperImplem.H:1727
virtual void regrid(const int a_lmin, const int a_oldFinestLevel, const int a_newFinestLevel) noexcept override
Regrid methods – puts all data on the new mesh.
Definition CD_ItoKMCGodunovStepperImplem.H:919
virtual void computeDiffusionTermCDR(EBAMRCellData &m_semiImplicitRhoCDR, const Real a_dt) noexcept
Compute the diffusion term for the CDR equations as well as the resulting CDR-contributions to the sp...
Definition CD_ItoKMCGodunovStepperImplem.H:2260
virtual void allocate() noexcept override
Allocate storage required for advancing the equations.
Definition CD_ItoKMCGodunovStepperImplem.H:101
@ ReflectIto
Reflect the particle's displacement about the boundary. The deposit follows the corrected hop.
Definition CD_ItoKMCGodunovStepper.H:201
@ Inside
Deposit from inside the solid, into a covered cell that contributes nothing to rho.
Definition CD_ItoKMCGodunovStepper.H:198
@ Cancel
Deposit at the pre-hop position. Conserves charge, but biases density towards where it started.
Definition CD_ItoKMCGodunovStepper.H:199
Vector< RefCountedPtr< ParticleContainer< NoPayload > > > m_rhoDaggerParticles
Definition CD_ItoKMCGodunovStepper.H:314
virtual Real advance(const Real a_dt) override
Advance the Ito-Poisson-KMC system over a_dt.
Definition CD_ItoKMCGodunovStepperImplem.H:529
EBAMRCellData m_particleScratchSum
Definition CD_ItoKMCGodunovStepper.H:361
bool m_emitSecondaryParticlesBeforeReactions
If true, particles will be emitted before the reactive step.
Definition CD_ItoKMCGodunovStepper.H:238
virtual void allocateInternals() noexcept override
Allocate "internal" storage.
Definition CD_ItoKMCGodunovStepperImplem.H:134
virtual void stepEulerMaruyamaCDR(const Real a_dt) noexcept
Step the CDR equations according to the regular Euler-Maruyama scheme.
Definition CD_ItoKMCGodunovStepperImplem.H:2366
EBAMRCellData m_particleScratchSumSolid
Definition CD_ItoKMCGodunovStepper.H:373
DiffusiveDeposit m_diffusiveDeposit
Definition CD_ItoKMCGodunovStepper.H:243
virtual void computeConductivities(const Vector< RefCountedPtr< ParticleContainer< NoPayload > > > &a_particles, const bool a_useStoredCdrConductivity) noexcept
Compute all conductivities (cell, face, and EB) from the input point particles.
Definition CD_ItoKMCGodunovStepperImplem.H:1449
WhichAlgorithm m_algorithm
Which advancement algorithm to use.
Definition CD_ItoKMCGodunovStepper.H:248
EBAMRCellData m_semiImplicitRhoCDR
Storage for CDR densities used during the semi-implicit solve.
Definition CD_ItoKMCGodunovStepper.H:321
virtual void parseAlgorithm() noexcept
Parse advancement algorithm.
Definition CD_ItoKMCGodunovStepperImplem.H:236
virtual void clearPointParticles(const Vector< RefCountedPtr< ParticleContainer< NoPayload > > > &a_particles, const SpeciesSubset a_subset) noexcept
Clear the input particle data holders.
Definition CD_ItoKMCGodunovStepperImplem.H:1313
int m_condFilterNum
Number of filterings of the conductivity.
Definition CD_ItoKMCGodunovStepper.H:273
Vector< RefCountedPtr< ParticleContainer< NoPayload > > > m_conductivityParticles
Definition CD_ItoKMCGodunovStepper.H:303
virtual void postPlot() noexcept override
Perform post-plot operations.
Definition CD_ItoKMCGodunovStepperImplem.H:2567
EBAMRCellData m_reactiveElectricField
Definition CD_ItoKMCGodunovStepper.H:352
virtual Real computeDt() override
Compute a time step used for the advance method.
Definition CD_ItoKMCGodunovStepperImplem.H:509
Vector< EBAMRCellData > m_cdrDivD
Storage for the conservative finite-volume approximation of kappa*div(D*grad(phi)) for the CDR equati...
Definition CD_ItoKMCGodunovStepper.H:345
EBAMRCellData m_scratchSemiImplicitRhoCDR
Scratch storage for CDR contribution to space charge density.
Definition CD_ItoKMCGodunovStepper.H:334
virtual void diffuseParticlesEulerMaruyama(Vector< RefCountedPtr< ParticleContainer< NoPayload > > > &a_rhoDaggerParticles, const Real a_dt) noexcept
Perform the explicit half of the Ito advance in the Euler-Maruyama step.
Definition CD_ItoKMCGodunovStepperImplem.H:1986
virtual void parseSecondaryEmissionSpecification() noexcept
Parse when secondary particles are emitted.
Definition CD_ItoKMCGodunovStepperImplem.H:311
virtual void parseFiltering() noexcept
Parse filter settings.
Definition CD_ItoKMCGodunovStepperImplem.H:261
virtual void parseRuntimeOptions() noexcept override
Parse run-time options.
Definition CD_ItoKMCGodunovStepperImplem.H:216
Real m_condFilterAlpha
Factor for strided filter. Alpha=0.5 yields a bilinear filter.
Definition CD_ItoKMCGodunovStepper.H:283
EBAMRCellData m_particleScratchSolid
Definition CD_ItoKMCGodunovStepper.H:367
virtual void depositPointParticles(const Vector< RefCountedPtr< ParticleContainer< NoPayload > > > &a_particles, const SpeciesSubset a_subset) noexcept
Deposit the input point particles on the mesh.
Definition CD_ItoKMCGodunovStepperImplem.H:1211
virtual bool solvePoisson() noexcept override
Solve the electrostatic problem.
Definition CD_ItoKMCGodunovStepperImplem.H:1862
virtual void computeFaceConductivity() noexcept
Compute the cell-centered conductivity.
Definition CD_ItoKMCGodunovStepperImplem.H:1550
virtual void computeCellConductivity(EBAMRCellData &a_conductivityCell, const Vector< RefCountedPtr< ParticleContainer< NoPayload > > > &a_particles, const bool a_useStoredCdrConductivity) noexcept
Compute the cell-centered conductivity.
Definition CD_ItoKMCGodunovStepperImplem.H:1464
EBAMRCellData m_fluidScratchSolid
Definition CD_ItoKMCGodunovStepper.H:379
int m_condFilterMaxStride
Stride when filtering the conductivity.
Definition CD_ItoKMCGodunovStepper.H:278
EBAMRCellData m_semiImplicitConductivityCDR
Storage for conductivity term due to mobile CDR species.
Definition CD_ItoKMCGodunovStepper.H:328
virtual void removeCoveredPointParticles(Vector< RefCountedPtr< ParticleContainer< NoPayload > > > &a_particles, const EBRepresentation a_representation, const Real a_tolerance) const noexcept
Remove covered particles.
Definition CD_ItoKMCGodunovStepperImplem.H:1764
virtual void remapPointParticles(Vector< RefCountedPtr< ParticleContainer< NoPayload > > > &a_particles, const SpeciesSubset a_subset) noexcept
Remap the input point particles.
Definition CD_ItoKMCGodunovStepperImplem.H:1106
virtual void prePlot() noexcept override
Perform pre-plot operations.
Definition CD_ItoKMCGodunovStepperImplem.H:2539
virtual ~ItoKMCGodunovStepper()
Destructor. Does nothing.
Definition CD_ItoKMCGodunovStepperImplem.H:75
virtual void setOldPositions() noexcept
Set the starting positions for the ItoSolver particles.
Definition CD_ItoKMCGodunovStepperImplem.H:1067
virtual void parseDiffusiveDeposit() noexcept
Parse what happens to a diffusion hop that would cross the embedded boundary.
Definition CD_ItoKMCGodunovStepperImplem.H:439
virtual void parseRhoDaggerHop() noexcept
Parse whether the stochastic diffusion hop enters rho^dagger.
Definition CD_ItoKMCGodunovStepperImplem.H:475
virtual void computeSemiImplicitRho() noexcept
Set up the space charge density for the regrid operation.
Definition CD_ItoKMCGodunovStepperImplem.H:1585
virtual void advanceEulerMaruyama(const Real a_dt) noexcept
Definition CD_ItoKMCGodunovStepperImplem.H:1901
virtual void preRegrid(const int a_lmin, const int a_oldFinestLevel) noexcept override
Perform pre-regrid operations.
Definition CD_ItoKMCGodunovStepperImplem.H:880
virtual void registerOperators() noexcept override
Register operators used for the simulation.
Definition CD_ItoKMCGodunovStepperImplem.H:85
virtual RealVect reflectDiffusionHop(const RealVect &a_pos, const RealVect &a_disp, const Real a_fOld, const Real a_dx, const EBIntersection a_intersectionAlg, const Real a_bisectStep) const noexcept
Reflect a rho^dagger deposit displacement that crosses the embedded boundary back into the fluid.
Definition CD_ItoKMCGodunovStepperImplem.H:342
EBAMRCellData m_scratchSemiImplicitConductivityCDR
Scratch storage for CDR contribution to conductivity.
Definition CD_ItoKMCGodunovStepper.H:340
virtual void plotParticles() const noexcept
Utility function for plotting the ItoSolver particles. These are written in a particles folder.
Definition CD_ItoKMCGodunovStepperImplem.H:2581
ItoKMCGodunovStepper()=delete
Disallowed default constructor. Use the full constructor.
Vector< RefCountedPtr< ParticleContainer< NoPayload > > > m_irregularParticles
Definition CD_ItoKMCGodunovStepper.H:308
Real m_rhoFilterAlpha
Factor for strided filter. Alpha=0.5 yields a bilinear filter.
Definition CD_ItoKMCGodunovStepper.H:268
int m_rhoFilterNum
Number of filterings when computing the semi-implicit space charge density.
Definition CD_ItoKMCGodunovStepper.H:258
virtual void parseReactiveFieldCentering() noexcept
Parse the time-centering of the electric field used for the reactive substep.
Definition CD_ItoKMCGodunovStepperImplem.H:489
virtual void parseCheckpointParticles() noexcept
Parse checkpoint-restart functionality.
Definition CD_ItoKMCGodunovStepperImplem.H:297
virtual void barrier() const noexcept
Set an MPI barrier if using debug mode.
Definition CD_ItoKMCGodunovStepperImplem.H:182
virtual void parseOptions() noexcept override
Parse options.
Definition CD_ItoKMCGodunovStepperImplem.H:196
int m_rhoFilterMaxStride
Stride when filtering the space charge density.
Definition CD_ItoKMCGodunovStepper.H:263
virtual void computeCdrConductivity() noexcept
Compute the CDR contribution to the semi-implicit conductivity, i.e. sum(|Z| * phi * mu).
Definition CD_ItoKMCGodunovStepperImplem.H:1419
virtual void stepEulerMaruyamaParticles(const Real a_dt) noexcept
Step the particles according to the regular Euler-Maruyama scheme.
Definition CD_ItoKMCGodunovStepperImplem.H:2309
virtual void copyConductivityParticles(Vector< RefCountedPtr< ParticleContainer< NoPayload > > > &a_conductivityParticles) noexcept
Copy particles from the ItoSolver into PointParticles whose weight are ItoParticle::m_weight * ItoPar...
Definition CD_ItoKMCGodunovStepperImplem.H:1804
Abstract TimeStepper for the Ito-KMC-Poisson system of equations.
Definition CD_ItoKMCStepper.H:66
RefCountedPtr< SurfaceODESolver< 1 > > m_sigmaSolver
Definition CD_ItoKMCStepper.H:439
EBAMRCellData m_conductivityCell
Definition CD_ItoKMCStepper.H:721
virtual void parseRuntimeOptions() noexcept override
Parse runtime configurable options.
Definition CD_ItoKMCStepperImplem.H:173
phase::which_phase m_plasmaPhase
Definition CD_ItoKMCStepper.H:408
virtual void computeElectricField(EBAMRCellData &a_electricField, const phase::which_phase a_phase) const noexcept
Definition CD_ItoKMCStepperImplem.H:1978
EBAMRCellData m_electricFieldParticle
Definition CD_ItoKMCStepper.H:791
virtual void computeSpaceChargeDensity() noexcept
Definition CD_ItoKMCStepperImplem.H:2005
virtual void fillNeutralDensity() noexcept
Definition CD_ItoKMCStepperImplem.H:1880
EBAMRCellData m_physicsPlotVariables
Definition CD_ItoKMCStepper.H:710
virtual void remapParticles(const SpeciesSubset a_speciesSubset) noexcept
Definition CD_ItoKMCStepperImplem.H:2728
RefCountedPtr< FieldSolver > m_fieldSolver
Definition CD_ItoKMCStepper.H:434
virtual void registerOperators() noexcept override
Register operators used for the simulation.
Definition CD_ItoKMCStepperImplem.H:1651
EBAMRCellData m_particleScratch1
Definition CD_ItoKMCStepper.H:824
virtual void multiplyCdrVelocitiesByMobilities() noexcept
Definition CD_ItoKMCStepperImplem.H:3023
virtual void intersectParticles(const SpeciesSubset a_speciesSubset, const bool a_delete, const std::function< void(ParticleSoA< ItoParticle > &, std::size_t)> a_nonDeletionModifier=[](ParticleSoA< ItoParticle > &, std::size_t) -> void { return;}) noexcept
Definition CD_ItoKMCStepperImplem.H:2300
ItoKMCStepper() noexcept
Definition CD_ItoKMCStepperImplem.H:98
virtual void depositParticles(const SpeciesSubset a_speciesSubset) noexcept
Definition CD_ItoKMCStepperImplem.H:2843
Vector< EBAMRCellData > m_cdrMobilities
Definition CD_ItoKMCStepper.H:660
virtual void parseOptions() noexcept
Parse options.
Definition CD_ItoKMCStepperImplem.H:152
virtual void preRegrid(const int a_lmin, const int a_oldFinestLevel) noexcept override
Perform pre-regrid operations - storing relevant data from the old grids.
Definition CD_ItoKMCStepperImplem.H:1703
EBAMRCellData m_fluidScratch1
Definition CD_ItoKMCStepper.H:814
virtual void computeDriftVelocities() noexcept
Definition CD_ItoKMCStepperImplem.H:3049
EBAMRCellData m_electricFieldFluid
Definition CD_ItoKMCStepper.H:786
RefCountedPtr< CdrLayout< CdrSolver > > m_cdr
Definition CD_ItoKMCStepper.H:424
virtual Real computeDt() override
Compute a time step used for the advance method.
Definition CD_ItoKMCStepperImplem.H:1522
virtual void coarsenCDRSolvers(const bool a_interpGhosts) noexcept
Definition CD_ItoKMCStepperImplem.H:5110
EBAMRFluxData m_conductivityFace
Definition CD_ItoKMCStepper.H:727
virtual void computeDiffusionCoefficients() noexcept
Definition CD_ItoKMCStepperImplem.H:3307
virtual void allocateInternals() noexcept
Allocate "internal" storage.
Definition CD_ItoKMCStepperImplem.H:621
virtual void setCdrVelocityFunctions() noexcept
Definition CD_ItoKMCStepperImplem.H:2989
RefCountedPtr< ItoKMCPhysics > m_physics
Definition CD_ItoKMCStepper.H:414
virtual void allocate() noexcept override
Allocate storage for solvers.
Definition CD_ItoKMCStepperImplem.H:603
RefCountedPtr< RtLayout< McPhoto > > m_rte
Definition CD_ItoKMCStepper.H:429
RefCountedPtr< ItoLayout< ItoSolver > > m_ito
Definition CD_ItoKMCStepper.H:419
virtual void prePlot() noexcept override
Perform pre-plot operations.
Definition CD_ItoKMCStepperImplem.H:1670
virtual void setItoVelocityFunctions() noexcept
Definition CD_ItoKMCStepperImplem.H:2958
int m_verbosity
Class verbosity.
Definition CD_TimeStepper.H:343
RefCountedPtr< ComputationalGeometry > m_computationalGeometry
Computational geometry.
Definition CD_TimeStepper.H:375
int m_timeStep
Time step.
Definition CD_TimeStepper.H:348
RefCountedPtr< AmrMesh > m_amr
AmrMesh.
Definition CD_TimeStepper.H:370
Class which is used for run-time monitoring of events.
Definition CD_Timer.H:32
void writeH5Part(std::string a_filename, const ParticleContainer< P, Traits > &a_particles, RealVect a_shift, Real a_time) noexcept
Write an SoA particle container to an H5Part file (quick visualization).
Definition CD_DischargeIOImplem.H:201
Real sum(const Real &a_value) noexcept
Compute the sum across all MPI ranks.
Definition CD_ParallelOpsImplem.H:354
void barrier() noexcept
MPI barrier.
Definition CD_ParallelOpsImplem.H:26
ALWAYS_INLINE void loop(const ParticleSoA< P, Traits > &a_soa, Functor &&a_kernel)
Launch a kernel over every particle in a ParticleSoA, decorating the loop with CD_PRAGMA_SIMD.
Definition CD_ParticleLoops.H:87
void deleteParticles(ParticleSoA< P, Traits > &a_particles, const Real a_weightThresh) noexcept
Remove particles from an SoA container if their weight is below the threshold (swap-and-pop).
Definition CD_ParticleManagementImplem.H:788
constexpr Real eps0
Permittivity of free space.
Definition CD_Units.H:30
constexpr Real Qe
Elementary charge.
Definition CD_Units.H:35
@ solid
Solid (dielectric) phase.
Definition CD_MultiFluidIndexSpace.H:40
@ gas
Gas phase.
Definition CD_MultiFluidIndexSpace.H:39
SoA payload for ItoSolver particles, i.e. drifting Brownian walkers.
Definition CD_ItoParticle.H:31
ParticleReal scratch_x
Scratch vector storage, x-component.
Definition CD_ItoParticle.H:49
ParticleReal scratch_y
Scratch vector storage, y-component.
Definition CD_ItoParticle.H:50
ParticleReal scratch_z
Scratch vector storage, z-component.
Definition CD_ItoParticle.H:52