chombo-discharge
Loading...
Searching...
No Matches
CD_ItoKMCStepperImplem.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_ITOKMCSTEPPERIMPLEM_H
14#define CD_ITOKMCSTEPPERIMPLEM_H
15
16// Std includes
17#include <limits>
18
19// Chombo includes
20#include <ParmParse.H>
21#include <BinFab.H>
22#include <BoxIterator.H>
23
24// Our includes
26#include <CD_ItoKMCStepper.H>
28#include <CD_ParticleOps.H>
29#include <CD_ParticleLoops.H>
30#include <CD_DataOps.H>
31#include <CD_ParallelOps.H>
32#include <CD_Units.H>
33#include <CD_Timer.H>
34#include <CD_Location.H>
35#include <CD_NamespaceHeader.H>
36
37using namespace Physics::ItoKMC;
38
39namespace {
40// SoA per-cell extract/rebuild bridge for the ItoKMC reaction kernels. The reaction interface operates on
41// per-cell SoA scratch containers (one small ParticleSoA<P> per grid cell) extracted from the leaves; the
42// mutated scratches are concatenated back into the leaf. Mirrors ItoSolver::makeSuperparticles. The per-cell
43// vector is indexed by the box's Fortran cell offset (Box::index), which matches ParticleSoA::sortByCell.
44
45// Cell-sort a_leaf and extract each cell into a_cells[Box::index(iv)] (one ParticleSoA<P> per cell).
46template <typename P, typename Traits>
47inline void
48binLeafToCells(std::vector<ParticleSoA<P, Traits>>& a_cells,
50 const Box& a_box,
51 const Real a_dx,
52 const RealVect& a_probLo) noexcept
53{
54 a_leaf.sortByCell(a_box, a_dx * RealVect::Unit, a_probLo);
55
56 a_cells.clear();
57 a_cells.resize(a_box.numPts());
58 for (std::size_t c = 0; c < a_leaf.numCells(); c++) {
59 a_leaf.extractCell(c, a_cells[c]);
60 }
61}
62
63// Rebuild a_leaf from the per-cell scratch vector (concatenate all cells, then swap into the leaf).
64// The cells are written back in Fortran cell order, so the rebuilt leaf is cell-sorted by construction
65// and adopts the CSR mapping rather than letting the next sortByCell() rediscover it.
66template <typename P, typename Traits>
67inline void
68rebuildLeafFromCells(ParticleSoA<P, Traits>& a_leaf,
69 const std::vector<ParticleSoA<P, Traits>>& a_cells,
70 const Box& a_box,
71 const Real a_dx,
72 const RealVect& a_probLo) noexcept
73{
74 CH_assert(a_cells.size() == static_cast<std::size_t>(a_box.numPts()));
75
76 // Prefix-sum the per-cell counts into the CSR start offsets. This also gives the known total, so the
77 // append loop below allocates once instead of growing geometrically (O(log N) reallocations) on every
78 // reaction-kernel step.
79 std::vector<std::size_t> cellStart(a_cells.size() + 1, 0);
80 for (std::size_t c = 0; c < a_cells.size(); c++) {
81 cellStart[c + 1] = cellStart[c] + a_cells[c].size();
82 }
83
85 rebuilt.reserve(cellStart.back());
86
87 for (const ParticleSoA<P, Traits>& cell : a_cells) {
88 rebuilt.append(cell);
89 }
90
91 a_leaf.swap(rebuilt);
92 a_leaf.adoptCellSort(a_box, a_dx * RealVect::Unit, a_probLo, std::move(cellStart));
94
95} // namespace
96
97template <typename I, typename C, typename R, typename F>
100 CH_TIME("ItoKMCStepper::ItoKMCStepper");
101
102 m_verbosity = -1;
103 m_profile = false;
104 m_name = "ItoKMCStepper";
106 m_dt = 0.0;
107 m_prevDt = -1.0;
108 m_maxGrowthDt = 1.E99;
109 m_maxShrinkDt = 1.E99;
110 m_time = 0.0;
112 m_loadPerCell = 1.0;
113 m_redistributeCDR = true;
114 m_cdrProductInjection = CdrProductInjection::Particle;
120 m_physicsDtFactor = 1.0;
121 m_maxParticleDiffusionCFL = std::numeric_limits<Real>::max();
122 m_minParticleAdvectionDiffusionCFL = std::numeric_limits<Real>::max();
123 m_maxParticleAdvectionDiffusionCFL = std::numeric_limits<Real>::max();
125 m_relaxTimeFactor = std::numeric_limits<Real>::max();
126 m_minDt = std::numeric_limits<Real>::min();
127 m_maxDt = std::numeric_limits<Real>::max();
128 m_physicsDt = std::numeric_limits<Real>::max();
129 m_maxReducedField = 0.0;
130}
132template <typename I, typename C, typename R, typename F>
133ItoKMCStepper<I, C, R, F>::ItoKMCStepper(RefCountedPtr<ItoKMCPhysics>& a_physics) noexcept : ItoKMCStepper<I, C, R, F>()
134{
135 CH_TIME("ItoKMCStepper::ItoKMCStepper(RefCountrPtr<ItoKMCPhysics>)");
136
137 m_physics = a_physics;
138
139 if (m_physics->getNumPlasmaSpecies() == 0) {
140 MayDay::Abort("ItoKMCStepper::ItoKMCStepper -- numPlasmaSpecies = 0, there's no problem to solve here!");
141 }
142}
143
144template <typename I, typename C, typename R, typename F>
146{
147 CH_TIME("ItoKMCStepper::~ItoKMCStepper");
148}
149
150template <typename I, typename C, typename R, typename F>
151void
153{
154 CH_TIME("ItoKMCStepper::parseOptions");
155 if (m_verbosity > 5) {
156 pout() << m_name + "::parseOptions" << endl;
157 }
158
159 this->parseVerbosity();
160 this->parseExitOnFailure();
161 this->parseRedistributeCDR();
162 this->parseCdrProducts();
163 this->parsePlotVariables();
164 this->parseSuperParticles();
165 this->parseDualGrid();
166 this->parseLoadBalance();
168 this->parseParametersEB();
169}
170
171template <typename I, typename C, typename R, typename F>
172void
174{
175 CH_TIME("ItoKMCStepper::parseRuntimeOptions");
176 if (m_verbosity > 5) {
177 pout() << m_name + "::parseRuntimeOptions" << endl;
178 }
179
180 this->parseVerbosity();
181 this->parseExitOnFailure();
182 this->parseRedistributeCDR();
184 this->parsePlotVariables();
185 this->parseSuperParticles();
186 this->parseLoadBalance();
188 this->parseParametersEB();
189
190 m_ito->parseRuntimeOptions();
191 m_cdr->parseRuntimeOptions();
192 m_fieldSolver->parseRuntimeOptions();
193 m_rte->parseRuntimeOptions();
194 m_sigmaSolver->parseRuntimeOptions();
195
196 m_physics->parseRuntimeOptions();
197}
198
199template <typename I, typename C, typename R, typename F>
200void
202{
203 CH_TIME("ItoKMCStepper::parseVerbosity");
204 if (m_verbosity > 5) {
205 pout() << m_name + "::parseVerbosity" << endl;
206 }
207
208 ParmParse pp(m_name.c_str());
209
210 pp.get("verbosity", m_verbosity);
211 pp.get("profile", m_profile);
212}
213
214template <typename I, typename C, typename R, typename F>
215void
217{
218 CH_TIME("ItoKMCStepper::parseExitOnFailure");
219 if (m_verbosity > 5) {
220 pout() << m_name + "::parseExitOnFailure" << endl;
221 }
222
223 ParmParse pp(m_name.c_str());
224
225 pp.get("abort_on_failure", m_abortOnFailure);
226}
227
228template <typename I, typename C, typename R, typename F>
229void
231{
232 CH_TIME("ItoKMCStepper::parseRedistributeCDR");
233 if (m_verbosity > 5) {
234 pout() << m_name + "::parseRedistributeCDR" << endl;
235 }
236
237 ParmParse pp(m_name.c_str());
239 pp.get("redistribute_cdr", m_redistributeCDR);
240}
241
242template <typename I, typename C, typename R, typename F>
243void
245{
246 CH_TIME("ItoKMCStepper::parseCdrProducts");
247 if (m_verbosity > 5) {
248 pout() << m_name + "::parseCdrProducts" << endl;
249 }
251 ParmParse pp(m_name.c_str());
252
253 std::string str;
254
255 pp.get("cdr_products", str);
257 if (str == "mesh") {
258 m_cdrProductInjection = CdrProductInjection::Mesh;
259 }
260 else if (str == "particle") {
261 m_cdrProductInjection = CdrProductInjection::Particle;
263 else {
264 MayDay::Error(("ItoKMCStepper::parseCdrProducts - unknown '" + m_name + ".cdr_products = " + str +
265 "', must be 'mesh' or 'particle'")
266 .c_str());
267 }
268}
269
270template <typename I, typename C, typename R, typename F>
271void
273{
274 CH_TIME("ItoKMCStepper::parsePlotVariables");
275 if (m_verbosity > 5) {
276 pout() << m_name + "::parsePlotVariables" << endl;
277 }
278
280 m_plotCurrentDensity = false;
282
283 // Read in plot variables.
284 ParmParse pp(m_name.c_str());
285 const int num = pp.countval("plt_vars");
286
287 if (num > 0) {
288 Vector<std::string> str(num);
289 pp.getarr("plt_vars", str, 0, num);
290
291 // Set plot variables
292 for (int i = 0; i < num; i++) {
293 if (str[i] == "conductivity") {
295 }
296 else if (str[i] == "current_density") {
297 m_plotCurrentDensity = true;
298 }
299 else if (str[i] == "particles_per_patch") {
300 m_plotParticlesPerPatch = true;
301 }
302 }
303 }
304}
305
306template <typename I, typename C, typename R, typename F>
307void
309{
310 CH_TIME("ItoKMCStepper::parseSuperParticles");
311 if (m_verbosity > 5) {
312 pout() << m_name + "::parseSuperParticles" << endl;
313 }
314
315 ParmParse pp(m_name.c_str());
316
317 // Cadence only. What to merge to, and whether to merge at a regrid, are properties of the solver and
318 // live there (ItoSolver.particles_per_cell / ItoSolver.regrid_superparticles). This is a property of
319 // the advance, which the solver has no notion of, so it stays here.
320 pp.get("merge_interval", m_mergeInterval);
321}
322
323template <typename I, typename C, typename R, typename F>
324void
326{
327 CH_TIME("ItoKMCStepper::parseDualGrid");
328 if (m_verbosity > 5) {
329 pout() << m_name + "::parseDualGrid" << endl;
330 }
332 ParmParse pp(m_name.c_str());
333
334 pp.get("dual_grid", m_dualGrid);
335
336 if (m_dualGrid) {
337 m_particleRealm = "ParticleRealm";
338
340 }
341 else {
342 m_particleRealm = m_fluidRealm;
343 }
344}
345
346template <typename I, typename C, typename R, typename F>
347void
349{
350 CH_TIME("ItoKMCStepper::parseLoadBalance");
351 if (m_verbosity > 5) {
352 pout() << m_name + "::parseLoadBalance" << endl;
353 }
354
355 ParmParse pp(m_name.c_str());
356
357 std::string str;
358
359 pp.get("load_balance_particles", m_loadBalanceParticles);
360 pp.get("load_balance_fluid", m_loadBalanceFluid);
361 pp.get("load_per_cell", m_loadPerCell);
362
363 // Box sorting for load balancing
364 pp.get("box_sorting", str);
365 if (str == "none") {
366 m_boxSort = BoxSorting::None;
367 }
368 else if (str == "std") {
369 m_boxSort = BoxSorting::Std;
370 }
371 else if (str == "shuffle") {
372 m_boxSort = BoxSorting::Shuffle;
373 }
374 else if (str == "morton") {
375 m_boxSort = BoxSorting::Morton;
376 }
377 else if (str == "hilbert") {
378 m_boxSort = BoxSorting::Hilbert;
379 }
380 else {
381 const std::string err = "ItoKMCStepper::parseLoadBalance - 'box_sorting = " + str + "' not recognized";
382
383 MayDay::Error(err.c_str());
384 }
385
386 // Get the load balancing index.
387 const int numIndices = pp.countval("load_indices");
388
389 if (numIndices > 0) {
390 pp.getarr("load_indices", m_loadBalanceIndices, 0, numIndices);
391 }
392 else {
393 const std::string err = "ItoKMCStepper::parseLoadBalance - 'load_indices' argument has zero entries";
394
395 MayDay::Error(err.c_str());
396 }
397}
398
399template <typename I, typename C, typename R, typename F>
400void
402{
403 CH_TIME("ItoKMCStepper::parseTimeStepRestrictions");
404 if (m_verbosity > 5) {
405 pout() << m_name + "::parseTimeStepRestrictions" << endl;
406 }
407
408 ParmParse pp(m_name.c_str());
409
410 pp.get("min_particle_advection_cfl", m_minParticleAdvectionCFL);
411 pp.get("max_particle_advection_cfl", m_maxParticleAdvectionCFL);
412 pp.get("min_particle_diffusion_cfl", m_minParticleDiffusionCFL);
413 pp.get("max_particle_diffusion_cfl", m_maxParticleDiffusionCFL);
414 pp.get("min_particle_advection_diffusion_cfl", m_minParticleAdvectionDiffusionCFL);
415 pp.get("max_particle_advection_diffusion_cfl", m_maxParticleAdvectionDiffusionCFL);
416 pp.get("fluid_advection_diffusion_cfl", m_fluidAdvectionDiffusionCFL);
417 pp.get("relax_dt_factor", m_relaxTimeFactor);
418 pp.get("min_dt", m_minDt);
419 pp.get("max_dt", m_maxDt);
420 pp.get("max_growth_dt", m_maxGrowthDt);
421 pp.get("max_shrink_dt", m_maxShrinkDt);
422 pp.get("physics_dt_factor", m_physicsDtFactor);
423
424 if (m_maxGrowthDt <= 1.0) {
425 MayDay::Error("ItoKMCStepper::parseTimeStepRestrictions() - must have max_growth_dt > 1.0");
426 }
427
428 if (m_maxShrinkDt <= 1.0) {
429 MayDay::Error("ItoKMCStepper::parseTimeStepRestrictions() - must have max_shrink_dt > 1.0");
430 }
431
432 if (m_relaxTimeFactor <= 0.0) {
433 MayDay::Error("ItoKMCStepper::parseTimeStepRestrictions() - must have relax_dt > 0.0");
434 }
435
436 if (m_minDt < 0.0) {
437 MayDay::Error("ItoKMCStepper::parseTimeStepRestrictions() - must have min_dt >= 0.0");
438 }
439
440 if (m_maxDt < 0.0) {
441 MayDay::Error("ItoKMCStepper::parseTimeStepRestrictions() - must have max_dt >= 0.0");
442 }
443
444 if (m_maxParticleAdvectionCFL <= 0.0) {
445 MayDay::Error("ItoKMCStepper::parseTimeStepRestrictions() - must have max_particle_advection_cfl > 0.0");
446 }
447
448 if (m_minParticleAdvectionCFL < 0.0) {
449 MayDay::Error("ItoKMCStepper::parseTimeStepRestrictions() - must have min_particle_advection_cfl >= 0.0");
450 }
451
452 if (m_maxParticleDiffusionCFL <= 0.0) {
453 MayDay::Error("ItoKMCStepper::parseTimeStepRestrictions() - must have particle_diffusion_cfl > 0.0");
454 }
455
456 if (m_minParticleDiffusionCFL < 0.0) {
457 MayDay::Error("ItoKMCStepper::parseTimeStepRestrictions() - must have particle_diffusion_cfl >= 0.0");
458 }
459
461 MayDay::Error("ItoKMCStepper::parseTimeStepRestrictions() - must have particle_advection_diffusion_cfl > 0.0");
462 }
463
465 MayDay::Error("ItoKMCStepper::parseTimeStepRestrictions() - must have particle_advection_diffusion_cfl >= 0.0");
466 }
467
468 if (m_fluidAdvectionDiffusionCFL <= 0.0) {
469 MayDay::Error("ItoKMCStepper::parseTimeStepRestrictions() - must have fluid_advection_diffusion_cfl > 0.0");
470 }
471
472 if (m_physicsDtFactor <= 0.0) {
473 MayDay::Error("ItoKMCStepper::parseTimeStepRestrictions() - must have physics_dft_factor > 0.0");
474 }
475}
476
477template <typename I, typename C, typename R, typename F>
478void
480{
481 CH_TIME("ItoKMCStepper::parseTimeStepRestrictions");
482 if (m_verbosity > 5) {
483 pout() << m_name + "::parseTimeStepRestrictions" << endl;
484 }
485
486 ParmParse pp(m_name.c_str());
487
488 std::string str;
489
490 pp.get("eb_tolerance", m_toleranceEB);
491}
492
493template <typename I, typename C, typename R, typename F>
494void
496{
497 CH_TIME("ItoKMCStepper::setupSolver");
498 if (m_verbosity > 5) {
499 pout() << m_name + "::setupSolvers" << endl;
500 }
501
502 this->setupIto();
503 this->setupCdr();
504 this->setupPoisson();
506 this->setupSigma();
507}
508
509template <typename I, typename C, typename R, typename F>
510void
512{
513 CH_TIME("ItoKMCStepper::setupIto");
514 if (m_verbosity > 5) {
515 pout() << m_name + "::setupIto" << endl;
516 }
517
519 m_ito = factory.newLayout(m_physics->getItoSpecies());
520
521 m_ito->parseOptions();
522 m_ito->setAmr(m_amr);
523 m_ito->setPhase(m_plasmaPhase);
524 m_ito->setComputationalGeometry(m_computationalGeometry);
525 m_ito->setRealm(m_particleRealm);
526}
527
528template <typename I, typename C, typename R, typename F>
529void
531{
532 CH_TIME("ItoKMCStepper::setupCdr");
533 if (m_verbosity > 5) {
534 pout() << m_name + "::setupCdr" << endl;
535 }
536
538 m_cdr = factory.newLayout(m_physics->getCdrSpecies());
539
540 m_cdr->parseOptions();
541 m_cdr->setAmr(m_amr);
542 m_cdr->setPhase(m_plasmaPhase);
543 m_cdr->setComputationalGeometry(m_computationalGeometry);
544 m_cdr->setRealm(m_fluidRealm);
545}
546
547template <typename I, typename C, typename R, typename F>
548void
550{
551 CH_TIME("ItoKMCStepper::setupRadiativeTransfer");
552 if (m_verbosity > 5) {
553 pout() << m_name + "::setupRadiativeTransfer" << endl;
554 }
555
556 RtFactory<McPhoto, R> factory;
557 m_rte = factory.newLayout(m_physics->getRtSpecies());
558
559 m_rte->parseOptions();
560 m_rte->setPhase(m_plasmaPhase);
561 m_rte->setAmr(m_amr);
562 m_rte->setComputationalGeometry(m_computationalGeometry);
563 m_rte->setRealm(m_particleRealm);
564 m_rte->sanityCheck();
565}
566
567template <typename I, typename C, typename R, typename F>
568void
570{
571 CH_TIME("ItoKMCStepper::setupPoisson");
572 if (m_verbosity > 5) {
573 pout() << m_name + "::setupPoisson" << endl;
574 }
575
576 m_fieldSolver = RefCountedPtr<FieldSolver>(new F());
577 m_fieldSolver->parseOptions();
578 m_fieldSolver->setAmr(m_amr);
579 m_fieldSolver->setComputationalGeometry(m_computationalGeometry);
580 m_fieldSolver->setVoltage(m_voltage);
581 m_fieldSolver->setRealm(m_fluidRealm);
582}
583
584template <typename I, typename C, typename R, typename F>
585void
587{
588 CH_TIME("ItoKMCStepper::setupSigma");
589 if (m_verbosity > 5) {
590 pout() << m_name + "::setupSigma" << endl;
591 }
592
593 m_sigmaSolver = RefCountedPtr<SurfaceODESolver<1>>(new SurfaceODESolver<1>(m_amr));
594 m_sigmaSolver->parseOptions();
595 m_sigmaSolver->setRealm(m_fluidRealm);
596 m_sigmaSolver->setPhase(m_plasmaPhase);
597 m_sigmaSolver->setName("Surface charge");
598 m_sigmaSolver->setTime(0, 0.0, 0.0);
599}
600
601template <typename I, typename C, typename R, typename F>
602void
604{
605 CH_TIME("ItoKMCStepper::allocate");
606 if (m_verbosity > 5) {
607 pout() << m_name + "::allocate" << endl;
608 }
609
610 m_ito->allocate();
611 m_cdr->allocate();
612 m_rte->allocate();
613 m_fieldSolver->allocate();
614 m_sigmaSolver->allocate();
615
616 this->allocateInternals();
617}
618
619template <typename I, typename C, typename R, typename F>
620void
622{
623 CH_TIME("ItoKMCStepper::allocateInternals");
624 if (m_verbosity > 5) {
625 pout() << m_name + "::allocateInternals" << endl;
626 }
627
628 const int numItoSpecies = m_physics->getNumItoSpecies();
629 const int numCdrSpecies = m_physics->getNumCdrSpecies();
630 const int numPlasmaSpecies = m_physics->getNumPlasmaSpecies();
631 const int numPhotonSpecies = m_physics->getNumPhotonSpecies();
632
633 CH_assert(numPlasmaSpecies > 0);
634
635 // Scratch data.
637 m_amr->allocate(m_fluidScratchD, m_fluidRealm, m_plasmaPhase, SpaceDim);
639
643
644 // Storage for neutral density
646
647 // Storage for conductivities on cell, cell faces, and EB faces.
651
652 // Electric field data on both realms.
655
656 // Data for CDR-based solver mobilities
657 m_cdrMobilities.resize(numCdrSpecies);
658 m_cdrProducts.resize(numCdrSpecies);
659 for (int i = 0; i < numCdrSpecies; i++) {
661
662 m_cdrProducts[i] = RefCountedPtr<ParticleContainer<NoPayload>>(new ParticleContainer<NoPayload>());
663 m_amr->allocate(*m_cdrProducts[i], m_particleRealm);
664 }
665
666 // Fluid-realm scratch shared by computeMobilities() and computeDiffusionCoefficients().
667 m_fluidScratchIto.resize(numItoSpecies);
668 for (int i = 0; i < numItoSpecies; i++) {
670 }
671
672 // Storage for the density gradients
673 m_fluidGradPhiIto.resize(numItoSpecies);
674 m_fluidPhiIto.resize(numItoSpecies);
675 m_fluidGradPhiCDR.resize(numCdrSpecies);
676 for (int i = 0; i < numItoSpecies; i++) {
677 m_amr->allocate(m_fluidGradPhiIto[i], m_fluidRealm, m_plasmaPhase, SpaceDim);
679 }
680 for (int i = 0; i < numCdrSpecies; i++) {
681 m_amr->allocate(m_fluidGradPhiCDR[i], m_fluidRealm, m_plasmaPhase, SpaceDim);
682 }
683
684 // Storage for secondary particle and photon emission
685 m_secondaryParticles.resize(numItoSpecies);
686 m_secondaryPhotons.resize(numPhotonSpecies);
687
688 m_cdrFluxes.resize(numCdrSpecies);
689 m_cdrFluxesExtrap.resize(numCdrSpecies);
690
691 for (int i = 0; i < numItoSpecies; i++) {
692 m_secondaryParticles[i] = RefCountedPtr<ParticleContainer<ItoParticle>>(new ParticleContainer<ItoParticle>());
694 }
695
696 for (int i = 0; i < numPhotonSpecies; i++) {
697 m_secondaryPhotons[i] = RefCountedPtr<ParticleContainer<Photon>>(new ParticleContainer<Photon>());
699 }
700
701 for (int i = 0; i < numCdrSpecies; i++) {
704 }
705
706 // Current density.
707 m_amr->allocate(m_currentDensity, m_fluidRealm, m_plasmaPhase, SpaceDim);
708
709 // Storage for the physics time step
710 m_amr->allocate(m_kmcDt, m_fluidRealm, m_plasmaPhase, 1);
711
712 // Storage required for the reaction network.
713 m_amr->allocate(m_fluidPPC, m_fluidRealm, m_plasmaPhase, numPlasmaSpecies);
714
715 if (numItoSpecies > 0) {
716 m_amr->allocate(m_particleItoPPC, m_particleRealm, m_plasmaPhase, numItoSpecies);
717 m_amr->allocate(m_particleOldItoPPC, m_particleRealm, m_plasmaPhase, numItoSpecies);
718 }
719 else {
720 // Allocate some dummy data -- makes it easier. Trust me.
723 }
724
725 if (numCdrSpecies > 0) {
726 m_amr->allocate(m_fluidCdrPPC, m_fluidRealm, m_plasmaPhase, numCdrSpecies);
727 m_amr->allocate(m_fluidOldCdrPPC, m_fluidRealm, m_plasmaPhase, numCdrSpecies);
729 }
730 else {
731 m_amr->allocatePointer(m_fluidCdrPPC, m_fluidRealm);
732 m_amr->allocatePointer(m_fluidOldCdrPPC, m_fluidRealm);
733
734 // Dummy data, for the same reason as the Ito holders above: the reconciliation kernels take it by reference.
736 }
737
738 if (numPhotonSpecies > 0) {
739 m_amr->allocate(m_particleYPC, m_particleRealm, m_plasmaPhase, numPhotonSpecies);
740 m_amr->allocate(m_fluidYPC, m_fluidRealm, m_plasmaPhase, numPhotonSpecies);
741 }
742 else {
743 // Allocate some dummy data -- makes it easier. Trust me.
746 }
747
748 DataOps::setValue(m_kmcDt, std::numeric_limits<Real>::max());
749}
750
751template <typename I, typename C, typename R, typename F>
752void
754{
755 CH_TIME("ItoKMCStepper::postInitialize");
756 if (m_verbosity > 5) {
757 pout() << m_name + "::postInitialize" << endl;
758 }
759}
760
761template <typename I, typename C, typename R, typename F>
762void
764{
765 CH_TIME("ItoKMCStepper::initialData");
766 if (m_verbosity > 5) {
767 pout() << m_name + "::initialData" << endl;
768 }
769
770 CH_assert(!(m_cdr.isNull()));
771 CH_assert(!(m_ito.isNull()));
772 CH_assert(!(m_rte.isNull()));
773 CH_assert(!(m_sigmaSolver.isNull()));
774 CH_assert(!(m_fieldSolver.isNull()));
775
776 m_ito->initialData();
777 m_cdr->initialData();
778 m_rte->initialData();
779 this->initialSigma();
780
781 // Make superparticles (makeSuperparticles() cell-sorts internally as needed and returns the containers
782 // patch-organized).
783 m_ito->makeSuperparticles(ItoSolver::WhichContainer::Bulk);
784
785 // Solve Poisson equation and compute the E-field
786 m_fieldSolver->setPermittivities();
788 this->solvePoisson();
789
790 // Fill solvers with velocities and diffusion coefficients
793
794 // Fill the internal neutral density
795 this->fillNeutralDensity();
796}
797
798template <typename I, typename C, typename R, typename F>
799void
801{
802 CH_TIME("ItoKMCStepper::initialSigma");
803 if (m_verbosity > 5) {
804 pout() << m_name + "::initialSigma" << endl;
805 }
806
807 const RealVect probLo = m_amr->getProbLo();
808
809 EBAMRIVData& sigma = m_sigmaSolver->getPhi();
810
811 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
812 const DisjointBoxLayout& dbl = m_amr->getGrids(m_sigmaSolver->getRealm())[lvl];
813 const DataIterator& dit = dbl.dataIterator();
814 const EBISLayout& ebisl = m_amr->getEBISLayout(m_sigmaSolver->getRealm(), m_sigmaSolver->getPhase())[lvl];
815 const Real dx = m_amr->getDx()[lvl];
816
817 const int nbox = dit.size();
818
819#pragma omp parallel for schedule(runtime)
820 for (int mybox = 0; mybox < nbox; mybox++) {
821 const DataIndex& din = dit[mybox];
822
823 BaseIVFAB<Real>& phi = (*sigma[lvl])[din];
824 const EBISBox& ebisbox = ebisl[din];
825
826 CH_assert(phi.nComp() == 1);
827
828 auto kernel = [&](const VolIndex& vof) -> void {
829 const RealVect pos = probLo + Location::position(Location::Cell::Boundary, vof, ebisbox, dx);
830
831 phi(vof, 0) = m_physics->initialSigma(m_time, pos);
832 };
833
834 VoFIterator& vofit = (*m_amr->getVofIterator(m_sigmaSolver->getRealm(), m_sigmaSolver->getPhase())[lvl])[din];
835
836 BoxLoops::loop(vofit, kernel);
837 }
838 }
839
840 // Coarsen throughout the AMR hierarchy.
841 m_amr->conservativeAverage(sigma, m_fluidRealm, m_sigmaSolver->getPhase());
842
843 // Set surface charge to zero on electrode cut-cells.
844 m_sigmaSolver->resetElectrodes(sigma, 0.0);
845}
846
847template <typename I, typename C, typename R, typename F>
848void
850{
851 CH_TIME("ItoKMCStepper::postCheckpointSetup");
852 if (m_verbosity > 5) {
853 pout() << m_name + "::postCheckpointSetup" << endl;
854 }
856 m_ito->remap();
857
858 // Recompute the electric field.
859 this->postCheckpointPoisson();
860
861 // Compute velocities and diffusion coefficients so we're prepared for the next time step.
864
865 // Fill the neutral density on the mesh. It is used for he reduced-field diagnostics (Emax, n/N)
866 // and for the abort_max_field check, and is otherwise onlyfilled in initialData() and regrid()
868}
869
870template <typename I, typename C, typename R, typename F>
871void
874 CH_TIME("ItoKMCStepper::postCheckpointPoisson");
875 if (m_verbosity > 5) {
876 pout() << m_name + "::postCheckpointPoisson" << endl;
877 }
878
879 // Do some post checkpointing stuff.
880 m_fieldSolver->postCheckpoint();
881
882 // Update ghost cells and re-compute the electric field from the HDF5 data.
883 MFAMRCellData& potential = m_fieldSolver->getPotential();
884
885 m_amr->conservativeAverage(potential, m_fluidRealm);
886 m_amr->interpGhostMG(potential, m_fluidRealm);
887
888 m_fieldSolver->computeElectricField();
889
890 // Fetch the electric field data on the plasma phase.
891 const EBAMRCellData E = m_amr->alias(m_plasmaPhase, m_fieldSolver->getElectricField());
892
893 // Copy onto the storage holding the electric field on the fluid realm. Then interpolate to centroids.
894 m_amr->copyData(m_electricFieldFluid, E);
899 // Copy onto the storage holding the electric field on the particle realm.
900 m_amr->copyData(m_electricFieldParticle, E);
904
905 // Set up the Poisson solver
906 m_fieldSolver->setupSolver();
907}
908
909#ifdef CH_USE_HDF5
910template <typename I, typename C, typename R, typename F>
911void
912ItoKMCStepper<I, C, R, F>::writeCheckpointHeader(HDF5HeaderData& a_header) const noexcept
913{
914 CH_TIME("ItoKMCStepper::writeCheckpointHeader");
915 if (m_verbosity > 5) {
916 pout() << m_name + "::writeCheckpointHeader" << endl;
917 }
918}
919#endif
920
921#ifdef CH_USE_HDF5
922template <typename I, typename C, typename R, typename F>
923void
924ItoKMCStepper<I, C, R, F>::readCheckpointHeader(HDF5HeaderData& a_header) noexcept
925{
926 CH_TIME("ItoKMCStepper::readCheckpointHeader");
927 if (m_verbosity > 5) {
928 pout() << m_name + "::readCheckpointHeader" << endl;
929 }
930}
931#endif
932
933#ifdef CH_USE_HDF5
934template <typename I, typename C, typename R, typename F>
935void
936ItoKMCStepper<I, C, R, F>::writeCheckpointData(HDF5Handle& a_handle, const int a_lvl) const noexcept
938 CH_TIME("ItoKMCStepper::writeCheckpointData");
939 if (m_verbosity > 5) {
940 pout() << m_name + "::writeCheckpointData" << endl;
941 }
942
943 for (ItoIterator<ItoSolver> solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
944 solverIt()->writeCheckpointLevel(a_handle, a_lvl);
945 }
946
947 for (CdrIterator<CdrSolver> solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
948 solverIt()->writeCheckpointLevel(a_handle, a_lvl);
949 }
950
951 for (RtIterator<McPhoto> solverIt = m_rte->iterator(); solverIt.ok(); ++solverIt) {
952 solverIt()->writeCheckpointLevel(a_handle, a_lvl);
953 }
954
955 m_fieldSolver->writeCheckpointLevel(a_handle, a_lvl);
956 m_sigmaSolver->writeCheckpointLevel(a_handle, a_lvl);
957}
958#endif
959
960#ifdef CH_USE_HDF5
961template <typename I, typename C, typename R, typename F>
962void
963ItoKMCStepper<I, C, R, F>::readCheckpointData(HDF5Handle& a_handle, const int a_lvl) noexcept
965 CH_TIME("ItoKMCStepper::readCheckpointData");
966 if (m_verbosity > 5) {
967 pout() << m_name + "::readCheckpointData" << endl;
968 }
969
970 for (ItoIterator<ItoSolver> solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
971 solverIt()->readCheckpointLevel(a_handle, a_lvl);
972 }
973
974 for (CdrIterator<CdrSolver> solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
975 solverIt()->readCheckpointLevel(a_handle, a_lvl);
976 }
977
978 for (RtIterator<McPhoto> solverIt = m_rte->iterator(); solverIt.ok(); ++solverIt) {
979 solverIt()->readCheckpointLevel(a_handle, a_lvl);
980 }
981
982 m_fieldSolver->readCheckpointLevel(a_handle, a_lvl);
983 m_sigmaSolver->readCheckpointLevel(a_handle, a_lvl);
984}
985#endif
986
987template <typename I, typename C, typename R, typename F>
988int
990{
991 CH_TIME("ItoKMCStepper::getNumberOfPlotVariables");
992 if (m_verbosity > 5) {
993 pout() << m_name + "::getNumberOfPlotVariables" << endl;
994 }
995
996 int numComp = 0;
998 // Ito solver variables.
999 for (ItoIterator<ItoSolver> solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
1000 numComp += solverIt()->getNumberOfPlotVariables();
1001 }
1002
1003 // Cdr solver variables
1004 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
1005 numComp += solverIt()->getNumberOfPlotVariables();
1006 }
1007
1008 // RTE solver variables.
1009 for (RtIterator<McPhoto> solverIt = m_rte->iterator(); solverIt.ok(); ++solverIt) {
1010 numComp += solverIt()->getNumberOfPlotVariables();
1011 }
1012
1013 // Field solver variables.
1014 numComp += m_fieldSolver->getNumberOfPlotVariables();
1015
1016 // Surface charge solver variables.
1017 numComp += m_sigmaSolver->getNumberOfPlotVariables();
1018
1019 // Conductivity
1020 if (m_plotConductivity) {
1021 numComp += 1;
1022 }
1023
1024 // Current density.
1025 if (m_plotCurrentDensity) {
1026 numComp += SpaceDim;
1027 }
1028
1029 // Number of particles per patch
1030 if (m_plotParticlesPerPatch) {
1031 numComp += 1;
1032 }
1033
1034 // Physics plot variables
1035 numComp += m_physics->getNumberOfPlotVariables();
1036
1037 return numComp;
1038}
1040template <typename I, typename C, typename R, typename F>
1041Vector<std::string>
1043{
1044 CH_TIME("ItoKMCStepper::getPlotVariableNames");
1045 if (m_verbosity > 5) {
1046 pout() << m_name + "::getPlotVariableNames" << endl;
1047 }
1048
1049 Vector<std::string> plotVarNames;
1050
1051 plotVarNames.append(m_fieldSolver->getPlotVariableNames());
1052 plotVarNames.append(m_sigmaSolver->getPlotVariableNames());
1053
1054 for (ItoIterator<ItoSolver> solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
1055 plotVarNames.append(solverIt()->getPlotVariableNames());
1056 }
1057
1058 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
1059 plotVarNames.append(solverIt()->getPlotVariableNames());
1060 }
1061
1062 for (RtIterator<McPhoto> solverIt = m_rte->iterator(); solverIt.ok(); ++solverIt) {
1063 plotVarNames.append(solverIt()->getPlotVariableNames());
1064 }
1065
1066 // Write the conductivity to the output
1067 if (m_plotConductivity) {
1068 plotVarNames.push_back("Conductivity");
1069 }
1070
1071 // Write the current to the output
1073 plotVarNames.push_back("x-J");
1074 plotVarNames.push_back("y-J");
1075 if (SpaceDim == 3) {
1076 plotVarNames.push_back("z-J");
1077 }
1078 }
1079
1080 // Write the number of particles per patch
1081 if (m_plotParticlesPerPatch) {
1082 plotVarNames.push_back("Particles per patch");
1083 }
1084
1085 // Physics plot variable names
1086 plotVarNames.append(m_physics->getPlotVariableNames());
1087
1088 return plotVarNames;
1089}
1090
1091template <typename I, typename C, typename R, typename F>
1092void
1093ItoKMCStepper<I, C, R, F>::writePlotData(LevelData<EBCellFAB>& a_output,
1094 int& a_icomp,
1095 const std::string& a_outputRealm,
1096 const int a_level) const noexcept
1097{
1098 CH_TIME("ItoKMCStepper::writePlotData");
1099 if (m_verbosity > 5) {
1100 pout() << m_name + "::writePlotData" << endl;
1102
1103 // Poisson solver copies over its output data
1104 m_fieldSolver->writePlotData(a_output, a_icomp, a_outputRealm, a_level);
1105
1106 // Surface charge solver writes
1107 m_sigmaSolver->writePlotData(a_output, a_icomp, a_outputRealm, a_level);
1109 // Ito solvers copy their output data
1110 for (ItoIterator<ItoSolver> solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
1111 solverIt()->writePlotData(a_output, a_icomp, a_outputRealm, a_level);
1112 }
1113
1114 // Cdr solvers output their data
1115 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
1116 solverIt()->writePlotData(a_output, a_icomp, a_outputRealm, a_level);
1117 }
1118
1119 // RTE solvers copy their output data
1120 for (RtIterator<McPhoto> solverIt = m_rte->iterator(); solverIt.ok(); ++solverIt) {
1121 solverIt()->writePlotData(a_output, a_icomp, a_outputRealm, a_level);
1122 }
1123
1124 // Write the conductivity to the output
1125 if (m_plotConductivity) {
1126 this->writeData(a_output, a_icomp, m_conductivityCell, a_outputRealm, a_level, false, true);
1128
1129 // Write the current to the output
1130 if (m_plotCurrentDensity) {
1131 this->writeData(a_output, a_icomp, m_currentDensity, a_outputRealm, a_level, false, true);
1132 }
1133
1134 // Write the number of particles per patch
1135 if (m_plotParticlesPerPatch) {
1136 this->writeNumberOfParticlesPerPatch(a_output, a_icomp, a_outputRealm, a_level);
1137 }
1138
1139 // Write physics plot variables
1140 if (m_physics->getNumberOfPlotVariables() > 0) {
1141 this->writeData(a_output, a_icomp, m_physicsPlotVariables, a_outputRealm, a_level, false, true);
1142 }
1143}
1144
1145template <typename I, typename C, typename R, typename F>
1146void
1147ItoKMCStepper<I, C, R, F>::writeData(LevelData<EBCellFAB>& a_output,
1148 int& a_comp,
1149 const EBAMRCellData& a_data,
1150 const std::string a_outputRealm,
1151 const int a_level,
1152 const bool a_interpToCentroids,
1153 const bool a_interpGhost) const noexcept
1154
1155{
1156 CH_TIMERS("ItoKMCStepper::writeData");
1157 CH_TIMER("ItoKMCStepper::writeData::allocate", t1);
1158 CH_TIMER("ItoKMCStepper::writeData::local_copy", t2);
1159 CH_TIMER("ItoKMCStepper::writeData::interp_ghost", t3);
1160 CH_TIMER("ItoKMCStepper::writeData::interp_centroid", t4);
1161 CH_TIMER("ItoKMCStepper::writeData::final_copy", t5);
1162 if (m_verbosity > 5) {
1163 pout() << m_name + "::writeData" << endl;
1164 }
1166 // Number of components we are working with.
1167 const int numComp = a_data[a_level]->nComp();
1168
1169 // Component ranges that we copy to/from.
1170 const Interval srcInterv(0, numComp - 1);
1171 const Interval dstInterv(a_comp, a_comp + numComp - 1);
1172
1173 CH_START(t1);
1174 LevelData<EBCellFAB> scratch;
1175 m_amr->allocate(scratch, a_data.getRealm(), m_plasmaPhase, a_level, numComp);
1176 CH_STOP(t1);
1177
1178 CH_START(t2);
1179 m_amr->copyData(scratch, *a_data[a_level], a_level, a_data.getRealm(), a_data.getRealm());
1180 CH_START(t2);
1181
1182 // Interpolate ghost cells
1183 CH_START(t3);
1184 if (a_level > 0 && a_interpGhost) {
1185 m_amr->interpGhost(scratch, *a_data[a_level - 1], a_level, a_data.getRealm(), m_plasmaPhase);
1186 }
1187 CH_STOP(t3);
1188
1189 CH_START(t4);
1190 if (a_interpToCentroids) {
1191 m_amr->interpToCentroids(scratch, a_data.getRealm(), m_plasmaPhase, a_level);
1192 }
1193 CH_STOP(t4);
1194
1195 DataOps::setCoveredValue(scratch, *m_amr->getCoveredCells(a_data.getRealm(), m_plasmaPhase)[a_level], 0.0);
1196
1197 CH_START(t5);
1198 m_amr->copyData(a_output,
1199 scratch,
1200 a_level,
1201 a_outputRealm,
1202 a_data.getRealm(),
1203 dstInterv,
1204 srcInterv,
1205 CopyStrategy::ValidGhost,
1206 CopyStrategy::ValidGhost);
1207 CH_STOP(t5);
1208
1209 a_comp += numComp;
1210}
1211
1212template <typename I, typename C, typename R, typename F>
1213void
1215 int& a_icomp,
1216 const std::string a_outputRealm,
1217 const int a_level) const noexcept
1218{
1219 CH_TIME("ItoKMCStepper::writeNumberOfParticlesPerPatch");
1220 if (m_verbosity > 5) {
1221 pout() << m_name + "::writeNumberOfParticlesPerPatch" << endl;
1222 }
1223
1224 CH_assert(a_level >= 0);
1225 CH_assert(a_level <= m_amr->getFinestLevel());
1226
1227 // The scratch has one component, and only this level is written out.
1229
1230 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
1231 const ParticleContainer<ItoParticle>& particles = solverIt()->getParticles(ItoSolver::WhichContainer::Bulk);
1232
1233 const DisjointBoxLayout& dbl = m_amr->getGrids(m_particleRealm)[a_level];
1234 const DataIterator& dit = dbl.dataIterator();
1236 const int nbox = dit.size();
1237
1238#pragma omp parallel for schedule(runtime)
1239 for (int mybox = 0; mybox < nbox; mybox++) {
1240 const DataIndex& din = dit[mybox];
1241
1242 (*m_particleScratch1[a_level])[din] += particles[a_level][din].size();
1244 }
1245
1246 m_amr->copyData(a_output,
1247 *m_particleScratch1[a_level],
1248 a_level,
1249 a_outputRealm,
1251 Interval(a_icomp, a_icomp),
1252 Interval(0, 0));
1253
1254 a_icomp += 1;
1255}
1256
1257template <typename I, typename C, typename R, typename F>
1258void
1259ItoKMCStepper<I, C, R, F>::synchronizeSolverTimes(const int a_step, const Real a_time, const Real a_dt) noexcept
1260{
1261 CH_TIME("ItoKMCStepper::synchronizeSolverTimes");
1262 if (m_verbosity > 5) {
1263 pout() << m_name + "::synchronizeSolverTimes" << endl;
1264 }
1265
1266 m_timeStep = a_step;
1267 m_time = a_time;
1268 m_dt = a_dt;
1269
1270 m_ito->setTime(a_step, a_time, a_dt);
1271 m_fieldSolver->setTime(a_step, a_time, a_dt);
1272 m_rte->setTime(a_step, a_time, a_dt);
1273 m_sigmaSolver->setTime(a_step, a_time, a_dt);
1274}
1275
1276template <typename I, typename C, typename R, typename F>
1277void
1279{
1280 CH_TIME("ItoKMCStepper::printStepReport");
1281 if (m_verbosity > 5) {
1282 pout() << m_name + "::printStepReport" << endl;
1283 }
1284
1285 const unsigned long long localParticlesBulk = m_ito->getNumParticles(ItoSolver::WhichContainer::Bulk, true);
1286 const unsigned long long globalParticlesBulk = m_ito->getNumParticles(ItoSolver::WhichContainer::Bulk, false);
1287 const unsigned long long localParticlesEB = m_ito->getNumParticles(ItoSolver::WhichContainer::EB, true);
1288 const unsigned long long globalParticlesEB = m_ito->getNumParticles(ItoSolver::WhichContainer::EB, false);
1289 const unsigned long long localParticlesDomain = m_ito->getNumParticles(ItoSolver::WhichContainer::Domain, true);
1290 const unsigned long long globalParticlesDomain = m_ito->getNumParticles(ItoSolver::WhichContainer::Domain, false);
1291 const unsigned long long localParticlesSource = m_ito->getNumParticles(ItoSolver::WhichContainer::Source, true);
1292 const unsigned long long globalParticlesSource = m_ito->getNumParticles(ItoSolver::WhichContainer::Source, false);
1293
1294 Real avgParticles = 0.0;
1295 Real stdDev = 0.0;
1296
1297 Real minParticles = 0.0;
1298 Real maxParticles = 0.0;
1299
1300 int minRank = 0;
1301 int maxRank = 0;
1302
1303 this->getParticleStatistics(avgParticles, stdDev, minParticles, maxParticles, minRank, maxRank);
1304
1305 Real maxDensity = -std::numeric_limits<Real>::max();
1306 Real minDensity = +std::numeric_limits<Real>::max();
1307
1308 std::string maxSolver = "invalid solver";
1309 std::string minSolver = "invalid solver";
1310
1311 this->getMaxMinRelativeItoDensity(maxDensity, minDensity, maxSolver, minSolver);
1312 this->getMaxMinRelativeCDRDensity(maxDensity, minDensity, maxSolver, minSolver);
1313
1314 std::string str;
1315 switch (m_timeCode) {
1316 case TimeCode::Physics: {
1317 str = "dt restricted by 'Physics'";
1318
1319 break;
1320 }
1321 case TimeCode::AdvectionIto: {
1322 str = "dt restricted by 'Advection (Ito)'";
1323
1324 break;
1325 }
1326 case TimeCode::DiffusionIto: {
1327 str = "dt restricted by 'Diffusion (Ito)'";
1328
1329 break;
1330 }
1331 case TimeCode::AdvectionDiffusionIto: {
1332 str = "dt restricted by 'AdvectionDiffusion (Ito)'";
1333
1334 break;
1335 }
1336 case TimeCode::AdvectionDiffusionCDR: {
1337 str = "dt restricted by 'AdvectionDiffusion (CDR)'";
1338
1339 break;
1340 }
1341 case TimeCode::RelaxationTime: {
1342 str = "dt restricted by 'Relaxation time'";
1343
1344 break;
1345 }
1346 case TimeCode::Hardcap: {
1347 str = "dt restricted by 'Hardcap'";
1348
1349 break;
1350 }
1351 default: {
1352 str = "dt restricted by 'Unspecified'";
1353
1354 break;
1355 }
1356 }
1357
1358 // Calculate the charge
1359 const Real Qplus = this->computeQplus();
1360 const Real Qminu = this->computeQminu();
1361 const Real Qsurf = this->computeQsurf();
1362 const Real Qtot = Qplus + Qminu + Qsurf;
1363
1364 // Print the step report.
1365
1366 //clang-format off
1367 const std::string whitespace = " ";
1368 pout() << " " + str << endl;
1369 pout() << whitespace + "Emax = " << m_maxReducedField << " (Td)" << endl
1370 << whitespace + "Max n/N = " << maxDensity << " (" << maxSolver << ")" << endl
1371 << whitespace + "Qplus = " << Qplus << endl
1372 << whitespace + "Qminu = " << Qminu << endl
1373 << whitespace + "Qsurf = " << Qsurf << endl
1374 << whitespace + "Qtot = " << Qtot << endl
1375 << whitespace + "CFL (Ito) = " << m_dt / m_particleAdvectionDiffusionDt << endl
1376 << whitespace + "CFL (CDR) = " << m_dt / m_fluidAdvectionDiffusionDt << endl
1377 << whitespace + "dt/dt_relax = " << m_dt / m_relaxationTime << endl
1378 << whitespace + "#Particles = " << DischargeIO::numberFmt(localParticlesBulk) << " ("
1379 << DischargeIO::numberFmt(globalParticlesBulk) << ")" << endl
1380 << whitespace + "#EB part. = " << DischargeIO::numberFmt(localParticlesEB) << " ("
1381 << DischargeIO::numberFmt(globalParticlesEB) << ")" << endl
1382 << whitespace + "#Dom. part. = " << DischargeIO::numberFmt(localParticlesDomain) << " ("
1383 << DischargeIO::numberFmt(globalParticlesDomain) << ")" << endl
1384 << whitespace + "#Src. part. = " << DischargeIO::numberFmt(localParticlesSource) << " ("
1385 << DischargeIO::numberFmt(globalParticlesSource) << ")" << endl
1386 << whitespace + "#Min part. = " << minParticles << " (on rank = " << minRank << ")" << endl
1387 << whitespace + "#Max part. = " << maxParticles << " (on rank = " << maxRank << ")" << endl
1388 << whitespace + "#Avg. part. = " << avgParticles << endl
1389 << whitespace + "#Dev. part. = " << stdDev << " (" << 100. * stdDev / avgParticles << "%)" << endl;
1390 //clang-format on
1391}
1392
1393template <typename I, typename C, typename R, typename F>
1394void
1396 Real& a_minDensity,
1397 std::string& a_maxSolver,
1398 std::string& a_minSolver) const noexcept
1399{
1400 CH_TIME("ItoKMCStepper::getMaxMinDensity(Realx2, std::string2x)");
1401 if (m_verbosity > 5) {
1402 pout() << m_name + "::getMaxMinDensity(Realx2, std::string2x)" << endl;
1403 }
1404
1405 // Scratch member rather than a per-call hierarchy -- printStepReport() runs every time step.
1406 EBAMRCellData& tmp = m_fluidScratch1;
1407
1408 // Go through each solver and find the max/min values.
1409 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
1410 const RefCountedPtr<ItoSolver>& solver = solverIt();
1411 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
1412 const int Z = species->getChargeNumber();
1413
1414 if (Z != 0) {
1415 Real curMin = std::numeric_limits<Real>::max();
1416 Real curMax = -std::numeric_limits<Real>::max();
1417
1418 // Ito solvers might be defined on a separate realm, so we have to copy the data over
1419 // before dividing by the neutral density
1420 const Interval dstInterv = Interval(0, 0);
1421 const Interval srcInterv = Interval(0, 0);
1422
1423 m_amr->copyData(tmp, solverIt()->getPhi(), dstInterv, srcInterv);
1424
1425 DataOps::divideFallback(tmp, m_neutralDensity, 0.0, m_amr->getMultiCutVofIterator(m_fluidRealm, m_plasmaPhase));
1426 DataOps::getMaxMin(curMax, curMin, tmp, 0, m_amr->getMultiCutVofIterator(m_fluidRealm, m_plasmaPhase));
1427
1428 if (curMax > a_maxDensity) {
1429 a_maxDensity = curMax;
1430 a_maxSolver = solver->getName();
1431 }
1432
1433 if (curMin < a_minDensity) {
1434 a_minDensity = curMin;
1435 a_minSolver = solver->getName();
1436 }
1437 }
1438 }
1439}
1440
1441template <typename I, typename C, typename R, typename F>
1442void
1444 Real& a_minDensity,
1445 std::string& a_maxSolver,
1446 std::string& a_minSolver) const noexcept
1447{
1448 CH_TIME("ItoKMCStepper::getMaxMinRelativeCDRDensity(Realx2, std::string2x)");
1449 if (m_verbosity > 5) {
1450 pout() << m_name + "::getMaxMinRelativeCDRDensity(Realx2, std::string2x)" << endl;
1451 }
1452
1453 // Scratch member rather than a per-call hierarchy -- printStepReport() runs every time step.
1454 EBAMRCellData& tmp = m_fluidScratch1;
1455
1456 // Go through each solver and find the max/min values.
1457 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
1458 const RefCountedPtr<CdrSolver>& solver = solverIt();
1459 const RefCountedPtr<CdrSpecies>& species = solver->getSpecies();
1460 const int Z = species->getChargeNumber();
1461
1462 if (Z != 0) {
1463 Real curMin = std::numeric_limits<Real>::max();
1464 Real curMax = -std::numeric_limits<Real>::max();
1465
1466 // Copy the data over to a temporary holder before dividing by the neutral density
1467 const Interval dstInterv = Interval(0, 0);
1468 const Interval srcInterv = Interval(0, 0);
1469
1470 m_amr->copyData(tmp, solverIt()->getPhi(), dstInterv, srcInterv);
1471
1472 DataOps::divideFallback(tmp, m_neutralDensity, 0.0, m_amr->getMultiCutVofIterator(m_fluidRealm, m_plasmaPhase));
1473 DataOps::getMaxMin(curMax, curMin, tmp, 0, m_amr->getMultiCutVofIterator(m_fluidRealm, m_plasmaPhase));
1474
1475 if (curMax > a_maxDensity) {
1476 a_maxDensity = curMax;
1477 a_maxSolver = solver->getName();
1478 }
1479
1480 if (curMin < a_minDensity) {
1481 a_minDensity = curMin;
1482 a_minSolver = solver->getName();
1483 }
1484 }
1485 }
1486}
1487
1488template <typename I, typename C, typename R, typename F>
1489void
1491 Real& a_sigma,
1492 Real& a_minParticles,
1493 Real& a_maxParticles,
1494 int& a_minRank,
1495 int& a_maxRank)
1496{
1497 CH_TIME("ItoKMCStepper::getParticleStatistics");
1498 if (m_verbosity > 5) {
1499 pout() << m_name + "::getParticleStatistics" << endl;
1500 }
1501
1502 // TLDR: We compute the number of particles, the standard deviation of the number of particles, as well
1503 // as the ranks having the smallest/largest number of particles.
1504
1505 const Real numParticles = 1.0 * m_ito->getNumParticles(ItoSolver::WhichContainer::Bulk, true);
1506
1507 const std::pair<Real, int> minParticles = ParallelOps::minRank(numParticles);
1508 const std::pair<Real, int> maxParticles = ParallelOps::maxRank(numParticles);
1509
1510 a_avgParticles = ParallelOps::average(numParticles);
1511 a_sigma = ParallelOps::standardDeviation(numParticles);
1512
1513 a_minParticles = minParticles.first;
1514 a_maxParticles = maxParticles.first;
1515
1516 a_minRank = minParticles.second;
1517 a_maxRank = maxParticles.second;
1518}
1519
1520template <typename I, typename C, typename R, typename F>
1521Real
1523{
1524 CH_TIME("ItoKMCStepper::computeDt");
1525 if (m_verbosity > 5) {
1526 pout() << m_name + "::computeDt" << endl;
1527 }
1528
1529 Timer timer(m_name + "::computeDt");
1530
1531 Real dt = std::numeric_limits<Real>::max();
1532
1533 const Real maxGrowthDt = m_prevDt > 0.0 ? m_prevDt * m_maxGrowthDt : dt;
1534 const Real minShrinkDt = m_prevDt > 0.0 ? m_prevDt / m_maxShrinkDt : 0.0;
1535
1536 if (m_timeStep == 0) {
1537 this->computeDummyPhysicsDt();
1538 }
1539
1540 // Compute various time steps.
1541 timer.startEvent("Advection (Ito)");
1542 m_particleAdvectionDt = m_ito->computeAdvectiveDt();
1543 timer.stopEvent("Advection (Ito)");
1544
1545 timer.startEvent("Diffusion (Ito)");
1546 m_particleDiffusionDt = m_ito->computeDiffusiveDt();
1547 timer.stopEvent("Diffusion (Ito)");
1548
1549 timer.startEvent("AdvectionDiffusion (Ito)");
1551 timer.stopEvent("AdvectionDiffusion (Ito)");
1552
1553 timer.startEvent("AdvectionDiffusion (CDR)");
1554 m_fluidAdvectionDiffusionDt = m_cdr->computeAdvectionDiffusionDt();
1555 timer.stopEvent("AdvectionDiffusion (CDR)");
1556
1557 timer.startEvent("Relaxation");
1559 timer.stopEvent("Relaxation");
1560
1561 const bool hasParticleAdvectionDt = m_particleAdvectionDt < std::numeric_limits<Real>::max();
1562 const bool hasParticleDiffusionDt = m_particleDiffusionDt < std::numeric_limits<Real>::max();
1563 const bool hasParticleAdvectionDiffusionDt = m_particleAdvectionDiffusionDt < std::numeric_limits<Real>::max();
1564
1567 m_timeCode = TimeCode::AdvectionIto;
1568 }
1569
1570 if (m_maxParticleDiffusionCFL * m_particleDiffusionDt < dt) {
1571 dt = m_maxParticleDiffusionCFL * m_particleDiffusionDt;
1572 m_timeCode = TimeCode::DiffusionIto;
1573 }
1574
1575 if (m_maxParticleAdvectionDiffusionCFL * m_particleAdvectionDiffusionDt < dt) {
1576 dt = m_maxParticleAdvectionDiffusionCFL * m_particleAdvectionDiffusionDt;
1577 m_timeCode = TimeCode::AdvectionDiffusionIto;
1578 }
1579
1580 if (std::min(m_fluidAdvectionDiffusionCFL, 0.9) * m_fluidAdvectionDiffusionDt < dt) {
1581 dt = std::min(m_fluidAdvectionDiffusionCFL, 0.9) * m_fluidAdvectionDiffusionDt;
1582 m_timeCode = TimeCode::AdvectionDiffusionCDR;
1583 }
1584
1585 if (m_relaxTimeFactor * m_relaxationTime < dt) {
1586 dt = m_relaxTimeFactor * m_relaxationTime;
1587 m_timeCode = TimeCode::RelaxationTime;
1588 }
1589
1590 if (m_physicsDtFactor * m_physicsDt < dt) {
1591 dt = m_physicsDtFactor * m_physicsDt;
1592 m_timeCode = TimeCode::Physics;
1593 }
1594
1595 if ((dt < m_minParticleAdvectionCFL * m_particleAdvectionDt) && hasParticleAdvectionDt) {
1596 dt = m_minParticleAdvectionCFL * m_particleAdvectionDt;
1597 m_timeCode = TimeCode::AdvectionIto;
1598 }
1599
1600 if ((dt < m_minParticleDiffusionCFL * m_particleDiffusionDt) && hasParticleDiffusionDt) {
1601 dt = m_minParticleDiffusionCFL * m_particleDiffusionDt;
1602 m_timeCode = TimeCode::DiffusionIto;
1603 }
1604
1605 if ((dt < m_minParticleAdvectionDiffusionCFL * m_particleAdvectionDiffusionDt) && hasParticleAdvectionDiffusionDt) {
1606 dt = m_minParticleAdvectionDiffusionCFL * m_particleAdvectionDiffusionDt;
1607 m_timeCode = TimeCode::AdvectionDiffusionIto;
1608 }
1609
1610 if (dt > maxGrowthDt) {
1611 dt = maxGrowthDt;
1613
1614 if (dt < minShrinkDt) {
1615 dt = minShrinkDt;
1616 }
1617
1618 if (m_minDt > dt) {
1619 dt = m_minDt;
1620 m_timeCode = TimeCode::Hardcap;
1621 }
1622
1623 if (m_maxDt < dt) {
1625 m_timeCode = TimeCode::Hardcap;
1626 }
1627
1628 if (m_profile) {
1629 timer.eventReport(pout(), false);
1630 }
1631
1632 return dt;
1634
1635template <typename I, typename C, typename R, typename F>
1636void
1638{
1639 CH_TIME("ItoKMCStepper::registerRealms");
1640 if (m_verbosity > 5) {
1641 pout() << m_name + "::registerRealms" << endl;
1642 }
1643
1644 // TLDR: If using dual grid then m_particleRealm != m_fluidRealm and we'll have two realms.
1645 m_amr->registerRealm(m_fluidRealm);
1646 m_amr->registerRealm(m_particleRealm);
1647}
1648
1649template <typename I, typename C, typename R, typename F>
1650void
1652{
1653 CH_TIME("ItoKMCStepper::registerOperators");
1654 if (m_verbosity > 5) {
1655 pout() << m_name + "::registerOperators" << endl;
1656 }
1657
1658 m_ito->registerOperators();
1659 m_cdr->registerOperators();
1660 m_fieldSolver->registerOperators();
1661 m_rte->registerOperators();
1662 m_sigmaSolver->registerOperators();
1663
1664 // Required for non-cell-based particle mergers.
1665 m_amr->registerParticleGhostMask(m_particleRealm, 1);
1666}
1667
1668template <typename I, typename C, typename R, typename F>
1669void
1671{
1672 CH_TIME("ItoKMCStepper::prePlot");
1673 if (m_verbosity > 5) {
1674 pout() << m_name + "::prePlot" << endl;
1675 }
1676
1677 const int numPhysicsPlotVars = m_physics->getNumberOfPlotVariables();
1678
1679 if (numPhysicsPlotVars > 0) {
1680 m_amr->allocate(m_physicsPlotVariables, m_fluidRealm, m_plasmaPhase, numPhysicsPlotVars);
1681
1682 this->computePhysicsPlotVariables(m_physicsPlotVariables);
1683 }
1684
1685 this->computeCurrentDensity(this->m_currentDensity);
1686 m_ito->depositParticles();
1687}
1688
1689template <typename I, typename C, typename R, typename F>
1690void
1692{
1693 CH_TIME("ItoKMCStepper::postPlot");
1694 if (m_verbosity > 5) {
1695 pout() << m_name + "::postPlot" << endl;
1696 }
1697
1698 m_physicsPlotVariables.clear();
1699}
1700
1701template <typename I, typename C, typename R, typename F>
1702void
1703ItoKMCStepper<I, C, R, F>::preRegrid(const int a_lmin, const int a_oldFinestLevel) noexcept
1704{
1705 CH_TIME("ItoKMCStepper::preRegrid");
1706 if (m_verbosity > 5) {
1707 pout() << m_name + "::preRegrid" << endl;
1708 }
1709
1710 const int numItoSpecies = m_physics->getNumItoSpecies();
1711 const int numCdrSpecies = m_physics->getNumCdrSpecies();
1712 const int numPlasmaSpecies = m_physics->getNumPlasmaSpecies();
1713 const int numPhotonSpecies = m_physics->getNumPhotonSpecies();
1714
1715 // If we are load balancing then we need to store the number of particles per cell on the old grids. This
1716 // will be used to estimate computational loads on the new grids.
1717 //
1718 // ORDERING: this must stay ahead of m_ito->preRegrid() below. That call extracts the bulk particles
1719 // into the solver's reduced regrid holder and leaves the ItoParticle container empty, so reading
1720 // getParticles(Bulk) afterwards would deposit nothing and every load would come back zero -- which
1721 // produces a perfectly valid, perfectly unbalanced layout rather than an error.
1723 Vector<RefCountedPtr<ItoSolver>> lbSolvers = this->getLoadBalanceSolvers();
1724
1725 m_loadBalancePPC.resize(lbSolvers.size());
1726
1727 // Allocate and compute number of computational particles per cell.
1728 for (int i = 0; i < lbSolvers.size(); i++) {
1730
1731 EBAMRCellData& compPPC = m_loadBalancePPC[i];
1732 const ParticleContainer<ItoParticle>& particles = lbSolvers[i]->getParticles(ItoSolver::WhichContainer::Bulk);
1735 }
1736 }
1737
1738 // Release some unnecessary storage.
1739 m_fluidScratch1.clear();
1740 m_fluidScratchD.clear();
1741 m_fluidScratchEB.clear();
1742
1743 for (int i = 0; i < m_fluidScratchIto.size(); i++) {
1744 m_fluidScratchIto[i].clear();
1745 }
1746
1747 m_particleScratch1.clear();
1748 m_particleScratchD.clear();
1749 m_particleScratchEB.clear();
1750
1751 m_conductivityCell.clear();
1752 m_conductivityFace.clear();
1753 m_conductivityEB.clear();
1754
1755 m_electricFieldParticle.clear();
1756 m_electricFieldFluid.clear();
1757
1758 m_electricFieldParticle.clear();
1759 m_electricFieldFluid.clear();
1760
1761 for (int i = 0; i < numCdrSpecies; i++) {
1763 m_cdrProducts[i]->clearParticles();
1764 }
1765
1766 for (int i = 0; i < numItoSpecies; i++) {
1767 m_fluidGradPhiIto[i].clear();
1768 m_fluidPhiIto[i].clear();
1769 }
1770 for (int i = 0; i < numCdrSpecies; i++) {
1771 m_fluidGradPhiCDR[i].clear();
1772 }
1773
1774 for (int i = 0; i < numItoSpecies; i++) {
1775 m_secondaryParticles[i]->clearParticles();
1776 }
1777 for (int i = 0; i < numPhotonSpecies; i++) {
1778 m_secondaryPhotons[i]->clearParticles();
1779 }
1780
1781 for (int i = 0; i < numCdrSpecies; i++) {
1782 m_cdrFluxes[i].clear();
1783 m_cdrFluxesExtrap[i].clear();
1784 }
1785
1786 m_currentDensity.clear();
1787 m_fluidPPC.clear();
1788
1789 m_particleItoPPC.clear();
1790 m_particleOldItoPPC.clear();
1791
1792 if (numCdrSpecies > 0) {
1793 m_fluidCdrPPC.clear();
1794 m_fluidOldCdrPPC.clear();
1795 }
1796
1797 // Unconditional: unlike the two above, this one holds real data even when there are no CDR species.
1798 m_particleCdrProduction.clear();
1800 m_particleYPC.clear();
1801 m_fluidYPC.clear();
1802
1803 // Put solvers in pre-regrid mode.
1804 m_ito->preRegrid(a_lmin, a_oldFinestLevel);
1805 m_cdr->preRegrid(a_lmin, a_oldFinestLevel);
1806 m_fieldSolver->preRegrid(a_lmin, a_oldFinestLevel);
1807 m_rte->preRegrid(a_lmin, a_oldFinestLevel);
1808 m_sigmaSolver->preRegrid(a_lmin, a_oldFinestLevel);
1809}
1811template <typename I, typename C, typename R, typename F>
1812void
1813ItoKMCStepper<I, C, R, F>::regrid(const int a_lmin, const int a_oldFinestLevel, const int a_newFinestLevel) noexcept
1814{
1815 CH_TIME("ItoKMCStepper::regrid");
1816 if (m_verbosity > 5) {
1817 pout() << m_name + "::regrid" << endl;
1819
1820 this->allocateInternals();
1821
1822 m_ito->regrid(a_lmin, a_oldFinestLevel, a_newFinestLevel);
1823 m_cdr->regrid(a_lmin, a_oldFinestLevel, a_newFinestLevel);
1824 m_fieldSolver->regrid(a_lmin, a_oldFinestLevel, a_newFinestLevel);
1825 m_rte->regrid(a_lmin, a_oldFinestLevel, a_newFinestLevel);
1826 m_sigmaSolver->regrid(a_lmin, a_oldFinestLevel, a_newFinestLevel);
1827
1828 // The regrid super-particle merge now runs inside ItoSolver::regrid(), on the reduced particles and
1829 // before they are rebuilt as ItoParticles -- which is the whole point: the de-refinement pile-up is
1830 // merged away while it is still 53 B per particle. See ItoSolver.regrid_superparticles.
1831
1832 // Redeposit particles and update the electric field on the new mesh.
1833 m_ito->depositParticles();
1834
1835 const bool converged = this->solvePoisson();
1836 if (!converged) {
1837 const std::string err = "ItoKMCStepper::regrid - Poisson solve did not converge after regrid!!!";
1838
1840 MayDay::Error(err.c_str());
1841 }
1842 else {
1843 MayDay::Warning(err.c_str());
1844 }
1845 }
1847 this->computeDriftVelocities();
1849
1850 this->fillNeutralDensity();
1851}
1852
1853template <typename I, typename C, typename R, typename F>
1854void
1856{
1857 CH_TIME("ItoKMCStepper::postRegrid");
1858
1860 for (int i = 0; i < m_loadBalancePPC.size(); i++) {
1861 m_amr->deallocate(m_loadBalancePPC[i]);
1862 }
1863 }
1864}
1865
1866template <typename I, typename C, typename R, typename F>
1867void
1868ItoKMCStepper<I, C, R, F>::setVoltage(const std::function<Real(const Real a_time)>& a_voltage) noexcept
1869{
1870 CH_TIME("ItoKMCStepper::setVoltage");
1871 if (m_verbosity > 5) {
1872 pout() << m_name + "::setVoltage" << endl;
1873 }
1874
1875 m_voltage = a_voltage;
1876}
1877
1878template <typename I, typename C, typename R, typename F>
1879void
1881{
1882 CH_TIME("ItoKMCStepper::fillNeutralDensity");
1883 if (m_verbosity > 5) {
1884 pout() << m_name + "::fillNeutralDensity" << endl;
1885 }
1886
1887 DataOps::setValue(m_neutralDensity, std::numeric_limits<Real>::max());
1888
1889 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
1890 const DisjointBoxLayout& dbl = m_amr->getGrids(m_fluidRealm)[lvl];
1891 const EBISLayout& ebisl = m_amr->getEBISLayout(m_fluidRealm, m_plasmaPhase)[lvl];
1892 const DataIterator& dit = dbl.dataIterator();
1893 const Real dx = m_amr->getDx()[lvl];
1894 const RealVect probLo = m_amr->getProbLo();
1895
1896 const int nbox = dit.size();
1897
1898 CH_assert(!(m_neutralDensity[lvl].isNull()));
1899 CH_assert(m_neutralDensity[lvl]->nComp() == 1);
1900
1901#pragma omp parallel for schedule(runtime)
1902 for (int mybox = 0; mybox < nbox; mybox++) {
1903 const DataIndex& din = dit[mybox];
1904 const Box cellBox = dbl[din];
1905 const EBISBox& ebisbox = ebisl[din];
1906
1907 EBCellFAB& neutralDensity = (*m_neutralDensity[lvl])[din];
1908 FArrayBox& neutralDensityReg = neutralDensity.getFArrayBox();
1909
1910 auto regularKernel = [&](const IntVect& iv) -> void {
1911 const RealVect pos = probLo + (0.5 * RealVect::Unit + iv) * dx;
1912
1913 neutralDensityReg(iv, 0) = m_physics->getNeutralDensity(pos);
1915
1916 auto irregularKernel = [&](const VolIndex& vof) -> void {
1917 const RealVect pos = probLo + Location::position(Location::Cell::Centroid, vof, ebisbox, dx);
1918
1919 neutralDensity(vof, 0) = m_physics->getNeutralDensity(pos);
1920 };
1921
1922 VoFIterator& vofit = (*m_amr->getVofIterator(m_fluidRealm, m_plasmaPhase)[lvl])[din];
1924 // Not vectorizable: m_physics->getNeutralDensity(pos) is a virtual call per cell. One-time setup.
1925 // Multi-cut N/A (center vs centroid position).
1926 BoxLoops::loop<D_DECL(1, 1, 1)>(cellBox, regularKernel);
1927 BoxLoops::loop(vofit, irregularKernel);
1928 }
1929 }
1931 m_amr->conservativeAverage(m_neutralDensity, m_fluidRealm, m_plasmaPhase);
1933}
1934
1935template <typename I, typename C, typename R, typename F>
1936Real
1938{
1939 CH_TIME("ItoKMCStepper::computeMaxReducedElectricField");
1940 if (m_verbosity > 5) {
1941 pout() << m_name + "::computeMaxReducedElectricField" << endl;
1943
1944 // The body below interpolates and divides on the plasma phase regardless of a_phase, and m_fluidScratch1
1945 // lives on the plasma phase, so the two have to agree.
1946 CH_assert(a_phase == m_plasmaPhase);
1947
1948 // Get a handle to the E-field. Note that this is the cell-centered field!
1949 const EBAMRCellData cellCenteredE = m_amr->alias(a_phase, m_fieldSolver->getElectricField());
1950
1951 // Interpolate to centroids. Runs through the scratch member rather than a per-call hierarchy: this is
1952 // called once per time step, and AmrMesh::allocate defines an exchange Copier per level.
1953 EBAMRCellData& tmp = m_fluidScratch1;
1956 cellCenteredE,
1957 m_amr->getNotCoveredCells(m_fluidRealm, a_phase),
1958 m_amr->getMultiCutVofIterator(m_fluidRealm, a_phase));
1959
1960 // The centroid interpolation reads the cell across each face, which at a box edge is a ghost cell. The vector length
1961 // fills the valid cells only, and the scratch holds whatever an earlier use left in its ghost cells, so they are
1962 // filled from the valid cells first, as the field's own ghost cells are.
1963 m_amr->interpGhost(tmp, m_fluidRealm, a_phase);
1964 m_amr->interpToCentroids(tmp, m_fluidRealm, m_plasmaPhase);
1965
1966 DataOps::divideFallback(tmp, m_neutralDensity, 0.0, m_amr->getMultiCutVofIterator(m_fluidRealm, m_plasmaPhase));
1967
1968 Real max = 0.0;
1969 Real min = 0.0;
1970
1971 DataOps::getMaxMin(max, min, tmp, 0, m_amr->getMultiCutVofIterator(m_fluidRealm, m_plasmaPhase));
1972
1973 return max * 1E21;
1974}
1975
1976template <typename I, typename C, typename R, typename F>
1977void
1979 const phase::which_phase a_phase) const noexcept
1980{
1981 CH_TIME("ItoKMCStepper::computeElectricField(EBAMRCellData, phase)");
1982 if (m_verbosity > 5) {
1983 pout() << m_name + "::computeElectricField(EBAMRCellData, phase)" << endl;
1984 }
1985
1986 CH_assert(a_electricField.getRealm() == m_fluidRealm);
1987
1988 m_fieldSolver->computeElectricField(a_electricField, a_phase, m_fieldSolver->getPotential());
1989}
1990
1991template <typename I, typename C, typename R, typename F>
1992Real
1994{
1995 CH_TIME("ItoKMCStepper::getTime");
1996 if (m_verbosity > 5) {
1997 pout() << m_name + "::getTime" << endl;
1998 }
1999
2000 return m_time;
2001}
2002
2003template <typename I, typename C, typename R, typename F>
2004void
2006{
2007 CH_TIME("ItoKMCStepper::computeSpaceChargeDensity()");
2008 if (m_verbosity > 5) {
2009 pout() << m_name + "::computeSpaceChargeDensity()" << endl;
2010 }
2011
2012 this->computeSpaceChargeDensity(m_fieldSolver->getRho(), m_ito->getDensities(), m_cdr->getPhis());
2013}
2014
2015template <typename I, typename C, typename R, typename F>
2016void
2018 const Vector<EBAMRCellData*>& a_itoDensities,
2019 const Vector<EBAMRCellData*>& a_cdrDensities) noexcept
2020{
2021 CH_TIME("ItoKMCStepper::computeSpaceChargeDensity(rho, densities)");
2022 if (m_verbosity > 5) {
2023 pout() << m_name + "::computeSpaceChargeDensity(rho, densities)" << endl;
2024 }
2025
2026 // Guard the realm spot-checks: either layout may legitimately be empty. A chemistry that puts every
2027 // plasma species on the Ito solver leaves a_cdrDensities empty, and indexing [0] to check its realm
2028 // then aborts on the assert rather than on anything real. The loops below iterate the solver
2029 // layouts, so an empty one is already a no-op there.
2030 CH_assert(a_rho.getRealm() == m_fluidRealm);
2031 CH_assert(a_itoDensities.size() == 0 || a_itoDensities[0]->getRealm() == m_particleRealm);
2032 CH_assert(a_cdrDensities.size() == 0 || a_cdrDensities[0]->getRealm() == m_fluidRealm);
2033
2034 // TLDR: a_itoDensities could be defined over the particle realm, so we use m_fluidScratch1 as a temporary storage.
2035
2036 DataOps::setValue(a_rho, 0.0);
2037
2038 // Alias for the plasma phase.
2039 EBAMRCellData rhoPhase = m_amr->alias(m_plasmaPhase, a_rho);
2040
2041 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
2042 const RefCountedPtr<ItoSolver>& solver = solverIt();
2043 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
2044 const int idx = solverIt.index();
2045 const int Z = species->getChargeNumber();
2046
2047 if (Z != 0) {
2048 m_amr->copyData(m_fluidScratch1, *a_itoDensities[idx]);
2049
2050 DataOps::incr(rhoPhase, m_fluidScratch1, 1.0 * Z);
2051 }
2052 }
2053
2054 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
2055 const RefCountedPtr<CdrSolver>& solver = solverIt();
2056 const RefCountedPtr<CdrSpecies>& species = solver->getSpecies();
2057 const int idx = solverIt.index();
2058 const int Z = species->getChargeNumber();
2059
2060 if (Z != 0) {
2061 DataOps::incr(rhoPhase, *a_cdrDensities[idx], 1.0 * Z);
2062 }
2063 }
2064
2065 DataOps::scale(a_rho, Units::Qe);
2066
2067 m_amr->arithmeticAverage(a_rho, m_fluidRealm);
2068 m_amr->interpGhostPwl(a_rho, m_fluidRealm);
2069
2070 // Interpolate to centroids.
2071 m_amr->interpToCentroids(rhoPhase, m_fluidRealm, m_plasmaPhase);
2072}
2073
2074template <typename I, typename C, typename R, typename F>
2075void
2076ItoKMCStepper<I, C, R, F>::computeConductivityCell(EBAMRCellData& a_conductivity) noexcept
2077{
2078 CH_TIME("ItoKMCStepper::computeConductivityCell(EBAMRCellData)");
2079 if (m_verbosity > 5) {
2080 pout() << m_name + "::computeConductivityCell(EBAMRCellData)" << endl;
2081 }
2082
2083 this->computeConductivityCell(a_conductivity, m_ito->getParticles(ItoSolver::WhichContainer::Bulk));
2084}
2085
2086template <typename I, typename C, typename R, typename F>
2087void
2089 const Vector<ParticleContainer<ItoParticle>*>& a_particles) noexcept
2090{
2091 CH_TIME("ItoKMCStepper::computeConductivityCell(EBAMRCellData, Particles)");
2092 if (m_verbosity > 5) {
2093 pout() << m_name + "::computeConductivityCell(EBAMRCellData, Particles)" << endl;
2094 }
2095
2096 DataOps::setValue(a_conductivity, 0.0);
2097
2098 // Add contribution from particle solvers
2099 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
2100 RefCountedPtr<ItoSolver>& solver = solverIt();
2101 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
2102
2103 const int idx = solverIt.index();
2104 const int Z = species->getChargeNumber();
2105
2106 if (Z != 0 && solver->isMobile()) {
2107 solver->depositConductivity(m_particleScratch1, *a_particles[idx]);
2108
2109 // Add to the fluid realm.
2111 DataOps::incr(a_conductivity, m_fluidScratch1, 1.0 * std::abs(Z));
2112 }
2113 }
2114
2115 // Add contribution from CDR solvers
2116 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
2117 const RefCountedPtr<CdrSolver>& solver = solverIt();
2118 const RefCountedPtr<CdrSpecies>& species = solver->getSpecies();
2119
2120 const int idx = solverIt.index();
2121 const int Z = species->getChargeNumber();
2122
2123 if (Z != 0 && solver->isMobile()) {
2124 const EBAMRCellData& phi = solver->getPhi();
2125 const EBAMRCellData& mobility = m_cdrMobilities[idx];
2126
2129 DataOps::incr(a_conductivity, m_fluidScratch1, 1.0 * std::abs(Z));
2130 }
2131 }
2132
2133 DataOps::scale(a_conductivity, Units::Qe);
2134
2135 m_amr->arithmeticAverage(a_conductivity, m_fluidRealm, m_plasmaPhase);
2136 m_amr->interpGhostPwl(a_conductivity, m_fluidRealm, m_plasmaPhase);
2137
2138 // Interpolate to centroids.
2139 m_amr->interpToCentroids(a_conductivity, m_fluidRealm, m_plasmaPhase);
2140}
2141
2142template <typename I, typename C, typename R, typename F>
2143void
2145{
2146 CH_TIME("ItoKMCStepper::computeDensityGradients()");
2147 if (m_verbosity > 5) {
2148 pout() << m_name + "::computeDensityGradients()" << endl;
2149 }
2150
2151 const int numItoSpecies = m_physics->getNumItoSpecies();
2152
2153 // Each gradient costs a cross-realm copy, a coarsening, a ghost interpolation and the gradient stencil
2154 // itself, over the whole hierarchy. The reaction kernel reads a gradient slot for every species, but a
2155 // chemistry typically corrects on one or two of them; the rest were computed and never looked at. Ask
2156 // the physics which ones it actually reads, and zero the others so the unread slots hold a defined
2157 // value rather than whatever the last grid left there.
2158 //
2159 // The plasma index is the Ito species first and then the CDR species, matching the density vector that
2160 // updateReactionRates() is handed.
2161
2162 // Do the same for the Ito species.
2163 for (auto it = m_ito->iterator(); it.ok(); ++it) {
2164 const RefCountedPtr<ItoSolver>& solver = it();
2165
2166 const int idx = it.index();
2167
2168 if (!(m_physics->needGradient(idx))) {
2170
2171 continue;
2172 }
2173
2174 // Update ghost cells and coarsenings. Then compute the gradient.
2175 m_amr->copyData(m_fluidPhiIto[idx], solver->getPhi());
2176
2177 m_amr->arithmeticAverage(m_fluidPhiIto[idx], m_fluidRealm, m_plasmaPhase);
2178 m_amr->interpGhostPwl(m_fluidPhiIto[idx], m_fluidRealm, m_plasmaPhase);
2179
2180 m_amr->computeGradient(m_fluidGradPhiIto[idx], m_fluidPhiIto[idx], m_fluidRealm, m_plasmaPhase);
2181 }
2182
2183 // Compute gradients for the CDR species.
2184 for (auto it = m_cdr->iterator(); it.ok(); ++it) {
2185 const RefCountedPtr<CdrSolver>& solver = it();
2186
2187 const int idx = it.index();
2188
2189 if (!(m_physics->needGradient(numItoSpecies + idx))) {
2191
2192 continue;
2193 }
2194
2195 // Update ghost cells and coarsenings. Then compute the gradient.
2196 m_amr->copyData(m_fluidScratch1, solver->getPhi());
2197
2198 m_amr->arithmeticAverage(m_fluidScratch1, m_fluidRealm, m_plasmaPhase);
2200
2202 }
2203}
2204
2205template <typename I, typename C, typename R, typename F>
2206void
2208{
2209 CH_TIME("ItoKMCStepper::computeCurrentDensity(EBAMRCellData)");
2210 if (m_verbosity > 5) {
2211 pout() << m_name + "::computeCurrentDensity(EBAMRCellData)" << endl;
2212 }
2213
2214 CH_assert(a_J[0]->nComp() == SpaceDim);
2215
2216 EBAMRCellData conductivity;
2217 m_amr->allocate(conductivity, m_fluidRealm, m_plasmaPhase, 1);
2218 this->computeConductivityCell(conductivity);
2219
2221 DataOps::multiplyScalar(a_J, conductivity);
2222}
2223
2224template <typename I, typename C, typename R, typename F>
2225Real
2227{
2228 CH_TIME("ItoKMCStepper::computeRelaxationTime()");
2229 if (m_verbosity > 5) {
2230 pout() << m_name + "::computeRelaxationTime()" << endl;
2231 }
2232
2233 // TLDR: We compute eps0/conductivity directly.
2234
2235 EBAMRCellData conductivity;
2236 EBAMRCellData relaxTime;
2237
2238 m_amr->allocate(conductivity, m_fluidRealm, m_plasmaPhase, 1);
2239 m_amr->allocate(relaxTime, m_fluidRealm, m_plasmaPhase, 1);
2240
2241 this->computeConductivityCell(conductivity);
2242
2243 DataOps::setValue(relaxTime, Units::eps0);
2244 DataOps::divideFallback(relaxTime,
2245 conductivity,
2246 std::numeric_limits<Real>::max(),
2247 m_amr->getMultiCutVofIterator(m_fluidRealm, m_plasmaPhase));
2248
2249 m_amr->conservativeAverage(relaxTime, m_fluidRealm, m_plasmaPhase);
2250
2251 Real min = std::numeric_limits<Real>::max();
2252 Real max = -std::numeric_limits<Real>::max();
2253
2254 DataOps::getMaxMinNorm(max, min, relaxTime, m_amr->getMultiCutVofIterator(m_fluidRealm, m_plasmaPhase));
2255
2256 return min;
2257}
2258
2259template <typename I, typename C, typename R, typename F>
2260bool
2262{
2263 CH_TIME("ItoKMCStepper::solvePoisson()");
2264 if (m_verbosity > 5) {
2265 pout() << m_name + "::solvePoisson()" << endl;
2266 }
2267
2268 // Solve the Poisson equation and compute the cell-centered electric field.
2269 MFAMRCellData& phi = m_fieldSolver->getPotential();
2270 MFAMRCellData& rho = m_fieldSolver->getRho();
2271 EBAMRIVData& sigma = m_sigmaSolver->getPhi();
2272
2273 const bool converged = m_fieldSolver->solve(phi, rho, sigma, false);
2274
2275 m_fieldSolver->computeElectricField();
2276
2277 // Copy the electric field to appropriate data holders and perform center-to-centroid
2278 // interpolation.
2279 EBAMRCellData E;
2280 m_amr->allocatePointer(E, m_fluidRealm);
2281 m_amr->alias(E, m_plasmaPhase, m_fieldSolver->getElectricField());
2282
2283 // Fluid realm
2284 m_amr->copyData(m_electricFieldFluid, E);
2285 m_amr->conservativeAverage(m_electricFieldFluid, m_fluidRealm, m_plasmaPhase);
2288
2289 // Particle realm
2290 m_amr->copyData(m_electricFieldParticle, E);
2294
2295 return converged;
2296}
2297
2298template <typename I, typename C, typename R, typename F>
2299void
2301 const SpeciesSubset a_speciesSubset,
2302 const bool a_delete,
2303 const std::function<void(ParticleSoA<ItoParticle>&, std::size_t)> a_nonDeletionModifier) noexcept
2304{
2305 CH_TIME("ItoKMCStepper::intersectParticles(SpeciesSubset, bool, std::function)");
2306 if (m_verbosity > 5) {
2307 pout() << m_name + "::intersectParticles(SpeciesSubset, bool, std::function)" << endl;
2308 }
2309
2310 this->intersectParticles(a_speciesSubset,
2311 ItoSolver::WhichContainer::Bulk,
2312 ItoSolver::WhichContainer::EB,
2313 ItoSolver::WhichContainer::Domain,
2314 a_delete,
2315 a_nonDeletionModifier);
2316}
2317
2318template <typename I, typename C, typename R, typename F>
2319void
2321 const SpeciesSubset a_speciesSubset,
2322 const ItoSolver::WhichContainer a_containerBulk,
2323 const ItoSolver::WhichContainer a_containerEB,
2324 const ItoSolver::WhichContainer a_containerDomain,
2325 const bool a_delete,
2326 const std::function<void(ParticleSoA<ItoParticle>&, std::size_t)> a_nonDeletionModifier) noexcept
2327{
2328 CH_TIME("ItoKMCStepper::intersectParticles(SpeciesSubset, Containerx3, bool, std::function)");
2329 if (m_verbosity > 5) {
2330 pout() << m_name + "::intersectParticles(SpeciesSubset, Containerx3, bool, std::function)" << endl;
2331 }
2332
2333 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
2334 RefCountedPtr<ItoSolver>& solver = solverIt();
2335 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
2336
2337 const bool mobile = solver->isMobile();
2338 const bool diffusive = solver->isDiffusive();
2339 const bool charged = (species->getChargeNumber() != 0);
2340
2341 const EBIntersection intersectionAlgorithm = solver->getIntersectionAlgorithm();
2342
2343 switch (a_speciesSubset) {
2344 case SpeciesSubset::All: {
2345 solver->intersectParticles(a_containerBulk,
2346 a_containerEB,
2347 a_containerDomain,
2348 intersectionAlgorithm,
2349 a_delete,
2350 a_nonDeletionModifier);
2351
2352 break;
2353 }
2355 if (mobile) {
2356 solver->intersectParticles(a_containerBulk,
2357 a_containerEB,
2358 a_containerDomain,
2359 intersectionAlgorithm,
2360 a_delete,
2361 a_nonDeletionModifier);
2362 }
2363
2364 break;
2365 }
2367 if (diffusive) {
2368 solver->intersectParticles(a_containerBulk,
2369 a_containerEB,
2370 a_containerDomain,
2371 intersectionAlgorithm,
2372 a_delete,
2373 a_nonDeletionModifier);
2374 }
2375
2376 break;
2377 }
2379 if (mobile || diffusive) {
2380 solver->intersectParticles(a_containerBulk,
2381 a_containerEB,
2382 a_containerDomain,
2383 intersectionAlgorithm,
2384 a_delete,
2385 a_nonDeletionModifier);
2386 }
2387
2388 break;
2389 }
2391 if (mobile && diffusive) {
2392 solver->intersectParticles(a_containerBulk,
2393 a_containerEB,
2394 a_containerDomain,
2395 intersectionAlgorithm,
2396 a_delete,
2397 a_nonDeletionModifier);
2398 }
2399
2400 break;
2401 }
2403 if (charged) {
2404 solver->intersectParticles(a_containerBulk,
2405 a_containerEB,
2406 a_containerDomain,
2407 intersectionAlgorithm,
2408 a_delete,
2409 a_nonDeletionModifier);
2410 }
2411
2412 break;
2413 }
2415 if (charged && mobile) {
2416 solver->intersectParticles(a_containerBulk,
2417 a_containerEB,
2418 a_containerDomain,
2419 intersectionAlgorithm,
2420 a_delete,
2421 a_nonDeletionModifier);
2422 }
2423
2424 break;
2425 }
2427 if (charged && diffusive) {
2428 solver->intersectParticles(a_containerBulk,
2429 a_containerEB,
2430 a_containerDomain,
2431 intersectionAlgorithm,
2432 a_delete,
2433 a_nonDeletionModifier);
2434 }
2435
2436 break;
2437 }
2439 if (charged && (mobile || diffusive)) {
2440 solver->intersectParticles(a_containerBulk,
2441 a_containerEB,
2442 a_containerDomain,
2443 intersectionAlgorithm,
2444 a_delete,
2445 a_nonDeletionModifier);
2446 }
2447
2448 break;
2449 }
2451 if (charged && (mobile && diffusive)) {
2452 solver->intersectParticles(a_containerBulk,
2453 a_containerEB,
2454 a_containerDomain,
2455 intersectionAlgorithm,
2456 a_delete,
2457 a_nonDeletionModifier);
2458 }
2459
2460 break;
2461 }
2463 if (!mobile && !diffusive) {
2464 solver->intersectParticles(a_containerBulk,
2465 a_containerEB,
2466 a_containerDomain,
2467 intersectionAlgorithm,
2468 a_delete,
2469 a_nonDeletionModifier);
2470 }
2471
2472 break;
2473 }
2474 default: {
2475 MayDay::Abort("ItoKMCStepper::intersectParticles - logic bust");
2476
2477 break;
2478 }
2479 }
2480 }
2481}
2482
2483template <typename I, typename C, typename R, typename F>
2484void
2486 const EBRepresentation a_representation,
2487 const Real a_tolerance) noexcept
2488{
2489 CH_TIME("ItoKMCStepper::removeCoveredParticles(SpeciesSubset, EBRepresentation, Real)");
2490 if (m_verbosity > 5) {
2491 pout() << m_name + "::removeCoveredParticles(SpeciesSubset, EBRepresentation, Real)" << endl;
2492 }
2493
2494 this->removeCoveredParticles(a_speciesSubset, ItoSolver::WhichContainer::Bulk, a_representation, a_tolerance);
2495}
2496
2497template <typename I, typename C, typename R, typename F>
2498void
2500 const ItoSolver::WhichContainer a_container,
2501 const EBRepresentation a_representation,
2502 const Real a_tolerance) noexcept
2503{
2504 CH_TIME("ItoKMCStepper::removeCoveredParticles(SpeciesSubset, container, EBRepresentation, tolerance)");
2505 if (m_verbosity > 5) {
2506 pout() << m_name + "::removeCoveredParticles(SpeciesSubset, container, EBRepresentation, tolerance)" << endl;
2507 }
2508
2509 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
2510 RefCountedPtr<ItoSolver>& solver = solverIt();
2511 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
2512
2513 const bool mobile = solver->isMobile();
2514 const bool diffusive = solver->isDiffusive();
2515 const bool charged = (species->getChargeNumber() != 0);
2516
2517 switch (a_which) {
2518 case SpeciesSubset::All: {
2519 solver->removeCoveredParticles(a_container, a_representation, a_tolerance);
2520
2521 break;
2522 }
2524 if (mobile) {
2525 solver->removeCoveredParticles(a_container, a_representation, a_tolerance);
2526 }
2527
2528 break;
2529 }
2531 if (diffusive) {
2532 solver->removeCoveredParticles(a_container, a_representation, a_tolerance);
2533 }
2534
2535 break;
2536 }
2538 if (mobile || diffusive) {
2539 solver->removeCoveredParticles(a_container, a_representation, a_tolerance);
2540 }
2541
2542 break;
2543 }
2545 if (mobile && diffusive) {
2546 solver->removeCoveredParticles(a_container, a_representation, a_tolerance);
2547 }
2548
2549 break;
2550 }
2552 if (charged) {
2553 solver->removeCoveredParticles(a_container, a_representation, a_tolerance);
2554 }
2555
2556 break;
2557 }
2559 if (charged && mobile) {
2560 solver->removeCoveredParticles(a_container, a_representation, a_tolerance);
2561 }
2562
2563 break;
2564 }
2566 if (charged && diffusive) {
2567 solver->removeCoveredParticles(a_container, a_representation, a_tolerance);
2568 }
2569
2570 break;
2571 }
2573 if (charged && (mobile || diffusive)) {
2574 solver->removeCoveredParticles(a_container, a_representation, a_tolerance);
2575 }
2576
2577 break;
2578 }
2580 if (charged && (mobile && diffusive)) {
2581 solver->removeCoveredParticles(a_container, a_representation, a_tolerance);
2582 }
2583
2584 break;
2585 }
2587 if (!mobile && !diffusive) {
2588 solver->removeCoveredParticles(a_container, a_representation, a_tolerance);
2589 }
2590
2591 break;
2592 }
2593 default: {
2594 MayDay::Abort("ItoKMCStepper::removeCoveredParticles - logic bust");
2595
2596 break;
2597 }
2598 }
2599 }
2600}
2601
2602template <typename I, typename C, typename R, typename F>
2603void
2605 const EBRepresentation a_representation,
2606 const Real a_tolerance) noexcept
2607{
2608 CH_TIME("ItoKMCStepper::transferCoveredParticles(SpeciesSubset, EBRepresentation, Real)");
2609 if (m_verbosity > 5) {
2610 pout() << m_name + "::transferCoveredParticles(SpeciesSubset, EBRepresentation, Real)" << endl;
2611 }
2612
2613 this->transferCoveredParticles(a_speciesSubset,
2614 ItoSolver::WhichContainer::Bulk,
2615 ItoSolver::WhichContainer::Covered,
2616 a_representation,
2617 a_tolerance);
2618}
2619
2620template <typename I, typename C, typename R, typename F>
2621void
2623 const ItoSolver::WhichContainer a_containerFrom,
2624 const ItoSolver::WhichContainer a_containerTo,
2625 const EBRepresentation a_representation,
2626 const Real a_tolerance) noexcept
2627{
2628 CH_TIME("ItoKMCStepper::transferCoveredParticles(SpeciesSubset, Containerx2, EBRepresentation, Real)");
2629 if (m_verbosity > 5) {
2630 pout() << m_name + "::transferCoveredParticles(SpeciesSubset, Containerx2, EBRepresentation, Real)" << endl;
2631 }
2632
2633 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
2634 RefCountedPtr<ItoSolver>& solver = solverIt();
2635 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
2636
2637 const bool mobile = solver->isMobile();
2638 const bool diffusive = solver->isDiffusive();
2639 const bool charged = (species->getChargeNumber() != 0);
2640
2641 switch (a_speciesSubset) {
2642 case SpeciesSubset::All: {
2643 solver->transferCoveredParticles(a_containerFrom, a_containerTo, a_representation, a_tolerance);
2644
2645 break;
2646 }
2648 if (mobile) {
2649 solver->transferCoveredParticles(a_containerFrom, a_containerTo, a_representation, a_tolerance);
2650 }
2651
2652 break;
2653 }
2655 if (diffusive) {
2656 solver->transferCoveredParticles(a_containerFrom, a_containerTo, a_representation, a_tolerance);
2657 }
2658
2659 break;
2660 }
2662 if (mobile || diffusive) {
2663 solver->transferCoveredParticles(a_containerFrom, a_containerTo, a_representation, a_tolerance);
2664 }
2665
2666 break;
2667 }
2669 if (mobile && diffusive) {
2670 solver->transferCoveredParticles(a_containerFrom, a_containerTo, a_representation, a_tolerance);
2671 }
2672
2673 break;
2674 }
2676 if (charged) {
2677 solver->transferCoveredParticles(a_containerFrom, a_containerTo, a_representation, a_tolerance);
2678 }
2679
2680 break;
2681 }
2683 if (charged && mobile) {
2684 solver->transferCoveredParticles(a_containerFrom, a_containerTo, a_representation, a_tolerance);
2685 }
2686
2687 break;
2688 }
2690 if (charged && diffusive) {
2691 solver->transferCoveredParticles(a_containerFrom, a_containerTo, a_representation, a_tolerance);
2692 }
2693
2694 break;
2695 }
2697 if (charged && (mobile || diffusive)) {
2698 solver->transferCoveredParticles(a_containerFrom, a_containerTo, a_representation, a_tolerance);
2699 }
2700
2701 break;
2702 }
2704 if (charged && (mobile && diffusive)) {
2705 solver->transferCoveredParticles(a_containerFrom, a_containerTo, a_representation, a_tolerance);
2706 }
2707
2708 break;
2709 }
2711 if (!mobile && !diffusive) {
2712 solver->transferCoveredParticles(a_containerFrom, a_containerTo, a_representation, a_tolerance);
2713 }
2714
2715 break;
2716 }
2717 default: {
2718 MayDay::Abort("ItoKMCStepper::transferCoveredParticles - logic bust");
2719
2720 break;
2721 }
2722 }
2723 }
2724}
2725
2726template <typename I, typename C, typename R, typename F>
2727void
2729{
2730 CH_TIME("ItoKMCStepper::remapParticles(SpeciesSubset)");
2731 if (m_verbosity > 5) {
2732 pout() << m_name + "::remapParticles(SpeciesSubset)" << endl;
2733 }
2734
2735 this->remapParticles(a_speciesSubset, ItoSolver::WhichContainer::Bulk);
2736}
2737
2738template <typename I, typename C, typename R, typename F>
2739void
2741 const ItoSolver::WhichContainer a_container) noexcept
2742{
2743 CH_TIME("ItoKMCStepper::remapParticles(SpeciesSubset, WhichContainer)");
2744 if (m_verbosity > 5) {
2745 pout() << m_name + "::remapParticles(SpeciesSubset, WhichContainer)" << endl;
2746 }
2747
2748 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
2749 RefCountedPtr<ItoSolver>& solver = solverIt();
2750 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
2751
2752 const bool mobile = solver->isMobile();
2753 const bool diffusive = solver->isDiffusive();
2754 const bool charged = (species->getChargeNumber() != 0);
2755
2756 switch (a_speciesSubset) {
2757 case SpeciesSubset::All: {
2758 solver->remap(a_container);
2759
2760 break;
2761 }
2763 if (mobile) {
2764 solver->remap(a_container);
2765 }
2766
2767 break;
2768 }
2770 if (diffusive) {
2771 solver->remap(a_container);
2772 }
2773
2774 break;
2775 }
2777 if (mobile || diffusive) {
2778 solver->remap(a_container);
2779 }
2780
2781 break;
2782 }
2784 if (mobile && diffusive) {
2785 solver->remap(a_container);
2786 }
2787
2788 break;
2789 }
2791 if (charged) {
2792 solver->remap(a_container);
2793 }
2794
2795 break;
2796 }
2798 if (charged && mobile) {
2799 solver->remap(a_container);
2800 }
2801
2802 break;
2803 }
2805 if (charged && diffusive) {
2806 solver->remap(a_container);
2807 }
2808
2809 break;
2810 }
2812 if (charged && (mobile || diffusive)) {
2813 solver->remap(a_container);
2814 }
2815
2816 break;
2817 }
2819 if (charged && (mobile && diffusive)) {
2820 solver->remap(a_container);
2821 }
2822
2823 break;
2824 }
2826 if (!mobile && !diffusive) {
2827 solver->remap(a_container);
2828 }
2829
2830 break;
2831 }
2832 default: {
2833 MayDay::Abort("ItoKMCStepper::remapParticles - logic bust");
2834
2835 break;
2836 }
2837 }
2838 }
2839}
2840
2841template <typename I, typename C, typename R, typename F>
2842void
2844{
2845 CH_TIME("ItoKMCStepper::depositParticles(SpeciesSubset)");
2846 if (m_verbosity > 5) {
2847 pout() << m_name + "::depositParticles(SpeciesSubset)" << endl;
2848 }
2849
2850 this->depositParticles(a_speciesSubset, ItoSolver::WhichContainer::Bulk);
2851}
2852
2853template <typename I, typename C, typename R, typename F>
2854void
2856 const ItoSolver::WhichContainer a_container) noexcept
2857{
2858 CH_TIME("ItoKMCStepper::depositParticles(SpeciesSubset)");
2859 if (m_verbosity > 5) {
2860 pout() << m_name + "::depositParticles(SpeciesSubset)" << endl;
2861 }
2862
2863 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
2864 RefCountedPtr<ItoSolver>& solver = solverIt();
2865 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
2866
2867 const bool mobile = solver->isMobile();
2868 const bool diffusive = solver->isDiffusive();
2869 const bool charged = (species->getChargeNumber() != 0);
2870
2871 switch (a_speciesSubset) {
2872 case SpeciesSubset::All: {
2873 solver->depositParticles(a_container);
2874
2875 break;
2876 }
2878 if (mobile) {
2879 solver->depositParticles(a_container);
2880 }
2881
2882 break;
2883 }
2885 if (diffusive) {
2886 solver->depositParticles(a_container);
2887 }
2888
2889 break;
2890 }
2892 if (mobile || diffusive) {
2893 solver->depositParticles(a_container);
2894 }
2895
2896 break;
2897 }
2899 if (mobile && diffusive) {
2900 solver->depositParticles(a_container);
2901 }
2902
2903 break;
2904 }
2906 if (charged) {
2907 solver->depositParticles(a_container);
2908 }
2909
2910 break;
2911 }
2913 if (charged && mobile) {
2914 solver->depositParticles(a_container);
2915 }
2916
2917 break;
2918 }
2920 if (charged && diffusive) {
2921 solver->depositParticles(a_container);
2922 }
2923
2924 break;
2925 }
2927 if (charged && (mobile || diffusive)) {
2928 solver->depositParticles(a_container);
2929 }
2930
2931 break;
2932 }
2934 if (charged && (mobile && diffusive)) {
2935 solver->depositParticles(a_container);
2936 }
2937
2938 break;
2939 }
2941 if (!mobile && !diffusive) {
2942 solver->depositParticles(a_container);
2943 }
2944
2945 break;
2946 }
2947 default: {
2948 MayDay::Abort("ItoKMCStepper::depositParticles - logic bust");
2949
2950 break;
2951 }
2952 }
2953 }
2954}
2955
2956template <typename I, typename C, typename R, typename F>
2957void
2959{
2960 CH_TIME("ItoKMCStepper::setItoVelocityFunctions");
2961 if (m_verbosity > 5) {
2962 pout() << m_name + "::setItoVelocityFunctions" << endl;
2963 }
2964
2965 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
2966 RefCountedPtr<ItoSolver>& solver = solverIt();
2967 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
2968 const int Z = species->getChargeNumber();
2969
2970 if (solver->isMobile() && Z != 0) {
2971 EBAMRCellData& velocityFunction = solver->getVelocityFunction();
2972 m_amr->copyData(velocityFunction, m_electricFieldParticle);
2973
2974 const int Z = species->getChargeNumber();
2975
2976 if (Z < 0) {
2977 DataOps::scale(velocityFunction, -1.0);
2978 }
2979
2980 // Coarsen and update ghost cells.
2981 m_amr->conservativeAverage(velocityFunction, m_particleRealm, m_plasmaPhase);
2982 m_amr->interpGhostPwl(velocityFunction, m_particleRealm, m_plasmaPhase);
2983 }
2984 }
2985}
2986
2987template <typename I, typename C, typename R, typename F>
2988void
2990{
2991 CH_TIME("ItoKMCStepper::setCdrVelocityFunctions");
2992 if (m_verbosity > 5) {
2993 pout() << m_name + "::setCdrVelocityFunctions" << endl;
2994 }
2995
2996 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
2997 RefCountedPtr<CdrSolver>& solver = solverIt();
2998 const RefCountedPtr<CdrSpecies>& species = solver->getSpecies();
2999 const int Z = species->getChargeNumber();
3000
3001 if (solver->isMobile() && Z != 0) {
3002 EBAMRCellData& velocity = solver->getCellCenteredVelocity();
3003 m_amr->copyData(velocity, m_electricFieldFluid);
3004
3005 const int Z = species->getChargeNumber();
3006
3007 if (Z < 0) {
3008 DataOps::scale(velocity, -1.0);
3009 }
3010
3011 // Coarsen and update ghost cells.
3012 m_amr->conservativeAverage(velocity, m_fluidRealm, m_plasmaPhase);
3013 m_amr->interpGhostPwl(velocity, m_fluidRealm, m_plasmaPhase);
3014 }
3015 else if (solver->isMobile() && Z == 0) {
3016 MayDay::Warning("ItoKMCStepper::setCdrVelocityFunctions -- how to handle mobile neutral species?");
3017 }
3018 }
3019}
3020
3021template <typename I, typename C, typename R, typename F>
3022void
3024{
3025 CH_TIME("ItoKMCStepper::multiplyCdrVelocitiesByMobilities()");
3026 if (m_verbosity > 5) {
3027 pout() << m_name + "::multiplyCdrVelocitiesByMobilities()" << endl;
3028 }
3029
3030 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
3031 RefCountedPtr<CdrSolver>& solver = solverIt();
3032 const int idx = solverIt.index();
3033
3034 if (solver->isMobile()) {
3035 EBAMRCellData& velocity = solver->getCellCenteredVelocity();
3036 const EBAMRCellData& mobility = m_cdrMobilities[idx];
3037
3038 DataOps::multiplyScalar(velocity, mobility);
3039
3040 // Coarsen and update ghost cells.
3041 m_amr->conservativeAverage(velocity, m_fluidRealm, m_plasmaPhase);
3042 m_amr->interpGhostPwl(velocity, m_fluidRealm, m_plasmaPhase);
3043 }
3044 }
3045}
3046
3047template <typename I, typename C, typename R, typename F>
3048void
3050{
3051 CH_TIME("ItoKMCStepper::computeDriftVelocities()");
3052 if (m_verbosity > 5) {
3053 pout() << m_name + "::computeDriftVelocities()" << endl;
3054 }
3055
3056 // Set velocities to be sgn(Z) * E
3059
3060 // Compute mobilities for both Ito and CDR species.
3061 this->computeMobilities();
3062
3063 // Multiply sgn(Z) * E by the mobilities. For the CDR solvers this is just a multiplication, for the Ito solvers
3064 // we interpolate mu*E to the particle positions (in some form).
3065 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
3066 solverIt()->interpolateVelocities();
3067 }
3068
3070}
3071
3072template <typename I, typename C, typename R, typename F>
3073void
3075{
3076 CH_TIME("ItoKMCStepper::computeMobilities()");
3077 if (m_verbosity > 5) {
3078 pout() << m_name + "::computeMobilities()" << endl;
3079 }
3080
3081 Vector<EBAMRCellData*> itoMobilities = m_ito->getMobilityFunctions();
3082
3084}
3085
3086template <typename I, typename C, typename R, typename F>
3087void
3088ItoKMCStepper<I, C, R, F>::computeMobilities(Vector<EBAMRCellData*>& a_itoMobilities,
3089 Vector<EBAMRCellData>& a_cdrMobilities,
3090 const EBAMRCellData& a_electricField,
3091 const Real a_time) noexcept
3092{
3093 CH_TIME("ItoKMCStepper::computeMobilities(mobilities, E, time)");
3094 if (m_verbosity > 5) {
3095 pout() << m_name + "::computeMobilities(mobilities, E, time)" << endl;
3096 }
3097
3098 const int numItoSpecies = m_physics->getNumItoSpecies();
3099 const int numCdrSpecies = m_physics->getNumCdrSpecies();
3100
3101 CH_assert(a_electricField.getRealm() == m_fluidRealm);
3102 CH_assert(a_itoMobilities.size() == numItoSpecies);
3103 CH_assert(a_cdrMobilities.size() == numCdrSpecies);
3104
3105 // The mesh mobilities belong on the particle realm (they are the ItoSolver mobilities) but we need to run
3106 // the computation on the fluid realm. m_fluidScratchIto is that staging area -- a member rather than a
3107 // local, because allocating one hierarchy per species per time step defines an exchange Copier per level
3108 // for storage that does not outlive the call.
3109 CH_assert(m_fluidScratchIto.size() == numItoSpecies);
3110
3111 for (int i = 0; i < numItoSpecies; i++) {
3113 DataOps::setValue(*a_itoMobilities[i], 0.0);
3114
3115 CH_assert(a_itoMobilities[i]->getRealm() == m_particleRealm);
3116 }
3117
3118 // Now run the computation on the fluid realm, computing the mobilities into fluidScratchMobilities
3119 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
3120 Vector<LevelData<EBCellFAB>*> itoMobilities(numItoSpecies);
3121 Vector<LevelData<EBCellFAB>*> cdrMobilities(numCdrSpecies);
3122
3123 for (int i = 0; i < numItoSpecies; i++) {
3124 itoMobilities[i] = &(*(m_fluidScratchIto[i])[lvl]);
3125 }
3126
3127 for (int i = 0; i < numCdrSpecies; i++) {
3128 cdrMobilities[i] = &(*(a_cdrMobilities[i])[lvl]);
3129 }
3130
3131 // Run the level computation, which will fill the mobilities.
3132 this->computeMobilities(itoMobilities, cdrMobilities, *a_electricField[lvl], lvl, a_time);
3133 }
3134
3135 // Copy fluid realm data into particle realm and interpolate mobilities to the particle position.
3136 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
3137 RefCountedPtr<ItoSolver>& solver = solverIt();
3138
3139 if (solver->isMobile()) {
3140 const int idx = solverIt.index();
3141
3142 m_amr->copyData(*a_itoMobilities[idx], m_fluidScratchIto[idx]);
3143 m_amr->conservativeAverage(*a_itoMobilities[idx], m_particleRealm, m_plasmaPhase);
3144 m_amr->interpGhostPwl(*a_itoMobilities[idx], m_particleRealm, m_plasmaPhase);
3145
3146 solver->interpolateMobilities();
3147 }
3148 }
3149}
3150
3151template <typename I, typename C, typename R, typename F>
3152void
3153ItoKMCStepper<I, C, R, F>::computeMobilities(Vector<LevelData<EBCellFAB>*>& a_itoMobilities,
3154 Vector<LevelData<EBCellFAB>*>& a_cdrMobilities,
3155 const LevelData<EBCellFAB>& a_electricField,
3156 const int a_level,
3157 const Real a_time) noexcept
3158{
3159 CH_TIME("ItoKMCStepper::computeMobilities(mobilities, E, level, time)");
3160 if (m_verbosity > 5) {
3161 pout() << m_name + "::computeMobilities(mobilities, E, level, time)" << endl;
3162 }
3163
3164 const DisjointBoxLayout& dbl = m_amr->getGrids(m_fluidRealm)[a_level];
3165 const DataIterator& dit = dbl.dataIterator();
3166
3167 const int nbox = dit.size();
3168
3169#pragma omp parallel for schedule(runtime)
3170 for (int mybox = 0; mybox < nbox; mybox++) {
3171 const DataIndex& din = dit[mybox];
3172
3173 const EBCellFAB& E = a_electricField[din];
3174 const Box cellBox = dbl[din];
3175
3176 Vector<EBCellFAB*> itoMobilities;
3177 Vector<EBCellFAB*> cdrMobilities;
3178
3179 for (int i = 0; i < a_itoMobilities.size(); i++) {
3180 itoMobilities.push_back(&((*a_itoMobilities[i])[din]));
3181 }
3182
3183 for (int i = 0; i < a_cdrMobilities.size(); i++) {
3184 cdrMobilities.push_back(&((*a_cdrMobilities[i])[din]));
3185 }
3186
3187 this->computeMobilities(itoMobilities, cdrMobilities, E, a_level, din, cellBox, a_time);
3188 }
3189}
3190
3191template <typename I, typename C, typename R, typename F>
3192void
3193ItoKMCStepper<I, C, R, F>::computeMobilities(Vector<EBCellFAB*>& a_itoMobilities,
3194 Vector<EBCellFAB*>& a_cdrMobilities,
3195 const EBCellFAB& a_electricField,
3196 const int a_level,
3197 const DataIndex a_din,
3198 const Box a_box,
3199 const Real a_time) noexcept
3200{
3201 CH_TIME("ItoKMCStepper::computeMobilities(meshMobilities, E, level, dit, box, time)");
3202 if (m_verbosity > 5) {
3203 pout() << m_name + "::computeMobilities(meshMobilities, E, level, dit, box, time)" << endl;
3204 }
3205
3206 // TLDR: We go through each and every cell and call the physics interface. This includes cells covered by a finer grid
3207 // but data is coarsened later anyways.
3208 const int numItoSpecies = m_physics->getNumItoSpecies();
3209 const int numCdrSpecies = m_physics->getNumCdrSpecies();
3210 const int numPlasmaSpecies = m_physics->getNumPlasmaSpecies();
3211
3212 const Real dx = m_amr->getDx()[a_level];
3213 const RealVect probLo = m_amr->getProbLo();
3214 const EBISBox& ebisbox = m_amr->getEBISLayout(m_fluidRealm, m_plasmaPhase)[a_level][a_din];
3215
3216 // Handles to regular data.
3217 const FArrayBox& electricFieldReg = a_electricField.getFArrayBox();
3218 Vector<FArrayBox*> itoMobilitiesReg(numItoSpecies);
3219 Vector<FArrayBox*> cdrMobilitiesReg(numCdrSpecies);
3220
3221 for (int i = 0; i < a_itoMobilities.size(); i++) {
3222 itoMobilitiesReg[i] = (&(a_itoMobilities[i]->getFArrayBox()));
3223 }
3224
3225 for (int i = 0; i < a_cdrMobilities.size(); i++) {
3226 cdrMobilitiesReg[i] = (&(a_cdrMobilities[i]->getFArrayBox()));
3227 }
3228
3229 // Physics interface mapping -- this maps a global index from the returned vector to an Ito or CDR solver
3230 const std::map<int, std::pair<SpeciesType, int>>& speciesMap = m_physics->getSpeciesMap();
3231
3232 // One buffer for the whole patch. The physics call fills it per cell; letting it return a vector instead
3233 // meant an allocation and a free in every cell of the domain. Declared here rather than in the kernels so
3234 // both share it -- they never run concurrently, and this function is already per-patch, so the buffer is
3235 // private to the thread that owns this patch.
3236 Vector<Real> mobilities;
3237
3238 // Regular kernel
3239 auto regularKernel = [&](const IntVect& iv) -> void {
3240 const RealVect pos = m_amr->getProbLo() + dx * (RealVect(iv) + 0.5 * RealVect::Unit);
3241 const RealVect E = RealVect(D_DECL(electricFieldReg(iv, 0), electricFieldReg(iv, 1), electricFieldReg(iv, 2)));
3242
3243 // Call physics interface and compute mobilities for each species.
3244 m_physics->computeMobilities(mobilities, a_time, pos, E);
3245
3246 CH_assert(mobilities.size() == numPlasmaSpecies);
3247
3248 // Put the mobilities where they belong.
3249 for (const auto& s : speciesMap) {
3250 const int& globalIndex = s.first;
3251 const SpeciesType& type = s.second.first;
3252 const int& localIndex = s.second.second;
3253
3254 if (type == SpeciesType::Ito) {
3255 (*itoMobilitiesReg[localIndex])(iv, 0) = mobilities[globalIndex];
3256 }
3257 else if (type == SpeciesType::CDR) {
3258 (*cdrMobilitiesReg[localIndex])(iv, 0) = mobilities[globalIndex];
3259 }
3260 }
3261 };
3262
3263 // Irregular kernel.
3264 auto irregularKernel = [&](const VolIndex& vof) -> void {
3265 const RealVect e = RealVect(D_DECL(a_electricField(vof, 0), a_electricField(vof, 1), a_electricField(vof, 2)));
3266 const RealVect pos = probLo + Location::position(Location::Cell::Centroid, vof, ebisbox, dx);
3267
3268 // Call physics interface and compute mobilities for each species.
3269 m_physics->computeMobilities(mobilities, a_time, pos, e);
3270
3271 CH_assert(mobilities.size() == numPlasmaSpecies);
3272
3273 // Put the mobilities where they belong.
3274 for (const auto& s : speciesMap) {
3275 const int& globalIndex = s.first;
3276 const SpeciesType& type = s.second.first;
3277 const int& localIndex = s.second.second;
3278
3279 if (type == SpeciesType::Ito) {
3280 (*a_itoMobilities[localIndex])(vof, 0) = mobilities[globalIndex];
3281 }
3282 else if (type == SpeciesType::CDR) {
3283 (*a_cdrMobilities[localIndex])(vof, 0) = mobilities[globalIndex];
3284 }
3285 }
3286 };
3287
3288 VoFIterator& vofit = (*m_amr->getVofIterator(m_fluidRealm, m_plasmaPhase)[a_level])[a_din];
3289
3290 // Run the kernels. Not vectorizable: m_physics->computeMobilities is an opaque virtual call
3291 // (heap allocation) per cell, then scattered to the per-species data holders.
3292 BoxLoops::loop<D_DECL(1, 1, 1)>(a_box, regularKernel);
3293 BoxLoops::loop(vofit, irregularKernel);
3294
3295 // Covered is bogus.
3296 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
3297 a_itoMobilities[solverIt.index()]->setCoveredCellVal(0.0, 0);
3298 }
3299
3300 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
3301 a_cdrMobilities[solverIt.index()]->setCoveredCellVal(0.0, 0);
3302 }
3303}
3304
3305template <typename I, typename C, typename R, typename F>
3306void
3308{
3309 CH_TIME("ItoKMCStepper::computeDiffusionCoefficients()");
3310 if (m_verbosity > 5) {
3311 pout() << m_name + "::computeDiffusionCoefficients()" << endl;
3312 }
3313
3314 Vector<EBAMRCellData*> itoDiffusionCoefficients = m_ito->getDiffusionFunctions();
3315 Vector<EBAMRCellData*> cdrDiffusionCoefficients = m_cdr->getCellCenteredDiffusionCoefficients();
3316
3317 this->computeDiffusionCoefficients(itoDiffusionCoefficients, cdrDiffusionCoefficients, m_electricFieldFluid, m_time);
3319}
3320
3321template <typename I, typename C, typename R, typename F>
3322void
3323ItoKMCStepper<I, C, R, F>::computeDiffusionCoefficients(Vector<EBAMRCellData*>& a_itoDiffusionCoefficients,
3324 Vector<EBAMRCellData*>& a_cdrDiffusionCoefficients,
3325 const EBAMRCellData& a_electricField,
3326 const Real a_time) noexcept
3327{
3328 CH_TIME("ItoKMCStepper::computeDiffusionCoefficients(Vector<EBAMRCellData*>, EBAMRCellData, Real)");
3329 if (m_verbosity > 5) {
3330 pout() << m_name + "::computeDiffusionCoefficients(Vector<EBAMRCellData*>, EBAMRCellData, Real)" << endl;
3331 }
3332
3333 const int numItoSpecies = m_physics->getNumItoSpecies();
3334 const int numCdrSpecies = m_physics->getNumCdrSpecies();
3335
3336 CH_assert(a_electricField.getRealm() == m_fluidRealm);
3337 CH_assert(a_itoDiffusionCoefficients.size() == numItoSpecies);
3338 CH_assert(a_cdrDiffusionCoefficients.size() == numCdrSpecies);
3339
3340 // Sanity check -- things need to be defined on the correct realms.
3341 for (int i = 0; i < numItoSpecies; i++) {
3342 CH_assert(a_itoDiffusionCoefficients[i]->getRealm() == m_particleRealm);
3343 }
3344 for (int i = 0; i < numCdrSpecies; i++) {
3345 CH_assert(a_cdrDiffusionCoefficients[i]->getRealm() == m_fluidRealm);
3346 }
3347
3348 // The mesh diffusion coefficients belong on the particle realm (they are the ItoSolver diffusion
3349 // coefficients) but we need to run the computation on the fluid realm. m_fluidScratchIto is that staging
3350 // area; see computeMobilities(), which uses it for the same purpose at a different point in the step.
3351 CH_assert(m_fluidScratchIto.size() == numItoSpecies);
3352
3353 // The staging area is copied whole, ghost cells included, and the coefficients are computed on the valid and covered
3354 // cells only, so it is cleared first rather than relying on what an earlier use left in it.
3355 for (int i = 0; i < numItoSpecies; i++) {
3357 }
3358
3359 // Compute mesh-based diffusion coefficients on the fluid realm.
3360 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
3361 Vector<LevelData<EBCellFAB>*> itoDiffusionCoefficients(numItoSpecies);
3362 Vector<LevelData<EBCellFAB>*> cdrDiffusionCoefficients(numCdrSpecies);
3363
3364 for (int i = 0; i < numItoSpecies; i++) {
3365 itoDiffusionCoefficients[i] = &(*(m_fluidScratchIto[i])[lvl]);
3366 }
3367 for (int i = 0; i < numCdrSpecies; i++) {
3368 cdrDiffusionCoefficients[i] = &(*(*a_cdrDiffusionCoefficients[i])[lvl]);
3369 }
3370
3371 this->computeDiffusionCoefficients(itoDiffusionCoefficients,
3372 cdrDiffusionCoefficients,
3373 *a_electricField[lvl],
3374 lvl,
3375 a_time);
3376 }
3377
3378 // Copy the fluid realm data over to the particle realm data and then coarsen and interpolate diffusion coefficients
3379 // to particle positions.
3380 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
3381 RefCountedPtr<ItoSolver>& solver = solverIt();
3382
3383 if (solver->isDiffusive()) {
3384 const int idx = solverIt.index();
3385
3386 m_amr->copyData(*a_itoDiffusionCoefficients[idx], m_fluidScratchIto[idx]);
3387 m_amr->conservativeAverage(*a_itoDiffusionCoefficients[idx], m_particleRealm, m_plasmaPhase);
3388 m_amr->interpGhostPwl(*a_itoDiffusionCoefficients[idx], m_particleRealm, m_plasmaPhase);
3389
3390 solver->interpolateDiffusion();
3391 }
3392 }
3393}
3394
3395template <typename I, typename C, typename R, typename F>
3396void
3397ItoKMCStepper<I, C, R, F>::computeDiffusionCoefficients(Vector<LevelData<EBCellFAB>*>& a_itoDiffusionCoefficients,
3398 Vector<LevelData<EBCellFAB>*>& a_cdrDiffusionCoefficients,
3399 const LevelData<EBCellFAB>& a_electricField,
3400 const int a_level,
3401 const Real a_time) noexcept
3402{
3403 CH_TIME("ItoKMCStepper::computeDiffusionCoefficients(Vector<LD<EBCellFAB>*>, LD<EBCellFAB>, int, Real)");
3404 if (m_verbosity > 5) {
3405 pout() << m_name + "::computeDiffusionCoefficients(Vector<LD<EBCellFAB>*>, LD<EBCellFAB>, int, Real)" << endl;
3406 }
3407
3408 const int numItoSpecies = m_physics->getNumItoSpecies();
3409 const int numCdrSpecies = m_physics->getNumCdrSpecies();
3410
3411 CH_assert(a_itoDiffusionCoefficients.size() == numItoSpecies);
3412 CH_assert(a_cdrDiffusionCoefficients.size() == numCdrSpecies);
3413
3414 const DisjointBoxLayout& dbl = m_amr->getGrids(m_fluidRealm)[a_level];
3415 const DataIterator& dit = dbl.dataIterator();
3416
3417 const int nbox = dit.size();
3418
3419#pragma omp parallel for schedule(runtime)
3420 for (int mybox = 0; mybox < nbox; mybox++) {
3421 const DataIndex& din = dit[mybox];
3422
3423 Vector<EBCellFAB*> itoDiffusionCoefficients(numItoSpecies);
3424 Vector<EBCellFAB*> cdrDiffusionCoefficients(numCdrSpecies);
3425
3426 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
3427 const int idx = solverIt.index();
3428
3429 if (solverIt()->isDiffusive()) {
3430 itoDiffusionCoefficients[idx] = &(*a_itoDiffusionCoefficients[idx])[din];
3431 }
3432 else {
3433 itoDiffusionCoefficients[idx] = nullptr;
3434 }
3435 }
3436
3437 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
3438 const int idx = solverIt.index();
3439
3440 if (solverIt()->isDiffusive()) {
3441 cdrDiffusionCoefficients[idx] = &(*a_cdrDiffusionCoefficients[idx])[din];
3442 }
3443 else {
3444 cdrDiffusionCoefficients[idx] = nullptr;
3445 }
3446 }
3447
3448 this->computeDiffusionCoefficients(itoDiffusionCoefficients,
3449 cdrDiffusionCoefficients,
3450 a_electricField[din],
3451 a_level,
3452 din,
3453 dbl[din],
3454 a_time);
3455 }
3456}
3457
3458template <typename I, typename C, typename R, typename F>
3459void
3460ItoKMCStepper<I, C, R, F>::computeDiffusionCoefficients(Vector<EBCellFAB*>& a_itoDiffusionCoefficients,
3461 Vector<EBCellFAB*>& a_cdrDiffusionCoefficients,
3462 const EBCellFAB& a_electricField,
3463 const int a_level,
3464 const DataIndex a_din,
3465 const Box a_box,
3466 const Real a_time) noexcept
3467{
3468 CH_TIME("ItoKMCStepper::computeDiffusionCoefficients(Patch)");
3469 if (m_verbosity > 5) {
3470 pout() << m_name + "::computeDiffusionCoefficients(Patch)" << endl;
3471 }
3472
3473 const int numItoSpecies = m_physics->getNumItoSpecies();
3474 const int numCdrSpecies = m_physics->getNumCdrSpecies();
3475 const int numPlasmaSpecies = m_physics->getNumPlasmaSpecies();
3476
3477 CH_assert(a_electricField.nComp() == SpaceDim);
3478 CH_assert(a_itoDiffusionCoefficients.size() == numItoSpecies);
3479 CH_assert(a_cdrDiffusionCoefficients.size() == numCdrSpecies);
3480
3481 // Geometric information that we need.
3482 const Real dx = m_amr->getDx()[a_level];
3483 const RealVect probLo = m_amr->getProbLo();
3484 const EBISBox& ebisbox = m_amr->getEBISLayout(m_fluidRealm, m_plasmaPhase)[a_level][a_din];
3485
3486 // Handle to single-valued data.
3487 const FArrayBox& electricFieldReg = a_electricField.getFArrayBox();
3488
3489 Vector<FArrayBox*> itoDiffCoReg(numItoSpecies, nullptr);
3490 Vector<FArrayBox*> cdrDiffCoReg(numCdrSpecies, nullptr);
3491
3492 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
3493 RefCountedPtr<ItoSolver>& solver = solverIt();
3494
3495 if (solver->isDiffusive()) {
3496 const int i = solverIt.index();
3497 itoDiffCoReg[i] = &(a_itoDiffusionCoefficients[i]->getFArrayBox());
3498 }
3499 }
3500
3501 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
3502 RefCountedPtr<CdrSolver>& solver = solverIt();
3503
3504 if (solver->isDiffusive()) {
3505 const int i = solverIt.index();
3506 cdrDiffCoReg[i] = &(a_cdrDiffusionCoefficients[i]->getFArrayBox());
3507 }
3508 }
3509
3510 // Physics interface mapping -- this maps a global index from the returned vector to an Ito or CDR solver
3511 const std::map<int, std::pair<SpeciesType, int>>& speciesMap = m_physics->getSpeciesMap();
3512
3513 // One buffer for the whole patch -- see computeMobilities() for why this is not left to the physics call.
3514 Vector<Real> diffusionCoefficients;
3515
3516 // Regular kernel definition.
3517 auto regularKernel = [&](const IntVect& iv) -> void {
3518 const RealVect pos = probLo + dx * (RealVect(iv) + 0.5 * RealVect::Unit);
3519 const RealVect E = RealVect(D_DECL(electricFieldReg(iv, 0), electricFieldReg(iv, 1), electricFieldReg(iv, 2)));
3520
3521 // Compute diffusion coefficients.
3522 m_physics->computeDiffusionCoefficients(diffusionCoefficients, a_time, pos, E);
3523
3524 CH_assert(diffusionCoefficients.size() == numPlasmaSpecies);
3525
3526 // Put the diffusion coefficients in the correct solver storage.
3527 for (const auto& s : speciesMap) {
3528 const int& globalIndex = s.first;
3529 const SpeciesType& type = s.second.first;
3530 const int& localIndex = s.second.second;
3531
3532 // We need an explicit check to see if
3533 if (type == SpeciesType::Ito) {
3534 if (m_ito->getSolvers()[localIndex]->isDiffusive()) {
3535 (*itoDiffCoReg[localIndex])(iv, 0) = diffusionCoefficients[globalIndex];
3536 }
3537 }
3538 else if (type == SpeciesType::CDR) {
3539 if (m_cdr->getSolvers()[localIndex]->isDiffusive()) {
3540 (*cdrDiffCoReg[localIndex])(iv, 0) = diffusionCoefficients[globalIndex];
3541 }
3542 }
3543 }
3544 };
3545
3546 // Irregular kernel.
3547 auto irregularKernel = [&](const VolIndex& vof) -> void {
3548 const RealVect E = RealVect(D_DECL(a_electricField(vof, 0), a_electricField(vof, 1), a_electricField(vof, 2)));
3549 const RealVect pos = probLo + Location::position(Location::Cell::Centroid, vof, ebisbox, dx);
3550
3551 // Compute diffusion coefficients.
3552 m_physics->computeDiffusionCoefficients(diffusionCoefficients, a_time, pos, E);
3553
3554 // Put the diffusion coefficients in the correct solver storage.
3555 for (const auto& s : speciesMap) {
3556 const int& globalIndex = s.first;
3557 const SpeciesType& type = s.second.first;
3558 const int& localIndex = s.second.second;
3559
3560 // We need an explicit check to see if
3561 if (type == SpeciesType::Ito) {
3562 if (m_ito->getSolvers()[localIndex]->isDiffusive()) {
3563 (*a_itoDiffusionCoefficients[localIndex])(vof, 0) = diffusionCoefficients[globalIndex];
3564 }
3565 }
3566 else if (type == SpeciesType::CDR) {
3567 if (m_cdr->getSolvers()[localIndex]->isDiffusive()) {
3568 (*a_cdrDiffusionCoefficients[localIndex])(vof, 0) = diffusionCoefficients[globalIndex];
3569 }
3570 }
3571 }
3572 };
3573
3574 // Run kernels.
3575 VoFIterator& vofit = (*m_amr->getVofIterator(m_fluidRealm, m_plasmaPhase)[a_level])[a_din];
3576
3577 BoxLoops::loop<D_DECL(1, 1, 1)>(a_box, regularKernel);
3578 BoxLoops::loop(vofit, irregularKernel);
3579
3580 // Covered is bogus.
3581 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
3582 if (solverIt()->isDiffusive()) {
3583 a_itoDiffusionCoefficients[solverIt.index()]->setCoveredCellVal(0.0, 0);
3584 }
3585 }
3586
3587 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
3588 if (solverIt()->isDiffusive()) {
3589 a_cdrDiffusionCoefficients[solverIt.index()]->setCoveredCellVal(0.0, 0);
3590 }
3591 }
3592}
3593
3594template <typename I, typename C, typename R, typename F>
3595void
3597{
3598 CH_TIME("ItoKMCStepper::averageDiffusionCoefficientsCellToFace");
3599 if (m_verbosity > 5) {
3600 pout() << m_name + "::averageDiffusionCoefficientsCellToFace" << endl;
3601 }
3602
3603 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
3604 RefCountedPtr<CdrSolver>& solver = solverIt();
3605
3606 if (solver->isDiffusive()) {
3607
3608 EBAMRCellData& cellCenteredDiffusionCoefficient = solver->getCellCenteredDiffusionCoefficient();
3609 EBAMRFluxData& faceCenteredDiffusionCoefficient = solver->getFaceCenteredDiffusionCoefficient();
3610
3611 CH_assert(cellCenteredDiffusionCoefficient.getRealm() == m_fluidRealm);
3612 CH_assert(faceCenteredDiffusionCoefficient.getRealm() == m_fluidRealm);
3613
3614 DataOps::setValue(faceCenteredDiffusionCoefficient, std::numeric_limits<Real>::max());
3615
3616 // Coarsen the cell-centered diffusion coefficient before averaging to faces.
3617 m_amr->arithmeticAverage(cellCenteredDiffusionCoefficient, m_fluidRealm, m_cdr->getPhase());
3618 m_amr->interpGhostPwl(cellCenteredDiffusionCoefficient, m_fluidRealm, m_cdr->getPhase());
3619
3620 // Average to cell faces. Note that this call also includes one ghost face (required when there's an EBCF
3621 // crossing).
3622 const int tanGhost = 1;
3623 const Interval interv = Interval(0, 0);
3624 const Average average = Average::Arithmetic;
3625
3626 DataOps::averageCellToFace(faceCenteredDiffusionCoefficient,
3627 cellCenteredDiffusionCoefficient,
3628 m_amr->getDomains(),
3629 tanGhost,
3630 interv,
3631 interv,
3632 average,
3633 m_amr->getFaceIteratorWithTangentialGhosts(m_fluidRealm, m_cdr->getPhase()));
3634 }
3635 }
3636}
3637
3638template <typename I, typename C, typename R, typename F>
3639void
3641{
3642 CH_TIME("ItoKMCStepper::getPhysicalParticlesPerCell(EBAMRCellData)");
3643 if (m_verbosity > 5) {
3644 pout() << m_name + "::getPhysicaParticlesPerCell(EBAMRCellData)" << endl;
3645 }
3646
3647 CH_assert(a_ppc.getRealm() == m_particleRealm);
3648
3649 for (auto it = m_ito->iterator(); it.ok(); ++it) {
3650 const int idx = it.index();
3651
3652 EBAMRCellData ppc = m_amr->slice(a_ppc, Interval(idx, idx));
3653
3654 const ParticleContainer<ItoParticle>& particles = it()->getParticles(ItoSolver::WhichContainer::Bulk);
3655
3657 }
3658}
3659
3660template <typename I, typename C, typename R, typename F>
3661void
3663{
3664 CH_TIME("ItoKMCStepper::computeReactiveItoParticlesPerCell(EBAMRCellData)");
3665 if (m_verbosity > 5) {
3666 pout() << m_name + "::computeReactiveItoParticlesPerCell(EBAMRCellData)" << endl;
3667 }
3668
3669 CH_assert(a_ppc.getRealm() == m_particleRealm);
3670
3671 DataOps::setValue(a_ppc, 0.0);
3672
3673 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
3674 this->computeReactiveItoParticlesPerCell(*a_ppc[lvl], lvl);
3675 }
3676}
3677
3678template <typename I, typename C, typename R, typename F>
3679void
3680ItoKMCStepper<I, C, R, F>::computeReactiveItoParticlesPerCell(LevelData<EBCellFAB>& a_ppc, const int a_level) noexcept
3681{
3682 CH_TIME("ItoKMCStepper::computeReactiveItoParticlesPerCell(LD<EBCellFAB>, int)");
3683 if (m_verbosity > 5) {
3684 pout() << m_name + "::computeReactiveItoParticlesPerCell(LD<EBCellFAB>, int)" << endl;
3685 }
3686
3687 const int numItoSpecies = m_physics->getNumItoSpecies();
3688
3689 CH_assert(a_ppc.nComp() == numItoSpecies);
3690
3691 const DisjointBoxLayout& dbl = m_amr->getGrids(m_particleRealm)[a_level];
3692 const EBISLayout& ebisl = m_amr->getEBISLayout(m_particleRealm, m_plasmaPhase)[a_level];
3693 const DataIterator& dit = dbl.dataIterator();
3694
3695 const int nbox = dit.size();
3696
3697#pragma omp parallel for schedule(runtime)
3698 for (int mybox = 0; mybox < nbox; mybox++) {
3699 const DataIndex& din = dit[mybox];
3700
3701 const Box box = dbl[din];
3702 const EBISBox& ebisbox = ebisl[din];
3703
3704 this->computeReactiveItoParticlesPerCell(a_ppc[din], a_level, din, box, ebisbox);
3705 }
3706}
3707
3708template <typename I, typename C, typename R, typename F>
3709void
3711 const int a_level,
3712 const DataIndex a_din,
3713 const Box a_box,
3714 const EBISBox& a_ebisbox) noexcept
3715{
3716 CH_TIME("ItoKMCStepper::computeReactiveItoParticlesPerCell(EBCellFAB, int, DataIndex, Box, EBISBox)");
3717 if (m_verbosity > 5) {
3718 pout() << m_name + "::computeReactiveItoParticlesPerCell(EBCellFAB, int, DataIndex, Box, EBISBox)" << endl;
3719 }
3720
3721 const int numItoSpecies = m_physics->getNumItoSpecies();
3722
3723 CH_assert(a_ppc.nComp() == numItoSpecies);
3724
3725 const Real dx = m_amr->getDx()[a_level];
3726 const RealVect probLo = m_amr->getProbLo();
3727
3728 // TLDR: We go through each solver and add the number of PHYSICAL particles per cell to a_ppc.
3729
3730 FArrayBox& ppcRegular = a_ppc.getFArrayBox();
3731
3732 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
3733 RefCountedPtr<ItoSolver>& solver = solverIt();
3734 const int idx = solverIt.index();
3735
3736 ParticleContainer<ItoParticle>& particles = solver->getParticles(ItoSolver::WhichContainer::Bulk);
3737
3738 // Cell-sort the leaf and read each cell's particles straight out of its CSR range. This kernel only
3739 // sums weights, so there is nothing to extract into per-cell scratch containers.
3740 ParticleSoA<ItoParticle>& leaf = particles[a_level][a_din];
3741 leaf.sortByCell(a_box, dx * RealVect::Unit, probLo);
3742
3743 // Regular cells kernel.
3744 auto regularKernel = [&](const IntVect& iv) -> void {
3745 Real num = 0.0;
3746
3747 if (a_ebisbox.isRegular(iv)) {
3748 const std::pair<std::size_t, std::size_t> range = leaf.cellRange(a_box.index(iv));
3749 for (std::size_t i = range.first; i < range.second; i++) {
3750 num += leaf.weight(i);
3751 }
3752 }
3753
3754 ppcRegular(iv, idx) = num;
3755 };
3756
3757 // Irregular kernel -- note that only particles that lie inside the domain get to react.
3758 auto irregularKernel = [&](const VolIndex& vof) -> void {
3759 const IntVect iv = vof.gridIndex();
3760 const RealVect normal = a_ebisbox.normal(vof);
3761 const RealVect physCentroid = probLo + Location::position(Location::Cell::Boundary, vof, a_ebisbox, dx);
3762
3763 Real num = 0.0;
3764
3765 const std::pair<std::size_t, std::size_t> range = leaf.cellRange(a_box.index(iv));
3766 for (std::size_t i = range.first; i < range.second; i++) {
3767 const RealVect pos = leaf.position(i);
3768 if ((pos - physCentroid).dotProduct(normal) >= 0.0) {
3769 num += leaf.weight(i);
3770 }
3771 }
3772
3773 a_ppc(vof, idx) = num;
3774 };
3775
3776 // Run the kernels.
3777 VoFIterator& vofit = (*m_amr->getVofIterator(m_particleRealm, m_plasmaPhase)[a_level])[a_din];
3778
3779 BoxLoops::loop<D_DECL(1, 1, 1)>(a_box, regularKernel);
3780 BoxLoops::loop(vofit, irregularKernel);
3781 }
3782}
3783
3784template <typename I, typename C, typename R, typename F>
3785void
3787{
3788 CH_TIME("ItoKMCStepper::computeReactiveCdrParticlesPerCell(EBAMRCellData)");
3789 if (m_verbosity > 5) {
3790 pout() << m_name + "::computeReactiveCdrParticlesPerCell(EBAMRCellData)" << endl;
3791 }
3792
3793 CH_assert(a_ppc.getRealm() == m_fluidRealm);
3794
3795 DataOps::setValue(a_ppc, 0.0);
3796
3797 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
3798 this->computeReactiveCdrParticlesPerCell(*a_ppc[lvl], lvl);
3799 }
3800}
3801
3802template <typename I, typename C, typename R, typename F>
3803void
3804ItoKMCStepper<I, C, R, F>::computeReactiveCdrParticlesPerCell(LevelData<EBCellFAB>& a_ppc, const int a_level) noexcept
3805{
3806 CH_TIME("ItoKMCStepper::computeReactiveCdrParticlesPerCell(LD<EBCellFAB>, int)");
3807 if (m_verbosity > 5) {
3808 pout() << m_name + "::computeReactiveCdrParticlesPerCell(LD<EBCellFAB>, int)" << endl;
3809 }
3810
3811 const int numCdrSpecies = m_physics->getNumCdrSpecies();
3812
3813 CH_assert(a_ppc.nComp() == numCdrSpecies);
3814
3815 if (numCdrSpecies > 0) {
3816 const DisjointBoxLayout& dbl = m_amr->getGrids(m_fluidRealm)[a_level];
3817 const EBISLayout& ebisl = m_amr->getEBISLayout(m_fluidRealm, m_plasmaPhase)[a_level];
3818 const DataIterator& dit = dbl.dataIterator();
3819
3820 const int nbox = dit.size();
3821
3822#pragma omp parallel for schedule(runtime)
3823 for (int mybox = 0; mybox < nbox; mybox++) {
3824 const DataIndex& din = dit[mybox];
3825
3826 const Box box = dbl[din];
3827 const EBISBox& ebisbox = ebisl[din];
3828
3829 this->computeReactiveCdrParticlesPerCell(a_ppc[din], a_level, din, box, ebisbox);
3830 }
3831 }
3832}
3833
3834template <typename I, typename C, typename R, typename F>
3835void
3837 const int a_level,
3838 const DataIndex a_din,
3839 const Box a_box,
3840 const EBISBox& a_ebisbox) noexcept
3841{
3842 CH_TIME("ItoKMCStepper::computeReactiveCdrParticlesPerCell(EBCellFAB, int, DataIndex, Box, EBISBox)");
3843 if (m_verbosity > 5) {
3844 pout() << m_name + "::computeReactiveCdrParticlesPerCell(EBCellFAB, int, DataIndex, Box, EBISBox)" << endl;
3845 }
3846
3847 constexpr Real zero = 0.0;
3848
3849 const int numCdrSpecies = m_physics->getNumCdrSpecies();
3850
3851 CH_assert(a_ppc.nComp() == numCdrSpecies);
3852
3853 const Real dx = m_amr->getDx()[a_level];
3854 const Real vol = std::pow(dx, SpaceDim);
3855 const RealVect probLo = m_amr->getProbLo();
3856
3857 // TLDR: We go through each solver and add the number of PHYSICAL particles per cell to a_ppc.
3858 FArrayBox& ppcRegular = a_ppc.getFArrayBox();
3859
3860 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
3861 RefCountedPtr<CdrSolver>& solver = solverIt();
3862 const int idx = solverIt.index();
3863
3864 const EBCellFAB& phi = (*(solver->getPhi())[a_level])[a_din];
3865 const FArrayBox& phiReg = phi.getFArrayBox();
3866
3867 // Regular cells kernel. Not vectorizable: the out-of-line a_ebisbox.isRegular(iv) guard blocks it, and a
3868 // branchless mask-multiply rewrite still does not vectorize on GCC ("no vectype for stmt" on the
3869 // floor/strided-component store, verified via opt-record), so the original guarded form is kept.
3870 auto regularKernel = [&](const IntVect& iv) -> void {
3871 if (a_ebisbox.isRegular(iv)) {
3872 ppcRegular(iv, idx) = std::max(zero, std::floor(phiReg(iv, 0) * vol));
3873 }
3874 };
3875
3876 // Irregular kernel -- note that only particles that lie inside the domain get to react.
3877 auto irregularKernel = [&](const VolIndex& vof) -> void {
3878 const Real kappa = a_ebisbox.volFrac(vof);
3879
3880 a_ppc(vof, idx) = std::max(zero, std::floor(kappa * phi(vof, 0) * vol));
3881 };
3882
3883 // Run the kernels.
3884 VoFIterator& vofit = (*m_amr->getVofIterator(m_fluidRealm, m_plasmaPhase)[a_level])[a_din];
3885
3886 BoxLoops::loop<D_DECL(1, 1, 1)>(a_box, regularKernel);
3887 BoxLoops::loop(vofit, irregularKernel);
3888 }
3889}
3890
3891template <typename I, typename C, typename R, typename F>
3892void
3894{
3895 CH_TIME("ItoKMCStepper::computeReactiveMaeanEnergiesPerCell(EBAMRCellData)");
3896 if (m_verbosity > 5) {
3897 pout() << m_name + "::computeReactiveMaeanEnergiesPerCell(EBAMRCellData)" << endl;
3898 }
3899
3900 CH_assert(a_meanEnergies.getRealm() == m_particleRealm);
3901
3902 DataOps::setValue(a_meanEnergies, 0.0);
3903
3904 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
3905 this->computeReactiveMeanEnergiesPerCell(*a_meanEnergies[lvl], lvl);
3906 }
3907}
3908
3909template <typename I, typename C, typename R, typename F>
3910void
3912 const int a_level) noexcept
3913{
3914 CH_TIME("ItoKMCStepper::computeReactiveMeanEnergiesPerCell(LD<EBCellFAB>, int)");
3915 if (m_verbosity > 5) {
3916 pout() << m_name + "::computeReactiveMeanEnergiesPerCell(LD<EBCellFAB>, int)" << endl;
3917 }
3918
3919 const int numPlasmaSpecies = m_physics->getNumItoSpecies();
3920
3921 CH_assert(a_meanEnergies.nComp() == numPlasmaSpecies);
3922
3923 const DisjointBoxLayout& dbl = m_amr->getGrids(m_particleRealm)[a_level];
3924 const EBISLayout& ebisl = m_amr->getEBISLayout(m_particleRealm, m_plasmaPhase)[a_level];
3925 const DataIterator& dit = dbl.dataIterator();
3926
3927 const int nbox = dit.size();
3928
3929#pragma omp parallel for schedule(runtime)
3930 for (int mybox = 0; mybox < nbox; mybox++) {
3931 const DataIndex& din = dit[mybox];
3932
3933 const Box box = dbl[din];
3934 const EBISBox& ebisbox = ebisl[din];
3935
3936 this->computeReactiveMeanEnergiesPerCell(a_meanEnergies[din], a_level, din, box, ebisbox);
3937 }
3938}
3939
3940template <typename I, typename C, typename R, typename F>
3941void
3943 const int a_level,
3944 const DataIndex a_din,
3945 const Box a_box,
3946 const EBISBox& a_ebisbox) noexcept
3947{
3948 CH_TIME("ItoKMCStepper::computeReactiveMeanEnergiesPerCell(EBCellFABint, DataIndex, Box, EBISBox)");
3949 if (m_verbosity > 5) {
3950 pout() << m_name + "::computeReactiveMeanEnergiesPerCell(EBCellFABint, DataIndex, Box, EBISBox))" << endl;
3951 }
3952
3953 const int numPlasmaSpecies = m_physics->getNumItoSpecies();
3954
3955 CH_assert(a_meanEnergies.nComp() == numPlasmaSpecies);
3956
3957 const Real dx = m_amr->getDx()[a_level];
3958 const RealVect probLo = m_amr->getProbLo();
3959
3960 // Get single-valued data.
3961 FArrayBox& meanEnergiesReg = a_meanEnergies.getFArrayBox();
3962
3963 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
3964 RefCountedPtr<ItoSolver>& solver = solverIt();
3965 const int idx = solverIt.index();
3966
3967 ParticleContainer<ItoParticle>& particles = solver->getParticles(ItoSolver::WhichContainer::Bulk);
3968
3969 // Cell-sort the leaf and read each cell's particles straight out of its CSR range. This kernel only
3970 // accumulates weights and energies, so there is nothing to extract into per-cell scratch containers.
3971 ParticleSoA<ItoParticle>& leaf = particles[a_level][a_din];
3972 leaf.sortByCell(a_box, dx * RealVect::Unit, probLo);
3973
3974 // Regular grid cells.
3975 auto regularKernel = [&](const IntVect& iv) -> void {
3976 if (a_ebisbox.isRegular(iv)) {
3977 Real totalWeight = 0.0;
3978 Real totalEnergy = 0.0;
3979
3980 const std::pair<std::size_t, std::size_t> range = leaf.cellRange(a_box.index(iv));
3981 for (std::size_t i = range.first; i < range.second; i++) {
3982 const Real w = leaf.weight(i);
3983 totalWeight += w;
3984 totalEnergy += w * leaf.template get<&ItoParticle::energy>(i);
3985 }
3986
3987 if (totalWeight > 0.0) {
3988 meanEnergiesReg(iv, idx) = totalEnergy / totalWeight;
3989 }
3990 else {
3991 meanEnergiesReg(iv, idx) = 0.0;
3992 }
3993 }
3994 };
3995
3996 // Irregular cells -- note that only valid particles get to play with us.
3997 auto irregularKernel = [&](const VolIndex& vof) -> void {
3998 const IntVect iv = vof.gridIndex();
3999 const RealVect normal = a_ebisbox.normal(vof);
4000 const RealVect ebCentroid = probLo + Location::position(Location::Cell::Boundary, vof, a_ebisbox, dx);
4001
4002 Real totalWeight = 0.0;
4003 Real totalEnergy = 0.0;
4004
4005 const std::pair<std::size_t, std::size_t> range = leaf.cellRange(a_box.index(iv));
4006 for (std::size_t i = range.first; i < range.second; i++) {
4007 const RealVect pos = leaf.position(i);
4008
4009 if ((pos - ebCentroid).dotProduct(normal) >= 0.0) {
4010 const Real w = leaf.weight(i);
4011 totalWeight += w;
4012 totalEnergy += w * leaf.template get<&ItoParticle::energy>(i);
4013 }
4014 }
4015
4016 if (totalWeight > 0.0) {
4017 meanEnergiesReg(iv, idx) = totalEnergy / totalWeight;
4018 }
4019 else {
4020 meanEnergiesReg(iv, idx) = 0.0;
4021 }
4022 };
4023
4024 // Run the kernels.
4025 VoFIterator& vofit = (*m_amr->getVofIterator(m_particleRealm, m_plasmaPhase)[a_level])[a_din];
4026
4027 BoxLoops::loop<D_DECL(1, 1, 1)>(a_box, regularKernel);
4028 BoxLoops::loop(vofit, irregularKernel);
4029 }
4030}
4031
4032template <typename I, typename C, typename R, typename F>
4033void
4035{
4036 CH_TIME("ItoKMCStepper::advanceReactionNetwork(dt)");
4037 if (m_verbosity > 5) {
4038 pout() << m_name + "::advanceReactionNetwork(dt)" << endl;
4039 }
4040
4041 CH_assert(a_dt > 0.0);
4042
4044
4045 // NOTE: super-particle merging is NOT done here. Chemistry creates/removes particles; the caller
4046 // (e.g. ItoKMCGodunovStepper::advance()) merges afterwards through
4047 // ItoSolver::makeSuperparticles(), where it can be timed as its own step.
4048}
4049
4050template <typename I, typename C, typename R, typename F>
4051void
4052ItoKMCStepper<I, C, R, F>::advanceReactionNetwork(const EBAMRCellData& a_electricField, const Real a_dt) noexcept
4053{
4054 CH_TIMERS("ItoKMCStepper::advanceReactionNetwork");
4055 CH_TIMER("ItoKMCStepper::advanceReactionNetwork::compute_ppc", t1);
4056 CH_TIMER("ItoKMCStepper::advanceReactionNetwork::integrate_network", t2);
4057 CH_TIMER("ItoKMCStepper::advanceReactionNetwork::copies", t3);
4058 CH_TIMER("ItoKMCStepper::advanceReactionNetwork::reconcile_particles", t4);
4059 CH_TIMER("ItoKMCStepper::advanceReactionNetwork::reconcile_cdr", t5);
4060 if (m_verbosity > 5) {
4061 pout() << m_name + "::advanceReactionNetwork" << endl;
4062 }
4063
4064 const int numItoSpecies = m_physics->getNumItoSpecies();
4065 const int numCdrSpecies = m_physics->getNumCdrSpecies();
4066 const int numPhotonSpecies = m_physics->getNumPhotonSpecies();
4067
4068 CH_assert(a_electricField.getRealm() == m_fluidRealm);
4069 CH_assert(a_dt > 0.0);
4070
4071 // Compute the number of reactive particles for both Ito and CDR species. Also do a backup of the initial number
4072 // of particles per cell. This is required when reconciling the results lateron.
4073 CH_START(t1);
4074 if (numItoSpecies > 0) {
4076
4077 const Interval srcInterv(0, numItoSpecies - 1);
4078 const Interval dstInterv(0, numItoSpecies - 1);
4079
4080 m_amr->copyData(m_fluidPPC, m_particleItoPPC, dstInterv, srcInterv);
4081
4083 }
4084 if (numCdrSpecies > 0) {
4086
4087 const Interval srcInterv(0, numCdrSpecies - 1);
4088 const Interval dstInterv(numItoSpecies, numItoSpecies + numCdrSpecies - 1);
4089
4090 m_amr->copyData(m_fluidPPC, m_fluidCdrPPC, dstInterv, srcInterv);
4091
4093 }
4094
4097 CH_STOP(t1);
4098
4099 // Advance the reaction network which gives us a new number of particles per cell, as well as the number of
4100 // photons that need to be generated per cell.
4101 CH_START(t2);
4102 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
4103 this->advanceReactionNetwork(*m_fluidPPC[lvl], *m_fluidYPC[lvl], *a_electricField[lvl], lvl, a_dt);
4104 }
4105 CH_STOP(t2);
4106
4107 // Copy the results back to the holders that hold the number of particles per cell for Ito/Cdr solvers.
4108 CH_START(t3);
4109 if (numItoSpecies > 0) {
4110 const Interval srcInterv(0, numItoSpecies - 1);
4111 const Interval dstInterv(0, numItoSpecies - 1);
4112
4113 m_amr->copyData(m_particleItoPPC, m_fluidPPC, dstInterv, srcInterv);
4114 }
4115 if (numCdrSpecies > 0) {
4116 const Interval srcInterv(numItoSpecies, numItoSpecies + numCdrSpecies - 1);
4117 const Interval dstInterv(0, numCdrSpecies - 1);
4118
4119 m_amr->copyData(m_fluidCdrPPC, m_fluidPPC, dstInterv, srcInterv);
4120 }
4121 if (numPhotonSpecies > 0) {
4122 m_amr->copyData(m_particleYPC, m_fluidYPC);
4123 }
4124 CH_STOP(t3);
4125
4126 // Turn the per-cell CDR result into the quantities the reconciliation below needs. m_fluidCdrPPC holds the new
4127 // count and m_fluidOldCdrPPC the old one, so their difference is the change the network computed; both holders
4128 // are dead afterwards and are reused to carry the result.
4129 //
4130 // Under CdrProductInjection::Particle the change is split by sign, and only the PRODUCTION becomes particles:
4131 // that is the half of the change that happens at a point in the cell and therefore has a sub-cell position to be
4132 // consistent about. Mass removed from a CDR species is proportional to the cell-averaged density, which carries
4133 // no sub-cell information, so it stays in the cell it was taken from. m_fluidCdrPPC then holds the removal (and,
4134 // after the deposition below, the total change) and m_fluidOldCdrPPC the production.
4135 //
4136 // Under CdrProductInjection::Mesh there is nothing to split -- the whole change goes into the cell it was
4137 // computed in, and m_fluidCdrPPC carries it straight to reconcileCdrDensities().
4138 CH_START(t4);
4139 if (numCdrSpecies > 0) {
4141
4143 const Vector<RefCountedPtr<LayoutData<VoFIterator>>>& vofIter = m_amr->getVofIterator(m_fluidRealm,
4145
4147
4148 DataOps::floor(m_fluidOldCdrPPC, 0.0, vofIter);
4149 DataOps::roof(m_fluidCdrPPC, 0.0, vofIter);
4150
4152 }
4153 }
4154
4155 for (int i = 0; i < m_cdrProducts.size(); i++) {
4156 m_cdrProducts[i]->clearParticles();
4157 m_cdrProducts[i]->organizeParticlesByCell();
4158 }
4159
4160 // Reconcile the results -- for the discrete solvers we add/remove particles/photons, and the CDR production is
4161 // turned into the particles that the deposition below puts on the mesh.
4167 CH_STOP(t4);
4168
4169 // Deposit the CDR products and add them to the removal already in m_fluidCdrPPC, giving the total per-cell change.
4170 CH_START(t5);
4172
4174 CH_STOP(t5);
4175}
4176
4177template <typename I, typename C, typename R, typename F>
4178void
4179ItoKMCStepper<I, C, R, F>::depositCdrProducts(EBAMRCellData& a_cdrChange) noexcept
4180{
4181 CH_TIME("ItoKMCStepper::depositCdrProducts");
4182 if (m_verbosity > 5) {
4183 pout() << m_name + "::depositCdrProducts" << endl;
4184 }
4185
4186 CH_assert(a_cdrChange.getRealm() == m_fluidRealm);
4187
4188 // Species whose product container is empty on EVERY rank deposit identically zero, so the whole block
4189 // below -- a halo deposition (which alone is ~3L-1 synchronizing stages), a cross-realm copy, and two
4190 // hierarchy-wide passes -- adds nothing to a_cdrChange.
4191 //
4192 // The test must be global because the work being skipped is collective: every rank has to reach the
4193 // same verdict for every species. One Allreduce over the whole vector answers it for all of them, and
4194 // the local counts it reduces are free (the containers track their own size). Skipping leaves stale
4195 // data in m_particleScratch1/m_fluidScratch1, which is harmless -- both are fully overwritten by their
4196 // next user.
4197 Vector<long long int> numProducts(m_cdrProducts.size(), 0LL);
4198
4199 for (int i = 0; i < m_cdrProducts.size(); i++) {
4200 numProducts[i] = static_cast<long long int>(m_cdrProducts[i]->getNumberOfValidParticlesLocal());
4201 }
4202
4203 ParallelOps::sum(numProducts);
4204
4205 // Under CdrProductInjection::Particle the products go down through ItoSolver::depositWeight, so they get the Ito
4206 // solvers' deposition in full -- kernel, coarse-fine strategy, cut-cell strategy and the mirror/redistribution
4207 // passes that go with it. That is the whole point: the two halves of a reaction then spread over the mesh the same
4208 // way, cut cells included. Any solver will do, since they all parse the same 'ItoSolver.deposition*' keys.
4209 //
4210 // Taking the cut-cell strategy from the solver is also why reconcileCdrDensities() skips the reactive
4211 // redistribution in this mode. The in-cell path is written in the kappa*n convention -- computeReactive-
4212 // CdrParticlesPerCell() reads a cut cell as kappa*phi*V and reconcileCdrDensities() writes it back as
4213 // phi += change/V, so a cut-cell reaction is damped by kappa and 'redistribute_cdr' exists to push the
4214 // resulting (1-kappa) share back out. A production deposited by the Ito solver carries the solver's cut-cell
4215 // normalization instead, so there is no such damping left for the redistribution to correct.
4216 //
4217 // Under CdrProductInjection::Mesh the only particles that reach here are the photoionization products, which have
4218 // no in-cell representation to fall back on. They are put down NGP with no cut-cell treatment, which is what the
4219 // code did before the chemistry products could become particles.
4220 const bool useItoDeposition = (m_cdrProductInjection == CdrProductInjection::Particle) &&
4221 (m_physics->getNumItoSpecies() > 0);
4222
4223 for (int i = 0; i < m_cdrProducts.size(); i++) {
4224 if (numProducts[i] == 0LL) {
4225 continue;
4226 }
4227
4228 m_cdrProducts[i]->organizeParticlesByPatch();
4229
4230 if (useItoDeposition) {
4231 const auto& solver = m_ito->getSolvers()[0];
4232
4233 solver->depositWeight(m_particleScratch1,
4234 *m_cdrProducts[i],
4235 solver->getDeposition(),
4236 solver->getCoarseFineDeposition());
4237 }
4238 else {
4239 m_amr->depositWeight(m_particleScratch1,
4242 *m_cdrProducts[i],
4243 DepositionType::NGP,
4244 CoarseFineDeposition::Halo,
4246 }
4247
4250
4251 EBAMRCellData cdrChange = m_amr->slice(a_cdrChange, Interval(i, i));
4252
4253 DataOps::incr(cdrChange, m_fluidScratch1, 1.0);
4254
4255 m_cdrProducts[i]->clearParticles();
4256 }
4257}
4258
4259template <typename I, typename C, typename R, typename F>
4260inline void
4261ItoKMCStepper<I, C, R, F>::advanceReactionNetwork(LevelData<EBCellFAB>& a_particlesPerCell,
4262 LevelData<EBCellFAB>& a_newPhotonsPerCell,
4263 const LevelData<EBCellFAB>& a_electricField,
4264 const int a_level,
4265 const Real a_dt) const noexcept
4266{
4267 CH_TIME("ItoKMCStepper::advanceReactionNetwork(LD<EBCellFAB>x3, int, Real)");
4268 if (m_verbosity > 5) {
4269 pout() << m_name + "::advanceReactionNetwork(LD<EBCellFAB>x3, int, Real)" << endl;
4270 }
4271
4272 const int numPlasmaSpecies = m_physics->getNumPlasmaSpecies();
4273 const int numPhotonSpecies = m_physics->getNumPhotonSpecies();
4274
4275 CH_assert(a_particlesPerCell.nComp() == numPlasmaSpecies);
4276 CH_assert(a_newPhotonsPerCell.nComp() == numPhotonSpecies);
4277 CH_assert(a_electricField.nComp() == SpaceDim);
4278
4279 const DisjointBoxLayout& dbl = m_amr->getGrids(m_fluidRealm)[a_level];
4280 const DataIterator& dit = dbl.dataIterator();
4281
4282 const int nbox = dit.size();
4283
4284#pragma omp parallel
4285 {
4286 m_physics->defineKMC();
4287
4288#pragma omp for schedule(runtime)
4289 for (int mybox = 0; mybox < nbox; mybox++) {
4290 const DataIndex& din = dit[mybox];
4291
4292 this->advanceReactionNetwork(a_particlesPerCell[din],
4293 a_newPhotonsPerCell[din],
4294 a_electricField[din],
4295 a_level,
4296 din,
4297 dbl[din],
4298 m_amr->getDx()[a_level],
4299 a_dt);
4300 }
4301
4302 m_physics->killKMC();
4303 }
4304}
4305
4306template <typename I, typename C, typename R, typename F>
4307inline void
4309 EBCellFAB& a_newPhotonsPerCell,
4310 const EBCellFAB& a_electricField,
4311 const int a_level,
4312 const DataIndex a_din,
4313 const Box a_box,
4314 const Real a_dx,
4315 const Real a_dt) const noexcept
4316{
4317 CH_TIME("ItoKMCStepper::advanceReactionNetwork(EBCellFABx3, int, DataIndex, Box, Realx2)");
4318 if (m_verbosity > 5) {
4319 pout() << m_name + "::advanceReactionNetwork(EBCellFABx3, int, DataIndex, Box, Realx2)" << endl;
4320 }
4321
4322 const int numCdrSpecies = m_physics->getNumCdrSpecies();
4323 const int numItoSpecies = m_physics->getNumItoSpecies();
4324 const int numPlasmaSpecies = m_physics->getNumPlasmaSpecies();
4325 const int numPhotonSpecies = m_physics->getNumPhotonSpecies();
4326
4327 CH_assert(a_particlesPerCell.nComp() == numPlasmaSpecies);
4328 CH_assert(a_newPhotonsPerCell.nComp() == numPhotonSpecies);
4329 CH_assert(a_electricField.nComp() == SpaceDim);
4330
4331 // Geometric information that we require.
4332 const RealVect probLo = m_amr->getProbLo();
4333 const EBISBox& ebisbox = m_amr->getEBISLayout(m_fluidRealm, m_plasmaPhase)[a_level][a_din];
4334
4335 const FArrayBox& electricFieldReg = a_electricField.getFArrayBox();
4336
4337 // Storage used by physics interface.
4338 Vector<Physics::ItoKMC::FPR> particles(numPlasmaSpecies);
4339 Vector<Physics::ItoKMC::FPR> newPhotons(numPhotonSpecies);
4340 Vector<Real> meanEnergies(numPlasmaSpecies);
4341 Vector<Real> energySources(numPlasmaSpecies);
4342 Vector<Real> densities(numPlasmaSpecies, 0.0);
4343 Vector<RealVect> densityGradients(numPlasmaSpecies, RealVect::Zero);
4344
4345 // Populate single-valued data.
4346 FArrayBox& particlesPerCellReg = a_particlesPerCell.getFArrayBox();
4347 FArrayBox& newPhotonsReg = a_newPhotonsPerCell.getFArrayBox();
4348
4349 // Handle to densities and density gradients for CDR and Ito species.
4350 Vector<const EBCellFAB*> densitiesIto(numItoSpecies);
4351 Vector<const EBCellFAB*> densityGradientsIto(numItoSpecies);
4352 Vector<const FArrayBox*> densitiesItoReg(numItoSpecies);
4353 Vector<const FArrayBox*> densityGradientsItoReg(numItoSpecies);
4354
4355 Vector<const EBCellFAB*> densitiesCDR(numCdrSpecies);
4356 Vector<const EBCellFAB*> densityGradientsCDR(numCdrSpecies);
4357 Vector<const FArrayBox*> densitiesCDRReg(numCdrSpecies);
4358 Vector<const FArrayBox*> densityGradientsCDRReg(numCdrSpecies);
4359
4360 // Handle to critical and non-critical time step containers.
4361 EBCellFAB& physicsDt = (*m_kmcDt[a_level])[a_din];
4362
4363 FArrayBox& physicsDtReg = physicsDt.getFArrayBox();
4364
4365 physicsDt.setVal(std::numeric_limits<Real>::max());
4366
4367 for (auto it = m_ito->iterator(); it.ok(); ++it) {
4368 const RefCountedPtr<ItoSolver>& solver = it();
4369
4370 const int i = it.index();
4371
4372 densitiesIto[i] = &(*(m_fluidPhiIto[i])[a_level])[a_din];
4373 densitiesItoReg[i] = &(densitiesIto[i]->getFArrayBox());
4374 densityGradientsIto[i] = &(*m_fluidGradPhiIto[i][a_level])[a_din];
4375 densityGradientsItoReg[i] = &(densityGradientsIto[i]->getFArrayBox());
4376 }
4377
4378 for (auto it = m_cdr->iterator(); it.ok(); ++it) {
4379 const RefCountedPtr<CdrSolver>& solver = it();
4380 const EBAMRCellData& phi = solver->getPhi();
4381
4382 const int i = it.index();
4383
4384 densitiesCDR[i] = &(*phi[a_level])[a_din];
4385 densitiesCDRReg[i] = &(densitiesCDR[i]->getFArrayBox());
4386 densityGradientsCDR[i] = &(*m_fluidGradPhiCDR[i][a_level])[a_din];
4387 densityGradientsCDRReg[i] = &(densityGradientsCDR[i]->getFArrayBox());
4388 }
4389
4390 // Handle to valid grid cells.
4391 const BaseFab<bool>& validCells = (*m_amr->getValidCells(m_fluidRealm)[a_level])[a_din];
4392
4393 // Regular cells
4394 auto regularKernel = [&](const IntVect& iv) -> void {
4395 if (ebisbox.isRegular(iv) && validCells(iv, 0)) {
4396 const RealVect pos = probLo + a_dx * (RealVect(iv) + 0.5 * RealVect::Unit);
4397 const RealVect E = RealVect(D_DECL(electricFieldReg(iv, 0), electricFieldReg(iv, 1), electricFieldReg(iv, 2)));
4398
4399 // Populate the data holders that the physics interface requires.
4400 for (int i = 0; i < numPlasmaSpecies; i++) {
4401 particles[i] = llround(particlesPerCellReg(iv, i));
4402 }
4403
4404 for (int i = 0; i < numPhotonSpecies; i++) {
4405 newPhotons[i] = 0LL;
4406 }
4407
4408 // Populate gradients.
4409 for (int i = 0; i < numItoSpecies; i++) {
4410 densities[i] = (*densitiesItoReg[i])(iv, 0);
4411 densityGradients[i] = RealVect(D_DECL((*densityGradientsItoReg[i])(iv, 0),
4412 (*densityGradientsItoReg[i])(iv, 1),
4413 (*densityGradientsItoReg[i])(iv, 2)));
4414 }
4415
4416 for (int i = 0; i < numCdrSpecies; i++) {
4417 densities[numItoSpecies + i] = (*densitiesCDRReg[i])(iv, 0);
4418 densityGradients[numItoSpecies + i] = RealVect(D_DECL((*densityGradientsCDRReg[i])(iv, 0),
4419 (*densityGradientsCDRReg[i])(iv, 1),
4420 (*densityGradientsCDRReg[i])(iv, 2)));
4421 }
4422
4423 // Do the physics advance.
4424 Real physDt = std::numeric_limits<Real>::max();
4425
4426 m_physics->advanceKMC(particles, newPhotons, physDt, densities, densityGradients, a_dt, E, pos, a_dx, 1.0);
4427
4428 // Repopulate the input data holders with the new number of particles/photons per cell.
4429 for (int i = 0; i < numPlasmaSpecies; i++) {
4430 particlesPerCellReg(iv, i) = 1.0 * particles[i];
4431 }
4432
4433 for (int i = 0; i < numPhotonSpecies; i++) {
4434 newPhotonsReg(iv, i) = 1.0 * newPhotons[i];
4435 }
4436
4437 physicsDtReg(iv, 0) = physDt;
4438 }
4439 };
4440
4441 // Irregular cells
4442 auto irregularKernel = [&](const VolIndex& vof) -> void {
4443 const IntVect iv = vof.gridIndex();
4444
4445 if (ebisbox.isIrregular(iv) && validCells(iv, 0)) {
4446 const Real kappa = ebisbox.volFrac(vof);
4447 const RealVect pos = probLo + Location::position(Location::Cell::Centroid, vof, ebisbox, a_dx);
4448 const RealVect E = RealVect(D_DECL(a_electricField(vof, 0), a_electricField(vof, 1), a_electricField(vof, 2)));
4449
4450 // Initialize for this cell.
4451 for (int i = 0; i < numPlasmaSpecies; i++) {
4452 particles[i] = llround(a_particlesPerCell(vof, i));
4453 }
4454
4455 for (int i = 0; i < numPhotonSpecies; i++) {
4456 newPhotons[i] = 0LL;
4457 }
4458
4459 // Populate gradients.
4460 for (int i = 0; i < numItoSpecies; i++) {
4461 densities[i] = (*densitiesIto[i])(vof, 0);
4462 densityGradients[i] = RealVect(D_DECL((*densityGradientsIto[i])(vof, 0),
4463 (*densityGradientsIto[i])(vof, 1),
4464 (*densityGradientsIto[i])(vof, 2)));
4465 }
4466
4467 for (int i = 0; i < numCdrSpecies; i++) {
4468 densities[numItoSpecies + i] = (*densitiesCDR[i])(vof, 0);
4469 densityGradients[numItoSpecies + i] = RealVect(D_DECL((*densityGradientsCDR[i])(vof, 0),
4470 (*densityGradientsCDR[i])(vof, 1),
4471 (*densityGradientsCDR[i])(vof, 2)));
4472 }
4473
4474 // Do the physics advance
4475 Real physDt = std::numeric_limits<Real>::max();
4476
4477 m_physics->advanceKMC(particles, newPhotons, physDt, densities, densityGradients, a_dt, E, pos, a_dx, kappa);
4478
4479 // Repopulate the input data holders with the new number of particles/photons per cell.
4480 for (int i = 0; i < numPlasmaSpecies; i++) {
4481 a_particlesPerCell(vof, i) = 1.0 * particles[i];
4482 }
4483
4484 for (int i = 0; i < numPhotonSpecies; i++) {
4485 a_newPhotonsPerCell(vof, i) = 1.0 * newPhotons[i];
4486 }
4487
4488 physicsDt(vof, 0) = physDt;
4489 }
4490 };
4491
4492 // Run the kernels. Not vectorizable: the core m_physics->advanceKMC stochastic reaction advance is a
4493 // virtual call per cell with per-cell std::vector state -- inherently scalar (this is the hot reaction path
4494 // but cannot vectorize).
4495 VoFIterator& vofit = (*m_amr->getVofIterator(m_fluidRealm, m_plasmaPhase)[a_level])[a_din];
4496
4497 BoxLoops::loop<D_DECL(1, 1, 1)>(a_box, regularKernel);
4498 BoxLoops::loop(vofit, irregularKernel);
4499}
4500
4501template <typename I, typename C, typename R, typename F>
4502inline void
4503ItoKMCStepper<I, C, R, F>::reconcileParticles(const EBAMRCellData& a_newParticlesPerCell,
4504 const EBAMRCellData& a_oldParticlesPerCell,
4505 const EBAMRCellData& a_newPhotonsPerCell,
4506 const EBAMRCellData& a_cdrProduction,
4507 const EBAMRCellData& a_electricField) const noexcept
4508{
4509 CH_TIME("ItoKMCStepper::reconcileParticles(EBAMRCellDatax4)");
4510 if (m_verbosity > 5) {
4511 pout() << m_name + "::reconcileParticles(EBAMRCellDatax4)";
4512 }
4513
4514 CH_assert(a_newParticlesPerCell.getRealm() == m_particleRealm);
4515 CH_assert(a_oldParticlesPerCell.getRealm() == m_particleRealm);
4516 CH_assert(a_newPhotonsPerCell.getRealm() == m_particleRealm);
4517 CH_assert(a_cdrProduction.getRealm() == m_particleRealm);
4518 CH_assert(a_electricField.getRealm() == m_particleRealm);
4519
4520 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
4521 this->reconcileParticles(*a_newParticlesPerCell[lvl],
4522 *a_oldParticlesPerCell[lvl],
4523 *a_newPhotonsPerCell[lvl],
4524 *a_cdrProduction[lvl],
4525 *a_electricField[lvl],
4526 lvl);
4527 }
4528}
4529
4530template <typename I, typename C, typename R, typename F>
4531inline void
4532ItoKMCStepper<I, C, R, F>::reconcileParticles(const LevelData<EBCellFAB>& a_newParticlesPerCell,
4533 const LevelData<EBCellFAB>& a_oldParticlesPerCell,
4534 const LevelData<EBCellFAB>& a_newPhotonsPerCell,
4535 const LevelData<EBCellFAB>& a_cdrProduction,
4536 const LevelData<EBCellFAB>& a_electricField,
4537 const int a_level) const noexcept
4538{
4539 CH_TIME("ItoKMCStepper::reconcileParticles(LevelData<EBCellFAB>x4, int)");
4540 if (m_verbosity > 5) {
4541 pout() << m_name + "::reconcileParticles(LevelData<EBCellFAB>x4, int)" << endl;
4542 }
4543
4544 const int numItoSpecies = m_physics->getNumItoSpecies();
4545 const int numPhotonSpecies = m_physics->getNumPhotonSpecies();
4546
4547 CH_assert(a_newParticlesPerCell.nComp() == numItoSpecies);
4548 CH_assert(a_oldParticlesPerCell.nComp() == numItoSpecies);
4549 CH_assert(a_newPhotonsPerCell.nComp() == numPhotonSpecies);
4550 CH_assert(a_electricField.nComp() == SpaceDim);
4551
4552 const DisjointBoxLayout& dbl = m_amr->getGrids(m_particleRealm)[a_level];
4553 const DataIterator& dit = dbl.dataIterator();
4554
4555 const int nbox = dit.size();
4556
4557#pragma omp parallel for schedule(runtime)
4558 for (int mybox = 0; mybox < nbox; mybox++) {
4559 const DataIndex& din = dit[mybox];
4560
4561 this->reconcileParticles(a_newParticlesPerCell[din],
4562 a_oldParticlesPerCell[din],
4563 a_newPhotonsPerCell[din],
4564 a_cdrProduction[din],
4565 a_electricField[din],
4566 a_level,
4567 din,
4568 dbl[din],
4569 m_amr->getDx()[a_level]);
4570 }
4571}
4572
4573template <typename I, typename C, typename R, typename F>
4574inline void
4575ItoKMCStepper<I, C, R, F>::reconcileParticles(const EBCellFAB& a_newParticlesPerCell,
4576 const EBCellFAB& a_oldParticlesPerCell,
4577 const EBCellFAB& a_newPhotonsPerCell,
4578 const EBCellFAB& a_cdrProduction,
4579 const EBCellFAB& a_electricField,
4580 const int a_level,
4581 const DataIndex a_din,
4582 const Box a_box,
4583 const Real a_dx) const noexcept
4584{
4585 CH_TIMERS("ItoKMCStepper::reconcileParticles(patch)");
4586 CH_TIMER("ItoKMCStepper::reconcileParticles(patch)::collect_ptr", t1);
4587 CH_TIMER("ItoKMCStepper::reconcileParticles(patch)::regular_cells", t2);
4588 CH_TIMER("ItoKMCStepper::reconcileParticles(patch)::irregular_cells", t3);
4589 if (m_verbosity > 5) {
4590 pout() << m_name + "::reconcileParticles(patch)" << endl;
4591 }
4592
4593 // clang-format off
4594 // TLDR: This is the main routine for generating new particles/photons after the chemistry advance have finished. We have
4595 // already computed the number of particles in each grid cell, and we now need to generate them. To do that we use
4596 // the reconciliation routines from the physics interface, which takes the per-cell responsibility for that. The main
4597 // work done in this routine is to expose the per-patch data to per-cell data that the physics interface can then use.
4598 // clang-format on
4599
4600 const int numItoSpecies = m_physics->getNumItoSpecies();
4601 const int numCdrSpecies = m_physics->getNumCdrSpecies();
4602 const int numPhotonSpecies = m_physics->getNumPhotonSpecies();
4603
4604 CH_assert(a_newParticlesPerCell.nComp() == numItoSpecies);
4605 CH_assert(a_oldParticlesPerCell.nComp() == numItoSpecies);
4606 CH_assert(a_newPhotonsPerCell.nComp() == numPhotonSpecies);
4607 CH_assert(a_electricField.nComp() == SpaceDim);
4608
4609 // Geometric information that we need.
4610 const RealVect probLo = m_amr->getProbLo();
4611 const EBISBox& ebisbox = m_amr->getEBISLayout(m_particleRealm, m_plasmaPhase)[a_level][a_din];
4612
4613 CH_START(t1);
4614 // List of valid grid cells
4615 const BaseFab<bool>& validCells = (*m_amr->getValidCells(m_particleRealm)[a_level])[a_din];
4616
4617 // Regular electric field cells
4618 const FArrayBox& electricFieldReg = a_electricField.getFArrayBox();
4619
4620 // Per-cell SoA scratch: one ParticleSoA<P> per grid cell, indexed by Box::index(iv). The Ito bulk leaves
4621 // and the bulk/source photon leaves are cell-sorted and split into these; the mutated scratches are rebuilt
4622 // into the SoA leaves after the kernels run. The CDR photoionization products use ParticleSoA<NoPayload>.
4623 std::vector<std::vector<ParticleSoA<ItoParticle>>> itoCells(numItoSpecies);
4624 std::vector<std::vector<ParticleSoA<Photon>>> bulkPhotonCells(numPhotonSpecies);
4625 std::vector<std::vector<ParticleSoA<Photon>>> sourcePhotonCells(numPhotonSpecies);
4626 std::vector<std::vector<ParticleSoA<NoPayload>>> cdrCells(numCdrSpecies);
4627
4628 // Build the per-cell Ito scratch from the SoA bulk leaves.
4629 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
4630 const int idx = solverIt.index();
4631
4632 ParticleContainer<ItoParticle>& solverParticles = solverIt()->getParticles(ItoSolver::WhichContainer::Bulk);
4633
4634 binLeafToCells(itoCells[idx], solverParticles[a_level][a_din], a_box, a_dx, probLo);
4635 }
4636
4637 // Build the per-cell CDR photoionization-product scratch from the SoA leaves.
4638 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
4639 const int idx = solverIt.index();
4640
4641 binLeafToCells(cdrCells[idx], (*m_cdrProducts[idx])[a_level][a_din], a_box, a_dx, probLo);
4642 }
4643
4644 // Build the per-cell photon scratch from the SoA bulk/source photon leaves.
4645 for (auto solverIt = m_rte->iterator(); solverIt.ok(); ++solverIt) {
4646 const int idx = solverIt.index();
4647
4648 ParticleContainer<Photon>& solverBulkPhotons = solverIt()->getBulkPhotons();
4649 ParticleContainer<Photon>& solverSourcePhotons = solverIt()->getSourcePhotons();
4650
4651 binLeafToCells(bulkPhotonCells[idx], solverBulkPhotons[a_level][a_din], a_box, a_dx, probLo);
4652 binLeafToCells(sourcePhotonCells[idx], solverSourcePhotons[a_level][a_din], a_box, a_dx, probLo);
4653 }
4654
4655 // The physics interface takes the physical number of particles/photons as arguments
4656 // to the reconciliation routines. These need to be set from the input arguments; this is the
4657 // storage we use in the grid cells.
4658 Vector<Physics::ItoKMC::FPR> numNewParticles(numItoSpecies);
4659 Vector<Physics::ItoKMC::FPR> numOldParticles(numItoSpecies);
4660 Vector<Physics::ItoKMC::FPR> numNewPhotons(numPhotonSpecies);
4661
4662 Vector<long long> numNewCdrParticles(numCdrSpecies);
4663
4664 // Under CdrProductInjection::Mesh the production never becomes particles, and a_cdrProduction is not filled at
4665 // all, so neither it nor the kernels below may be read.
4666 const bool injectCdrProducts = (m_cdrProductInjection == CdrProductInjection::Particle);
4667
4668 // The physics interface also takes the actual particles/photons as argument to its reconciliation routines. This
4669 // is the storage we use for these; note that it is repopulated in every grid cell (pointing at the per-cell
4670 // SoA scratch above). CDR products remain AoS lists.
4671 Vector<ParticleSoA<ItoParticle>*> itoParticles(numItoSpecies);
4672 Vector<ParticleSoA<NoPayload>*> cdrParticles(numCdrSpecies);
4673 Vector<ParticleSoA<Photon>*> bulkPhotons(numPhotonSpecies);
4674 Vector<ParticleSoA<Photon>*> sourcePhotons(numPhotonSpecies);
4675 CH_STOP(t1);
4676
4677 // Regular cells
4678 auto regularKernel = [&](const IntVect& iv) -> void {
4679 if (ebisbox.isRegular(iv) && validCells(iv)) {
4680 const RealVect electricField = RealVect(
4681 D_DECL(electricFieldReg(iv, 0), electricFieldReg(iv, 1), electricFieldReg(iv, 2)));
4682 const RealVect cellPos = probLo + a_dx * (RealVect(iv) + 0.5 * RealVect::Unit);
4683 const RealVect centroidPos = RealVect::Zero;
4684 const RealVect lo = -0.5 * RealVect::Unit;
4685 const RealVect hi = 0.5 * RealVect::Unit;
4686 const RealVect bndryCentroid = RealVect::Zero;
4687 const RealVect bndryNormal = RealVect::Zero;
4688 const Real kappa = 1.0;
4689
4690 // Populate the per-cell Ito data
4691 for (int i = 0; i < numItoSpecies; i++) {
4692 itoParticles[i] = &itoCells[i][a_box.index(iv)];
4693 numNewParticles[i] = llround(a_newParticlesPerCell.getSingleValuedFAB()(iv, i));
4694 numOldParticles[i] = llround(a_oldParticlesPerCell.getSingleValuedFAB()(iv, i));
4695 }
4696
4697 // Populate the per-cell CDR data
4698 for (int i = 0; i < numCdrSpecies; i++) {
4699 cdrParticles[i] = &cdrCells[i][a_box.index(iv)];
4700 numNewCdrParticles[i] = injectCdrProducts ? llround(a_cdrProduction.getSingleValuedFAB()(iv, i)) : 0LL;
4701 }
4702
4703 // Populate the per-cell photon data.
4704 for (int i = 0; i < numPhotonSpecies; i++) {
4705 bulkPhotons[i] = &bulkPhotonCells[i][a_box.index(iv)];
4706 sourcePhotons[i] = &sourcePhotonCells[i][a_box.index(iv)];
4707
4708 numNewPhotons[i] = llround(a_newPhotonsPerCell.getSingleValuedFAB()(iv, i));
4709
4710 // sourcePhotons will hold the NEW number of photons to be generated -- it should already
4711 // have been cleared in upstream code but I'm leaving this in for safety.
4712 sourcePhotons[i]->clear();
4713 }
4714
4715 // Turn the CDR production into particles, so that it reaches the mesh through the same deposition kernel as
4716 // the Ito products rather than landing in this cell alone. Deposited by depositCdrProducts(). A zero
4717 // production makes this a no-op, which is what CdrProductInjection::Mesh relies on.
4718 //
4719 // Runs BEFORE the Ito reconciliation so that both halves of a reaction see the same Ito particles. Under
4720 // ParticlePlacement::Downstream that is what keeps the downstream region identical for the two: the Ito
4721 // products below are placed downstream and so cannot move it, but the photoionization products are placed at
4722 // the absorption position and can.
4723 m_physics->reconcileCdrParticles(cdrParticles,
4724 itoParticles,
4725 numNewCdrParticles,
4726 electricField,
4727 cellPos,
4728 centroidPos,
4729 lo,
4730 hi,
4731 bndryCentroid,
4732 bndryNormal,
4733 a_dx,
4734 kappa);
4735
4736 // Reconcile the ItoSolver particles -- this either removes weight from the original particles (if we lost
4737 // physical particles) or adds new particles (if we gained physical particles)
4738 m_physics->reconcileParticles(itoParticles,
4739 numNewParticles,
4740 numOldParticles,
4741 electricField,
4742 cellPos,
4743 centroidPos,
4744 lo,
4745 hi,
4746 bndryCentroid,
4747 bndryNormal,
4748 a_dx,
4749 kappa);
4750
4751 // Reconcile the photon solver. This will generate new computational photons that are later added to the Monte
4752 // Carlo photon solvers.
4753 m_physics->reconcilePhotons(sourcePhotons,
4754 numNewPhotons,
4755 cellPos,
4756 centroidPos,
4757 lo,
4758 hi,
4759 bndryCentroid,
4760 bndryNormal,
4761 a_dx,
4762 kappa);
4763
4764 // Add the photoionization term. This will adds new particles from the photoionization reactions.
4765 m_physics->reconcilePhotoionization(itoParticles, cdrParticles, bulkPhotons);
4766
4767 // NOTE: Super-particle merging is NOT done here anymore. It is a separate step run after the
4768 // whole chemistry advance (see advanceReactionNetwork(Real)), through the public
4769 // ItoSolver::makeSuperparticles(), so that both per-cell and AMR-wide merge algorithms
4770 // are supported. It used to be done here only because the particles happened to be
4771 // cell-sorted for the reaction kernels.
4772 }
4773 };
4774
4775 // Irregular cells
4776 auto irregularKernel = [&](const VolIndex& vof) -> void {
4777 const IntVect iv = vof.gridIndex();
4778 if (ebisbox.isIrregular(iv) && validCells(iv, 0)) {
4779 const RealVect electricField = RealVect(
4780 D_DECL(a_electricField(vof, 0), a_electricField(vof, 1), a_electricField(vof, 2)));
4781 const RealVect cellPos = probLo + Location::position(Location::Cell::Center, vof, ebisbox, a_dx);
4782 const RealVect centroidPos = ebisbox.centroid(vof);
4783 const RealVect bndryCentroid = ebisbox.bndryCentroid(vof);
4784 const RealVect bndryNormal = ebisbox.normal(vof);
4785 const Real kappa = ebisbox.volFrac(vof);
4786
4787 // Compute the minimum bounding box that encloses this cut-cell.
4788 RealVect lo = -0.5 * RealVect::Unit;
4789 RealVect hi = 0.5 * RealVect::Unit;
4790 if (kappa < 1.0) {
4791 DataOps::computeMinValidBox(lo, hi, bndryNormal, bndryCentroid);
4792 }
4793
4794 // Populate the per-cell particle data.
4795 for (int i = 0; i < numItoSpecies; i++) {
4796 itoParticles[i] = &itoCells[i][a_box.index(iv)];
4797 numNewParticles[i] = llround(a_newParticlesPerCell(vof, i));
4798 numOldParticles[i] = llround(a_oldParticlesPerCell(vof, i));
4799 }
4800
4801 // Populate the per-cell CDR data
4802 for (int i = 0; i < numCdrSpecies; i++) {
4803 cdrParticles[i] = &cdrCells[i][a_box.index(iv)];
4804 numNewCdrParticles[i] = injectCdrProducts ? llround(a_cdrProduction(vof, i)) : 0LL;
4805 }
4806
4807 // Populate the per-cell photon data.
4808 for (int i = 0; i < numPhotonSpecies; i++) {
4809 bulkPhotons[i] = &bulkPhotonCells[i][a_box.index(iv)];
4810 sourcePhotons[i] = &sourcePhotonCells[i][a_box.index(iv)];
4811
4812 numNewPhotons[i] = llround(a_newPhotonsPerCell(vof, i));
4813
4814 // sourcePhotons will hold the NEW number of photons to be generated -- it should already
4815 // have been cleared in upstream code but I'm leaving this in for safety.
4816 sourcePhotons[i]->clear();
4817 }
4818
4819 // Turn the CDR production into particles -- see the regular kernel above.
4820 m_physics->reconcileCdrParticles(cdrParticles,
4821 itoParticles,
4822 numNewCdrParticles,
4823 electricField,
4824 cellPos,
4825 centroidPos,
4826 lo,
4827 hi,
4828 bndryCentroid,
4829 bndryNormal,
4830 a_dx,
4831 kappa);
4832
4833 // Reconcile the ItoSolver particles -- this either removes weight from the original particles (if we lost
4834 // physical particles) or adds new particles (if we gained physical particles)
4835 m_physics->reconcileParticles(itoParticles,
4836 numNewParticles,
4837 numOldParticles,
4838 electricField,
4839 cellPos,
4840 centroidPos,
4841 lo,
4842 hi,
4843 bndryCentroid,
4844 bndryNormal,
4845 a_dx,
4846 kappa);
4847
4848 // Reconcile the photon solver. This will generate new computational photons that are later added to the Monte
4849 // Carlo photon solvers.
4850 m_physics->reconcilePhotons(sourcePhotons,
4851 numNewPhotons,
4852 cellPos,
4853 centroidPos,
4854 lo,
4855 hi,
4856 bndryCentroid,
4857 bndryNormal,
4858 a_dx,
4859 kappa);
4860
4861 // Add the photoionization term. This will adds new particles from the photoionization reactions.
4862 m_physics->reconcilePhotoionization(itoParticles, cdrParticles, bulkPhotons);
4863
4864 // NOTE: Super-particle merging is done after the chemistry advance -- see the regular kernel
4865 // above and advanceReactionNetwork(Real).
4866 }
4867 };
4868
4869 // Run the kernels.
4870 VoFIterator& vofit = (*m_amr->getVofIterator(m_particleRealm, m_plasmaPhase)[a_level])[a_din];
4871
4872 CH_START(t2);
4873 BoxLoops::loop<D_DECL(1, 1, 1)>(a_box, regularKernel);
4874 CH_STOP(t2);
4875
4876 CH_START(t3);
4877 BoxLoops::loop(vofit, irregularKernel);
4878 CH_STOP(t3);
4879
4880 // SoA write-back: rebuild the Ito bulk leaves and the source-photon leaves from the mutated per-cell SoA
4881 // scratch (reconcile added/removed/merged Ito particles and generated source photons). The bulk-photon
4882 // scratch was read-only (photoionization), so it needs no write-back.
4883 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
4884 const int idx = solverIt.index();
4885
4886 ParticleContainer<ItoParticle>& solverParticles = solverIt()->getParticles(ItoSolver::WhichContainer::Bulk);
4887
4888 rebuildLeafFromCells(solverParticles[a_level][a_din], itoCells[idx], a_box, a_dx, probLo);
4889 }
4890
4891 for (auto solverIt = m_rte->iterator(); solverIt.ok(); ++solverIt) {
4892 const int idx = solverIt.index();
4893
4894 ParticleContainer<Photon>& solverSourcePhotons = solverIt()->getSourcePhotons();
4895
4896 rebuildLeafFromCells(solverSourcePhotons[a_level][a_din], sourcePhotonCells[idx], a_box, a_dx, probLo);
4897 }
4898
4899 // Rebuild the CDR photoionization-product leaves from the mutated per-cell scratch.
4900 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
4901 const int idx = solverIt.index();
4902
4903 rebuildLeafFromCells((*m_cdrProducts[idx])[a_level][a_din], cdrCells[idx], a_box, a_dx, probLo);
4904 }
4905}
4906
4907template <typename I, typename C, typename R, typename F>
4908void
4910{
4911 CH_TIME("ItoKMCStepper::reconcilePhotoionization()");
4912 if (m_verbosity > 5) {
4913 pout() << m_name + "::reconcilePhotoionization()" << endl;
4914 }
4915
4916 const int numItoSpecies = m_physics->getNumItoSpecies();
4917 const int numCdrSpecies = m_physics->getNumCdrSpecies();
4918 const int numPhotonSpecies = m_physics->getNumPhotonSpecies();
4919
4920 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
4921 const DisjointBoxLayout& dbl = m_amr->getGrids(m_particleRealm)[lvl];
4922 const DataIterator& dit = dbl.dataIterator();
4923
4924 const int nbox = dit.size();
4925
4926#pragma omp parallel for schedule(runtime)
4927 for (int mybox = 0; mybox < nbox; mybox++) {
4928 const DataIndex& din = dit[mybox];
4929
4930 // reconcilePhotoionization only APPENDS new Ito/CDR products (reading the absorbed bulk photons), so we
4931 // pass fresh empty Ito product containers and point the absorbed-photon args directly at the live bulk
4932 // photon leaves (read-only). The new Ito products are then bulk-appended to the SoA bulk leaves,
4933 // preserving the existing particles' full payload.
4934 Vector<ParticleSoA<ItoParticle>> itoProducts(numItoSpecies);
4935
4936 Vector<ParticleSoA<ItoParticle>*> itoParticles(numItoSpecies);
4937 Vector<ParticleSoA<NoPayload>*> cdrParticles(numCdrSpecies);
4938 Vector<ParticleSoA<Photon>*> photonParticles(numPhotonSpecies);
4939
4940 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
4941 itoParticles[solverIt.index()] = &itoProducts[solverIt.index()];
4942 }
4943
4944 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
4945 cdrParticles[solverIt.index()] = &((*m_cdrProducts[solverIt.index()])[lvl][din]);
4946 }
4947
4948 for (auto solverIt = m_rte->iterator(); solverIt.ok(); ++solverIt) {
4949 photonParticles[solverIt.index()] = &(solverIt()->getBulkPhotons()[lvl][din]);
4950 }
4951
4952 m_physics->reconcilePhotoionization(itoParticles, cdrParticles, photonParticles);
4953
4954 // Append the new Ito photoionization products into the SoA bulk leaves (existing particles untouched).
4955 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
4956 const int idx = solverIt.index();
4957 ParticleSoA<ItoParticle>& leaf = solverIt()->getParticles(ItoSolver::WhichContainer::Bulk)[lvl][din];
4958
4959 leaf.append(itoProducts[idx]);
4960 }
4961 }
4962 }
4963}
4964
4965template <typename I, typename C, typename R, typename F>
4966void
4967ItoKMCStepper<I, C, R, F>::reconcileCdrDensities(const EBAMRCellData& a_cdrChange, const Real a_dt) noexcept
4968{
4969 CH_TIME("ItoKMCStepper::reconcileCdrDensities(EBAMRCellData, Real)");
4970 if (m_verbosity > 5) {
4971 pout() << m_name + "::reconcileCdrDensities(EBAMRCellData, Real)" << endl;
4972 }
4973
4974 const int numCdrSpecies = m_physics->getNumCdrSpecies();
4975
4976 CH_assert(a_cdrChange.getRealm() == m_fluidRealm);
4977 CH_assert(a_dt > 0.0);
4978
4979 if (numCdrSpecies > 0) {
4980
4981 // Increment, but don't divide by kappa.
4982 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
4983 this->reconcileCdrDensities(*a_cdrChange[lvl], lvl, a_dt);
4984 }
4985
4986 // Redistribute if the user calls for it. Only under CdrProductInjection::Mesh: the redistribution corrects the
4987 // kappa damping that phi += change/V imposes on a cut-cell reaction, and under CdrProductInjection::Particle the
4988 // production no longer lands in the cell through that route -- it is deposited by the Ito solver, with the Ito
4989 // solver's own cut-cell normalization. See depositCdrProducts().
4991 for (auto it = m_cdr->iterator(); it.ok(); ++it) {
4992 const int idx = it.index();
4993
4994 const EBAMRCellData cdrChange = m_amr->slice(a_cdrChange, Interval(idx, idx));
4995
4996 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
4997 const DisjointBoxLayout& dbl = m_amr->getGrids(m_fluidRealm)[lvl];
4998 const DataIterator& dit = dbl.dataIterator();
4999 const EBISLayout& ebisl = m_amr->getEBISLayout(m_fluidRealm, m_plasmaPhase)[lvl];
5000 const Real dx = m_amr->getDx()[lvl];
5001
5002 const int nbox = dit.size();
5003
5004#pragma omp parallel for schedule(runtime)
5005 for (int mybox = 0; mybox < nbox; mybox++) {
5006 const DataIndex& din = dit[mybox];
5007 const EBISBox& ebisbox = ebisl[din];
5008
5009 BaseIVFAB<Real>& deltaMass = (*m_fluidScratchEB[lvl])[din];
5010
5011 deltaMass.setVal(0.0);
5012
5013 const EBCellFAB& change = (*a_cdrChange[lvl])[din];
5014
5015 auto kernel = [&](const VolIndex& vof) -> void {
5016 const Real kappa = ebisbox.volFrac(vof);
5017
5018 deltaMass(vof, 0) = change(vof, idx) * (1.0 - kappa) / std::pow(dx, SpaceDim);
5019 };
5020
5021 VoFIterator& vofit = (*m_amr->getVofIterator(m_fluidRealm, m_plasmaPhase)[lvl])[din];
5022
5023 BoxLoops::loop(vofit, kernel);
5024 }
5025 }
5026
5027 const RefCountedPtr<CdrSolver>& solver = it();
5028
5029 solver->redistribute(solver->getPhi(), m_fluidScratchEB);
5030 }
5031 }
5032
5033 // No ghost interpolation: nothing reads the density or source-term ghost cells between here and the
5034 // next transport step, which fills them itself. See coarsenCDRSolvers().
5035 this->coarsenCDRSolvers(false);
5036 }
5037}
5038
5039template <typename I, typename C, typename R, typename F>
5040void
5041ItoKMCStepper<I, C, R, F>::reconcileCdrDensities(const LevelData<EBCellFAB>& a_cdrChange,
5042 const int a_level,
5043 const Real a_dt) noexcept
5044{
5045 CH_TIME("ItoKMCStepper::reconcileCdrDensities(LD<EBCellFAB>, int, Real)");
5046 if (m_verbosity > 5) {
5047 pout() << m_name + "::reconcileCdrDensities(LD<EBCellFAB>, int, Real)" << endl;
5048 }
5049
5050 const int numCdrSpecies = m_physics->getNumCdrSpecies();
5051
5052 CH_assert(a_cdrChange.nComp() == numCdrSpecies);
5053
5054 const DisjointBoxLayout& dbl = m_amr->getGrids(m_fluidRealm)[a_level];
5055 const DataIterator& dit = dbl.dataIterator();
5056 const Real dx = m_amr->getDx()[a_level];
5057
5058 const int nbox = dit.size();
5059
5060#pragma omp parallel for schedule(runtime)
5061 for (int mybox = 0; mybox < nbox; mybox++) {
5062 const DataIndex& din = dit[mybox];
5063
5064 this->reconcileCdrDensities(a_cdrChange[din], a_level, din, dbl[din], dx, a_dt);
5065 }
5066}
5067
5068template <typename I, typename C, typename R, typename F>
5069void
5071 const int a_level,
5072 const DataIndex a_din,
5073 const Box a_box,
5074 const Real a_dx,
5075 const Real a_dt) noexcept
5076{
5077 CH_TIME("ItoKMCStepper::reconcileCdrDensities(EBCellFAB, int, DataIndex, Box, Realx2)");
5078 if (m_verbosity > 5) {
5079 pout() << m_name + "::reconcileCdrDensities(EBCellFAB, int, DataIndex, Box, Realx2)" << endl;
5080 }
5081
5082 const int numCdrSpecies = m_physics->getNumCdrSpecies();
5083
5084 CH_assert(a_cdrChange.nComp() == numCdrSpecies);
5085
5086 const Real volume = std::pow(a_dx, SpaceDim);
5087
5088 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
5089 RefCountedPtr<CdrSolver>& solver = solverIt();
5090 const int index = solverIt.index();
5091
5092 EBCellFAB& phi = (*(solver->getPhi()[a_level]))[a_din];
5093 EBCellFAB& src = (*(solver->getSource()[a_level]))[a_din];
5094
5095 // Source = change/volume
5096 src.setVal(0.0);
5097 src.plus(a_cdrChange, index, 0, 1);
5098 src /= volume;
5099
5100 // Phi += change/volume
5101 phi += src;
5102
5103 // Source = change/(volume*dt)
5104 src /= a_dt;
5105 }
5106}
5107
5108template <typename I, typename C, typename R, typename F>
5109void
5110ItoKMCStepper<I, C, R, F>::coarsenCDRSolvers(const bool a_interpGhosts) noexcept
5111{
5112 CH_TIME("ItoKMCStepper::coarsenCDRSolvers");
5113 if (m_verbosity > 5) {
5114 pout() << m_name + "::coarsenCDRSolvers" << endl;
5115 }
5116
5117 for (auto solverIt = this->m_cdr->iterator(); solverIt.ok(); ++solverIt) {
5118 auto& solver = solverIt();
5119
5120 EBAMRCellData& phi = solver->getPhi();
5121 EBAMRCellData& src = solver->getSource();
5122
5123 this->m_amr->conservativeAverage(phi, phi.getRealm(), this->m_plasmaPhase);
5124 this->m_amr->conservativeAverage(src, src.getRealm(), this->m_plasmaPhase);
5125
5126 // Density only. The source term's ghost cells have no reader anywhere -- see the note on the
5127 // declaration -- so interpolating them is a hierarchy-wide exchange per species per step for data
5128 // nothing looks at.
5129 if (a_interpGhosts) {
5130 this->m_amr->interpGhostPwl(phi, phi.getRealm(), this->m_plasmaPhase);
5131 }
5132
5133 DataOps::setCoveredValue(phi, this->m_amr->getCoveredCells(phi.getRealm(), this->m_plasmaPhase), 0.0);
5134 DataOps::setCoveredValue(src, this->m_amr->getCoveredCells(src.getRealm(), this->m_plasmaPhase), 0.0);
5135 }
5136}
5137
5138template <typename I, typename C, typename R, typename F>
5139bool
5141{
5142 CH_TIME("ItoKMCStepper::needSecondaryEmissionEB");
5143 if (m_verbosity > 5) {
5144 pout() << m_name + "::needSecondaryEmissionEB" << endl;
5145 }
5146
5147 // Emission that needs no primaries (e.g. field emission) must run every step. Static, hence no reduction.
5148 if (m_physics->emitsWithoutPrimariesEB()) {
5149 return true;
5150 }
5151
5152 // A mobile CDR species can deliver flux to the boundary with no particles or photons involved at all, so
5153 // its presence alone forces the emission to run. Static, hence no reduction.
5154 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
5155 if (solverIt()->isMobile()) {
5156 return true;
5157 }
5158 }
5159
5160 long long numPrimaries = 0;
5161
5162 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
5163 numPrimaries += static_cast<long long>(
5164 solverIt()->getParticles(ItoSolver::WhichContainer::EB).getNumberOfValidParticlesLocal());
5165 }
5166
5167 for (auto solverIt = m_rte->iterator(); solverIt.ok(); ++solverIt) {
5168 numPrimaries += static_cast<long long>(solverIt()->getEbPhotons().getNumberOfValidParticlesLocal());
5169 }
5170
5171 return ParallelOps::sum(numPrimaries) > 0LL;
5172}
5173
5174template <typename I, typename C, typename R, typename F>
5175void
5177{
5178 CH_TIME("ItoKMCStepper::fillSecondaryEmissionEB(Real)");
5179 if (m_verbosity > 5) {
5180 pout() << m_name + "::fillSecondaryEmissionEB(Real)" << endl;
5181 }
5182
5183 // Particles that left the domain
5184 Vector<ParticleContainer<ItoParticle>*> primaryParticles;
5185 for (auto it = m_ito->iterator(); it.ok(); ++it) {
5186 ParticleContainer<ItoParticle>& intersectedParticles = it()->getParticles(ItoSolver::WhichContainer::EB);
5187
5188 primaryParticles.push_back(&intersectedParticles);
5189 }
5190
5191 // CDR solvers extrapolate their fluxes. We then copy the extrapolated fluxes to transient data holders (which are
5192 // defined over the particle realm).
5193 EBAMRIVData tmp;
5194 m_amr->allocate(tmp, m_fluidRealm, m_plasmaPhase, 1);
5195
5196 for (auto solverIt = m_cdr->iterator(); solverIt.ok(); ++solverIt) {
5197 const int idx = solverIt.index();
5198 const RefCountedPtr<CdrSolver>& solver = solverIt();
5199
5200 EBAMRIVData& extrapFlux = m_cdrFluxesExtrap[idx];
5201
5202 if (solver->isMobile()) {
5203 solver->extrapolateAdvectiveFluxToEB(tmp);
5204
5205 m_amr->copyData(extrapFlux, tmp);
5206 }
5207 else {
5208 DataOps::setValue(extrapFlux, 0.0);
5209 }
5210 }
5211
5212 // Photons that left the domain
5213 Vector<ParticleContainer<Photon>*> primaryPhotons;
5214 for (auto it = m_rte->iterator(); it.ok(); ++it) {
5215 ParticleContainer<Photon>& intersectedPhotons = it()->getEbPhotons();
5216
5217 primaryPhotons.push_back(&intersectedPhotons);
5218 }
5219
5220 // Call the other version.
5224 primaryParticles,
5226 primaryPhotons,
5228 a_dt);
5229}
5230
5231template <typename I, typename C, typename R, typename F>
5232void
5234 Vector<RefCountedPtr<ParticleContainer<ItoParticle>>>& a_secondaryParticles,
5235 Vector<EBAMRIVData>& a_cdrFluxes,
5236 Vector<RefCountedPtr<ParticleContainer<Photon>>>& a_secondaryPhotons,
5237 Vector<ParticleContainer<ItoParticle>*>& a_primaryParticles,
5238 Vector<EBAMRIVData>& a_cdrFluxesExtrap,
5239 Vector<ParticleContainer<Photon>*>& a_primaryPhotons,
5240 const EBAMRCellData& a_electricField,
5241 const Real a_dt) noexcept
5242{
5243 CH_TIME("ItoKMCStepper::fillSecondaryEmissionEB(full)");
5244 if (m_verbosity > 5) {
5245 pout() << m_name + "::fillSecondaryEmissionEB(full)" << endl;
5246 }
5247
5248 const int numItoSpecies = m_physics->getNumItoSpecies();
5249 const int numCdrSpecies = m_physics->getNumCdrSpecies();
5250 const int numPhotonSpecies = m_physics->getNumPhotonSpecies();
5251
5252 CH_assert(a_secondaryParticles.size() == numItoSpecies);
5253 CH_assert(a_cdrFluxes.size() == numCdrSpecies);
5254 CH_assert(a_secondaryPhotons.size() == numPhotonSpecies);
5255 CH_assert(a_primaryParticles.size() == numItoSpecies);
5256 CH_assert(a_cdrFluxesExtrap.size() == numCdrSpecies);
5257 CH_assert(a_primaryPhotons.size() == numPhotonSpecies);
5258 CH_assert(a_electricField.getRealm() == m_particleRealm);
5259 CH_assert(a_dt >= 0.0);
5260
5261 // Incoming/outgoing particle containers must be sorted by cell.
5262 for (int i = 0; i < numItoSpecies; i++) {
5263 CH_assert(a_secondaryParticles[i]->getRealm() == m_particleRealm);
5264 CH_assert(a_primaryParticles[i]->getRealm() == m_particleRealm);
5265
5266 a_secondaryParticles[i]->clearParticles();
5267 a_secondaryParticles[i]->organizeParticlesByCell();
5268
5269 a_primaryParticles[i]->organizeParticlesByCell();
5270 }
5271
5272 for (int i = 0; i < numCdrSpecies; i++) {
5273 CH_assert(a_cdrFluxes[i].getRealm() == m_particleRealm);
5274 CH_assert(a_cdrFluxesExtrap[i].getRealm() == m_particleRealm);
5275
5276 DataOps::setValue(a_cdrFluxes[i], 0.0);
5277 }
5278
5279 // Incoming/outgoing photon containers by be sorted by cell
5280 for (int i = 0; i < numPhotonSpecies; i++) {
5281 CH_assert(a_secondaryPhotons[i]->getRealm() == m_particleRealm);
5282 CH_assert(a_primaryPhotons[i]->getRealm() == m_particleRealm);
5283
5284 a_secondaryPhotons[i]->clearParticles();
5285
5286 a_secondaryPhotons[i]->organizeParticlesByCell();
5287 a_primaryPhotons[i]->organizeParticlesByCell();
5288 }
5289
5290 const RealVect probLo = m_amr->getProbLo();
5291
5292 const Vector<Electrode>& electrodes = m_computationalGeometry->getElectrodes();
5293 const Vector<Dielectric>& dielectrics = m_computationalGeometry->getDielectrics();
5294
5295 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
5296 const DisjointBoxLayout& dbl = m_amr->getGrids(m_particleRealm)[lvl];
5297 const DataIterator& dit = dbl.dataIterator();
5298 const EBISLayout& ebisl = m_amr->getEBISLayout(m_particleRealm, m_plasmaPhase)[lvl];
5299 const Real dx = m_amr->getDx()[lvl];
5300
5301 const int nbox = dit.size();
5302
5303#pragma omp parallel for schedule(runtime)
5304 for (int mybox = 0; mybox < nbox; mybox++) {
5305 const DataIndex& din = dit[mybox];
5306
5307 // The kernel below is driven by the cut cells, so a patch without any has nothing to do. Its
5308 // secondary containers were cleared and its CDR fluxes zeroed before this loop, which is
5309 // exactly the state the patch would be left in anyway. Skipping matters because everything
5310 // below is per species and would otherwise be paid on every patch in the domain, whether or
5311 // not it is anywhere near the EB.
5312 VoFIterator& vofit = (*m_amr->getVofIterator(m_particleRealm, m_plasmaPhase)[lvl])[din];
5313
5314 if (vofit.size() == 0) {
5315 continue;
5316 }
5317
5318 const EBISBox& ebisbox = ebisl[din];
5319 const EBCellFAB& electricField = (*a_electricField[lvl])[din];
5320 const BaseFab<bool>& validCells = (*m_amr->getValidCells(m_particleRealm)[lvl])[din];
5321 const Box box = dbl[din];
5322
5323 bool isDielectric = false;
5324
5325 // Per-cell SoA scratch (indexed by Box::index(iv)). Primary cells are read from the SoA leaves;
5326 // secondary cells start empty and are rebuilt into the SoA leaves after the kernel.
5327 std::vector<std::vector<ParticleSoA<ItoParticle>>> primaryItoCells(numItoSpecies);
5328 std::vector<std::vector<ParticleSoA<ItoParticle>>> secondaryItoCells(numItoSpecies);
5329 std::vector<std::vector<ParticleSoA<Photon>>> primaryPhotonCells(numPhotonSpecies);
5330 std::vector<std::vector<ParticleSoA<Photon>>> secondaryPhotonCells(numPhotonSpecies);
5331
5332 Vector<BaseIVFAB<Real>*> cdrFluxesFAB;
5333 Vector<BaseIVFAB<Real>*> cdrFluxesExtrapFAB;
5334
5335 for (auto it = m_ito->iterator(); it.ok(); ++it) {
5336 const int idx = it.index();
5337
5338 binLeafToCells(primaryItoCells[idx], (*a_primaryParticles[idx])[lvl][din], box, dx, probLo);
5339 secondaryItoCells[idx].resize(box.numPts());
5340 }
5341
5342 for (auto it = m_cdr->iterator(); it.ok(); ++it) {
5343 cdrFluxesFAB.push_back(&((*(a_cdrFluxes[it.index()])[lvl])[din]));
5344 cdrFluxesExtrapFAB.push_back(&((*(a_cdrFluxesExtrap[it.index()])[lvl])[din]));
5345 }
5346
5347 for (auto it = m_rte->iterator(); it.ok(); ++it) {
5348 const int idx = it.index();
5349
5350 binLeafToCells(primaryPhotonCells[idx], (*a_primaryPhotons[idx])[lvl][din], box, dx, probLo);
5351 secondaryPhotonCells[idx].resize(box.numPts());
5352 }
5353
5354 // Kernel definition.
5355 auto irregularKernel = [&](const VolIndex& vof) -> void {
5356 const IntVect iv = vof.gridIndex();
5357
5358 if (validCells(iv)) {
5359 const RealVect E = RealVect(D_DECL(electricField(vof, 0), electricField(vof, 1), electricField(vof, 2)));
5360 const RealVect bndryNormal = ebisbox.normal(vof);
5361 const RealVect bndryCentroid = ebisbox.bndryCentroid(vof);
5362 const RealVect cellCentroid = ebisbox.centroid(vof);
5363 const RealVect cellCenter = probLo + Location::position(Location::Cell::Center, vof, ebisbox, dx);
5364 const RealVect physPos = cellCenter + bndryCentroid * dx;
5365 const Real bndryArea = ebisbox.bndryArea(vof);
5366
5367 const long cellIdx = box.index(iv);
5368
5369 // Secondary containers start empty; the kernel appends to them. Primary cells are moved in from the
5370 // per-cell scratch (read-only input; their leaves are not written back).
5371 Vector<ParticleSoA<ItoParticle>> secondaryParticles(numItoSpecies);
5372 Vector<ParticleSoA<ItoParticle>> primaryParticles(numItoSpecies);
5373
5374 Vector<Real> cdrFluxes(numCdrSpecies, 0.0);
5375 Vector<Real> cdrFluxesExtrap(numCdrSpecies, 0.0);
5376
5377 Vector<ParticleSoA<Photon>> secondaryPhotons(numPhotonSpecies);
5378 Vector<ParticleSoA<Photon>> primaryPhotons(numPhotonSpecies);
5379
5380 for (int i = 0; i < numItoSpecies; i++) {
5381 primaryParticles[i] = std::move(primaryItoCells[i][cellIdx]);
5382 }
5383
5384 // Populate CDR fluxes
5385 for (int i = 0; i < numCdrSpecies; i++) {
5386 cdrFluxes[i] = 0.0;
5387 cdrFluxesExtrap[i] = (*cdrFluxesExtrapFAB[i])(vof, 0);
5388 }
5389
5390 for (int i = 0; i < numPhotonSpecies; i++) {
5391 primaryPhotons[i] = std::move(primaryPhotonCells[i][cellIdx]);
5392 }
5393
5394 // Figure out which material we are dealing with.
5395 int matIndex = -1;
5396 Real minDist = std::numeric_limits<Real>::max();
5397
5398 for (int i = 0; i < electrodes.size(); i++) {
5399 const Real curDist = electrodes[i].getImplicitFunction()->value(physPos);
5400
5401 if (std::abs(curDist) < std::abs(minDist)) {
5402 minDist = curDist;
5403 matIndex = i;
5404 }
5405 }
5406
5407 for (int i = 0; i < dielectrics.size(); i++) {
5408 const Real curDist = dielectrics[i].getImplicitFunction()->value(physPos);
5409
5410 if (std::abs(curDist) < std::abs(minDist)) {
5411 minDist = curDist;
5412 matIndex = i;
5413 isDielectric = true;
5414 }
5415 }
5416
5417 // Call the physics framework.
5418 m_physics->secondaryEmissionEB(secondaryParticles,
5419 cdrFluxes,
5420 secondaryPhotons,
5421 primaryParticles,
5422 cdrFluxesExtrap,
5423 primaryPhotons,
5424 E,
5425 cellCenter,
5426 cellCentroid,
5427 bndryCentroid,
5428 bndryNormal,
5429 bndryArea,
5430 dx,
5431 a_dt,
5432 isDielectric,
5433 matIndex);
5434
5435 // Fill output data holders (move the per-cell secondary results into the per-cell scratch).
5436 for (int i = 0; i < numItoSpecies; i++) {
5437 secondaryItoCells[i][cellIdx] = std::move(secondaryParticles[i]);
5438 }
5439
5440 for (int i = 0; i < numCdrSpecies; i++) {
5441 (*cdrFluxesFAB[i])(vof, 0) = cdrFluxes[i];
5442 }
5443
5444 for (int i = 0; i < numPhotonSpecies; i++) {
5445 secondaryPhotonCells[i][cellIdx] = std::move(secondaryPhotons[i]);
5446 }
5447 }
5448 };
5449
5450 // Run the kernel.
5451 BoxLoops::loop(vofit, irregularKernel);
5452
5453 // SoA write-back: rebuild the secondary Ito/photon leaves for this patch from the filled per-cell scratch.
5454 // Primaries are read-only (the physics interface takes them by const reference), so they are not written.
5455 for (auto it = m_ito->iterator(); it.ok(); ++it) {
5456 const int idx = it.index();
5457 rebuildLeafFromCells((*a_secondaryParticles[idx])[lvl][din], secondaryItoCells[idx], box, dx, probLo);
5458 }
5459 for (auto it = m_rte->iterator(); it.ok(); ++it) {
5460 const int idx = it.index();
5461 rebuildLeafFromCells((*a_secondaryPhotons[idx])[lvl][din], secondaryPhotonCells[idx], box, dx, probLo);
5462 }
5463 }
5464 }
5465
5466 // Sort by patch
5467 for (int i = 0; i < numItoSpecies; i++) {
5468 a_secondaryParticles[i]->organizeParticlesByPatch();
5469 a_primaryParticles[i]->organizeParticlesByPatch();
5470 }
5471
5472 for (int i = 0; i < numPhotonSpecies; i++) {
5473 a_secondaryPhotons[i]->organizeParticlesByPatch();
5474 a_primaryPhotons[i]->organizeParticlesByPatch();
5475 }
5476}
5477
5478template <typename I, typename C, typename R, typename F>
5479void
5481{
5482 CH_TIME("ItoKMCStepper::resolveSecondaryEmissionEB(short)");
5483 if (m_verbosity > 5) {
5484 pout() << m_name + "::resolveSecondaryEmissionEB(short)" << endl;
5485 }
5486
5487 Vector<ParticleContainer<ItoParticle>*> secondaryParticles;
5488 Vector<ParticleContainer<ItoParticle>*> primaryParticles;
5489
5490 for (auto it = m_ito->iterator(); it.ok(); ++it) {
5491 const int idx = it.index();
5492
5493 primaryParticles.push_back(&(it()->getParticles(ItoSolver::WhichContainer::EB)));
5494 secondaryParticles.push_back(&(*m_secondaryParticles[idx]));
5495 }
5496
5497 // Copy the CDR fluxes on the particle realm over to the fluid realm.
5498 Vector<EBAMRIVData*> cdrFluxes;
5499 for (auto it = m_cdr->iterator(); it.ok(); ++it) {
5500 const RefCountedPtr<CdrSolver>& solver = it();
5501 const int idx = it.index();
5502
5503 EBAMRIVData& ebFlux = solver->getEbFlux();
5504
5505 m_amr->copyData(ebFlux, m_cdrFluxes[idx]);
5506
5507 m_amr->arithmeticAverage(ebFlux, m_fluidRealm, m_plasmaPhase);
5508
5509 cdrFluxes.push_back(&ebFlux);
5510 }
5511
5512 // Handle to surface charge density.
5513 EBAMRIVData& surfaceChargeDensity = m_sigmaSolver->getPhi();
5514
5515 this->resolveSecondaryEmissionEB(secondaryParticles, primaryParticles, cdrFluxes, surfaceChargeDensity, a_dt);
5516
5517 m_sigmaSolver->resetElectrodes(0.0);
5518 m_amr->arithmeticAverage(surfaceChargeDensity, m_fluidRealm, m_plasmaPhase);
5519}
5520
5521template <typename I, typename C, typename R, typename F>
5522void
5524 Vector<ParticleContainer<ItoParticle>*>& a_primaryParticles,
5525 Vector<EBAMRIVData*>& a_cdrFluxes,
5526 EBAMRIVData& a_surfaceChargeDensity,
5527 const Real a_dt) noexcept
5528{
5529 CH_TIME("ItoKMCStepper::resolveSecondaryEmissionEB(full)");
5530 if (m_verbosity > 5) {
5531 pout() << m_name + "::resolveSecondaryEmissionEB(full)" << endl;
5532 }
5533
5534 const int numItoSpecies = m_physics->getNumItoSpecies();
5535 const int numCdrSpecies = m_physics->getNumCdrSpecies();
5536
5537 CH_assert(a_secondaryParticles.size() == numItoSpecies);
5538 CH_assert(a_primaryParticles.size() == numItoSpecies);
5539 CH_assert(a_cdrFluxes.size() == numCdrSpecies);
5540 CH_assert(a_surfaceChargeDensity.getRealm() == m_fluidRealm);
5541
5542 for (int i = 0; i < numItoSpecies; i++) {
5543 CH_assert(a_secondaryParticles[i]->getRealm() == m_particleRealm);
5544 CH_assert(a_primaryParticles[i]->getRealm() == m_particleRealm);
5545 }
5546
5547 for (int i = 0; i < numCdrSpecies; i++) {
5548 CH_assert(a_secondaryParticles[i]->getRealm() == m_particleRealm);
5549 CH_assert(a_primaryParticles[i]->getRealm() == m_particleRealm);
5550 }
5551
5552 // Deposit the incoming/outgoing particles on the surface and update the surface charge density.
5553 for (auto it = m_ito->iterator(); it.ok(); ++it) {
5554 const RefCountedPtr<ItoSolver>& solver = it();
5555 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
5556
5557 const int idx = it.index();
5558 const int Z = species->getChargeNumber();
5559
5560 if (Z != 0) {
5561
5562 // Add charge from primary particles
5563 m_amr->depositParticles(m_particleScratchEB, m_particleRealm, m_plasmaPhase, *a_primaryParticles[idx]);
5564
5566 DataOps::incr(a_surfaceChargeDensity,
5568 1.0 * Z * Units::Qe,
5569 m_amr->getVofIterator(m_fluidRealm, m_plasmaPhase));
5570
5571 // Subtract charge from secondary particles
5572 m_amr->depositParticles(m_particleScratchEB, m_particleRealm, m_plasmaPhase, *a_secondaryParticles[idx]);
5573
5575 DataOps::incr(a_surfaceChargeDensity,
5577 -1.0 * Z * Units::Qe,
5578 m_amr->getVofIterator(m_fluidRealm, m_plasmaPhase));
5579 }
5580
5581 // Add the secondary particles into the solvers and remove the primary particles.
5582 ParticleContainer<ItoParticle>& particles = solver->getParticles(ItoSolver::WhichContainer::Bulk);
5583 particles.transferParticles(a_secondaryParticles[idx]->getParticles());
5584
5585 a_primaryParticles[idx]->clearParticles();
5586
5587 if (a_secondaryParticles[idx]->getNumberOfValidParticlesGlobal() > 0) {
5588 MayDay::Abort("logic bust");
5589 }
5590 }
5591
5592 // Add CDR fluxes to the CDR solvers
5593 for (auto it = m_cdr->iterator(); it.ok(); ++it) {
5594 const RefCountedPtr<CdrSolver>& solver = it();
5595 const RefCountedPtr<CdrSpecies>& species = solver->getSpecies();
5596
5597 const int idx = it.index();
5598 const int Z = species->getChargeNumber();
5599
5600 if (Z != 0) {
5601 DataOps::incr(a_surfaceChargeDensity,
5602 *a_cdrFluxes[idx],
5603 Z * a_dt * Units::Qe,
5604 m_amr->getVofIterator(m_fluidRealm, m_plasmaPhase));
5605 }
5606
5607 // Add mass to CDR solvers -- this is an inefficient way of doing it but I don't know if it'll be a performance
5608 // bottleneck as well.
5609 EBAMRCellData divG;
5610 EBAMRFluxData G;
5611
5612 m_amr->allocate(divG, m_fluidRealm, m_plasmaPhase, 1);
5613 m_amr->allocate(G, m_fluidRealm, m_plasmaPhase, 1);
5614
5615 DataOps::setValue(G, 0.0);
5616
5617 EBAMRCellData& phi = solver->getPhi();
5618
5619 solver->computeDivG(divG, G, *a_cdrFluxes[idx], phi, a_dt, false);
5620
5621 DataOps::incr(phi, divG, -a_dt);
5622
5623 m_amr->conservativeAverage(phi, m_fluidRealm, m_plasmaPhase);
5624 m_amr->interpGhostPwl(phi, m_fluidRealm, m_plasmaPhase);
5625
5626 // Really don't want negative densities.
5627 DataOps::floor(phi, 0.0, m_amr->getVofIterator(m_fluidRealm, m_plasmaPhase));
5628 }
5629
5630 // Conservatively coarsen the surface charge density.
5631 m_amr->conservativeAverage(a_surfaceChargeDensity, m_fluidRealm, m_plasmaPhase);
5632}
5633
5634template <typename I, typename C, typename R, typename F>
5635bool
5637{
5638 CH_TIME("ItoKMCStepper::needSecondaryEmissionDomain");
5639 if (m_verbosity > 5) {
5640 pout() << m_name + "::needSecondaryEmissionDomain" << endl;
5641 }
5642
5643 // Emission that needs no primaries (e.g. field emission) must run every step. Static, hence no reduction.
5644 if (m_physics->emitsWithoutPrimariesDomain()) {
5645 return true;
5646 }
5647
5648 long long numPrimaries = 0;
5649
5650 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
5651 numPrimaries += static_cast<long long>(
5652 solverIt()->getParticles(ItoSolver::WhichContainer::Domain).getNumberOfValidParticlesLocal());
5653 }
5654
5655 for (auto solverIt = m_rte->iterator(); solverIt.ok(); ++solverIt) {
5656 numPrimaries += static_cast<long long>(solverIt()->getDomainPhotons().getNumberOfValidParticlesLocal());
5657 }
5658
5659 return ParallelOps::sum(numPrimaries) > 0LL;
5660}
5661
5662template <typename I, typename C, typename R, typename F>
5663void
5665{
5666 CH_TIME("ItoKMCStepper::fillSecondaryEmissionDomain(Real)");
5667 if (m_verbosity > 5) {
5668 pout() << m_name + "::fillSecondaryEmissionDomain(Real)" << endl;
5669 }
5670
5671 // Particles that left the domain
5672 Vector<ParticleContainer<ItoParticle>*> primaryParticles;
5673
5674 for (auto it = m_ito->iterator(); it.ok(); ++it) {
5675 primaryParticles.push_back(&(it()->getParticles(ItoSolver::WhichContainer::Domain)));
5676 }
5677
5678 // Photons that left the domain
5679 Vector<ParticleContainer<Photon>*> primaryPhotons;
5680
5681 for (auto it = m_rte->iterator(); it.ok(); ++it) {
5682 primaryPhotons.push_back(&(it()->getDomainPhotons()));
5683 }
5684
5687 primaryParticles,
5688 primaryPhotons,
5690 a_dt);
5691}
5692
5693template <typename I, typename C, typename R, typename F>
5694void
5696 Vector<RefCountedPtr<ParticleContainer<ItoParticle>>>& a_secondaryParticles,
5697 Vector<RefCountedPtr<ParticleContainer<Photon>>>& a_secondaryPhotons,
5698 Vector<ParticleContainer<ItoParticle>*>& a_primaryParticles,
5699 Vector<ParticleContainer<Photon>*>& a_primaryPhotons,
5700 const EBAMRCellData& a_electricField,
5701 const Real a_dt) noexcept
5702{
5703 CH_TIME("ItoKMCStepper::fillSecondaryEmissionDomain(full)");
5704 if (m_verbosity > 5) {
5705 pout() << m_name + "::fillSecondaryEmissionDomain(full)" << endl;
5706 }
5707
5708 const int numItoSpecies = m_physics->getNumItoSpecies();
5709 const int numPhotonSpecies = m_physics->getNumPhotonSpecies();
5710
5711 CH_assert(a_secondaryParticles.size() == numItoSpecies);
5712 CH_assert(a_secondaryPhotons.size() == numPhotonSpecies);
5713 CH_assert(a_primaryParticles.size() == numItoSpecies);
5714 CH_assert(a_primaryPhotons.size() == numPhotonSpecies);
5715 CH_assert(a_electricField.getRealm() == m_particleRealm);
5716 CH_assert(a_dt >= 0.0);
5717
5718 // Incoming/outgoing particle and photon containers must be sorted by cell.
5719 for (int i = 0; i < numItoSpecies; i++) {
5720 CH_assert(a_secondaryParticles[i]->getRealm() == m_particleRealm);
5721 CH_assert(a_primaryParticles[i]->getRealm() == m_particleRealm);
5722
5723 a_secondaryParticles[i]->clearParticles();
5724 a_secondaryParticles[i]->organizeParticlesByCell();
5725
5726 a_primaryParticles[i]->organizeParticlesByCell();
5727 }
5728
5729 for (int i = 0; i < numPhotonSpecies; i++) {
5730 CH_assert(a_secondaryPhotons[i]->getRealm() == m_particleRealm);
5731 CH_assert(a_primaryPhotons[i]->getRealm() == m_particleRealm);
5732
5733 a_secondaryPhotons[i]->clearParticles();
5734
5735 a_secondaryPhotons[i]->organizeParticlesByCell();
5736 a_primaryPhotons[i]->organizeParticlesByCell();
5737 }
5738
5739 const RealVect probLo = m_amr->getProbLo();
5740 const RealVect probHi = m_amr->getProbHi();
5741
5742 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
5743 const DisjointBoxLayout& dbl = m_amr->getGrids(m_particleRealm)[lvl];
5744 const DataIterator& dit = dbl.dataIterator();
5745 const EBISLayout& ebisl = m_amr->getEBISLayout(m_particleRealm, m_plasmaPhase)[lvl];
5746 const ProblemDomain& domain = m_amr->getDomains()[lvl];
5747 const Box domainBox = domain.domainBox();
5748 const Real dx = m_amr->getDx()[lvl];
5749
5750 // All domain faces, and the non-periodic ones that emit. Periodic faces do not emit.
5751 std::vector<std::pair<int, Side::LoHiSide>> allFaces;
5752 std::vector<std::pair<int, Side::LoHiSide>> domainFaces;
5753
5754 for (int dir = 0; dir < SpaceDim; dir++) {
5755 for (SideIterator sit; sit.ok(); ++sit) {
5756 allFaces.emplace_back(dir, sit());
5757
5758 if (!(domain.isPeriodic(dir))) {
5759 domainFaces.emplace_back(dir, sit());
5760 }
5761 }
5762 }
5763
5764 // A primary was put just inside the domain where it crossed the boundary, so the face it crossed is the one
5765 // it lies nearest. All faces are considered, so a primary that crossed a periodic face is assigned to that face
5766 // and does not emit, rather than being credited to a non-periodic face that shares its edge or corner cell.
5767 auto crossedFace = [&](const RealVect& a_pos) -> std::pair<int, Side::LoHiSide> {
5768 std::pair<int, Side::LoHiSide> nearest = allFaces.front();
5769 Real distance = std::numeric_limits<Real>::max();
5770
5771 for (const auto& face : allFaces) {
5772 const int dir = face.first;
5773 const Real d = (face.second == Side::Lo) ? a_pos[dir] - probLo[dir] : probHi[dir] - a_pos[dir];
5774
5775 if (d < distance) {
5776 distance = d;
5777 nearest = face;
5778 }
5779 }
5780
5781 return nearest;
5782 };
5783
5784 const int nbox = dit.size();
5785
5786#pragma omp parallel for schedule(runtime)
5787 for (int mybox = 0; mybox < nbox; mybox++) {
5788 const DataIndex& din = dit[mybox];
5789 const Box box = dbl[din];
5790
5791 // The domain faces this patch touches. A patch away from the boundary has nothing to do; its secondary
5792 // containers were cleared above, which is the state it would be left in anyway.
5793 std::vector<std::pair<int, Side::LoHiSide>> patchFaces;
5794
5795 for (const auto& face : domainFaces) {
5796 const int dir = face.first;
5797 const bool touches = (face.second == Side::Lo) ? box.smallEnd(dir) == domainBox.smallEnd(dir)
5798 : box.bigEnd(dir) == domainBox.bigEnd(dir);
5799
5800 if (touches) {
5801 patchFaces.emplace_back(face);
5802 }
5803 }
5804
5805 if (patchFaces.empty()) {
5806 continue;
5807 }
5808
5809 const EBISBox& ebisbox = ebisl[din];
5810 const EBCellFAB& electricField = (*a_electricField[lvl])[din];
5811 const BaseFab<bool>& validCells = (*m_amr->getValidCells(m_particleRealm)[lvl])[din];
5812
5813 // Per-cell SoA scratch (indexed by Box::index(iv)). Primary cells are read from the SoA leaves;
5814 // secondary cells start empty and are rebuilt into the SoA leaves after the kernel.
5815 std::vector<std::vector<ParticleSoA<ItoParticle>>> primaryItoCells(numItoSpecies);
5816 std::vector<std::vector<ParticleSoA<ItoParticle>>> secondaryItoCells(numItoSpecies);
5817 std::vector<std::vector<ParticleSoA<Photon>>> primaryPhotonCells(numPhotonSpecies);
5818 std::vector<std::vector<ParticleSoA<Photon>>> secondaryPhotonCells(numPhotonSpecies);
5819
5820 for (int i = 0; i < numItoSpecies; i++) {
5821 binLeafToCells(primaryItoCells[i], (*a_primaryParticles[i])[lvl][din], box, dx, probLo);
5822 secondaryItoCells[i].resize(box.numPts());
5823 }
5824
5825 for (int i = 0; i < numPhotonSpecies; i++) {
5826 binLeafToCells(primaryPhotonCells[i], (*a_primaryPhotons[i])[lvl][din], box, dx, probLo);
5827 secondaryPhotonCells[i].resize(box.numPts());
5828 }
5829
5830 for (const auto& face : patchFaces) {
5831 const int dir = face.first;
5832 const Side::LoHiSide side = face.second;
5833
5834 // The layer of cells just inside this domain face.
5835 Box faceCells = (side == Side::Lo) ? adjCellLo(domainBox, dir, -1) : adjCellHi(domainBox, dir, -1);
5836 faceCells &= box;
5837
5838 for (BoxIterator bit(faceCells); bit.ok(); ++bit) {
5839 const IntVect iv = bit();
5840
5841 // Primaries in a covered cell, where the EB meets the domain face, are cleared without emitting.
5842 if (!validCells(iv) || ebisbox.isCovered(iv)) {
5843 continue;
5844 }
5845
5846 // A multi-valued cell gets all its primaries on its first VoF.
5847 const VolIndex vof = ebisbox.getVoFs(iv)[0];
5848 const long cellIdx = box.index(iv);
5849
5850 // The primaries in this cell that crossed this face.
5851 Vector<ParticleSoA<ItoParticle>> primaryParticles(numItoSpecies);
5852 Vector<ParticleSoA<Photon>> primaryPhotons(numPhotonSpecies);
5853 Vector<ParticleSoA<ItoParticle>> secondaryParticles(numItoSpecies);
5854 Vector<ParticleSoA<Photon>> secondaryPhotons(numPhotonSpecies);
5855
5856 auto selectCrossed = [&](auto& a_selected, const auto& a_cell) -> void {
5857 for (std::size_t j = 0; j < a_cell.size(); j++) {
5858 if (crossedFace(a_cell.position(j)) == face) {
5859 a_selected.appendParticle(a_cell, j);
5860 }
5861 }
5862 };
5863
5864 for (int i = 0; i < numItoSpecies; i++) {
5865 selectCrossed(primaryParticles[i], primaryItoCells[i][cellIdx]);
5866 }
5867
5868 for (int i = 0; i < numPhotonSpecies; i++) {
5869 selectCrossed(primaryPhotons[i], primaryPhotonCells[i][cellIdx]);
5870 }
5871
5872 const RealVect E = RealVect(D_DECL(electricField(vof, 0), electricField(vof, 1), electricField(vof, 2)));
5873 const RealVect cellCenter = probLo + Location::position(Location::Cell::Center, vof, ebisbox, dx);
5874 const RealVect cellCentroid = ebisbox.centroid(vof);
5875
5876 // The EB geometry is only passed for cells that the EB cuts.
5877 const bool isCutCell = ebisbox.isIrregular(iv);
5878 const RealVect bndryCentroid = isCutCell ? ebisbox.bndryCentroid(vof) : RealVect::Zero;
5879 const RealVect bndryNormal = isCutCell ? ebisbox.normal(vof) : RealVect::Zero;
5880
5881 // Area fraction of this cell's domain face that is open to the gas.
5882 const Vector<FaceIndex> faces = ebisbox.getFaces(vof, dir, side);
5883
5884 Real faceArea = 0.0;
5885
5886 for (int f = 0; f < faces.size(); f++) {
5887 faceArea += ebisbox.areaFrac(faces[f]);
5888 }
5889
5890 m_physics->secondaryEmissionDomain(secondaryParticles,
5891 secondaryPhotons,
5892 primaryParticles,
5893 primaryPhotons,
5894 E,
5895 cellCenter,
5896 cellCentroid,
5897 bndryCentroid,
5898 bndryNormal,
5899 dir,
5900 side,
5901 faceArea,
5902 dx,
5903 a_dt);
5904
5905 // A cell on an edge or corner is visited once per face, so the secondaries are appended.
5906 for (int i = 0; i < numItoSpecies; i++) {
5907 secondaryItoCells[i][cellIdx].append(secondaryParticles[i]);
5908 }
5909
5910 for (int i = 0; i < numPhotonSpecies; i++) {
5911 secondaryPhotonCells[i][cellIdx].append(secondaryPhotons[i]);
5912 }
5913 }
5914 }
5915
5916 // SoA write-back: rebuild the secondary Ito/photon leaves for this patch from the filled per-cell scratch.
5917 for (int i = 0; i < numItoSpecies; i++) {
5918 rebuildLeafFromCells((*a_secondaryParticles[i])[lvl][din], secondaryItoCells[i], box, dx, probLo);
5919 }
5920
5921 for (int i = 0; i < numPhotonSpecies; i++) {
5922 rebuildLeafFromCells((*a_secondaryPhotons[i])[lvl][din], secondaryPhotonCells[i], box, dx, probLo);
5923 }
5924 }
5925 }
5926
5927 // Sort by patch
5928 for (int i = 0; i < numItoSpecies; i++) {
5929 a_secondaryParticles[i]->organizeParticlesByPatch();
5930 a_primaryParticles[i]->organizeParticlesByPatch();
5931 }
5932
5933 for (int i = 0; i < numPhotonSpecies; i++) {
5934 a_secondaryPhotons[i]->organizeParticlesByPatch();
5935 a_primaryPhotons[i]->organizeParticlesByPatch();
5936 }
5937}
5938
5939template <typename I, typename C, typename R, typename F>
5940void
5942{
5943 CH_TIME("ItoKMCStepper::resolveSecondaryEmissionDomain");
5944 if (m_verbosity > 5) {
5945 pout() << m_name + "::resolveSecondaryEmissionDomain" << endl;
5946 }
5947
5948 // Add the secondary particles into the solvers and remove the primary particles.
5949 for (auto it = m_ito->iterator(); it.ok(); ++it) {
5950 const RefCountedPtr<ItoSolver>& solver = it();
5951
5952 const int idx = it.index();
5953
5954 ParticleContainer<ItoParticle>& particles = solver->getParticles(ItoSolver::WhichContainer::Bulk);
5955 particles.transferParticles(m_secondaryParticles[idx]->getParticles());
5956
5957 solver->getParticles(ItoSolver::WhichContainer::Domain).clearParticles();
5958 }
5959}
5960
5961template <typename I, typename C, typename R, typename F>
5962void
5964{
5965 CH_TIME("ItoKMCStepper::computePhysicsDt()");
5966 if (m_verbosity > 5) {
5967 pout() << m_name + "::computePhysicsDt()" << endl;
5968 }
5969
5970 Real maxDt = std::numeric_limits<Real>::max();
5971 Real minDt = std::numeric_limits<Real>::max();
5972
5973 DataOps::getMaxMin(maxDt, minDt, m_kmcDt, 0, m_amr->getMultiCutVofIterator(m_fluidRealm, m_plasmaPhase));
5974
5975 m_physicsDt = minDt;
5976}
5977
5978template <typename I, typename C, typename R, typename F>
5979void
5981{
5982 CH_TIME("ItoKMCStepper::computeDummyPhysicsDt()");
5983 if (m_verbosity > 5) {
5984 pout() << m_name + "::computeDummyPhysicsDt()" << endl;
5985 }
5986
5987 const int numItoSpecies = m_physics->getNumItoSpecies();
5988 const int numCdrSpecies = m_physics->getNumCdrSpecies();
5989 const int numPhotonSpecies = m_physics->getNumPhotonSpecies();
5990
5991 // Sort by cells
5992 (this->m_ito)->organizeParticlesByCell(ItoSolver::WhichContainer::Bulk);
5993 this->sortPhotonsByCell(McPhoto::WhichContainer::Bulk);
5994 this->sortPhotonsByCell(McPhoto::WhichContainer::Source);
5995
5996 // Compute the number of reactive particles for both Ito and CDR species. Also do a backup of the initial number
5997 // of particles per cell. This is required when reconciling the results lateron.
5998 if (numItoSpecies > 0) {
6000
6001 const Interval srcInterv(0, numItoSpecies - 1);
6002 const Interval dstInterv(0, numItoSpecies - 1);
6003
6004 m_amr->copyData(m_fluidPPC, m_particleItoPPC, dstInterv, srcInterv);
6005
6007 }
6008 if (numCdrSpecies > 0) {
6010
6011 const Interval srcInterv(0, numCdrSpecies - 1);
6012 const Interval dstInterv(numItoSpecies, numItoSpecies + numCdrSpecies - 1);
6013
6014 m_amr->copyData(m_fluidPPC, m_fluidCdrPPC, dstInterv, srcInterv);
6015
6017 }
6018
6021
6022 // Advance the reaction network using a zero time step, which should not trigger any change in the state vector.
6023 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
6024 this->advanceReactionNetwork(*m_fluidPPC[lvl], *m_fluidYPC[lvl], *m_electricFieldFluid[lvl], lvl, 0.0);
6025 }
6026
6027 // Reorganize into patch
6028 (this->m_ito)->organizeParticlesByPatch(ItoSolver::WhichContainer::Bulk);
6029 this->sortPhotonsByPatch(McPhoto::WhichContainer::Bulk);
6030 this->sortPhotonsByPatch(McPhoto::WhichContainer::Source);
6031
6032 this->computePhysicsDt();
6033}
6034
6035template <typename I, typename C, typename R, typename F>
6036Real
6038{
6039 CH_TIME("ItoKMCStepper::computeTotalCharge()");
6040 if (m_verbosity > 5) {
6041 pout() << m_name + "::computeTotalCharge()" << endl;
6042 }
6043
6044 const bool kappaScale = true;
6045
6046 Real totalCharge = 0.0;
6047
6048 totalCharge += this->computeQplus();
6049 totalCharge += this->computeQminu();
6050 totalCharge += this->computeQsurf();
6051
6052 return totalCharge;
6053}
6054
6055template <typename I, typename C, typename R, typename F>
6056Real
6058{
6059 CH_TIME("ItoKMCStepper::computeQplus()");
6060 if (m_verbosity > 5) {
6061 pout() << m_name + "::computeQplus()" << endl;
6062 }
6063
6064 const bool kappaScale = true;
6065
6066 Real totalCharge = 0.0;
6067
6068 // Charge from Ito solvers.
6069 for (auto it = m_ito->iterator(); it.ok(); ++it) {
6070 const RefCountedPtr<ItoSolver>& solver = it();
6071 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
6072
6073 const int Z = species->getChargeNumber();
6074
6075 if (Z > 0) {
6076 const ParticleContainer<ItoParticle>& particles = solver->getParticles(ItoSolver::WhichContainer::Bulk);
6077
6078 totalCharge += Z * ParticleOps::sum(particles);
6079 }
6080 }
6081
6082 // Charge from CDR solvers
6083 for (auto it = m_cdr->iterator(); it.ok(); ++it) {
6084 const RefCountedPtr<CdrSolver>& solver = it();
6085 const RefCountedPtr<CdrSpecies>& species = solver->getSpecies();
6086
6087 const int Z = species->getChargeNumber();
6088
6089 if (Z > 0) {
6090 const EBAMRCellData& phi = solver->getPhi();
6091
6092 totalCharge += Z * solver->computeMass(phi, kappaScale);
6093 }
6094 }
6095
6096 return totalCharge * Units::Qe;
6097}
6098
6099template <typename I, typename C, typename R, typename F>
6100Real
6102{
6103 CH_TIME("ItoKMCStepper::computeQminu()");
6104 if (m_verbosity > 5) {
6105 pout() << m_name + "::computeQminu()" << endl;
6106 }
6107
6108 const bool kappaScale = true;
6109
6110 Real totalCharge = 0.0;
6111
6112 // Charge from Ito solvers.
6113 for (auto it = m_ito->iterator(); it.ok(); ++it) {
6114 const RefCountedPtr<ItoSolver>& solver = it();
6115 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
6116
6117 const int Z = species->getChargeNumber();
6118
6119 if (Z < 0) {
6120 const ParticleContainer<ItoParticle>& particles = solver->getParticles(ItoSolver::WhichContainer::Bulk);
6121
6122 totalCharge += Z * ParticleOps::sum(particles);
6123 }
6124 }
6125
6126 // Charge from CDR solvers
6127 for (auto it = m_cdr->iterator(); it.ok(); ++it) {
6128 const RefCountedPtr<CdrSolver>& solver = it();
6129 const RefCountedPtr<CdrSpecies>& species = solver->getSpecies();
6130
6131 const int Z = species->getChargeNumber();
6132
6133 if (Z < 0) {
6134 const EBAMRCellData& phi = solver->getPhi();
6135
6136 totalCharge += Z * solver->computeMass(phi, kappaScale);
6137 }
6138 }
6139
6140 return totalCharge * Units::Qe;
6141}
6142
6143template <typename I, typename C, typename R, typename F>
6144Real
6146{
6147 CH_TIME("ItoKMCStepper::computeQsurf()");
6148 if (m_verbosity > 5) {
6149 pout() << m_name + "::computeQsurf()" << endl;
6150 }
6151
6152 return m_sigmaSolver->computeMass();
6153}
6154
6155template <typename I, typename C, typename R, typename F>
6156void
6158{
6159 CH_TIME("ItoKMCStepper::advancePhotons(Real)");
6160 if (m_verbosity > 5) {
6161 pout() << m_name + "::advancePhotons(Real)" << endl;
6162 }
6163
6164 // TLDR: This will add the source photons to the "bulk" photons and then advance them. If the
6165 // solver is a true transient solver then the photons are moved and some of them are eventually
6166 // absorbed on the mesh. If the solver is an "instanteneous" solver then all source photons
6167 // are absorbed on the mesh.
6168
6169 for (auto solverIt = m_rte->iterator(); solverIt.ok(); ++solverIt) {
6170 RefCountedPtr<McPhoto>& solver = solverIt();
6171
6172 // To reiterate: photons are the photons that live in the solver and are moved around. bulkPhotons
6173 // are the solvers that were absorbed on the mesh, bbPhotons are the photons that collided with the EB
6174 // and domainPhotons are photons that moved out of the domain.
6175 ParticleContainer<Photon>& photons = solver->getPhotons();
6176 ParticleContainer<Photon>& bulkPhotons = solver->getBulkPhotons();
6177 ParticleContainer<Photon>& ebPhotons = solver->getEbPhotons();
6178 ParticleContainer<Photon>& domainPhotons = solver->getDomainPhotons();
6179 ParticleContainer<Photon>& sourcePhotons = solver->getSourcePhotons();
6180
6181 solver->clear(bulkPhotons);
6182 solver->clear(ebPhotons);
6183 solver->clear(domainPhotons);
6184
6185 if (solver->isInstantaneous()) {
6186 solver->clear(photons);
6187
6188 // Add source Photons
6189 photons.transferParticles(sourcePhotons.getParticles());
6190 solver->clear(sourcePhotons);
6191
6192 // Instantaneous advance.
6193 solver->advancePhotonsInstantaneous(bulkPhotons, ebPhotons, domainPhotons, photons);
6194 }
6195 else {
6196 // Add source Photons
6197 photons.transferParticles(sourcePhotons.getParticles());
6198 solver->clear(sourcePhotons);
6199
6200 // Stationary advance
6201 solver->advancePhotonsTransient(bulkPhotons, ebPhotons, domainPhotons, photons, a_dt);
6202 }
6203 }
6204}
6205
6206template <typename I, typename C, typename R, typename F>
6207void
6209{
6210 CH_TIME("ItoKMCStepper::sortPhotonsByCell(McPhoto::WhichContainer)");
6211 if (m_verbosity > 5) {
6212 pout() << m_name + "::sortPhotonsByCell(McPhoto::WhichContainer)" << endl;
6213 }
6214
6215 for (auto solverIt = m_rte->iterator(); solverIt.ok(); ++solverIt) {
6216 solverIt()->sortPhotonsByCell(a_which);
6217 }
6218}
6219
6220template <typename I, typename C, typename R, typename F>
6221void
6223{
6224 CH_TIME("ItoKMCStepper::sortPhotonsByPatch(McPhoto::WhichContainer)");
6225 if (m_verbosity > 5) {
6226 pout() << m_name + "::sortPhotonsByPatch(McPhoto::WhichContainer)" << endl;
6227 }
6228
6229 for (auto solverIt = m_rte->iterator(); solverIt.ok(); ++solverIt) {
6230 solverIt()->sortPhotonsByPatch(a_which);
6231 }
6232}
6233
6234template <typename I, typename C, typename R, typename F>
6235Vector<RefCountedPtr<ItoSolver>>
6237{
6238 CH_TIME("ItoKMCStepper::getLoadBalanceSolvers()");
6239 if (m_verbosity > 5) {
6240 pout() << m_name + "::getLoadBalanceSolvers()" << endl;
6241 }
6242
6243 Vector<RefCountedPtr<ItoSolver>> lbSolvers;
6244
6245 // If there's an index < 0 we load balance everything.
6246 bool loadBalanceAll = false;
6247 for (int i = 0; i < m_loadBalanceIndices.size(); i++) {
6248 if (m_loadBalanceIndices[i] < 0) {
6249 loadBalanceAll = true;
6250 }
6251 }
6252
6253 if (loadBalanceAll) {
6254 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
6255 lbSolvers.push_back(solverIt());
6256 }
6257 }
6258 else {
6259 for (int i = 0; i < m_loadBalanceIndices.size(); i++) {
6260 RefCountedPtr<ItoSolver>& solver = m_ito->getSolvers()[i];
6261
6262 lbSolvers.push_back(solver);
6263 }
6264 }
6265
6266 return lbSolvers;
6267}
6268
6269template <typename I, typename C, typename R, typename F>
6270bool
6272{
6273 CH_TIME("TimeStepper::loadBalanceThisRealm");
6274 if (m_verbosity > 5) {
6275 pout() << "TimeStepper::loadBalanceThisRealm" << endl;
6276 }
6277
6278 bool ret = false;
6279
6280 if (a_realm == m_particleRealm && m_loadBalanceParticles) {
6281 ret = true;
6282 }
6283 else if (a_realm == m_fluidRealm && m_loadBalanceFluid) {
6284 ret = true;
6285 }
6286
6287 return ret;
6288}
6289
6290template <typename I, typename C, typename R, typename F>
6291void
6293 Vector<Vector<Box>>& a_boxes,
6294 const std::string& a_realm,
6295 const Vector<DisjointBoxLayout>& a_grids,
6296 const int a_lmin,
6297 const int a_finestLevel)
6298{
6299 CH_TIME("ItoKMCStepper::loadBalanceBoxes");
6300 if (m_verbosity > 5) {
6301 pout() << m_name + "::loadBalanceBoxes" << endl;
6302 }
6303
6304 if (m_loadBalanceParticles && a_realm == m_particleRealm) {
6305 this->loadBalanceParticleRealm(a_procs, a_boxes, a_realm, a_grids, a_lmin, a_finestLevel);
6306 }
6307 else if (m_loadBalanceFluid && a_realm == m_fluidRealm) {
6308 this->loadBalanceFluidRealm(a_procs, a_boxes, a_realm, a_grids, a_lmin, a_finestLevel);
6309 }
6310}
6311
6312template <typename I, typename C, typename R, typename F>
6313void
6315 Vector<Vector<Box>>& a_boxes,
6316 const std::string a_realm,
6317 const Vector<DisjointBoxLayout>& a_grids,
6318 const int a_lmin,
6319 const int a_finestLevel) noexcept
6320{
6321 CH_TIME("ItoKMCStepper::loadBalanceParticleRealm(...)");
6322 if (m_verbosity > 5) {
6323 pout() << m_name + "::loadBalanceParticleRealm(...)" << endl;
6324 }
6325
6326 // TLDR: This is a bit involved due to the fact that the simulation lives in a state between the old grids
6327 // and the new grids. We want to compute the number of computational in patch on the new grid, and
6328 // use that for load balancing. We have already computed the number of computational particles per
6329 // grid cell on the old grids, but the new grids are not ready (yet). We only have the proxy-grids
6330 // coming in through the argument (a_grids), and our job is to take this grid and reassign the patches
6331 // so that each MPI rank gets roughly the same number of computational particles. To do this we perform
6332 // the following steps:
6333 //
6334 // 1. Allocate storage on the proxy grids (a_grids) so we have something to regrid into.
6335 // 2. Define regrid operators for going between the proxy grids and the old grids.
6336 // 3. Regrid the PPC on the old grids onto the proxy grids.
6337 // 4. Go through the patches on the proxy grids and figure out the total number of particles
6338 // in each patch (there's a weird global-to-local remapping taking place through intCode()).
6339 // 5. Call our nifty load-balancing routines.
6340 //
6341
6343 MayDay::Error("ItoKMCStepper::loadBalanceParticleRealm -- logic bust, should not have been called!");
6344 }
6345
6346 // Get the solvers that we will use for load balancing.
6347 Vector<RefCountedPtr<ItoSolver>> lbSolvers = this->getLoadBalanceSolvers();
6348
6349 // Decompose the DisjointBoxLayout
6350 a_procs.resize(1 + a_finestLevel);
6351 a_boxes.resize(1 + a_finestLevel);
6352
6353 for (int lvl = a_lmin; lvl <= a_finestLevel; lvl++) {
6354 a_procs[lvl] = a_grids[lvl].procIDs();
6355 a_boxes[lvl] = a_grids[lvl].boxArray();
6356 }
6357
6358 // 1. Allocate something that we can regrid the PPC for each species into, and something that holds the total
6359 // PPC on the new grids.
6360 EBAMRCellData totalPPC;
6361 EBAMRCellData speciesPPC;
6362
6363 m_amr->allocate(totalPPC, m_particleRealm, m_plasmaPhase, 1);
6364 m_amr->allocate(speciesPPC, m_particleRealm, m_plasmaPhase, 1);
6365
6366 DataOps::setValue(totalPPC, 0.0);
6367 DataOps::setValue(speciesPPC, 0.0);
6368
6369 // 2. EBCoarseToFineInterp is not a part of the registry for ItoSolver so we just define it here ourselves. Note that
6370 // it is stored on the same level that we interpolate to.
6371 Vector<RefCountedPtr<EBCoarseToFineInterp>> interpOp(1 + a_finestLevel);
6372 for (int lvl = 1; lvl <= a_finestLevel; lvl++) {
6373 const EBLevelGrid& eblgFine = *m_amr->getEBLevelGrid(m_particleRealm, m_plasmaPhase)[lvl];
6374 const EBLevelGrid& eblgCoFi = *m_amr->getEBLevelGridCoFi(m_particleRealm, m_plasmaPhase)[lvl - 1];
6375 const EBLevelGrid& eblgCoar = *m_amr->getEBLevelGrid(m_particleRealm, m_plasmaPhase)[lvl - 1];
6376 const int refRat = m_amr->getRefinementRatios()[lvl - 1];
6377
6378 interpOp[lvl] = RefCountedPtr<EBCoarseToFineInterp>(new EBCoarseToFineInterp(eblgFine, eblgCoFi, eblgCoar, refRat));
6379 }
6380
6381 // 3. Go through each solver and figure out the number of particles on the new grids. Add
6382 // these to totalPPC.
6383 for (int i = 0; i < lbSolvers.size(); i++) {
6384 const EBAMRCellData& oldData = m_loadBalancePPC[i];
6385 const int oldFinestLevel = oldData.size() - 1;
6386
6387 // These levels have not changed but ownship MIGHT have changed.
6388 for (int lvl = 0; lvl <= std::max(0, a_lmin - 1); lvl++) {
6389 oldData[lvl]->copyTo(*speciesPPC[lvl]);
6390 }
6391
6392 // These levels have changed.
6393 for (int lvl = std::max(1, a_lmin); lvl <= a_finestLevel; lvl++) {
6394 RefCountedPtr<EBCoarseToFineInterp>& interpolator = interpOp[lvl];
6395
6396 interpolator->interpolate(*speciesPPC[lvl],
6397 *speciesPPC[lvl - 1],
6398 Interval(0, 0),
6399 EBCoarseToFineInterp::Type::ConservativePWC);
6400
6401 // There could be parts of the new grid that overlapped with the old grid (on level lvl) -- we don't want
6402 // to pollute the solution with interpolation there since we already have valid data.
6403 if (lvl <= std::min(oldFinestLevel, a_finestLevel)) {
6404 oldData[lvl]->copyTo(*speciesPPC[lvl]);
6405 }
6406 }
6407
6408 // Add to totalPPC.
6409 DataOps::incr(totalPPC, speciesPPC, 1.0);
6410 }
6411
6412 // 4. totalPPC contains the total number of computational particles per cell on the new grids,
6413 // we need to map this to something we can load balance.
6414 Vector<Vector<long int>> loads(1 + a_finestLevel, 0L);
6415 for (int lvl = 0; lvl <= a_finestLevel; lvl++) {
6416 const DisjointBoxLayout& dbl = a_grids[lvl];
6417 const DataIterator& dit = dbl.dataIterator();
6418
6419 Vector<long int>& levelLoads = loads[lvl];
6420
6421 levelLoads.resize(dbl.size());
6422
6423 const int nbox = dit.size();
6424
6425#pragma omp parallel for schedule(runtime)
6426 for (int mybox = 0; mybox < nbox; mybox++) {
6427 const DataIndex& din = dit[mybox];
6428
6429 const Box cellBox = dbl[din];
6430 const EBCellFAB& PPC = (*totalPPC[lvl])[din];
6431 const EBISBox& ebisbox = PPC.getEBISBox();
6432 const BaseFab<bool>& validCells = (*m_amr->getValidCells(m_particleRealm)[lvl])[din];
6433 const FArrayBox& regPPC = PPC.getFArrayBox();
6434
6435 auto regularKernel = [&](const IntVect& iv) -> void {
6436 if (validCells(iv, 0) && ebisbox.isRegular(iv)) {
6437 levelLoads[din.intCode()] += (long int)regPPC(iv, 0);
6438 }
6439 };
6440
6441 BoxLoops::loop<D_DECL(1, 1, 1)>(cellBox, regularKernel);
6442 }
6443
6444 ParallelOps::sum(levelLoads);
6445
6446 // Add the "constant" load from the other PPC stuff
6447 for (LayoutIterator lit = dbl.layoutIterator(); lit.ok(); ++lit) {
6448 const Box cellBox = dbl[lit()];
6449
6450 levelLoads[lit().intCode()] += (long int)m_loadPerCell * cellBox.numPts();
6451 }
6452 }
6453
6454 // 5. Finally do the actual load balancing.
6455 LoadBalancing::sort(a_boxes, loads, m_boxSort);
6456
6457 Loads rankLoads;
6458 rankLoads.resetLoads();
6459
6460 for (int lvl = 0; lvl <= a_finestLevel; lvl++) {
6461 LoadBalancing::makeBalance(a_procs[lvl], rankLoads, loads[lvl], a_boxes[lvl]);
6462 }
6463}
6464
6465template <typename I, typename C, typename R, typename F>
6466void
6468 Vector<Vector<Box>>& a_boxes,
6469 const std::string a_realm,
6470 const Vector<DisjointBoxLayout>& a_grids,
6471 const int a_lmin,
6472 const int a_finestLevel) noexcept
6473{
6474 CH_TIME("ItoKMCStepper::loadBalanceFluidRealm(...)");
6475 if (m_verbosity > 5) {
6476 pout() << m_name + "::loadBalanceFluidRealm(...)" << endl;
6477 }
6478
6479 CH_assert(m_loadBalanceFluid);
6480 CH_assert(a_realm == m_fluidRealm);
6481
6482 // clang-format off
6483 // TLDR: This code tries to compute a load for each grid patch by applying a relaxation operator to each box. This means that the load
6484 // should be a decent estimate that takes into account boundary conditions, coarse-fine interface arithmetic, and enlargened stencils
6485 // near the embedded boundary.
6486 // clang-format on
6487
6488 a_procs.resize(1 + a_finestLevel);
6489 a_boxes.resize(1 + a_finestLevel);
6490
6491 // We need to make AmrMesh restore some operators that we need in order to create a multigrid object. Fortunately,
6492 // FieldSolver has routines for doing that but it will not know if AmrMesh has updated it's operators or not. So, we
6493 // need to regrid them.
6494 m_amr->regridOperators(m_fluidRealm, a_lmin);
6495
6496 // Field solver needs to allocate solver and set up the multigrid solver.
6497 m_fieldSolver->allocate();
6498 m_fieldSolver->setupSolver();
6499
6500 // Loads on each rank
6501 Loads rankLoads;
6502 rankLoads.resetLoads();
6503
6504 // Field solver implementation gets the responsibility of computing loads on each level.
6505 for (int lvl = 0; lvl <= a_finestLevel; lvl++) {
6506 Vector<long long> boxLoads = m_fieldSolver->computeLoads(a_grids[lvl], lvl);
6507
6508 // Do the desired sorting and load balancing
6509 a_boxes[lvl] = a_grids[lvl].boxArray();
6510
6511 LoadBalancing::sort(a_boxes[lvl], boxLoads, m_boxSort);
6512 LoadBalancing::makeBalance(a_procs[lvl], rankLoads, boxLoads, a_boxes[lvl]);
6513 }
6514}
6515
6516template <typename I, typename C, typename R, typename F>
6517Vector<long int>
6518ItoKMCStepper<I, C, R, F>::getCheckpointLoads(const std::string& a_realm, const int a_level) const
6519{
6520 CH_TIME("ItoKMCStepper::getCheckpointLoads(...)");
6521 if (m_verbosity > 5) {
6522 pout() << m_name + "::getCheckpointLoads(...)" << endl;
6523 }
6524
6525 const DisjointBoxLayout& dbl = m_amr->getGrids(a_realm)[a_level];
6526 const int nbox = dbl.size();
6527
6528 Vector<long int> loads(nbox, 0L);
6529
6530 if (m_loadBalanceParticles && a_realm == m_particleRealm) {
6531
6532 // If we're load balancing with particles, get the number of particles per patch
6533 // from the relevant particle solvers. Since these are Ito solvers, the loads
6534 // are equal to the number of computational particles in the grid patches.
6535 Vector<RefCountedPtr<ItoSolver>> loadBalanceProxySolvers = this->getLoadBalanceSolvers();
6536
6537 for (int isolver = 0; isolver < loadBalanceProxySolvers.size(); isolver++) {
6538
6539 // This solver computes loads -- there's a parallel gather operation
6540 // under the hood here.
6541 Vector<long int> solverLoads(nbox, 0L);
6542 loadBalanceProxySolvers[isolver]->computeLoads(solverLoads, dbl, a_level);
6543
6544 // Add to total loads.
6545 for (int ibox = 0; ibox < nbox; ibox++) {
6546 loads[ibox] += solverLoads[ibox];
6547 }
6548 }
6549
6550 // Add the "constant" loads -- these are computational loads due to the "mesh" part. We use
6551 // a heuristic where we have m_loadPerCell "cost".
6552 for (LayoutIterator lit = dbl.layoutIterator(); lit.ok(); ++lit) {
6553 const Box box = dbl[lit()];
6554
6555 loads[lit().intCode()] += lround(m_loadPerCell * box.numPts());
6556 }
6557 }
6558 else {
6559 loads = TimeStepper::getCheckpointLoads(a_realm, a_level);
6560 }
6561
6562 return loads;
6563}
6564
6565template <typename I, typename C, typename R, typename F>
6566void
6568{
6569 CH_TIME("ItoKMCStepper::computeEdotJSource(a_dt)");
6570 if (m_verbosity > 5) {
6571 pout() << m_name + "::computeEdotJSource(a_dt)" << endl;
6572 }
6573
6574 CH_assert(a_dt > 0.0);
6575
6577
6578 CH_assert(m_EdotJ.getRealm() == m_fluidRealm);
6579
6580 // clang-format off
6581 // TLDR: EdotJ is an energy term for the various species, i.e. it is the rate of energy increase as the particle moves from
6582 // position A to position B, excluding friction from collision with other molecules. We compute this energy increase as
6583 //
6584 // q * V(B) - V(A)
6585 //
6586 // which means that the energy rate is q*(V(B) - V(A))/a_dt.
6587 //
6588 // We simply assign this factor to the particles and then deposit them on the mesh. However, this is more complex than
6589 // it sounds because the particles m_EdotJ live on different realms. The way we do this is that we copy the potential
6590 // over into the particle realm and we interpolate V(B) and V(A) onto some storage in the particle container. We then
6591 // assign an effective weight w * [V(B) - V(A)] to the particles which we deposit onto the mesh using the appropriate
6592 // deposition scheme that the user has assgned.
6593 //
6594 // clang-format on
6595
6596 // Allocate a transient SoA particle holder. The container owns the weight and position; the payload holds
6597 // V(A), V(B), and the per-component "other" position (alt) so we can interpolate the potential at both A and B.
6598 ParticleContainer<ItoKMCFieldParticle> computationParticles;
6599 m_amr->allocate(computationParticles, m_particleRealm);
6600
6601 // Electrostatic potential on appropriate phase. This is defined on the fluid realm
6602 // but we need it on the particle realm.
6603 const EBAMRCellData potentialPhase = m_amr->alias(m_plasmaPhase, m_fieldSolver->getPotential());
6604
6605 for (auto solverIt = m_ito->iterator(); solverIt.ok(); ++solverIt) {
6606 RefCountedPtr<ItoSolver>& solver = solverIt();
6607 const RefCountedPtr<ItoSpecies>& species = solver->getSpecies();
6608
6609 const int idx = solverIt.index();
6610 const int Z = species->getChargeNumber();
6611 const bool mobile = solver->isMobile();
6612 const bool diffusive = solver->isDiffusive();
6613
6614 if (Z != 0 && (mobile || diffusive)) {
6615
6616 // The potential is copied into the scratch for every species, since the deposit below overwrites it.
6617 m_amr->copyData(m_particleScratch1, potentialPhase);
6618
6619 m_amr->conservativeAverage(m_particleScratch1, m_particleRealm, m_plasmaPhase);
6621
6622 const ParticleContainer<ItoParticle>& particles = solver->getParticles(ItoSolver::WhichContainer::Bulk);
6623
6624 // Copy the ItoParticles to the transient particles we use for computing these things. The container
6625 // position holds B (the current position); the payload "alt" columns hold A (the old position).
6626 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
6627 const DisjointBoxLayout& dbl = m_amr->getGrids(m_particleRealm)[lvl];
6628 const DataIterator& dit = dbl.dataIterator();
6629
6630 const int nbox = dit.size();
6631
6632#pragma omp parallel for schedule(runtime)
6633 for (int mybox = 0; mybox < nbox; mybox++) {
6634 const DataIndex& din = dit[mybox];
6635
6636 ParticleSoA<ItoKMCFieldParticle>& comp = computationParticles[lvl][din];
6637 const ParticleSoA<ItoParticle>& leaf = particles[lvl][din];
6638
6639 for (std::size_t i = 0; i < leaf.size(); i++) {
6640 const RealVect posA = RealVect(D_DECL(leaf.template get<&ItoParticle::old_x>(i),
6641 leaf.template get<&ItoParticle::old_y>(i),
6642 leaf.template get<&ItoParticle::old_z>(i)));
6643
6644 // No cast to ParticleReal: x0 is a position and stays double, so casting would round the
6645 // old position through float whenever PARTICLE_PRECISION=FLOAT. This one compiles either
6646 // way, which is why it survived where the pointer bindings below did not.
6647 ItoKMCFieldParticle payload;
6648 D_DECL(payload.x0_x = posA[0], payload.x0_y = posA[1], payload.x0_z = posA[2]);
6649
6650 comp.append(leaf.position(i), leaf.weight(i), payload);
6651 }
6652 }
6653 }
6654
6655 // Interpolate the potential to the current particle position which gives us V(B) for the particles.
6656 m_amr->interpolateParticles<&ItoKMCFieldParticle::phiB>(computationParticles,
6660 solver->getDeposition(),
6661 false);
6662
6663 // Move the particles back to their old positions (A) and interpolate the potential there. The container
6664 // position and the payload "alt" position are swapped so position now holds A and alt holds B.
6665 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
6666 const DisjointBoxLayout& dbl = m_amr->getGrids(m_particleRealm)[lvl];
6667 const DataIterator& dit = dbl.dataIterator();
6668
6669 const int nbox = dit.size();
6670
6671#pragma omp parallel for schedule(runtime)
6672 for (int mybox = 0; mybox < nbox; mybox++) {
6673 const DataIndex& din = dit[mybox];
6674
6675 ParticleSoA<ItoKMCFieldParticle>& comp = computationParticles[lvl][din];
6676
6677 double* const pos[SpaceDim] = {
6678 D_DECL(comp.positionColumn(0), comp.positionColumn(1), comp.positionColumn(2))};
6679 // double rather than ParticleReal: x0 is a position, and positions are double at every
6680 // PARTICLE_PRECISION setting -- see ItoKMCFieldParticle. Typing these as ParticleReal
6681 // compiles only while the payload precision happens to be double.
6682 double* const alt[SpaceDim] = {D_DECL(comp.template column<&ItoKMCFieldParticle::x0_x>(),
6683 comp.template column<&ItoKMCFieldParticle::x0_y>(),
6684 comp.template column<&ItoKMCFieldParticle::x0_z>())};
6685
6686 ParticleLoops::loop(comp, [&](const std::size_t i) {
6687 for (int dir = 0; dir < SpaceDim; dir++) {
6688 const double posB = pos[dir][i];
6689 pos[dir][i] = alt[dir][i];
6690 alt[dir][i] = posB;
6691 }
6692 });
6693 }
6694 }
6695
6696 computationParticles.remap();
6697
6698 // Interpolate the potential to the previous particle position which gives us V(A) for the particles.
6699 m_amr->interpolateParticles<&ItoKMCFieldParticle::phiA>(computationParticles,
6703 solver->getDeposition(),
6704 false);
6705
6706 // Move the particles back to B again and multiply the weight by (V(B) - V(A)).
6707 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
6708 const DisjointBoxLayout& dbl = m_amr->getGrids(m_particleRealm)[lvl];
6709 const DataIterator& dit = dbl.dataIterator();
6710
6711 const int nbox = dit.size();
6712
6713#pragma omp parallel for schedule(runtime)
6714 for (int mybox = 0; mybox < nbox; mybox++) {
6715 const DataIndex& din = dit[mybox];
6716
6717 ParticleSoA<ItoKMCFieldParticle>& comp = computationParticles[lvl][din];
6718
6719 double* const pos[SpaceDim] = {
6720 D_DECL(comp.positionColumn(0), comp.positionColumn(1), comp.positionColumn(2))};
6721 // See the swap above: x0 is a position, hence double rather than ParticleReal.
6722 const double* const alt[SpaceDim] = {D_DECL(comp.template column<&ItoKMCFieldParticle::x0_x>(),
6723 comp.template column<&ItoKMCFieldParticle::x0_y>(),
6724 comp.template column<&ItoKMCFieldParticle::x0_z>())};
6725 double* const w = comp.weightColumn();
6726 const ParticleReal* const phiA = comp.template column<&ItoKMCFieldParticle::phiA>();
6727 const ParticleReal* const phiB = comp.template column<&ItoKMCFieldParticle::phiB>();
6728
6729 ParticleLoops::loop(comp, [&](const std::size_t i) {
6730 for (int dir = 0; dir < SpaceDim; dir++) {
6731 pos[dir][i] = alt[dir][i];
6732 }
6733
6734 // Effective weight = weight * (V(B) - V(A)).
6735 w[i] *= (phiB[i] - phiA[i]);
6736 });
6737 }
6738 }
6739
6740 computationParticles.remap();
6741
6742 // Deposit the effective (energy-weighted) weight.
6743 m_amr->depositWeight(m_particleScratch1,
6746 computationParticles,
6747 solver->getDeposition(),
6748 solver->getCoarseFineDeposition(),
6750
6751 // Copy data back onto the fluid realm.
6755 }
6756
6757 computationParticles.clearParticles();
6758 }
6759}
6760
6761template <typename I, typename C, typename R, typename F>
6762void
6763ItoKMCStepper<I, C, R, F>::computePhysicsPlotVariables(EBAMRCellData& a_physicsPlotVars) noexcept
6764{
6765 CH_TIME("ItoKMCStepper::computePhysicsPlotVariables");
6766 if (m_verbosity > 5) {
6767 pout() << m_name + "::computePhysicsPlotVariables" << endl;
6768 }
6769
6770 // Number of output variables from CdrPlasmaPhysics
6771 const int numVars = m_physics->getNumberOfPlotVariables();
6772 const int numItoSpecies = m_physics->getNumItoSpecies();
6773 const int numCdrSpecies = m_physics->getNumCdrSpecies();
6774 const int numPlasmaSpecies = m_physics->getNumPlasmaSpecies();
6775 const int numPhotonSpecies = m_physics->getNumPhotonSpecies();
6776
6777 CH_assert(!(a_physicsPlotVars[0].isNull()));
6778 CH_assert(a_physicsPlotVars[0]->nComp() == numVars);
6779 CH_assert(a_physicsPlotVars.getRealm() == m_fluidRealm);
6780
6781 // Update gradients
6783
6784 const RealVect probLo = m_amr->getProbLo();
6785
6786 for (int lvl = 0; lvl <= m_amr->getFinestLevel(); lvl++) {
6787 const DisjointBoxLayout& dbl = m_amr->getGrids(m_fluidRealm)[lvl];
6788 const DataIterator& dit = dbl.dataIterator();
6789 const EBISLayout& ebisl = m_amr->getEBISLayout(m_fluidRealm, m_plasmaPhase)[lvl];
6790 const Real dx = m_amr->getDx()[lvl];
6791
6792 const int nbox = dit.size();
6793
6794#pragma omp parallel for schedule(runtime)
6795 for (int mybox = 0; mybox < nbox; mybox++) {
6796 const DataIndex& din = dit[mybox];
6797
6798 const Box& cellBox = dbl[din];
6799 const EBISBox& ebisBox = ebisl[din];
6800
6801 // Handle to electric field
6802 const EBCellFAB& electricField = (*m_electricFieldFluid[lvl])[din];
6803 const FArrayBox& electricFieldReg = electricField.getFArrayBox();
6804
6805 // Handle to densities and density gradients for CDR and Ito species.
6806 Vector<const EBCellFAB*> densitiesIto(numItoSpecies);
6807 Vector<const EBCellFAB*> densityGradientsIto(numItoSpecies);
6808 Vector<const FArrayBox*> densitiesItoReg(numItoSpecies);
6809 Vector<const FArrayBox*> densityGradientsItoReg(numItoSpecies);
6810
6811 Vector<const EBCellFAB*> densitiesCDR(numCdrSpecies);
6812 Vector<const EBCellFAB*> densityGradientsCDR(numCdrSpecies);
6813 Vector<const FArrayBox*> densitiesCDRReg(numCdrSpecies);
6814 Vector<const FArrayBox*> densityGradientsCDRReg(numCdrSpecies);
6815
6816 for (auto it = m_ito->iterator(); it.ok(); ++it) {
6817 const RefCountedPtr<ItoSolver>& solver = it();
6818
6819 const int i = it.index();
6820
6821 densitiesIto[i] = &(*(m_fluidPhiIto[i])[lvl])[din];
6822 densitiesItoReg[i] = &(densitiesIto[i]->getFArrayBox());
6823 densityGradientsIto[i] = &(*m_fluidGradPhiIto[i][lvl])[din];
6824 densityGradientsItoReg[i] = &(densityGradientsIto[i]->getFArrayBox());
6825 }
6826
6827 for (auto it = m_cdr->iterator(); it.ok(); ++it) {
6828 const RefCountedPtr<CdrSolver>& solver = it();
6829 const EBAMRCellData& phi = solver->getPhi();
6830
6831 const int i = it.index();
6832
6833 densitiesCDR[i] = &(*phi[lvl])[din];
6834 densitiesCDRReg[i] = &(densitiesCDR[i]->getFArrayBox());
6835 densityGradientsCDR[i] = &(*m_fluidGradPhiCDR[i][lvl])[din];
6836 densityGradientsCDRReg[i] = &(densityGradientsCDR[i]->getFArrayBox());
6837 }
6838
6839 // Handle to valid grid cells.
6840 const BaseFab<bool>& validCells = (*m_amr->getValidCells(m_fluidRealm)[lvl])[din];
6841
6842 // Handle to output variables
6843 EBCellFAB& physicsPlotVars = (*a_physicsPlotVars[lvl])[din];
6844 FArrayBox& physicsPlotVarsReg = physicsPlotVars.getFArrayBox();
6845
6846 // Things that will be populated in the kernels.
6847 Vector<Real> densities(numPlasmaSpecies);
6848 Vector<RealVect> densityGradients(numPlasmaSpecies);
6849
6850 // Regular cells
6851 auto regularKernel = [&](const IntVect& iv) -> void {
6852 if (ebisBox.isRegular(iv) && validCells(iv, 0)) {
6853 const RealVect pos = probLo + dx * (RealVect(iv) + 0.5 * RealVect::Unit);
6854 const RealVect E = RealVect(
6855 D_DECL(electricFieldReg(iv, 0), electricFieldReg(iv, 1), electricFieldReg(iv, 2)));
6856
6857 // Populate gradients.
6858 for (int i = 0; i < numItoSpecies; i++) {
6859 densities[i] = (*densitiesItoReg[i])(iv, 0);
6860 densityGradients[i] = RealVect(D_DECL((*densityGradientsItoReg[i])(iv, 0),
6861 (*densityGradientsItoReg[i])(iv, 1),
6862 (*densityGradientsItoReg[i])(iv, 2)));
6863 }
6864
6865 for (int i = 0; i < numCdrSpecies; i++) {
6866 densities[numItoSpecies + i] = (*densitiesCDRReg[i])(iv, 0);
6867 densityGradients[numItoSpecies + i] = RealVect(D_DECL((*densityGradientsCDRReg[i])(iv, 0),
6868 (*densityGradientsCDRReg[i])(iv, 1),
6869 (*densityGradientsCDRReg[i])(iv, 2)));
6870 }
6871
6872 // Do the physics advance.
6873 const Vector<Real> plotVars = m_physics->getPlotVariables(E, pos, densities, densityGradients, dx, 1.0);
6874
6875 CH_assert(plotVars.size() == numVars);
6876
6877 for (int i = 0; i < numVars; i++) {
6878 physicsPlotVarsReg(iv, i) = plotVars[i];
6879 }
6880 }
6881 };
6882
6883 // Irregular cells
6884 auto irregularKernel = [&](const VolIndex& vof) -> void {
6885 if (validCells(vof.gridIndex(), 0)) {
6886 const RealVect pos = probLo + dx * (RealVect(vof.gridIndex()) + 0.5 * RealVect::Unit);
6887 const RealVect E = RealVect(D_DECL(electricField(vof, 0), electricField(vof, 1), electricField(vof, 2)));
6888
6889 // Populate gradients.
6890 for (int i = 0; i < numItoSpecies; i++) {
6891 densities[i] = (*densitiesIto[i])(vof, 0);
6892 densityGradients[i] = RealVect(D_DECL((*densityGradientsIto[i])(vof, 0),
6893 (*densityGradientsIto[i])(vof, 1),
6894 (*densityGradientsIto[i])(vof, 2)));
6895 }
6896
6897 for (int i = 0; i < numCdrSpecies; i++) {
6898 densities[numItoSpecies + i] = (*densitiesCDR[i])(vof, 0);
6899 densityGradients[numItoSpecies + i] = RealVect(D_DECL((*densityGradientsCDR[i])(vof, 0),
6900 (*densityGradientsCDR[i])(vof, 1),
6901 (*densityGradientsCDR[i])(vof, 2)));
6902 }
6903
6904 // Do the physics advance.
6905 const Vector<Real> plotVars = m_physics->getPlotVariables(E, pos, densities, densityGradients, dx, 1.0);
6906
6907 CH_assert(plotVars.size() == numVars);
6908
6909 for (int i = 0; i < numVars; i++) {
6910 physicsPlotVars(vof, i) = plotVars[i];
6911 }
6912 }
6913 };
6914
6915 // Run the kernels.
6916 VoFIterator& vofit = (*m_amr->getVofIterator(m_fluidRealm, m_plasmaPhase)[lvl])[din];
6917
6918 BoxLoops::loop<D_DECL(1, 1, 1)>(cellBox, regularKernel);
6919 BoxLoops::loop(vofit, irregularKernel);
6920 }
6921 }
6922
6923 m_amr->average(a_physicsPlotVars, m_fluidRealm, m_plasmaPhase, Average::Arithmetic, Interval(0, numVars - 1));
6924 m_amr->interpGhost(a_physicsPlotVars, m_fluidRealm, m_plasmaPhase);
6925}
6926
6927#include <CD_NamespaceFooter.H>
6928
6929#endif
Average
Various averaging methods.
Definition CD_Average.H:25
Agglomeration of useful data operations.
Declaration of an aggregated class for regrid operations.
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
@ Native
Deposit as-is, with no cut-cell treatment at all.
Definition CD_IrregularDeposition.H:41
@ NGP
Put the particle's entire cloud in its own cell when that cell is a cut cell.
Definition CD_IrregularDeposition.H:48
SoA payload for the transient E-dot-J energy computation in ItoKMCStepper.
SpeciesType
Tag for distinguishing species solved with an Ito diffusion or CDR fluid formalism.
Definition CD_ItoKMCPhysics.H:76
@ CDR
Convection-diffusion-reaction (fluid) solver.
Definition CD_ItoKMCPhysics.H:78
@ Ito
Ito stochastic drift-diffusion solver.
Definition CD_ItoKMCPhysics.H:77
Declaration of the Physics::ItoKMC::ItoKMCStepper abstract TimeStepper.
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
Declaration of cell positions.
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
Implementation of CD_Timer.H.
Declaration of various useful units.
Factory class for CdrLayout. T is (usually) CdrSolver and S is the implementation class (e....
Definition CD_CdrLayout.H:316
RefCountedPtr< CdrLayout< T > > newLayout(const Vector< RefCountedPtr< CdrSpecies > > &a_species) const
Factory method, create a new CdrLayout.
Definition CD_CdrLayoutImplem.H:547
Iterator class for CdrLayout. This allows iteration through solvers (or subsets of solvers).
Definition CD_CdrIterator.H:29
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 getMaxMin(Real &max, Real &min, EBAMRCellData &a_data, const int a_comp, const Vector< RefCountedPtr< LayoutData< VoFIterator > > > &a_vofIter)
Get maximum and minimum value of specified component.
Definition CD_DataOps.cpp:1772
static void volumeScale(EBAMRCellData &a_data, const Vector< Real > &a_dx)
Scale data by dx^SpaceDim.
Definition CD_DataOps.cpp:2297
static void getMaxMinNorm(Real &a_max, Real &a_min, EBAMRCellData &data, const Vector< RefCountedPtr< LayoutData< VoFIterator > > > &a_vofIter)
Get maximum and minimum value of normed data.
Definition CD_DataOps.cpp:1940
static void roof(EBAMRCellData &a_lhs, const Real a_value, const Vector< RefCountedPtr< LayoutData< VoFIterator > > > &a_vofIter)
Roof values in data holder. This sets all values above a_value to a_value.
Definition CD_DataOps.cpp:1617
static void computeMinValidBox(RealVect &a_lo, RealVect &a_hi, const RealVect &a_normal, const RealVect &a_centroid)
Compute the tightest possible valid box around a cut-cell volume.
Definition CD_DataOps.cpp:3748
static void vectorLength(EBAMRCellData &a_lhs, const EBAMRCellData &a_rhs, const EBAMRCellData &a_notCovered, const Vector< RefCountedPtr< LayoutData< VoFIterator > > > &a_vofIter)
Compute the vector length of a data holder. Sets a_lhs = |a_rhs| where a_rhs contains SpaceDim compon...
Definition CD_DataOps.cpp:3561
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 divideFallback(EBAMRCellData &a_numerator, const EBAMRCellData &a_denominator, const Real a_fallback, const Vector< RefCountedPtr< LayoutData< VoFIterator > > > &a_vofIter)
Divide data. If the denominator is zero, set the value to a fallback option.
Definition CD_DataOps.cpp:1448
static void setCoveredValue(EBAMRCellData &a_lhs, const EBAMRCellData &a_coveredMask, const int a_comp, const Real a_value)
Set value in covered cells. Does specified component.
Definition CD_DataOps.cpp:2716
static void plus(EBAMRCellData &a_lhs, const EBAMRCellData &a_rhs, const int a_srcComp, const int a_dstComp, const int a_numComp)
General addition operator for adding together data. The user can choose which components to add.
Definition CD_DataOps.cpp:946
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
static void multiplyScalar(EBAMRCellData &a_lhs, const EBAMRCellData &a_rhs)
Multiply data holder by another data holder.
Definition CD_DataOps.cpp:2402
Class for interpolating data to fine grids. Can use constant interpolation or include limiters.
Definition CD_EBCoarseToFineInterp.H:33
Factory class for making ItoLayout.
Definition CD_ItoLayout.H:412
RefCountedPtr< ItoLayout< T > > newLayout(const Vector< RefCountedPtr< ItoSpecies > > &a_species) const
Factory method which creates a new layout from a set of species. This can do automated casting betwee...
Definition CD_ItoLayoutImplem.H:438
"Iterator" class for going through solvers in an ItoLayout.
Definition CD_ItoIterator.H:26
WhichContainer
Enum class for distinguishing various types of particle containers.
Definition CD_ItoSolver.H:52
static void makeBalance(Vector< int > &a_ranks, const Vector< T > &a_loads, const Vector< Box > &a_boxes)
Load balancing, assigning ranks to boxes.
Definition CD_LoadBalancingImplem.H:36
static void sort(Vector< Vector< Box > > &a_boxes, Vector< Vector< T > > &a_loads, const BoxSorting a_whichSorting)
Sorts boxes and loads over a hierarchy according to some sorting criterion.
Definition CD_LoadBalancingImplem.H:227
Class for holding computational loads.
Definition CD_Loads.H:31
virtual void resetLoads() noexcept
Reset loads. Sets all loads to 0.
Definition CD_Loads.cpp:55
WhichContainer
Enum class for identifying various containers. Only used for interface reasons.
Definition CD_McPhoto.H:43
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
void transferParticles(AMRParticlesSoA< P, Traits > &a_source)
Move all particles from another holder (on the same valid grids) into the valid holder.
Definition CD_ParticleContainer.H:810
AMRParticlesSoA< P, Traits > & getParticles()
The valid particles on all levels.
Definition CD_ParticleContainer.H:322
static Real sum(const ParticleContainer< P, Traits > &a_particles) noexcept
Global sum of the container-owned weight column (SoA overload).
Definition CD_ParticleOpsImplem.H:302
static void getComputationalParticlesPerCell(EBAMRCellData &a_ppc, const ParticleContainer< P, Traits > &a_src) noexcept
Get the number of computational particles per cell (SoA overload).
Definition CD_ParticleOpsImplem.H:85
static void getPhysicalParticlesPerCell(EBAMRCellData &a_ppc, const ParticleContainer< P, Traits > &a_src) noexcept
Get the number of physical particles per cell (SoA overload).
Definition CD_ParticleOpsImplem.H:53
Arena-backed Struct-of-Arrays particle container for a single grid patch.
Definition CD_ParticleSoA.H:655
void sortByCell(const Box &a_box, const RealVect &a_dx, const RealVect &a_probLo)
Counting-sort the columns into Fortran cell order and build CSR cell offsets.
Definition CD_ParticleSoAImplem.H:303
void append(const RealVect &a_position, const double a_weight)
Append one particle with a default-constructed payload.
Definition CD_ParticleSoA.H:962
double * weightColumn() noexcept
Raw weight column (double*).
Definition CD_ParticleSoA.H:1167
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
std::pair< std::size_t, std::size_t > cellRange(const std::size_t a_cell) const noexcept
Half-open particle index range [begin, end) owned by cell c (valid after sortByCell).
Definition CD_ParticleSoA.H:1546
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
Abstract TimeStepper for the Ito-KMC-Poisson system of equations.
Definition CD_ItoKMCStepper.H:66
virtual void transferCoveredParticles(const SpeciesSubset a_speciesSubset, const EBRepresentation a_representation, const Real a_tolerance) noexcept
Transfer covered particles (i.e., particles inside the EB) from the ItoSolver bulk container to EB co...
Definition CD_ItoKMCStepperImplem.H:2604
virtual void setupCdr() noexcept
Set up the CDR solvers.
Definition CD_ItoKMCStepperImplem.H:530
EBAMRCellData m_particleCdrProduction
Per-cell CDR production from the reaction network, on the particle realm.
Definition CD_ItoKMCStepper.H:694
Vector< RefCountedPtr< ParticleContainer< NoPayload > > > m_cdrProducts
Reaction products to be put in the CDR equations, as particles.
Definition CD_ItoKMCStepper.H:686
virtual void resolveSecondaryEmissionDomain() noexcept
Resolve secondary emission on the domain boundary.
Definition CD_ItoKMCStepperImplem.H:5941
virtual void getParticleStatistics(Real &a_avgParticles, Real &a_sigma, Real &a_minParticles, Real &a_maxParticles, int &a_minRank, int &a_maxRank)
Compute some particle statistics.
Definition CD_ItoKMCStepperImplem.H:1490
RefCountedPtr< SurfaceODESolver< 1 > > m_sigmaSolver
Definition CD_ItoKMCStepper.H:439
virtual void computePhysicsPlotVariables(EBAMRCellData &a_physicsPlotVars) noexcept
Compute physics plot variables.
Definition CD_ItoKMCStepperImplem.H:6763
Vector< EBAMRCellData > m_fluidPhiIto
For holding the Ito species densities on the fluid realm.
Definition CD_ItoKMCStepper.H:677
virtual void computePhysicsDt() noexcept
Compute a physics-based maximum time step.
Definition CD_ItoKMCStepperImplem.H:5963
virtual void computeReactiveMeanEnergiesPerCell(EBAMRCellData &a_meanEnergies) noexcept
Compute the mean particle energy in all grid cells.
Definition CD_ItoKMCStepperImplem.H:3893
EBAMRCellData m_conductivityCell
Cell-centered conductivity.
Definition CD_ItoKMCStepper.H:721
EBAMRCellData m_particleOldItoPPC
For holding the previous number of particles per cell for all species.
Definition CD_ItoKMCStepper.H:757
Real m_particleAdvectionDt
The particle advective time step.
Definition CD_ItoKMCStepper.H:619
Vector< EBAMRIVData > m_cdrFluxes
CDR fluxes for CDR BCs.
Definition CD_ItoKMCStepper.H:460
virtual void parseRuntimeOptions() noexcept override
Parse runtime configurable options.
Definition CD_ItoKMCStepperImplem.H:173
phase::which_phase m_plasmaPhase
Definition CD_ItoKMCStepper.H:408
EBAMRCellData m_neutralDensity
Storage for the neutral density.
Definition CD_ItoKMCStepper.H:715
virtual void computeElectricField(EBAMRCellData &a_electricField, const phase::which_phase a_phase) const noexcept
Recompute the electric field onto the specified data holder.
Definition CD_ItoKMCStepperImplem.H:1978
virtual void removeCoveredParticles(const SpeciesSubset a_which, const EBRepresentation a_representation, const Real a_tolerance) noexcept
Remove covered particles (i.e., particles inside the EB).
Definition CD_ItoKMCStepperImplem.H:2485
BoxSorting m_boxSort
Box sorting method when using dual-grid with particle load balancing.
Definition CD_ItoKMCStepper.H:381
virtual void setupRadiativeTransfer() noexcept
Set up the radiative transfer solver.
Definition CD_ItoKMCStepperImplem.H:549
EBAMRCellData m_electricFieldParticle
Storage for holding the plasma phase electric field on the particle realm.
Definition CD_ItoKMCStepper.H:791
virtual void registerRealms() noexcept override
Register realms used for the simulation.
Definition CD_ItoKMCStepperImplem.H:1637
virtual void loadBalanceBoxes(Vector< Vector< int > > &a_procs, Vector< Vector< Box > > &a_boxes, const std::string &a_realm, const Vector< DisjointBoxLayout > &a_grids, const int a_lmin, const int a_finestLevel) override
Load balance grid boxes for a specified realm.
Definition CD_ItoKMCStepperImplem.H:6292
virtual Vector< RefCountedPtr< ItoSolver > > getLoadBalanceSolvers() const noexcept
Definition CD_ItoKMCStepperImplem.H:6236
virtual void computeSpaceChargeDensity() noexcept
Compute the space charge. Calls the other version.
Definition CD_ItoKMCStepperImplem.H:2005
virtual void fillNeutralDensity() noexcept
Compute the neutral density on the mesh.
Definition CD_ItoKMCStepperImplem.H:1880
virtual void setVoltage(const std::function< Real(const Real a_time)> &a_voltage) noexcept
Set voltage used for the simulation.
Definition CD_ItoKMCStepperImplem.H:1868
virtual void advanceReactionNetwork(const Real a_dt) noexcept
Chemistry advance over time a_dt.
Definition CD_ItoKMCStepperImplem.H:4034
virtual Real getTime() const noexcept
Get current simulation time.
Definition CD_ItoKMCStepperImplem.H:1993
virtual Vector< long int > getCheckpointLoads(const std::string &a_realm, const int a_level) const override
Get computational loads to be checkpointed.
Definition CD_ItoKMCStepperImplem.H:6518
virtual void computeDummyPhysicsDt() noexcept
Special routine which performs a dummy KMC advance over a zero time step.
Definition CD_ItoKMCStepperImplem.H:5980
void reconcileParticles(const EBAMRCellData &a_newParticlesPerCell, const EBAMRCellData &a_oldParticlesPerCell, const EBAMRCellData &a_newPhotonsPerCell, const EBAMRCellData &a_cdrProduction, const EBAMRCellData &a_electricField) const noexcept
Reconcile particles. At the bottom, this will call the physics interface for particle reconciliation.
Definition CD_ItoKMCStepperImplem.H:4503
virtual int getNumberOfPlotVariables() const noexcept override
Get number of plot variables for the output file.
Definition CD_ItoKMCStepperImplem.H:989
virtual void fillSecondaryEmissionDomain(const Real a_dt) noexcept
Compute secondary emission on the domain boundary.
Definition CD_ItoKMCStepperImplem.H:5664
virtual void remapParticles(const SpeciesSubset a_speciesSubset) noexcept
Remap a subset of ItoSolver particles.
Definition CD_ItoKMCStepperImplem.H:2728
virtual void parseVerbosity() noexcept
Parse chattiness.
Definition CD_ItoKMCStepperImplem.H:201
virtual void computeReactiveCdrParticlesPerCell(EBAMRCellData &a_ppc) noexcept
Compute the number of reactive particles per cell for the CDR solvers.
Definition CD_ItoKMCStepperImplem.H:3786
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
Scratch storage on the particle realm with 1 component.
Definition CD_ItoKMCStepper.H:824
EBAMRCellData m_EdotJ
Storage for E·J (Ohmic heating) on the fluid realm. 1 component.
Definition CD_ItoKMCStepper.H:809
virtual void loadBalanceParticleRealm(Vector< Vector< int > > &a_procs, Vector< Vector< Box > > &a_boxes, const std::string a_realm, const Vector< DisjointBoxLayout > &a_grids, const int a_lmin, const int a_finestLevel) noexcept
Routine called by loadBalanceBoxes and used for particle-based load balancing.
Definition CD_ItoKMCStepperImplem.H:6314
Vector< RefCountedPtr< ParticleContainer< ItoParticle > > > m_secondaryParticles
List of secondary particles injected through the EB.
Definition CD_ItoKMCStepper.H:446
virtual void averageDiffusionCoefficientsCellToFace() noexcept
Average cell-centered diffusion coefficient to faces.
Definition CD_ItoKMCStepperImplem.H:3596
virtual void parsePlotVariables() noexcept
Parse plot variables.
Definition CD_ItoKMCStepperImplem.H:272
virtual void parseSuperParticles() noexcept
Parse the super-particle merge cadence.
Definition CD_ItoKMCStepperImplem.H:308
virtual void writeData(LevelData< EBCellFAB > &a_output, int &a_comp, const EBAMRCellData &a_data, const std::string a_outputRealm, const int a_level, const bool a_interpToCentroids, const bool a_interpGhost) const noexcept
Write data to output. Convenience function.
Definition CD_ItoKMCStepperImplem.H:1147
virtual void computeDensityGradients() noexcept
Compute grad(phi) and phi for both CDR and Ito species and put the result on the fluid realm.
Definition CD_ItoKMCStepperImplem.H:2144
virtual void computeEdotJSource(const Real a_dt) noexcept
Compute the energy source term for the various plasma species.
Definition CD_ItoKMCStepperImplem.H:6567
virtual void parseCdrProducts() noexcept
Parse how the reaction network's CDR production reaches the mesh.
Definition CD_ItoKMCStepperImplem.H:244
EBAMRCellData m_particleItoPPC
For holding the number of physical particles per cell for all Ito species.
Definition CD_ItoKMCStepper.H:739
virtual bool solvePoisson() noexcept
Solve the electrostatic problem.
Definition CD_ItoKMCStepperImplem.H:2261
virtual Real computeQminu() const noexcept
Compute negative charge.
Definition CD_ItoKMCStepperImplem.H:6101
virtual void multiplyCdrVelocitiesByMobilities() noexcept
Multiply CDR solver velocities by mobilities.
Definition CD_ItoKMCStepperImplem.H:3023
virtual void parseRedistributeCDR() noexcept
Parse CDR mass redistribution when assigning reactive products.
Definition CD_ItoKMCStepperImplem.H:230
virtual void computeCurrentDensity(EBAMRCellData &a_J) noexcept
Compute the current density.
Definition CD_ItoKMCStepperImplem.H:2207
Real m_toleranceEB
Accepted tolerance (relative to dx) for EB intersection.
Definition CD_ItoKMCStepper.H:563
virtual void writeNumberOfParticlesPerPatch(LevelData< EBCellFAB > &a_output, int &a_icomp, const std::string a_outputRealm, const int a_level) const noexcept
Write number of particles per patch to output holder.
Definition CD_ItoKMCStepperImplem.H:1214
EBAMRCellData m_fluidScratchD
Scratch storage on the fluid realm with SpaceDim components.
Definition CD_ItoKMCStepper.H:819
bool m_loadBalanceFluid
Load balance fluid realm or not.
Definition CD_ItoKMCStepper.H:510
virtual void parseTimeStepRestrictions() noexcept
Parse time step restrictions.
Definition CD_ItoKMCStepperImplem.H:401
EBAMRIVData m_particleScratchEB
Scratch storage for EB-only data on the particle realm. One component.
Definition CD_ItoKMCStepper.H:839
virtual void fillSecondaryEmissionEB(const Real a_dt) noexcept
Resolve particle injection at EBs.
Definition CD_ItoKMCStepperImplem.H:5176
EBAMRCellData m_particleYPC
For holding the number of generated photons per cell.
Definition CD_ItoKMCStepper.H:745
virtual void initialSigma() noexcept
Fill surface charge solver with initial data taken from the physics interface.
Definition CD_ItoKMCStepperImplem.H:800
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
Intersect a subset of the particles with the domain and embedded boundary.
Definition CD_ItoKMCStepperImplem.H:2300
ItoKMCStepper() noexcept
Default constructor. Sets default options.
Definition CD_ItoKMCStepperImplem.H:98
EBAMRCellData m_currentDensity
Storage for current density.
Definition CD_ItoKMCStepper.H:705
virtual void printStepReport() noexcept override
Print a step report. Used by Driver for user monitoring of simulation.
Definition CD_ItoKMCStepperImplem.H:1278
virtual void depositParticles(const SpeciesSubset a_speciesSubset) noexcept
Deposit a subset of the ItoSolver particles on the mesh.
Definition CD_ItoKMCStepperImplem.H:2843
Vector< EBAMRCellData > m_cdrMobilities
For holding the mobilities for the CDR species.
Definition CD_ItoKMCStepper.H:660
virtual void setupSigma() noexcept
Set up the surface charge solver.
Definition CD_ItoKMCStepperImplem.H:586
Vector< EBAMRCellData > m_loadBalancePPC
Definition CD_ItoKMCStepper.H:654
CdrProductInjection m_cdrProductInjection
Definition CD_ItoKMCStepper.H:490
virtual void setupSolvers() noexcept override
Set up solvers.
Definition CD_ItoKMCStepperImplem.H:495
EBAMRCellData m_fluidPPC
For holding the number of particles per cell for all species.
Definition CD_ItoKMCStepper.H:775
virtual void parseOptions() noexcept
Parse options.
Definition CD_ItoKMCStepperImplem.H:152
virtual void advancePhotons(const Real a_dt) noexcept
Photon advancement routine.
Definition CD_ItoKMCStepperImplem.H:6157
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
virtual void depositCdrProducts(EBAMRCellData &a_cdrChange) noexcept
Deposit the CDR reaction products in m_cdrProducts and add the result to a per-cell change.
Definition CD_ItoKMCStepperImplem.H:4179
EBAMRIVData m_fluidScratchEB
Scratch storage for EB-only data on the fluid realm. One component.
Definition CD_ItoKMCStepper.H:834
virtual void parseDualGrid() noexcept
Parse dual or single realm calculations.
Definition CD_ItoKMCStepperImplem.H:325
Vector< EBAMRCellData > m_fluidScratchIto
Per-Ito-species scratch storage on the fluid realm, one component each.
Definition CD_ItoKMCStepper.H:849
virtual void reconcilePhotoionization() noexcept
Reconcile the results from photoionization reactions.
Definition CD_ItoKMCStepperImplem.H:4909
EBAMRCellData m_fluidScratch1
Scratch storage on the fluid realm having 1 component.
Definition CD_ItoKMCStepper.H:814
virtual void loadBalanceFluidRealm(Vector< Vector< int > > &a_procs, Vector< Vector< Box > > &a_boxes, const std::string a_realm, const Vector< DisjointBoxLayout > &a_grids, const int a_lmin, const int a_finestLevel) noexcept
Routine called by loadBalanceBoxes and used for particle-based load balancing.
Definition CD_ItoKMCStepperImplem.H:6467
EBAMRCellData m_fluidOldCdrPPC
For holding the previous number of physical particles per cell for all CDR species.
Definition CD_ItoKMCStepper.H:769
EBAMRCellData m_kmcDt
Storage for the non-critical time step computed by ItoKMCPhysics.
Definition CD_ItoKMCStepper.H:798
virtual Vector< std::string > getPlotVariableNames() const noexcept override
Get plot variable names.
Definition CD_ItoKMCStepperImplem.H:1042
virtual void sortPhotonsByCell(const McPhoto::WhichContainer a_which) noexcept
Sort photons by cells.
Definition CD_ItoKMCStepperImplem.H:6208
virtual Real computeQplus() const noexcept
Compute positive charge.
Definition CD_ItoKMCStepperImplem.H:6057
virtual void parseLoadBalance() noexcept
Parse load balancing.
Definition CD_ItoKMCStepperImplem.H:348
virtual void computeDriftVelocities() noexcept
Compute ItoSolver velocities.
Definition CD_ItoKMCStepperImplem.H:3049
EBAMRCellData m_electricFieldFluid
Storage for holding the plasma phase electric field on the fluid realm.
Definition CD_ItoKMCStepper.H:786
EBAMRCellData m_particleScratchD
Scratch storage on the particle realm with SpaceDim components.
Definition CD_ItoKMCStepper.H:829
Vector< EBAMRCellData > m_fluidGradPhiCDR
For holding the gradient of all CDR species densities.
Definition CD_ItoKMCStepper.H:666
virtual void setupPoisson() noexcept
Set up the electrostatic field solver.
Definition CD_ItoKMCStepperImplem.H:569
RefCountedPtr< CdrLayout< CdrSolver > > m_cdr
Definition CD_ItoKMCStepper.H:424
virtual void setupIto() noexcept
Set up the Ito particle solvers.
Definition CD_ItoKMCStepperImplem.H:511
virtual Real computeQsurf() const noexcept
Compute surface charge.
Definition CD_ItoKMCStepperImplem.H:6145
virtual Real computeDt() override
Compute a time step used for the advance method.
Definition CD_ItoKMCStepperImplem.H:1522
virtual void synchronizeSolverTimes(const int a_step, const Real a_time, const Real a_dt) noexcept override
Synchronize solver times for all the solvers.
Definition CD_ItoKMCStepperImplem.H:1259
virtual Real computeTotalCharge() const noexcept
Compute total charge.
Definition CD_ItoKMCStepperImplem.H:6037
virtual void resolveSecondaryEmissionEB(const Real a_dt) noexcept
Resolve secondary emission at the EB.
Definition CD_ItoKMCStepperImplem.H:5480
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_ItoKMCStepperImplem.H:1813
virtual void coarsenCDRSolvers(const bool a_interpGhosts) noexcept
Coarsen data for CDR solvers.
Definition CD_ItoKMCStepperImplem.H:5110
EBAMRCellData m_fluidCdrPPC
For holding the number of physical particles per cell for all CDR species.
Definition CD_ItoKMCStepper.H:763
EBAMRFluxData m_conductivityFace
Face-centered conductivity.
Definition CD_ItoKMCStepper.H:727
virtual void computeDiffusionCoefficients() noexcept
Compute mesh-based diffusion coefficients for LFA coupling.
Definition CD_ItoKMCStepperImplem.H:3307
virtual void allocateInternals() noexcept
Allocate "internal" storage.
Definition CD_ItoKMCStepperImplem.H:621
virtual bool loadBalanceThisRealm(const std::string &a_realm) const override
Load balancing query for a specified realm. If this returns true for a_realm, load balancing routines...
Definition CD_ItoKMCStepperImplem.H:6271
virtual Real computeMaxReducedElectricField(const phase::which_phase a_phase) const noexcept
Compute the maximum electric field (norm).
Definition CD_ItoKMCStepperImplem.H:1937
EBAMRIVData m_conductivityEB
EB-centered conductivity.
Definition CD_ItoKMCStepper.H:733
Vector< EBAMRIVData > m_cdrFluxesExtrap
Extrapolated CDR fluxes.
Definition CD_ItoKMCStepper.H:465
virtual void setCdrVelocityFunctions() noexcept
Set the Cdr velocities to be sgn(charge) * E.
Definition CD_ItoKMCStepperImplem.H:2989
virtual void postRegrid() noexcept override
Perform post-regrid operations.
Definition CD_ItoKMCStepperImplem.H:1855
virtual Real computeRelaxationTime() noexcept
Definition CD_ItoKMCStepperImplem.H:2226
virtual void parseParametersEB() noexcept
Parse parameters related to how we treat particle-EB interaction.
Definition CD_ItoKMCStepperImplem.H:479
virtual void initialData() noexcept override
Fill solvers with initial data.
Definition CD_ItoKMCStepperImplem.H:763
virtual void postPlot() noexcept override
Perform post-plot operations.
Definition CD_ItoKMCStepperImplem.H:1691
virtual ~ItoKMCStepper() noexcept
Destructor.
Definition CD_ItoKMCStepperImplem.H:145
RefCountedPtr< ItoKMCPhysics > m_physics
Implementation of ItoKMCPhysics.
Definition CD_ItoKMCStepper.H:414
virtual void getMaxMinRelativeItoDensity(Real &a_maxDensity, Real &a_minDensity, std::string &a_maxSolver, std::string &a_minSolver) const noexcept
Definition CD_ItoKMCStepperImplem.H:1395
virtual void computeReactiveItoParticlesPerCell(EBAMRCellData &a_ppc) noexcept
Compute the number of reactive particles per cell.
Definition CD_ItoKMCStepperImplem.H:3662
virtual bool needSecondaryEmissionEB() const noexcept
Whether anything can be emitted from the EB this step, answered globally.
Definition CD_ItoKMCStepperImplem.H:5140
virtual bool needSecondaryEmissionDomain() const noexcept
Whether anything can be emitted from the domain boundary this step, answered globally.
Definition CD_ItoKMCStepperImplem.H:5636
EBAMRCellData m_fluidYPC
For holding the number of generated photons per cell.
Definition CD_ItoKMCStepper.H:781
virtual void allocate() noexcept override
Allocate storage for solvers.
Definition CD_ItoKMCStepperImplem.H:603
RefCountedPtr< RtLayout< McPhoto > > m_rte
Definition CD_ItoKMCStepper.H:429
virtual void parseExitOnFailure() noexcept
Parse exit on failure.
Definition CD_ItoKMCStepperImplem.H:216
RefCountedPtr< ItoLayout< ItoSolver > > m_ito
Definition CD_ItoKMCStepper.H:419
Vector< int > m_loadBalanceIndices
Solver indices used when load-balancing the particle solvers.
Definition CD_ItoKMCStepper.H:699
std::function< Real(const Real a_time)> m_voltage
Voltage curve on the electrodes used in the simulation.
Definition CD_ItoKMCStepper.H:470
virtual void computeConductivityCell(EBAMRCellData &a_conductivity) noexcept
Compute the cell-centered conductiivty.
Definition CD_ItoKMCStepperImplem.H:2076
virtual void postCheckpointPoisson() noexcept
Definition CD_ItoKMCStepperImplem.H:872
virtual void reconcileCdrDensities(const EBAMRCellData &a_cdrChange, const Real a_dt) noexcept
Reconcile the CDR densities after the reaction network.
Definition CD_ItoKMCStepperImplem.H:4967
virtual void prePlot() noexcept override
Perform pre-plot operations.
Definition CD_ItoKMCStepperImplem.H:1670
virtual void postInitialize() noexcept override
Post-initialization operations. Default does nothing.
Definition CD_ItoKMCStepperImplem.H:753
@ Particle
Emit the production as particles and deposit it with the Ito solvers' deposition.
Definition CD_ItoKMCStepper.H:375
@ Mesh
Add the production directly into the cell that produced it.
Definition CD_ItoKMCStepper.H:367
virtual void postCheckpointSetup() noexcept override
Perform post-checkpoint operations.
Definition CD_ItoKMCStepperImplem.H:849
Vector< RefCountedPtr< ParticleContainer< Photon > > > m_secondaryPhotons
List of secondary photons injected through the EB.
Definition CD_ItoKMCStepper.H:453
Real m_particleDiffusionDt
The particle diffusive time step.
Definition CD_ItoKMCStepper.H:624
virtual void getMaxMinRelativeCDRDensity(Real &a_maxDensity, Real &a_minDensity, std::string &a_maxSolver, std::string &a_minSolver) const noexcept
Definition CD_ItoKMCStepperImplem.H:1443
virtual void writePlotData(LevelData< EBCellFAB > &a_output, int &a_icomp, const std::string &a_outputRealm, const int a_level) const noexcept override
Write plot data to output holder.
Definition CD_ItoKMCStepperImplem.H:1093
virtual void computeMobilities() noexcept
Compute mesh-based mobilities for LFA coupling.
Definition CD_ItoKMCStepperImplem.H:3074
virtual void setItoVelocityFunctions() noexcept
Set the Ito velocity functions. This is sgn(charge) * E.
Definition CD_ItoKMCStepperImplem.H:2958
Vector< EBAMRCellData > m_fluidGradPhiIto
For holding the gradient of all Ito species densities.
Definition CD_ItoKMCStepper.H:672
bool m_loadBalanceParticles
Load balance particle realm or not.
Definition CD_ItoKMCStepper.H:505
virtual void sortPhotonsByPatch(const McPhoto::WhichContainer a_which) noexcept
Sort photons by patch.
Definition CD_ItoKMCStepperImplem.H:6222
virtual void getPhysicalParticlesPerCell(EBAMRCellData &a_ppc) const noexcept
Get the physical number of particles per cell.
Definition CD_ItoKMCStepperImplem.H:3640
static const std::string Primal
Identifier for perimal realm.
Definition CD_Realm.H:44
Factory class for RtLayout.
Definition CD_RtLayout.H:278
RefCountedPtr< RtLayout< T > > newLayout(const Vector< RefCountedPtr< RtSpecies > > &a_species) const
Get a new Layout. This will cast S to a specific class (T).
Definition CD_RtLayoutImplem.H:458
Iterator class for RtLayout.
Definition CD_RtIterator.H:25
virtual bool ok()
Check if we can cycle further through the solvers.
Definition CD_RtIteratorImplem.H:65
Surface ODE solver.
Definition CD_SurfaceODESolver.H:29
Real m_time
TIme.
Definition CD_TimeStepper.H:353
int m_verbosity
Class verbosity.
Definition CD_TimeStepper.H:343
virtual Vector< long int > getCheckpointLoads(const std::string &a_realm, int a_level) const
Get computational loads to be checkpointed.
Definition CD_TimeStepper.cpp:78
RefCountedPtr< ComputationalGeometry > m_computationalGeometry
Computational geometry.
Definition CD_TimeStepper.H:375
int m_timeStep
Time step.
Definition CD_TimeStepper.H:348
Real m_dt
Previous time step size.
Definition CD_TimeStepper.H:358
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 startEvent(const std::string &a_event) noexcept
Start an event.
Definition CD_TimerImplem.H:60
void eventReport(std::ostream &a_outputStream, const bool a_localReportOnly=false) const noexcept
Print all timed events to cout.
Definition CD_TimerImplem.H:170
void stopEvent(const std::string &a_event) noexcept
Stop an event.
Definition CD_TimerImplem.H:89
ALWAYS_INLINE void loop(const Box &a_computeBox, Functor &&kernel)
Launch a C++ kernel over a regular grid with compile-time per-dimension strides.
Definition CD_BoxLoopsImplem.H:39
std::string numberFmt(long long n, char a_sep=',') noexcept
Number formatting method – writes big numbers using an input separator. E.g. the number 123456 is wri...
Definition CD_DischargeIO.cpp:37
RealVect position(Location::Cell a_location, const VolIndex &a_vof, const EBISBox &a_ebisbox, const Real &a_dx)
Compute the position (ignoring the "origin) of a Vof.
Definition CD_LocationImplem.H:21
std::pair< Real, int > maxRank(const Real &a_val) noexcept
Get the maximum value and the rank having the maximum value.
Definition CD_ParallelOpsImplem.H:294
Real average(const Real &a_val) noexcept
Compute the average (across MPI ranks) of the input value.
Definition CD_ParallelOpsImplem.H:521
Real standardDeviation(const Real &a_value) noexcept
Compute the standard deviation of the input value.
Definition CD_ParallelOpsImplem.H:533
std::pair< Real, int > minRank(const Real &a_val) noexcept
Get the minimum value and the rank having the minimum value.
Definition CD_ParallelOpsImplem.H:324
Real sum(const Real &a_value) noexcept
Compute the sum across all MPI ranks.
Definition CD_ParallelOpsImplem.H:354
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
constexpr Real eps0
Permittivity of free space.
Definition CD_Units.H:30
constexpr Real Qe
Elementary charge.
Definition CD_Units.H:35
constexpr Real c
Speed of light.
Definition CD_Units.H:40
which_phase
Enumeration of supported phases.
Definition CD_MultiFluidIndexSpace.H:38
@ gas
Gas phase.
Definition CD_MultiFluidIndexSpace.H:39
SoA payload for the transient particles used by ItoKMCStepper::computeEdotJSource.
Definition CD_ItoKMCFieldParticle.H:29
ParticleReal phiA
Electrostatic potential at position A.
Definition CD_ItoKMCFieldParticle.H:30
ParticleReal phiB
Electrostatic potential at position B.
Definition CD_ItoKMCFieldParticle.H:31
double x0_z
Alternate (other) position, z-component (double: position-like).
Definition CD_ItoKMCFieldParticle.H:36
double x0_y
Alternate (other) position, y-component (double: position-like).
Definition CD_ItoKMCFieldParticle.H:34
double x0_x
Alternate (other) position, x-component (double: position-like).
Definition CD_ItoKMCFieldParticle.H:33