flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
flow_ibm_project.hpp
Go to the documentation of this file.
1
8#ifndef PECLET_FLOW_FLOW_IBM_PROJECT_HPP
9#define PECLET_FLOW_FLOW_IBM_PROJECT_HPP
10
11namespace peclet::flow {
12
13template <class Grid>
15 // The step*() phases are contiguous blocks of this function, called in their original order
16 // (WO-HO): launches, fences, halo/MPI calls and the refusals keep their order inside them.
17 stepPrechecks();
18
19 // The momentum-solver choice, for a configuration that never calls set_solid. set_solid is the
20 // other (and historically the only) place it is made; a domain-BC case with no immersed solid
21 // never reaches it, which is why enabling the velocity MG there used to build no hierarchy and
22 // segfault. Deciding at the head of the first step is if anything more correct than deciding in
23 // set_solid: every flag the eligibility test reads (advection scheme, variable properties,
24 // drag, porous) is final by now, whereas at set_solid time it need not be.
25 if (!vmgDecided_) {
28 vmgDecided_ = true;
29 }
30 const double ts0 = phaseTick();
31 tPredictor_ = tMomentum_ = tProjection_ = 0.0;
32 lastMomentumSweeps_ = 0;
33 lastMomentumResid_ = -1.0;
34 mg_.resetAllreduceCounters();
35 const bool hoisted = stepHeadFields();
36 stepStencils();
37 const bool fullStress = stepTimeBase();
38 stepPressureGhosts();
39 stepBalancedForce(hoisted);
40 lastOuterIters_ = 0;
41 for (int outer = 0; outer < outerIters_; ++outer) {
42 const double tp0 = phaseTick();
43 lastOuterIters_ = outer + 1;
44 if (outerTol_ > 0)
45 for (int c = 0; c < 3; ++c)
46 Kokkos::deep_copy(prev_[c], C[c].u);
47 stepPredictorInputs();
48 const bool coloFF = stepPredictorRhs();
49 stepPredictorForces(coloFF, fullStress);
50 stepPredictorOperator();
51 stepPredictorCoarseAdvection();
52 const double tp1 = phaseTick();
53 tPredictor_ += tp1 - tp0;
54 stepMomentumSolve();
55 const double tp2 = phaseTick();
56 tMomentum_ += tp2 - tp1;
57 stepProjection();
58 tProjection_ += phaseTick() - tp2;
59 stepPostProjection();
60 if (outerTol_ > 0) { // outer convergence: max velocity change over this Picard iteration
61 double corr = 0.0;
62 for (int c = 0; c < 3; ++c)
63 corr = Kokkos::fmax(corr, maxAbsDiffInner(CCConst(C[c].u), CCConst(prev_[c])));
64 lastOuterCorr_ = corr;
65 if (corr < outerTol_)
66 break;
67 }
68 }
69 stepTransport();
70 stepBackflowWarning();
71 tStep_ = phaseTick() - ts0;
72 if (vofTiming_) { // WO-V9: the coarse phases, summed over the profiled window
73 tStepSum_ += tStep_;
74 tPredSum_ += tPredictor_;
75 tMomSum_ += tMomentum_;
76 tProjSum_ += tProjection_;
77 ++vt_.steps;
78 }
79}
80
81template <class Grid>
82void Solver<Grid>::stepPrechecks() {
83 // ISSUES sweep item 1 (VOF_PLAN section 13 item 9): make `step()` ATOMIC across the two
84 // explicit two-phase stability throws. Both used to fire AFTER the momentum half had already
85 // advanced by the rejected dt -- the Weymouth-Yue boundedness cap from inside `advectVof`
86 // (which runs at the TAIL of the step without momentum consistency) and the Brackbill
87 // capillary cap from `updateVofCurvature` (which runs after `advectVofMomentum`). So the
88 // obvious driver pattern -- catch, halve dt, retry -- gave the momentum equation one extra
89 // over-long step the colour never saw, i.e. it DESYNCHRONISED the two fields instead of
90 // retrying. Both checks are now evaluated here, at the head of `step()` and before the first
91 // mutator, so a throw leaves every field bitwise as it was on entry. No-op unless VoF is on.
92 vofStepPrecheck();
93 superficialVelocityPrecheck(); // its scope, before the first mutator (same reason)
94 // The configuration refusals of rung V8 (S0: all-fluid, no ghost projection, no harmonic rho_f,
95 // incremental pressure) and of the balanced-force projection (§4.6.4), HERE beside the VoF
96 // pre-check -- before advectVofMomentum, phaseChangeStep and updateProperties -- so a refused
97 // step also leaves every field bitwise as it was. Inert (no check at all) off those paths.
98 if (colocatedFaceForce())
99 requireCollocatedFaceForceScope("step");
100 if (balancedForceActive())
101 requireBalancedForceScope("step", true);
102 // The viscous stress form: AUTO (the default, WO-7) resolves here -- no refusal, laplacian plus a
103 // one-time notice off the full stress's scope; an explicit "full" gets the §5.6 refusals
104 // (constant mu: inert either way).
105 if (viscousStressAuto_)
106 resolveViscousStressAuto();
107 else if (fullStress_ && varProps_)
108 requireFullStressScope("step");
109 resolveSharpViscous(); // the sharp interface (inert unless requested; refusals here)
110}
111
112template <class Grid>
113bool Solver<Grid>::stepHeadFields() {
114 // Momentum-consistent geometric VoF (rung V2b, WO-K): the colour field and rho^c u_c are
115 // advanced TOGETHER, by the same fluxes, at the head of the step — the momentum advection has
116 // to precede the predictor that consumes it. The advecting field is u^n, the previous step's
117 // projected (discretely divergence-free) output. No-op unless enable_vof_momentum ran; when it
118 // has NOT, the colour advection keeps WO-J's slot at the bottom of the step and this path is
119 // byte-identical to V2a. See enableVofMomentum().
120 advectVofMomentum();
121 // Phase change (rungs P0/P1, WO-P01): mdot + the PLIC areas/normals from (C^n, T^n), the
122 // divergence source deposit read by project(), and the interface regression applied to the
123 // SAME C^n the planes came from. No-op (byte-identical) unless enable_phase_change ran.
124 {
125 const double _t0 = vofTick(); // WO-V9
126 phaseChangeStep();
127 vofAdd(vt_.phaseChange, _t0);
128 }
129 // Multiphysics: refresh material properties / body forces from the current fields (frozen over
130 // the step). No-op (byte-identical) when no closure is registered.
131 updateProperties();
132 // X (doc/vof_gpu_coarse_tail_design.md §5.6): the variable-rho operator of this step, and its
133 // bottom factor on a side instance, NOW -- nothing below writes rho, rho1_, the openness bridge
134 // or the MG level-0 coefficients before project(), and nothing reads them but project() (the
135 // audit in the WO-X commit). project() then skips its build (coeffBuiltThisStep_).
136 const bool hoisted = prefactorHoistEligible();
137 if (hoisted) {
138 projectBuildCoefficients();
139 mg_.prefactorBottom();
140 }
141 // WO-G: give the per-cell body force the ghost ring its consumer assumes. This is the ONE point
142 // in the step that is after BOTH writers (the closures just above; an external CFD-DEM
143 // field_view/exchange_field_add deposit, which happens before step()) and before every consumer
144 // (buildRhsVar in the Picard loop). Inert when no force field is registered.
145 fillCellForceGhosts();
146 // WO-I: and the same for the per-cell drag coefficient, for the same reason one phase earlier.
147 // Same call site, same justification: after BOTH writers, before the FIRST consumer (the
148 // momentum stencil builds just below). See fillDragBetaGhosts().
149 fillDragBetaGhosts();
150 // Rung V4 (WO-P): the interface curvature of the colour field this step will run with, and the
151 // explicit capillary stability check. No-op (byte-identical) unless set_surface_tension ran.
152 {
153 const double _t0 = vofTick(); // WO-V9
154 updateVofCurvature();
155 vofAdd(vt_.curvature, _t0);
156 }
157 // eps-conservative porous momentum: the volume-averaged time term is (eps_f rho/dt) u, i.e.
158 // the variable-density machinery with the effective density rho_eff = eps*rho, refreshed from
159 // the just-deposited eps every step (eps ghosts are already filled by the coupling driver, so
160 // the whole-block product has valid ghosts). Without this weight the plain-u momentum lets the
161 // projection drag gas along with the moving porosity at zero inertia cost — a spurious energy
162 // source that pumps the particles through the drag (measured in the HCS benchmark).
163 if (porous_ && porousCons_)
164 updateEpsRho();
165 return hoisted;
166}
167
168template <class Grid>
169void Solver<Grid>::stepStencils() {
170 // The sharp viscous interface: planes + band classes of this step's colour, before the bands.
171 if (sharpActive_)
172 sharpViscousGeometry();
173 // Variable properties / implicit drag: rebuild the diffusion stencil from the current mu/rho
174 // and drag_beta fields (the implicit-FOU path rebuilds it per Picard in buildAdvStencil*, so
175 // only the non-advective path needs this).
176 if (((varProps_ || varRho_ || hasDrag_ || (porous_ && porousCons_)) || dtDirty_) &&
177 !implicitAdv())
178 rebuildStencils();
179 dtDirty_ = false; // implicit-FOU rebuilds per Picard below (reads dt_ live) — clear either way
180}
181
182template <class Grid>
183bool Solver<Grid>::stepTimeBase() {
184 // u^n time base, fixed for the whole step (Picard lags the advecting velocity at u^k, not the
185 // base).
186 for (int c = 0; c < 3; ++c)
187 Kokkos::deep_copy(CCExec(), old_[c], C[c].u); // S4: instance-ordered, no global fence
188 // Full viscous stress (doc/full_viscous_stress.md §4.3): the once-per-step prelude -- mu
189 // uniformity test, u^n ghosts incl. edges, regular-node masks. Inert unless requested.
190 const bool fullStress = fullStressActive();
191 if (fullStress)
192 fullStressPrelude();
193 if (sharpActive_ && fullStress)
194 sharpViscousFit();
195 // Review F6: a globally uniform mu skips the transpose (and the fit), so the sharp cell link's
196 // WO-5b split -- 2 mu implicit, 0 explicit -- would leave mu d_cc u_c too much. Only reachable
197 // with interfacial cells everywhere at one colour (a uniform "mixture" C): the interface is
198 // inert this step and the bands built above are rebuilt without it (the implicit-FOU path
199 // builds them per Picard below, after this).
200 if (sharpActive_ && fullStress && muUniform_) {
201 sharpActive_ = false;
202 if (!implicitAdv())
203 rebuildStencils();
204 }
205 return fullStress;
206}
207
208template <class Grid>
209void Solver<Grid>::stepPressureGhosts() {
210 if (cutcellPressure_ && incremental_) {
211 fillGhosts(P_);
212 if (hasBc_)
213 pressureBcGhost();
214 } // grad(P^n) for the incremental predictor (once)
215 // Rung V8 (doc/collocated_varrho_forces.md §4.2; its scope was checked at the step head).
216 if (colocatedFaceForce()) {
217 // The density ghosts under the PROPERTY ghost policy (Neumann copy at walls) — the same values
218 // the Poisson coefficient reads in projectBuildCoefficients (§4.9 L4: the operator's rho_f,
219 // the predictor's rho_f and Pi_rho's mass weights see the same cell rho). A bare halo fill
220 // wraps a wall's ghost periodically, and Pi_rho would then carry the near-wall velocity onto
221 // the closed wall face (a spurious transport flux; the constraint itself ignores that face).
222 if (effVarRho())
223 fillPropGhosts(effRhoField());
224 }
225}
226
227template <class Grid>
228void Solver<Grid>::stepBalancedForce(bool hoisted) {
229 // (B) The balanced-force projection (doc/collocated_varrho_forces.md §4.6.2): once per step,
230 // before the Picard loop. Byte-identical (not even a flag read beyond this) when it is off.
231 coeffBuiltThisStep_ = hoisted; // X: the reset must not undo the hoist
232 if (pWritten_ || pbWritten_) { // a restart restored the pressure: is Pb its split?
233 pbValid_ = pWritten_ && pbWritten_;
234 pWritten_ = pbWritten_ = false;
235 }
236 if (balancedForceActive()) {
237 applyBalancedForceProjection();
238 } else {
239 pbValid_ = false; // this step moves P without Pb: the next ON step re-splits
240 if (!bfpSet_ && !bfpOpenNotice_ && colocatedFaceForce() && hasOpenDomainFace()) {
241 // The V8 default resolved OFF because of an open face: say so once, as the AUTO-scheme
242 // fallback does.
243 bfpOpenNotice_ = true;
244 int r = 0;
245#ifdef PECLET_FLOW_MPI
246 if (distributed_)
247 MPI_Comm_rank(comm_, &r);
248#endif
249 if (r == 0)
250 std::fprintf(stderr,
251 "peclet::flow SolverColocated: the balanced-force projection (default ON on "
252 "variable density / surface tension) is OFF: it does not support "
253 "inflow/outflow domain faces (v1). Call set_balanced_force_projection(False) "
254 "to silence this notice.\n");
255 }
256 }
257}
258
259template <class Grid>
260void Solver<Grid>::stepPredictorInputs() {
261 if (advectsMomentum() || hasBc_ || (Grid::collocated && faceInterp_ >= 5 && faceInterp_ <= 7))
262 for (int c = 0; c < 3; ++c)
263 fillVelGhosts(c, 0); // explicit ghosts (periodic + BC) for advect / embed defect matvec
264 // A0 (advective cut-wall flux): build the advection's wall-aware velocity inputs. AFTER the
265 // ghost exchange, over the extended block, so ghost solid rows carry the wall velocity too.
266 // No-op -- and no allocation -- unless a scene instance is moving; static scenes keep reading
267 // C[*].u byte for byte. See buildAdvInputs().
268 buildAdvInputs();
269 // Porous advection-form compensation: the Koren/SOU/FOU advection operators are CONSERVATIVE
270 // (flux form, ∇·(u u)), which equals the true advective transport u·∇u only for a solenoidal
271 // advecting field. Under the volume-averaged continuity div(eps u)=0 the plain divergence
272 // div(u) = -(1/eps) u·grad(eps) != 0, and the flux form silently adds the spurious force
273 // +u(div u) — largest where grad(eps) is large (clusters), where it pumps particle kinetic
274 // energy through the drag with no physical source (measured: HCS variance rising ~x30 past
275 // the clustering plateau). Compensate by subtracting u_f·div(u)_f from the advection in the
276 // RHS (the exact identity u·∇u = ∇·(uu) − u∇·u; div(u) at the face = mean of the two cell
277 // divergences). Gated on porous_ so every other path is byte-identical.
278 if (porous_ && advectsMomentum())
279 computeDivAdv();
280}
281
282template <class Grid>
283bool Solver<Grid>::stepPredictorRhs() {
284 // Rung V8: on the collocated grid with variable density and/or surface tension the pressure
285 // and every force go INSIDE this implicit predictor through the mass-adjoint face integral —
286 // WHY, and why never as a face acceleration after the viscous solve: see buildRhsColoVar.
287 // `colocatedFaceForce()` is false on the staggered path and on every constant-density
288 // collocated path without CSF, so this dispatch is inert there.
289 const bool coloFF = colocatedFaceForce();
290 for (int c = 0; c < 3; ++c) // RHS from u^n base + advection lagged at u^k
291 coloFF ? buildRhsColoVar(c)
292 : (vofMomEnabled_ ? buildRhsVarMom(c)
293 : (effVarRho() ? buildRhsVar(c)
294 : (hasCellForce_ ? buildRhsForced(c) : buildRhs(c))));
295 return coloFF;
296}
297
298template <class Grid>
299void Solver<Grid>::stepPredictorForces(bool coloFF, bool fullStress) {
300 // Rung V4 (WO-P): the balanced-force CSF, ADDED to whichever RHS the configuration built --
301 // at the same place, and with the same face difference, as the incremental -grad(P^n) just
302 // above it. Independent of the time term and the advection form, hence additive rather than a
303 // fifth RHS kernel. Gated: byte-identical when surface tension is off.
304 if (csfActive() && !coloFF) {
305 const double _t0 = vofTick(); // WO-V9
306 for (int c = 0; c < 3; ++c)
307 vofBlockCsf()
308 ? addCsfRhsBlocks(c)
309 : (csfMode_ == 0 ? addCsfRhs(c, C[c].b, true) : addCsfRhsCellInterp(c, C[c].b, true));
310 vofAdd(vt_.csf, _t0);
311 }
312 // Full viscous stress: rs_c * T_c(u^n), explicit on the time base and constant across Picard
313 // iterations; additive like the CSF, independent of which RHS kernel ran (§4.2-§4.3). Skipped
314 // entirely when mu is globally uniform (§4.4).
315 if (fullStress && !muUniform_)
316 for (int c = 0; c < 3; ++c)
317 addFullStressRhsComp(c);
318}
319
320template <class Grid>
321void Solver<Grid>::stepPredictorOperator() {
322 // Implicit-FOU: rebuild the IBM velocity stencil = backward-Euler diffusion + rho*FOU(u^k),
323 // then re-apply the cut-cell bake. Per Picard iteration (advecting velocity changes). Applies
324 // to the IBM (periodic/porous) path when the user opts in, AND ALWAYS to the domain-BC
325 // stencil path (inflow/outflow) -- implicitAdv() -> fully-implicit upwind advection (stable
326 // at large dt). The velocity-MG BC path keeps its own FOU coarse operator.
327 if (implicitAdv() && (!hasBc_ || !useVelocityMg_ || mixedVelocityMg()))
328 for (int c = 0; c < 3; ++c)
329 (varProps_ || effVarRho()) ? buildAdvStencilVar(c) : buildAdvStencil(c);
330 // Outflow backflow stabilization: dissipate reverse flow at the outlet in the momentum
331 // operator used by the domain-BC stencil smoother (prevents backflow divergence). Inert
332 // without reversal.
333 if (bcStencilPath() && backflowBeta_ > 0.0 && hasOutflow_)
334 for (int c = 0; c < 3; ++c)
335 applyBackflowStab(c);
336}
337
338template <class Grid>
339void Solver<Grid>::stepPredictorCoarseAdvection() {
340 // upwind-convective velocity-MG: restrict the (frozen u^k) advecting velocity to the coarse
341 // levels ONCE, before the per-component solves update it (shared across the 3 momentum
342 // components).
343 if (useVelocityMg_ && advectsMomentum() &&
344 ((implicitFou_ && !hasBc_) || (mixedVelocityMg() && implicitAdv())))
345 vmg_.restrictAdvVelocities( // A0: same inputs as the fine operator -- including the
346 // collocated projected face field, so the coarse FOU
347 // preconditioner stays consistent with the fine one
348 // (levels >= 1 only; level 0 IS buildAdvStencil's operator)
349 ufAdvVelocity() ? openFaceView(0) : advVelView(0),
350 ufAdvVelocity() ? openFaceView(1) : advVelView(1),
351 ufAdvVelocity() ? openFaceView(2) : advVelView(2));
352}
353
354template <class Grid>
355void Solver<Grid>::stepMomentumSolve() {
356 for (int c = 0; c < 3; ++c)
357 smoothComp(c); // per-component IBM implicit-diffusion solve
358 // Route (b): stash u* for the reaction-force budget. Every Picard iteration overwrites, so
359 // what survives is the LAST momentum solve -- the one whose viscous fluxes, together with
360 // the last projection, actually produced u^{n+1} (the time base is u^n for every iteration,
361 // so earlier iterations leave no trace in the final state except through P_). A pure
362 // deep_copy: no numerical effect on any solve.
363 if constexpr (!Grid::collocated) {
364 if (hasScene_) {
365 for (int c = 0; c < 3; ++c) {
366 if (uStar_[c].extent(0) != n_)
367 uStar_[c] = CCField("uStar", n_);
368 Kokkos::deep_copy(uStar_[c], C[c].u);
369 }
370 haveUStar_ = true;
371 }
372 }
373}
374
375template <class Grid>
376void Solver<Grid>::stepProjection() {
377 // The porous (volume-averaged) projection lives entirely on the cut-cell operator rails
378 // (divergOpenEps + buildPorousCoeff* into CutcellMG). Without set_solid /
379 // set_pressure_geometry there is NO projection at all — the gas would never accelerate to
380 // the interstitial velocity in a bed and the drag comes out ~5x too weak (a fluidized bed
381 // quietly refuses to fluidize). Fail loudly instead of silently dropping the constraint.
382 if (porous_ && !cutcellPressure_)
383 throw std::runtime_error(
384 "set_porous_continuity(True) requires the cut-cell pressure operator: call "
385 "set_solid(...) or set_pressure_geometry(all-fluid SDF) before stepping (a "
386 "domain-BC-only box otherwise runs with NO continuity constraint at all)");
387 if (cutcellPressure_)
388 project(); // cut-cell projection -> incompressible
389}
390
391template <class Grid>
392void Solver<Grid>::stepPostProjection() {
393 if (hasBc_)
394 applyVelocityBcAll(0, false); // re-impose domain BCs (keep outflow), components 0, 1, 2
395 // WO-5b: a cut-cell scalar's open-face flux is the one this projection constrained; keep it
396 // before any ghost fill wraps the high-side plane (no-op without one; the last iteration wins).
397 if (cutcellPressure_)
398 scalarCaptureOpenFaceFlux();
399}
400
401template <class Grid>
402void Solver<Grid>::stepTransport() {
403 // Geometric VoF (rung V2a): advance the colour field with the just-projected, discretely
404 // divergence-free face velocities — the SAME slot, and the same justification, as
405 // advanceScalars() below (Weymouth-Yue's exact conservation is conditioned on the advecting
406 // field's discrete divergence; see advectVof()). No-op (byte-identical) when VoF is off.
407 // Under momentum consistency (V2b) the colour was already advanced at the head of the step,
408 // together with the momentum it shares its fluxes with — see advectVofMomentum().
409 if (!vofMomEnabled_)
410 advectVof();
411 // WO-P23: refresh k(C) / (rho c_p)(C) from the colour the energy solve is about to see. No-op
412 // unless the consistent-energy transport is on.
413 pcUpdateEnergyProps();
414 // WO-P01: refresh the energy scalar's per-cell Dirichlet set from the colour the energy solve
415 // is about to see. No-op unless the thermal mass flux is on.
416 pcUpdateThermalMask();
417 // Segregated multiphysics: advance any transported scalars with the just-projected
418 // divergence-free velocity (properties frozen over the step). No-op (byte-identical) when no
419 // scalar is registered.
420 advanceScalars();
421 // set_superficial_velocity: the uniform shift of one velocity component, LAST, so the next step
422 // starts from the constrained field exactly as a driver shifting it between steps would. No-op
423 // when off.
424 applySuperficialVelocity();
425}
426
427template <class Grid>
428void Solver<Grid>::stepBackflowWarning() {
429 // The UNSTABLE outflow regime, detected rather than guessed (peclet-examples ISSUES.md
430 // "Inflow/outflow diverges to NaN"): reversed flow on an outflow face with the backflow
431 // stabilization switched OFF. Checked only in that configuration (beta <= 0 is not the
432 // default), once per solver; see outflowBackflow() for the mechanism.
433 if (hasOutflow_ && backflowBeta_ <= 0.0 && !backflowWarned_) {
434 const OutflowBackflow ob = outflowBackflow();
435 if (ob.reversed > 0) {
436 backflowWarned_ = true;
437 int r = 0;
438#ifdef PECLET_FLOW_MPI
439 if (distributed_)
440 MPI_Comm_rank(comm_, &r);
441#endif
442 if (r == 0)
443 std::fprintf(stderr,
444 "peclet::flow WARNING: reversed flow on an OUTFLOW face (max u.n = -%.3e, "
445 "%.1f%% of the outlet area, kinetic-energy influx %.3e) with the backflow "
446 "stabilization OFF. The zero-gradient outflow is only conditionally "
447 "energy-stable under reversal (the re-entering flux carries the boundary "
448 "cell's own velocity back in with no sink); this is the configuration in "
449 "which the literature's backflow divergence occurs. Call "
450 "set_backflow_stabilization(beta) (default 0.2; beta >= 0.5 is the "
451 "unconditional bound), or lengthen the domain so the recirculation closes "
452 "before the outlet. Monitor with outflow_backflow().\n",
453 ob.maxReverse, 100.0 * ob.fraction, ob.energyInflux);
454 }
455 }
456}
457
458template <class Grid>
460 if (superficialAxis_ < 0)
461 return;
462 const int a = superficialAxis_;
463 if (bc_[2 * a] != 0 || bc_[2 * a + 1] != 0)
464 throw std::runtime_error(
465 "set_superficial_velocity: the axis carries a domain boundary condition; a uniform "
466 "shift of the normal velocity is divergence-free only on a PERIODIC axis");
467 if (hasSolid_)
468 throw std::runtime_error(
469 "set_superficial_velocity: an immersed solid is present; a uniform shift would move fluid "
470 "through the cut faces (all-fluid domains only)");
471}
472
473template <class Grid>
475 if (superficialAxis_ < 0)
476 return;
477 const int a = superficialAxis_;
478 CCExec space;
479 const C3 e = e_;
480 CCField f = C[a].u;
481 long ncell = static_cast<long>(nx_) * ny_ * nz_;
482#ifdef PECLET_FLOW_MPI
483 if (distributed_)
484 ncell = static_cast<long>(gnx_) * gny_ * gnz_;
485#endif
486 const double target = superficialVelPhys_ * u_.velToInt(a), dn = static_cast<double>(ncell);
487 Kokkos::View<double, CCMem> shift = superficialShift_;
488 const auto inner = MDRange3<CCExec>(space, {G, G, G}, {e.x - G, e.y - G, e.z - G});
489 // The inner sum into the device scalar (asynchronous: the result never visits the host).
490 Kokkos::parallel_reduce(
491 "superficial_velocity_sum", inner,
492 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
493 acc += f((long)x + (long)y * e.x + (long)z * (long)e.x * e.y);
494 },
495 Kokkos::Sum<double, CCMem>(shift));
496#ifdef PECLET_FLOW_MPI
497 if (distributed_) {
498 // The global sum needs the host (MPI on host buffers): one scalar each way per step.
499 double loc = 0.0, glob = 0.0;
500 Kokkos::deep_copy(loc, shift);
501 MPI_Allreduce(&loc, &glob, 1, MPI_DOUBLE, MPI_SUM, comm_);
502 Kokkos::deep_copy(shift, glob);
503 }
504#endif
505 Kokkos::parallel_for(
506 "superficial_velocity_to_shift", Kokkos::RangePolicy<CCExec>(space, 0, 1),
507 KOKKOS_LAMBDA(int) { shift() = target - shift() / dn; });
508 Kokkos::parallel_for(
509 "superficial_velocity_shift", inner, KOKKOS_LAMBDA(int x, int y, int z) {
510 f((long)x + (long)y * e.x + (long)z * (long)e.x * e.y) += shift();
511 });
512 // The ghost ring follows its (shifted) owners: periodic images, and the domain BCs of the
513 // other axes re-imposed on the new tangential values.
514 fillVelGhosts(a, 0);
515}
516
517template <class Grid>
519 return Grid::collocated && (varRho_ || csfActive());
520}
521
522template <class Grid>
524 if constexpr (Grid::collocated) {
525 if (colSchemeAuto_ && ghostProjection_) {
526 ghostProjection_ = false;
527 gpNRows_ = -1;
528 faceInterp_ = 9;
529 fprintf(stderr,
530 "peclet::flow SolverColocated: AUTO scheme fell back to gauge-exact (%s is rung V8 "
531 "and the ghost projection v1 does not support it). Select explicitly with "
532 "set_collocated_scheme to silence this notice.\n",
533 why);
534 }
535 }
536}
537
538template <class Grid>
540 for (int c = 0; c < 3; ++c)
541 if (faceAcc_[c].extent(0) != n_)
542 faceAcc_[c] = CCField("faceAcc", n_);
543}
544
545template <class Grid>
547 if (!colocatedFaceForce())
548 return;
549 std::string m(who);
550 if (hasSolid_)
551 throw std::runtime_error(
552 m +
553 ": variable density / surface tension on SolverColocated is rung V8 and is ALL-FLUID "
554 "only (set_pressure_geometry). Immersed solids on this path are the next package "
555 "(doc/collocated_multiphase_solids_plan.md) — not this rung.");
556 if (ghostProjection_)
557 throw std::runtime_error(
558 m +
559 ": the ghost projection (v1) does not support variable density; select "
560 "set_collocated_scheme(\"gauge-exact\") (the AUTO fallback already does).");
561 if (rhoFaceHarmonic_)
562 throw std::runtime_error(
563 m +
564 ": set_rho_face_harmonic is not wired into the collocated variable-density pair (the "
565 "pressure force and the face coefficient would use different rho_f). Staggered only.");
566 if (!incremental_)
567 throw std::runtime_error(
568 m +
569 ": variable density / surface tension on SolverColocated needs the incremental pressure "
570 "(diagnostics.set_incremental_pressure(True)): the pressure force lives inside the "
571 "implicit predictor, and the non-incremental (Chorin) step has none, so its steady state "
572 "would depend on dt.");
573}
574
575template <class Grid>
577 if (enabled)
578 requireBalancedForceScope("set_balanced_force_projection", false);
579 bfpSet_ = true;
580 bfpOn_ = enabled;
582}
583
584template <class Grid>
586 if (balancedForceActive() && Pb_.extent(0) != n_)
587 Pb_ = addField("p_balanced"); // zero-initialised: with P = 0 that is a valid split
588}
589
590template <class Grid>
594
595template <class Grid>
597 return lastBalancedForceIters_;
598}
599
600template <class Grid>
602 return lastBalancedForceFailed_;
603}
604
605template <class Grid>
607 return balancedForceFailures_;
608}
609
610template <class Grid>
612 // U2 (doc/collocated_varrho_forces.md §0): an explicit setting wins; the DEFAULT is ON on the
613 // collocated variable-density / CSF path (V8), where the settled constant-kappa CSF balance
614 // needs it, and OFF everywhere else (staggered and constant-density collocated stay
615 // byte-identical). With an inflow/outflow domain face the V8 default resolves OFF (the option
616 // does not support open faces, §4.6.4 / Q7; step() says so once): only an EXPLICIT ON throws.
617 if (bfpSet_)
618 return bfpOn_;
620}
621
622template <class Grid>
624 for (int f = 0; f < 6; ++f)
625 if (bc_[f] == 2 || bc_[f] == 3)
626 return true;
627 return false;
628}
629
630template <class Grid>
631void Solver<Grid>::requireBalancedForceScope(const char* who, bool atStep) const {
632 const std::string m = std::string(who) + ": the balanced-force projection ";
633 if (porous_)
634 throw std::runtime_error(m +
635 "does not support the porous (volume-averaged) continuity: the "
636 "VANS operator carries eps and the drag relaxation (CFD-DEM is out "
637 "of scope). Call set_balanced_force_projection(False).");
638 bool autoGhost = false;
639 if constexpr (Grid::collocated)
640 autoGhost = colSchemeAuto_; // an AUTO 'ghost' may still fall back; final at the step
641 if (ghostProjection_ && (atStep || !autoGhost))
642 throw std::runtime_error(m +
643 "does not support the ghost projection (its overlay does not reach "
644 "the balanced face force yet). Call set_balanced_force_projection"
645 "(False).");
646 if (fluidOnlyMode_ == 2)
647 throw std::runtime_error(m + "does not support set_fluid_only_constraint(2).");
648 if (vofBlockCsf())
649 throw std::runtime_error(m + "does not support the block CSF (enable_vof_block_csf).");
650 for (int f = 0; f < 6; ++f)
651 if (bc_[f] == 2 || bc_[f] == 3)
652 throw std::runtime_error(
653 m +
654 "does not support inflow/outflow domain faces (v1: the operator-vs-flux openness rule "
655 "at inflow and the outflow planes are not wired). Call "
656 "set_balanced_force_projection(False).");
657 if (!incremental_)
658 throw std::runtime_error(m + "needs the incremental pressure (it re-splits P).");
659 if (atStep) {
660 if (!cutcellPressure_)
661 throw std::runtime_error(
662 m + "needs the cut-cell pressure operator (set_solid or set_pressure_geometry).");
663 if constexpr (Grid::collocated)
664 if (!colocatedFaceForce())
665 throw std::runtime_error(
666 m +
667 "has nothing to balance on the constant-density collocated path without surface "
668 "tension (its pressure force is the gauge-exact cell gradient, not the face "
669 "integral). It applies to variable density / surface tension on SolverColocated "
670 "and to every Solver configuration. Call set_balanced_force_projection(False).");
671 }
672}
673
674template <class Grid>
676 // beta = f_const + ½(f(j) + f(j-s)) (+ CSF below) on the face range [G, e-G]: the predictor's
677 // own face force. The face mean is the staggered Grid::atVelocity expression on BOTH grids (on
678 // the collocated grid the cell value is the predictor's placement, and the face mean is what the
679 // pressure must carry for rho g to balance: rho_c R(½(rho_L+rho_R) g/rho_f) = W rho_c g).
680 CCExec space;
681 const double fc = f_[c];
682 const long s = strideOf(c);
683 const bool haveFb = hasCellForce_;
684 CCConst fb = CCConst(haveFb ? cellForce_[c] : C[c].rscale);
685 CCField af = faceAcc_[c];
686 C3 e = e_;
687 using MD = MDRange3<CCExec>;
688 Kokkos::parallel_for(
689 "peclet::flow::bfp_face_force", MD(space, {G, G, G}, {e.x - G + 1, e.y - G + 1, e.z - G + 1}),
690 KOKKOS_LAMBDA(int x, int y, int z) {
691 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
692 af(i) = fc + (haveFb ? 0.5 * ((double)fb(i) + (double)fb(i - s)) : 0.0);
693 });
694 // CSF from the SAME code the predictor uses (row scale off, face range): the V4 face form on the
695 // collocated V8 path (which always uses it), and the csf mode's kernel on the staggered grid.
696 if (csfActive()) {
697 if (Grid::collocated || csfMode_ == 0)
698 addCsfRhs(c, af, /*rowScaled=*/false, /*faceRange=*/true);
699 else
700 addCsfRhsCellInterp(c, af, /*rowScaled=*/false, /*faceRange=*/true);
701 }
702 // times c = rho0/rho_f^op, the operator's own face mean (buildRhoCoeff / buildRhoCoeffHarm).
703 if (varRho_) {
704 CCConst rho = CCConst(rhoField_);
705 const double rho0 = rho_;
706 const bool harm = rhoFaceHarmonic_;
707 Kokkos::parallel_for(
708 "peclet::flow::bfp_face_coeff",
709 MD(space, {G, G, G}, {e.x - G + 1, e.y - G + 1, e.z - G + 1}),
710 KOKKOS_LAMBDA(int x, int y, int z) {
711 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
712 const double cf = harm ? rho0 * (rho(i) + rho(i - s)) / (2.0 * rho(i) * rho(i - s))
713 : rho0 / (0.5 * (rho(i) + rho(i - s)));
714 af(i) *= cf;
715 });
716 }
717}
718
719template <class Grid>
721 return prefactorHoist_ && varRho_ && !porous_ && outerIters_ == 1 && !balancedForceActive() &&
722 !useChebyshev_ && !ghostProjection_ && mg_.directPrefactorEligible();
723}
724
725template <class Grid>
727 // (scope: checked at the step head, beside vofStepPrecheck)
728 // (B1) the variable-rho operator, once for the step (project() then skips its rebuild).
729 if (varRho_) {
731 coeffBuiltThisStep_ = true;
732 if (prefactorHoist_ && !useChebyshev_ && !ghostProjection_)
733 mg_.prefactorBottom(); // X: the factor on the side instance from the early build
734 }
735 registerBalancedForceState(); // normally already registered by the setter that enabled it
736 if (pb1_.extent(0) != n1_)
737 pb1_ = CCField("pb1", n1_);
738 // (B2) the face force c*beta, (B3) its constraint divergence (div_ is scratch here: project()
739 // recomputes it before anything reads it).
741 for (int c = 0; c < 3; ++c)
743 constraintDivergence(CCConst(faceAcc_[0]), CCConst(faceAcc_[1]), CCConst(faceAcc_[2]), div_);
744 // (B4) the INCREMENT solve (WO-P5): A dP_b = D(O c beta) - A P_b^{n-1}, stopped RELATIVE TO THE
745 // FULL right-hand side, |r| <= rtol * max|D(O c beta)| -- run as the projection's own driver
746 // started from x = P_b^{n-1} with a full-RHS stop reference (the driver's first residual
747 // b - A P_b^{n-1} IS the increment's right-hand side, and x - P_b^{n-1} the increment), and
748 // skipped outright (zero iterations) when that initial residual already meets the test: a
749 // static interface costs no iterations. A force with no divergence needs no pressure at all.
750 long iters = 0;
751 bool failed = false;
752 double bmax = maxAbsInner(CCConst(div_), e_, G);
753#ifdef PECLET_FLOW_MPI
754 if (distributed_) {
755 double g = 0.0;
756 MPI_Allreduce(&bmax, &g, 1, MPI_DOUBLE, MPI_MAX, comm_);
757 bmax = g;
758 }
759#endif
760 if (bmax == 0.0) {
761 Kokkos::deep_copy(pb1_, 0.0);
762 } else {
763 copyInner(rhs1_, e1_, 1, CCConst(div_), e_, G);
764 {
765 CCExec space;
766 CCField r = rhs1_;
767 Kokkos::parallel_for(
768 "peclet::flow::bfp_negdiv", Kokkos::RangePolicy<CCExec>(space, 0, n1_),
769 KOKKOS_LAMBDA(std::size_t i) { r(i) = -r(i); });
770 }
771 copyInner(pb1_, e1_, 1, CCConst(Pb_), e_, G);
772 const double rtol = useChebyshev_ ? chebRtol_ : pcgRtol_;
773 const double bref = std::max(mg_.rhsNorm(rhs1_, r_), 1e-300);
774 const double r0 = mg_.residualNorm(rhs1_, pb1_, r_, Ap_);
775 if (r0 > rtol * bref) {
776 iters = solveBalancedForceSystem(bref, r0);
777 // Captured right after the solve (ISSUES sweep item 6: a breakdown reports the cap and
778 // raises the flag); a non-finite X fails too. Agreed across ranks.
779 int bad = mg_.lastSolveFailed() ? 1 : 0;
780 {
781 CCExec space;
782 CCConst x1 = CCConst(pb1_);
783 const C3 e1 = e1_;
784 long nf = 0; // a COUNT (sum reduction, identity 0) of the non-finite inner values
785 Kokkos::parallel_reduce(
786 "peclet::flow::bfp_nonfinite",
787 MDRange3<CCExec>(space, {1, 1, 1}, {e1.x - 1, e1.y - 1, e1.z - 1}),
788 KOKKOS_LAMBDA(int x, int y, int z, long& acc) {
789 const long i = (long)x + (long)y * e1.x + (long)z * (long)e1.x * e1.y;
790 if (!Kokkos::isfinite(x1(i)))
791 acc += 1;
792 },
793 nf);
794 bad = (bad || nf > 0) ? 1 : 0;
795 }
796#ifdef PECLET_FLOW_MPI
797 if (distributed_) {
798 int g = 0;
799 MPI_Allreduce(&bad, &g, 1, MPI_INT, MPI_MAX, comm_);
800 bad = g;
801 }
802#endif
803 failed = bad != 0;
804 }
805 }
806 lastBalancedForceIters_ = iters;
807 lastBalancedForceFailed_ = failed;
808 if (failed) {
809 // Keep the previous split: P and P_b unchanged (their ghosts were filled at the step head),
810 // so this step's predictor sees the forces exactly as with the option off. Counted, and the
811 // first one warns.
812 ++balancedForceFailures_;
813 if (!bfpFailWarned_) {
814 bfpFailWarned_ = true;
815 int r = 0;
816#ifdef PECLET_FLOW_MPI
817 if (distributed_)
818 MPI_Comm_rank(comm_, &r);
819#endif
820 if (r == 0)
821 std::fprintf(stderr,
822 "peclet::flow WARNING: the balanced-force pre-projection solve failed (driver "
823 "breakdown or a non-finite result, %ld iterations); P and p_balanced were "
824 "kept for this step. Further failures are counted silently in "
825 "diagnostics.balanced_force_failures().\n",
826 iters);
827 }
828 return;
829 }
830 // (B5) P += X - P_b; P_b = X (one fused kernel over the inner cells), then the P ghosts the
831 // predictor reads. When P_b is NOT a valid split of the current P (pbValid_: steps with the
832 // option off moved P, or a restart restored "p" without "p_balanced"), P already holds the
833 // balanced pressure, and P += X - P_b would add it a second time: RE-SPLIT instead, P_b = X
834 // with P unchanged (doc/collocated_varrho_forces.md §4.6.2).
835 {
836 CCExec space;
837 CCField P = P_, pb = Pb_;
838 CCConst x1 = CCConst(pb1_);
839 const C3 e1 = e1_, e2 = e_;
840 const bool resplit = !pbValid_;
841 Kokkos::parallel_for(
842 "peclet::flow::bfp_split", MDRange3<CCExec>(space, {0, 0, 0}, {nx_, ny_, nz_}),
843 KOKKOS_LAMBDA(int x, int y, int z) {
844 const long i1 = (long)(x + 1) + (long)(y + 1) * e1.x + (long)(z + 1) * (long)e1.x * e1.y;
845 const long i2 = (long)(x + G) + (long)(y + G) * e2.x + (long)(z + G) * (long)e2.x * e2.y;
846 const double xv = x1(i1);
847 if (!resplit)
848 P(i2) += xv - pb(i2);
849 pb(i2) = xv;
850 });
851 }
852 pbValid_ = true;
853 fillGhosts(P_);
854 if (hasBc_)
856}
857
858template <class Grid>
859long Solver<Grid>::solveBalancedForceSystem(double bref, double r0) {
860 // The balanced-force projection's own call path: the same operator and driver as the main
861 // projection, but the stop is relative to the full right-hand side (setStopReference, reset on
862 // every exit) and a Chebyshev solve uses bounds of its OWN (bfpChebA_/B_), never the main
863 // projection's (doc §11 Q9: the main bounds are estimated on the main right-hand side, and the
864 // per-step variable-rho refresh invalidates them every step). The own bounds are estimated once
865 // on this solve's right-hand side and kept across steps; they are re-estimated after a
866 // structural operator change (bfpChebSet_ cleared) or when the iteration DIVERGES: it ran to
867 // the cap and its residual ended above r0. Then the solve restarts from P_b^{n-1} with fresh
868 // bounds.
869 struct StopRefGuard {
870 CutcellMG& mg;
871 ~StopRefGuard() { mg.setStopReference(-1.0); }
872 } guard{mg_};
873 mg_.setStopReference(bref);
874 if (useChebyshev_) {
875 if (!bfpChebSet_) { // from scratch (a structural change): no ratchet floor
876 mg_.estimateEigenvalues(CCConst(rhs1_), bfpChebA_, bfpChebB_, 15, 2, 2, 12);
877 bfpLmaxFloor_ = 0.0;
878 bfpChebSet_ = true;
879 }
880 // The bounds are always a cold estimate: the growth guard (as solvePressureSystem's) runs.
881 long it = mg_.solveChebyshev(rhs1_, pb1_, chebMaxit_, chebRtol_, 2, 2, 12, bfpChebA_, bfpChebB_,
882 false, true);
883 if (mg_.chebyshevGuardTripped()) { // the residual grew: lambda_max underestimated
885 mg_.estimateEigenvalues(CCConst(rhs1_), bfpChebA_, bfpChebB_, 15, 2, 2, 12,
887 if (bfpChebB_ < bfpLmaxFloor_)
888 bfpChebB_ = bfpLmaxFloor_;
889 bfpLmaxFloor_ = bfpChebB_; // the bracketed bounds persist ((b))
890 copyInner(pb1_, e1_, 1, CCConst(Pb_), e_, G);
891 it += mg_.solveChebyshev(rhs1_, pb1_, chebMaxit_, chebRtol_, 2, 2, 12, bfpChebA_, bfpChebB_);
892 } else if (it >= chebMaxit_) { // never met the stop: slow, or diverging on bounds gone stale?
893 const double rfin = mg_.residualNorm(rhs1_, pb1_, r_, Ap_);
894 if (!(rfin <= r0)) { // residual growth (or non-finite): re-estimate and restart once
895 mg_.estimateEigenvalues(CCConst(rhs1_), bfpChebA_, bfpChebB_, 15, 2, 2, 12);
896 if (bfpChebB_ < bfpLmaxFloor_) // the ratchet ((b))
897 bfpChebB_ = bfpLmaxFloor_;
898 copyInner(pb1_, e1_, 1, CCConst(Pb_), e_, G);
899 it +=
900 mg_.solveChebyshev(rhs1_, pb1_, chebMaxit_, chebRtol_, 2, 2, 12, bfpChebA_, bfpChebB_);
901 }
902 }
903 return it;
904 }
905 long it;
906 if (useFcg_) {
907 if (zp1_.extent(0) != n1_)
908 zp1_ = CCField("zp1", n1_);
909 it = mg_.solveFCG(rhs1_, pb1_, r_, pp_, z_, zp1_, Ap_, pcgMaxit_, pcgRtol_, 2, 2, 12, nullptr,
910 0, C3{nx_, ny_, nz_});
911 } else {
912 it = mg_.solvePCG(rhs1_, pb1_, r_, pp_, z_, Ap_, pcgMaxit_, pcgRtol_, 2, 2, 12, nullptr, 0,
913 C3{nx_, ny_, nz_});
914 }
915 checkCgExit(rhs1_, pb1_, it, useFcg_ ? "balanced-force flexible-CG" : "balanced-force MG-PCG",
916 nullptr);
917 return it;
918}
919
920template <class Grid>
922 CCExec space;
923 const double idiag = rho_ / dt_, fc = f_[c], rho = rho_, wc = u_.w[c];
924 C3 e = e_;
925 CCField bb = C[c].b, rs = C[c].rscale, P = P_, brhs = bcBrhs_[c], inh = C[c].inhom;
926 // A0: U/V/W (the advecting velocities) and aP (the advected field) come from the wall-aware
927 // advection inputs -- identical to C[*].u unless an instance is moving. `uu` stays the live
928 // field: its only other consumer is the porous advection-form compensation.
929 // COLLOCATED (`ufa`): the advecting velocities are instead the PROJECTED divergence-free MAC
930 // face field of the last projection (the advected field aP stays the CELL field) -- see
931 // ufAdvVelocity(). advWallInputs() is staggered-only, so the two never overlap.
932 const bool ufa = ufAdvVelocity();
933 CCConst U = ufa ? openFaceView(0) : advVelView(0), V = ufa ? openFaceView(1) : advVelView(1),
934 W = ufa ? openFaceView(2) : advVelView(2), aP = advVelView(c), uu = CCConst(C[c].u),
935 un = CCConst(old_[c]);
936 const long strd = (c == 0) ? 1 : (c == 1) ? e_.x : (long)e_.x * e_.y;
937 // Pure implicit FOU (no deferred correction): 1st-order upwind carried entirely by the
938 // operator, no explicit high-order term in the RHS -- maximally dissipative/stable (diffuses
939 // sharp shear layers). Only meaningful on an implicit-advection path.
940 const bool pureFou = implicitAdv() && !deferredCorr_;
941 const bool incr = cutcellPressure_ && incremental_, adv = advectsMomentum() && !pureFou,
942 bc = hasBc_ && !bcStencilPath(); // fold RHS only on the const-coeff domain-BC path;
943 // on the stencil path (solid and/or implicit advection) the walls enter via reflection ghosts
944 // (smoothComp) and the RHS carries the IBM inhom (=0 for no-slip) + the deferred correction.
945 // incr predictor carries -grad(P^n).
946 const bool ifou = implicitAdv() &&
947 deferredCorr_; // deferred correction: keep (HO - FOU) explicit in the RHS
948 // (implicit on the domain-BC path by default, opt-in elsewhere)
949 const int sch = advScheme_; // 0 = SOU (default), 1 = Koren TVD
950 // R0: stash the explicit advective term for the reaction-force budget (staggered scenes only).
951 // The LAST Picard iteration overwrites, matching uStar_'s convention -- that is the RHS the
952 // final momentum solve actually saw.
953 const bool sa = ensureAdvStash(c, adv);
954 CCField ar = advRhs_[c];
955 // Embed rung 5: wall-aware pressure force (collocated): -grad(P) = the TRANSPOSE of the
956 // wall-aware cell->face constraint interpolation, precomputed per component (the plain path's
957 // central difference is the transpose of the plain 1/2-1/2 average, so this keeps the
958 // momentum/constraint operators an adjoint pair on both paths).
959 const bool tg = Grid::collocated && faceInterp_ == 5 && incr;
960 // embed 6/7: openness-weighted -grad(P^n) predictor, matching the fs-weighted correction
961 const bool wg = Grid::collocated && (faceInterp_ == 6 || faceInterp_ == 7) && incr;
962 // ghost mode and the gauge-exact scheme: directional gpCenterGrad predictor — the mode-0
963 // central difference reads the decoupled P=0 at solid-centered cells, a gauge-dependent O(1)
964 // gradient error at every cut cell (measured O(1/h) in physical units,
965 // ghost_collocated_apriori.py [C2]).
966 const bool gg = Grid::collocated && (ghostProjection_ || faceInterp_ == 9) && incr;
967 if constexpr (Grid::collocated) {
968 // Phase 2 C2: each gradient kernel carries the metric weight w_c of ITS OWN axis on its
969 // output (doc/anisotropic_metric.md §3), which is why the `gpw(i)` branch of the RHS below
970 // is not scaled again.
971 if (gg) {
972 gpCenterGrad(tgp_, CCConst(P_), CCConst(ghostProjection_ ? sdfGp_ : sdf_), c, e_, G, u_.w[c]);
973 } else if (tg) {
974 CCField xcs[3] = {xcx_, xcy_, xcz_};
975 CCField oax[3] = {ox_, oy_, oz_};
976 transposeGradWallAware(tgp_, CCConst(P_), CCConst(sdf_), CCConst(oax[c]), CCConst(xcs[c]),
977 true, c, e_, G, u_.w[c]);
978 } else if (wg) {
979 CCField oax[3] = {ox_, oy_, oz_};
980 centerGradOpen(tgp_, CCConst(P_), CCConst(oax[c]), c, e_, G, u_.w[c]);
981 }
982 }
983 CCConst gpw = CCConst(tgp_); // empty view on the staggered path (tg/wg/gg false there)
984 // Embed (5/6/7) FV momentum via DEFECT CORRECTION: solve M·u^{k+1} = M·u^k − rs·L_FV(u^k) +
985 // rs·b_FV so the fixed point satisfies the second-order finite-volume balance L_FV·u* = b_FV
986 // exactly, with the (stable, small-cell-safe) IBM matrix M only as preconditioner. fvM_ = M·u^k
987 // (stencilMatvec), fvL_ = L_FV(u^k) (embedViscousApply: o_f faces + cs time + true-normal
988 // wall drag). Interior cells: M = L_FV → the defect vanishes → byte-identical to mode 0.
989 // Stokes only (advection folds into the IBM matrix, not yet into L_FV).
990 // Porous advection-form compensation (+rho*u_f*div(u)_f): see the step() comment. Off (and the
991 // view untouched) on every non-porous path.
992 const bool pc = porous_ && advectsMomentum();
993 CCConst dv = CCConst(divAdv_);
994 const bool wd = Grid::collocated && faceInterp_ >= 5 && faceInterp_ <= 7;
995 if constexpr (Grid::collocated)
996 if (wd) {
997 stencilMatvec(fvM_, CCConst(C[c].u), FPC(C[c].AC), FPC(C[c].AW), FPC(C[c].AE), FPC(C[c].AS),
998 FPC(C[c].AN), FPC(C[c].AB), FPC(C[c].AT), e_, G);
999 embedViscousApply(fvL_, CCConst(C[c].u), CCConst(sdf_), CCConst(cs_), CCConst(ox_),
1000 CCConst(oy_), CCConst(oz_), mu_, rho_ / dt_, e_, G, u_.w[0], u_.w[1],
1001 u_.w[2], u_.hp[0], u_.hp[1], u_.hp[2]);
1002 }
1003 CCConst fvM = CCConst(fvM_), fvL = CCConst(fvL_), cs = CCConst(cs_);
1004 // b = descale*(idiag*u^n - rho*Koren(u^k) + rho*FOU(u^k) + f - grad P^n) - inhom (+ BC fold
1005 // brhs). The time base is u^n (Picard); the advecting velocity & advected field are the current
1006 // iterate u^k.
1007 ccFor3(
1008 "rhs", C3{G, G, G}, C3{e.x - G, e.y - G, e.z - G}, KOKKOS_LAMBDA(int x, int y, int z) {
1009 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
1010 double aK = 0.0, aF = 0.0;
1011 if (adv) {
1012 sadv::ViewAcc Ua{U, e.x, e.y}, Va{V, e.x, e.y}, Wa{W, e.x, e.y}, Fa{aP, e.x, e.y};
1013 aK = (sch == 0) ? Grid::advect_sou(c, x, y, z, Ua, Va, Wa, Fa, ufa)
1014 : Grid::advect(c, x, y, z, Ua, Va, Wa, Fa, ufa);
1015 if (ifou)
1016 aF = Grid::advect_fou(c, x, y, z, Ua, Va, Wa, Fa, ufa);
1017 }
1018 if (sa)
1019 ar(i) = rho * (aF - aK);
1020 // incremental predictor's -grad(P^n): central-difference cell gradient on the collocated
1021 // grid (or the wall-aware transpose gradient, mode 2), one-sided face gradient (P at the
1022 // high cell of the staggered face) on the staggered grid.
1023 // The pressure gradient of component c carries the metric weight w_c
1024 // (doc/anisotropic_metric.md §1.2/§2); wc == 1.0 exactly on the isotropic path. The
1025 // gpw() kernels carry their own weight (§3), so they are not scaled again here.
1026 const double gp =
1027 !incr ? 0.0
1028 : Grid::collocated
1029 ? ((tg || wg || gg) ? gpw(i) : wc * (0.5 * (P((long)i + strd) - P((long)i - strd))))
1030 : wc * (P(i) - P((long)i - strd));
1031 if (wd) { // FV defect-correction RHS M·u − rs·(L_FV·u − b_FV), b_FV = idt·cs·u^n +
1032 // cs·(f − grad P); the fixed point L_FV·u* = b_FV.
1033 const double bfv = idiag * cs(i) * un(i) + cs(i) * (fc - gp);
1034 bb(i) = fvM(i) - rs(i) * (fvL(i) - bfv);
1035 } else {
1036 const double comp = pc ? rho * uu(i) * 0.5 * (dv(i) + dv((long)i - strd)) : 0.0;
1037 bb(i) = rs(i) * (idiag * un(i) + fc - rho * aK + rho * aF + comp - gp) +
1038 (bc ? brhs(i) : -inh(i));
1039 }
1040 }); // BC fold (brhs) on the domain-BC path; -inhom on the IBM path (=0 for no-slip)
1041}
1042
1043template <class Grid>
1045 CCExec space;
1046 const double idiag = rho_ / dt_, fc = f_[c], rho = rho_, wc = u_.w[c];
1047 C3 e = e_;
1048 CCField bb = C[c].b, rs = C[c].rscale, P = P_, brhs = bcBrhs_[c], inh = C[c].inhom;
1049 CCConst fb = CCConst(cellForce_[c]);
1050 // A0: U/V/W (the advecting velocities) and aP (the advected field) come from the wall-aware
1051 // advection inputs -- identical to C[*].u unless an instance is moving. `uu` stays the live
1052 // field: its only other consumer is the porous advection-form compensation.
1053 // COLLOCATED (`ufa`): the advecting velocities are instead the PROJECTED divergence-free MAC
1054 // face field of the last projection (the advected field aP stays the CELL field) -- see
1055 // ufAdvVelocity(). advWallInputs() is staggered-only, so the two never overlap.
1056 const bool ufa = ufAdvVelocity();
1057 CCConst U = ufa ? openFaceView(0) : advVelView(0), V = ufa ? openFaceView(1) : advVelView(1),
1058 W = ufa ? openFaceView(2) : advVelView(2), aP = advVelView(c), uu = CCConst(C[c].u),
1059 un = CCConst(old_[c]);
1060 const long strd = (c == 0) ? 1 : (c == 1) ? e_.x : (long)e_.x * e_.y;
1061 const bool pureFou = implicitAdv() && !deferredCorr_;
1062 const bool incr = cutcellPressure_ && incremental_, adv = advectsMomentum() && !pureFou,
1063 bc = hasBc_ && !bcStencilPath();
1064 const bool ifou = implicitAdv() && deferredCorr_;
1065 const int sch = advScheme_;
1066 const bool sa = ensureAdvStash(c, adv); // R0: see buildRhs
1067 CCField ar = advRhs_[c];
1068 // Porous advection-form compensation (+rho*u_f*div(u)_f): see the step() comment.
1069 const bool pc = porous_ && advectsMomentum();
1070 CCConst dv = CCConst(divAdv_);
1071 const bool tg = Grid::collocated && faceInterp_ == 5 && incr; // wall-aware -grad(P)
1072 const bool gg = Grid::collocated && (ghostProjection_ || faceInterp_ == 9) &&
1073 incr; // directional ghost -grad(P)
1074 if constexpr (Grid::collocated) {
1075 if (gg) {
1076 gpCenterGrad(tgp_, CCConst(P_), CCConst(ghostProjection_ ? sdfGp_ : sdf_), c, e_, G, u_.w[c]);
1077 } else if (tg) {
1078 CCField xcs[3] = {xcx_, xcy_, xcz_};
1079 CCField oax[3] = {ox_, oy_, oz_};
1080 transposeGradWallAware(tgp_, CCConst(P_), CCConst(sdf_), CCConst(oax[c]), CCConst(xcs[c]),
1081 true, c, e_, G, u_.w[c]);
1082 }
1083 }
1084 CCConst gpw = CCConst(tgp_);
1085 using MD = MDRange3<CCExec>;
1086 Kokkos::parallel_for(
1087 "rhs_forced", MD(space, {G, G, G}, {e.x - G, e.y - G, e.z - G}),
1088 KOKKOS_LAMBDA(int x, int y, int z) {
1089 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
1090 double aK = 0.0, aF = 0.0;
1091 if (adv) {
1092 sadv::ViewAcc Ua{U, e.x, e.y}, Va{V, e.x, e.y}, Wa{W, e.x, e.y}, Fa{aP, e.x, e.y};
1093 aK = (sch == 0) ? Grid::advect_sou(c, x, y, z, Ua, Va, Wa, Fa, ufa)
1094 : Grid::advect(c, x, y, z, Ua, Va, Wa, Fa, ufa);
1095 if (ifou)
1096 aF = Grid::advect_fou(c, x, y, z, Ua, Va, Wa, Fa, ufa);
1097 }
1098 if (sa)
1099 ar(i) = rho * (aF - aK);
1100 const double gp =
1101 !incr ? 0.0
1102 : Grid::collocated
1103 ? ((tg || gg) ? gpw(i) : wc * (0.5 * (P((long)i + strd) - P((long)i - strd))))
1104 : wc * (P(i) - P((long)i - strd));
1105 const double comp = pc ? rho * uu(i) * 0.5 * (dv(i) + dv((long)i - strd)) : 0.0;
1106 // The cell force is VOLUMETRIC: placed where the unknown lives (face mean on the MAC grid,
1107 // cell value collocated) -- Grid::atVelocity, shared with buildRhsVar / addDragDiagonal.
1108 const double fbU = Grid::atVelocity(fb, i, strd);
1109 bb(i) = rs(i) * (idiag * un(i) + fc + fbU - rho * aK + rho * aF + comp - gp) +
1110 (bc ? brhs(i) : -inh(i));
1111 });
1112}
1113
1114template <class Grid>
1116 const double idt = 1.0 / dt_, fc = f_[c], wc = u_.w[c];
1117 C3 e = e_;
1118 CCField bb = C[c].b, rs = C[c].rscale, P = P_, brhs = bcBrhs_[c], inh = C[c].inhom;
1119 CCConst fb = CCConst(cellForce_[c]);
1120 CCConst rf = CCConst(effRhoField());
1121 // A0: U/V/W (the advecting velocities) and aP (the advected field) come from the wall-aware
1122 // advection inputs -- identical to C[*].u unless an instance is moving. `uu` stays the live
1123 // field: its only other consumer is the porous advection-form compensation.
1124 // COLLOCATED (`ufa`): the advecting velocities are instead the PROJECTED divergence-free MAC
1125 // face field of the last projection (the advected field aP stays the CELL field) -- see
1126 // ufAdvVelocity(). advWallInputs() is staggered-only, so the two never overlap.
1127 const bool ufa = ufAdvVelocity();
1128 CCConst U = ufa ? openFaceView(0) : advVelView(0), V = ufa ? openFaceView(1) : advVelView(1),
1129 W = ufa ? openFaceView(2) : advVelView(2), aP = advVelView(c), uu = CCConst(C[c].u),
1130 un = CCConst(old_[c]);
1131 const long strd = strideOf(c);
1132 const bool pureFou = implicitAdv() && !deferredCorr_;
1133 const bool incr = cutcellPressure_ && incremental_, adv = advectsMomentum() && !pureFou,
1134 bc = hasBc_ && !bcStencilPath();
1135 const bool ifou = implicitAdv() && deferredCorr_;
1136 const int sch = advScheme_;
1137 // Porous advective-form compensation, weighted by the face density (rho_eff = eps*rho): the
1138 // eps-weighted ADVECTIVE form eps*rho*(du/dt + u.grad u) IS the conservative volume-averaged
1139 // momentum given the enforced continuity (the u*[d(eps)/dt + div(eps u)] bracket vanishes).
1140 const bool pc = porous_ && advectsMomentum();
1141 CCConst dv = CCConst(divAdv_);
1142 // rule H (§4.5; §14 H-3c): host pencil, device MDRange; the body is verbatim. Each cell writes
1143 // only bb(i), which nothing in the body reads (ccFor3's simd contract).
1144 ccFor3(
1145 "rhs_var", C3{G, G, G}, C3{e.x - G, e.y - G, e.z - G}, KOKKOS_LAMBDA(int x, int y, int z) {
1146 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
1147 const double rhoF = 0.5 * (rf(i) + rf(i - strd)); // face density of the velocity unknown
1148 double aK = 0.0, aF = 0.0;
1149 if (adv) {
1150 sadv::ViewAcc Ua{U, e.x, e.y}, Va{V, e.x, e.y}, Wa{W, e.x, e.y}, Fa{aP, e.x, e.y};
1151 aK = (sch == 0) ? Grid::advect_sou(c, x, y, z, Ua, Va, Wa, Fa, ufa)
1152 : Grid::advect(c, x, y, z, Ua, Va, Wa, Fa, ufa);
1153 if (ifou)
1154 aF = Grid::advect_fou(c, x, y, z, Ua, Va, Wa, Fa, ufa);
1155 }
1156 const double gp = !incr ? 0.0
1157 : Grid::collocated ? wc * (0.5 * (P((long)i + strd) - P((long)i - strd)))
1158 : wc * (P(i) - P((long)i - strd));
1159 const double fbF = Grid::atVelocity(fb, i, strd);
1160 const double comp = pc ? rhoF * uu(i) * 0.5 * (dv(i) + dv((long)i - strd)) : 0.0;
1161 bb(i) = rs(i) * (rhoF * idt * un(i) + fc + fbF - rhoF * aK + rhoF * aF + comp - gp) +
1162 (bc ? brhs(i) : -inh(i));
1163 });
1164}
1165
1166template <class Grid>
1168 CCExec space;
1169 const double idt = 1.0 / dt_, fc = f_[c], wc = u_.w[c];
1170 C3 e = e_;
1171 CCField bb = C[c].b, rs = C[c].rscale, P = P_, brhs = bcBrhs_[c], inh = C[c].inhom;
1172 CCConst fb = CCConst(cellForce_[c]);
1173 CCConst rf = CCConst(effRhoField());
1174 CCConst ua = CCConst(uAdv_[c]);
1175 const long strd = strideOf(c);
1176 const bool incr = cutcellPressure_ && incremental_;
1177 const bool bc = hasBc_ && !bcStencilPath();
1178 using MD = MDRange3<CCExec>;
1179 Kokkos::parallel_for(
1180 "rhs_var_mom", MD(space, {G, G, G}, {e.x - G, e.y - G, e.z - G}),
1181 KOKKOS_LAMBDA(int x, int y, int z) {
1182 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
1183 const double rhoF = 0.5 * (rf(i) + rf(i - strd));
1184 const double gp = !incr ? 0.0
1185 : Grid::collocated ? wc * (0.5 * (P((long)i + strd) - P((long)i - strd)))
1186 : wc * (P(i) - P((long)i - strd));
1187 const double fbF = Grid::atVelocity(fb, i, strd);
1188 bb(i) = rs(i) * (rhoF * idt * ua(i) + fc + fbF - gp) + (bc ? brhs(i) : -inh(i));
1189 });
1190}
1191
1192// WHY the pressure and every force are HERE, inside the implicit predictor, and never a face
1193// acceleration added after the viscous solve (the Basilisk centered.h "kick" that rung V8/WO-T
1194// used until 2026-09-25): added after A^{-1}, the lagged pressure -dt*G P^n/rho_f lies exactly in
1195// the range the projection removes, so P^n never reaches u (the step is non-incremental Chorin:
1196// steady state scaled by (1 + dt*mu*Lambda)), and the rotational term -kappa*div then acts on it
1197// as an explicit diffusion, P^{n+1} = -4*kappa*dt*S*P^n/rho (-12.0000 measured at (pi,pi,pi)).
1198// Balance at a density jump comes from the operators, not the placement: the pressure force is
1199// rho_c * avg_faces(G_f P / rho_f) (FV face integral, acceleration-continuous face pressure), and
1200// the constraint reads the momentum-weighted face velocity, so M*Gamma = -C^T. Gates:
1201// tests/python/test_collocated_stability_guard.py. Design: doc/collocated_varrho_forces.md.
1202template <class Grid>
1204 // (S5) the face accelerations Phi_c = (f_const + CSF - w (P(j) - P(j-s))) / rho_f on the face
1205 // range [G, e-G], WITHOUT the openness (the reconstruction below applies it once). Reads the
1206 // live P_ (the incremental predictor's P^n; later Picard iterations see the updated P).
1207 ensureFaceAcc();
1208 const bool haveRho = effVarRho();
1209 const bool incr = cutcellPressure_ && incremental_;
1210 const long sc = strideOf(c);
1211 // Unread placeholder when the density is constant (a Kokkos View must still be a live handle).
1212 CCConst rf = CCConst(haveRho ? effRhoField() : C[c].rscale);
1213 buildFaceAccelVar(faceAcc_[c], CCConst(P_), rf, CCConst(C[c].rscale), /*haveFb=*/false, haveRho,
1214 rho_, f_[c], incr, /*scale=*/1.0, sc, e_, G, u_.w[c]);
1215 if (csfActive())
1216 addFaceAccelCsf(faceAcc_[c], CCConst(cField_), CCConst(kappaField_), CCConst(kappaBranch_), rf,
1217 haveRho, rho_, sigmaCsf_, 1.0 / u_.w[c], /*scale=*/1.0, sc, e_, G);
1218 // (S6) the RHS: b = rs [ (rho_c/dt) u^n - rho_c aK + rho_c aF + W f_c + rho_c R(Phi) ] + bc/inh,
1219 // R(Phi) = cellFromFaces(Phi(i), Phi(i+s), o(i), o(i+s)), W = weightSum(o(i), o(i+s)) — the SAME
1220 // two openness reads, so the per-cell force balances the reconstructed pressure force exactly.
1221 CCExec space;
1222 const double idt = 1.0 / dt_, rhoIdtC = rho_ / dt_, rhoK = rho_;
1223 C3 e = e_;
1224 CCField bb = C[c].b, rs = C[c].rscale, brhs = bcBrhs_[c], inh = C[c].inhom;
1225 CCField oax[3] = {ox_, oy_, oz_};
1226 CCConst o = CCConst(oax[c]), phiF = CCConst(faceAcc_[c]);
1227 const bool haveFb = hasCellForce_;
1228 CCConst fb = CCConst(haveFb ? cellForce_[c] : C[c].rscale);
1229 const bool ufa = ufAdvVelocity();
1230 CCConst U = ufa ? openFaceView(0) : advVelView(0), V = ufa ? openFaceView(1) : advVelView(1),
1231 W = ufa ? openFaceView(2) : advVelView(2), aP = advVelView(c), un = CCConst(old_[c]);
1232 const bool pureFou = implicitAdv() && !deferredCorr_;
1233 const bool adv = advectsMomentum() && !pureFou, bc = hasBc_ && !bcStencilPath();
1234 const bool ifou = implicitAdv() && deferredCorr_;
1235 const int sch = advScheme_;
1236 using MD = MDRange3<CCExec>;
1237 Kokkos::parallel_for(
1238 "rhs_colo_var", MD(space, {G, G, G}, {e.x - G, e.y - G, e.z - G}),
1239 KOKKOS_LAMBDA(int x, int y, int z) {
1240 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
1241 const double rhoC = haveRho ? rf(i) : rhoK;
1242 const double dg = haveRho ? rhoC * idt : rhoIdtC;
1243 double aK = 0.0, aF = 0.0;
1244 if (adv) {
1245 sadv::ViewAcc Ua{U, e.x, e.y}, Va{V, e.x, e.y}, Wa{W, e.x, e.y}, Fa{aP, e.x, e.y};
1246 aK = (sch == 0) ? Grid::advect_sou(c, x, y, z, Ua, Va, Wa, Fa, ufa)
1247 : Grid::advect(c, x, y, z, Ua, Va, Wa, Fa, ufa);
1248 if (ifou)
1249 aF = Grid::advect_fou(c, x, y, z, Ua, Va, Wa, Fa, ufa);
1250 }
1251 const long j = i + (long)((c == 0) ? 1 : (c == 1) ? e.x : (long)e.x * e.y);
1252 const double oLo = o(i), oHi = o(j);
1253 const double wsum = varrho::weightSum(oLo, oHi);
1254 const double fcell = haveFb ? wsum * fb(i) : 0.0;
1255 const double pf = rhoC * varrho::cellFromFaces(phiF(i), phiF(j), oLo, oHi);
1256 bb(i) =
1257 rs(i) * (dg * un(i) - rhoC * aK + rhoC * aF + fcell + pf) + (bc ? brhs(i) : -inh(i));
1258 });
1259}
1260
1261template <class Grid>
1263 CCExec space;
1264 Kokkos::deep_copy(tgp_, f);
1265 fillGhosts(tgp_);
1266 CCConst src = CCConst(tgp_);
1267 CCConst sd = CCConst(sdf_);
1268 const double eps = rotFilterEps_;
1269 C3 e = e_;
1270 using MD = MDRange3<CCExec>;
1271 Kokkos::parallel_for(
1272 "peclet::flow::rot_filter", MD(space, {G, G, G}, {e.x - G, e.y - G, e.z - G}),
1273 KOKKOS_LAMBDA(int x, int y, int z) {
1274 const long sy = e.x, sz = (long)e.x * e.y;
1275 const long i = (long)x + (long)y * sy + (long)z * sz;
1276 const long sa = (axis == 0) ? 1 : (axis == 1) ? sy : sz;
1277 if (sd(i) < 0.0)
1278 return;
1279 const bool am = sd(i - sa) >= 0.0, ap = sd(i + sa) >= 0.0;
1280 double sm;
1281 if (am && ap)
1282 sm = 0.25 * (src(i - sa) + 2.0 * src(i) + src(i + sa));
1283 else if (ap)
1284 sm = 0.5 * (src(i) + src(i + sa));
1285 else if (am)
1286 sm = 0.5 * (src(i) + src(i - sa));
1287 else
1288 sm = src(i);
1289 // eps-floor blend: S' = eps*I + (1-eps)*S. A pure S has an exact checkerboard null
1290 // space, which at dt -> infinity (where the (rho/dt)*phi term vanishes) degenerates the
1291 // fixed point into a frozen-checkerboard family; the floor keeps S' > 0 so
1292 // (rho/dt + mu S'A) phi = 0 forces phi = 0 at EVERY dt, while still cutting the
1293 // dangerous mode's feedback gain by ~1/eps.
1294 f(i) = eps * src(i) + (1.0 - eps) * sm;
1295 });
1296}
1297
1298template <class Grid>
1301 if (!coeffBuiltThisStep_) // the balanced-force stage (B1) already built them this step
1303 projectSolve();
1306}
1307
1308template <class Grid>
1310 // ghosts incl. domain BCs (outflow zero-gradient) BEFORE the divergence -- matches CUDA
1311 // apply_velocity_bc before diverg_open, so div(u*) counts the outflow flux (else the rotational
1312 // pressure pumps the mis-counted outflow divergence and blows up the outflow-wall corner).
1313 if constexpr (Grid::collocated) {
1314 // Approximate (MAC) projection: average the cell velocities onto a face field, then project
1315 // THAT. Use the BC-aware ghost fill (periodic / cross-rank + domain BCs) so the averaged
1316 // inflow/outflow faces carry the right value -- at open boundaries the flux is counted
1317 // (closed walls are openness 0).
1318 for (int c = 0; c < 3; ++c)
1319 fillVelGhosts(c, 0);
1320 if (colocatedFaceForce()) {
1321 // Rung V8 (S8.1): the constraint's face field is the MOMENTUM-weighted map Pi_rho u*, the
1322 // adjoint partner of the predictor's pressure force (collocated_varrho.hpp; §4.3). No face
1323 // acceleration: every force already went through the implicit predictor.
1324 if (effVarRho())
1325 centerToFaceMassWeighted(uf_, vf_, wf_, CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u),
1326 CCConst(effRhoField()), e_, G);
1327 else
1328 centerToFace(uf_, vf_, wf_, CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u), e_, G);
1329 } else if (faceInterp_ == 5 || faceInterp_ == 7) // wall-aware flux map at solid (embed 5/7)
1330 centerToFaceWallAware(uf_, vf_, wf_, CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u),
1331 CCConst(sdf_), CCConst(xcx_), CCConst(xcy_), CCConst(xcz_), true, e_,
1332 G);
1333 else
1334 centerToFace(uf_, vf_, wf_, CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u), e_, G);
1335 faceFieldValid_ = true; // ISSUES sweep item 5
1336 if (ghostProjection_) {
1337 // Collocated ghost divergence: the SAME binary-openness + closure-delta pair as the
1338 // staggered path, applied to the 1/2-1/2 face-averaged field (the closures only ever read
1339 // faces whose two adjacent centers are fluid, so the masked solid-cell zeros never enter
1340 // except at EXPLICIT slivers — faithfully modelled in the a-priori study).
1341 if (gpNRows_ < 0)
1342 throw std::runtime_error("ghost projection: call set_solid after set_ghost_projection");
1343 if (porous_ || varRho_ || useChebyshev_)
1344 throw std::runtime_error(
1345 "ghost projection: porous/variable-rho/Chebyshev unsupported (v1)");
1346 divergOpen(CCConst(uf_), CCConst(vf_), CCConst(wf_), CCConst(oxb_), CCConst(oyb_),
1347 CCConst(ozb_), div_, e_, G);
1348 gpDivergDelta(div_, CCConst(uf_), CCConst(vf_), CCConst(wf_), gpOv_, gpNRows_,
1349 C3{nx_, ny_, nz_}, e_, G, distributed_);
1350 } else
1351 constraintDivergence(CCConst(uf_), CCConst(vf_), CCConst(wf_), div_);
1352 } else {
1353 for (int c = 0; c < 3; ++c)
1354 fillVelGhosts(c, 0);
1355 if (porous_) { // volume-averaged continuity: div(open*eps*u*), constraint div(eps
1356 // u)=-d(eps)/dt
1357 fillPorousEpsGhosts(); // BEFORE the divergence — one eps ghost policy for RHS,
1358 // coefficients and residual (the deposit rewrites these ghosts
1359 // every step)
1360 divergOpenEps(CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u), CCConst(ox_), CCConst(oy_),
1361 CCConst(oz_), CCConst(epsField_), div_, e_, G);
1362 } else if (ghostProjection_) {
1363 // Directional ghost-cell divergence: binary-openness face differences (COUPLED faces)
1364 // plus the wall-anchored closures at ghost faces, row-rescaled — the SAME kernel pair
1365 // serves the RHS here and the diagnostic in maxOpenDivergence (diagnostic == residual).
1366 if (gpNRows_ < 0)
1367 throw std::runtime_error("ghost projection: call set_solid after set_ghost_projection");
1368 if (porous_ || varRho_ || useChebyshev_)
1369 throw std::runtime_error(
1370 "ghost projection: porous/variable-rho/Chebyshev unsupported (v1)");
1371 divergOpen(CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u), CCConst(oxb_), CCConst(oyb_),
1372 CCConst(ozb_), div_, e_, G);
1373 gpDivergDelta(div_, CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u), gpOv_, gpNRows_,
1374 C3{nx_, ny_, nz_}, e_, G, distributed_);
1375 } else
1376 constraintDivergence(CCConst(C[0].u), CCConst(C[1].u), CCConst(C[2].u), div_);
1377 }
1378 // MOVING GEOMETRY (rung 3): the wall's own volume flux. Inert without a moving instance.
1380 // WO-P01: the phase-change (and any prescribed) divergence source, so the deflated solve
1381 // delivers div(open u) = S instead of 0. Inert unless enable_phase_change /
1382 // set_divergence_source ran.
1384 // Porous continuity source: fold d(eps)/dt into the divergence so the Poisson solves for
1385 // div(eps u) = -d(eps)/dt (not 0). d(eps)/dt = (eps^{n+1}-eps^n)/dt from the deposited void
1386 // fraction; stored in depsdt_ (epsPrev_ is overwritten at step end, so the residual reuses
1387 // this).
1388 if (porous_) {
1389 CCExec space;
1390 C3 e = e_; // local copy — a KOKKOS_LAMBDA capturing e_ would read this-> on the device
1391 CCField d = div_, dd = depsdt_, ep = epsField_, epp = epsPrev_;
1392 const double idt = 1.0 / dt_;
1393 const bool useDt = porousDepsDt_;
1394 using MD = MDRange3<CCExec>;
1395 Kokkos::parallel_for(
1396 "peclet::flow::deps_dt", MD(space, {G, G, G}, {e.x - G, e.y - G, e.z - G}),
1397 KOKKOS_LAMBDA(int x, int y, int z) {
1398 const long i = (long)x + (long)y * e.x + (long)z * e.x * e.y;
1399 dd(i) = (ep(i) - epp(i)) * idt;
1400 if (useDt)
1401 d(i) += dd(i); // off -> solve div(eps u)=0 (drop the noisy time-derivative source)
1402 });
1403 }
1404 // bridge -div(u*) (g=2 block) -> the MG rhs (g=1 block); keep div(u*) in div_ for the pressure
1405 // update
1406 copyInner(rhs1_, e1_, 1, CCConst(div_), e_, G);
1407 {
1408 CCExec space;
1409 CCField r = rhs1_;
1410 Kokkos::parallel_for(
1411 "negdiv", Kokkos::RangePolicy<CCExec>(space, 0, n1_),
1412 KOKKOS_LAMBDA(std::size_t i) { r(i) = -r(i); });
1413 }
1414 if (fluidOnlyMode_ == 2) {
1415 // Design B: solid rows carry no constraint -- mask their rhs (their operator rows are empty
1416 // in the filtered 7-point part; the star overlay never adds to them), so phi_s stays 0.
1417 if (useChebyshev_)
1418 throw std::runtime_error("set_fluid_only_constraint(2): Chebyshev unsupported (v1)");
1419 CCExec space;
1420 CCField r = rhs1_;
1421 CCConst sd = CCConst(sdf_);
1422 const C3 e1 = e1_, e2 = e_;
1423 Kokkos::parallel_for(
1424 "peclet::flow::star_mask_rhs", MDRange3<CCExec>(space, {0, 0, 0}, {nx_, ny_, nz_}),
1425 KOKKOS_LAMBDA(int x, int y, int z) {
1426 const long i2 = (long)(x + G) + (long)(y + G) * e2.x + (long)(z + G) * (long)e2.x * e2.y;
1427 if (sd(i2) < 0.0)
1428 r((long)(x + 1) + (long)(y + 1) * e1.x + (long)(z + 1) * (long)e1.x * e1.y) = 0.0;
1429 });
1430 }
1431}
1432
1433template <class Grid>
1435 // Variable density: rebuild the Poisson operator with the face coefficients
1436 // c_f = open_f * rho0/rho_f (rho0 = the scalar rho_, so uniform rho == rho_ reduces exactly to
1437 // the openness operator). The coefficient fields ride the openness rails: bridge rho to the g=1
1438 // block INCLUDING its ghost ring, form the coefficients on the inner cells, and hand them to
1439 // setOpenness, whose per-level ghost fill + boundary re-imposition + coarsening (rediscretized
1440 // averaging) treat them exactly like openness. Rebuilt every step (rho may be closure/transport
1441 // driven); Chebyshev bounds are invalidated (stale bounds under changing coefficients diverge
1442 // silently — PCG is the recommended/default driver here).
1443 // H-2a (doc/vof_projection_cost_design.md §8): on a single rank without an outflow face the
1444 // coefficients are built straight into the MG's level-0 fields (no staging copies); otherwise
1445 // into cx1_/cy1_/cz1_, which setOpenness copies, as before.
1446 const bool inPlace = !mg_.distributed() && !hasOutflow_;
1447 CCField cx = inPlace ? mg_.level0Coefficient(0) : cx1_;
1448 CCField cy = inPlace ? mg_.level0Coefficient(1) : cy1_;
1449 CCField cz = inPlace ? mg_.level0Coefficient(2) : cz1_;
1450 if (varRho_) {
1451 fillPropGhosts(rhoField_);
1452 copyBlockShifted(rho1_, e1_, CCConst(rhoField_), e_, G - 1);
1453 // Face mean of rho: ARITHMETIC by default (the hydrostatic-exactness + series-mobility
1454 // choice); the harmonic sibling is the opt-in WO-J knob and must be paired with the matching
1455 // correction in projectVelocities or the projection stops being exact (mac_pressure.hpp).
1456 if (rhoFaceHarmonic_)
1457 buildRhoCoeffHarm(cx, cy, cz, CCConst(ox1_), CCConst(oy1_), CCConst(oz1_), CCConst(rho1_),
1458 rho_, e1_, 1);
1459 else
1460 buildRhoCoeff(cx, cy, cz, CCConst(ox1_), CCConst(oy1_), CCConst(oz1_), CCConst(rho1_), rho_,
1461 e1_, 1);
1462 // WO-R2 item 1: buildRhoCoeff covers the LOW domain face of each axis (an inner index) but
1463 // not the HIGH one (a ghost index). Fill the high outflow planes here, and tell the MG to
1464 // carry the caller's coefficient at every Dirichlet domain face instead of re-imposing the
1465 // literal openness 1.0 (which used to overwrite `rho0/rho_f` with 1 on BOTH sides and made
1466 // the low-side outlet inconsistent with projectCorrectVar by the full density ratio).
1467 {
1468 CCField cc[3] = {cx, cy, cz};
1469 CCField oo[3] = {ox1_, oy1_, oz1_};
1470 for (int a = 0; a < 3; ++a)
1471 if (bc_[2 * a + 1] == 3 && touchesGlobalFace(2 * a + 1))
1472 buildRhoCoeffOutflowFace(cc[a], CCConst(oo[a]), CCConst(rho1_), rho_, e1_, 1, a,
1473 rhoFaceHarmonic_);
1474 }
1475 mg_.setBoundaryConditions(bc_);
1476 mg_.setOutflowCoefficient(hasOutflow_ && outflowOpCoeff_);
1477 mg_.setOpenness(CCConst(cx), CCConst(cy), CCConst(cz), u_.w[0], u_.w[1], u_.w[2]);
1478 mg_.setOutflowCoefficient(false);
1479 // The spectrum changed with the coefficients: re-estimated by the solve, warm-started from
1480 // the previous estimate's iterates when the bounds being dropped were valid (D3, §5.13).
1481 chebWarmOk_ = chebWarmOk_ || chebBoundsSet_;
1482 chebBoundsSet_ = false;
1483 }
1484 // Porous continuity: the Poisson operator is eps-weighted (c_f = open_f * eps_f), same rails as
1485 // the density coefficient above. Rebuilt every step (eps moves with the particles). With
1486 // implicit CFD-DEM drag the coefficient AND the correction carry the drag-relaxation w_f =
1487 // idt/(idt+beta_f) (idt = rho/dt) so the pressure correction is consistent with the drag-loaded
1488 // momentum diagonal A_P = idt+beta (SIMPLE/PISO-with-implicit-drag; stiff drag -> w_f->0 -> the
1489 // drag holds the velocity, stable). beta==0 reduces exactly to the plain eps-weighted operator.
1490 if (porous_) {
1491 // eps ghosts were filled by fillPorousEpsGhosts() before the divergence above — the SAME
1492 // ghost values must feed the coefficient bridge (face eps == 1 at open domain faces), or the
1493 // operator and the RHS disagree at the boundary rows.
1494 copyBlockShifted(eps1_, e1_, CCConst(epsField_), e_, G - 1);
1495 if (hasDrag_) {
1496 fillPropGhosts(dragBeta_);
1497 copyBlockShifted(beta1_, e1_, CCConst(dragBeta_), e_, G - 1);
1498 } else if (porousCons_) {
1499 Kokkos::deep_copy(beta1_, 0.0); // conservative kernels read beta unconditionally when used
1500 }
1501 if (porousCons_) {
1502 // eps-CONSERVATIVE pair: c_f = open * (eps_f rho idt)/(eps_f rho idt + beta_f), matching
1503 // the eps-weighted momentum diagonal; the eps of the flux cancels the eps of the inertia
1504 // (see mac_pressure.hpp). Correction: projectCorrectPorousCons below.
1505 buildPorousCoeffCons(cx, cy, cz, CCConst(ox1_), CCConst(oy1_), CCConst(oz1_), CCConst(eps1_),
1506 CCConst(beta1_), hasDrag_, rho_ / dt_, e1_, 1);
1507 } else if (hasDrag_) {
1508 buildPorousCoeffDrag(cx, cy, cz, CCConst(ox1_), CCConst(oy1_), CCConst(oz1_), CCConst(eps1_),
1509 CCConst(beta1_), rho_ / dt_, e1_, 1);
1510 } else {
1511 buildPorousCoeff(cx, cy, cz, CCConst(ox1_), CCConst(oy1_), CCConst(oz1_), CCConst(eps1_), e1_,
1512 1);
1513 }
1514 mg_.setBoundaryConditions(bc_);
1515 // SCALING_ISSUES #3: the widened porous builders above wrote the HIGH Dirichlet face plane
1516 // too, so the outlet row carries open_f*eps_f (and w_f) exactly like every inner face,
1517 // instead of the literal openness 1.0.
1518 mg_.setOutflowCoefficient(hasOutflow_ && outflowOpCoeff_);
1519 mg_.setOpenness(CCConst(cx), CCConst(cy), CCConst(cz), u_.w[0], u_.w[1], u_.w[2]);
1520 mg_.setOutflowCoefficient(false);
1521 chebWarmOk_ = chebWarmOk_ || chebBoundsSet_; // a coefficient rebuild, as above (D3)
1522 chebBoundsSet_ = false;
1523 }
1524}
1525
1526template <class Grid>
1528 // geometric multigrid solve of the cut-cell pressure Poisson A phi = -div(u*) (CUDA
1529 // mac_multigrid): MG-PCG by default, or the communication-light Chebyshev driver (bounds
1530 // estimated once, then reused). Warm start (CUDA pwarm_): keep the previous step's phi1_ as the
1531 // initial guess instead of zeroing.
1532 // E (doc/vof_projection_cost_design.md §5.3, set_pressure_initial_guess): the projected guess
1533 // on an eligible solve ('auto' / 'projected'); 'zero' (the default) is the cold path below.
1534 bool guess = false;
1535 if (pguessMode_ != 1) {
1536 const char* why = projectedGuessIneligible();
1537 if (why && pguessMode_ == 2)
1538 throw std::runtime_error(
1539 std::string("set_pressure_initial_guess('projected'): not eligible here: ") + why);
1540 guess = why == nullptr;
1541 }
1542 if (!guess) {
1543 pguessCount_ = 0; // the history holds consecutive projected-guess solves only
1544 if (!pwarm_)
1545 Kokkos::deep_copy(CCExec(), phi1_, 0.0);
1546 // H-2c: on the cold path phi1_ is +0, and the single-rank PCG skips its A x0 (scoped to this
1547 // one solve, exception-safe).
1548 {
1549 struct ZeroGuessScope {
1550 CutcellMG& mg;
1551 ~ZeroGuessScope() { mg.setZeroInitialGuess(false); }
1552 } zeroGuessScope{mg_};
1553 mg_.setZeroInitialGuess(!pwarm_);
1554 lastPressureIters_ = solvePressureSystem(rhs1_, phi1_);
1555 }
1556 } else {
1557 // Buffers: phi1_ holds phi^n, phiPrev1_ phi^{n-1} (history 2); the solve writes into
1558 // phiPrev1_, then the handles swap (no copies). History 0 is the cold solve, bitwise.
1559 const int driver = useFcg_ ? 2 : 1;
1560 if (phiPrev1_.extent(0) != n1_) {
1561 phiPrev1_ = CCField("phiPrev1", n1_);
1562 pguessCount_ = 0;
1563 }
1564 if (driver != pguessDriver_)
1565 pguessCount_ = 0; // a driver change
1566 pguessDriver_ = driver;
1567 const int hist = std::min(pguessCount_, pguessHistMax_);
1568 struct GuessScope {
1569 CutcellMG& mg;
1570 ~GuessScope() {
1571 mg.setZeroInitialGuess(false);
1573 }
1574 } guessScope{mg_};
1575 if (hist == 0) {
1576 Kokkos::deep_copy(phiPrev1_, 0.0);
1577 mg_.setZeroInitialGuess(true);
1578 }
1579 mg_.setProjectedGuess(phi1_, hist);
1580 lastPressureIters_ = solvePressureSystem(rhs1_, phiPrev1_);
1581 std::swap(phi1_, phiPrev1_);
1582 pguessCount_ = std::min(pguessCount_ + 1, pguessHistMax_);
1583 if (mg_.lastSolveFailed() || lastPressureIters_ >= pcgMaxit_)
1584 pguessCount_ = 0; // a failed or capped solve
1585 }
1586 // ISSUES sweep item 6: a solve that gave up on a non-finite recurrence scalar reports the
1587 // iteration CAP (see CutcellMG::solvePCG) and raises this flag, so `pressure_solve_failed()`
1588 // and the usual rule-3b "no capped solve" check both catch it. It used to print one line to
1589 // stdout, silently zero the correction and report 0 iterations.
1590 lastPressureFailed_ = mg_.lastSolveFailed();
1591 if (fluidOnlyMode_ == 2) {
1592 // Pin phi at solid-centered cells to 0 (their rows are unconstrained; the smoother must not
1593 // leave garbage there -- projectCorrect reads phi_s at fluid|solid faces and the
1594 // starCorrectFaces fix-up assumes the applied value was exactly 0).
1595 CCExec space;
1596 CCField ph = phi1_;
1597 CCConst sd = CCConst(sdf_);
1598 const C3 e1 = e1_, e2 = e_;
1599 Kokkos::parallel_for(
1600 "peclet::flow::star_pin_solid", MDRange3<CCExec>(space, {0, 0, 0}, {nx_, ny_, nz_}),
1601 KOKKOS_LAMBDA(int x, int y, int z) {
1602 const long i2 = (long)(x + G) + (long)(y + G) * e2.x + (long)(z + G) * (long)e2.x * e2.y;
1603 if (sd(i2) < 0.0)
1604 ph((long)(x + 1) + (long)(y + 1) * e1.x + (long)(z + 1) * (long)e1.x * e1.y) = 0.0;
1605 });
1606 }
1607 copyInner(phi_, e_, G, CCConst(phi1_), e1_, 1); // bridge phi back g=1 -> g=2
1608 fillGhosts(phi_);
1609 if (hasOutflow_) { // hold phi=0 at the outflow ghost so grad(phi) drives the outflow face
1610 // (Dirichlet p=0)
1611 B3 e{e_.x, e_.y, e_.z};
1612 for (int a = 0; a < 3; ++a)
1613 for (int s = 0; s < 2; ++s)
1614 if (bc_[2 * a + s] == 3 && touchesGlobalFace(2 * a + s))
1615 bcZeroPressureGhost(phi_, e, G, a, s);
1616 }
1617}
1618
1619template <class Grid>
1621 ++chebGrowthTrips_;
1622 if (chebGrowthWarned_)
1623 return;
1624 chebGrowthWarned_ = true;
1625 int r = 0;
1626#ifdef PECLET_FLOW_MPI
1627 if (distributed_)
1628 MPI_Comm_rank(comm_, &r);
1629#endif
1630 if (r == 0)
1631 std::fprintf(stderr,
1632 "peclet::flow notice: a Chebyshev pressure solve on cold spectral bounds saw its "
1633 "residual grow (iteration %ld): lambda_max was underestimated; the bounds were "
1634 "re-estimated with a bracketing margin and the solve redone. Further cases are "
1635 "counted silently in diagnostics.num_pressure_chebyshev_growth_trips.\n",
1636 iters);
1637}
1638
1639template <class Grid>
1641 long iters = 0;
1642 if (useChebyshev_) {
1643 // D3 (doc/vof_step_performance_design.md §5.13): after a coefficient rebuild the bounds are
1644 // re-estimated from the previous estimate's last v_max / v_min iterates with 5 + 5 power
1645 // iterations instead of 15 + 15 from the right-hand side. Guard: a solve on such bounds that
1646 // reaches the cap, or whose residual after 3 iterations exceeds r0, is redone from its
1647 // starting iterate on cold bounds (counted in chebColdRestarts_). Every other estimate --
1648 // the first, and the one after a structural change (a driver/density/porous setter, a
1649 // hierarchy rebuild) -- is the cold one, unchanged.
1650 using ES = typename CutcellMG::EigenStart;
1651 // The bounds ratchet ((b), chebLmaxFloor_): lambda_max never drops below a growth trip's
1652 // bracketed value. Bitwise inert while no trip has happened (floor 0).
1653 auto ratchet = [&]() {
1654 if (chebB_ < chebLmaxFloor_)
1655 chebB_ = chebLmaxFloor_;
1656 };
1657 bool warm = false;
1658 if (!chebBoundsSet_) {
1659 if (!chebWarmOk_) // a structural invalidation (or the first estimate): no floor
1660 chebLmaxFloor_ = 0.0;
1661 warm = chebWarmOk_ && mg_.eigenWarmReady();
1662 mg_.estimateEigenvalues(CCConst(rhs1), chebA_, chebB_, warm ? 5 : 15, 2, 2, 12,
1663 warm ? ES::Warm : ES::ColdKeep);
1664 if (warm && !mg_.eigenWarmReady()) { // the warm estimate came out degenerate: cold one
1665 warm = false;
1666 mg_.estimateEigenvalues(CCConst(rhs1), chebA_, chebB_, 15, 2, 2, 12, ES::ColdKeep);
1667 }
1668 ratchet();
1669 chebBoundsSet_ = true;
1670 }
1671 // Under the pressure warm start the starting iterate is the previous phi: kept for a redo
1672 // (otherwise it is zero).
1673 auto keepStart = [&]() {
1674 if (pwarm_) {
1675 if (chebX0_.extent(0) != x1.extent(0))
1676 chebX0_ = CCField("chebX0", x1.extent(0));
1677 Kokkos::deep_copy(CCExec(), chebX0_, x1);
1678 }
1679 };
1680 auto restoreStart = [&]() {
1681 if (pwarm_)
1682 Kokkos::deep_copy(CCExec(), x1, chebX0_);
1683 else
1684 Kokkos::deep_copy(CCExec(), x1, 0.0);
1685 };
1686 // A solve on COLD-estimated bounds runs the growth guard (doc/mg_depth_policy_log.md
1687 // 2026-10-30): a residual above r0 at any iteration means lambda_max was underestimated
1688 // (the top lies above 0.95 lmin + 1.05 lmax); the bounds are re-estimated cold with the
1689 // bracketing margin and the solve is redone once from its starting iterate. Inert unless
1690 // it trips.
1691 auto coldSolve = [&]() {
1692 keepStart();
1693 long it = mg_.solveChebyshev(rhs1, x1, chebMaxit_, chebRtol_, 2, 2, 12, chebA_, chebB_, false,
1694 true);
1695 if (mg_.chebyshevGuardTripped()) {
1697 mg_.estimateEigenvalues(CCConst(rhs1), chebA_, chebB_, 15, 2, 2, 12, ES::ColdKeep,
1699 ratchet();
1700 chebLmaxFloor_ = chebB_; // the bracketed bounds persist ((b))
1701 restoreStart();
1702 it += mg_.solveChebyshev(rhs1, x1, chebMaxit_, chebRtol_, 2, 2, 12, chebA_, chebB_);
1703 }
1704 return it;
1705 };
1706 if (!warm) {
1707 iters = coldSolve();
1708 } else {
1709 keepStart();
1710 iters = mg_.solveChebyshev(rhs1, x1, chebMaxit_, chebRtol_, 2, 2, 12, chebA_, chebB_, true);
1711 if (iters >= chebMaxit_ || mg_.chebyshevGuardTripped()) {
1712 ++chebColdRestarts_;
1713 mg_.estimateEigenvalues(CCConst(rhs1), chebA_, chebB_, 15, 2, 2, 12, ES::ColdKeep);
1714 ratchet();
1715 restoreStart();
1716 iters += coldSolve();
1717 }
1718 }
1719 } else if (ghostProjection_) {
1720 // Nonsymmetric ghost-projection operator (both grids — the phi matrix is identical):
1721 // BiCGStab, preconditioned by the symmetric binary-openness V-cycle (the hierarchy set up
1722 // in setSolid); the overlay delta enters the fine-level matvec only. Distributed, the
1723 // matvec stages the iterate on this solver's g=2 block (gpX2_) whose halo carries the
1724 // overlay's +/-2 reach.
1725#ifdef PECLET_FLOW_MPI
1726 if (distributed_)
1727 iters =
1728 mg_.solveBiCGStab(rhs1, x1, r_, gpRh_, pp_, Ap_, gpT_, z_, gpZ2_, pcgMaxit_, pcgRtol_, 2,
1729 2, 12, gpOv_, gpNRows_, C3{nx_, ny_, nz_}, gpX2_, velDev_.get(), e_);
1730 else
1731#endif
1732 iters = mg_.solveBiCGStab(rhs1, x1, r_, gpRh_, pp_, Ap_, gpT_, z_, gpZ2_, pcgMaxit_, pcgRtol_,
1733 2, 2, 12, gpOv_, gpNRows_, C3{nx_, ny_, nz_});
1734 // Pin the FREE variables of the binary-openness operator to their design value phi = 0:
1735 // solid-centered (sdfGp < 0) cells and fully-BC_ONLY overlay rows have a zero row AND zero
1736 // rhs, so the Krylov iteration leaves an arbitrary (V-cycle-prolongation, iteration-path,
1737 // and decomposition dependent) value there — invisible to the gp residual (the closures
1738 // never read those faces) but INJECTED into real near-wall fluid velocities by the plain
1739 // projectCorrect face gradient. The doc contract of ghost_projection.hpp is "decoupled
1740 // rows hold phi = 0"; enforce it (measured: without this, np=2 runs differ from the
1741 // reference by ~1e-2 relative u at sphere-surface faces while agreeing 1e-13 elsewhere).
1742 {
1743 CCExec space;
1744 CCField ph = x1;
1745 CCConst sg = CCConst(sdfGp_);
1746 auto idMap = gpIdMap_;
1747 auto ov = gpOv_;
1748 const C3 e1 = e1_, e2 = e_;
1749 const int lnx = nx_, lny = ny_;
1750 Kokkos::parallel_for(
1751 "peclet::flow::gp_pin_decoupled", MDRange3<CCExec>(space, {0, 0, 0}, {nx_, ny_, nz_}),
1752 KOKKOS_LAMBDA(int x, int y, int z) {
1753 const long i1 =
1754 (long)(x + 1) + (long)(y + 1) * e1.x + (long)(z + 1) * (long)e1.x * e1.y;
1755 const long i2 =
1756 (long)(x + G) + (long)(y + G) * e2.x + (long)(z + G) * (long)e2.x * e2.y;
1757 bool dec = sg(i2) < 0.0;
1758 if (!dec) {
1759 const int s = idMap((long)x + (long)y * lnx + (long)z * (long)lnx * lny);
1760 if (s >= 0 && ov.coupled(s) == 0)
1761 dec = true;
1762 }
1763 if (dec)
1764 ph(i1) = 0.0;
1765 });
1766 }
1767 } else if (useFcg_) {
1768 // Flexible CG (set_pressure_fcg): identical to the MG-PCG branch below but for the
1769 // Polak-Ribiere beta, which tolerates a V-cycle preconditioner that is not symmetric w.r.t.
1770 // the fine operator. Its one extra vector is allocated on first use, so an unselected FCG
1771 // costs nothing (not even memory).
1772 if (zp1_.extent(0) != n1_)
1773 zp1_ = CCField("zp1", n1_);
1774 iters = mg_.solveFCG(rhs1, x1, r_, pp_, z_, zp1_, Ap_, pcgMaxit_, pcgRtol_, 2, 2, 12,
1775 fluidOnlyMode_ == 2 ? &starOv_ : nullptr, nStar_, C3{nx_, ny_, nz_});
1776 checkCgExit(rhs1, x1, iters, "flexible-CG", fluidOnlyMode_ == 2 ? &starOv_ : nullptr);
1777 } else {
1778 iters = mg_.solvePCG(rhs1, x1, r_, pp_, z_, Ap_, pcgMaxit_, pcgRtol_, 2, 2, 12,
1779 fluidOnlyMode_ == 2 ? &starOv_ : nullptr, nStar_, C3{nx_, ny_, nz_});
1780 checkCgExit(rhs1, x1, iters, "MG-PCG", fluidOnlyMode_ == 2 ? &starOv_ : nullptr);
1781 }
1782 return iters;
1783}
1784
1785template <class Grid>
1786void Solver<Grid>::checkCgExit(CCField rhs1, CCField x1, long iters, const char* which,
1787 const StarOverlay* star) {
1788 // Q18 (a). Everything read here is global -- the iteration count, the breakdown flag and the
1789 // allreduced residual ratio -- so every rank takes the same decision and keeps the same count.
1790 // `star` is the overlay the driver's fine matvec carried (mode B's main solve only).
1792 const bool failed = mg_.lastSolveFailed();
1793 lastPressureTrueResidual_ =
1794 mg_.cgTrueResidual(rhs1, x1, r_, Ap_, star, star ? nStar_ : 0, C3{nx_, ny_, nz_});
1795 const bool capped = iters >= pcgMaxit_ || failed;
1796 const double limit = std::max(kCgGuardFactor, kCgGuardFloor / pcgRtol_);
1797 if (!capped && lastPressureTrueResidual_ <= limit) // NaN-safe: a NaN ratio reports
1798 return;
1799 ++numPressureUnconvergedSolves_;
1800 if (numPressureUnconvergedSolves_ < cgGuardNextReport_)
1801 return;
1802 cgGuardNextReport_ *= 10;
1803 int r = 0;
1804#ifdef PECLET_FLOW_MPI
1805 if (distributed_)
1806 MPI_Comm_rank(comm_, &r);
1807#endif
1808 if (r == 0)
1809 std::fprintf(
1810 stderr,
1811 "peclet::flow: the %s pressure solve did not converge (%s; true residual "
1812 "max|b - A x| = %.3g x the stop tolerance rtol*r0, limit %.3g, rtol %.1e) -- the "
1813 "field it returned is not a projection. %ld such solve%s so far "
1814 "(diagnostics.num_pressure_unconverged_solves; next report at %ld). Chebyshev, the "
1815 "variable-density default, is healthy at high density contrast "
1816 "(set_pressure_chebyshev).\n",
1817 which,
1818 failed ? "broke down"
1819 : iters >= pcgMaxit_ ? "capped"
1820 : "stopped on its recurrence residual",
1821 lastPressureTrueResidual_, limit, pcgRtol_, numPressureUnconvergedSolves_,
1822 numPressureUnconvergedSolves_ == 1 ? "" : "s", cgGuardNextReport_);
1823}
1824
1825template <class Grid>
1827 // Q18 (b): once per explicit set_pressure_pcg/_fcg selection, at its first solve under
1828 // variable density, name Chebyshev if the density contrast is in the regime where both CG
1829 // drivers fail: above ~1e3 under the trilinear V-cycle (set_pressure_vcycle_symmetric(False)).
1830 // The default SPD V-cycle (A3) keeps them healthy there, so it stays silent. One min/max
1831 // reduction, at most once per selection.
1832 if (!cgContrastPending_ || !varRho_ || rhoField_.extent(0) == 0 || mg_.symmetricVcycle())
1833 return;
1834 cgContrastPending_ = false;
1835 CCConst f = CCConst(rhoField_);
1836 const C3 e = e_;
1837 double ext[2] = {-1e300, -1e300}; // {max rho, max -rho}: two single reducers, no combined one
1838 for (int k = 0; k < 2; ++k) {
1839 const double sg = k == 0 ? 1.0 : -1.0;
1840 Kokkos::parallel_reduce(
1841 "peclet::flow::cg_rho_extrema",
1842 MDRange3<CCExec>(CCExec(), {G, G, G}, {e.x - G, e.y - G, e.z - G}),
1843 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
1844 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
1845 acc = Kokkos::fmax(acc, sg * f(i));
1846 },
1847 Kokkos::Max<double>(ext[k]));
1848 }
1849 double mx = ext[0], mn = -ext[1];
1850 int r = 0;
1851#ifdef PECLET_FLOW_MPI
1852 if (distributed_) {
1853 double g[2] = {-mn, mx}, o[2];
1854 MPI_Allreduce(g, o, 2, MPI_DOUBLE, MPI_MAX, comm_);
1855 mn = -o[0];
1856 mx = o[1];
1857 MPI_Comm_rank(comm_, &r);
1858 }
1859#endif
1860 if (r == 0 && mn > 0.0 && mx >= 1e3 * mn)
1861 std::fprintf(
1862 stderr,
1863 "peclet::flow: set_pressure_%s selected under variable density with "
1864 "rho_max/rho_min = %.3g and the trilinear V-cycle (set_pressure_vcycle_symmetric(False)). "
1865 "Both CG drivers fail above a density ratio of ~1e3 with that V-cycle (the "
1866 "preconditioner turns indefinite); Chebyshev, the variable-density "
1867 "default, is healthy there (set_pressure_chebyshev). Unconverged CG solves are "
1868 "reported and counted (diagnostics.num_pressure_unconverged_solves).\n",
1869 useFcg_ ? "fcg" : "pcg", mx / mn);
1870}
1871
1872template <class Grid>
1874 divergOpen(fx, fy, fz, CCConst(ox_), CCConst(oy_), CCConst(oz_), out, e_, G);
1875}
1876
1877template <class Grid>
1879 if constexpr (Grid::collocated) {
1880 projectPhiWallGhosts();
1881 projectCorrectFaceField();
1882 projectCorrectFaceFieldOutflow();
1883 // The face field is now final for this step. Derive the OPEN-boundary view the next
1884 // predictor's advection and the divergence diagnostic read (buildOpenFaceField explains why
1885 // the outflow face cannot be the mass-balance closure there); a no-op without an outflow.
1887 projectCorrectCellField();
1888 } else {
1889 projectCorrectStaggered();
1890 projectCorrectStaggeredOutflow();
1891 }
1892 // the grad(phi) correction also touches solid faces; re-impose no-slip there so the decoupled
1893 // solid velocity cannot accumulate (matches the CUDA apply_mask/mask_k after correct_k ->
1894 // stability).
1895 for (int c = 0; c < 3; ++c)
1896 maskVelocity(c);
1897}
1898
1899template <class Grid>
1900void Solver<Grid>::projectPhiWallGhosts() {
1901 // phi: zero-gradient (Neumann) at non-periodic walls so the cell-centered central-difference
1902 // correction carries no spurious normal acceleration through the wall (the periodic fill
1903 // wrapped the opposite boundary's phi). Outflow (Dirichlet p=0) is handled by hasOutflow_
1904 // above (phase 5b).
1905 if (hasBc_) {
1906 B3 e{e_.x, e_.y, e_.z};
1907 for (int a = 0; a < 3; ++a)
1908 for (int s = 0; s < 2; ++s) {
1909 const int t = bc_[2 * a + s];
1910 if (t != 0 && t != 3 && touchesGlobalFace(2 * a + s))
1911 bcNeumannGhost(phi_, e, G, a, s);
1912 }
1913 }
1914}
1915
1916template <class Grid>
1917void Solver<Grid>::projectCorrectFaceField() {
1918 // Correct the face field (-> discretely divergence-free; transient this step) and the cell
1919 // field (central-difference cell gradient).
1920 // rung V8: per-face 1/rho_f on the gradient, matching the operator coefficient
1921 // c_f = o_f*rho0/rho_f — the SAME exact-adjoint face correction the staggered path uses.
1922 // Phase 2 C2 (doc/anisotropic_metric.md §3): the per-axis weight w_a multiplies the whole
1923 // existing correction, matching the w_a on the operator row of that axis. 1.0 isotropic.
1924 if (varRho_)
1925 projectCorrectVar(uf_, vf_, wf_, CCConst(phi_), CCConst(rhoField_), rho_, e_, G, u_.w[0],
1926 u_.w[1], u_.w[2]);
1927 else
1928 projectCorrect(uf_, vf_, wf_, CCConst(phi_), e_, G, u_.w[0], u_.w[1], u_.w[2]);
1929 if (fluidOnlyMode_ == 2) // Design B: replace the solid side's phi=0 by phibar_s at
1930 starCorrectFaces(uf_, vf_, wf_, CCConst(phi_), starOv_, nStar_, // fluid|solid faces
1931 C3{nx_, ny_, nz_}, e_, G, e_, G, exactResidual_, u_.w[0], u_.w[1], u_.w[2]);
1932 // Complete the face field's ghosts, KEEPING each high-side boundary face: a plain fillGhosts
1933 // wraps the inlet plane onto the outlet, so bcCorrectOutflow below would correct the wrong
1934 // value (doc/uf_outlet_fix.md). Momentum never saw it (openFaceView), the scalars and the
1935 // backflow census did.
1936 fillFaceGhostsKeepBoundary(uf_, 0);
1937 fillFaceGhostsKeepBoundary(vf_, 1);
1938 fillFaceGhostsKeepBoundary(wf_, 2);
1939}
1940
1941template <class Grid>
1942void Solver<Grid>::projectCorrectFaceFieldOutflow() {
1943 if (hasOutflow_) { // correct the high-side outflow face on the face field so mass leaves
1944 // (phi=0 there)
1945 B3 e{e_.x, e_.y, e_.z};
1946 CCField fa[3] = {uf_, vf_, wf_};
1947 // WO-R2 item 1: same rule as the staggered path below — with the operator's outflow row
1948 // carrying rho0/rho_f (setOutflowCoefficient) the consistent correction carries it too.
1949 const bool var = varRho_ && !porous_ && outflowRhoCorr_;
1950 for (int a = 0; a < 3; ++a)
1951 if (bc_[2 * a + 1] == 3 && touchesGlobalFace(2 * a + 1)) {
1952 if (var)
1953 bcCorrectOutflowVar(fa[a], phi_, rhoField_, rho_, e, G, a, rhoFaceHarmonic_, u_.w[a]);
1954 else
1955 bcCorrectOutflow(fa[a], phi_, e, G, a, u_.w[a]);
1956 }
1957 }
1958}
1959
1960template <class Grid>
1961void Solver<Grid>::projectCorrectCellField() {
1962 if (colocatedFaceForce()) {
1963 // Rung V8 (S8.5): the cell correction is the predictor's face-to-cell reconstruction applied
1964 // to the face corrections k(j) = w (rho0/rho_f)(phi(j) - phi(j-s)) — the transpose of the
1965 // constraint, so the pair stays adjoint (collocated_varrho.hpp). Replaces the whole
1966 // constant-density cell-correction chain below.
1967 CCField oax[3] = {ox_, oy_, oz_};
1968 for (int cc = 0; cc < 3; ++cc)
1969 correctCellFaceAverageVar(C[cc].u, CCConst(phi_), CCConst(varRho_ ? rhoField_ : C[cc].rscale),
1970 CCConst(oax[cc]), varRho_, rho_, strideOf(cc), e_, G, u_.w[cc]);
1971 } else if (ghostProjection_ || faceInterp_ == 9) {
1972 // Ghost cell correction (also the gauge-exact scheme): the directional gpCenterGrad
1973 // gradient of phi — 2nd-order one-sided at cut cells, never reads a decoupled
1974 // (solid/pocket) phi. The same operator supplies the momentum's -grad(P^n) predictor
1975 // (buildRhs), so the pressure force the momentum feels and the correction stay one
1976 // operator family.
1977 for (int cc = 0; cc < 3; ++cc) {
1978 gpCenterGrad(tgp_, CCConst(phi_), CCConst(ghostProjection_ ? sdfGp_ : sdf_), cc, e_, G,
1979 u_.w[cc]);
1980 subtractField(C[cc].u, CCConst(tgp_), e_, G);
1981 }
1982 } else if (faceInterp_ == 5) { // embed 5: cell correction = the TRANSPOSE of the
1983 // wall-aware map, keeping (T, Tᵀ) an adjoint pair (transposeGradWallAware)
1984 CCField xcs[3] = {xcx_, xcy_, xcz_};
1985 CCField oax[3] = {ox_, oy_, oz_};
1986 for (int cc = 0; cc < 3; ++cc) {
1987 transposeGradWallAware(tgp_, CCConst(phi_), CCConst(sdf_), CCConst(oax[cc]), CCConst(xcs[cc]),
1988 true, cc, e_, G, u_.w[cc]);
1989 subtractField(C[cc].u, CCConst(tgp_), e_, G);
1990 }
1991 } else if (faceInterp_ == 6 || faceInterp_ == 7) { // embed: openness-WEIGHTED cell correction
1992 // (full open-face pressure force at cut cells) — Basilisk centered_grad
1993 projectCorrectCenterOpen(C[0].u, C[1].u, C[2].u, CCConst(phi_), CCConst(ox_), CCConst(oy_),
1994 CCConst(oz_), e_, G, u_.w[0], u_.w[1], u_.w[2]);
1995 } else {
1996 projectCorrectCenter(C[0].u, C[1].u, C[2].u, CCConst(phi_), CCConst(ox_), CCConst(oy_),
1997 CCConst(oz_), e_, G, u_.w[0], u_.w[1], u_.w[2]);
1998 }
1999}
2000
2001template <class Grid>
2002void Solver<Grid>::projectCorrectStaggered() {
2003 if (porous_ && porousCons_) // eps-conservative gradient rho*idt/(eps_f rho idt + beta_f),
2004 // matching buildPorousCoeffCons (see mac_pressure.hpp)
2005 projectCorrectPorousCons(C[0].u, C[1].u, C[2].u, CCConst(phi_), CCConst(epsField_),
2006 CCConst(dragBeta_), hasDrag_, rho_ / dt_, e_, G, u_.w[0], u_.w[1],
2007 u_.w[2]);
2008 else if (porous_ &&
2009 hasDrag_) // drag-relaxed gradient w_f=idt/(idt+beta_f), matching buildPorousCoeffDrag
2010 projectCorrectPorousDrag(C[0].u, C[1].u, C[2].u, CCConst(phi_), CCConst(dragBeta_), rho_ / dt_,
2011 e_, G, u_.w[0], u_.w[1], u_.w[2]);
2012 else if (varRho_ && rhoFaceHarmonic_) // the WO-J harmonic knob: coefficient AND correction
2013 projectCorrectVarHarm(C[0].u, C[1].u, C[2].u, CCConst(phi_), CCConst(rhoField_), rho_, e_, G,
2014 u_.w[0], u_.w[1], u_.w[2]);
2015 else if (varRho_) // per-face 1/rho on the gradient, matching the operator coefficient
2016 projectCorrectVar(C[0].u, C[1].u, C[2].u, CCConst(phi_), CCConst(rhoField_), rho_, e_, G,
2017 u_.w[0], u_.w[1], u_.w[2]);
2018 else
2019 projectCorrect(C[0].u, C[1].u, C[2].u, CCConst(phi_), e_, G, u_.w[0], u_.w[1], u_.w[2]);
2020}
2021
2022template <class Grid>
2023void Solver<Grid>::projectCorrectStaggeredOutflow() {
2024 if (hasOutflow_) { // correct the high-side outflow normal face that projectCorrect misses
2025 // (mass leaves)
2026 B3 e{e_.x, e_.y, e_.z};
2027 // WO-R item 4: with variable density every OTHER corrected face carries the mobility
2028 // factor rho0/rho_f (projectCorrectVar) and this one did not — a ratio-sized error on the
2029 // outflow face, invisible at constant density (rho_f == rho0) which is why the channel/BFS
2030 // validations never saw it. The porous branches keep the plain correction: their
2031 // coefficient is the drag/eps relaxation, not 1/rho, and a two-phase porous outlet is not
2032 // this rung. `!varRho_` is byte-identical.
2033 // `set_outflow_rho_correction(False)` drops the 1/rho_f
2034 // factor. DEFAULT ON since WO-R2 fixed the operator's outflow-face coefficient — see
2035 // setOutflowRhoCorrection for the before/after table and the mechanism.
2036 const bool var = varRho_ && !porous_ && outflowRhoCorr_;
2037 for (int a = 0; a < 3; ++a)
2038 if (bc_[2 * a + 1] == 3 && touchesGlobalFace(2 * a + 1)) {
2039 if (var)
2040 bcCorrectOutflowVar(C[a].u, phi_, rhoField_, rho_, e, G, a, rhoFaceHarmonic_, u_.w[a]);
2041 else
2042 bcCorrectOutflow(C[a].u, phi_, e, G, a, u_.w[a]);
2043 }
2044 outflowCorrValid_ = true; // the outflow face now carries the mass that leaves
2045 }
2046}
2047
2048template <class Grid>
2050 // Rotational incremental pressure (Timmermans), matching CUDA press_update_k: P += (rho/dt)*phi
2051 // - mu*div(u*). Classical non-incremental Chorin (!incremental_) skips the accumulation;
2052 // getPressure() derives p from phi.
2053 if (incremental_) {
2054 if (rotFilter_ && rotationalP_)
2055 for (int a = 0; a < 3; ++a)
2056 filterCellField(div_, a); // S(div u*): see setRotationalFilter
2057 CCExec space;
2058 CCField P = P_, ph = phi_, d = div_;
2059 // Pressure under-relaxation (MFIX §10.1): accumulate only omega_p of the increment into the
2060 // physical pressure P (the velocity correction still uses the full phi to satisfy
2061 // continuity), so the next step's incremental predictor -grad(P^n) can't overshoot for a
2062 // stiff drag diagonal. omega_p=1 (default) is the current behaviour; <1 only stabilizes the
2063 // porous+drag path.
2064 const double ct = pressUnderRelax_ * rho_ / dt_, mu = rotationalP_ ? rotWeight_ * mu_ : 0.0;
2065 if (varProps_) {
2066 // Variable viscosity: the pointwise Timmermans term -mu(i)*div(u*) is inconsistent for
2067 // heterogeneous mu (see setVariableRotational). Default = constant coefficient chi*mu_min
2068 // (stable by domination, exact fallback to the uniform-mu scheme); "full" = pointwise
2069 // (mild contrast only); "off" = plain incremental.
2070 if (varRotMode_ == 1) {
2071 CCConst mf = CCConst(muField_);
2072 const double chi = varRotChi_;
2073 Kokkos::parallel_for(
2074 "press_var_full", Kokkos::RangePolicy<CCExec>(space, 0, n_),
2075 KOKKOS_LAMBDA(std::size_t i) { P(i) += ct * ph(i) - chi * mf(i) * d(i); });
2076 } else {
2077 const double muRot = (varRotMode_ == 2) ? 0.0 : varRotChi_ * minMuInner();
2078 Kokkos::parallel_for(
2079 "press_var_min", Kokkos::RangePolicy<CCExec>(space, 0, n_),
2080 KOKKOS_LAMBDA(std::size_t i) { P(i) += ct * ph(i) - muRot * d(i); });
2081 }
2082 } else if (rotWallW_ > 0.0 && rotationalP_) {
2083 // Frank's wall-banded blend (setRotationalWallWeight): at fluid cells with a solid
2084 // axis-neighbour (the rows whose one-sided gpCenterGrad makes the cell-centered
2085 // rotational update marginally unstable) use
2086 // P += (rho/dt + w*mu/dx^2)*phi - (1-w)*mu*div(u*)
2087 // (dx = 1 in cell units): the (1-w) shrinks the destabilizing off-diagonal there and the
2088 // diagonal w*mu gain keeps those rows relaxing at dt -> infinity where rho/dt vanishes.
2089 // Bulk cells (w = 0) keep the full-speed rotational update. Outer-shell cells keep the
2090 // bulk formula (their P is ghost/overwritten).
2091 CCConst sd = CCConst(sdf_);
2092 const double w0 = rotWallW_, muF = rotWeight_ * mu_;
2093 C3 e = e_;
2094 Kokkos::parallel_for(
2095 "press_wallblend", Kokkos::RangePolicy<CCExec>(space, 0, n_),
2096 KOKKOS_LAMBDA(std::size_t i) {
2097 const long sy = e.x, sz = (long)e.x * e.y;
2098 const int x = (int)(i % e.x), y = (int)((i / e.x) % e.y), z = (int)(i / sz);
2099 double w = 0.0;
2100 if (x > 0 && y > 0 && z > 0 && x < e.x - 1 && y < e.y - 1 && z < e.z - 1 &&
2101 sd(i) >= 0.0 &&
2102 (sd(i - 1) < 0.0 || sd(i + 1) < 0.0 || sd(i - sy) < 0.0 || sd(i + sy) < 0.0 ||
2103 sd(i - sz) < 0.0 || sd(i + sz) < 0.0))
2104 w = w0;
2105 P(i) += (ct + w * muF) * ph(i) - (1.0 - w) * muF * d(i);
2106 });
2107 } else {
2108 Kokkos::parallel_for(
2109 "press", Kokkos::RangePolicy<CCExec>(space, 0, n_),
2110 KOKKOS_LAMBDA(std::size_t i) { P(i) += ct * ph(i) - mu * d(i); });
2111 }
2112 }
2113 // Snapshot eps^{n+1} -> epsPrev_ for the next step's d(eps)/dt (this projection consumed it).
2114 if (porous_)
2115 Kokkos::deep_copy(epsPrev_, epsField_);
2116}
2117
2118} // namespace peclet::flow
2119
2120#endif // PECLET_FLOW_FLOW_IBM_PROJECT_HPP
static constexpr double kChebBracket
void setStopReference(double ref)
void noteChebyshevGrowthTrip(long iters)
void fillVelGhosts(int comp, int fold)
void addCsfRhs(int c, CCField dst, bool rowScaled, bool faceRange=false)
bool advectsMomentum() const
void checkCgExit(CCField rhs1, CCField x1, long iters, const char *which, const StarOverlay *star)
bool balancedForceProjection() const
void buildOpenFaceField()
Build ufOpen_ = the face field with each open (outflow) domain face overwritten by its zero-gradient ...
long solveBalancedForceSystem(double bref, double r0)
void fillGhosts(CCField f)
void fillPropGhosts(CCField f, bool edges=false)
void requireCollocatedFaceForceScope(const char *who)
void pcApplyDivergenceSource(CCField div)
Subtract the phase-change (and any prescribed) divergence source from div_ so the deflated pressure s...
bool prefactorHoistEligible() const
CCField addField(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 copyInner(CCField dst, C3 de, int dg, CCConst src, C3 se, int sg)
bool ufAdvVelocity() const
Are the advection operators reading the projected face field this step?
bool lastBalancedForceFailed() const
CCConst openFaceView(int c) const
Component c of the face field AS THE ADVECTION AND THE DIVERGENCE DIAGNOSTIC MUST READ IT: advFaceVie...
void addWallFluxDivergence(CCField d)
long lastBalancedForceIterations() const
void constraintDivergence(CCConst fx, CCConst fy, CCConst fz, CCField out)
long balancedForceFailures() const
static constexpr int G
Definition flow_ibm.hpp:82
long strideOf(int c) const
void collocatedV8AutoFallback(const char *why)
long solvePressureSystem(CCField rhs1, CCField x1)
const char * projectedGuessIneligible() const
void superficialVelocityPrecheck() const
void requireBalancedForceScope(const char *who, bool atStep) const
void filterCellField(CCField f, int axis)
bool ensureAdvStash(int c, bool adv)
void addCsfRhsCellInterp(int c, CCField dst, bool rowScaled, bool faceRange=false)
void setBalancedForceProjection(bool enabled)
void copyBlockShifted(CCField dst, C3 de, CCConst src, C3 se, int off)
void buildRhs(CCField b, CCConst cOld, CCConst kappa, CCConst unk, double idt, double srcConst, CCConst src, bool useField, double srcFactor, C3 e, int g)
Base right-hand side: b = kappa (idt c^n + S'), identity rows 0.
double weightSum(double oLo, double oHi)
double cellFromFaces(double aLo, double aHi, double oLo, double oHi)
void stencilMatvec(CCField y, CCConst u, MC AC, MC AW, MC AE, MC AS, MC AN, MC AB, MC AT, C3 e, int g)
Kokkos::DefaultExecutionSpace CCExec
void bcCorrectOutflow(BField f, BField phi, B3 ext, int g, int a, double wa=1.0)
Definition mac_bc.hpp:345
void buildRhoCoeffOutflowFace(CCField ca, CCConst oa, CCConst rho, double rho0, C3 e, int g, int a, bool harmonic)
void gpDivergDelta(CCField d, CCConst u, CCConst v, CCConst w, const GpOverlayReal< Real > &ov, int nOv, C3 nn, C3 extb, int gb, bool useGhost=false)
Overlay divergence correction: d(r) = rho_r * (d(r) + closure/BC/explicit face values),...
void buildPorousCoeffDrag(CCField cx, CCField cy, CCField cz, CCConst ox, CCConst oy, CCConst oz, CCConst eps, CCConst beta, double idt, C3 e, int g)
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 centerGradOpen(CCField out, CCConst p, CCConst o, int axis, C3 e, int g, double wa=1.0)
void projectCorrectPorousDrag(CCField u, CCField v, CCField w, CCConst phi, CCConst beta, double idt, C3 e, int g, double wx=1.0, double wy=1.0, double wz=1.0)
void buildRhoCoeff(CCField cx, CCField cy, CCField cz, CCConst ox, CCConst oy, CCConst oz, CCConst rho, double rho0, C3 e, int g)
void buildPorousCoeffCons(CCField cx, CCField cy, CCField cz, CCConst ox, CCConst oy, CCConst oz, CCConst eps, CCConst beta, bool useBeta, double rhoidt, C3 e, int g)
void bcZeroPressureGhost(BField phi, B3 ext, int g, int a, int s)
Definition mac_bc.hpp:321
void subtractField(CCField u, CCConst d, C3 e, int g)
Kokkos::View< const double *, CCMem > CCConst
void transposeGradWallAware(CCField out, CCConst p, CCConst sdf, CCConst o, CCConst xc, bool useCen, int axis, C3 e, int g, double wa=1.0)
void divergOpen(CCConst u, CCConst v, CCConst w, CCConst ox, CCConst oy, CCConst oz, CCField d, C3 e, int g)
void projectCorrect(CCField u, CCField v, CCField w, CCConst phi, C3 e, int g, double wx=1.0, double wy=1.0, double wz=1.0)
void projectCorrectCenterOpen(CCField u, CCField v, CCField w, CCConst phi, CCConst ox, CCConst oy, CCConst oz, C3 e, int g, double wx=1.0, double wy=1.0, double wz=1.0)
void correctCellFaceAverageVar(CCField u, CCConst phi, CCConst rho, CCConst o, bool haveRho, double rho0, long s, C3 e, int g, double wa=1.0)
Kokkos::View< const MReal *, CCMem > FPC
void projectCorrectPorousCons(CCField u, CCField v, CCField w, CCConst phi, CCConst eps, CCConst beta, bool useBeta, double rhoidt, C3 e, int g, double wx=1.0, double wy=1.0, double wz=1.0)
void buildFaceAccelVar(CCField af, CCConst P, CCConst rho, CCConst fb, bool haveFb, bool haveRho, double rhoC, double fc, bool incr, double scale, long s, C3 e, int g, double wa=1.0)
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)
void starCorrectFaces(CCField uf, CCField vf, CCField wf, CCConst phi, const StarOverlay &ov, int nOv, C3 nn, C3 ext, int g, C3 extP, int gP, bool exact, double wx=1.0, double wy=1.0, double wz=1.0)
Fix the face correction at fluid|solid faces: projectCorrect applied -(phi_hi - phi_lo) with the soli...
void projectCorrectVar(CCField u, CCField v, CCField w, CCConst phi, CCConst rho, double rho0, C3 e, int g, double wx=1.0, double wy=1.0, double wz=1.0)
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)
void embedViscousApply(CCField Lu, CCConst U, CCConst sdf, CCConst cs, CCConst ox, CCConst oy, CCConst oz, double mu, double idt, C3 e, int g, double wx=1.0, double wy=1.0, double wz=1.0, double hpx=1.0, double hpy=1.0, double hpz=1.0)
double maxAbsDiffInner(CCConst a, CCConst b, C3 e, int g)
void buildPorousCoeff(CCField cx, CCField cy, CCField cz, CCConst ox, CCConst oy, CCConst oz, CCConst eps, C3 e, int g)
void buildRhoCoeffHarm(CCField cx, CCField cy, CCField cz, CCConst ox, CCConst oy, CCConst oz, CCConst rho, double rho0, C3 e, int g)
void projectCorrectCenter(CCField u, CCField v, CCField w, CCConst phi, CCConst ox, CCConst oy, CCConst oz, C3 e, int g, double wx=1.0, double wy=1.0, double wz=1.0)
void centerToFaceMassWeighted(CCField uf, CCField vf, CCField wf, CCConst U, CCConst V, CCConst W, CCConst rho, C3 e, int g)
void divergOpenEps(CCConst u, CCConst v, CCConst w, CCConst ox, CCConst oy, CCConst oz, CCConst eps, CCField d, C3 e, int g)
void projectCorrectVarHarm(CCField u, CCField v, CCField w, CCConst phi, CCConst rho, double rho0, C3 e, int g, double wx=1.0, double wy=1.0, double wz=1.0)
void addFaceAccelCsf(CCField af, CCConst cv, CCConst kp, CCConst kb, CCConst rho, bool haveRho, double rhoC, double sigma, double hGrad, double scale, long s, C3 e, int g)
void gpCenterGrad(CCField out, CCConst p, CCConst sdf, int axis, C3 e, int g, double wa=1.0)
Directional cell-center gradient (collocated ghost path) of a cell field p whose solid-centered rows ...
void bcCorrectOutflowVar(BField f, BField phi, BField rho, double rho0, B3 ext, int g, int a, bool harmonic, double wa=1.0)
Definition mac_bc.hpp:375
void bcNeumannGhost(BField f, B3 ext, int g, int a, int s)
Definition mac_bc.hpp:265
One entry per eliminated solid-centered cell: packed INNER flat index + the apertures of its (up to 6...
static constexpr int G
static constexpr double AC
static constexpr double U