flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
flow_ibm_core.hpp
Go to the documentation of this file.
1
9#ifndef PECLET_FLOW_FLOW_IBM_CORE_HPP
10#define PECLET_FLOW_FLOW_IBM_CORE_HPP
11
12namespace peclet::flow {
13
14template <class Grid>
15Solver<Grid>::Solver(int nx, int ny, int nz) {
17}
18
19template <class Grid>
21 SceneMap m;
22 if (!u_.physical)
23 return m;
24 for (int a = 0; a < 3; ++a) {
25 m.a[a] = u_.org[a] + 0.5 * u_.h[a];
26 m.b[a] = u_.h[a];
27 m.velToInt[a] = u_.velToInt(a);
28 }
29 m.dToInt = u_.lenToInt();
30 m.angToInt = u_.angVelToInt();
31 return m;
32}
33
34template <class Grid>
35Solver<Grid>::Solver(int nx, int ny, int nz, const std::array<double, 3>& extent,
36 const std::array<double, 3>& origin, const std::array<long, 3>& globalCells) {
38 setPhysicalDomain(extent, origin, globalCells);
39}
40
41template <class Grid>
42void Solver<Grid>::setPhysicalDomain(const std::array<double, 3>& extent,
43 const std::array<double, 3>& origin,
44 const std::array<long, 3>& globalCells) {
45 const long c[3] = {globalCells[0] > 0 ? globalCells[0] : nx_,
46 globalCells[1] > 0 ? globalCells[1] : ny_,
47 globalCells[2] > 0 ? globalCells[2] : nz_};
48 for (int a = 0; a < 3; ++a) {
49 if (!(extent[a] > 0.0))
50 throw std::runtime_error("physical domain: every extent component must be > 0");
51 if (c[a] <= 0)
52 throw std::runtime_error("physical domain: every cell count must be > 0");
53 }
54 double hh[3];
55 for (int a = 0; a < 3; ++a)
56 hh[a] = extent[a] / (double)c[a];
57 // Phase 2 C2 — THE SNAP (doc/anisotropic_metric.md §1.4). Phase 1 refused any extent whose
58 // three spacings differed; this replaces the throw. If the three agree to 1e-12 relative the
59 // spacings are SNAPPED to h_0 on every axis, so the metric is EXACTLY the identity
60 // (hp = w = (1,1,1), vol = 1, aniso = false) — that exactness is what keeps every operator
61 // fold of C1/C2 bit-identical and what keeps `units_scale_invariance` on literally Phase 1's
62 // arithmetic, whose per-axis extents N_a*H can differ by an ulp across axes (trap 2).
63 // Otherwise the cells really are anisotropic: hRef = min_a h_a, and h_a' comes from the STORED
64 // doubles (trap 1 — never extent/(cells*hRef); h_a' is exactly 1.0 only on the finest axis).
65 // What that admits is §7 / `requireIsotropic` below; Phase 3 then admitted the VoF
66 // entry points too, so nothing in the solver refuses an anisotropic domain today.
67 bool iso = true;
68 for (int a = 1; a < 3; ++a)
69 if (std::fabs(hh[a] - hh[0]) > 1e-12 * std::fabs(hh[0]))
70 iso = false;
71 if (iso)
72 for (int a = 1; a < 3; ++a)
73 hh[a] = hh[0];
74 u_.physical = true;
75 for (int a = 0; a < 3; ++a) {
76 u_.h[a] = hh[a];
77 u_.ext[a] = extent[a];
78 u_.org[a] = origin[a];
79 u_.cells[a] = c[a];
80 }
81 u_.hRef = std::min(hh[0], std::min(hh[1], hh[2]));
82 for (int a = 0; a < 3; ++a) {
83 u_.hp[a] = iso ? 1.0 : u_.h[a] / u_.hRef;
84 u_.w[a] = iso ? 1.0 : 1.0 / (u_.hp[a] * u_.hp[a]);
85 }
86 u_.vol = iso ? 1.0 : u_.hp[0] * u_.hp[1] * u_.hp[2];
87 u_.aniso = !iso;
88 // rhoRef / tRef are pinned by the first set_rho / set_dt; whatever was set BEFORE the domain
89 // (nothing, in the documented order) is re-derived here.
91 // Phase 2 commit C4 LIFTED the collocated refusal that stood here: the embedded closures
92 // (`fvViscousApply`, `embedViscousApply` / `embedDirichletGradient`) now march along the
93 // anisotropic index-space normal `m` of doc/anisotropic_metric.md §6.1 and carry the per-axis
94 // `w_a` on their face and wall terms, `starCorrectFaces` carries the same `w_a` its
95 // `projectCorrect` fix-up needs, and the V8 face integral weights its pressure difference.
96 // `enable_vof` kept its own refusal here until PHASE 3 lifted it (see enableVof).
97}
98
99template <class Grid>
100void Solver<Grid>::requireIsotropic(const char* what) const {
101 if (!u_.aniso)
102 return;
103 char msg[520];
104 std::snprintf(msg, sizeof msg,
105 "%s: this entry point requires ISOTROPIC cells, but extent/cells gives "
106 "dx=%.17g dy=%.17g dz=%.17g (hRef=%.17g, h'=(%.17g, %.17g, %.17g)).",
107 what, u_.h[0], u_.h[1], u_.h[2], u_.hRef, u_.hp[0], u_.hp[1], u_.hp[2]);
108 throw std::runtime_error(msg);
109}
110
111template <class Grid>
113 return u_.physical;
114}
115
116template <class Grid>
118 return u_;
119}
120
121template <class Grid>
122std::array<double, 3> Solver<Grid>::spacing() const {
123 return {u_.h[0], u_.h[1], u_.h[2]};
124}
125
126template <class Grid>
127std::array<double, 3> Solver<Grid>::domainOrigin() const {
128 return {u_.org[0], u_.org[1], u_.org[2]};
129}
130
131template <class Grid>
132std::array<double, 3> Solver<Grid>::domainExtent() const {
133 if (u_.physical)
134 return {u_.ext[0], u_.ext[1], u_.ext[2]};
135 std::array<long, 3> gc = globalCells();
136 return {(double)gc[0], (double)gc[1], (double)gc[2]};
137}
138
139template <class Grid>
140std::array<long, 3> Solver<Grid>::globalCells() const {
141 if (u_.physical && u_.cells[0] > 0)
142 return {u_.cells[0], u_.cells[1], u_.cells[2]};
143#ifdef PECLET_FLOW_MPI
144 if (gnx_ > 0)
145 return {gnx_, gny_, gnz_};
146#endif
147 return {nx_, ny_, nz_};
148}
149
150template <class Grid>
151std::vector<double> Solver<Grid>::cellCentres(int axis) const {
152 if (axis < 0 || axis > 2)
153 throw std::runtime_error("cell_centers: axis must be 0, 1 or 2");
154 const int n[3] = {nx_, ny_, nz_};
155 const int og[3] = {og_.x, og_.y, og_.z};
156 std::vector<double> c((std::size_t)n[axis]);
157 for (int i = 0; i < n[axis]; ++i)
158 c[(std::size_t)i] = u_.org[axis] + ((double)(og[axis] + i) + 0.5) * u_.h[axis];
159 return c;
160}
161
162template <class Grid>
164 // Phase 3: `hp`, `w`, `vol` and `aniso` are set by `setPhysicalDomain` — including its SNAP,
165 // which forces them to the EXACT identity when the three spacings agree to 1e-12. Recomputing
166 // them from `h[a]/hRef` here would undo that snap the moment the extents differ by an ulp
167 // across axes, so this only derives the one member Phase 3 added and hands the metric to the
168 // VoF drivers.
169 u_.hpMax = std::max(u_.hp[0], std::max(u_.hp[1], u_.hp[2]));
171 rho_ = rhoPhys_ * u_.rhoToInt();
172 mu_ = muPhys_ * u_.muToInt();
173 const double dtInt = dtPhys_ * u_.timeToInt();
174 if (dtInt != dt_)
175 dt_ = dtInt;
176 for (int a = 0; a < 3; ++a)
177 f_[a] = fPhys_[a] * u_.forceToInt(a);
178 sigmaCsf_ = sigmaPhys_ * u_.sigmaToInt();
179 // The block container keeps its own copy of the internal sigma (enable_vof_block_csf): it must
180 // follow a scale that moves after it, e.g. tRef pinned by the first set_dt (sigma' ~ tRef^2).
181 if (vofBlocks_ && vofBlocks_->csfEnabled)
182 vofBlocks_->sigma = sigmaCsf_;
183 slipLambda_ = slipPhys_ * u_.lenToInt();
184 for (auto& sc : scalars_)
185 sc.D = sc.Dphys * u_.diffToInt(); // the scalar diffusivity follows tRef like mu does
186 pcRefreshUnits(); // the phase-change densities, latent heat, k, rho c_p, R_int
187 for (auto& cl : closures_)
188 closureRefreshUnits(cl); // rho/mu/force closure parameters
189 for (int face = 0; face < 6; ++face) {
190 for (int a = 0; a < 3; ++a)
191 bcVel_[face][a] = bcVelPhys_[face][a] * u_.velToInt(a);
192 if (!bcProfRaw_[face].empty())
193 resampleBcProfile(face);
194 }
195 // rho/mu/dt all feed the momentum diagonal; a scale that moved after the operator was built
196 // must rebuild it. (Only reachable on the physical path — the cell-unit path never calls
197 // this, so no existing run gains a rebuild.)
198 dtDirty_ = true;
199}
200
201template <class Grid>
203 const vof::VofMetric g = u_.vofMetric();
204 vofAdv_.metric = g;
205 vofCurv_.metric = g;
206 vofDyn_.metric = g;
207 pcAreaC_.metric = g;
208 pcAreaMc_.metric = g;
209 if (vofBlocks_)
210 vofBlocks_->setMetric(g);
211}
212
213template <class Grid>
214void Solver<Grid>::allocateBlock(int nx, int ny, int nz) {
215 pguessCount_ = 0; // E: a new block (§5.3)
216 phiPrev1_ = CCField();
217 nx_ = nx;
218 ny_ = ny;
219 nz_ = nz;
220 e_ = C3{nx + 2 * G, ny + 2 * G, nz + 2 * G};
221 n_ = (std::size_t)e_.x * e_.y * e_.z;
222 e1_ = C3{nx + 2, ny + 2, nz + 2}; // g=1 block for the cut-cell pressure MG
223 n1_ = (std::size_t)e1_.x * e1_.y * e1_.z;
224 sdf_ = CCField("sdf", n_);
225 ox_ = CCField("ox", n_);
226 oy_ = CCField("oy", n_);
227 oz_ = CCField("oz", n_);
228 phi_ = CCField("phi", n_);
229 div_ = CCField("div", n_);
230 P_ = CCField("P", n_);
231 // g=1 scratch for the MG bridge (openness + rhs/phi + PCG vectors)
232 ox1_ = CCField("ox1", n1_);
233 oy1_ = CCField("oy1", n1_);
234 oz1_ = CCField("oz1", n1_);
235 rhs1_ = CCField("rhs1", n1_);
236 phi1_ = CCField("phi1", n1_);
237 r_ = CCField("r", n1_);
238 z_ = CCField("z", n1_);
239 pp_ = CCField("pp", n1_);
240 Ap_ = CCField("Ap", n1_);
241 for (int c = 0; c < 3; ++c) {
242 C[c].u = CCField("u", n_);
243 C[c].b = CCField("b", n_);
244 C[c].AC = FV("AC", n_);
245 C[c].AW = FV("AW", n_);
246 C[c].AE = FV("AE", n_);
247 C[c].AS = FV("AS", n_);
248 C[c].AN = FV("AN", n_);
249 C[c].AB = FV("AB", n_);
250 C[c].AT = FV("AT", n_);
251 C[c].inhom = CCField("inhom", n_);
252 C[c].rscale = CCField("rscale", n_);
253 C[c].mask = CCField("mask", n_);
254 bcDcorr_[c] = CCField("dcorr", n_);
255 bcBrhs_[c] = CCField("brhs", n_);
256 const int maxCut = nx * ny * nz;
257 // G.6: IbmOverlay row data follows MReal (was hardcoded float -- FV32) so a
258 // -DPECLET_FLOW_OPERATOR_DOUBLE build carries the overlay in double end to end.
259 C[c].ov = IbmOverlay{Kokkos::View<int*, CCMem>("ci", maxCut),
260 Kokkos::View<int*, CCMem>("nb", maxCut),
261 FV("dr", maxCut),
262 Kokkos::View<int*, CCMem>("dc", (std::size_t)maxCut * 6),
263 FV("K", (std::size_t)maxCut * 6),
264 FV("M", (std::size_t)maxCut * 6),
265 FV("X", (std::size_t)maxCut * 6),
266 FV("Nbc", (std::size_t)maxCut * 6),
267 FV("R", (std::size_t)maxCut * 6)};
268 C[c].idMap = Kokkos::View<int*, CCMem>("idMap", n_);
269 C[c].counter = Kokkos::View<int, CCMem>("cnt");
270 old_[c] = CCField("uOld", n_); // u^n time base (fixed over the step's Picard sweeps)
271 prev_[c] = CCField("uPrev", n_); // previous Picard iterate (outer-tolerance check)
272 }
273 if constexpr (Grid::collocated) { // transient face (MAC) field for the approximate projection
274 uf_ = CCField("uf", n_);
275 vf_ = CCField("vf", n_);
276 wf_ = CCField("wf", n_);
277 tgp_ = CCField("tgp", n_); // scratch: the collocated cell pressure gradient
278 fvM_ = CCField("fvM", n_); // scratch: M·u^k (embed defect matvec)
279 fvL_ = CCField("fvL", n_); // scratch: L_FV(u^k) (embed operator apply)
280 cs_ = CCField("cs", n_); // static cell fluid fraction (embed)
281 xcx_ = CCField("xcx", n_); // static per-face open-centroid wall distance (wall-aware map)
282 xcy_ = CCField("xcy", n_);
283 xcz_ = CCField("xcz", n_);
284 }
285 // Register the pre-existing solver fields in the named directory so the multiphysics machinery
286 // (scalar transport, property closures) and load-balance redistribution can enumerate the whole
287 // set uniformly. adopt() aliases the members (no reallocation, no ownership); all live on the
288 // G=2 velocity block and share velHalo_ under MPI.
289 fields_.adopt("u", C[0].u, G, peclet::core::Centering::FaceX);
290 fields_.adopt("v", C[1].u, G, peclet::core::Centering::FaceY);
291 fields_.adopt("w", C[2].u, G, peclet::core::Centering::FaceZ);
292 fields_.adopt("p", P_, G, peclet::core::Centering::Cell);
293 fields_.adopt("sdf", sdf_, G, peclet::core::Centering::Cell);
294}
295
296template <class Grid>
297void Solver<Grid>::setRho(double r) {
298 rhoPhys_ = r;
299 if (u_.physical && !u_.rhoRefSet) {
300 u_.rhoRef = r;
301 u_.rhoRefSet = true;
303 return;
304 }
305 const double ri = r * u_.rhoToInt();
306 if (ri != rho_) {
307 rho_ = ri;
308 dtDirty_ = true; // the momentum stencil bakes rho/dt in its diagonal (rebuildStencils)
309 }
310}
311
312template <class Grid>
313void Solver<Grid>::setMu(double m) {
314 muPhys_ = m;
315 const double mi = m * u_.muToInt();
316 if (mi != mu_) {
317 mu_ = mi;
318 dtDirty_ = true; // the momentum stencil bakes mu in its off-diagonals (rebuildStencils)
319 }
320}
321
322template <class Grid>
323void Solver<Grid>::setDt(double d) {
324 dtPhys_ = d;
325 if (u_.physical && !u_.tRefSet) {
326 u_.tRef = d;
327 u_.tRefSet = true;
328 const double before = dt_;
329 refreshUnitDerived(); // pins tRef, so mu'/p'/F'/v all move with it
330 if (dt_ != before)
331 dtDirty_ = true;
332 return;
333 }
334 const double di = d * u_.timeToInt();
335 if (di != dt_) {
336 dt_ = di;
337 dtDirty_ = true; // the momentum stencil bakes rho/dt in its diagonal (rebuildStencils);
338 // a mid-run dt change must rebuild it or the operator and RHS disagree
339 }
340}
341
342template <class Grid>
343void Solver<Grid>::setBodyForce(double fx, double fy, double fz) {
344 fPhys_ = {fx, fy, fz};
345 for (int a = 0; a < 3; ++a)
346 f_[a] = fPhys_[a] * u_.forceToInt(a);
347}
348
349template <class Grid>
350void Solver<Grid>::setSuperficialVelocity(bool on, int axis, double velocity) {
351 if (!on) {
352 superficialAxis_ = -1;
353 return;
354 }
355 if (axis < 0 || axis > 2)
356 throw std::invalid_argument("set_superficial_velocity: axis must be 0, 1 or 2");
357 if constexpr (Grid::collocated)
358 throw std::runtime_error(
359 "set_superficial_velocity: staggered Solver only (the collocated grid would have to "
360 "shift the projected face field and the cell velocity consistently; not implemented)");
361 superficialAxis_ = axis;
362 superficialVelPhys_ = velocity;
363 if (superficialShift_.data() == nullptr)
364 superficialShift_ = Kokkos::View<double, CCMem>("superficial_shift");
365 Kokkos::deep_copy(superficialShift_, 0.0);
366}
367
368template <class Grid>
370 if (superficialAxis_ < 0 || superficialShift_.data() == nullptr)
371 return 0.0;
372 double h = 0.0;
373 Kokkos::deep_copy(h, superficialShift_);
374 return h * u_.velToPhys(superficialAxis_);
375}
376
377template <class Grid>
379 velIters_ = it;
380}
381
382template <class Grid>
383void Solver<Grid>::setVelocityTolerance(double rtol, int minIters) {
384 velTol_ = rtol > 0.0 ? rtol : 0.0;
385 velMinIters_ = minIters < 1 ? 1 : minIters;
386}
387
388template <class Grid>
390 return lastMomentumSweeps_;
391}
392
393template <class Grid>
395 velResTol_ = rtol;
396}
397
398template <class Grid>
399void Solver<Grid>::setVelocityMultigridAuto(long cellsPerRank, long minGlobalCells,
400 int minBlockExtent) {
401 vmgAutoCells_ = cellsPerRank;
402 if (minGlobalCells >= 0)
403 vmgAutoMinGlobal_ = minGlobalCells;
404 if (minBlockExtent >= 0)
405 vmgAutoMinExtent_ = minBlockExtent;
406}
407
408template <class Grid>
409void Solver<Grid>::setVelocityChebyshev(bool on, int maxit) {
410 useVelocityCheb_ = on;
411 velChebMaxit_ = maxit < 1 ? 1 : maxit;
412}
413
414template <class Grid>
416 vmgExplicit_ = false;
417 useVelocityCheb_ = false;
418 useVelocityMg_ = false;
419 vmgDecided_ = false; // re-decide at the next step()
420}
421
422template <class Grid>
424 return useVelocityCheb_;
425}
426
427template <class Grid>
428void Solver<Grid>::setVelocityMgChebyshev(bool on, int degree, double eig_ratio) {
429 vmgCheb_ = on;
430 vmgChebDegree_ = degree;
431 vmgChebEigRatio_ = eig_ratio;
432 vmg_.setChebyshevSmoother(on, degree, eig_ratio);
433}
434
435template <class Grid>
437 return vmgCheb_;
438}
439
440template <class Grid>
442 if (velResTol_ >= 0.0)
443 return velResTol_;
444 return useChebyshev_ ? chebRtol_ : pcgRtol_; // FCG shares pcgRtol_; the plain V-cycle driver
445 // has no tolerance and takes the PCG default
446}
447
448template <class Grid>
450 return lastMomentumResid_;
451}
452
453template <class Grid>
455 mg_.setMeanRemovalScope(all);
456}
457
458template <class Grid>
460 presIters_ = it;
461}
462
463template <class Grid>
465 advect_ = on;
466}
467
468template <class Grid>
470 advScheme_ = s;
471}
472
473template <class Grid>
475 implicitFou_ = on;
476}
477
478template <class Grid>
480 outerIters_ = iters < 1 ? 1 : iters;
481}
482
483template <class Grid>
485 outerTol_ = tol;
486}
487
488template <class Grid>
490 return lastOuterIters_;
491}
492
493template <class Grid>
494void Solver<Grid>::setVelocityMultigrid(bool on, int levels, int vcycles) {
495 if (on && varProps_)
496 throwVelocityMgVariableMu("set_velocity_multigrid / set_velocity_solver('multigrid')");
497 useVelocityMg_ = on;
498 vmgExplicit_ = true; // an explicit choice disables the AUTO rule
499 vmgLevels_ = levels < 1 ? 1 : levels;
500 vmgVcycles_ = vcycles < 1 ? 1 : vcycles;
501}
502
503template <class Grid>
504void Solver<Grid>::throwVelocityMgVariableMu(const char* who) const {
505 throw std::invalid_argument(
506 std::string(who) +
507 ": the velocity multigrid takes a SCALAR viscosity and would silently solve the momentum "
508 "equation with the constant set_mu value, ignoring the variable viscosity (a 'mu' "
509 "closure or set_property_mode('variable')). Use set_velocity_solver('gauss_seidel') or "
510 "'auto' (the AUTO rule already keeps variable viscosity on the red-black smoother).");
511}
512
513template <class Grid>
515 return useVelocityMg_;
516}
517
518template <class Grid>
520 pressAgglomMode_ = mode;
521 if (cutcellPressure_)
522 mg_.setAgglomerationMode(mode);
523}
524
525template <class Grid>
527 mg_.setBottomSolver(engine);
528}
529
530template <class Grid>
532 // A different V-cycle: the kept Chebyshev bounds (main and balanced-force) are stale.
533 if (enabled != mg_.lineRelaxation()) {
534 chebBoundsSet_ = false;
535 chebWarmOk_ = false;
536 bfpChebSet_ = false;
537 }
538 mg_.setLineRelaxation(enabled); // drops the kept power-iteration vectors on a change
539}
540
541template <class Grid>
543 // A different V-cycle: the kept Chebyshev bounds (main and balanced-force) are stale.
544 if (enabled != mg_.symmetricVcycle()) {
545 chebBoundsSet_ = false;
546 chebWarmOk_ = false;
547 bfpChebSet_ = false;
548 }
549 mg_.setSymmetricVcycle(enabled); // drops the kept power-iteration vectors on a change
550}
551
552template <class Grid>
554 mg_.setVcyclePrecision(mode);
555}
556
557template <class Grid>
559 return mg_.lastVcycleFp32();
560}
561
562template <class Grid>
564 mg_.debugSetFp32Fault(kind, at);
565}
566
567template <class Grid>
569 return mg_.vcycleRestarts();
570}
571
572template <class Grid>
574 return pguessCount_;
575}
576
577template <class Grid>
579 mg_.setTelescope(on);
580}
581
582template <class Grid>
584 return mg_.telescope();
585}
586
587template <class Grid>
589 mg_.setTelescopeForceLevel(level);
590}
591
592template <class Grid>
594 return mg_.telescopeCount();
595}
596
597template <class Grid>
599 return mg_.prefactorLaunches();
600}
601
602template <class Grid>
604 pressGraphAmg_ = on;
605 if (cutcellPressure_)
606 mg_.setGraphAmgBottom(on); // propagate live (previously only applied at the next set_solid,
607 // so toggling after geometry silently had no effect)
608}
609
610template <class Grid>
612 nLevels_ = levels < 0 ? 1 : levels; // 0 = AUTO (doc/mg_depth_policy.md §4.3)
613}
614
615template <class Grid>
617 backflowBeta_ = beta < 0.0 ? 0.0 : beta;
618}
619
620template <class Grid>
622 deferredCorr_ = on;
623}
624
625template <class Grid>
626void Solver<Grid>::setPressureChebyshev(bool on, int maxit, double rtol) {
627 useChebyshev_ = on;
628 if (on)
629 useFcg_ = false;
630 chebMaxit_ = maxit;
631 chebRtol_ = rtol;
632 chebBoundsSet_ = false;
633 chebWarmOk_ = false;
634 bfpChebSet_ = false;
635}
636
637template <class Grid>
638void Solver<Grid>::setPressurePcg(bool on, int maxit, double rtol) {
639 if (!on)
640 throw std::runtime_error(
641 "set_pressure_pcg(False): MG-PCG is the default/terminal pressure driver, so it cannot be "
642 "deselected on its own — select the driver you want instead "
643 "(set_pressure_chebyshev(True, ...) or set_pressure_fcg(True, ...)).");
644 useChebyshev_ = false; // genuine selection: the three drivers are mutually exclusive
645 useFcg_ = false;
646 chebBoundsSet_ = false;
647 chebWarmOk_ = false;
648 bfpChebSet_ = false;
649 pcgMaxit_ = maxit;
650 pcgRtol_ = rtol;
651 cgContrastPending_ = true; // Q18 (b): the high-contrast notice, at the first solve
652}
653
654template <class Grid>
655void Solver<Grid>::setPressureFcg(bool on, int maxit, double rtol) {
656 if (on && ghostProjection_)
657 throw std::runtime_error(
658 "set_pressure_fcg: the ghost-projection operator is nonsymmetric and is solved by "
659 "BiCGStab; FCG does not apply");
660 useFcg_ = on;
661 if (on)
662 useChebyshev_ = false; // genuine selection (the pair is exclusive)
663 pcgMaxit_ = maxit;
664 pcgRtol_ = rtol;
665 cgContrastPending_ = true; // Q18 (b): the high-contrast notice, at the first solve
666}
667
668template <class Grid>
669void Solver<Grid>::setGhostProjection(bool on, int matrixOrder, int rhsOrder) {
670 if constexpr (Grid::collocated) {
671 // Collocated ghost mode: the SAME phi matrix/closures on the 1/2-1/2 face-averaged field
672 // (the face correction uf -= grad(phi) is the identical substitution), plus the directional
673 // gpCenterGrad cell gradient for the predictor -grad(P^n) and the cell correction. Only the
674 // plain (mode-0) face map applies — the wall-aware/FV/embed face-interp modes replace the
675 // very operators this scheme owns.
676 if (on && faceInterp_ != 0)
677 faceInterp_ = 0; // QUARANTINED verification path: it owns the operators the gauge-exact
678 // scheme replaces, so it selects the plain face map itself rather than
679 // throwing on the (now default) gauge-exact scheme.
680 }
681 if (on && geometryBuilt_)
682 throw std::runtime_error(
683 "set_ghost_projection / set_collocated_scheme('ghost'): call BEFORE set_solid -- the "
684 "ghost overlay is built with the geometry");
685 if (on && (porous_ || varRho_ || hasBc_ || useChebyshev_))
686 throw std::runtime_error(
687 "set_ghost_projection: incompatible with porous/variable-rho/domain-BC/Chebyshev (v1)");
688 if (matrixOrder < 1 || matrixOrder > 2 || rhsOrder < 1 || rhsOrder > 2)
689 throw std::runtime_error("set_ghost_projection: matrix_order/rhs_order must be 1 or 2");
690 if (on && distributed_ && (hasExactCross_ || hasOpenOverride_))
691 throw std::runtime_error(
692 "set_ghost_projection: exact-crossings/openness-override are single-rank only");
693 ghostProjection_ = on;
694 colSchemeAuto_ = false; // explicit selection disables the AUTO default
695 gpMatrixOrder_ = matrixOrder;
696 gpRhsOrder_ = rhsOrder;
697 gpNRows_ = -1; // takes effect at the next set_solid
698}
699
700template <class Grid>
701void Solver<Grid>::setExactCrossings(const std::vector<double>& t) {
702 requireNoGeometry("set_exact_crossings");
703 const std::size_t n = (std::size_t)nx_ * ny_ * nz_;
704 if (t.empty()) {
705 hasExactCross_ = false;
706 return;
707 }
708 if (t.size() != 9 * n)
709 throw std::runtime_error("set_exact_crossings: expected 9*nx*ny*nz values");
710#ifdef PECLET_FLOW_MPI
711 if (distributed_)
712 throw std::runtime_error("set_exact_crossings: single-rank only");
713#endif
714 for (int c = 0; c < 3; ++c)
715 for (int k = 0; k < 3; ++k) {
716 tEx_[c][k] = CCField("tEx", n);
717 Kokkos::deep_copy(
718 tEx_[c][k],
719 Kokkos::View<const double*, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged>>(
720 t.data() + ((std::size_t)c * 3 + k) * n, n));
721 }
722 hasExactCross_ = true;
723}
724
725template <class Grid>
726void Solver<Grid>::setOpennessOverride(const std::vector<double>& ox, const std::vector<double>& oy,
727 const std::vector<double>& oz) {
728 requireNoGeometry("set_openness_override");
729 const std::size_t n = (std::size_t)nx_ * ny_ * nz_;
730 if (ox.empty()) {
731 hasOpenOverride_ = false;
732 return;
733 }
734 if (ox.size() != n || oy.size() != n || oz.size() != n)
735 throw std::runtime_error("set_openness_override: expected nx*ny*nz values per field");
736#ifdef PECLET_FLOW_MPI
737 if (distributed_)
738 throw std::runtime_error("set_openness_override: single-rank only");
739#endif
740 oxOverride_ = ox;
741 oyOverride_ = oy;
742 ozOverride_ = oz;
743 hasOpenOverride_ = true;
744}
745
746template <class Grid>
748 incremental_ = on;
749}
750
751template <class Grid>
753 pwarm_ = on;
754}
755
756template <class Grid>
757void Solver<Grid>::setPressureInitialGuess(int mode, int history) {
758 if (mode < 0 || mode > 2)
759 throw std::runtime_error("set_pressure_initial_guess: 'auto' | 'zero' | 'projected'");
760 if (history != 1 && history != 2)
761 throw std::runtime_error("set_pressure_initial_guess: history must be 1 or 2");
762 pguessMode_ = mode;
763 pguessHistMax_ = history;
764 pguessCount_ = 0; // a guess-mode change (§5.3)
765}
766
767template <class Grid>
769 // §5.3 eligibility: a Krylov driver (PCG or FCG), the legacy warm start off, no ghost
770 // projection; any np (distributed since doc/vof_projection_distributed_design.md §6). The
771 // balanced-force solve never takes it (its own call path).
772 if (useChebyshev_)
773 return "the Chebyshev driver (not a Krylov driver; set_pressure_pcg or set_pressure_fcg)";
774 if (ghostProjection_)
775 return "the ghost projection (its BiCGStab driver)";
776 if (pwarm_)
777 return "set_pressure_warmstart(True)";
778 return nullptr;
779}
780
781template <class Grid>
783 if (mode != 0 && mode != 9 && (mode < 5 || mode > 7))
784 throw std::runtime_error(
785 "set_face_interp: mode " + std::to_string(mode) +
786 " is not one of 0 (plain), 5/6/7 (embed rungs) or 9 (gauge-exact); use "
787 "set_collocated_scheme('plain' | 'gauge-exact' | 'embed' | 'ghost')");
788 if (ghostProjection_ && mode != 0)
789 throw std::runtime_error(
790 "set_face_interp: incompatible with the ghost projection (set_ghost_projection(False) "
791 "first, or use set_collocated_scheme which handles the transition)");
792 faceInterp_ = mode;
793 colSchemeAuto_ = false; // explicit selection disables the AUTO default
794}
795
796template <class Grid>
798 return faceInterp_;
799}
800
801template <class Grid>
802void Solver<Grid>::setCollocatedScheme(const std::string& name) {
803 if (name != "ghost" && ghostProjection_) {
804 ghostProjection_ = false; // scheme transition: drop the ghost before selecting a face mode
805 gpNRows_ = -1;
806 }
807 if (name == "gauge-exact") {
808 setFaceInterp(9);
809 } else if (name == "plain") {
810 setFaceInterp(0);
811 } else if (name == "embed") {
812 setFaceInterp(7);
813 } else if (name == "ghost") {
814 // The fluid-only constraint scheme (route 2b, 2026-08): binary-openness divergence +
815 // directional closures + gauge-exact gradient. Clean-protocol record: family-free
816 // (m1 -> 1e-5 monotone, |P| frozen), NO Layer-1 instability, C2 across dt = 60..1e20 with
817 // no stabilizer, both-bed ladders -1.4% -> +0.22% (R=8..24; its own small plateau), Z&H
818 // anchor -0.018% at N=128. Costs: BiCGStab (~2.3-2.7x pressure stage; star preconditioner
819 // planned), ~1.6 KB/cell overlay (caps single-GPU size), fragmentation guard. The (1,2)
820 // mixed mode stays quarantined (march-unstable on >2000-sphere beds).
821 setGhostProjection(true, 2, 2);
822 } else
823 throw std::runtime_error(
824 "set_collocated_scheme: expected 'ghost', 'gauge-exact', 'plain' or 'embed', got '" + name +
825 "'");
826}
827
828template <class Grid>
830 rotationalP_ = on;
831}
832
833template <class Grid>
835 rotWeight_ = w;
836}
837
838template <class Grid>
840 rotWallW_ = w0;
841}
842
843template <class Grid>
845 requireNoGeometry("set_aperture_order");
846 if (order < 1 || order > 2)
847 throw std::runtime_error("set_aperture_order: order must be 1 or 2");
848 apertureOrder_ = order;
849}
850
851template <class Grid>
853 return apertureOrder_;
854}
855
856template <class Grid>
858 advWallVel_ = on;
859}
860
861template <class Grid>
863 return advWallVel_;
864}
865
866template <class Grid>
868 if (distributed_)
869 throw std::runtime_error(
870 "set_comm_avoiding: call BEFORE init_mpi -- the momentum half is latched with the halo "
871 "topology");
872 caMode_ = mask;
873 mg_.setCommAvoiding(mask);
874}
875
876template <class Grid>
878 return caMode_;
879}
880
881template <class Grid>
883 if (!(theta > 1.0))
884 throw std::runtime_error("set_multigrid_aspect_threshold: theta must be > 1");
885 aspectTheta_ = theta;
886 mg_.setAspectThreshold(theta);
887 vmg_.setAspectThreshold(theta);
888}
889
890template <class Grid>
892 return aspectTheta_;
893}
894
895template <class Grid>
897 mg_.setStrictPressure(on);
898}
899
900template <class Grid>
902 return mg_.strictPressure();
903}
904
905template <class Grid>
907 mg_.setCoarseGhost(on);
908}
909
910template <class Grid>
912 return mg_.coarseGhost();
913}
914
915template <class Grid>
917 mg_.setAgglomerationExtent(cells);
918}
919
920template <class Grid>
922 return mg_.agglomerationExtent();
923}
924
925template <class Grid>
926void Solver<Grid>::setDecomposition(int levels, double maxImbalance) {
927 if (distributed_)
928 throw std::runtime_error(
929 "set_decomposition: call BEFORE init_mpi -- the decomposition is built there");
930 if (levels < 0)
931 throw std::invalid_argument(
932 "set_decomposition: levels must be >= 0 (0 = auto, 1 = the legacy aligned ORB, >= 2 = "
933 "coarse-first at that depth)");
934 if (!(maxImbalance > 1.0))
935 throw std::invalid_argument(
936 "set_decomposition: max_imbalance must be > 1.0 (the largest / smallest block cell-count "
937 "ratio a candidate may reach; default 1.05)");
938 decompLevels_ = levels;
939 decompMaxImbalance_ = maxImbalance;
940}
941
942template <class Grid>
944 return decompLevels_;
945}
946
947template <class Grid>
949 return decompMaxImbalance_;
950}
951
952template <class Grid>
954 requireNoGeometry("set_fluid_only_constraint");
955 if (mode < 0 || mode > 2)
956 throw std::runtime_error("set_fluid_only_constraint: mode must be 0, 1 or 2");
957 fluidOnlyMode_ = mode;
958 if (mode != 0)
959 colSchemeAuto_ = false; // mechanism instruments run on the aperture rails, not AUTO-ghost
960}
961
962template <class Grid>
963void Solver<Grid>::setRotationalFilter(bool on, double eps) {
964 rotFilter_ = on;
965 rotFilterEps_ = eps;
966}
967
968template <class Grid>
970 if constexpr (Grid::collocated) {
971 for (int c = 0; c < 3; ++c)
972 fillVelGhosts(c, 0);
973 if (faceInterp_ == 5 || faceInterp_ == 7)
974 centerToFaceWallAware(uf_, vf_, wf_, CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u),
975 CCConst(sdf_), CCConst(xcx_), CCConst(xcy_), CCConst(xcz_), true, e_,
976 G);
977 else
978 centerToFace(uf_, vf_, wf_, CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u), e_, G);
979 faceFieldValid_ = true;
980 buildOpenFaceField(); // keep the advecting/diagnostic view in step with the seeded field
981 }
982}
983
984template <class Grid>
985void Solver<Grid>::uploadVelocity(const std::vector<double>& uu, const std::vector<double>& vv,
986 const std::vector<double>& ww) {
987 pguessCount_ = 0; // E: a state write (doc/vof_projection_cost_design.md §5.3)
988 const std::vector<double>* src[3] = {&uu, &vv, &ww};
989 std::vector<double> scaled[3];
990 for (int c = 0; c < 3; ++c) {
991 const double k = u_.velToInt(c);
992 if (k == 1.0)
993 continue;
994 scaled[c].resize(src[c]->size());
995 for (std::size_t i = 0; i < src[c]->size(); ++i)
996 scaled[c][i] = (*src[c])[i] * k;
997 src[c] = &scaled[c];
998 }
999 CCExec space;
1000 const int ex = e_.x, ey = e_.y, nx = nx_, ny = ny_, nz = nz_, g = G;
1001 for (int c = 0; c < 3; ++c) {
1002 // Upload the inner field once, write it into the inner cells on device, then refresh the
1003 // periodic ghosts (G4) — the old path mirrored the field down, looped on host, and copied
1004 // back up.
1005 CCField din("peclet::flow::vel_in_d", static_cast<std::size_t>(nx_) * ny_ * nz_);
1006 Kokkos::deep_copy(
1007 din,
1008 Kokkos::View<const double*, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged>>(
1009 src[c]->data(), src[c]->size()));
1010 CCField u = C[c].u;
1011 Kokkos::parallel_for(
1012 "peclet::flow::upload_velocity", MDRange3<CCExec>(space, {0, 0, 0}, {nx, ny, nz}),
1013 KOKKOS_LAMBDA(int x, int y, int z) {
1014 u((long)(x + g) + (long)(y + g) * ex + (long)(z + g) * (long)ex * ey) =
1015 din((std::size_t)x + (std::size_t)y * nx + (std::size_t)z * (std::size_t)nx * ny);
1016 });
1017 fillGhosts(C[c].u);
1018 }
1019 seedFaceFieldFromCells(); // ISSUES sweep item 5 (collocated only; a no-op staggered)
1020}
1021
1022template <class Grid>
1023int Solver<Grid>::nx() const {
1024 return nx_;
1025}
1026
1027template <class Grid>
1028int Solver<Grid>::ny() const {
1029 return ny_;
1030}
1031
1032template <class Grid>
1033int Solver<Grid>::nz() const {
1034 return nz_;
1035}
1036
1037template <class Grid>
1039 return advectsMomentum() && (implicitFou_ || (hasBc_ && (!useVelocityMg_ || hasSolid_)));
1040}
1041
1042template <class Grid>
1044 return hasBc_ &&
1045 (hasSolid_ || (!useVelocityMg_ && (implicitAdv() || varProps_ || varRho_ || hasDrag_)));
1046}
1047
1048template <class Grid>
1050 return hasBc_ && useVelocityMg_ && hasSolid_ && !varProps_ && !varRho_ && !hasDrag_;
1051}
1052
1053template <class Grid>
1054long Solver<Grid>::strideOf(int c) const {
1055 return (c == 0) ? 1 : (c == 1) ? e_.x : (long)e_.x * e_.y;
1056}
1057
1058template <class Grid>
1060 // Per-axis viscous coefficient b_a = mu' * w_a (doc/anisotropic_metric.md §2); w == 1.0 on
1061 // the isotropic path, so this is literally `beta = mu_` there.
1062 const double idiag = rho_ / dt_, bx = mu_ * u_.w[0], by = mu_ * u_.w[1], bz = mu_ * u_.w[2];
1063 if (varProps_)
1064 fillMuGhosts(); // face means read mu at i +- stride (boundary inner cells -> ghosts)
1065 if (varRho_)
1066 fillPropGhosts(rhoField_);
1067 for (int c = 0; c < 3; ++c) {
1068 Kokkos::deep_copy(CCExec(), C[c].rscale, 1.0); // S4: instance-ordered fills
1069 Kokkos::deep_copy(CCExec(), C[c].inhom, 0.0);
1070 if (sharpActive_) // the band edges' PLIC face-fraction mu (doc/vof_sharp_viscous_stress.md §6)
1071 ibmBuildDiffusionVar(C[c].AC, C[c].AW, C[c].AE, C[c].AS, C[c].AN, C[c].AB, C[c].AT, e_.x,
1072 e_.y, e_.z, G, makeSharpFaceProps(c, vof::SvRole::kImplicit), u_.w[0],
1073 u_.w[1], u_.w[2]);
1074 else if (varProps_ || effVarRho())
1075 ibmBuildDiffusionVar(C[c].AC, C[c].AW, C[c].AE, C[c].AS, C[c].AN, C[c].AB, C[c].AT, e_.x,
1076 e_.y, e_.z, G, makeFaceProps(c), u_.w[0], u_.w[1], u_.w[2]);
1077 else
1078 ibmBuildDiffusion(C[c].AC, C[c].AW, C[c].AE, C[c].AS, C[c].AN, C[c].AB, C[c].AT, e_.x, e_.y,
1079 e_.z, bx, by, bz, idiag);
1080 ibmModifyStencil(C[c].AC, C[c].AW, C[c].AE, C[c].AS, C[c].AN, C[c].AB, C[c].AT, C[c].inhom,
1081 C[c].rscale, C[c].ov, C[c].nCut, 0.0f, wallVelView(c));
1082 if (hasDrag_)
1083 addDragDiagonal(c);
1084 }
1085}
1086
1087template <class Grid>
1088void Solver<Grid>::copyInner(CCField dst, C3 de, int dg, CCConst src, C3 se, int sg) {
1089 // rule H (§4.5; §14 H-3a): host pencil, device MDRange -- no per-cell 64-bit div/mod. dst and
1090 // src are different fields (two blocks of different ghost width), so ccFor3's simd contract
1091 // holds.
1092 ccFor3(
1093 "peclet::flow::copyInner", C3{0, 0, 0}, C3{nx_, ny_, nz_},
1094 KOKKOS_LAMBDA(int ix, int iy, int iz) {
1095 const long di =
1096 (long)(ix + dg) + (long)(iy + dg) * de.x + (long)(iz + dg) * (long)de.x * de.y;
1097 const long si =
1098 (long)(ix + sg) + (long)(iy + sg) * se.x + (long)(iz + sg) * (long)se.x * se.y;
1099 dst(di) = src(si);
1100 });
1101}
1102
1103template <class Grid>
1104void Solver<Grid>::copyBlockShifted(CCField dst, C3 de, CCConst src, C3 se, int off) {
1105 ccFor3( // rule H (doc/vof_step_performance_design.md §4.5): host pencil, device MDRange
1106 "peclet::flow::copyBlockShifted", C3{0, 0, 0}, C3{de.x, de.y, de.z},
1107 KOKKOS_LAMBDA(int x, int y, int z) {
1108 const long di = (long)x + (long)y * de.x + (long)z * (long)de.x * de.y;
1109 const long si =
1110 (long)(x + off) + (long)(y + off) * se.x + (long)(z + off) * (long)se.x * se.y;
1111 dst(di) = src(si);
1112 });
1113}
1114
1115template <class Grid>
1117#ifdef PECLET_FLOW_MPI
1118 if (distributed_) {
1119 velDev_->exchange(f);
1120 return;
1121 }
1122#endif
1123 fillPeriodicAxes(f, 7); // §14 H-3(d): x, y, z in one launch (was fillAxis 0, 1, 2)
1124}
1125
1126template <class Grid>
1128#ifdef PECLET_FLOW_MPI
1129 if (distributed_) {
1130 velDev_->exchange(f);
1131 return;
1132 } // halo gives all ghosts; the 7-pt smoother uses the faces
1133#endif
1134 CCExec space;
1135 C3 e = e_;
1136 const int Nx = nx_, Ny = ny_, Nz = nz_;
1137 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
1138 CCField ff = f;
1139 Kokkos::parallel_for(
1140 "peclet::flow::ibm_facefill", Kokkos::RangePolicy<CCExec>(space, 0, (long)nx_ * ny_ * nz_),
1141 KOKKOS_LAMBDA(long n) {
1142 const int ix = (int)(n % Nx), iy = (int)((n / Nx) % Ny), iz = (int)(n / ((long)Nx * Ny));
1143 const long i = (long)(ix + G) * sx + (long)(iy + G) * sy + (long)(iz + G) * sz;
1144 if (ix < G)
1145 ff(i + (long)Nx * sx) = ff(i);
1146 else if (ix >= Nx - G)
1147 ff(i - (long)Nx * sx) = ff(i);
1148 if (iy < G)
1149 ff(i + (long)Ny * sy) = ff(i);
1150 else if (iy >= Ny - G)
1151 ff(i - (long)Ny * sy) = ff(i);
1152 if (iz < G)
1153 ff(i + (long)Nz * sz) = ff(i);
1154 else if (iz >= Nz - G)
1155 ff(i - (long)Nz * sz) = ff(i);
1156 });
1157}
1158
1159template <class Grid>
1161 CCExec space;
1162 C3 e = e_;
1163 int N3[3] = {nx_, ny_, nz_};
1164 int dims[3] = {e.x, e.y, e.z};
1165 long st[3] = {1, e.x, (long)e.x * e.y};
1166 const int a = axis, b = (axis + 1) % 3, c = (axis + 2) % 3;
1167 const long sa = st[a], sb = st[b], sc = st[c];
1168 const int N = N3[a];
1169 CCField ff = f;
1170 Kokkos::parallel_for(
1171 "peclet::flow::ibm_pfill", MDRange2<CCExec>(space, {0, 0}, {dims[b], dims[c]}),
1172 KOKKOS_LAMBDA(int p0, int p1) {
1173 const long base = (long)p0 * sb + (long)p1 * sc;
1174 for (int gl = 0; gl < G; ++gl) {
1175 ff(base + (long)gl * sa) = ff(base + (long)(gl + N) * sa);
1176 ff(base + (long)(G + N + gl) * sa) = ff(base + (long)(G + gl) * sa);
1177 }
1178 });
1179}
1180
1181// §14 H-3(d): every ghost cell that has a ghost coordinate on at least one axis in `axes` takes the
1182// value of the cell its periodic coordinates (those in `axes`) wrap to; its other coordinates stay.
1183// That is exactly what the sequential fillAxis passes over those axes in ascending order (each over
1184// the full transverse extent, ghosts included) leave behind: a ghost an earlier pass wrote is
1185// overwritten by a later pass with the wrapped value of a cell the earlier pass had written from
1186// its own wrap, and the source of every write (inner on every axis in `axes`) is never written.
1187// Pure copies, so bit-identical (CutcellMG::fillWrap's argument, §5.4, with non-periodic axes
1188// kept). The shell as up to three disjoint slabs: z-ghost planes (all x, y) if z is in `axes`; then
1189// y-ghost rows (all x) over the z range the z slab did not cover; then x-ghost cells over the (y,
1190// z) range the first two did not cover.
1191template <class Grid>
1193 const bool px = axes & 1, py = axes & 2, pz = axes & 4;
1194 const int nx = nx_, ny = ny_, nz = nz_;
1195 if ((px && nx < G) || (py && ny < G) || (pz && nz < G)) {
1196 // a ghost band wider than the block: the sequential passes copy ghost from ghost, which the
1197 // one-shot wrap does not reproduce -- keep them
1198 for (int a = 0; a < 3; ++a)
1199 if (axes & (1 << a))
1200 fillAxis(f, a);
1201 return;
1202 }
1203 CCExec space;
1204 const C3 e = e_;
1205 const long exy = (long)e.x * e.y;
1206 // the z range of the y slab and the (y, z) range of the x slab: inner on a periodic axis whose
1207 // slab came first, the full extent otherwise
1208 const int z0 = pz ? G : 0, zn = pz ? nz : e.z;
1209 const int y0 = py ? G : 0, yn = py ? ny : e.y;
1210 const long nZ = pz ? 2L * G * exy : 0, nY = py ? (long)zn * 2 * G * e.x : 0,
1211 nX = px ? (long)zn * yn * 2 * G : 0;
1212 CCField ff = f;
1213 if constexpr (std::is_same_v<typename CCExec::memory_space, Kokkos::HostSpace>) {
1214 // host: the slabs ROW by row (one division per row, a contiguous copy along x), serially below
1215 // the cutoff (rule H). No simd mark: a row's source and destination can share the row.
1216 const long rZ = pz ? 2L * G * e.y : 0, rY = py ? (long)zn * 2 * G : 0,
1217 rX = px ? (long)zn * yn : 0;
1218 auto copyRow = [=](long dst, long src) { // one full x row, wrapped along x if x is periodic
1219 if (px) {
1220 for (int x = 0; x < G; ++x)
1221 ff(dst + x) = ff(src + x + nx);
1222 for (int x = G; x < G + nx; ++x)
1223 ff(dst + x) = ff(src + x);
1224 for (int x = G + nx; x < e.x; ++x)
1225 ff(dst + x) = ff(src + x - nx);
1226 } else {
1227 for (int x = 0; x < e.x; ++x)
1228 ff(dst + x) = ff(src + x);
1229 }
1230 };
1231 auto row = [=](long t) {
1232 if (t < rZ) { // z-ghost plane row (y, zg)
1233 const int l = (int)(t / e.y), y = (int)(t - (long)l * e.y);
1234 const int z = l < G ? l : nz + l;
1235 const int sy = !py ? y : (y < G ? y + ny : (y >= G + ny ? y - ny : y));
1236 const int sz = z < G ? z + nz : z - nz;
1237 copyRow((long)y * e.x + (long)z * exy, (long)sy * e.x + (long)sz * exy);
1238 } else if (t < rZ + rY) { // y-ghost row (yg, z) of the y slab's z range
1239 const long t2 = t - rZ;
1240 const int zi = (int)(t2 / (2 * G)), l = (int)(t2 - (long)zi * 2 * G);
1241 const int y = l < G ? l : ny + l, z = z0 + zi;
1242 const int sy = y < G ? y + ny : y - ny;
1243 copyRow((long)y * e.x + (long)z * exy, (long)sy * e.x + (long)z * exy);
1244 } else { // the x-ghost cells of row (y, z) of the x slab's range
1245 const long t3 = t - rZ - rY;
1246 const int zi = (int)(t3 / yn), yi = (int)(t3 - (long)zi * yn);
1247 const long base = (long)(y0 + yi) * e.x + (long)(z0 + zi) * exy;
1248 for (int x = 0; x < G; ++x)
1249 ff(base + x) = ff(base + x + nx);
1250 for (int x = G + nx; x < e.x; ++x)
1251 ff(base + x) = ff(base + x - nx);
1252 }
1253 };
1254 if (hostRunSerial(nZ + nY + nX)) {
1255 const HostSerialRegion serialRegion("peclet::flow::ibm_pfill3@serial"); // WO-T
1256 for (long t = 0; t < rZ + rY + rX; ++t)
1257 row(t);
1258 return;
1259 }
1260 Kokkos::parallel_for("peclet::flow::ibm_pfill3",
1261 Kokkos::RangePolicy<CCExec>(space, 0, rZ + rY + rX), row);
1262 return;
1263 }
1264 Kokkos::parallel_for(
1265 "peclet::flow::ibm_pfill3", Kokkos::RangePolicy<CCExec>(space, 0, nZ + nY + nX),
1266 KOKKOS_LAMBDA(long t) {
1267 int x, y, z;
1268 if (t < nZ) {
1269 const int l = (int)(t / exy);
1270 const long r = t - (long)l * exy;
1271 x = (int)(r % e.x);
1272 y = (int)(r / e.x);
1273 z = l < G ? l : nz + l;
1274 } else if (t < nZ + nY) {
1275 const long t2 = t - nZ, rw = 2L * G * e.x;
1276 const long zi = t2 / rw, r = t2 - zi * rw;
1277 const int l = (int)(r / e.x);
1278 x = (int)(r % e.x);
1279 y = l < G ? l : ny + l;
1280 z = z0 + (int)zi;
1281 } else {
1282 const long t3 = t - nZ - nY, rw = (long)yn * 2 * G;
1283 const long zi = t3 / rw, r = t3 - zi * rw;
1284 const int l = (int)(r % (2 * G));
1285 x = l < G ? l : nx + l;
1286 y = y0 + (int)(r / (2 * G));
1287 z = z0 + (int)zi;
1288 }
1289 const int sx = !px ? x : (x < G ? x + nx : (x >= G + nx ? x - nx : x));
1290 const int sy = !py ? y : (y < G ? y + ny : (y >= G + ny ? y - ny : y));
1291 const int sz = !pz ? z : (z < G ? z + nz : (z >= G + nz ? z - nz : z));
1292 ff((long)x + (long)y * e.x + (long)z * exy) =
1293 ff((long)sx + (long)sy * e.x + (long)sz * exy);
1294 });
1295}
1296
1297template <class Grid>
1299 int axes = 0, n = 0, last = -1;
1300 for (int a = 0; a < 3; ++a)
1301 if (bc_[2 * a] == 0 && bc_[2 * a + 1] == 0) {
1302 axes |= 1 << a;
1303 ++n;
1304 last = a;
1305 }
1306 if (n >= 2)
1307 fillPeriodicAxes(f, axes);
1308 else if (n == 1)
1309 fillAxis(f, last); // a single-axis fill keeps its own launch
1310}
1311
1312template <class Grid>
1314 return advWallVel_ && !Grid::collocated && hasScene_ && hasMotion_ && advectsMomentum() &&
1315 uBc_[0].extent(0) == n_ && C[0].mask.extent(0) == n_;
1316}
1317
1318template <class Grid>
1320 if (!advWallInputs())
1321 return;
1322 CCExec space;
1323 for (int c = 0; c < 3; ++c) {
1324 if (uwAdv_[c].extent(0) != n_)
1325 uwAdv_[c] = CCField("uwAdv", n_);
1326 Kokkos::deep_copy(uwAdv_[c], C[c].u);
1327 CCField a = uwAdv_[c];
1328 CCConst m = CCConst(C[c].mask), w = CCConst(uBc_[c]);
1329 Kokkos::parallel_for(
1330 "peclet::flow::adv_wall_inputs", Kokkos::RangePolicy<CCExec>(space, 0, (long)n_),
1331 KOKKOS_LAMBDA(long i) {
1332 if (m(i) <= 0.5)
1333 return;
1334 a(i) = w(i);
1335 });
1336 }
1337 space.fence();
1338}
1339
1340template <class Grid>
1342 return advWallInputs() ? CCConst(uwAdv_[c]) : CCConst(C[c].u);
1343}
1344
1345template <class Grid>
1347 return CCConst(c == 0 ? uf_ : (c == 1 ? vf_ : wf_));
1348}
1349
1350template <class Grid>
1352 return (hasOutflow_ && ufOpen_[c].extent(0) == n_) ? CCConst(ufOpen_[c]) : advFaceView(c);
1353}
1354
1355template <class Grid>
1357 if constexpr (Grid::collocated) {
1358 if (!hasOutflow_)
1359 return; // openFaceView then reads uf_ directly: nothing to replace
1360 CCField src[3] = {uf_, vf_, wf_};
1361 for (int a = 0; a < 3; ++a) {
1362 if (ufOpen_[a].extent(0) != n_)
1363 ufOpen_[a] = CCField("peclet::flow::ufOpen", n_);
1364 Kokkos::deep_copy(ufOpen_[a], src[a]);
1365 }
1366 B3 e{e_.x, e_.y, e_.z};
1367 for (int a = 0; a < 3; ++a)
1368 if (bc_[2 * a + 1] == 3 && touchesGlobalFace(2 * a + 1))
1369 bcNeumannGhost(ufOpen_[a], e, G, a, 1);
1370 }
1371}
1372
1373template <class Grid>
1375 return Grid::collocated && ufAdvect_ && faceFieldValid_;
1376}
1377
1378template <class Grid>
1380 ufAdvect_ = on;
1381}
1382
1383template <class Grid>
1385 return ufAdvect_;
1386}
1387
1388template <class Grid>
1389bool Solver<Grid>::ensureAdvStash(int c, bool adv) {
1390 const bool want = !Grid::collocated && hasScene_ && adv;
1391 if (want && advRhs_[c].extent(0) != n_)
1392 advRhs_[c] = CCField("advRhs", n_);
1393 haveAdvRhs_ = want;
1394 return want;
1395}
1396
1397template <class Grid>
1399 // b_a = mu' * w_a (doc/anisotropic_metric.md §2); the FOU part is index-native and unchanged.
1400 const double idiag = rho_ / dt_, fouw = rho_, bx = mu_ * u_.w[0], by = mu_ * u_.w[1],
1401 bz = mu_ * u_.w[2];
1402 C3 e = e_;
1403 ibmBuildDiffusion(C[c].AC, C[c].AW, C[c].AE, C[c].AS, C[c].AN, C[c].AB, C[c].AT, e.x, e.y, e.z,
1404 bx, by, bz, idiag);
1405 CCExec space;
1406 FV AC = C[c].AC, AW = C[c].AW, AE = C[c].AE, AS = C[c].AS, AN = C[c].AN, AB = C[c].AB,
1407 AT = C[c].AT;
1408 // A0: wall-aware inputs (staggered). COLLOCATED: the projected divergence-free face field --
1409 // the implicit FOU operator MUST see the same advecting velocity as the explicit deferred
1410 // (SOU - FOU) correction in buildRhs* or the FOU stops cancelling at steady state
1411 // (ufAdvVelocity()).
1412 const bool ufa = ufAdvVelocity();
1413 CCConst U = ufa ? openFaceView(0) : advVelView(0), V = ufa ? openFaceView(1) : advVelView(1),
1414 W = ufa ? openFaceView(2) : advVelView(2);
1415 using MD = MDRange3<CCExec>;
1416 Kokkos::parallel_for(
1417 "advstencil", MD(space, {G, G, G}, {e.x - G, e.y - G, e.z - G}),
1418 KOKKOS_LAMBDA(int x, int y, int z) {
1419 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
1420 double cC = AC(i), cxm = AW(i), cxp = AE(i), cym = AS(i), cyp = AN(i), czm = AB(i),
1421 czp = AT(i);
1422 sadv::ViewAcc Ua{U, e.x, e.y}, Va{V, e.x, e.y}, Wa{W, e.x, e.y};
1423 Grid::fou_operator(c, x, y, z, Ua, Va, Wa, fouw, cC, cxm, cxp, cym, cyp, czm, czp, ufa);
1424 AC(i) = (MReal)cC;
1425 AW(i) = (MReal)cxm;
1426 AE(i) = (MReal)cxp;
1427 AS(i) = (MReal)cym;
1428 AN(i) = (MReal)cyp;
1429 AB(i) = (MReal)czm;
1430 AT(i) = (MReal)czp;
1431 });
1432
1433 Kokkos::deep_copy(C[c].rscale, 1.0);
1434 Kokkos::deep_copy(C[c].inhom, 0.0);
1435 ibmModifyStencil(C[c].AC, C[c].AW, C[c].AE, C[c].AS, C[c].AN, C[c].AB, C[c].AT, C[c].inhom,
1436 C[c].rscale, C[c].ov, C[c].nCut, 0.0f, wallVelView(c));
1437 if (hasDrag_)
1438 addDragDiagonal(c);
1439}
1440
1441template <class Grid>
1443 C3 e = e_;
1444 if (c == 0) {
1445 if (varProps_)
1446 fillMuGhosts();
1447 if (varRho_)
1448 fillPropGhosts(rhoField_);
1449 if (!varRho_ && porous_ && porousCons_)
1450 updateEpsRho(); // eps ghosts are driver-filled; whole-block product has valid ghosts
1451 }
1452 if (sharpActive_)
1453 ibmBuildDiffusionVar(C[c].AC, C[c].AW, C[c].AE, C[c].AS, C[c].AN, C[c].AB, C[c].AT, e.x, e.y,
1454 e.z, G, makeSharpFaceProps(c, vof::SvRole::kImplicit), u_.w[0], u_.w[1],
1455 u_.w[2]);
1456 else
1457 ibmBuildDiffusionVar(C[c].AC, C[c].AW, C[c].AE, C[c].AS, C[c].AN, C[c].AB, C[c].AT, e.x, e.y,
1458 e.z, G, makeFaceProps(c), u_.w[0], u_.w[1], u_.w[2]);
1459 CCExec space;
1460 FV AC = C[c].AC, AW = C[c].AW, AE = C[c].AE, AS = C[c].AS, AN = C[c].AN, AB = C[c].AB,
1461 AT = C[c].AT;
1462 // A0: wall-aware inputs (staggered). COLLOCATED: the projected divergence-free face field --
1463 // the implicit FOU operator MUST see the same advecting velocity as the explicit deferred
1464 // (SOU - FOU) correction in buildRhs* or the FOU stops cancelling at steady state
1465 // (ufAdvVelocity()).
1466 const bool ufa = ufAdvVelocity();
1467 CCConst U = ufa ? openFaceView(0) : advVelView(0), V = ufa ? openFaceView(1) : advVelView(1),
1468 W = ufa ? openFaceView(2) : advVelView(2);
1469 const bool vr = effVarRho();
1470 const double rhoC = rho_;
1471 CCConst rf = vr ? CCConst(effRhoField()) : CCConst();
1472 const long sc = strideOf(c);
1473 using MD = MDRange3<CCExec>;
1474 Kokkos::parallel_for(
1475 "advstencil_var", MD(space, {G, G, G}, {e.x - G, e.y - G, e.z - G}),
1476 KOKKOS_LAMBDA(int x, int y, int z) {
1477 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
1478 double cC = AC(i), cxm = AW(i), cxp = AE(i), cym = AS(i), cyp = AN(i), czm = AB(i),
1479 czp = AT(i);
1480 sadv::ViewAcc Ua{U, e.x, e.y}, Va{V, e.x, e.y}, Wa{W, e.x, e.y};
1481 const double fouw = vr ? 0.5 * (rf(i) + rf(i - sc)) : rhoC;
1482 Grid::fou_operator(c, x, y, z, Ua, Va, Wa, fouw, cC, cxm, cxp, cym, cyp, czm, czp, ufa);
1483 AC(i) = (MReal)cC;
1484 AW(i) = (MReal)cxm;
1485 AE(i) = (MReal)cxp;
1486 AS(i) = (MReal)cym;
1487 AN(i) = (MReal)cyp;
1488 AB(i) = (MReal)czm;
1489 AT(i) = (MReal)czp;
1490 });
1491 Kokkos::deep_copy(C[c].rscale, 1.0);
1492 Kokkos::deep_copy(C[c].inhom, 0.0);
1493 ibmModifyStencil(C[c].AC, C[c].AW, C[c].AE, C[c].AS, C[c].AN, C[c].AB, C[c].AT, C[c].inhom,
1494 C[c].rscale, C[c].ov, C[c].nCut, 0.0f, wallVelView(c));
1495 if (hasDrag_)
1496 addDragDiagonal(c);
1497}
1498
1499template <class Grid>
1501 CCExec space;
1502 C3 e = e_;
1503 double m = 0;
1504 Kokkos::parallel_reduce(
1505 "maxdiff", MDRange3<CCExec>(space, {G, G, G}, {e.x - G, e.y - G, e.z - G}),
1506 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
1507 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
1508 const double d = Kokkos::fabs(a(i) - b(i));
1509 if (d > acc)
1510 acc = d;
1511 },
1512 Kokkos::Max<double>(m));
1513 return m;
1514}
1515
1516template <class Grid>
1517template <class Fill, class Color, class ColorDu>
1518void Solver<Grid>::velSweepLoop(Fill&& fill, Color&& sweepColor, ColorDu&& sweepColorDu,
1519 std::function<double()> resid, double bnorm) {
1520 double du0 = 0.0;
1521 int used = velIters_;
1522 const double vtol = velocityResidualTolerance();
1523 const bool useRes = vtol > 0.0 && resid;
1524 auto gmax = [&](double v) {
1525#ifdef PECLET_FLOW_MPI
1526 if (distributed_) {
1527 double g = 0.0;
1528 MPI_Allreduce(&v, &g, 1, MPI_DOUBLE, MPI_MAX, comm_);
1529 return g;
1530 }
1531#endif
1532 return v;
1533 };
1534 double scale = 0.0, rPrev = -1.0;
1535 if (useRes) {
1536 // The convergence scale from the initial residual: forcing may enter through a Dirichlet
1537 // ghost (inflow), not b, hence max(|b|, |A u|). NO early return on a converged warm start:
1538 // the projection needs u* to carry the O(rtol) response of the momentum equation (the
1539 // hydrostatic acid test drifts by 1e-8 in dP/dz if the solve is skipped), so at least one
1540 // sweep always runs -- a negligible cost against the 8-9 the solve typically takes.
1541 fill();
1542 (void)gmax(resid());
1543 // F-1: bnorm < 0 = max|b| from the residual functor's evaluation just above (stencilBnorm)
1544 scale = std::max(gmax(bnorm >= 0.0 ? bnorm : lastBNorm_), gmax(lastAxNorm_));
1545 }
1546 // F-2 (doc/vof_projection_cost_design.md §7, the caller's dedupe ruling): a residual check
1547 // that does not stop leaves the ghosts its fill() wrote current -- resid() writes no field the
1548 // fill touches (the stencil / constant-coefficient functors write nothing since F-1; the
1549 // exchanging functor runs with an empty fill) -- so the next iteration's colour-0 fill, the
1550 // same functor on the same field, is skipped (a ghost fill is a function of the inner cells).
1551 // F-2b: the same holds for the scale check above (fill, resid, then the first colour-0 fill).
1552 bool ghostsCurrent = useRes;
1553 for (int it = 0; it < velIters_; ++it) {
1554 if (!ghostsCurrent)
1555 fill();
1556 ghostsCurrent = false;
1557 sweepColor(0);
1558 fill();
1559 if (useRes) {
1560 sweepColor(1);
1561 // check on the first sweep, then every 4th (a residual costs about half a sweep)
1562 if (it == 0 || (it + 1) % 4 == 0 || it + 1 == velIters_) {
1563 fill();
1564 const double r = gmax(resid());
1565 const double ratio = scale > 0 ? r / scale : 0.0;
1566 // Round-off floor / stagnation guard: a residual at ~1e-14 of the scale, or one that no
1567 // longer decreases between checks, cannot be improved by more sweeps -- stop rather than
1568 // chase noise to the cap (an exact case such as the hydrostatic column lands here).
1569 const bool floor = r <= 1e-14 * scale || (rPrev >= 0.0 && r >= rPrev);
1570 rPrev = r;
1571 if (r <= vtol * scale || floor || it + 1 == velIters_) {
1572 lastMomentumResid_ = std::max(lastMomentumResid_, ratio); // EXIT ratio per component
1573 used = it + 1;
1574 break;
1575 }
1576 ghostsCurrent = true;
1577 }
1578 } else if (velTol_ > 0.0) {
1579 double du = sweepColorDu(1);
1580#ifdef PECLET_FLOW_MPI
1581 if (distributed_) {
1582 double gd = 0.0;
1583 MPI_Allreduce(&du, &gd, 1, MPI_DOUBLE, MPI_MAX, comm_);
1584 du = gd;
1585 }
1586#endif
1587 if (it == 0)
1588 du0 = du;
1589 if (it + 1 >= velMinIters_ && du <= velTol_ * du0) {
1590 used = it + 1;
1591 break;
1592 }
1593 } else {
1594 sweepColor(1);
1595 }
1596 }
1597 lastMomentumSweeps_ += used;
1598}
1599
1600template <class Grid>
1602#ifdef PECLET_FLOW_MPI
1603 return comm_;
1604#else
1605 return nullptr;
1606#endif
1607}
1608
1609template <class Grid>
1611 if (hasBc_) {
1612 const int t = bc_[2 * c];
1613 if ((t == 1 || t == 2 || t == 4) && touchesGlobalFace(2 * c))
1614 return c;
1615 }
1616 return -1;
1617}
1618
1619template <class Grid>
1621 if (heldResidualPlane(c) >= 0)
1622 zeroPlane(velRes_, e_, c, G);
1623 lastAxNorm_ = peclet::flow::maxAbsDiffInner(CCConst(C[c].b), CCConst(velRes_), e_, G);
1624 return maxAbsInner(CCConst(velRes_), e_, G);
1625}
1626
1627template <class Grid>
1628std::function<double()> Solver<Grid>::stencilResidual(int c, bool exchange) {
1629 if (velocityResidualTolerance() <= 0.0)
1630 return nullptr;
1631 if (velRes_.extent(0) != n_)
1632 velRes_ = CCField("velRes", n_);
1633 return [this, c, exchange]() {
1634#ifdef PECLET_FLOW_MPI
1635 if (exchange && distributed_)
1636 velDev_->exchange(C[c].u);
1637#else
1638 (void)exchange;
1639#endif
1640 // F-1 (doc/vof_projection_cost_design.md §7): one max reduction, no write of velRes_ (read
1641 // only by finishResidual; the Chebyshev path forms its own); finishResidual's held plane
1642 double rmax = 0.0, bdmax = 0.0, bmax = 0.0;
1643 residualVarPinMax(CCConst(C[c].u), CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW), FPC(C[c].AE),
1644 FPC(C[c].AS), FPC(C[c].AN), FPC(C[c].AB), FPC(C[c].AT), CCConst(C[c].mask),
1645 e_, G, heldResidualPlane(c), G, rmax, bdmax, bmax);
1646 lastAxNorm_ = bdmax;
1647 lastBNorm_ = bmax;
1648 return rmax;
1649 };
1650}
1651
1652template <class Grid>
1653std::function<double()> Solver<Grid>::constCoeffResidual(int c, double bx, double by, double bz,
1654 double Ac) {
1655 if (velocityResidualTolerance() <= 0.0)
1656 return nullptr;
1657 if (velRes_.extent(0) != n_)
1658 velRes_ = CCField("velRes", n_);
1659 const bool an = u_.aniso;
1660 return [this, c, bx, by, bz, Ac, an]() {
1661 const I3 e{e_.x, e_.y, e_.z};
1662 double rmax = 0.0, bdmax = 0.0, bmax = 0.0; // F-1: one max reduction, no write of velRes_
1663 diffResidualMax(CCConst(C[c].u), CCConst(C[c].b), e, G, bx, by, bz, Ac, CCConst(bcDcorr_[c]),
1664 an, heldResidualPlane(c), G, rmax, bdmax, bmax);
1665 lastAxNorm_ = bdmax;
1666 lastBNorm_ = bmax;
1667 return rmax;
1668 };
1669}
1670
1671template <class Grid>
1673 (void)c; // F-1: max|b| comes from the stencil / constant-coefficient residual functors
1674 return velocityResidualTolerance() > 0.0 ? -1.0 : 0.0;
1675}
1676
1677template <class Grid>
1679 if (chebD_.extent(0) != n_)
1680 chebD_ = CCField("chebD", n_);
1681 if (velRes_.extent(0) != n_)
1682 velRes_ = CCField("velRes", n_);
1683 Kokkos::deep_copy(chebD_, 0.0);
1684
1685 auto gmax = [&](double v) {
1686#ifdef PECLET_FLOW_MPI
1687 if (distributed_) {
1688 double g = 0.0;
1689 MPI_Allreduce(&v, &g, 1, MPI_DOUBLE, MPI_MAX, comm_);
1690 return g;
1691 }
1692#endif
1693 return v;
1694 };
1695 auto fill = [&] {
1696#ifdef PECLET_FLOW_MPI
1697 if (distributed_) {
1698 velDev_->exchange(C[c].u);
1699 return;
1700 }
1701#endif
1702 fillGhostsFaces(C[c].u);
1703 };
1704 auto residual = [&] {
1705 residualVarPin(velRes_, CCConst(C[c].u), CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW),
1706 FPC(C[c].AE), FPC(C[c].AS), FPC(C[c].AN), FPC(C[c].AB), FPC(C[c].AT),
1707 CCConst(C[c].mask), e_, G);
1708 };
1709
1710 // The interval must be IDENTICAL on every rank or the iterates diverge from one another, so the
1711 // two Gershgorin bounds are reduced over the communicator before the recurrence starts. They are
1712 // bounds, not estimates: -lo is reduced by MAX to get a global MIN without a second reducer.
1713 double lo = 0.0, hi = 0.0;
1714 ibmStencilJacobiBounds(FPC(C[c].AC), FPC(C[c].AW), FPC(C[c].AE), FPC(C[c].AS), FPC(C[c].AN),
1715 FPC(C[c].AB), FPC(C[c].AT), CCConst(C[c].mask), e_, G, lo, hi);
1716 lo = -gmax(-lo);
1717 hi = gmax(hi);
1718 // A degenerate interval means the operator is not the positive-definite Helmholtz this solver
1719 // assumes (an all-pinned block, or a stencil not yet built). Fall back rather than diverge.
1720 if (!(hi > lo) || !(lo > 0.0)) {
1721 smoothComp(c);
1722 return;
1723 }
1724
1725 const double vtol = velocityResidualTolerance();
1726 const bool useRes = vtol > 0.0;
1727 ChebCoeffs cb(lo, hi);
1728 double scale = 0.0, rPrev = -1.0;
1729 if (useRes) {
1730 // Same convergence scale as velSweepLoop: max(|b|, |A u|) from the initial residual, so the
1731 // two solvers stop on the same criterion at the same tolerance.
1732 fill();
1733 residual();
1734 (void)finishResidual(c);
1735 scale = std::max(gmax(maxAbsInner(CCConst(C[c].b), e_, G)), gmax(lastAxNorm_));
1736 }
1737
1738 int used = velChebMaxit_;
1739 for (int it = 0; it < velChebMaxit_; ++it) {
1740 fill();
1741 residual();
1742 if (useRes && (it == 0 || (it + 1) % 4 == 0 || it + 1 == velChebMaxit_)) {
1743 const double r = gmax(finishResidual(c));
1744 // Round-off floor ONLY -- NOT velSweepLoop's "no decrease between checks" guard. Chebyshev
1745 // minimises a polynomial over the spectral interval, so its max-norm residual is not
1746 // monotone: it rises over the first few iterations before it falls. Carrying the Gauss-
1747 // Seidel stagnation test across aborted the solve after three iterations per component and
1748 // left <u> 3.9 % off the red-black answer. Stagnation is instead caught by the cap.
1749 const bool floor = r <= 1e-14 * scale;
1750 rPrev = r;
1751 if (r <= vtol * scale || floor) {
1752 lastMomentumResid_ = std::max(lastMomentumResid_, scale > 0 ? r / scale : 0.0);
1753 used = it; // this iteration's update is not applied: the iterate already passes
1754 break;
1755 }
1756 }
1757 double alpha = 0.0, beta = 0.0;
1758 cb.next(it, alpha, beta);
1759 ibmChebUpdate(C[c].u, chebD_, CCConst(velRes_), FPC(C[c].AC), CCConst(C[c].mask), e_, G, alpha,
1760 beta);
1761 }
1762 lastMomentumSweeps_ += used;
1763}
1764
1765template <class Grid>
1767 if constexpr (Grid::collocated) {
1768 if (hasBc_) { // collocated domain BC: the (all-fluid) IBM diffusion stencil + cell-centered
1769 // wall
1770 // reflection ghosts refreshed each colour (explicit no-slip; no fold). Converges to the
1771 // wall value.
1772 velSweepLoop([&] { fillVelGhostsTo(C[c].u, c, 0); },
1773 [&](int col) {
1774 ibmRbgsStencilColor(C[c].u, CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW),
1775 FPC(C[c].AE), FPC(C[c].AS), FPC(C[c].AN), FPC(C[c].AB),
1776 FPC(C[c].AT), CCConst(C[c].mask), e_, og_, G, col);
1777 },
1778 [&](int col) {
1779 return ibmRbgsStencilColorDu(C[c].u, CCConst(C[c].b), FPC(C[c].AC),
1780 FPC(C[c].AW), FPC(C[c].AE), FPC(C[c].AS),
1781 FPC(C[c].AN), FPC(C[c].AB), FPC(C[c].AT),
1782 CCConst(C[c].mask), e_, og_, G, col);
1783 },
1784 stencilResidual(c, /*exchange=*/false), stencilBnorm(c));
1785 return;
1786 }
1787 }
1788 if (mixedVelocityMg()) {
1789 // MIXED: immersed solid + domain BCs (the packed bed with an inlet/outlet). Fine = the sharp
1790 // cut-cell stencil, solid pin, clean-fluid exclude + held-face exclude; coarse = staircase
1791 // Helmholtz + domain-face folds (VelocityMG::setStaircaseBc). The BC hook re-imposes the
1792 // level-0 velocity BC after every ghost fill, exactly as the RB-GS path's fillVelGhosts(c,1).
1793 const Off3 off = Grid::offset(c);
1794 ibmVolfrac(vmgTheta_, CCConst(sdf_), e_, off, u_.aniso, u_.hp[0], u_.hp[1], u_.hp[2], u_.w[0],
1795 u_.w[1], u_.w[2]);
1796 ibmCleanFluidMask(vmgClean_, CCConst(sdf_), e_, off);
1797 vmg_.setFineStencil(FPC(C[c].AC), FPC(C[c].AW), FPC(C[c].AE), FPC(C[c].AS), FPC(C[c].AN),
1798 FPC(C[c].AB), FPC(C[c].AT));
1799 // coarse = staircase Helmholtz (+ FOU from the restricted advecting velocity when the fine
1800 // stencil carries implicit advection) + domain-face folds
1801 vmg_.setStaircaseBc(c, CCConst(vmgTheta_), CCConst(C[c].mask), CCConst(vmgClean_), mu_,
1802 rho_ / dt_, 0.5, /*upwind=*/implicitAdv(), rho_);
1803 // fold=0: level 0 is the UNFOLDED cut-cell stencil, so its wall ghosts are reflections
1804 // (exactly the bcStencilPath RB-GS convention); the folded coarse levels hold theirs at 0.
1805 fillVelGhosts(c, 0);
1806 vmg_.setBcApplyL0([this, c](CCField x) { applyVelocityBcCompTo(x, c, 0, true); });
1807 lastMomentumSweeps_ += vmg_.solve(CCConst(C[c].b), C[c].u, vmgVcycles_, 2, 2, 8, velTol_,
1809 lastMomentumResid_ = std::max(lastMomentumResid_, vmg_.lastResidualRatio());
1810 maskVelocity(c);
1811 return;
1812 }
1813 if (bcStencilPath()) {
1814 // Domain BCs solved with the Robust-Scaled cut-cell / FOU stencil (built by setSolid /
1815 // buildAdvStencil) while refreshing the domain-BC ghosts each colour -- explicit walls/inflow
1816 // (reflection, fold=0) + outflow zero-gradient. Mirrors the collocated path above. Used for
1817 // an immersed solid (cut-cell no-slip in the operator) and/or implicit advection (FOU upwind
1818 // in the stencil -> stable at large dt). The const-coeff fold smoothers below are all-fluid,
1819 // diffusion-only: they ignore the solid AND run advection explicitly (CFL-limited).
1820 velSweepLoop([&] { fillVelGhostsTo(C[c].u, c, 0); },
1821 [&](int col) {
1822 ibmRbgsStencilColor(C[c].u, CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW),
1823 FPC(C[c].AE), FPC(C[c].AS), FPC(C[c].AN), FPC(C[c].AB),
1824 FPC(C[c].AT), CCConst(C[c].mask), e_, og_, G, col);
1825 },
1826 [&](int col) {
1827 return ibmRbgsStencilColorDu(C[c].u, CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW),
1828 FPC(C[c].AE), FPC(C[c].AS), FPC(C[c].AN),
1829 FPC(C[c].AB), FPC(C[c].AT), CCConst(C[c].mask), e_,
1830 og_, G, col);
1831 },
1833 return;
1834 }
1835 if (hasBc_ &&
1836 useVelocityMg_) { // domain-BC velocity multigrid: const-coeff aniso op + no-slip/inflow/
1837 // outflow boundary fold on every level (CUDA setDiffusionConstAllLevels +
1838 // setDiffusionBoundaryFold).
1839 vmg_.setDomainBcOp(c, mu_, rho_ / dt_); // per component (the fold is component-dependent)
1841 c, 1); // set the level-0 boundary ghosts (wall fold=0, inflow value, outflow zero-grad)
1842 // Re-impose the velocity BC on the vel-MG's level-0 iterate each colour/residual (the
1843 // const-coeff smoother updates the held Dirichlet faces) -> the vel-MG converges to the RB-GS
1844 // fixed point (not the ~2% drift CUDA's vmg leaves at the boundary corners).
1845 // (the hook applies the BC only: VelocityMG::fill owns the periodic wrap / halo exchange)
1846 vmg_.setBcApplyL0([this, c](CCField x) { applyVelocityBcCompTo(x, c, 1, true); });
1847 lastMomentumSweeps_ += vmg_.solve(CCConst(C[c].b), C[c].u, vmgVcycles_, 2, 2, 8, velTol_,
1849 lastMomentumResid_ = std::max(lastMomentumResid_, vmg_.lastResidualRatio());
1850 return;
1851 }
1852 if (hasBc_) { // domain-BC (no immersed solid): CUDA's double const-coeff diff_k + dcorr fold
1853 // og_ is the GLOBAL block origin (red-black parity); {0,0,0} single-rank, so byte-identical
1854 // there. It was hard-coded {0,0,0} here, which swaps the colours on any rank whose block
1855 // origin has odd parity — the only smoother in the file that did not carry og_.
1856 const I3 e{e_.x, e_.y, e_.z}, og{og_.x, og_.y, og_.z};
1857 // b_a = mu' * w_a; Ac = rho/dt + 2*((bx+by)+bz) in EXACTLY that association order, which is
1858 // fl(6*mu_) at bx==by==bz (doc/anisotropic_metric.md §2, trap 3).
1859 const double bx = mu_ * u_.w[0], by = mu_ * u_.w[1], bz = mu_ * u_.w[2];
1860 const double Ac = rho_ / dt_ + 2.0 * ((bx + by) + bz);
1861 const bool an = u_.aniso;
1862 velSweepLoop([&] { fillVelGhosts(c, 1); }, // re-impose wall faces (fold) before each color
1863 [&](int col) {
1864 diffSmoothColor(C[c].u, CCConst(C[c].b), e, og, G, bx, by, bz, Ac, col,
1865 CCConst(bcDcorr_[c]), an);
1866 },
1867 [&](int col) {
1868 return diffSmoothColorDu(C[c].u, CCConst(C[c].b), e, og, G, bx, by, bz, Ac, col,
1869 CCConst(bcDcorr_[c]), an);
1870 },
1871 constCoeffResidual(c, bx, by, bz, Ac), stencilBnorm(c));
1872 return;
1873 }
1874 if (useVelocityCheb_) {
1875 // Chebyshev momentum solver on the sharp cut-cell stencil. Reached only on the IBM/periodic
1876 // path: the collocated, mixed, bcStencilPath and domain-BC branches above have all returned,
1877 // so a configuration with domain BCs keeps the red-black smoother that owns its ghost fold.
1878 chebSolveComp(c);
1879 maskVelocity(c);
1880 return;
1881 }
1882 if (useVelocityMg_) { // IBM velocity multigrid: fine = sharp As_[c]; coarse op depends on the
1883 // regime.
1884 vmg_.setFineStencil(FPC(C[c].AC), FPC(C[c].AW), FPC(C[c].AE), FPC(C[c].AS), FPC(C[c].AN),
1885 FPC(C[c].AB), FPC(C[c].AT));
1886 if (implicitFou_ && advectsMomentum()) {
1887 // UPWIND-CONVECTIVE coarse op (advection-dominated): aniso const-coeff diffusion + dt*FOU
1888 // from the restricted advecting velocity (restrictAdvVelocities ran once in step()). No pin
1889 // / no exclude mask.
1890 vmg_.buildUpwindCoarse(c, mu_, rho_ / dt_, rho_);
1891 } else {
1892 // STAIRCASE coarse op (diffusion-only): theta classification + clean-fluid exclude (exact
1893 // == RB-GS).
1894 const Off3 off =
1895 Grid::offset(c); // velocity-unknown placement (staggered: -1/2 face; collocated: 0)
1896 ibmVolfrac(vmgTheta_, CCConst(sdf_), e_, off, u_.aniso, u_.hp[0], u_.hp[1], u_.hp[2], u_.w[0],
1897 u_.w[1], u_.w[2]);
1898 ibmCleanFluidMask(vmgClean_, CCConst(sdf_), e_, off);
1899 vmg_.setStaircase(CCConst(vmgTheta_), CCConst(C[c].mask), CCConst(vmgClean_), mu_, rho_ / dt_,
1900 0.5);
1901 }
1902 lastMomentumSweeps_ += vmg_.solve(CCConst(C[c].b), C[c].u, vmgVcycles_, 2, 2, 8, velTol_,
1904 lastMomentumResid_ = std::max(lastMomentumResid_, vmg_.lastResidualRatio());
1905 maskVelocity(c); // re-impose no-slip at solid (the masked solve leaves them at the pin value)
1906 return;
1907 }
1908 // IBM / periodic: Robust-Scaled cut-cell stencil (float). The 7-point smoother reads faces
1909 // only -> the fused 1-kernel face fill suffices.
1910#ifdef PECLET_FLOW_MPI
1911 if (distributed_ && caMomentum_) {
1912 // Communication-avoiding pair (the momentum counterpart of CutcellMG::smooth's CA path):
1913 // ONE 2-deep exchange per red-black pair instead of one per colour — the velocity block is
1914 // g=2 already. Colour 0 overlaps the exchange with the interior sweep, then sweeps the
1915 // boundary shell PLUS the 1-deep ghost ring, redundantly recomputing the neighbour's
1916 // boundary cells from the same operands the neighbour uses (2-deep u ghosts; the ring rows
1917 // of the stencil/mask/rhs are exchanged below, so they are the owner's bit-exact values).
1918 // Colour 1 then sweeps with NO exchange: its boundary cells read only colour-0 ring cells,
1919 // which equal what a fresh exchange would have delivered — bit-identical at half the halo
1920 // events. The tolerance stop's colour-1 kernel is the ORIGINAL full-inner fused reduction
1921 // (host pencil form intact), so du matches the blocking path exactly.
1922 // Stencil + mask ring exchange: once per (re)build. The per-step machinery (implicit-FOU
1923 // Picard rebuilds, variable properties, implicit drag, eps-conservative porous) rewrites the
1924 // stencil every solve, so those paths re-exchange every solve — mirrors the step() rebuild
1925 // gates; a false positive costs 8 extra exchanges, a false negative would break the np>1
1926 // bit-exactness (the ring rows would read a stale operator).
1927 const bool perStepStencil = implicitAdv() || varProps_ || varRho_ || effVarRho() || hasDrag_;
1928 if (momStencilDirty_[c] || perStepStencil) {
1929 for (FV* a : {&C[c].AC, &C[c].AW, &C[c].AE, &C[c].AS, &C[c].AN, &C[c].AB, &C[c].AT})
1930 velDevF_->exchange(*a);
1931 velDev_->exchange(C[c].mask);
1932 momStencilDirty_[c] = false;
1933 }
1934 velDev_->exchange(C[c].b); // rhs ring (owner's inner values); fixed over the sweeps
1935 const C3 lo{G + 1, G + 1, G + 1}, hi{e_.x - G - 1, e_.y - G - 1, e_.z - G - 1};
1936 const C3 rlo{G - 1, G - 1, G - 1}, rhi{e_.x - G + 1, e_.y - G + 1, e_.z - G + 1};
1937 const C3 z0{0, 0, 0};
1939 [] {},
1940 [&](int col) {
1941 if (col == 0) {
1942 velDev_->exchangeBegin(C[c].u);
1943 ibmRbgsStencilColorBox(C[c].u, CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW),
1944 FPC(C[c].AE), FPC(C[c].AS), FPC(C[c].AN), FPC(C[c].AB),
1945 FPC(C[c].AT), CCConst(C[c].mask), e_, og_, col, lo, hi, z0, z0);
1946 velDev_->exchangeEnd(C[c].u);
1947 ibmRbgsStencilColorBox(C[c].u, CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW),
1948 FPC(C[c].AE), FPC(C[c].AS), FPC(C[c].AN), FPC(C[c].AB),
1949 FPC(C[c].AT), CCConst(C[c].mask), e_, og_, col, rlo, rhi, lo,
1950 hi);
1951 } else {
1952 ibmRbgsStencilColor(C[c].u, CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW), FPC(C[c].AE),
1953 FPC(C[c].AS), FPC(C[c].AN), FPC(C[c].AB), FPC(C[c].AT),
1954 CCConst(C[c].mask), e_, og_, G, col);
1955 }
1956 },
1957 [&](int col) {
1958 return ibmRbgsStencilColorDu(C[c].u, CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW),
1959 FPC(C[c].AE), FPC(C[c].AS), FPC(C[c].AN), FPC(C[c].AB),
1960 FPC(C[c].AT), CCConst(C[c].mask), e_, og_, G, col);
1961 },
1962 stencilResidual(c, /*exchange=*/true), stencilBnorm(c));
1963 return;
1964 }
1965 if (distributed_) {
1966 // Overlap the per-colour halo with the interior sweep (the momentum counterpart of the MG
1967 // smoothers' split, 3ace962): post the exchange, sweep the interior cells — whose 7-point
1968 // stencil reads no ghost — while the messages fly, complete it, then sweep the boundary
1969 // shell. A colour's cells never read same-colour cells, so interior-then-shell is
1970 // bit-identical to the blocking exchange + full sweep; the tolerance stop's max-increment
1971 // combines the two passes by max (order-independent). Only this periodic/IBM path overlaps:
1972 // the domain-BC paths re-impose ghost BCs each colour and keep the blocking order (the same
1973 // decision as VelocityMG's overlap). The exchange is posted INSIDE the colour lambda (fill
1974 // is a no-op) so the packed send values are exactly the blocking call's.
1975 const C3 ilo{G, G, G}, ihi{e_.x - G, e_.y - G, e_.z - G};
1976 const C3 lo{G + 1, G + 1, G + 1}, hi{e_.x - G - 1, e_.y - G - 1, e_.z - G - 1};
1977 const C3 z0{0, 0, 0};
1979 [] {},
1980 [&](int col) {
1981 velDev_->exchangeBegin(C[c].u);
1982 ibmRbgsStencilColorBox(C[c].u, CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW), FPC(C[c].AE),
1983 FPC(C[c].AS), FPC(C[c].AN), FPC(C[c].AB), FPC(C[c].AT),
1984 CCConst(C[c].mask), e_, og_, col, lo, hi, z0, z0);
1985 velDev_->exchangeEnd(C[c].u);
1986 ibmRbgsStencilColorBox(C[c].u, CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW), FPC(C[c].AE),
1987 FPC(C[c].AS), FPC(C[c].AN), FPC(C[c].AB), FPC(C[c].AT),
1988 CCConst(C[c].mask), e_, og_, col, ilo, ihi, lo, hi);
1989 },
1990 [&](int col) {
1991 velDev_->exchangeBegin(C[c].u);
1992 const double di = ibmRbgsStencilColorDuBox(
1993 C[c].u, CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW), FPC(C[c].AE), FPC(C[c].AS),
1994 FPC(C[c].AN), FPC(C[c].AB), FPC(C[c].AT), CCConst(C[c].mask), e_, og_, col, lo, hi,
1995 z0, z0);
1996 velDev_->exchangeEnd(C[c].u);
1997 const double ds = ibmRbgsStencilColorDuBox(
1998 C[c].u, CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW), FPC(C[c].AE), FPC(C[c].AS),
1999 FPC(C[c].AN), FPC(C[c].AB), FPC(C[c].AT), CCConst(C[c].mask), e_, og_, col, ilo, ihi,
2000 lo, hi);
2001 return di > ds ? di : ds;
2002 },
2003 stencilResidual(c, /*exchange=*/true), stencilBnorm(c));
2004 return;
2005 }
2006#endif
2007 velSweepLoop([&] { fillGhostsFaces(C[c].u); },
2008 [&](int col) {
2009 ibmRbgsStencilColor(C[c].u, CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW),
2010 FPC(C[c].AE), FPC(C[c].AS), FPC(C[c].AN), FPC(C[c].AB),
2011 FPC(C[c].AT), CCConst(C[c].mask), e_, og_, G, col);
2012 },
2013 [&](int col) {
2014 return ibmRbgsStencilColorDu(C[c].u, CCConst(C[c].b), FPC(C[c].AC), FPC(C[c].AW),
2015 FPC(C[c].AE), FPC(C[c].AS), FPC(C[c].AN),
2016 FPC(C[c].AB), FPC(C[c].AT), CCConst(C[c].mask), e_,
2017 og_, G, col);
2018 },
2019 stencilResidual(c, /*exchange=*/false), stencilBnorm(c));
2020}
2021
2022template <class Grid>
2024 CCExec space;
2025 CCField u = C[c].u, m = C[c].mask;
2026 Kokkos::parallel_for(
2027 "vmask", Kokkos::RangePolicy<CCExec>(space, 0, n_), KOKKOS_LAMBDA(std::size_t i) {
2028 if (m(i) > 0.5)
2029 u(i) = 0.0;
2030 });
2031}
2032
2033template <class Grid>
2035 CCExec space;
2036 C3 e = e_;
2037 CCConst f = CCConst(muField_);
2038 double m = 1e300;
2039 Kokkos::parallel_reduce(
2040 "minmu", MDRange3<CCExec>(space, {G, G, G}, {e.x - G, e.y - G, e.z - G}),
2041 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
2042 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
2043 if (f(i) < acc)
2044 acc = f(i);
2045 },
2046 Kokkos::Min<double>(m));
2047#ifdef PECLET_FLOW_MPI
2048 if (distributed_) {
2049 double g = m;
2050 MPI_Allreduce(&m, &g, 1, MPI_DOUBLE, MPI_MIN, comm_);
2051 m = g;
2052 }
2053#endif
2054 return m;
2055}
2056
2057template <class Grid>
2059 CCExec space;
2060 C3 e = e_;
2061 double m = 0;
2062 Kokkos::parallel_reduce(
2063 "maxabs", MDRange3<CCExec>(space, {G, G, G}, {e.x - G, e.y - G, e.z - G}),
2064 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
2065 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
2066 const double a = Kokkos::fabs(f(i));
2067 if (a > acc)
2068 acc = a;
2069 },
2070 Kokkos::Max<double>(m));
2071 return m;
2072}
2073
2074template <class Grid>
2075std::vector<double> Solver<Grid>::gatherInner(CCField fld) {
2076 auto h = Kokkos::create_mirror_view(fld);
2077 Kokkos::deep_copy(h, fld);
2078 std::vector<double> out((std::size_t)nx_ * ny_ * nz_);
2079 for (int z = 0; z < nz_; ++z)
2080 for (int y = 0; y < ny_; ++y)
2081 for (int x = 0; x < nx_; ++x)
2082 out[(std::size_t)x + (std::size_t)y * nx_ + (std::size_t)z * (std::size_t)nx_ * ny_] =
2083 h((long)(x + G) + (long)(y + G) * e_.x + (long)(z + G) * (long)e_.x * e_.y);
2084 return out;
2085}
2086
2087template <class Grid>
2088void Solver<Grid>::scatterInner(CCField fld, const std::vector<double>& in) {
2089 if (in.size() != (std::size_t)nx_ * ny_ * nz_)
2090 throw std::runtime_error("flow::setField: array size does not match the inner grid");
2091 auto h = Kokkos::create_mirror_view(fld);
2092 Kokkos::deep_copy(h, fld); // preserve existing ghosts
2093 for (int z = 0; z < nz_; ++z)
2094 for (int y = 0; y < ny_; ++y)
2095 for (int x = 0; x < nx_; ++x)
2096 h((long)(x + G) + (long)(y + G) * e_.x + (long)(z + G) * (long)e_.x * e_.y) =
2097 in[(std::size_t)x + (std::size_t)y * nx_ + (std::size_t)z * (std::size_t)nx_ * ny_];
2098 Kokkos::deep_copy(fld, h);
2099}
2100
2101template <class Grid>
2102CCField Solver<Grid>::addField(const std::string& name) {
2103 if (fields_.has(name))
2104 return fields_.at(name).data;
2105 return fields_.add(name, n_, G, peclet::core::Centering::Cell).data;
2106}
2107
2108template <class Grid>
2109bool Solver<Grid>::hasField(const std::string& name) const {
2110 return fields_.has(name);
2111}
2112
2113template <class Grid>
2114CCField Solver<Grid>::fieldView(const std::string& name) {
2115 return fields_.at(name).data;
2116}
2117
2118template <class Grid>
2119std::vector<std::string> Solver<Grid>::fieldNames() const {
2120 return fields_.names();
2121}
2122
2123template <class Grid>
2124void Solver<Grid>::exchangeField(const std::string& name) {
2125 fillGhosts(fields_.at(name).data);
2126}
2127
2128template <class Grid>
2129void Solver<Grid>::exchangeFieldAdd(const std::string& name) {
2130#ifdef PECLET_FLOW_MPI
2131 if (distributed_ && velHalo_) {
2132 CCField f = fields_.at(name).data;
2133 auto h = Kokkos::create_mirror_view(f);
2134 Kokkos::deep_copy(h, f);
2135 peclet::core::halo::GridFieldView<double> view{h.data()};
2136 velHalo_->reverseAdd(view);
2137 Kokkos::deep_copy(f, h);
2138 }
2139#else
2140 (void)name;
2141#endif
2142}
2143
2144template <class Grid>
2145std::vector<double> Solver<Grid>::getField(const std::string& name) {
2146 return gatherInner(fields_.at(name).data);
2147}
2148
2149template <class Grid>
2150void Solver<Grid>::setField(const std::string& name, const std::vector<double>& v) {
2151 scatterInner(fields_.at(name).data, v);
2152 if (name == "u" || name == "v" || name == "w" || name == "p" || name == "phi")
2153 pguessCount_ = 0; // E: a state write (doc/vof_projection_cost_design.md §5.3)
2154 // The balanced-force split (doc/collocated_varrho_forces.md §4.6.2): a restart that restores
2155 // the pressure must restore "p_balanced" with it, or the next ON step re-splits. Flags only.
2156 if (name == "p")
2157 pWritten_ = true;
2158 else if (name == "p_balanced")
2159 pbWritten_ = true;
2160}
2161
2162template <class Grid>
2163std::array<int, 3> Solver<Grid>::blockShape() const {
2164 return {e_.x, e_.y, e_.z};
2165}
2166
2167template <class Grid>
2169 return G;
2170}
2171
2172template <class Grid>
2173std::array<int, 3> Solver<Grid>::globalResolution() const {
2174#ifdef PECLET_FLOW_MPI
2175 if (distributed_)
2176 return {gnx_, gny_, gnz_};
2177#endif
2178 return {nx_, ny_, nz_};
2179}
2180
2181template <class Grid>
2182std::array<int, 3> Solver<Grid>::blockOrigin() const {
2183 return {og_.x, og_.y, og_.z};
2184}
2185
2186template <class Grid>
2188 rhoFaceHarmonic_ = on;
2189 bfpChebSet_ = false; // a different face mean: the pre-projection's kept bounds are stale
2190}
2191
2192template <class Grid>
2194 exactResidual_ = on;
2195 mg_.setExactResidual(on);
2196}
2197
2198template <class Grid>
2200 outflowOpCoeff_ = on;
2201}
2202
2203template <class Grid>
2205 return outflowOpCoeff_;
2206}
2207
2208template <class Grid>
2210 return exactResidual_;
2211}
2212
2213template <class Grid>
2215 return rhoFaceHarmonic_;
2216}
2217
2218template <class Grid>
2220 outflowRhoCorr_ = on;
2221}
2222
2223template <class Grid>
2225 return outflowRhoCorr_;
2226}
2227
2228template <class Grid>
2229CCField Solver<Grid>::ensureTarget(const std::string& name) {
2230 if (name == "force_x" || name == "force_y" || name == "force_z")
2231 ensureCellForceAll();
2232 return addField(name); // idempotent; returns the (now-existing) buffer
2233}
2234
2235template <class Grid>
2236void Solver<Grid>::ensureCellForceAll() {
2237 static const char* fn[3] = {"force_x", "force_y", "force_z"};
2238 for (int c = 0; c < 3; ++c)
2239 cellForce_[c] = addField(fn[c]); // zero-initialised, registered
2240 hasCellForce_ = true;
2241}
2242
2243} // namespace peclet::flow
2244
2245#endif // PECLET_FLOW_FLOW_IBM_CORE_HPP
int pressureBottomExtent() const
void setPressureLineRelaxation(bool enabled)
void setPressureMeanRemoval(bool all)
double multigridAspectThreshold() const
bool pressureVcycleFp32() const
std::array< int, 3 > globalResolution() const
void setPhysicalDomain(const std::array< double, 3 > &extent, const std::array< double, 3 > &origin, const std::array< long, 3 > &globalCells)
Arm the physical domain.
void fillVelGhosts(int comp, int fold)
void setIncrementalPressure(bool on)
std::function< double()> constCoeffResidual(int c, double bx, double by, double bz, double Ac)
void setVelocityTolerance(double rtol, int minIters)
bool pressureCoarseGhost() const
void scatterInner(CCField fld, const std::vector< double > &in)
bool advectsMomentum() const
void buildOpenFaceField()
Build ufOpen_ = the face field with each open (outflow) domain face overwritten by its zero-gradient ...
void fillGhosts(CCField f)
long lastOuterIterations() const
long pressurePrefactorCount() const
double decompositionMaxImbalance() const
void fillDomainPeriodic(CCField f)
void setPressureCoarseGhost(bool on)
Neumann (zero-gradient) coarse ghost on wall/inflow faces before the pressure MG's prolongation — the...
bool advWallInputs() const
R0 helper: allocate (once) and arm the per-component advective-term stash the reaction-force budget c...
void setUfAdvection(bool on)
Advect the collocated momentum with the PROJECTED, divergence-free MAC face field uf_/vf_/wf_ (DEFAUL...
void fillPropGhosts(CCField f, bool edges=false)
void setFaceInterp(int mode)
std::vector< double > getField(const std::string &name)
void setOutflowRhoCorrection(bool on)
void setVelocityChebyshev(bool on, int maxit=400)
void setOpennessOverride(const std::vector< double > &ox, const std::vector< double > &oy, const std::vector< double > &oz)
void setOuterTolerance(double tol)
CCField addField(const std::string &name)
double lastMomentumResidual() const
std::array< double, 3 > domainOrigin() const
Physical lower corner of the GLOBAL inner grid.
void setPressureGraphAmg(bool on)
VelocityMG::Comm vmgComm() const
double velocityResidualTolerance() const
void setPressureTelescope(bool on)
void setPressureStrict(bool on)
Throw instead of reporting when the pressure preconditioner returns a non-finite correction (ISSUES s...
void fillGhostsFaces(CCField f)
bool advectionWallVelocity() const
void exchangeFieldAdd(const std::string &name)
CCConst advVelView(int c) const
The velocity view the advection operators must read for component c: the wall-corrected scratch while...
void exchangeField(const std::string &name)
void setAdvection(bool on)
std::array< long, 3 > globalCells() const
The GLOBAL cell counts (this rank's block single-rank).
void setPressureExactResidual(bool on)
WO-R2 item 3 — the exact (matrix-free, double, flux-form) level-0 operator apply in the residual and ...
void uploadVelocity(const std::vector< double > &uu, const std::vector< double > &vv, const std::vector< double > &ww)
Upload an initial velocity field in the caller's PHYSICAL units (converted per component to the index...
bool outflowRhoCorrection() const
void copyInner(CCField dst, C3 de, int dg, CCConst src, C3 se, int sg)
void requireNoGeometry(const char *who) const
void applyVelocityBcCompTo(CCField f, int comp, int fold, bool doOutflow)
void setPressureVcycleSymmetric(bool enabled)
double maxAbsDiffInner(CCConst a, CCConst b)
void fillPeriodicAxes(CCField f, int axes)
void requireIsotropic(const char *what) const
Phase 2 §7 — refuse an ANISOTROPIC domain in a consumer this phase does not carry.
void setBackflowStab(double beta)
std::array< double, 3 > spacing() const
Cell size per axis (equal on every axis unless the Phase 2 anisotropic path is armed – see unitScales...
bool velocityChebyshevActive() const
void setVelocityIterations(int it)
double finishResidual(int c)
bool ufAdvVelocity() const
Are the advection operators reading the projected face field this step?
void setPressureChebyshev(bool on, int maxit, double rtol)
const UnitScales & unitScales() const
CCConst openFaceView(int c) const
Component c of the face field AS THE ADVECTION AND THE DIVERGENCE DIAGNOSTIC MUST READ IT: advFaceVie...
bool pressureStrict() const
Solver(int nx, int ny, int nz)
void setPressureInitialGuess(int mode, int history)
void setGhostProjection(bool on, int matrixOrder=2, int rhsOrder=2)
CCConst advFaceView(int c) const
Component c of the collocated MAC face field (uf_/vf_/wf_), flow's low-face convention: entry i is th...
long lastMomentumSweeps() const
void setPressureLevels(int levels)
std::array< int, 3 > blockOrigin() const
void setFluidOnlyConstraint(int mode)
void setRotationalPressure(bool on)
void setDeferredCorrection(bool on)
void resampleBcProfile(int face)
void setPressureVcyclePrecision(int mode)
static constexpr int G
Definition flow_ibm.hpp:82
int pressureGuessCount() const
SceneMap sceneMap() const
void setCommAvoiding(int mask)
Communication-avoiding red-black smoothing: kCaMomentum | kCaMg.
void fillAxis(CCField f, int axis)
void setAdvectionWallVelocity(bool on)
A0 — wall velocity (not zeros) in the advection inputs' masked rows. DEFAULT true.
void setField(const std::string &name, const std::vector< double > &v)
void setApertureOrder(int order)
double lastSuperficialVelocityShift() const
The shift the last step() applied (caller's velocity units; 0 when off).
void setBodyForce(double fx, double fy, double fz)
Body force per unit volume, in the caller's units (e.g. a mean pressure gradient, or rho*g).
void closureRefreshUnits(Closure &cl)
Re-derive a closure's internal p / tabY from its physical pPhys / tabYPhys with the current reference...
std::array< int, 3 > blockShape() const
void setRhoFaceHarmonic(bool on)
bool pressureExactResidual() const
long strideOf(int c) const
void fillVelGhostsTo(CCField f, int comp, int fold, bool doOutflow=true, bool faceEdges=false)
bool hasField(const std::string &name) const
void debugSetPressureFp32Fault(int kind, int at)
void setAdvectionScheme(int s)
void throwVelocityMgVariableMu(const char *who) const
int pressureTelescopeCount() const
void setPressurePcg(bool on, int maxit, double rtol)
void setVelocityMultigridAuto(long cellsPerRank, long minGlobalCells=-1, int minBlockExtent=-1)
void allocateBlock(int nx, int ny, int nz)
const char * projectedGuessIneligible() const
int pressureVcycleRestarts() const
void setVelocityMultigrid(bool on, int levels, int vcycles)
void setRotationalWeight(double w)
void setMu(double m)
Dynamic viscosity, in the caller's units.
void setDecomposition(int levels, double maxImbalance=1.05)
How the shared level-0 MPI decomposition is built.
void setExactCrossings(const std::vector< double > &t)
void setPressureWarmstart(bool on)
void velSweepLoop(Fill &&fill, Color &&sweepColor, ColorDu &&sweepColorDu, std::function< double()> resid=nullptr, double bnorm=0.0)
void setPressureIterations(int it)
Kokkos::View< MReal *, CCMem > FV
Definition flow_ibm.hpp:81
bool velocityMgChebyshev() const
int heldResidualPlane(int c) const
void refreshUnitDerived()
Re-derive every internal (index-unit) quantity from the stored physical inputs.
void setPressureBottomSolver(int engine)
void setPressureTelescopeForceLevel(int level)
CCField fieldView(const std::string &name)
void pushVofMetric()
Hand the anisotropic cell metric to every VoF driver that exists (Phase 3).
void setCollocatedScheme(const std::string &name)
void setVelocityMgChebyshev(bool on, int degree=0, double eig_ratio=10.0)
void setPressureBottomExtent(int cells)
The set_pressure_bottom("auto") criterion: agglomerate once the coarsest GLOBAL grid exceeds this man...
bool ensureAdvStash(int c, bool adv)
void setOutflowOperatorCoefficient(bool on)
WO-R2 item 1 ABLATION: set_outflow_operator_coefficient(False) restores the pre-WO-R2 operator,...
void setImplicitAdvection(bool on)
void setVelocityResidualTolerance(double rtol)
vof::SharpFaceProps makeSharpFaceProps(int c, vof::SvRole role)
std::function< double()> stencilResidual(int c, bool exchange=false)
void setPressureBottomMode(int mode)
VarFaceProps makeFaceProps(int c)
void setRotationalWallWeight(double w0)
bool pressureTelescope() const
double reduceMaxAbsInner(CCConst f)
void setRho(double r)
Fluid density, in the caller's units.
void setRotationalFilter(bool on, double eps=0.05)
bool velocityMultigridActive() const
std::array< double, 3 > domainExtent() const
Physical extent of the GLOBAL inner grid (cell counts without a physical domain).
std::vector< std::string > fieldNames() const
std::vector< double > gatherInner(CCField fld)
void setSuperficialVelocity(bool on, int axis, double velocity)
Hold the SUPERFICIAL velocity along a periodic axis: at the end of every step() one uniform shift is ...
std::vector< double > cellCentres(int axis) const
Physical cell-centre coordinates of THIS rank's inner block along axis (nx/ny/nz values).
void copyBlockShifted(CCField dst, C3 de, CCConst src, C3 se, int off)
void pcRefreshUnits()
Re-derive the INTERNAL phase-change constants (pcRhoG_ ... pcRcpL_) from the caller's physical ones (...
int decompositionLevels() const
CCConst wallVelView(int c) const
bool outflowOperatorCoefficient() const
void setPressureFcg(bool on, int maxit, double rtol)
void setMultigridAspectThreshold(double theta)
The anisotropic-coarsening aspect threshold theta shared by the pressure and velocity multigrids (doc...
void setOuterIterations(int iters)
bool hasPhysicalDomain() const
void zeroPlane(CCField m, C3 e, int axis, int idx)
Kokkos::DefaultExecutionSpace CCExec
void residualVarPinMax(CCConst x, CCConst b, FPC AC, FPC AW, FPC AE, FPC AS, FPC AN, FPC AB, FPC AT, CCConst pin, C3 e, int g, int holdAxis, int holdIdx, double &rmax, double &bdmax, double &bmax)
Kokkos::MDRangePolicy< Exec, Kokkos::Rank< 3, Kokkos::Iterate::Left, Kokkos::Iterate::Left > > MDRange3
3-D range, x (the first index) fastest (both the tile order and the order within a tile).
Definition policy.hpp:36
void ibmChebUpdate(CCField x, CCField d, CCConst r, FPC AC, CCConst solidmask, C3 e, int g, double alpha, double beta)
One Chebyshev update on the Jacobi-preconditioned system: d <- beta*d + alpha*r/AC ; x += d.
void ibmCleanFluidMask(CCField m, CCConst sdf, C3 ext, Off3 off)
Definition mac_ibm.hpp:262
Kokkos::View< const double *, CCMem > CCConst
void ibmStencilJacobiBounds(MC AC, MC AW, MC AE, MC AS, MC AN, MC AB, MC AT, CCConst solidmask, C3 e, int g, double &lo, double &hi)
Gershgorin bounds [lo, hi] on the spectrum of the Jacobi-preconditioned cut-cell Helmholtz diag(AC)^-...
void ibmBuildDiffusionVar(MV AC, MV AW, MV AE, MV AS, MV AN, MV AB, MV AT, int ex, int ey, int ez, int g, FaceProps fp, double wx=1.0, double wy=1.0, double wz=1.0)
void ibmModifyStencil(MV AC, MV AW, MV AE, MV AS, MV AN, MV AB, MV AT, Kokkos::View< double *, IMem > a_inhom, Kokkos::View< double *, IMem > rhs_scale, const OV &ibm, int numActive, typename OV::value_type u_bc_val, Kokkos::View< const double *, IMem > u_bc=Kokkos::View< const double *, IMem >())
void ibmVolfrac(CCField theta, CCConst sdf, C3 ext, Off3 off, bool aniso=false, double hpx=1.0, double hpy=1.0, double hpz=1.0, double wx=1.0, double wy=1.0, double wz=1.0)
Definition mac_ibm.hpp:188
void residualVarPin(CCField r, CCConst x, CCConst b, FPC AC, FPC AW, FPC AE, FPC AS, FPC AN, FPC AB, FPC AT, CCConst pin, C3 e, int g)
double diffSmoothColorDu(SField c, SConst b, I3 e, I3 og, int g, double bx, double by, double bz, double Ac, int color, SConst dcorr, bool aniso)
Kokkos::View< const MReal *, CCMem > FPC
void centerToFaceWallAware(CCField uf, CCField vf, CCField wf, CCConst U, CCConst V, CCConst W, CCConst sdf, CCConst xcx, CCConst xcy, CCConst xcz, bool useCen, C3 e, int g)
double maxAbsInner(CCConst a, C3 e, int g)
Kokkos::View< double *, CCMem > CCField
void ccFor3(const char *name, C3 lo, C3 hi, F f)
void centerToFace(CCField uf, CCField vf, CCField wf, CCConst U, CCConst V, CCConst W, C3 e, int g)
IbmOverlayT< IMem, mreal > IbmOverlay
Definition mac_ibm.hpp:33
double maxAbsDiffInner(CCConst a, CCConst b, C3 e, int g)
void ibmRbgsStencilColorBox(CCField x, CCConst b, MC AC, MC AW, MC AE, MC AS, MC AN, MC AB, MC AT, CCConst solidmask, C3 ext, C3 og, int color, C3 rlo, C3 rhi, C3 slo, C3 shi)
Definition mac_ibm.hpp:410
double ibmRbgsStencilColorDuBox(CCField x, CCConst b, MC AC, MC AW, MC AE, MC AS, MC AN, MC AB, MC AT, CCConst solidmask, C3 ext, C3 og, int color, C3 rlo, C3 rhi, C3 slo, C3 shi)
Definition mac_ibm.hpp:446
void ibmBuildDiffusion(MV AC, MV AW, MV AE, MV AS, MV AN, MV AB, MV AT, int ex, int ey, int ez, double bx, double by, double bz, double idiag)
double ibmRbgsStencilColorDu(CCField x, CCConst b, MC AC, MC AW, MC AE, MC AS, MC AN, MC AB, MC AT, CCConst solidmask, C3 ext, C3 og, int g, int color)
Definition mac_ibm.hpp:342
bool hostRunSerial(long cells)
void bcNeumannGhost(BField f, B3 ext, int g, int a, int s)
Definition mac_bc.hpp:265
void ibmRbgsStencilColor(CCField x, CCConst b, MC AC, MC AW, MC AE, MC AS, MC AN, MC AB, MC AT, CCConst solidmask, C3 ext, C3 og, int g, int color)
Definition mac_ibm.hpp:287
void diffResidualMax(SConst c, SConst b, I3 e, int g, double bx, double by, double bz, double Ac, SConst dcorr, bool aniso, int holdAxis, int holdIdx, double &rmax, double &bdmax, double &bmax)
Kokkos::MDRangePolicy< Exec, Kokkos::Rank< 2, Kokkos::Iterate::Left, Kokkos::Iterate::Left > > MDRange2
2-D range, first index fastest (both the tile order and the order within a tile).
Definition policy.hpp:31
void diffSmoothColor(SField c, SConst b, I3 e, I3 og, int g, double bx, double by, double bz, double Ac, int color, SConst dcorr, bool aniso)
The Chebyshev coefficient recurrence (Golub-Varga; the form multigrid Chebyshev smoothers use).
void next(int it, double &alpha, double &beta)
Coefficients for iteration it (0-based). Advances the recurrence.
The map between the solver's INDEX coordinates and the coordinate system the analytic scene is writte...
Definition flow_ibm.hpp:243
static constexpr int N
static constexpr double AC
Kokkos::View< float *, IMem > FV
static constexpr double U