flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
flow_ibm.hpp
Go to the documentation of this file.
1
18#ifndef PECLET_FLOW_SDFLOW_IBM_HPP
19#define PECLET_FLOW_SDFLOW_IBM_HPP
20
21#include <algorithm>
22#include <array>
23#include <chrono>
24#include <cmath>
25#include <cstdlib>
26#include <cstring>
27#include <Kokkos_Core.hpp>
28#include <limits>
29#include <memory>
30#include <string>
31#include <vector>
32
33#include "peclet/core/geom/device_scene.hpp"
34
35#include "collocated_varrho.hpp" // rung V8: the collocated variable-density (mass-adjoint) kernels
36#include "face_props.hpp"
37#include "full_stress.hpp"
39#include "ghost_projection_debug.hpp" // opt-in gp row forensics (PECLET_FLOW_GP_DEBUG), no-op off
40#include "grid_layout.hpp"
42#include "mac_cheb_momentum.hpp"
43#include "mac_cutcell_mg.hpp"
44#include "mac_ibm.hpp"
45#include "mac_pressure.hpp"
46#include "mac_stencils.hpp"
47#include "mac_velocity_mg.hpp"
48#include "peclet/core/field/field_set.hpp"
49#include "peclet/core/solver/anderson.hpp" // AndersonRole of the march state (MarchState)
50#include "property_closures.hpp"
51#include "scalar_cutcell_geometry.hpp" // cut-cell scalars: the geometry record (WO-2)
52#include "scalar_cutcell_operator.hpp" // cut-cell scalars: operator + per-scalar state (WO-3)
53#include "scalar_krylov.hpp" // cut-cell scalars: BiCGStab (WO-3)
54#include "scalar_mg.hpp" // cut-cell scalars: ScalarMG preconditioner (WO-4)
55#include "scalar_transport.hpp"
57#include "vof/advect_wy.hpp" // VoF rung V1: the Weymouth-Yue colour advector (its own g=3 block)
58#include "vof/block_container.hpp" // VoF Part III rung W0: the per-bubble block container
59#include "vof/block_exchange.hpp" // VoF Part III rung W0: the block gather / scatter
60#include "vof/colour_field.hpp" // VoF rung V2a: the G=2 <-> g=3 bridge + the colour ghost policy
61#include "vof/colour_bc.hpp" // VoF rung V-BC: inflow/outflow/backflow colour + the outside mask
62#include "vof/curvature_field.hpp" // VoF rung V3: the HF curvature cascade + PV fallback
63#include "vof/sharp_viscous.hpp" // the sharp viscous stress at the interface (doc/vof_sharp_viscous_stress.md)
64#include "vof/momentum_advect.hpp" // VoF rung V2b: momentum-consistent rho^c u_c transport
65#include "vof/surface_tension.hpp" // VoF rung V4: balanced-force CSF + the capillary dt
66#include "vof/phase_change.hpp" // VoF Part II rungs P0/P1: mass flux, plane-shift regression
67#include "vof/wetting_dynamic.hpp" // VoF rung V6: dynamic contact angle + hysteresis
68#include "vof/energy_advect.hpp" // VoF Part II rung P2/P3: consistent rho c_p T transport
69#include "vof/interface_area_field.hpp" // VoF Part II rung P3c: the cascade-consistent A_Gamma
70#include "vof/marching_cubes_field.hpp" // VoF Part II rung P3d: the JOINED (marching-tet) A_Gamma
71
72namespace peclet::flow {
73
74// Templated on a GridLayout policy (grid_layout.hpp) that supplies the grid-position-dependent
75// pieces (currently: the per-component velocity sample offset). IbmSolver == Solver<Staggered> (the
76// alias below) is bit-identical to the pre-policy solver; the Colocated policy is added in a later
77// phase.
78template <class Grid>
79class Solver {
80 public:
81 using FV = Kokkos::View<MReal*, CCMem>; // velocity operator storage tracks MReal
82 static constexpr int G = 2; // velocity block: Koren advection reach (pressure/MG bridged to g=1)
83
84 Solver(int nx, int ny, int nz);
85
86
87
88 // ==========================================================================================
89 // PHYSICAL UNITS — the solver takes the world in the caller's own units
90 // (suite/docs/PHYSICAL_UNITS_PLAN.md; Phase 1 = isotropic cells)
91 //
92 // DERIVATION. The discrete algorithms in this file are index-native: red-black sweeps,
93 // cut-cell apertures, multigrid transfers, the halo, PLIC. Rather than divide every finite
94 // difference by a cell size, the solver keeps computing on the UNIT LATTICE and folds the
95 // metric into constants at the API boundary (plan §3.2, option B). Write
96 //
97 // x_a = origin_a + h_a * xi_a (physical position of the index coordinate xi)
98 // t = tRef * t' (tRef = the first dt the caller sets)
99 // u_a = (h_a / tRef) * v_a (v = index velocity: cells per tRef)
100 // rho = rhoRef * rho'
101 //
102 // and substitute into rho (du/dt + u.grad u) = -grad p + mu lap u + F. Every term then
103 // carries the same factor rhoRef*hRef/tRef^2 when the cells are isotropic (h_a == hRef,
104 // Phase 1), and dividing it out leaves EXACTLY the equation this file already solves,
105 //
106 // rho' (dv/dt' + v.grad_xi v) = -grad_xi p' + mu' lap_xi v + F'
107 //
108 // with the boundary conversions
109 //
110 // rho' = rho / rhoRef dt' = dt / tRef
111 // mu' = mu * tRef / (rhoRef*hRef^2) (the cell diffusion number)
112 // p' = p * tRef^2 / (rhoRef*hRef^2) F' = F * tRef^2 / (rhoRef*h_a)
113 // v_a = u_a * tRef / h_a (the Courant number)
114 // sigma' = sigma * tRef^2 / (rhoRef*hRef^3) so p' = sigma'*kappa' with kappa' = kappa*hRef
115 // kappa' = kappa * hRef div' = div * tRef
116 // d' = d / hRef (any length: SDF value, slip length)
117 // xi_a = (x_a - origin_a) / h_a (any position)
118 //
119 // Advection is untouched in index space, so the Koren/TVD and implicit-FOU paths do not change;
120 // cut-cell apertures and wall crossings are ratios along an axis and are unit-free.
121 //
122 // WHY THE REFERENCE SCALES (plan decision D3). They exist so the STORED float operator
123 // coefficients stay O(1) whatever unit system the caller uses: mu' is a diffusion number and
124 // rho'/dt' is 1 at the first dt, where dividing mu by a physical h^2 would put 1e7 next to 1e8
125 // in float storage (docs/SCALING_ISSUES.md #1). hRef is fixed at construction, rhoRef at the
126 // first set_rho and tRef at the first set_dt, and never move again — no stored state is ever
127 // rescaled mid-run. Because the order of those calls must not matter, the PHYSICAL inputs are
128 // kept verbatim (rhoPhys_ / muPhys_ / ...) and `refreshUnitDerived()` re-derives the internal
129 // ones whenever a scale is first pinned.
130 //
131 // IDENTITY. With no extent at all (`extent=None`, the historical cell-unit API) the solver is
132 // never armed: hRef = rhoRef = tRef = 1 and every factor below evaluates to exactly 1.0,
133 // whatever rho and dt are. Multiplying a double by 1.0 is the identity in IEEE-754, so every
134 // pre-existing script, test and gallery page is bit-identical (plan §5 gate 1). With
135 // extent == cells, dt = 1 and rho = 1 the armed path reproduces the same 1.0 factors — that is
136 // the `units_identity` gate.
137 // ==========================================================================================
138 struct UnitScales {
139 bool physical = false;
140 double h[3] = {1.0, 1.0, 1.0};
141 double org[3] = {0.0, 0.0, 0.0};
142 double ext[3] = {0.0, 0.0, 0.0};
143 long cells[3] = {0, 0, 0};
144 double hRef = 1.0;
145 double rhoRef = 1.0;
146 double tRef = 1.0;
147 bool rhoRefSet = false, tRefSet = false;
148
149 // Every factor below is exactly 1.0 while `physical` is false.
150 double lenToInt() const { return 1.0 / hRef; }
151 double lenToPhys() const { return hRef; }
152 double velToInt(int a) const { return tRef / h[a]; }
153 double velToPhys(int a) const { return h[a] / tRef; }
154 double timeToInt() const { return 1.0 / tRef; }
155 double rhoToInt() const { return 1.0 / rhoRef; }
156 double muToInt() const { return tRef / (rhoRef * hRef * hRef); }
157 double pToInt() const { return tRef * tRef / (rhoRef * hRef * hRef); }
158 double pToPhys() const { return rhoRef * hRef * hRef / (tRef * tRef); }
159 double forceToInt(int a) const { return tRef * tRef / (rhoRef * h[a]); }
160 double sigmaToInt() const { return tRef * tRef / (rhoRef * hRef * hRef * hRef); }
161 double curvToPhys() const { return 1.0 / hRef; }
162 double divToPhys() const { return 1.0 / tRef; }
163 double timeToPhys() const { return tRef; }
164 double angVelToInt() const { return tRef; } // omega' = omega*tRef (v = omega x r on both sides)
165 // A TOTAL force F = int f dV: f' = f*tRef^2/(rhoRef*hRef) and dV' = dV/hRef^3, so
166 // F' = F*tRef^2/(rhoRef*hRef^4); a torque carries one more length.
167 double forceTotalToPhys() const {
168 const double h2 = hRef * hRef;
169 return rhoRef * h2 * h2 / (tRef * tRef);
170 }
171 double torqueToPhys() const { return forceTotalToPhys() * hRef; }
172
173 // ---- Phase 2 (anisotropic cells): the per-axis metric of the discrete operators ----------
174 // doc/anisotropic_metric.md §1.1. h_a' = h_a/hRef >= 1 (exactly 1.0 on the finest axis),
175 // w_a = 1/h_a'^2 <= 1 the pressure-gradient / Laplacian weight of axis a, V' = h_x'h_y'h_z'
176 // the cell volume in hRef^3, and `aniso` true iff some h_a' != 1. Every operator fold below
177 // is "today's expression times one of these", so on the isotropic path — where they are all
178 // EXACTLY 1.0 — the arithmetic is bit-identical (multiplying an IEEE-754 double by 1.0 is the
179 // identity). APPEND new members here; never reorder the struct.
180 double hp[3] = {1.0, 1.0, 1.0};
181 double w[3] = {1.0, 1.0, 1.0};
182 double vol = 1.0;
183 bool aniso = false;
184
185 // ---- Phase 3 (the VoF half; flow/doc/anisotropic_vof.md §9) appends TWO more, and reuses
186 // the four above verbatim — the two sessions derived the same metric and the rebase kept one
187 // copy. `hpMax` is the Wendland support scale of the curvature/area fits; `vofMetric()` is
188 // the per-axis cell size the container-free VoF kernels take (`core/vof/plic.hpp`), which is
189 // `{1,1,1}` — hence the pre-Phase-3 arithmetic exactly — whenever the cells are cubes.
190 double hpMax = 1.0;
191 vof::VofMetric vofMetric() const { return vof::VofMetric{{hp[0], hp[1], hp[2]}}; }
192
193 // ---- Scalar transport and the phase-change energy path (2026-10-02) -----------------------
194 // The internal system is the one above: length hRef, time tRef, mass rhoRef*hRef^3. A
195 // transported scalar (temperature, concentration) is NOT scaled — it enters every equation
196 // linearly or through an absolute value (T_sat, a Boussinesq T0, an Arrhenius 1/T) — so each
197 // factor below is the M-L-T dimension of its quantity alone, with temperature as its own unit.
198 // Every one is a product of 1.0s, i.e. EXACTLY 1.0, while `physical` is false.
199 // diffusivity D L^2/T D' = D * tRef/hRef^2 (the cell Fourier number)
200 // mass flux mdot M/(L^2 T) mdot' = mdot * tRef/(rhoRef*hRef)
201 // latent heat h_lv L^2/T^2 h' = h_lv * tRef^2/hRef^2
202 // conductivity k M L/(T^3 K) k' = k * tRef^3/(rhoRef*hRef^4)
203 // heat capacity rho c_p M/(L T^2 K) rcp' = rcp * tRef^2/(rhoRef*hRef^2)
204 // IHTR resistance R_int K L^2 T/M R' = R_int * rhoRef*hRef/tRef (T = mdot R)
205 // divergence source S 1/T S' = S * tRef
206 // so k'/rcp' = D', mdot' = k' grad'T / h' and mdot' R' = mdot R_int (a temperature): every
207 // phase-change formula holds unchanged on the internal values. Out, per CELL SUM (the
208 // diagnostics sum per cell without the cell volume, which the caller multiplies by `vol`):
209 double diffToInt() const { return tRef / (hRef * hRef); }
210 double mdotToInt() const { return tRef / (rhoRef * hRef); }
211 double mdotToPhys() const { return rhoRef * hRef / tRef; }
212 double latentToInt() const { return (tRef * tRef) / (hRef * hRef); }
213 double condToInt() const {
214 const double h2 = hRef * hRef;
215 return tRef * tRef * tRef / (rhoRef * h2 * h2);
216 }
217 double rcpToInt() const { return tRef * tRef / (rhoRef * hRef * hRef); }
218 double rintToInt() const { return rhoRef * hRef / tRef; }
219 double divToInt() const { return tRef; }
220 double areaToPhys() const { return hRef * hRef; }
221 double volToPhys() const { return hRef * hRef * hRef; }
224 double energyToPhys() const { return rhoRef * volToPhys() * hRef * hRef / (tRef * tRef); }
225 double powerToPhys() const { return energyToPhys() / tRef; }
226
227 // ---- Cut-cell scalars (doc/scalar_ibm_design.md §1.2, WO-3) -------------------------------
228 // A speed L/T — the Robin transfer coefficient k and the Neumann wall flux q (c L/T) — on the
229 // internal lattice: k' = k tRef/hRef. ISOTROPIC by construction (the wall closure divides by a
230 // probe distance in hRef units), unlike the per-axis velToInt(a). Exactly 1.0 unarmed.
231 double speedToInt() const { return tRef / hRef; }
232 // A contact resistance R_c, T/L (doc/scalar_ibm_design.md §1.2, WO-7): the conjugate
233 // interface's q = (psi_s - psi_f)/R_c sits in series with s/Lam (T/L), so R_c' = R_c
234 // hRef/tRef = 1/speedToInt(). Exactly 1.0 unarmed.
235 double resistToInt() const { return hRef / tRef; }
236 };
237
243 struct SceneMap {
244 double a[3] = {0.0, 0.0, 0.0};
245 double b[3] = {1.0, 1.0, 1.0};
246 double dToInt = 1.0;
247 double velToInt[3] = {1.0, 1.0, 1.0};
248 double angToInt = 1.0;
249 };
250 SceneMap sceneMap() const;
251
252
253
258 Solver(int nx, int ny, int nz, const std::array<double, 3>& extent,
259 const std::array<double, 3>& origin, const std::array<long, 3>& globalCells);
260
261
262
265 void setPhysicalDomain(const std::array<double, 3>& extent, const std::array<double, 3>& origin,
266 const std::array<long, 3>& globalCells);
267
268
269
283 void requireIsotropic(const char* what) const;
284
285
286
287 bool hasPhysicalDomain() const;
288
289
290 const UnitScales& unitScales() const;
291
292
295 std::array<double, 3> spacing() const;
296
297
299 std::array<double, 3> domainOrigin() const;
300
301
303 std::array<double, 3> domainExtent() const;
304
305
307 std::array<long, 3> globalCells() const;
308
309
312 std::vector<double> cellCentres(int axis) const;
313
314
315
320
321
322
330
331
332
333 // (Re)allocate every per-block buffer for a local inner block of nx*ny*nz. Called by the
334 // constructor and by redistribute() after a re-decomposition changes this rank's block size.
335 void allocateBlock(int nx, int ny, int nz);
336
337
338
341 void setRho(double r);
342
343
346 void setMu(double m);
347
348
349 void setDt(double d);
350
351
353 void setBodyForce(double fx, double fy, double fz);
354
365 void setSuperficialVelocity(bool on, int axis, double velocity);
369
370
372
373
374 // Momentum tolerance stop: end the RB-GS loop once the swept colour's max increment has dropped
375 // to rtol of the first sweep's (GS contracts geometrically, so the increment tracks the error).
376 // rtol = 0 (default) keeps the legacy fixed-count loop byte-identical. Easy regimes (small
377 // nu*dt/dx^2) exit after ~3-5 sweeps; stiff regimes run to the velIters_ cap unchanged. The
378 // check is fused into the sweep kernel (no extra memory pass) and the stop decision is
379 // rank-uniform (MPI max) so distributed halo exchanges stay in lockstep.
380 void setVelocityTolerance(double rtol, int minIters);
381
382
383 long lastMomentumSweeps() const;
384
385
386 // Residual-based momentum stop (opt-in, 0 = off): a component's implicit solve ends once
387 // max|b - A u| <= rtol * max|b| over the fluid unknowns (global under MPI). Unlike the update
388 // criterion (relative to the FIRST sweep's update, which on a warm-started near-steady step is
389 // already at noise level and then costs hundreds of sweeps to shrink by 1e-3) this measures the
390 // equation's own convergence, and a converged warm start stops at sweep 1. Available on the
391 // stencil paths (IBM / cut-cell domain-BC RB-GS, every velocity-MG mode); the const-coefficient
392 // domain-BC smoother keeps the update criterion.
393 // rtol > 0: fixed; rtol == 0: the legacy update criterion; rtol < 0 (DEFAULT): FOLLOW THE
394 // PRESSURE SOLVER'S TOLERANCE -- the projection is what consumes u*, and it resolves the
395 // divergence the momentum residual leaves to its own rtol, so "solve momentum no less
396 // accurately than pressure" is the self-consistent choice with no free constant.
398
399
400 // The momentum solver's default selection rule. Since 2026-09-15 the DEFAULT is the velocity
401 // V-cycle on every validated operator mode and at every rank count, replacing red-black
402 // Gauss-Seidel. Measured on the 1.0.0 scaling benchmark (384^3 cut-cell bed): the V-cycle is
403 // faster at every rung of both the Genoa and the H100 ladder -- 2.23x at 147k cells/rank,
404 // 2.19x on a single H100 -- and red-black was running at its sweep cap (velIters_), i.e. not
405 // converging, on every rung of both.
406 //
407 // This setter narrows that default rather than enabling it:
408 // cellsPerRank upper bound in cells per rank (default: none). 0 = never use the V-cycle.
409 // set_velocity_multigrid_auto(65536, 1 << 23) restores the 1.0.0 rule.
410 // minGlobalCells global-size floor (default: none).
411 // minBlockExtent shortest per-rank inner extent worth building a hierarchy on (default 16);
412 // below it the V-cycle degenerates to its bottom smoother and only adds setup.
413 // An explicit setVelocityMultigrid() overrides all of this.
414 void setVelocityMultigridAuto(long cellsPerRank, long minGlobalCells = -1,
415 int minBlockExtent = -1);
416
417
418 // Chebyshev semi-iteration as the momentum solver, in place of the red-black Gauss-Seidel
419 // smoother, on the SAME sharp cut-cell stencil and to the same tolerance -- so it has the same
420 // fixed point and the projection consumes the same u*. The momentum operator's condition number
421 // is kappa = 1 + 12 D in D = mu dt/(rho h^2) and does NOT grow with the mesh, so Chebyshev's
422 // O(sqrt kappa) beats Gauss-Seidel's O(kappa) without a coarse grid; and one Chebyshev step is
423 // ONE residual and ONE halo exchange against a red-black sweep's two of each. The spectral
424 // interval is Gershgorin arithmetic on the stored stencil (ibmStencilJacobiBounds), not a power
425 // iteration. IBM/periodic path only: a domain-BC configuration keeps RB-GS.
426 void setVelocityChebyshev(bool on, int maxit = 400);
427
428 // Return the momentum-solver choice to the automatic rule (the default), undoing an
429 // explicit setVelocityMultigrid/setVelocityChebyshev. The choice is re-taken at the next
430 // step(), where dt and mu are final.
433
434 // Chebyshev as the velocity MULTIGRID's smoother, in place of red-black Gauss-Seidel on every
435 // level. Independent of setVelocityChebyshev (which replaces the V-cycle outright): this keeps
436 // the V-cycle -- whose convergence is what actually wins on this operator -- and spends half the
437 // halo exchanges inside it. `degree` 0 follows the V-cycle's own pre/post/bottom sweep counts,
438 // so the two smoothers are compared at equal nominal work.
439 void setVelocityMgChebyshev(bool on, int degree = 0, double eig_ratio = 10.0);
441
442
443 // The tolerance actually in force (resolves the follow-the-pressure default).
445
446
447 // max over components of max|r|/max|b| at exit of the last step's momentum solves (residual
448 // mode only; -1 otherwise).
449 double lastMomentumResidual() const;
450
451
452 // Pressure-solve mean-removal scope: "fine" (default — drops the interior-level / post-matvec
453 // nullspace projections, ~3x fewer global-reduction latency hits per Krylov iteration; measured
454 // winner of the at-scale ablation, iteration counts identical) or "all" (legacy). See CutcellMG.
456
457
459
460
461 // Momentum advection, ON by default (2026-10-23 user directive; off = Stokes). Inert under
462 // enable_vof_momentum: see advectsMomentum().
463 void setAdvection(bool on);
464
465 // explicit high-order advection (default SOU)
466 // High-order advection scheme for the (explicit, or deferred-correction) flux: 0 = second-order
467 // upwind (SOU, default — 2nd order at smooth extrema too); 1 = Koren TVD (monotone limiter, the
468 // legacy CUDA scheme). Only matters when advection is enabled; FOU stays the deferred-correction
469 // base.
471
472
473 // Implicit-FOU deferred-correction advection (CUDA set_implicit_advection): solve the
474 // first-order-upwind part of advection implicitly (in the velocity operator) + keep (Koren-FOU)
475 // explicit in the RHS -> unconditionally stable for advection (high Re / large dt). Requires the
476 // IBM stencil (rebuilt per Picard iteration with the FOU term); the domain-BC path needs
477 // velocity-MG (separate milestone).
478 void setImplicitAdvection(bool on);
479
480
481 // Picard outer iterations over the step (CUDA set_outer_iterations): the advecting velocity is
482 // lagged at the current iterate u^k while the time base stays u^n. iters>=1; tol>0 stops early on
483 // max|du| < tol.
484 void setOuterIterations(int iters);
485
486
487 void setOuterTolerance(double tol);
488
489
491
492
493 // Velocity (momentum) multigrid for the IBM diffusion solve (CUDA set_velocity_multigrid): the
494 // STAIRCASE coarse operator (exact == RB-GS, stiff-stable at large dt). Call before set_solid;
495 // built at geometry time.
496 // Refused (std::invalid_argument) with a variable viscosity: the V-cycle takes a scalar mu.
497 void setVelocityMultigrid(bool on, int levels, int vcycles);
498
499 // The one message for an explicit velocity multigrid combined with a variable viscosity.
500 void throwVelocityMgVariableMu(const char* who) const;
501
502
504
505
506 // Enable the agglomerated GraphAMG bottom solve in the pressure MG: the coarsest level is solved
507 // by a mesh-agnostic algebraic multigrid on the operator gathered to rank 0 --
508 // decomposition-agnostic, so multilevel convergence works under a WEIGHTED ORB (where the
509 // geometric coarse levels can't cleanly coarsen). Applied at the next set_solid / geometry
510 // rebuild.
511 // Coarse-level (bottom) solve policy: 0 smoothed bottom (default), -1 auto (agglomerate exactly
512 // when the geometric hierarchy cannot reach a small enough coarsest grid), 1 always. See CutcellMG.
513 void setPressureBottomMode(int mode);
514 // Engine of an agglomerated bottom (doc/vof_step_performance_design.md §13): 0 "auto" (the
515 // single-team device bottom -- FP64 FCG preconditioned by the FP32 block-tridiagonal direct
516 // factor -- where eligible on a device backend, GraphAMG otherwise), 1 "direct" (raises at the
517 // bottom solve, naming the failed condition, where ineligible), 2 "algebraic" (GraphAMG always).
518 // Live; independent of the geometry.
519 void setPressureBottomSolver(int engine);
520 // Zebra line relaxation on the pressure-MG levels whose unique strong axis stops coarsening
521 // (doc/mg_depth_policy.md Amendment A2.4): DEFAULT on; off = point RB-GS everywhere. Live.
522 void setPressureLineRelaxation(bool enabled);
523 // The symmetric pressure V-cycle (doc/mg_depth_policy.md Amendment A3): piecewise-constant
524 // prolongation P = c R^T of the average restriction and a palindromic smoothed bottom, so the
525 // V-cycle is an SPD preconditioner for the CG drivers. DEFAULT on (WO-S3); off = the trilinear
526 // prolongation and the forward bottom bit for bit. Live.
527 void setPressureVcycleSymmetric(bool enabled);
528 // Precision of the pressure V-cycle preconditioner (doc/vof_projection_cost_design.md §4.4.6):
529 // 1 "fp64" (DEFAULT), 2 "fp32" (opt-in, single-rank; raises at the solve, naming the failed
530 // condition, where CutcellMG::fp32VcycleIneligible does not hold), 0 "auto" (opt-in; FP32 where
531 // eligible, else FP64, on a device backend; FP64 on a host backend, WO-A of
532 // doc/vof_projection_distributed_design.md). Live: the FP32 weights are rebuilt from the stored
533 // level openness at once.
535 // The precision the last pressure solve's V-cycles used: true = FP32.
536 bool pressureVcycleFp32() const;
537 // C++ test hooks of the FP64 restart (doc/vof_projection_distributed_design.md §4, gate G-R (g));
538 // no Python binding: CutcellMG::debugSetFp32Fault, the restart count, the projected-guess
539 // history count.
540 void debugSetPressureFp32Fault(int kind, int at);
543
544 // Coarse-level telescoping of the pressure multigrid (mac_cutcell_mg.hpp Telescope): when a
545 // per-rank block turns odd, merge ORB siblings onto fewer ranks and keep coarsening instead of
546 // stopping. Multi-rank only; a no-op single-rank. Takes effect at the next init_mpi/set_solid.
547 void setPressureTelescope(bool on);
548
549
550 bool pressureTelescope() const;
551
552
553 // Force a telescope at that level even where in-place coarsening is legal (tests: compare the
554 // two hierarchies on one problem); -1 = the trigger decides. Set before geometry.
556
557
559
560
561
562 void setPressureGraphAmg(bool on);
563
564
565 void setPressureLevels(int levels);
566
567 // MG depth (CUDA default 4)
568 // Backflow stabilization at outflow faces (Bazilevs 2009 / Esmaily-Moghadam 2011): beta in [0,1]
569 // scales the dissipative outflow term that prevents backflow divergence (0 = off). Default 0.2.
570 void setBackflowStab(double beta);
571
572
573 // Deferred-correction advection: on (default) = implicit FOU operator + explicit (HO - FOU)
574 // high-order correction (2nd order; HO = SOU by default, or Koren TVD via set_advection_scheme).
575 // off = pure implicit FOU (1st order, more dissipative, unconditionally stable) -- useful for
576 // very sharp shear layers where the (unlimited SOU) explicit correction overshoots and
577 // destabilizes.
579
580
581 // Chebyshev pressure driver (CUDA set_pressure_chebyshev): communication-light alternative to
582 // MG-PCG -- Chebyshev semi-iteration preconditioned by one symmetric V-cycle, no per-iteration
583 // global dot-products. Spectral bounds of M^{-1}A are estimated once (lazily) on the first solve
584 // and reused every step.
585 // Selecting it clears the competing FCG selection (the three Krylov drivers are mutually
586 // exclusive, last set wins); `on = false` only deselects Chebyshev, so the solve falls back to
587 // whatever else is selected — FCG if set, otherwise MG-PCG.
588 void setPressureChebyshev(bool on, int maxit, double rtol);
589
590
591 // MG-PCG pressure driver (CUDA set_pressure_pcg) + its iteration cap / relative tolerance.
592 // `on = true` GENUINELY SELECTS MG-PCG, clearing both competing selections (Chebyshev and FCG),
593 // so it works after set_density_mode / set_porous — "last set wins", as CLAUDE.md and the
594 // docstring have always claimed. Until 2026-08-30 the flag was silently discarded (WO-H defect 1;
595 // the working spelling was set_pressure_chebyshev(False, ...)), which is why every "PCG under
596 // varRho/porous" measurement before WO-B actually measured Chebyshev.
597 //
598 // `on = false` cannot be honoured and therefore THROWS rather than being silently ignored (the
599 // failure mode this repair exists to remove): MG-PCG is the terminal fallback of the dispatch in
600 // project() — with neither Chebyshev nor FCG selected the solve IS MG-PCG — so "not PCG" is only
601 // expressible by selecting another driver. Say which one: set_pressure_chebyshev(True, ...) or
602 // set_pressure_fcg(True, ...).
603 //
604 // Under set_ghost_projection the operator is nonsymmetric and is solved by BiCGStab; this call
605 // stays legal there (it is how that path's cap/tolerance is set — pcgMaxit_/pcgRtol_ are shared)
606 // and simply does not change which Krylov method the gp branch runs.
607 void setPressurePcg(bool on, int maxit, double rtol);
608
609
610 // FLEXIBLE MG-CG (set_pressure_fcg): the same Krylov driver as MG-PCG with the same V-cycle
611 // preconditioner, the same stopping estimate, the same mean removal and the same cap/tolerance
612 // (`pcgMaxit_`/`pcgRtol_`, shared deliberately — it is the same solve), differing ONLY in the
613 // beta recurrence: Polak-Ribiere `r^T(z_{k+1} - z_k) / r^T z_k` instead of Fletcher-Reeves.
614 // Costs one extra level-0 vector and one extra global dot per iteration; buys tolerance of a
615 // preconditioner that is not symmetric w.r.t. the fine operator (CutcellMG::solveFCG).
616 //
617 // All three Krylov drivers are mutually exclusive in both directions and the last set wins:
618 // `on` clears `useChebyshev_` here, `setPressureChebyshev(true, ...)` clears `useFcg_`, and
619 // `setPressurePcg(true, ...)` clears both. `set_pressure_fcg(false)` returns the solve to MG-PCG.
620 // (Before WO-H, setPressurePcg's `on` flag was silently discarded — see its comment.)
621 void setPressureFcg(bool on, int maxit, double rtol);
622
623
624 // EXPERIMENTAL directional ghost-cell projection (second staggered IBM, ghost_projection.hpp):
625 // point-based FD divergence with wall-anchored directional closures instead of the
626 // openness-weighted cut-cell projection. Call BEFORE set_solid (the overlay is built there).
627 // v1: periodic + IBM only, stationary walls (both grids; the collocated variant closes the
628 // face-AVERAGED field and adds the gpCenterGrad predictor/correction, face_interp 0 only).
629 // Runs multi-rank (initMpi): gp-row ownership is by inner-block cell, the closures read the
630 // exchanged g=2 halo, and the fragmentation guard runs on the allgathered GLOBAL sdf (the
631 // exact-crossings / openness-override study inputs stay single-rank). The nonsymmetric extended
632 // stencil is solved by MG-preconditioned BiCGStab (binary-openness surrogate hierarchy).
633 // matrixOrder/rhsOrder select the closure order (1 = linear, 2 = wall-anchored quadratic) for
634 // the implicit phi couplings and the divergence RHS/diagnostic respectively:
635 // (2,2) full quadratic (13-point nonsymmetric matrix);
636 // (1,1) linear everywhere (7-point matrix, 1st-order closure);
637 // (1,2) MIXED/deferred: 2nd-order steady constraint with a 7-point near-symmetric matrix —
638 // the operator mismatch converges through the time stepping (measured rate ~0.4).
639 void setGhostProjection(bool on, int matrixOrder = 2, int rhsOrder = 2);
640
641
642 // Analytic-SDF capability: EXACT wall-crossing fractions overriding the linear-interp theta in
643 // BOTH the momentum cut-cell overlay and the ghost-projection closures. t is a flat array of
644 // size 9*nx*ny*nz, blocks ordered [(c*3 + k)]: for velocity component c, t[(c*3+k)*n + i] is
645 // the exact crossing fraction in (0,1) from component c's staggered point at inner cell i
646 // toward its +k-axis neighbour point, NaN where the segment has no wall crossing. Computed in
647 // Python from the analytic geometry (e.g. line-sphere intersection). Call BEFORE set_solid;
648 // pass an empty array to clear. Single-rank only.
649 void setExactCrossings(const std::vector<double>& t);
650
651
652 // Analytic-SDF capability: EXACT face-openness (aperture) fields overriding the sampled-SDF
653 // ccFractionCore openness the cut-cell projection uses. Inner arrays (flat x-fastest,
654 // nx*ny*nz); ox[i] = fluid area fraction of the -x face of cell i, etc. Call BEFORE set_solid.
655 void setOpennessOverride(const std::vector<double>& ox, const std::vector<double>& oy,
656 const std::vector<double>& oz);
657
658
659 // Incremental-rotational pressure (CUDA set_incremental_pressure, default ON): the predictor
660 // carries -grad(P^n) and the physical pressure is accumulated rotationally P += (rho/dt)*phi -
661 // mu*div(u*). OFF => classical non-incremental Chorin (no -grad(P^n) predictor; P derived on
662 // demand as (rho/dt)*phi).
664
665
666 // Balanced-force projection (doc/collocated_varrho_forces.md §4.6; PUBLIC tier, both grids).
667 // Once per step, after the property/curvature refresh and before the momentum predictor, solve
668 // D(O c w G X) = D(O c beta), c = rho0/rho_f^op (1 at constant rho),
669 // beta = f_const + ½(f(j) + f(j-s)) + CSF(j) (the predictor's own face force, without rs),
670 // with the projection's OWN operator, constraint divergence and driver, as an INCREMENT on the
671 // previous split, X = P_b + dP_b, stopped relative to the full right-hand side (and skipped when
672 // P_b already meets it), then P += X - P_b, P_b = X -- or, when P_b is not a valid split of the
673 // current P (the first step after steps with the option off, or a restart that restored "p"
674 // but not "p_balanced"), P_b = X with P unchanged (a RE-SPLIT: never a second copy of the
675 // balanced pressure). "p_balanced" is RESTART STATE: it is registered as soon as the option is
676 // active; restoring it together with "p" (set_field) keeps the split, omitting it re-splits.
677 // P stays the total physical pressure; the predictor then sees only
678 // the part of the forces that drives flow, so gradient forces (hydrostatics, constant-kappa CSF)
679 // are balanced exactly from step 1 at every mu, dt, density ratio and openness. The solve is
680 // state-independent: stability and the converged steady state are identical ON and OFF. Cost:
681 // one extra pressure solve per step while the forces change; none for a static interface.
682 // DEFAULT (U2): ON on the collocated variable-density / CSF path (V8) -- except with an
683 // inflow/outflow domain face, where the default resolves OFF with a one-time stderr notice --
684 // and OFF elsewhere; an explicit setting always wins. OFF is byte-identical to a solver
685 // without the option. Refused, with a named error at this setter when the configuration is
686 // already known and otherwise at the next step: porous continuity, the ghost projection,
687 // set_fluid_only_constraint(2), the block CSF, any inflow/outflow face, the non-incremental
688 // pressure, no cut-cell pressure operator, and the constant-density collocated path (its
689 // pressure force is gpCenterGrad; there is nothing to balance).
690 void setBalancedForceProjection(bool enabled);
692 // Pressure-driver iterations of the last step's balanced-force solve (0 when the force
693 // divergence was exactly zero, or the option is off).
695 // Did the last step's balanced-force solve FAIL (driver breakdown, or a non-finite result)? A
696 // failed solve leaves P and P_b as they were (the step runs as if the option were off for that
697 // step's split) and is counted in balancedForceFailures(); the first one warns on stderr.
700
701
702 // Pressure warm-start (CUDA set_pressure_warmstart, default OFF): seed each cut-cell pressure
703 // solve from the previous step's projection potential (consecutive phi's are similar along a
704 // steady march -> a more converged phi per fixed solver budget) instead of zeroing the initial
705 // guess.
706 void setPressureWarmstart(bool on);
707 // Initial guess of the projection solve (doc/vof_projection_cost_design.md §5.3): 1 "zero"
708 // (DEFAULT), 2 "projected" (opt-in, any np; raises at the solve, naming the failed
709 // condition, where ineligible), 0 "auto" (opt-in; projected where eligible, else zero); history
710 // 1 or 2 increments. Resets the history.
711 void setPressureInitialGuess(int mode, int history);
712 // Why the projected guess cannot run on this solver's next projection, or nullptr.
713 const char* projectedGuessIneligible() const;
714
715
716 // Collocated cut-cell treatment of the approximate projection (no effect on the staggered path).
717 // The public API is the string form setCollocatedScheme(); the integer mode is the C++ switch
718 // behind it and the Python developer tier's `diagnostics.set_face_interp(5|6)`:
719 // 0 "plain" plain ½/½ cell->face averaging + central-difference -grad(P): a consistent
720 // adjoint pair of the WRONG geometry (wall at the solid neighbour's centre),
721 // first-order drag at curved walls. Legacy, kept for reproducing results.
722 // 9 "gauge-exact" the aperture constraint (unchanged, throat-safe, symmetric MG-PCG) with the
723 // directional gpCenterGrad replacing the two operators measured to be O(1)
724 // at cut cells -- the -grad(P) predictor and the projection's cell
725 // correction. SECOND ORDER on two periodic sphere beds (2.36-2.89 over
726 // R=5..8, +0.08 % of k_inf at R=16) where mode 0 is first order; the
727 // cheapest scheme measured (doc/collocated_paper_plan.md).
728 // 5/6/7 "embed" the Basilisk embed.h port (commits db5b4aa/f5fde8c/6d412ec/03a71c6,
729 // doc/history/collocated_embed_port_plan.md): the FV momentum operator with
730 // the true-normal dirichlet_gradient wall drag applied as a defect
731 // correction on the IBM matrix (5 = that alone, on the wall-aware face map
732 // with the transpose-gradient pressure force; 6 = plus the openness-weighted
733 // -grad(P) predictor and cell correction, on the plain face map; 7 = 6 on
734 // the wall-aware face map and the solid-cut-cell sliver mask -- the
735 // COMPLETE port, the public "embed"). The live candidate for removing the
736 // collocated accuracy ceiling; 5 and 6 are its two intermediate rungs.
737 // The "ghost" scheme (setGhostProjection) is not a face-interp mode: it owns the operators the
738 // modes replace and forces mode 0 underneath itself.
739 // Modes 1, 2, 3, 4, 10, 11, 12 and 13 (pure ablations, the FV-constraint variants and the
740 // adjoint-aperture family) and the "gauge-2a" one-sided gradient branch were DELETED with their
741 // kernels at 1.0.0 (suite/docs/QUALITY_PLAN.md F); the record of what they measured is in
742 // doc/history/collocated_*.md.
743 void setFaceInterp(int mode);
744
745
746 int faceInterp() const;
747
748
749 // Preferred API for the collocated projection scheme (the strings the Python API takes):
750 // "ghost" the fluid-only constraint scheme (the AUTO default where supported)
751 // "gauge-exact" aperture constraint + directional (gauge-exact) pressure gradient (mode 9)
752 // "plain" the legacy plain-average / central-difference path (mode 0, first order)
753 // "embed" the complete Basilisk embed.h port (mode 7)
754 void setCollocatedScheme(const std::string& name);
755
756
757 // PM I ablation (Guy-Fogelson): keep the incremental predictor -grad(P^n) but accumulate
758 // P += (rho/dt)*phi WITHOUT the rotational -mu*div(u*) term (constant-mu path only; the
759 // variable-mu branches keep their own treatment). Default true = shipped behaviour.
761
762
763 // Rotational under-relaxation: P += ct*phi - w*mu*div(u*). w = 1 is the shipped Timmermans
764 // update; w = 0 is PM I. Shrinking w shrinks the O(1) velocity->pressure off-diagonal that
765 // makes the cell-centered approximate projection marginally unstable (Guy-Fogelson eq. 92-94:
766 // the destabilizing-perturbation threshold scales ~1/w), at the cost of ~1/w slower pressure
767 // relaxation of the smooth modes at large dt. phi = 0 stays the unique fixed point for ANY
768 // w > 0, at every dt including dt -> infinity.
769 void setRotationalWeight(double w);
770
771
772 // Wall-banded rotational blend (Frank, 2026-08-20): see the press_wallblend kernel. w0 = 0
773 // (default) disables; typical w0 ~ 0.3-0.5. Composes with setRotationalWeight (uniform factor).
774 void setRotationalWallWeight(double w0);
775
776
777 // Fluid-only pressure constraint (route 2b). Call BEFORE set_solid. Collocated experiment;
778 // defaults byte-identical when 0. mode 1 = Design A (close every openness face with a
779 // solid-centered side, everywhere); mode 2 = Design B (Kron star elimination: filtered
780 // openness feeds the MG hierarchy only, the SPD star overlay restores the throat coupling in
781 // the PCG matvec, the divergence keeps the original apertures on fluid rows, and fluid|solid
782 // faces are corrected with phibar_s -- see star_elimination.hpp).
783 // Aperture estimation order (2026-08-26): 1 = the shipped one-sample linear model (default,
784 // byte-identical), 2 = marching-squares (5 trilinear samples/face, triangle-fan; O(h^2),
785 // removes the convexity bias measured at +0.59%/+0.27% bed-k at R=8/12 -- tracker row 51).
786 // In-solver ceiling is the trilinear field; for ANALYTIC geometry use exact/Saye apertures
787 // via set_openness_override (scripts/exact_apertures_spheres.py). Call before set_solid.
788 void setApertureOrder(int order);
789
790
791 int apertureOrder() const;
792
793
796
797
799
800
811 void setUfAdvection(bool on);
812
813
814 bool ufAdvection() const;
815
816
820 void setCommAvoiding(int mask);
821
822
823 int commAvoiding() const;
824
825
828 void setMultigridAspectThreshold(double theta);
829
830
832
833
836 void setPressureStrict(bool on);
837
838
839 bool pressureStrict() const;
840
841
845
846
848
849
852 void setPressureBottomExtent(int cells);
853
854
856
857
860 void setDecomposition(int levels, double maxImbalance = 1.05);
861
862
864
865
867
868
870
871
872 // Filtered rotational update (experimental): P += ct*phi - mu*S(div u*), S = one mask-aware
873 // axis-wise (1,2,1)/4 smoothing pass per axis (one-sided 1/2(d_i+d_nbr) toward the open side at
874 // a solid-centered neighbour, identity when sandwiched). S annihilates the axis checkerboard
875 // including AT wall-adjacent cells; for smooth fields S = I + O(h^2). Steady state unchanged.
876 void setRotationalFilter(bool on, double eps = 0.05);
877
878
879 // Seed/restore the velocity state (CUDA set_state / upload_velocity): u/v/w are inner-cell fields
880 // (flat x-fastest, size nx*ny*nz); written into the velocity block + ghosts refreshed (periodic
881 // wrap).
882 // ISSUES sweep item 5. On the COLLOCATED grid the colour transport rides the MAC face field
883 // `uf_/vf_/wf_` (the only discretely divergence-free field on that grid), which only exists
884 // after a projection. `set_state` / `set_velocity` write the CELL field and used to leave the
885 // face field untouched — all zeros on a fresh solver — and `advect_vof` then ran happily:
886 // its guard measures the FACE field's divergence and a zero field is perfectly solenoidal. So a
887 // benchmark loop written the staggered way produced a "conservative" run in which nothing ever
888 // moved (measured on LeVeque 32^3: max|u| = 63.3, max|uf| = 0.0, max|C - C0| = 0.0 after
889 // `advect_vof`, no throw and no warning).
890 //
891 // Seeding the face field from the cell field with the SAME `centerToFace` map `project()` uses
892 // makes the kinematic entry point mean the same thing on both grids — and it makes the existing
893 // divergence guard MEASURE something: an analytic cell field that is not discretely solenoidal
894 // on the faces is now rejected instead of silently accepted. It does not make the face field
895 // divergence-free (only a projection does), and it is overwritten by the next `project()`, so
896 // nothing downstream changes. Staggered: a no-op (the cell field IS the face field).
898
899
902 void uploadVelocity(const std::vector<double>& uu, const std::vector<double>& vv,
903 const std::vector<double>& ww);
904
905#ifdef PECLET_FLOW_MPI
906
907 // Multi-rank: this rank's IbmSolver is constructed with its LOCAL block dims (= the
908 // BlockDecomposer of the GLOBAL grid for this rank); initMpi wires the g=2 velocity-block halo +
909 // the global-origin red-black parity, and switches fillGhosts/maxOpenDivergence + the pressure MG
910 // (CutcellMG::initMpi) onto their distributed paths. The caller decomposes first (deterministic
911 // ORB) to size the constructor; initMpi re-derives it.
912 void initMpi(int gnx, int gny, int gnz, MPI_Comm comm);
913
914
915 // Shared-decomposition overload: wire the g=2 velocity-block halo from an EXTERNALLY-built ORB
916 // (so flow and dem share one BlockDecomposer for coupled runs, and redistribute() can re-init
917 // onto a re-decomposed partition). The local block size must already match dec.block(rank).size
918 // (set via the constructor / allocateBlock).
919 void initMpi(const peclet::core::decomp::BlockDecomposer<3>& dec, MPI_Comm comm);
920
921
922 // Redistribute the solver's state onto a NEW decomposition (dynamic load balancing). Enumerates
923 // the registered fields, moves them from the current block layout to the new one (bit-exact via
924 // redistributeGridFields), reallocates every buffer to the new block, re-inits the halo +
925 // pressure MG on the new partition, and rebuilds all geometry-derived state (openness / IBM
926 // overlay / stencils) from the migrated SDF. Velocity + pressure + SDF (+ any registered
927 // scalar/property fields) survive; per-step scratch is rebuilt.
928 void redistribute(const peclet::core::decomp::BlockDecomposer<3>& newDec);
929
930
931 // Redistribute onto the ALIGNED weighted ORB of per-cell weights `w` (global x-fastest,
932 // gnx*gny*gnz). The ergonomic Python entry point for load balancing: the caller passes a weight
933 // field (e.g. fluid work + gamma*particle_count) and both flow and dem rebuild the SAME
934 // deterministic partition from it. No BlockDecomposer object crosses the language boundary.
935 // Returns the alignment 2^a the imbalance budget chose (1 = the plain weighted ORB; 1 also when
936 // not distributed): a co-decomposing code must build its partition from the same `w` AND this
937 // alignment (dem: `migrate_to_weights(w, align=...)`), or the two own different blocks.
938 int rebalanceByWeights(const std::vector<peclet::core::Real>& w);
939
940 // The pressure multigrid hierarchy as built, one row per level in the format of the pure
941 // pre-flight CutcellMG::predict (flow.predict_hierarchy): global dims, ranks holding the level,
942 // this rank's block, ratio to the next level, and whether (and how) the transition out of it
943 // telescopes. Rank 0 holds every level. The test oracle for the forecast.
944 std::vector<CutcellMG::PlanRow> pressureMgPlan() const;
945
946#endif
947
948 // per-face domain BC {face 0..5 = -x,+x,-y,+y,-z,+z}: type 0=periodic,1=no-slip
949 // wall,2=Dirichlet/inflow,3=outflow,4=free-slip/symmetry (zero normal velocity, zero normal
950 // derivative of the tangential components, pressure Neumann like a wall; vx/vy/vz ignored).
951 // Call order (QUALITY_PLAN F milestone iv, refined 2026-09-10): the TYPE decides the operator
952 // openness (wall/inflow closed, outflow open, periodic) and the stencil path, so only a TYPE
953 // CHANGE has to precede the geometry; a VALUE update on a face whose type is unchanged (ramping
954 // an inflow jet, a lid's tangential speed) is allowed at any time and takes effect the next
955 // step -- see the refresh below.
956 void setDomainBc(int face, int type, double vx, double vy, double vz);
957
958
959 // per-position inlet velocity profile on `face` (CUDA set_domain_bc_profile): prof is (nb,nc,3)
960 // on the inner grid of the face's two perpendicular axes; sets the face to inflow (type 2).
961 // Resampled (clamp) to the ghost-inclusive face grid so the BC kernel indexes it directly by face
962 // position. Same call-order rule as set_domain_bc: allowed after the geometry only when the
963 // face is ALREADY inflow (a profile VALUE update), since that is the one case that does not
964 // change the type the operators were built with.
965 void setDomainBcProfile(int face, const std::vector<double>& prof, int nb, int nc);
966
967
968 // Resample the stored raw inlet profile of `face` onto THIS block's ghost-inclusive face grid.
969 void resampleBcProfile(int face);
970
971
972 // all-fluid + domain-BC pressure (CUDA set_pressure_geometry): same path as set_solid with an
973 // open SDF.
974 void setPressureGeometry(const std::vector<double>& sdfInner);
975
976
977
978 // SDF on the inner cells (flat x-fastest, size nx*ny*nz; <0 solid). cutcellPressure enables the
979 // open-face-weighted cut-cell projection (off => velocity-only, e.g. unidirectional body-force
980 // flow).
981 // ---------------------------------------------------------------------------------------
982 // ANALYTIC SCENE (Layer 2 of suite/docs/ANALYTIC_SDF_GEOMETRY.md)
983 //
984 // Geometry has only ever reached flow as an already-sampled field, with "analytic accuracy"
985 // supplied as override arrays computed in Python (set_exact_crossings / set_openness_override) --
986 // spheres only, and SINGLE-RANK only. A scene set here is device-resident and REPLICATED on every
987 // rank, so a rank derives its own block's geometry from it with no communication at all; that is
988 // what lifts the single-rank restriction rather than any new exchange.
989 //
990 // Geometry is expressed in CELL UNITS on the GLOBAL inner grid (cell centre (i,j,k) sits at
991 // (i,j,k)), matching scripts/exact_apertures_spheres.py's centers_cells / radii_cells.
992 //
993 // PERIODICITY is the caller's: the scene is evaluated at global cell coordinates and has no
994 // wrap of its own, so a periodic packing must instantiate its images (or use a node whose eval
995 // is periodic). Nothing here min-images for you.
996 // ---------------------------------------------------------------------------------------
997
1008 void setScene(const std::vector<int>& nodeInts, const std::vector<double>& nodeReals,
1009 const std::vector<int>& instInts, const std::vector<double>& instReals,
1010 bool periodic = false);
1011
1012
1013
1016 std::array<double, 3> instanceCenter(int i) const;
1017
1018
1019 bool instanceCenterPinned(int i) const;
1020
1021
1022
1031 void setInstanceMotion(int i, const std::array<double, 3>& lin,
1032 const std::array<double, 3>& ang, const double* center = nullptr);
1033
1034
1035
1043 void setInstanceTransform(int i, const std::array<double, 3>& translation,
1044 const std::array<double, 4>& quat);
1045
1046
1047
1063
1064
1065
1082
1083
1084
1088 void setFreshCellSeed(bool on);
1089
1090
1091 bool freshCellSeed() const;
1092
1093
1094
1108
1109
1110
1113 bool hasMovingInstance() const;
1114
1115
1117
1118
1119
1125
1126
1128
1129
1130
1131 bool hasScene() const;
1132
1133
1134
1137 std::vector<int> getCutOwner() const;
1138
1139
1140
1143 void setSolidFromScene(bool cutcellPressure);
1144
1145
1146
1154
1155
1160 std::vector<long> movingInstanceCutCells() const;
1161
1162
1164 std::vector<long> movingInstanceDegeneratePoints() const;
1165
1166
1167
1171
1172
1173
1184
1185
1186
1189 void setSolid(const std::vector<double>& sdfInner, bool cutcellPressure);
1190
1191
1192
1197 void buildVelocityOverlays(bool resetU);
1198
1199
1200
1207
1208
1211 void setSolidDevice(CCField din, bool cutcellPressure);
1212
1213
1214 // ---- setSolidDevice stages (QUALITY_PLAN G.1): pure cut-and-paste, each a contiguous
1215 // block of the original function sharing only member fields and a CCExec. ----
1217
1218
1220
1221
1223
1224
1226
1227
1229
1230
1232
1236
1241
1242
1244
1245
1247 // setSolidGhostProjectionOverlay() phase (WO-HO), public for its device lambda: the pocket-decoupled
1248 // projection sdf uploaded into sdfGp (block + halo exchange, or periodic wrap).
1249 void gpUploadSdf(const std::vector<double>& sdfGpHost, std::size_t nInner, CCField sdfGp);
1250
1251
1253
1254
1255 bool geometryBuilt() const;
1256
1257
1258 void requireNoGeometry(const char* who) const;
1259
1260
1261
1262 void step();
1263
1264
1265
1284 double maxReverse = 0.0, fraction = 0.0, energyInflux = 0.0;
1285 long reversed = 0, total = 0;
1286 };
1287 OutflowBackflow outflowBackflow();
1288
1289
1290 // velocity component c (0=u,1=v,2=w) on the inner cells, flat x-fastest [nx*ny*nz].
1291 std::vector<double> getVelocity(int c);
1292
1293
1297 void setVelocity(int c, const std::vector<double>& v);
1298
1299
1300 // The divergence-free FACE velocity component (collocated: the projected MAC face field
1301 // uf_/vf_/wf_, exactly div-free; staggered: C[c].u already lives on the faces). For a periodic
1302 // bed its mean is the momentum-balance superficial velocity, unperturbed by the openness-aware
1303 // cell gradient correction (projectCorrectCenter) that biases the cell-field mean at cut cells.
1304 std::vector<double> getFaceVelocity(int c);
1305
1306
1307 // TEMP DIAGNOSTIC: the face openness (fluid area fraction) used by the cut-cell projection.
1308 // component c: 0 -> ox_ (low -x face of each inner cell), 1 -> oy_, 2 -> oz_. Grid-independent
1309 // (built once from the SDF). Exposed to compare the open-weighted superficial flux against the
1310 // raw velocity mean.
1311 std::vector<double> getOpenness(int c);
1312
1313
1314 // Diagnostic read-out of the ASSEMBLED momentum-operator diagonal of component c — the float
1315 // stencil `AC` after the diffusion build, the Robust-Scaled cut-cell bake and, under implicit
1316 // drag, `addDragDiagonal`'s face drag beta_f — as an x-fastest (nx,ny,nz) inner-region host
1317 // buffer. Read-only; no solver state is touched. Added for WO-I's
1318 // `tests/kokkos_mpi/test_dragbeta_ghost_mpi.cpp`, which must gate the FACE drag mean where it is
1319 // formed: on a periodic box the projection homogenizes a single bad plane into a uniform mean
1320 // shift of the velocity, so a velocity-only gate sees THAT the drag was wrong but not WHERE.
1321 std::vector<double> getMomentumDiagonal(int c);
1322
1323
1324 // The openness whose face fluxes the PROJECTION conserves: the binary (COUPLED) openness in
1325 // ghost-projection mode (oxb_ — the geometric ox_ stays a diagnostic there), the geometric
1326 // cut-cell openness otherwise. This is what flux bookkeeping downstream of the solve must use
1327 // (e.g. peclet.pnm's extract_network_flow): sum(o_proj*u*A) over a cell's faces IS the
1328 // discrete divergence the projection drives to zero.
1329 std::vector<double> getOpennessProj(int c);
1330
1331
1332 std::vector<double> getPressure();
1333
1334
1335 // WO-R: the divergence of the field the projection ACTUALLY produced, outflow correction
1336 // included. `maxOpenDivergence()` below re-imposes the zero-gradient outflow face before
1337 // measuring (its own comment says so) — which both destroys `bcCorrectOutflow`'s correction as a
1338 // side effect and reports the divergence of a field the solver never used. On an open-boundary
1339 // two-phase box that artefact is the dominant number: measured 5e-3, flat in the iteration
1340 // count, flat in the density ratio and bit-identical in a `-DPECLET_FLOW_OPERATOR_DOUBLE` build —
1341 // i.e. not a solver residual at all. This sibling fills the ghosts with `doOutflow = false`,
1342 // exactly as `step()` does after `project()`, and leaves the velocity field alone.
1343 //
1344 // Kept as a SIBLING rather than a change of default: every recorded open-boundary number in the
1345 // repo was taken with the mutating one, and re-baselining them is not this work order's call.
1347
1348
1351
1352
1354
1355
1358
1359
1360 // Residual of the volume-averaged continuity, max|div(open*eps*u) + d(eps)/dt| — the quantity the
1361 // porous projection actually drives to zero (NOT the velocity divergence, which is -d(eps)/dt !=
1362 // 0 in a fluidizing bed). Meaningful only with set_porous_continuity(True); returns 0 otherwise.
1364
1365
1367
1368
1369 // D3 (doc/vof_step_performance_design.md §5.13): how many pressure solves on warm-started
1370 // Chebyshev bounds tripped the guard (the cap, or a residual above r0 after 3 iterations) and
1371 // were redone on cold bounds, since construction.
1372 long numPressureChebyshevRestarts() const { return chebColdRestarts_; }
1373 // C++ test hook, no Python binding: how many Chebyshev spectral-bound estimates (main and
1374 // balanced-force) the pressure multigrid has run since construction.
1375 long numPressureEigenEstimates() const { return mg_.numEigenEstimates(); }
1376 // How many Chebyshev pressure solves on COLD-estimated bounds (main and balanced-force) saw
1377 // their preconditioned residual norm rise above its initial value and were redone on bounds re-estimated with the bracketing
1378 // margin (CutcellMG::kChebBracket), since construction (doc/mg_depth_policy_log.md 2026-10-30).
1379 long numPressureChebyshevGrowthTrips() const { return chebGrowthTrips_; }
1380 // C++ test hook, no Python binding: the NEXT spectral-bound estimate returns both bounds x s
1381 // (CutcellMG::debugSetEigenScale; s < 1 forces the growth guard).
1382 void debugSetPressureEigenScale(double s) { mg_.debugSetEigenScale(s); }
1383 // C++ test hook, no Python binding: drop the main Chebyshev bounds exactly as a coefficient
1384 // rebuild does (project()'s variable-density refresh), so the next solve re-estimates warm.
1386 chebWarmOk_ = chebWarmOk_ || chebBoundsSet_;
1387 chebBoundsSet_ = false;
1388 }
1389
1390
1391 // Q18: the exit check of the two CG drivers (MG-PCG, flexible CG). After every PCG/FCG
1392 // pressure solve -- the main and the balanced-force projection -- the TRUE residual
1393 // max|P(b - A x)| is recomputed once and divided by the stop test's own threshold rtol * r0
1394 // (CutcellMG::cgTrueResidual). Above max(kCgGuardFactor, kCgGuardFloor / rtol), or capped /
1395 // broken down, the solve counts as UNCONVERGED: a warning goes to stderr (rank 0; the first, then the 10th, 100th, ...), and
1396 // numPressureUnconvergedSolves() counts it. The check never touches x, the iteration or the
1397 // stopping rule. lastPressureTrueResidual() is the last checked ratio (0 when the last solve was
1398 // not a CG solve or had a zero right-hand side).
1399 double lastPressureTrueResidual() const { return lastPressureTrueResidual_; }
1400 long numPressureUnconvergedSolves() const { return numPressureUnconvergedSolves_; }
1401
1402
1403 // The pressure multigrid's per-level coarsening ratio, one {rx, ry, rz} per level
1404 // (doc/anisotropic_metric.md §5). On an isotropic domain this is today's table; on a stretched
1405 // one the aspect rule defers an axis while it is at least the aspect threshold (2) times
1406 // coarser than the finest coarsenable one. Empty until the cut-cell operator exists.
1407 std::vector<std::array<int, 3>> pressureMgLevelRatios() const;
1408
1409
1410 // ISSUES sweep item 6: did the last pressure solve break down (non-finite
1411 // preconditioner output / recurrence scalar)? A failing solve also reports the
1412 // iteration cap through `lastPressureIterations()`.
1414
1415
1416 // The state of the steady march (doc/steady_acceleration.md §3.1, §5.1, rev 1): exactly what
1417 // step() reads across steps, as the full padded G = 2 buffers, with their roles for the Anderson
1418 // accelerator's metric. Velocity = the three velocity components (measured); Carried = the
1419 // accumulated pressure P and, on the collocated grid with projected-face advection, the face
1420 // field uf/vf/wf (mixed and differenced, never measured). `signature` is (dt, rho, mu, Fx, Fy,
1421 // Fz, advection on, advection scheme, implicit advection), all internal: a change of any of them
1422 // changes the map (the last three: review R5).
1423 struct MarchState {
1424 std::vector<CCField> fields;
1425 std::vector<peclet::core::solver::AndersonRole> roles;
1426 C3 e{0, 0, 0};
1427 int G = 2;
1428 std::array<double, 9> signature{};
1429#ifdef PECLET_FLOW_MPI
1430 MPI_Comm comm = MPI_COMM_NULL;
1431 bool distributed = false;
1432#endif
1433 };
1434
1435
1436 // The march state of this solver (above), for the Anderson accelerator
1437 // (src/anderson_accelerator.hpp). Public C++, not bound. Throws std::runtime_error naming the
1438 // FIRST configuration the steady acceleration refuses (doc/steady_acceleration.md §5.3, D10): a
1439 // collocated scheme other than the fluid-only 'ghost' projection; phase change; VoF; transported
1440 // scalars; porous continuity; variable density or viscosity; a drag_beta field; cell force
1441 // fields; moving scene instances; a superficial-velocity target; the pressure warm start; the
1442 // balanced-force projection. A re-evaluation of host flags only, so the accelerator repeats it
1443 // at every step.
1444 MarchState marchState();
1445
1446
1447 // Per-phase wall times of the last step() in seconds, THIS RANK (device-fenced at each phase
1448 // boundary): predictor = ghost fills + RHS/advection/stencil builds, momentum = the per-component
1449 // implicit-diffusion solves, projection = the cut-cell pressure projection; step = the whole
1450 // step() (remainder = BC re-imposition, Picard bookkeeping, scalars). The allreduce pair is the
1451 // pressure solve's global-reduction tax (time in / count of MPI_Allreduce; 0 single-rank).
1452 double lastStepSeconds() const;
1453
1454
1455 double lastPredictorSeconds() const;
1456
1457
1458 double lastMomentumSeconds() const;
1459
1460
1462
1463
1464 // ---- WO-V9: the VoF pipeline's own per-stage timers ----------------------------------------
1465 //
1466 // `set_vof_timing(True)` arms them; they are OFF by default and, when off, cost one predictable
1467 // branch per stage and no fence. A phase boundary on a device backend has to fence or the
1468 // queued work of one stage is billed to the next — the same rule `phaseTick()` already applies
1469 // to the step's three coarse phases — so the boundaries fence WHEN ARMED and only then. A fence
1470 // reorders nothing and computes nothing: the gate is that the same run with timing on and off
1471 // produces bit-identical fields (`tests/kokkos/test_vof_timing.cpp`).
1472 //
1473 // The stages are cumulative over steps since the last reset; `steps` counts step() calls with
1474 // the instrument armed, so every number divides down to a per-step cost.
1475 struct VofTiming {
1476 double advect = 0.0;
1477 double bridge = 0.0;
1478 double momAdvect = 0.0;
1479 double momBridge = 0.0;
1480 double curvature = 0.0;
1481 double csf = 0.0;
1482 double phaseChange = 0.0;
1483 double blockAdvect = 0.0;
1484 double blockDebris = 0.0;
1485 long steps = 0;
1486 };
1487 void setVofTiming(bool on);
1488
1489
1490 bool vofTiming() const;
1491
1492
1494
1495
1496 const VofTiming& vofTimingReport() const;
1497
1498
1500
1501
1503
1504
1509
1510
1512
1513
1514 double vofTimingStepSeconds() const;
1515
1516
1518
1519
1521
1522
1524
1525
1528 void setVofWorklist(bool on);
1529
1530
1531 bool vofWorklist() const;
1532
1533
1535
1536
1538
1539
1540 int nx() const;
1541
1542
1543 int ny() const;
1544
1545
1546 int nz() const;
1547
1548
1549
1550 private:
1551 struct Comp {
1552 CCField u, b, inhom, rscale, mask;
1553 FV AC, AW, AE, AS, AN, AB, AT;
1554 IbmOverlay ov;
1555 Kokkos::View<int*, CCMem> idMap;
1556 Kokkos::View<int, CCMem> counter;
1557 int nCut = 0;
1558 };
1559
1560 // ---- step() phases (WO-HO): contiguous blocks of step(), called once each in its order. ----
1561 // The two-phase stability checks and the configuration refusals, before the first mutator.
1562 void stepPrechecks();
1563 // VoF momentum + colour, phase change, properties, the hoisted operator build, the body-force /
1564 // drag ghosts, curvature and the porous rho_eff. Returns whether the operator build was hoisted.
1565 bool stepHeadFields();
1566 // The sharp-interface geometry and the diffusion stencil rebuild of this step.
1567 void stepStencils();
1568 // The u^n time base and the full-stress prelude. Returns fullStressActive().
1569 bool stepTimeBase();
1570 // The incremental grad(P^n) ghosts and the V8 density ghosts.
1571 void stepPressureGhosts();
1572 // The coefficient-build flag, the restart split of P and the balanced-force projection.
1573 void stepBalancedForce(bool hoisted);
1574 // Per Picard iteration: velocity ghosts, advection inputs and the porous div(u) compensation.
1575 void stepPredictorInputs();
1576 // Per Picard iteration: the momentum right-hand side. Returns colocatedFaceForce().
1577 bool stepPredictorRhs();
1578 // Per Picard iteration: the CSF and full-stress terms added to that right-hand side.
1579 void stepPredictorForces(bool coloFF, bool fullStress);
1580 // Per Picard iteration: the implicit-FOU stencil and the outflow backflow stabilization.
1581 void stepPredictorOperator();
1582 // Per Picard iteration: the advecting velocity restricted to the velocity-MG coarse levels.
1583 void stepPredictorCoarseAdvection();
1584 // Per Picard iteration: the momentum solves and the u* stash for the reaction force.
1585 void stepMomentumSolve();
1586 // Per Picard iteration: the cut-cell projection (and the porous-continuity refusal).
1587 void stepProjection();
1588 // Per Picard iteration: domain BCs re-imposed and the scalar open-face flux captured.
1589 void stepPostProjection();
1590 // After the Picard loop: colour advection, energy properties, scalars, superficial velocity.
1591 void stepTransport();
1592 // The one-time warning for reversed flow on an outflow face without backflow stabilization.
1593 void stepBackflowWarning();
1594
1595 // ---- projectCorrectVelocities() phases (WO-HO): contiguous blocks, called once each. ----
1596 // Collocated: phi's Neumann ghosts at non-periodic walls.
1597 void projectPhiWallGhosts();
1598 // Collocated: the face-field correction and its ghosts (high-side boundary faces kept).
1599 void projectCorrectFaceField();
1600 // Collocated: the high-side outflow faces of the face field.
1601 void projectCorrectFaceFieldOutflow();
1602 // Collocated: the cell-field correction of the configured scheme.
1603 void projectCorrectCellField();
1604 // Staggered: the gradient correction of the configured coefficient.
1605 void projectCorrectStaggered();
1606 // Staggered: the high-side outflow normal faces.
1607 void projectCorrectStaggeredOutflow();
1608
1609 // ---- setSolidGhostProjectionOverlay() phases (WO-HO): contiguous blocks, called once each. ----
1610 // The fragmentation guard: the inner sdf on the host (allgathered when distributed), pockets
1611 // outside the main coupled component decoupled, this rank's block returned.
1612 std::vector<double> gpPocketGuardSdf(CCField din);
1613 // The binary openness, the overlay build (+ debug report) and the MG surrogate openness.
1614 void gpBuildOverlay(CCField sdfGp);
1615
1616 // ---- pcBuildInterface() phases (WO-HO): contiguous blocks, called once each. ----
1617 // The temperature ghosts, the stale-mask refresh and the cascade interfacial area. Returns
1618 // whether the cascade area is in use.
1619 bool pcBuildInputs();
1620 // The unit refusal of the operator flux and the in-domain mask it reads.
1621 void pcOperatorDomain(bool opMode, bool opEnergy);
1622 // The ghost exchange of the interface fields, domain-face ghosts zeroed.
1623 void pcExchangeInterfaceGhosts();
1624
1625 // ---- hydroForceTorqueReaction() phase (WO-HO). ----
1626 // The refusals: collocated, the momentum terms the budget does not carry, no stashed u*/advection.
1627 void hydroReactionChecks();
1628
1629 public: // nvcc forbids extended __host__ __device__ lambdas inside private/protected members.
1630 // Advection treated implicitly (implicit-FOU upwind + deferred correction): the user opt-in
1631 // (set_implicit_advection) on any path, OR the DEFAULT on the domain-BC path (inflow/outflow),
1632 // where explicit advection is unstable. The velocity-MG BC path carries its own FOU coarse
1633 // operator, so the default does not apply there (it still honours the explicit opt-in).
1634 // Advection is implicit (first-order upwind in the stencil, stable at large dt) when the user
1635 // asks for it, and ALWAYS on the domain-BC stencil path -- which includes the mixed velocity MG
1636 // (solid + domain BCs), so switching that solver on does not silently change the momentum
1637 // discretization. The all-fluid domain-BC velocity MG (folded const-coefficient operator) keeps
1638 // explicit advection, as before.
1639 bool implicitAdv() const;
1640 // Whether the solver's OWN momentum-advection operator runs: set_advection, unless
1641 // enable_vof_momentum is on -- there the VoF fluxes already carry rho*u (buildRhsVarMom reads
1642 // uAdv_, never advRhs_), so a second advection would double-count it. Every advect_ read goes
1643 // through here. Under VoF momentum this reproduces the advection-off binary bit for bit, which
1644 // was ALSO what advection-on gave on the periodic path (probe 2026-10-23); on a domain-BC box
1645 // advection-on used to throw in advectVofMomentum.
1646 bool advectsMomentum() const { return !vofMomEnabled_ && advect_; }
1647
1648
1649 // Domain-BC momentum solved via the Robust-Scaled cut-cell / FOU stencil smoother
1650 // (ibmRbgsStencilColor
1651 // + reflection-ghost BCs), not the all-fluid const-coeff fold. Needed when (a) an immersed solid
1652 // is present (cut-cell no-slip must be in the operator), or (b) advection is implicit (the FOU
1653 // upwind lives in the stencil -> stable at large dt, the fully-implicit design), or (c) any
1654 // per-cell coefficient lives in the stencil: variable properties, or the implicit CFD-DEM drag
1655 // diagonal (hasDrag_). Without (c) an all-fluid domain-BC problem fell through to the
1656 // CONST-COEFFICIENT fold smoother (Ac = rho/dt + 6mu computed inline), which never reads the
1657 // assembled band -- the drag never entered the momentum operator while the porous projection's
1658 // w_f=idt/(idt+beta_f) assumed it did, an inconsistency with pressure-loop gain beta*dt/rho (a
1659 // fixed bed diverged whenever beta > rho/dt; measured gain 3.84 vs predicted 3.85 at beta=77,
1660 // idt=20).
1661 // Domain BCs solved with the (unfolded) cut-cell / FOU stencil and reflection ghosts, as
1662 // opposed to the folded const-coefficient smoother. Decides the RHS treatment too (the fold's
1663 // RHS correction applies only off this path), so it must agree with the solver actually used:
1664 // the MIXED velocity MG (solid + domain BCs) runs on this stencil and is therefore ON this path,
1665 // while the all-fluid domain-BC velocity MG is the folded operator and is not.
1666 bool bcStencilPath() const;
1667
1668
1669 // The mixed velocity MG: solid + domain BCs, diffusion-dominated constant-property momentum
1670 // (implicit advection / variable properties / drag stay on RB-GS: their fine stencils are not
1671 // approximated by the staircase Helmholtz).
1672 bool mixedVelocityMg() const;
1673
1674
1675 // Fill a property field's ghosts for the face means: periodic/halo base, then zero-gradient
1676 // (copy) on domain-BC (wall/inflow/outflow) faces — a periodic wrap there would bring the wrong
1677 // layer's value to the wall face (destabilising, especially for the harmonic mean).
1678 // Distributed: the override is per-face rank-OWNED (`touchesGlobalFace`), exactly as
1679 // `applyScalarBc` does — the halo fill runs first (and periodic-wraps the global boundary ghost),
1680 // the BC overwrite wins on the rank that owns the face. The former `if (!distributed_)` guard
1681 // keyed on the wrong predicate: it dropped the override at EVERY np including 1.
1682 // `edges` extends the BC copy over the tangential ghost rows (the edge/corner ghosts), for a
1683 // consumer that reads diagonal neighbours (the staggered cross-face viscosity).
1684 void fillPropGhosts(CCField f, bool edges = false);
1685
1686
1688
1689
1690 // Ghost ring of the per-cell body-force fields ("force_x/y/z") — WO-G.
1691 //
1692 // Neither writer of these fields fills their ghosts: `applyClosure` writes the INNER cells only
1693 // ("ghosts untouched — refilled by the field's own exchange", `property_closures.hpp`), and the
1694 // external CFD-DEM writer (`field_view` + `exchangeFieldAdd`) folds its ghost-band deposit onto
1695 // the owners but leaves the ghost band holding that deposit residue. Nothing else exchanged them,
1696 // so `buildRhsVar`'s face interpolation `0.5*(fb(i) + fb(i - s_c))` read the registration zero (or
1697 // the residue) on the first inner plane of every block — the face body force came out exactly
1698 // HALVED at every rank boundary, and single-rank at the periodic wrap plane. Net effect on a
1699 // periodic axis: a body-force deficit of 1/(2*N_axis) on the whole domain, because the projection
1700 // removes the non-uniform part and what survives is the (deficient) mean.
1701 //
1702 // WHY THE PROPERTY POLICY IS THE RIGHT ONE, even though a body force is not a transported
1703 // property. `buildRhsVar` face-interpolates the force with the SAME arithmetic mean it uses for
1704 // the momentum time term and the projection coefficient face-interpolate rho, and the physical
1705 // content of that pair is the acceleration f_f/rho_f (this three-way consistency is what makes
1706 // the discrete hydrostatic balance exact — `doc/variable_density_projection.md` §1/§3). Whatever
1707 // ghost policy rho has, the force must have the SAME one or the ratio breaks at a boundary. rho
1708 // uses `fillPropGhosts` (halo/periodic base, then Neumann copy on a rank-OWNED domain-BC face),
1709 // so the force does too, per BC type:
1710 // * WALL / inflow (Dirichlet). The ghost feeds only the face force of the wall-NORMAL component
1711 // ON the boundary plane — the one unknown the Dirichlet BC pins (`bcVelocityComp`, comp == a:
1712 // `at(bf) = wall`) and whose flux openness is 0. So the value is unobservable there today,
1713 // which is exactly why the hydrostatic acid test passed at 2.75e-17 with the defect present.
1714 // Neumann copy is still the right answer: it is the only choice that keeps f_f/rho_f equal to
1715 // the intended acceleration if that pin is relaxed (free-slip / stress BC), and "zero" would
1716 // assert that the volumetric source stops at the wall. A body force is a SOURCE, not a flux —
1717 // there is no reflection or odd-extension principle to invoke, only extrapolation, and the
1718 // piecewise-constant (Neumann) extrapolation is O(h), the same order as rho's own ghost.
1719 // * OUTFLOW. Zero-gradient is what every other quantity gets there, and a zero ghost would
1720 // halve the body force on the outlet face — this same defect, relocated to the outlet.
1721 // So the policy does NOT differ per BC type; `fillPropGhosts` is used verbatim.
1722 //
1723 // Consumer note: on the MAC grid EVERY RHS kernel reads the ghost -- `buildRhsForced`,
1724 // `buildRhsVar` and `buildRhsVarMom` all place the force at the face by the same
1725 // `Grid::atVelocity` mean (the constant-density kernel used to read the cell value alone, half a
1726 // cell off the face; fixed 2026-09-25). On the collocated grid the cell value is the placement and
1727 // the fill is inert -- applied unconditionally anyway, so the field's ghost contract does not
1728 // depend on which RHS kernel happens to consume it.
1730
1731
1732 // Ghost ring of the per-cell drag coefficient "drag_beta" — WO-I.
1733 //
1734 // Same defect class as the body force above, one phase earlier in the step. Under `porous_`,
1735 // `addDragDiagonal` builds the staggered momentum diagonal from the FACE drag
1736 //
1737 // beta_f(i) = 0.5*(beta(i) + beta(i - s_c))
1738 //
1739 // and all three of its call sites (`rebuildStencils`, `buildAdvStencil`, `buildAdvStencilVar`)
1740 // run at/after the TOP of `step()`. But no writer of `drag_beta` fills its ghosts: `setField` and
1741 // `applyClosure` write the inner cells only, and the external CFD-DEM writer's driver FOLDS its
1742 // ghost-band deposit onto the owners and then ZEROES that band (single rank) or leaves the
1743 // reverse-halo residue in it (MPI). The only `fillPropGhosts(dragBeta_)` used to be inside
1744 // `project()` — i.e. AFTER the momentum build. So on the first inner plane of every block the
1745 // momentum diagonal was assembled from a stale/zero ghost while the projection's coefficient
1746 // (`buildPorousCoeffDrag`/`Cons`) and its correction (`projectCorrectPorous*`) used the freshly
1747 // exchanged value on that SAME face.
1748 //
1749 // That mismatch is exactly what `addDragDiagonal`'s own comment warns about: the incremental
1750 // pressure loop then has gain (idt + beta_f)/(idt + beta_f^momentum) instead of 1, and "the
1751 // accumulated pressure diverges exponentially" — here localized to block/wrap boundaries rather
1752 // than to the bed top. With the CFD-DEM writer's zeroed ghost the momentum diagonal on that plane
1753 // carried beta/2 against the projection's beta, a factor-2 error in the drag, not round-off.
1754 //
1755 // WHY THIS CALL SITE. It is the only point that is after BOTH writers — a closure targeting
1756 // "drag_beta" (applied by `updateProperties()` immediately above) and the external deposit (which
1757 // happens before `step()` is entered) — and before the FIRST consumer, the momentum stencil build
1758 // a few lines below. Nothing inside `step()` writes `drag_beta`.
1759 //
1760 // WHY `fillPropGhosts` AND NOT SOME OTHER POLICY. There is no freedom here: `project()` already
1761 // fills this very field with `fillPropGhosts` (halo/periodic base + Neumann copy on a rank-OWNED
1762 // domain-BC face), and the whole point is that the momentum diagonal and the projection
1763 // coefficient must agree on beta_f face by face — the three-way consistency
1764 // `doc/variable_density_projection.md` §1/§3 states for (time term, body force, projection
1765 // coefficient) and `doc/porous_drag_scheme.md` §2 states for (diagonal, operator, correction).
1766 // Any policy other than the one `project()` uses would re-create the mismatch it is fixing.
1767 //
1768 // `project()`'s fill is therefore REDUNDANT after this one (nothing writes `drag_beta` in
1769 // between). It is kept deliberately: removing it is a separate change, `project()` must keep its
1770 // own ghost contract for any future mid-step writer, and it costs one exchange on the porous path
1771 // only.
1772 //
1773 // Gated on `hasDrag_` (the field exists iff `enableDrag()` ran), not on `porous_`: the field's
1774 // ghost contract should not depend on which consumer happens to read it. Since 2026-09-25
1775 // `addDragDiagonal` takes the face mean on the MAC grid on the non-porous path too, so the fill
1776 // is live there as well; it is inert only on the collocated grid (cell value).
1778
1779
1780 // Eps ghost policy for the porous (volume-averaged) machinery. Periodic/halo base fill, then at
1781 // non-periodic domain faces: wall -> zero-gradient; INFLOW/OUTFLOW -> mirror around 1 so the
1782 // arithmetic face mean is EXACTLY 1 (the boundary is pure gas: below the distributor and in the
1783 // freeboard eps = 1, so a prescribed inflow velocity is the SUPERFICIAL gas velocity and its face
1784 // flux is open_f*1*u — the Kuipers/MFIX distributor convention). Every consumer — the projection
1785 // RHS divergence, the Poisson coefficients, and maxPorousResidual — must use THIS fill: the
1786 // external deposit writes its own leakage into these ghosts each step, and any two consumers
1787 // reading different ghost values enforce two different constraints, which leaves an irreducible
1788 // residual (eps_f_rhs - eps_f_resid)*u_in pinned at the distributor row and feeds gas at
1789 // eps_f*U instead of U.
1791
1792
1793 // --- VoF internals (rung V2a, WO-J) ---------------------------------------------------------
1794 // Allocate the colour field's own g=3 working block and wire its ghost/all-reduce hooks. Called
1795 // by enableVof() and again by any path that re-sizes the block (redistribute -> initMpi), since
1796 // the advector's block must track the solver's.
1798
1799
1800 // --- rung V5a (WO-Q): the cut-cell geometry of the colour block ------------------------------
1801 //
1802 // The advector needs, on ITS g=3 block and in ITS high-face index convention, the face openness
1803 // `o_d` and the cell fluid fraction `eps`. Both are built here and both are then run through the
1804 // colour field's OWN ghost policy (`vofFillGhosts`), which is what makes the classification at
1805 // the outermost ghost layer the owner's classification rather than a locally-guessed one — the
1806 // solid-band fill of `cutcell.hpp` reads fluid neighbours at ghost depth 3, so a wrong
1807 // classification there would be a decomposition dependence in the INNER result.
1808 //
1809 // `eps` comes from `buildCellFraction` (mac_approx_projection.hpp: 4^3-subsampled trilinear SDF),
1810 // which the collocated path already uses for `cs_`. `cs_` is allocated only on the collocated
1811 // grid, so the staggered path gets its own `vofCs_` here.
1812 //
1813 // The openness embed is `vof::copyFaceVelocity`, i.e. THE SAME shifted embed the face velocity
1814 // uses — because it is the same face. `ox_(i)` is the openness of the `-x` face of cell `i` and
1815 // the advector wants the `+x` face of cell `i`, exactly the low-face -> high-face shift of
1816 // `colour_field.hpp`. Using a concentric embed here instead is the openness twin of WO-J's 35 %
1817 // conservation defect and is what gate G3 exists to catch.
1818 // ISSUES sweep item 3. Which domain faces are WETTING WALLS for the colour band fill: a
1819 // type-1 no-slip or type-4 free-slip face, i.e. an impermeable one, and only while a contact
1820 // angle is actually set. Returned as a per-face bitmask (bit 2a+s), 0 when the feature is unused
1821 // -- which is what keeps every existing path byte-identical.
1822 //
1823 // A domain wall IS a flat SDF wall sitting exactly on the boundary face; the only reason
1824 // `set_contact_angle` used to be silently ignored there is that the band fill classifies cells
1825 // from the colour block's cut-cell GEOMETRY, and an all-fluid solver has none. So the repair is
1826 // not a new fill rule -- it is a SYNTHESISED geometry for those faces (`applyDomainWallGeometry`)
1827 // plus the matching wall SDF (`applyContactAngle`), after which WO-S's theta pass, WO-Q's
1828 // passes 2-3, the branch census and the V6 dynamic angle all run unchanged, with `n_w` coming
1829 // out of the same central difference and equalling the inward face normal by construction.
1830 int vofWetWallMask() const;
1831
1832
1833 // Signed distance (cell units, POSITIVE inside the domain) from a cell centre at GLOBAL index
1834 // (gx,gy,gz) to the nearest wetting domain wall plane. Container-free so a device lambda can
1835 // call it. `+inf` when no face is a wetting wall.
1836 KOKKOS_INLINE_FUNCTION static double vofWallPlaneSdf(int gx, int gy, int gz, I3 gs, int mask);
1837
1838
1840
1841
1842 // ISSUES sweep item 3: close the colour block's out-of-domain band across every wetting domain
1843 // wall, so `classifyGeometry` calls those ghost cells SOLID and WO-S's theta pass owns them.
1844 //
1845 // The rule is the one the SDF path uses, evaluated on an exact plane: a cell whose centre lies
1846 // outside the wall has fluid fraction 0, and a face is open only if BOTH of its cells are
1847 // inside. That closes the boundary face itself (which the flux openness already closes, so
1848 // nothing in the projection moves) AND all six faces of every band cell, which is what
1849 // `vofIsSolidCell` requires. Composes with an SDF solid: the solid's eps/openness are simply
1850 // masked to zero outside the wall.
1852
1853
1854 // ISSUES sweep item 3: mark the out-of-domain band SOLID after the classification exchange
1855 // (see the call site for why the exchange undoes it).
1856 void imposeDomainWallKind(int mask);
1857
1858
1859 // ISSUES sweep item 3: the outermost (depth-3) band layer of a wetting DOMAIN wall is the one
1860 // cell no fill pass can write -- the passes stop at ghost depth 3-k and their 6-point stencil
1861 // would index outside the g=3 block there -- and the zero-gradient clamp that used to supply it
1862 // is now skipped (it would wipe the theta band). Continue the band outward instead: depth 3
1863 // takes depth 2's value, the zero-slope continuation of the theta plane rather than of the first
1864 // INNER cell's colour. For an SDF wall this cell is an ordinary solid cell and nothing here
1865 // applies.
1866 void vofExtendWallBand(CCField f, int mask);
1867
1868
1869 // Zero the canonical G=2 colour field inside solid cells (see buildVofGeometry).
1871
1872
1873 // Is axis `a` periodic for the colour field? flow's per-face bc_ is 0 (periodic) on BOTH ends of
1874 // a periodic axis, so an axis is periodic iff neither of its faces carries a domain BC.
1875 bool vofAxisPeriodic(int a) const;
1876
1877
1878 // The colour field's ghost policy on its own g=3 block: halo/periodic base, then zero-gradient
1879 // (globally clamped) on every non-periodic axis. Zero-gradient is the same policy the material
1880 // properties get (`fillPropGhosts`) — a wall neither creates nor destroys colour, and the MYC
1881 // stencil of an inner boundary cell must see a plausible continuation rather than a wrap from the
1882 // far side of the domain. Prescribing C at an inflow face is a V5+ concern (it needs a flux BC,
1883 // not a ghost value) and is not offered here.
1885
1886
1888
1889
1891
1892
1893 // Global index of this block's inner cell (0,0,0). og_ is exactly that (originInclGhost + G).
1894 I3 vofOrigin() const;
1895
1896
1897 // Face velocities -> the advector's g=3 block. The advecting field must be the PROJECTED one
1898 // (see advectVof), and its ghost ring must be valid because the advector reads the `-d` face of
1899 // the first inner cell, which is a ghost cell's `+d` face. fillVelGhosts is the solver's own
1900 // halo+domain-BC fill and is exactly what the Picard loop does at the top of every iteration, so
1901 // calling it here leaves the velocity ghosts in the state the next consumer would have produced.
1903
1904
1905 // --- rung W0: the block container's view of this rank's patch --------------------------------
1906 // The owned inner box of every rank, in global cells — the table the block gather/scatter pieces
1907 // are cut against. It is a function of the CURRENT decomposition, so it is built here rather
1908 // than inlined at `enable_vof_blocks`: a redistribute has to push the new one through
1909 // `bindVofBlockPatch` or every piece keeps addressing the previous partition.
1910 std::vector<vof::VofBox> vofBlockRankBoxes(int size) const;
1911
1912
1913 // The gather reads the face velocity in the ADVECTOR's high-face convention on the g=3 block,
1914 // i.e. exactly what `bridgeVelocityToVof` writes, and the scatter writes the union into that
1915 // same block's colour. `buildVofBlock` reallocates those Views, so the binding is refreshed
1916 // there — a stale View here would silently gather from freed memory.
1918
1919
1920 // The union colour on the g=3 block -> the canonical registered "C" (+ its ghost policy, the
1921 // same `fillPropGhosts` rho and mu are derived through).
1923
1924
1925
1926 // Colour: G=2 registry mirror -> the g=3 working block, then the colour field's own ghost policy.
1927 // Inner cells only in the copy — the two blocks have different ghost extents and each fills its
1928 // own (the one bridge; see the enableVof note).
1930
1931
1932
1933 // Staggered face stride of velocity component c (the -c face of cell i pairs cells i and i-s).
1934 long strideOf(int c) const;
1935
1936
1937 // The face-property accessor for the momentum stencil of component c: mu constant-or-field
1938 // (arithmetic/harmonic mean), rho constant-or-field (arithmetic face mean for the time diagonal —
1939 // the same face density the variable-density projection uses).
1940 // Effective variable density: true varRho, or the eps-conservative porous momentum (rho_eff =
1941 // eps*rho in epsRho_, refreshed per step by updateEpsRho).
1942 bool effVarRho() const;
1943
1944
1946
1947
1948 // --- rung V8: the collocated variable-density / CSF path ---------------------------------------
1949 //
1950 // TRUE exactly on the configurations that used to throw outright on this grid — variable density
1951 // (`set_density_mode`) and surface tension (which needs `enable_vof`) on `SolverColocated` — so
1952 // every validated collocated path (constant density, no VoF: `benchmarks/staggered-vs-collocated`,
1953 // the colocated regression baselines) and the whole staggered solver take the same branches they
1954 // always did, byte for byte.
1955 //
1956 // When it is on, the step is the mass-adjoint ABC pair of doc/collocated_varrho_forces.md: the
1957 // pressure and every force inside the implicit predictor (`buildRhsColoVar`), the momentum-weighted
1958 // centre-to-face map in the constraint, and the face-to-cell reconstruction of the face correction
1959 // as the cell correction — see `collocated_varrho.hpp`.
1961
1962
1963 // The AUTO collocated scheme (set in setSolid/setPressureGeometry) picks the GHOST projection when
1964 // the configuration allows it, and the ghost v1 supports neither variable density nor the V8 face
1965 // force. `set_density_mode` / `enable_vof` can be called AFTER the geometry, so re-run the same
1966 // fallback here rather than failing later inside project(). An explicit scheme selection has
1967 // already cleared colSchemeAuto_ and is left alone (it will hit the loud throw instead).
1968 void collocatedV8AutoFallback(const char* why);
1969
1970
1972
1973
1974 // Guard rail for rung V8's scope. The collocated variable-density / face-force path is validated
1975 // ALL-FLUID (`set_pressure_geometry`); an immersed solid on it would need the cut-cell face
1976 // acceleration AND the one-sided (gauge-exact / ghost) closures to agree with the face averaging
1977 // operator, which is a separate derivation. Fail loudly instead of half-supporting it.
1978 void requireCollocatedFaceForceScope(const char* who);
1979
1980
1981 // --- the balanced-force projection (doc/collocated_varrho_forces.md §4.6) --------------------
1982 // Is it on for this step? (the explicit setting, else ON exactly on the V8 path without an
1983 // inflow/outflow face)
1985 // X (doc/vof_gpu_coarse_tail_design.md §5.6): build the variable-rho pressure coefficients right
1986 // after updateProperties() and factor the device direct bottom on a side instance, hidden behind
1987 // the momentum stage. Variable rho, not porous, one outer iteration, no balanced-force stage, a
1988 // PCG/FCG driver, and the MG's own eligibility (single-rank device direct bottom).
1990 // Diagnostics tier (tests): switch the X hoist off (default on) -- the pre-X path, coefficients
1991 // built in project() and the bottom factor lazily in the bottom solve; bitwise the same state.
1992 void setPressurePrefactorHoist(bool on) { prefactorHoist_ = on; }
1993 bool pressurePrefactorHoist() const { return prefactorHoist_; }
1994 // Side-instance bottom factors launched by the X hoist so far.
1996 bool hasOpenDomainFace() const; // any inflow (2) / outflow (3) domain face
1997 // The §4.6.4 refusals. `atStep` adds the checks that are only final once the solver is set up
1998 // (the cut-cell operator, the collocated density path, an AUTO-selected ghost scheme).
1999 void requireBalancedForceScope(const char* who, bool atStep) const;
2000 // (B2) faceAcc_[c] = c * beta on the face range [G, e-G] (no openness: the divergence applies it).
2002 // Register "p_balanced" (zero) as soon as the option is active, so a restart can restore it
2003 // with set_field before the first step. Called by every setter that can switch it on.
2005 // B1-B5, once per step before the Picard loop.
2007 // (B4) the increment solve with the full-RHS stop (WO-P5); pb1_ in/out, rhs1_ the RHS; r0 its
2008 // initial residual (the divergence test of the kept Chebyshev bounds).
2009 long solveBalancedForceSystem(double bref, double r0);
2010
2011
2013
2014
2016
2017 // FULL VISCOUS STRESS (doc/full_viscous_stress.md). With variable mu the momentum predictor
2018 // gains the transpose term T = div(mu (grad u)^T), explicit on the time base u^n (`old_`), as
2019 // conservative MAC stress elements with the Laplacian bands' own beta (src/full_stress.hpp).
2020 // `set_viscous_stress("auto" | "full" | "laplacian")`; default "auto" (WO-7, USER 2026-10-23):
2021 // resolved at each step head to full on the staggered grid when mu is variable, arithmetic, not
2022 // porous, not moving and free of immersed solids (review B1), else to laplacian with a one-time stderr notice. Raises on
2023 // SolverColocated for an explicit "full" (planned, §9).
2024 void setViscousStress(const std::string& form);
2025 // (explicit full || AUTO resolved full) && varProps_ && staggered: the term is evaluated this
2026 // step (constant mu: inactive, no error -- the term is identically zero).
2027 bool fullStressActive() const;
2028 // WO-7: the AUTO resolution at the head of step() (sets fullStressAuto_; notice on fallback).
2030 // §5.6 refusals (harmonic face mu, porous momentum, moving scene instances), raised at the head
2031 // of step() when "full" is requested under variable mu, before the first mutator.
2032 void requireFullStressScope(const char* who) const;
2033 // §4.3 prelude, once per step right after old_ = u^n: mu ghosts on the implicit-FOU path, the
2034 // exact global uniformity test (muUniform_), the u^n ghosts incl. edges, the regular-node masks.
2036 // §4.3: rs_c * T_c(u^n) added to C[c].b, after the CSF, in every Picard iteration.
2038 // §5.4: reg_c = not solid and not a cut row, ghosts by the property-ghost fill incl. edges.
2040
2041 // SHARP VISCOUS INTERFACE (doc/vof_sharp_viscous_stress.md, src/vof/sharp_viscous.hpp). Under
2042 // VoF with mu = LinearMix(C) and the full stress: band edges take the PLIC face-fraction mu of
2043 // the row's own face in the implicit bands and the explicit transpose, plus the interface-
2044 // traction (tau) terms and the cell midsection term, all explicit on u^n; tau_hat / D_nn from a
2045 // kinked least-squares fit per interfacial cell. `set_vof_viscous_interface("auto" | "sharp" |
2046 // "averaged")`, default "auto" (USER 2026-11-04, note §9): resolved at each step head to sharp
2047 // when VoF is on, mu = LinearMix(C) varies, the full stress is active and there are no immersed
2048 // solids, porous momentum, moving scene instances or phase change; else to "averaged" (= the
2049 // operator before the sharp interface, bitwise) with a one-time stderr notice. SolverColocated
2050 // stays "averaged" (§8); an explicit "sharp" raises there and outside the v1 scope.
2051 void setVofViscousInterface(const std::string& mode);
2052 std::string vofViscousInterface() const;
2053 // Step head, after the viscous-stress resolution: sharpActive_ for this step. AUTO falls back
2054 // with the one-time notice; an explicit "sharp" outside the v1 scope (§1, §9) raises here,
2055 // before the first mutator.
2057 // After updateProperties()/updateVofCurvature(), before the momentum bands are built: the PLIC
2058 // planes of the current colour (reconstructed here unless the curvature cascade just did) and
2059 // the band classes (§5.2, §7, Q9).
2061 // After fullStressPrelude(): the tau_hat / D_nn fit on u^n over the owned cells, then their ghost
2062 // exchange (§7). Skipped when mu is globally uniform.
2064 // The component-c face props of the sharp interface for one half of the split (§6.1, WO-5b).
2066 // The band census of the last step (§9), LOCAL to this rank: interfacial cells, virtual-plane
2067 // cells, film cells among those, fit fallbacks. Zero while the sharp interface is inactive.
2069 // The last step's fit (§5.3), LOCAL inner block, x-fastest: tau_hat x/y/z and D_nn (internal
2070 // units) and the fallback flag as 0/1. All five empty while the sharp interface is inactive.
2071 std::array<std::vector<double>, 5> vofViscousInterfaceFit();
2072 // The sharp interface's per-step state and the u^n base, by view (the operator-level MPI ctest
2073 // sharp_viscous_mpi drives the step's pieces one by one and reads these back).
2079 SharpViscousState sharpViscousState() const {
2080 return SharpViscousState{svCls_, svFb_, {svTau_[0], svTau_[1], svTau_[2]}, svDnn_,
2081 {old_[0], old_[1], old_[2]}, sharpGeom_};
2082 }
2083
2084
2085 // Mirror the host motion arrays onto the device (KBs; rebuilt only when a driver changes a
2086 // body's velocity, not per step).
2088
2089
2090
2092
2093
2094
2096
2097
2098
2099 peclet::core::geom::InstanceMotionView<double> motionView() const;
2100
2101
2102
2103 // MOVING GEOMETRY (Layer 3 rungs 2-3): sample the scene's KINEMATIC WALL VELOCITY onto the grid.
2104 //
2105 // At each probe p (component c's staggered point for rung 2; the cell centre for rung 3):
2106 // n_hat = central difference of the SAMPLED sdf_, normalised -- O(h), the v1 fidelity
2107 // w = p - sdf(p) * n_hat -- core's geom::wallPoint
2108 // u_w = geom::instanceVelocity(owner(p), w)
2109 //
2110 // THE OWNER IS QUERIED AT p, not read from the cell-centred cutOwner_ field. At a contact
2111 // between two bodies the staggered point and the cell centre can belong to different ones, and
2112 // a wall velocity taken from the wrong body is precisely the error this rung exists to avoid.
2113 //
2114 // Per-direction crossing-point placement (via tEx_) would put the wall point on the exact
2115 // crossing instead of along the gradient; that is the documented refinement, deliberately not
2116 // taken in v1 -- see the design note.
2118
2119
2120
2126
2127
2128
2129 // MOVING GEOMETRY rung 3: the wall's own volume flux, folded into the cell divergence.
2130 //
2131 // A rigid body sweeping through a cut cell injects a net flux through the WALL part of the
2132 // cell's fluid boundary; it is zero only integrally over a closed body, never cell by cell.
2133 // The wall area VECTOR is exact from the aperture identity -- apply the divergence theorem to
2134 // the constant field e_a over the cell's fluid region and the open-face terms telescope:
2135 // A_wall = -(oE - oW, oN - oS, oT - oB) (in h=1 cell units, matching divergOpen)
2136 // so continuity over the fluid region reads div_open(u) + u_w . A_wall = 0. divergOpen has
2137 // already written the first term into `d`; this adds the second, leaving rhs = -(d) untouched
2138 // in form. Inert unless a moving instance exists.
2140
2141
2142
2169 void scaleForceTorque(std::vector<double>& out, std::size_t m) const;
2170
2171
2172
2185 std::vector<double> hydroForceTorque();
2186
2187
2188
2283 std::vector<double> hydroForceTorqueReaction();
2284
2285
2286
2289 std::array<long, 3> fluidMomentumCells();
2290
2291
2292
2306 std::vector<double> reactionBudgetTerms();
2307
2308
2309
2318 std::array<double, 3> wallAreaProbe();
2319
2320
2321
2327
2328
2329
2330 // Empty when the geometry is static -> ibmModifyStencil takes its scalar u_bc path, unchanged.
2331 CCConst wallVelView(int c) const;
2332
2333
2334
2336
2337
2338 // copy the nx*ny*nz inner cells between two extended blocks of different ghost width (g=2 <-> g=1
2339 // MG).
2340 void copyInner(CCField dst, C3 de, int dg, CCConst src, C3 se, int sg);
2341
2342
2343 // Copy the ENTIRE destination block (including its ghost ring) from the source block at per-axis
2344 // cell offset `off`: dst(x,y,z) <- src(x+off, y+off, z+off). Bridges a G=2 field to the g=1 MG
2345 // block INCLUDING the g=1 ghosts (off = G-1), so face means at the first inner cell read a valid
2346 // neighbour. Requires the source ghosts filled (fillGhosts/fillPropGhosts) — under MPI those are
2347 // the cross-rank values, so the bridge is decomposition-correct.
2348 void copyBlockShifted(CCField dst, C3 de, CCConst src, C3 se, int off);
2349
2350
2351 // Fill ghost width G periodically on all 3 axes (x then y then z, covering corners). Distributed:
2352 // the velocity-block halo (cross-rank + periodic, all ghosts incl. corners).
2354
2355
2356 // Fused periodic FACE-ghost fill in ONE kernel (vs 3 fillAxis): each inner boundary cell scatters
2357 // its periodic image to the opposite face ghost, all 3 axes at once. Valid only for
2358 // FACE-neighbour (7-point) stencils -- it does NOT fill the corner/edge ghosts (which fillAxis's
2359 // sequential x->y->z does). The IBM RB-GS smoother reads only the 7-point stencil, so this is
2360 // exact there and cuts the velocity solve's dominant kernel-launch cost (~7200 -> ~2400 fill
2361 // launches/step) at low resolution. NOT for the Koren advection RHS (reads diagonals) -- keep the
2362 // full fillGhosts there.
2364
2365
2366 void fillAxis(CCField f, int axis);
2367 // §14 H-3(d): the single-rank periodic fill of the axes in `axes` (bit a = axis a) in ONE launch
2368 // over their ghost slabs -- bit-identical to fillAxis on those axes in ascending order (see the
2369 // definition). Falls back to the sequential passes when a periodic axis is shorter than G.
2370 void fillPeriodicAxes(CCField f, int axes);
2371 // The single-rank fill of the domain's periodic axes (both faces periodic): fillPeriodicAxes when
2372 // two or three are periodic, fillAxis when one is -- bit-identical to fillAxis per periodic axis in
2373 // ascending order.
2375
2376
2377 // Cell divergence of the current velocity iterate, on the inner cells + one ghost ring (the RHS
2378 // compensation reads div at i and i-strd, so faces at the low inner boundary need the ghost-cell
2379 // value; velocity ghosts were just filled). Porous-only scratch (divAdv_).
2381
2382
2383
2388 // --- A0: wall-aware advection inputs (advective cut-wall flux) -------------------------------
2389 //
2390 // The momentum advection kernels (`sadv::advect / advect_sou / advect_fou / fou_operator`) are
2391 // geometry-blind: `adv_vel` averages the solid-masked rows into the advecting face velocity and
2392 // the SOU/Koren `PHI` stencils read the advected field up to 2 cells INSIDE the solid.
2393 // `maskVelocity` pins those rows to 0.0, which IS the wall velocity for a STATIC wall -- so a
2394 // static scene only carries the O(h) aperture defect (D2, docs/ANALYTIC_SDF_GEOMETRY.md §7 item
2395 // 8, measured -0.4..-1% on the 4-sphere bed). For a body moving at u_wall the advective term
2396 // near the body is wrong by O(u_wall): an O(1) local error in exactly the term that produces the
2397 // finite-Re screening of the confined wall correction (D1). This is the same defect family the
2398 // fresh-cell seed closed for the TIME term (seedFreshCells); the advective term never got it.
2399 //
2400 // The fix does NOT touch the global mask convention -- the masked zeros are load-bearing for the
2401 // viscous/pressure operators and for the reaction budget's telescoping. Instead the advection
2402 // gets its own input: a copy of u whose masked rows hold `uBc_`, the local rigid-body wall
2403 // velocity `v_inst + omega_inst x r` that `buildWallVelocity` already evaluates at component c's
2404 // staggered points over the WHOLE extended block (ghosts included -- the scene is analytic, so
2405 // ghost solid rows are computable pointwise and no extra exchange is needed).
2406 //
2407 // Both the explicit path (buildRhs / buildRhsForced / buildRhsVar) and the implicit-FOU stencil
2408 // path (buildAdvStencil / buildAdvStencilVar) read these views, or the deferred correction
2409 // rho*(aF - aK) would be assembled from two different velocity fields. The advRhs_ stash (the
2410 // reaction budget's R0 term) therefore carries the corrected term automatically.
2411 //
2412 // The fluid rows are the current Picard iterate u^k, so the COPY is per Picard iteration; the
2413 // WALL rows come from uBc_, which depends only on instance motion and is built once per
2414 // geometry/motion update.
2415 //
2416 // ABLATION: `set_advection_wall_velocity(False)` restores the pre-A0 behaviour (masked zeros in
2417 // the advection inputs) -- the instrument that differences "zeros vs wall velocity in the
2418 // advective term" directly. Everything else on the moving path is untouched by it.
2419 bool advWallInputs() const;
2420
2421
2423
2424
2427 CCConst advVelView(int c) const;
2428
2429
2433 CCConst advFaceView(int c) const;
2434
2435
2440 CCConst openFaceView(int c) const;
2441
2442
2463
2464
2470 bool ufAdvVelocity() const;
2471
2472
2473
2474 bool ensureAdvStash(int c, bool adv);
2475
2476
2477
2478 void buildRhs(int c);
2479
2480
2481 // Sibling of buildRhs adding a per-cell body force (Boussinesq buoyancy / CFD-DEM feedback): the
2482 // constant fc becomes fc + Grid::atVelocity(fb) -- the force at the unknown's location, the face
2483 // mean 1/2(fb(i)+fb(i-s_c)) on the MAC grid and fb(i) collocated (never chosen by the density
2484 // model: buildRhsVar uses the same rule). Kept as a separate kernel so buildRhs stays
2485 // byte-identical (no codegen drift on the single-phase path). Selected in step() when
2486 // hasCellForce_.
2487 void buildRhsForced(int c);
2488
2489
2490 // Variable-density RHS (sibling of buildRhsForced): the time term, the advection weight, and the
2491 // per-cell body force all use the FACE density of component c (arithmetic mean over the staggered
2492 // face, matching VarFaceProps::idiag and the projection coefficient — this three-way consistency
2493 // is what makes discrete hydrostatic balance exact). The cell force fb is face-interpolated for
2494 // the same reason (a rho*g cell field becomes rho_face*g at the velocity location). Requires the
2495 // rho ghosts filled (rebuildStencils / buildAdvStencilVar did it this step).
2496 void buildRhsVar(int c);
2497
2498
2499 // Momentum-consistent sibling of buildRhsVar (rung V2b, WO-K). The validated `buildRhsVar` is not
2500 // touched; this one differs in exactly one term and drops one.
2501 //
2502 // buildRhsVar : rho_f/dt * u^n - rho_f * adv(u^k) (+ implicit-FOU deferred correction)
2503 // this : rho_f/dt * u^adv
2504 //
2505 // `u^adv` is `(rho^c u_c)/rho^c` after the geometric advection that shared its fluxes with the
2506 // colour field, so it already contains BOTH the time base and the advection — the Koren/SOU term
2507 // and the deferred correction are not merely unnecessary here, adding them would advect the
2508 // momentum twice. Everything else (the incremental -grad(P^n), the face body force, the domain-BC
2509 // inhomogeneity, the cut-cell rescale) is verbatim, and `rho_f` is the SAME arithmetic face mean
2510 // the projection coefficient and the face body force use — the three-way consistency that makes
2511 // hydrostatic balance exact is untouched (see the enableVofMomentum note).
2512 void buildRhsVarMom(int c);
2513
2514
2515
2516 // --- rung V8: the collocated variable-density / CSF predictor ----------------------------------
2517 //
2518 // SIBLING of buildRhsVar, reached only when `colocatedFaceForce()` — i.e. only on `SolverColocated`
2519 // with variable density and/or surface tension (doc/collocated_varrho_forces.md §4.2, S5-S6):
2520 //
2521 // b = rs [ (rho_c/dt) u^n - rho_c aK + rho_c aF + W f_c + rho_c R(Phi) ] + (bc fold | -inhom)
2522 //
2523 // * the density weight of the time term and of the advection is the CELL density `rho(i)`: the
2524 // collocated velocity unknown IS the cell (`Grid::offset(c) == 0`), and this is the same
2525 // placement `VarFaceProps::idiag` uses for the operator diagonal;
2526 // * the pressure, the CSF and the uniform drive `set_body_force` (a mean pressure gradient) enter
2527 // as the face accelerations Phi = (f_const + CSF - w G_f P)/rho_f reconstructed at the cell,
2528 // R(Phi) = ½(o_lo Phi_lo + o_hi Phi_hi) (`varrho::cellFromFaces`);
2529 // * a per-cell force enters at the cell value times the reconstruction's weight sum W
2530 // (`varrho::weightSum`, the same two openness reads).
2531 //
2532 // What survives verbatim from the other builders: the cut-cell rescale `rs`, the domain-BC fold /
2533 // IBM inhomogeneity, the Koren/SOU advection and its implicit-FOU deferred correction. The WHY
2534 // (and the retired face-acceleration form it replaces) is the comment at the definition.
2535 void buildRhsColoVar(int c);
2536
2537
2538
2539 // --- balanced-force CSF (rung V4, WO-P) ------------------------------------------------------
2540 //
2541 // ADDITIVE to whichever RHS builder just ran (`buildRhs` / `buildRhsForced` / `buildRhsVar` /
2542 // `buildRhsVarMom`), because the force is independent of which time term and which advection form
2543 // the configuration selected — and because those four are validated kernel bodies (hard rule 1).
2544 // It is applied at the same point in the RHS as the incremental `-(P(i) - P(i - s_c))` and
2545 // carries the same `rs(i)` cut-cell rescale every other RHS term carries.
2546 //
2547 // WHY NOT THROUGH THE PER-CELL FORCE FIELD. `cellForce_` is the natural conduit for a body force
2548 // and its ghosts are sound since WO-G, but its face rule is the ARITHMETIC INTERPOLATION
2549 // `½(f(i) + f(i - s_c))` of a cell-centred force. That rule is exactly right for `ρg` (the pair
2550 // `f_f/ρ_f` is then the intended acceleration) and exactly wrong for `σκ∇C`: an interpolated
2551 // cell-centred `σκ∇C` is not in the range of the discrete gradient operator the projection
2552 // inverts, so the projection cannot annihilate it and the residue is the classical spurious
2553 // current. The face value here is instead formed BY the projection's own operator — the same
2554 // difference `C(i) - C(i - s_c)` that `projectCorrectVar` applies to φ and `buildRhsVar` applies
2555 // to P. See `vof/surface_tension.hpp` for the full argument; the stationary-droplet gate is what
2556 // measures it, and it fails loudly on any other choice.
2557 //
2558 // `sigmaCsf_ == 0` (the default) never reaches here: `csfActive()` gates the call site, so every
2559 // non-VoF path is byte-identical.
2560 //
2561 // `dst` receives the force (`C[c].b` in the predictor); `rowScaled` multiplies it by the cut-cell
2562 // row rescale `rs(i)` (true in the predictor, false for the balanced-force projection's face
2563 // force, doc/collocated_varrho_forces.md §4.6.2 B2, where `rs` multiplies the whole row and is not
2564 // part of the force). `faceRange` widens the kernel from the inner cells `[G, e-G)` to the face
2565 // range `[G, e-G]` the constraint divergence reads.
2566 void addCsfRhs(int c, CCField dst, bool rowScaled, bool faceRange = false);
2567
2568
2569 // ABLATION (`set_csf_mode(1)`): the same physics discretized the OTHER plausible way — a
2570 // cell-centred force `f(j) = sigma*kappa(j)*(C(j+s) - C(j-s))/2h` interpolated to the face with
2571 // the arithmetic mean `1/2 (f(i) + f(i-s))`, exactly as the per-cell body-force machinery would
2572 // carry a `rho*g` field. It is consistent, it converges, and it is WRONG for surface tension: the
2573 // face value is no longer in the range of the projection's discrete gradient, so the projection
2574 // cannot annihilate it. This kernel exists so the difference is a measured number in the ctest
2575 // rather than an argument — the same role the harmonic-rho_f ablation plays for WO-J's
2576 // hydrostatic gate. NEVER a production path. Arguments as `addCsfRhs`.
2577 void addCsfRhsCellInterp(int c, CCField dst, bool rowScaled, bool faceRange = false);
2578
2579
2580 // --- rung W2 (WO-W12): the BLOCK CSF, a sibling of `addCsfRhs` ------------------------------
2581 //
2582 // Same force, same place in the RHS, same `rs(i)` cut-cell rescale — but the face value was
2583 // formed ON THE BLOCKS (each marker's own curvature cascade on its own dense box, the same
2584 // `csfFaceCurvature` + `csfFaceForce` pair this file's `addCsfRhs` applies to the global field)
2585 // and scattered into `csfBlkF_` with UNPACK_SUM, so two markers whose bands overlap ADD their
2586 // forces instead of one of them being lost to the union's `max`. This is TBFsolver's
2587 // `VOF.f90::computeSurfaceTension` structure (block `stx/sty/stz` -> `boxes_2_grid_vf(...,
2588 // UNPACK_SUM)`), on the suite's own kernels.
2589 //
2590 // WHY THE FORCE AND NOT THE CURVATURE IS SCATTERED. kappa is not additive and the union colour
2591 // is a `max`, so a face between two overlapping markers has no single (kappa, dC) pair to build
2592 // a force from; the force is the additive quantity, and forming it where the marker's own colour
2593 // still exists is the only place the balanced-force pairing (the SAME face difference the
2594 // projection's gradient uses) is available per marker.
2595 //
2596 // Gated on `vofBlockCsf()`, which is false whenever the block container is absent.
2597 void addCsfRhsBlocks(int c);
2598
2599
2600
2601 // Census of the CSF face force over this rank's inner region, on the CURRENT colour + curvature
2602 // fields: the max |F| per component, and the number of ORPHAN faces — faces across which the
2603 // colour jumps by more than the wisp threshold but neither cell carries a curvature estimate, so
2604 // the force was silently dropped. An orphan is a defect (Basilisk's "this should not happen"); it
2605 // is counted rather than hidden.
2606 //
2607 // The threshold matters: the FORCE is applied at every face with `dC != 0` exactly (dropping the
2608 // round-off jumps would itself break the discrete-gradient identity by O(sigma*kappa*eps), which
2609 // is 1e-9 and would be visible in the machine-zero gate), but a face whose colour jump is 1e-30
2610 // is not a missing interface and counting it as one would bury the real thing.
2612 double maxForce[3] = {0.0, 0.0, 0.0};
2613 long orphanFaces[3] = {0, 0, 0};
2614 long forcedFaces[3] = {0, 0, 0};
2615 };
2616 CsfDiagnostics csfDiagnostics();
2617
2618
2619
2620 // Implicit-FOU velocity stencil (CUDA build_adv_stencil_k + ibm_modify_stencil): backward-Euler
2621 // diffusion (idiag+6beta diag, -beta off) + rho*FOU(u^k) upwind operator (diagonally dominant ->
2622 // stable at high Re), then the Robust-Scaled cut-cell bake. The advecting velocity u^k = the
2623 // current C[*].u (ghosts filled).
2624 void buildAdvStencil(int c);
2625
2626
2627 // Variable-property sibling of buildAdvStencil: VarFaceProps diffusion build (per-face mu, face-
2628 // density time diagonal) + the FOU upwind weighted by the FACE density (constant path:
2629 // fouw=rho_). Separate kernel so the validated buildAdvStencil stays byte-identical.
2631
2632
2633 // Backflow stabilization (Bazilevs 2009 / Esmaily-Moghadam 2011) for the NORMAL momentum at
2634 // outflow faces: add the dissipative diagonal term beta*rho*|min(u.n,0)| where the outflow
2635 // reverses (fluid re-entering, u.n<0). This removes the spurious kinetic-energy influx that the
2636 // do-nothing/zero- gradient outflow advects in -- the "backflow divergence" that blows up
2637 // separated flows (e.g. the BFS recirculation reaching the outlet), worse on finer grids. Purely
2638 // dissipative (u_ext=0), so it is implicit + unconditionally stable, and INERT where the outlet
2639 // is outgoing (u.n>=0) -> the channel and any non-reversing outflow stay byte-identical. Applied
2640 // to C[c].AC after buildAdvStencil (per Picard iteration, lagged at u^k); only the component
2641 // normal to each outflow face.
2643
2644
2645 // max|a-b| over inner cells (Picard outer-tolerance check).
2647
2648
2649 // Shared momentum RB-GS loop: fixed velIters_ sweeps, or (velTol_ > 0) the tolerance stop —
2650 // colour 0 plain, colour 1 via the fused max-increment kernel, stop once the increment has
2651 // contracted to velTol_ of the first sweep's. The decision is rank-uniform under MPI (all ranks
2652 // see the same global max), so per-sweep halo exchanges stay in lockstep.
2653 // Stencil paths supply `resid` (returns max|b - A u| over this rank's inner fluid cells after
2654 // a fresh ghost fill) and `bnorm` (max|b|), enabling the residual stop when velResTol_ > 0.
2655 template <class Fill, class Color, class ColorDu>
2656 void velSweepLoop(Fill&& fill, Color&& sweepColor, ColorDu&& sweepColorDu,
2657 std::function<double()> resid = nullptr, double bnorm = 0.0);
2658
2659
2660
2662
2663
2664 // residual functor + max|b| for the stencil paths of component c (see velSweepLoop)
2665 // Common tail of a residual evaluation: the held normal-Dirichlet face is imposed, not solved
2666 // (excluded), remember max|A u| for the convergence scale, return max|r|.
2667 double finishResidual(int c);
2668 // the axis of component c's held normal-Dirichlet residual plane (index G), or -1
2669 int heldResidualPlane(int c) const;
2670
2671
2672 std::function<double()> stencilResidual(int c, bool exchange = false);
2673
2674
2675 // The all-fluid domain-BC smoother's operator (per-axis constant coefficients + the boundary
2676 // fold). `aniso` selects the per-axis body; the isotropic path runs the legacy kernel literally
2677 // (doc/anisotropic_metric.md §2, trap 4).
2678 std::function<double()> constCoeffResidual(int c, double bx, double by, double bz, double Ac);
2679
2680
2681 // velSweepLoop's |b| for the stop scale: -1 = "the residual functor's max|b|" (F-1, set in
2682 // lastBNorm_ by stencilResidual / constCoeffResidual), 0 without a residual stop
2683 double stencilBnorm(int c);
2684
2685
2686
2687 void smoothComp(int c);
2688 // Chebyshev momentum solve for one component (IBM/periodic path). Same stop criterion,
2689 // scale and counters as velSweepLoop, so the two solvers are interchangeable.
2690 void chebSolveComp(int c);
2691
2692
2693 // pressure ghost at domain faces for the incremental predictor's grad(P): zero-gradient (Neumann)
2694 // at every non-periodic face so grad(P) carries no spurious force there (the periodic fill
2695 // wrapped the opposite boundary's pressure). Outflow pressure (Dirichlet p=0) is enforced
2696 // separately in the MG solve.
2698
2699
2700 // domain-BC velocity ghosts: periodic-fill periodic axes, then apply per-face BCs (fold=0
2701 // explicit/1 implicit).
2702 void fillVelGhosts(int comp, int fold);
2703
2704
2705 void applyVelocityBcComp(int comp, int fold, bool doOutflow);
2706
2707
2708 // Field-parameterized variants (so the velocity-MG can re-impose the BC on its own level-0
2709 // iterate). `doOutflow = false` is the SIBLING behaviour merged in here (was
2710 // `fillVelGhostsKeepOutflow`, used ONLY by `bridgeVelocityToVof` and the two call sites below,
2711 // always with `fold = 0`): it does NOT re-impose the zero-gradient OUTFLOW face — exactly what
2712 // `step()` already passes after `project()` ("keep outflow").
2713 //
2714 // WHY THE `doOutflow = false` PATH EXISTS (WO-R; a defect found by gate F2). The projection
2715 // corrects the high-side OUTFLOW normal face separately from every other face
2716 // (`bcCorrectOutflow`) — that correction IS how mass leaves the domain, and `step()` deliberately
2717 // re-imposes the domain BCs afterwards with `doOutflow = false` so it survives. `bridgeVelocityToVof`
2718 // used to call the FULL fill (`doOutflow = true`), whose `bcOutflowComp` overwrites the boundary
2719 // face with the zero-gradient copy of the last inner cell — erasing the correction immediately
2720 // after the projection made it, on every step, whenever VoF is enabled.
2721 //
2722 // Two measured consequences, both of which vanish with `doOutflow = false`
2723 // (`tests/kokkos/test_vof_bc.cpp` gate F2):
2724 // * the field the colour advector is handed is NOT discretely divergence-free at the outflow,
2725 // which is precisely the hypothesis Weymouth-Yue's exact conservation rests on;
2726 // * `max_open_divergence()`, evaluated after `step()` returns, reports the ERASED field —
2727 // measured 4.0 on a stratified outflow box that the projection had actually solved.
2728 // The outer ghost layers beyond the boundary face are left as the exchange/periodic fill wrote
2729 // them, and the advector never reads them: its flux sweep along axis d reaches exactly the
2730 // domain boundary face and no further.
2731 //
2732 // Inert for everything that existed: `bridgeVelocityToVof` runs only under `enable_vof`, and no
2733 // VoF configuration before this rung combined VoF with an outflow face.
2734 //
2735 // `faceEdges` (distributed, `doOutflow = false` only; the full-stress prelude passes it): also
2736 // give the TRANSVERSE ghost ring of the kept outflow face plane its single-rank value, the
2737 // periodic image of that plane, at the cost of one more exchange (review S1; mac_bc.hpp
2738 // bcHighFacePlaneToLastInner). The domain BCs are then applied AFTER the restore, as the
2739 // single-rank fill applies them after its periodic fill. Off, the fill is the one it always was.
2740 void fillVelGhostsTo(CCField f, int comp, int fold, bool doOutflow = true,
2741 bool faceEdges = false);
2742 // Ghost-fill a MAC FACE field whose normal axis is `a` (collocated uf_/vf_/wf_, or a staggered
2743 // C[a].u handed to a face-velocity consumer) WITHOUT losing its high-side domain-boundary face.
2744 // That face is the first GHOST index along `a`, and fillGhosts wraps every axis periodically
2745 // (single-rank fillAxis and the distributed exchange alike), so it would come back carrying
2746 // the LOW boundary's face -- on an inflow/outflow channel the inlet plane on the outlet
2747 // (doc/uf_outlet_fix.md). The plane is saved and restored over the INNER transverse range only
2748 // (the transverse ghost rows are legitimately the neighbour's; SCALING_ISSUES #8), and only on
2749 // a NON-PERIODIC axis whose high global face this rank owns; otherwise it IS fillGhosts. Every
2750 // non-periodic type, not just outflow: a high-side INFLOW face got the low (outlet) plane the
2751 // same way, and collocated momentum read that one (openFaceView replaces outflow faces only).
2753
2754
2755 // Distributed: a rank applies a face's BC iff its block TOUCHES that global face
2756 // (`touchesGlobalFace`, the same rule the scalar path uses in `applyScalarBc`). Without the test
2757 // every rank imposed the wall on its OWN block faces, so a partition cutting a walled axis split
2758 // the domain into independent sub-domains — invisible in the velocity (each sub-domain is
2759 // separately consistent) and only visible in the pressure. Single-rank the test is always true,
2760 // so this is byte-identical there.
2761 void applyVelocityBcCompTo(CCField f, int comp, int fold, bool doOutflow);
2762 // §14 H-3(e) (staggered): one face's velocity BC (the per-face body of applyVelocityBcCompTo);
2763 // whether both faces of axis a take bcVelocityComp on this rank with disjoint ghost planes (one
2764 // launch then covers both); and the three components back to back (applyVelocityBcComp for
2765 // c = 0, 1, 2), one launch per such axis.
2766 void applyVelocityBcFace(CCField f, int comp, int a, int s, int fold, bool doOutflow);
2767 bool bcVelFacePair(int a) const;
2768 void applyVelocityBcAll(int fold, bool doOutflow);
2769
2770
2771 // implicit-diffusion wall fold (CUDA setup_bc_diffusion): dcorr += (wall:+beta tangential /
2772 // outflow:-beta), brhs += 2*beta*wall (tangential Dirichlet); bake dcorr into the per-component
2773 // stencil diagonal.
2775
2776
2777 // Incremental (rotational) cut-cell projection: solve A phi = -div_open(u*) (RB-GS,
2778 // mean-removed), u -= grad phi, then accumulate the physical pressure P += (rho/dt)*phi -
2779 // mu*div(u*) (Timmermans).
2780 // one mask-aware axis-wise smoothing pass of a cell field (the filtered-rotational S; see
2781 // setRotationalFilter). Reads the +/-1 axis neighbours' sdf: fluid-fluid -> (1,2,1)/4;
2782 // one solid side -> 1/2(self + open-side neighbour); both solid -> identity.
2783 void filterCellField(CCField f, int axis);
2784
2785
2786 void project();
2787
2788
2789 // ---- project() stages (QUALITY_PLAN G.1): pure cut-and-paste, each a contiguous
2790 // block of the original function sharing only member fields and a CCExec. ----
2792
2793
2795
2796
2798
2799
2800 // The pressure-driver dispatch of projectSolve (Chebyshev with its bound estimate / ghost
2801 // BiCGStab / flexible CG / MG-PCG): solve the projection's own operator for `x1` (g=1 block,
2802 // used as the initial guess) with the right-hand side `rhs1`, at the driver's own rtol. Returns
2803 // the iteration count; `mg_.lastSolveFailed()` reports a non-finite recurrence. Shared by the
2804 // main projection and the balanced-force projection (doc/collocated_varrho_forces.md §4.6.2 B4).
2806 // Count a cold-bounds Chebyshev growth-guard firing; the first one prints a stderr notice.
2807 void noteChebyshevGrowthTrip(long iters);
2808 // Q18: the CG exit check (see lastPressureTrueResidual) and the one-time high-contrast notice.
2809 void checkCgExit(CCField rhs1, CCField x1, long iters, const char* which,
2810 const StarOverlay* star);
2812
2813
2814 // The projection's constraint divergence of a face field (`out` on the g=2 block, inner cells):
2815 // the flux-openness divergence `divergOpen(f, ox_, oy_, oz_)` of the non-porous, non-ghost
2816 // branches of both grids. The balanced-force projection applies it to its face force (§4.9 L2:
2817 // always through this routine, never divergOpen directly, so a scheme's overlay reaches both).
2819
2820
2822
2823
2825
2826
2827 void maskVelocity(int c);
2828
2829
2830 // Minimum viscosity over the (global, under MPI) inner cells — the provably-stable rotational
2831 // coefficient for variable viscosity (chi*mu_min <= mu(x) everywhere).
2832 double minMuInner();
2833
2834
2836
2837
2838 std::vector<double> gatherInner(CCField fld);
2839
2840
2841 // Inverse of gatherInner: scatter an x-fastest (nx,ny,nz) inner-region host buffer into the inner
2842 // cells of a ghosted G=2 field (ghost cells untouched — refill via exchangeField/fillGhosts).
2843 void scatterInner(CCField fld, const std::vector<double>& in);
2844
2845
2846
2847 // --- Named field registry (multiphysics field container) ------------------------------------
2848 // Register a new zero-initialised cell-centred field on the G=2 velocity block and return its
2849 // buffer. Idempotent: re-adding an existing name returns the existing buffer unchanged.
2850 CCField addField(const std::string& name);
2851
2852
2853 bool hasField(const std::string& name) const;
2854
2855
2856 CCField fieldView(const std::string& name);
2857
2858
2859 std::vector<std::string> fieldNames() const;
2860
2861
2862 // Ghost-exchange a registered field (cross-rank + periodic under MPI; periodic-only single-rank).
2863 void exchangeField(const std::string& name);
2864
2865
2866 // Add-reduce ("reverse") halo: fold ghost-layer deposits back onto their owner cell (both
2867 // cross-rank AND periodic self-wrap). This is the coupling primitive for particle->grid
2868 // deposition (e.g. void fraction / drag reaction) where a particle near a block boundary scatters
2869 // into ghost cells owned by a neighbour; after this the inner block holds the complete sum.
2870 // Single-rank non-periodic: a no-op.
2871 void exchangeFieldAdd(const std::string& name);
2872
2873
2874 // Host round-trip: read a registered field's inner region as an x-fastest (nx,ny,nz) buffer, or
2875 // write one (ghosts left stale until the next exchangeField).
2876 std::vector<double> getField(const std::string& name);
2877
2878
2879 void setField(const std::string& name, const std::vector<double>& v);
2880
2881
2882 // Padded-block extents + ghost width, so a zero-copy field buffer (size ex*ey*ez, x-fastest) can
2883 // be reshaped in Python.
2884 std::array<int, 3> blockShape() const;
2885
2886
2887 int ghostWidth() const;
2888
2889
2890 // Global grid dims (== local dims single-rank). For the CFD-DEM co-decomposition weight field.
2891 std::array<int, 3> globalResolution() const;
2892
2893
2894 // This rank's inner-block origin in GLOBAL cells ({0,0,0} single-rank). The deposit-origin shift
2895 // so particles in global coords land in the local block (gm origin = blockOrigin * h).
2896 std::array<int, 3> blockOrigin() const;
2897
2898
2899
2900 // --- Scalar transport (advection-diffusion) -------------------------------------------------
2901 // Register a transported scalar `name` with constant diffusivity D (length^2/time in the
2902 // caller's units; under no extent, cells^2 per time unit). scheme: 0 FOU,
2903 // 1 Koren TVD (default), 2 SOU. iters = RB-GS sweeps for the implicit diffusion solve. Its field
2904 // is registered in the directory (get_field/set_field/field_view). Openness (set_solid /
2905 // set_pressure_geometry) must be established for transport to occur.
2906 // cutcell = true selects the cut-cell discretization (doc/scalar_ibm_design.md, §8.1): `iters`
2907 // is then unused (the solve is BiCGStab to a residual tolerance) and every other cut-cell setter
2908 // below applies.
2909 void addScalar(const std::string& name, double D, int scheme, int iters, bool cutcell = false);
2910
2911
2912 bool hasScalar(const std::string& name) const;
2913
2914
2915 // Per-face scalar BC: face 0..5 = -x,+x,-y,+y,-z,+z; type 0 periodic, 1 Neumann zero-flux
2916 // (adiabatic), 2 Dirichlet value. Single-rank / non-decomposed domains (distributed BC deferred).
2917 void setScalarBc(const std::string& name, int face, int type, double value);
2918
2919
2920 // Advance all registered scalars one dt with the current divergence-free velocity (also called at
2921 // the end of step()). Exposed so a test can prescribe a velocity and transport a scalar in
2922 // isolation.
2924
2925
2926 // --- Cut-cell scalar transport: the geometry record (doc/scalar_ibm_design.md §2, §3; WO-2) ---
2927 // One record per geometry, shared by every cut-cell scalar: kappa, the snapped UNGATED scalar
2928 // apertures, the fluid-unknown flags, the facet overlay with its fluid probes, and the census.
2929 // Built lazily (`ensureScalarCutGeometry`) on first use after the geometry exists; invalidated by
2930 // every geometry build (set_solid, set_solid_from_scene, set_pressure_geometry, redistribute --
2931 // all of which reach setSolidDevice). It never reads or writes ox_/oy_/oz_, cs_ or cutOwner_.
2934 // The record itself (builds it if stale). For tests and the operator; the views are the block's.
2936 // Inner (nx*ny*nz, x-fastest) copy of one record field: 0 kappa, 1/2/3 the snapped aperture of
2937 // the -x/-y/-z face of each cell, 4 the fluid-unknown flag (1/0).
2938 std::vector<double> scalarGeometryField(int which);
2939 // The geometry census, summed over ranks (collective under MPI); sealedVolume physical.
2941
2942 // --- Cut-cell scalar transport: operator, Krylov, steady + transient diffusion (WO-3) --------
2943 // doc/scalar_ibm_design.md §1.4, §4, §5.1, §8. A cut-cell scalar is advanced by
2944 // `advanceScalarCutCell` (the first statement of advanceScalars' per-scalar loop, §5.5); the
2945 // legacy kernels never see it. Every setter stores PHYSICAL values verbatim; they are converted
2946 // and folded into the operator at the next advance or steady solve, which rebuilds the operator
2947 // (ruling D-WO3-3). Advection (WO-5, §6): the explicit-implicit split of D12 on the projection's
2948 // face flux (`scalarFaceFlux`).
2949 bool isCutcellScalar(const std::string& name) const;
2950 // Wall condition of one scene instance (instance >= 0, needs a scene) or of every body
2951 // (instance = -1, which also clears the per-instance overrides): type 0 neumann (value = flux
2952 // into the fluid, c L/T), 1 dirichlet (value = wall c), 2 robin (coefficient = k, L/T; value = g).
2953 void setScalarWall(const std::string& name, int type, double value, double coefficient,
2954 int instance);
2955 // Conjugate transport (§1.1, §8.1, WO-7): make one scene instance (instance >= 0, needs a
2956 // scene) or every body (instance = -1, which also clears the per-instance settings) conjugate:
2957 // its solid interior carries the scalar too, in the registered field `<name>_solid` (psi_s =
2958 // c_s / K, allocated by the first call). D_s (L^2/T) the solid's own diffusivity, C_s the
2959 // capacity ratio, K the partition coefficient (c_s = K c at equilibrium), R_c the contact
2960 // resistance (T/L, on psi). A later setScalarWall for the same instance makes it a wall again.
2961 void setScalarSolid(const std::string& name, double D, double capacity, double partition,
2962 double contactResistance, int instance);
2963 // `get_scalar_solid` (§8.1): this rank's inner block (x-fastest) of c_s = K psi_s, NaN outside
2964 // the solid unknowns (all NaN before the first advance or steady solve with a conjugate body).
2965 std::vector<double> getScalarSolid(const std::string& name);
2966 // The solid geometry of a conjugate scalar (diagnostics.scalar_geometry): inner copies of
2967 // kappa_s = 1 - kappa (which = 0) and the solid-unknown flag (which = 1).
2968 std::vector<double> scalarSolidGeometryField(const std::string& name, int which);
2969 // Volumetric source S (c/T): uniform, or per cell (this rank's inner block, x-fastest).
2970 void setScalarSource(const std::string& name, double S);
2971 void setScalarSourceField(const std::string& name, const std::vector<double>& S);
2972 // Max-norm relative residual tolerance of the solve (default 1e-10, §5.1).
2973 void setScalarResidualTolerance(const std::string& name, double rtol);
2974 // BiCGStab iteration cap (default 200, §5.1). Diagnostics tier.
2975 void setScalarMaxIterations(const std::string& name, int maxit);
2976 // Mean-gradient (closure) mode (§1.5, WO-6): G physical (c/L); the field then holds theta,
2977 // c = G.x + theta, in the frame moving with the fluid's mean velocity. (0, 0, 0) is off.
2978 void setScalarMeanGradient(const std::string& name, const std::array<double, 3>& G);
2979 // `scalar_mean_flux` (§8.1): the box-averaged total flux (3,), c L/T (physical), of the last
2980 // advance or steady solve: the face sum of -Lam a A (c_j - c_i), c = theta + G.x, plus
2981 // (1/V_box) sum_i (U_i - kappa_i V Ubar) theta_i. Collective under MPI.
2982 std::array<double, 3> scalarMeanFlux(const std::string& name);
2983 // G.x at an extended-block cell centre for the physical gradient G (§1.5; global, unwrapped).
2984 sco::MeanGradPosition scalarMeanGradPosition(const double Gphys[3]) const;
2985 // Dirichlet value of a domain face as a per-face profile: n1 x n2 values over this rank's face
2986 // cells in the face's tangential axes in x, y, z order, the first fastest (§8.1).
2987 void setScalarBcProfile(const std::string& name, int face, const std::vector<double>& prof,
2988 int n1, int n2);
2989 // Steady solve now (§1.4 steady mode): kappa/dt and c^n dropped; initial guess = the field.
2990 void solveScalarSteady(const std::string& name);
2991 // Bodies the wall table distinguishes: the scene's instances, or 1 for raw-SDF geometry.
2992 int scalarNumBodies() const;
2993 // Integrated flux INTO the fluid per body over the last advance/solve (c L^3/T, physical),
2994 // summed on the host in facet order, then over ranks (collective under MPI).
2995 std::vector<double> scalarWallFlux(const std::string& name);
2998 double mass = 0.0, massSolid = 0.0, dMass = 0.0, wallIn = 0.0, boundaryIn = 0.0,
2999 sourceIn = 0.0, defect = 0.0, identityError = 0.0;
3000 };
3001 ScalarCutBudget scalarBudget(const std::string& name);
3005 std::vector<double> centroid, normal, area, wallValue, flux;
3006 std::vector<int> instance, rung;
3007 };
3008 ScalarCutFacets scalarFacets(const std::string& name);
3009 // The cut-cell scalar of this name (throws std::invalid_argument when it is not one).
3010 ScalarField& cutcellScalar(const std::string& name, const char* who);
3011 // The transient advance of one cut-cell scalar (from advanceScalars).
3013 // The refusals of §8.1, checked at every advance / steady solve (std::runtime_error).
3014 void scalarCutRefusals(const ScalarField& sc) const;
3015 // Assemble (bands, overlay coefficients, surrogate diagonal, rhs) and solve; the field's
3016 // non-unknown cells are zeroed first and its ghosts filled after.
3017 void scalarCutAssembleSolve(ScalarField& sc, bool steady);
3018 // WO-8: the resolution warnings of §9 (thin solids, R2 > 1 % of the probes, sealed volume >
3019 // 1e-6 of the fluid volume), stderr on rank 0, once per scalar at its first build.
3021 bool scalarRootRank() const;
3022 // y = A x for the stored operator of `sc` (exchanges x's ghosts).
3024 // WO-7: the two-field y = A x of a conjugate scalar (exchanges both fields' ghosts).
3026 // WO-7: the per-scalar solid record (§2.7 materials, §1.3 solid unknowns, §3.4 solid probes),
3027 // rebuilt when the geometry or the set of conjugate bodies changed; `conj` the resolved
3028 // conjugate flag per body.
3029 void ensureScalarSolidRecord(ScalarField& sc, const std::vector<char>& conj);
3030 // WO-7: the per-body material table (internal units) of the current settings.
3043 ScalarFaceFlux scalarFaceFlux(int a) const;
3044 // WO-5b (§6.5, ruling D-WO5-3): capture, on every flow inflow/outflow global face this rank
3045 // touches, the boundary-face flux open * vel the projection constrained (through
3046 // `scalarFaceFlux`), over the face plane's full transverse extent. Called by step() right after
3047 // the projection and the domain-BC re-imposition, before any ghost fill overwrites the high-side
3048 // plane (the first ghost index, which a fill wraps from the opposite face). No-op without an
3049 // open face; numerically inert for the flow (it only copies a plane).
3051 // WO-5 (§6): the face fluxes, the small-cell classification and the census of one advance or
3052 // steady solve, into `sc.cut` (st.advecting false: no face carries flux, nothing else is built).
3053 void scalarCutAdvection(ScalarField& sc, bool steady);
3054 // setSuperficialVelocity's per-step shift (the tail of step()); no-op when off.
3057
3058
3059
3060 // --- Geometric VoF: the colour field (rung V2a, WO-J) ---------------------------------------
3061 //
3062 // WHAT THIS RUNG IS. One phase, transported by geometric (PLIC + Weymouth-Yue) VoF, drives the
3063 // fluid properties through the ORDINARY property closures, and the existing variable-density
3064 // projection carries the density jump. No surface tension (V4), and — important — NO
3065 // MOMENTUM-CONSISTENT TRANSPORT (that is rung V2b / WO-K). Mass and momentum are therefore
3066 // advected by different fluxes, which multiplies the light phase's acceleration by the heavy
3067 // phase's density in a mixed cell: a spurious interfacial momentum source of order Δρ. The
3068 // literature is unambiguous that this breaks down around density ratio 1000 unless the
3069 // resolution is absurd (Rudman 1998; Arrufat et al., Computers & Fluids 215:104785, 2021 —
3070 // accurate raindrop at 15 cells/diameter WITH consistency versus ~200 without). SO: **V2a is
3071 // valid only at modest density ratios.** A ratio-1000 case that is at REST (the hydrostatic acid
3072 // test) is exact here, because there is no momentum to mis-advect; a ratio-1000 case with motion
3073 // is not this rung's business.
3074 //
3075 // USAGE
3076 // s.enable_vof() # registers "C" and the g=3 working block
3077 // s.set_vof(C0) # sharp initial colour, C in [0,1]
3078 // s.set_property_model("rho", "linear", "C", [rho_g, rho_l - rho_g]) # rho(C); enables varRho
3079 // s.set_property_model("mu", "linear", "C", [mu_g, mu_l - mu_g]) # mu(C) (optional)
3080 // s.set_property_model("force_z", "linear", "rho", [0.0, -g]) # gravity
3081 //
3082 // STRUCTURE (`suite/docs/VOF_PLAN.md` §3 rule 1: the colour field gets its own g=3 halo and the
3083 // solver's G = 2 is NOT widened). There are two blocks and the split is deliberate:
3084 // * `"C"` is a NORMAL registered G=2 cell field. That is what makes item 3 of the work order
3085 // ("ρ(C) and μ(C) through the EXISTING closures, no new closure machinery") possible at all:
3086 // `applyClosure` indexes its input and its output with the SAME linear index on the SAME
3087 // extent, so a closure input MUST live on the G=2 block. It is also what gives C
3088 // get_field/set_field/field_view/exchange_field/redistribute for free.
3089 // * the g=3 block is the advector's own working block (`vof::WyAdvector`), with its own
3090 // `GridHaloTopology` at width 3 under MPI. MYC needs 3^3 and the donor ring is one cell
3091 // outside the inner region (so advection alone needs 2); width 3 is the plan's choice for the
3092 // V3 height-function columns.
3093 // The two blocks exchange INNER REGIONS ONLY (`copyInner`, both ways) and each fills its own
3094 // ghosts with its own policy — that is the one bridge, and it carries no offset arithmetic
3095 // beyond `copyInner`'s. The face velocities go the other way, whole-block-embedded
3096 // (`vof::copyBlockEmbed`), because the advector reads them one cell outside its inner region.
3097 //
3098 // STAGGERED ONLY. The collocated path is rung V8 and needs the collocated variable-density
3099 // projection (which throws today) before it means anything; `enableVof` throws there rather than
3100 // half-supporting it.
3101 //
3102 // NO IMMERSED SOLIDS YET. `VOF_PLAN.md` §3 rule 2 makes C the liquid fraction of the FLUID volume
3103 // with openness-weighted geometric fluxes (Huang 2025/2026 solid-clipped flux polygons). That is
3104 // not this work order's scope, and a silently-unweighted flux would leak C into the solid, so
3105 // `advectVof` throws if an immersed solid is present. An ALL-FLUID `set_pressure_geometry` is
3106 // fine (and is what the acid test uses) — the check is on `hasSolid_`, i.e. on any inner SDF < 0.
3107 static constexpr int kVofG = 3; // the colour field's ghost width (VOF_PLAN §3 rule 1)
3108
3110
3111
3115 void setVofWispEps(double eps);
3116
3117
3118 double vofWispEps() const;
3119
3120
3123 static constexpr double defaultVofWispEps();
3124
3125
3126 bool vofEnabled() const;
3127
3128
3129 // Initial / prescribed colour field on the inner cells (flat x-fastest, nx*ny*nz), C in [0,1]:
3130 // the LIQUID fraction of the cell. Enables VoF if it is not on yet. Ghosts are refreshed here so
3131 // a closure applied before the first step already sees a consistent field.
3132 void setVof(const std::vector<double>& c);
3133
3134
3135 std::vector<double> getVof();
3136
3137
3138 // Local (this rank's) colour census: sum / min / max / mixed-cell count / wisp count.
3140
3141
3142 // sum of the canonical colour field "C" over SOLID cells of this rank (0 by construction).
3144
3145
3146 // Interface-local Courant number max|uf|*dt/h over the faces of mixed cells and their face
3147 // neighbours, with the CURRENT velocity and dt (an all-reduce max under MPI). This is the number
3148 // the WY boundedness bound applies to — NOT the global max, which over-throttles badly (V1
3149 // measured 0.314 in a quiescent Zalesak corner against 0.157 at the interface). Use it to pick
3150 // dt: `dt_new = dt * cfl_target / vof_max_courant()`.
3152
3153
3154 // The interface-local Courant number of the step just taken (0 before the first step).
3155 double vofLastCourant() const;
3156
3157
3158 // Weymouth-Yue boundedness cap (default 0.25, the PROVEN 3D bound 1/(2(N-1)); 0.5 is the 2D
3159 // value). `step()` throws when the interface-local Courant number exceeds it.
3160 void setVofCflLimit(double v);
3161
3162
3163 double vofCflLimit() const;
3164
3165
3166
3167 // --- rung V5a (WO-Q): VoF transport through an immersed solid ---------------------------------
3168 //
3169 // The colour advection is openness-weighted (`vof/cutcell.hpp`): the geometric flux of every face
3170 // is multiplied by the face openness `o_f`, the update is done in FLUID-VOLUME units
3171 // (`eps_i C_i`), and the dilation term uses the same `o_f a_f` — so the conserved functional
3172 // `sum_i eps_eff_i C_i` telescopes against the projection's own openness-weighted divergence,
3173 // exactly as in the uncut case. Solid cells carry no colour (the canonical "C" reads 0 there) and
3174 // the working block's solid band carries the neutral 90-degree fill for the MYC / height-function
3175 // stencils.
3176 //
3177 // WHAT IT APPROXIMATES: the PLIC polyhedron is reconstructed on the WHOLE unit cell and its slab
3178 // volume is multiplied by the open area, instead of being clipped against the solid as well
3179 // (Huang, JCP 2025/2026). Conservative and exact where interface and wall are parallel or the
3180 // cell is whole; O(1) wrong in the distribution INSIDE a cell whose interface crosses its wall.
3181 // `vof_diagnostics().clipped_volume` is the tripwire.
3182 void requireVofGeometry(const char* who);
3183
3184
3185 // Does the colour advection run the cut-cell (openness-weighted) kernels?
3186 bool vofHasGeometry() const;
3187
3188
3189 // Ablation: drop Weymouth's admissible-interval clamp on the openness-weighted flux
3190 // (`vof/cutcell.hpp` vofCutFluxClamp). ON by default — the measurement that put it there is in
3191 // that header. With it off the [0,1] clip becomes the mechanism instead of a tripwire and the
3192 // conserved functional drifts.
3193 void setVofCutFluxClamp(bool on);
3194
3195
3196 bool vofCutFluxClamp() const;
3197
3198
3199 // What the CANONICAL "C" field carries in SOLID cells (the working block always carries the
3200 // neutral band fill, which is what the MYC / height-function stencils need):
3201 // true (default) 0 — "no colour in the solid", the WO-Q gate. The closures then see gas
3202 // density there and the CSF sees a full colour jump across a wall face.
3203 // false the band fill — a zero-slope continuation of the liquid into the wall.
3204 // Measured on the G5 cap (D/dx = 24, sigma = 1, mu = 0.05): see the WO-Q findings entry.
3206
3207
3209
3210
3211 // The colour field INCLUDING the neutral solid-band fill, on the inner region — i.e. what the
3212 // MYC / height-function stencils actually read, as opposed to the canonical "C" (0 in solid).
3213 // The fill is regenerated here, so this is also the direct gate on its decomposition
3214 // independence: it must be pointwise BITWISE across np (`tests/kokkos_mpi/test_vof_cutcell_mpi`).
3215 std::vector<double> getVofFilledColour();
3216
3217
3218 // The cut-cell geometry the colour block runs on, on the inner region: 0 = the cell fluid
3219 // fraction eps, 1/2/3 = the openness of the +x/+y/+z face of each cell (the ADVECTOR's high-face
3220 // convention), 4 = the cell classification (1 = solid). All must be bitwise across np.
3221 std::vector<double> getVofGeometry(int which);
3222
3223
3224 // --- rung V5b (WO-S): static contact angle on SDF solids --------------------------------------
3225 //
3226 // The band fill of rung V5a is a stencil device: it decides what the MYC 3^3 stencil and the V3
3227 // height-function columns of a near-wall cell see INSIDE the solid, and WO-Q's neutral (mean of
3228 // the fluid face neighbours) rule is the zero-slope continuation, i.e. the 90-degree
3229 // Afkhami-Bussmann limit. `set_contact_angle` replaces PASS 1 of that fill by the fractions of
3230 // the plane that continues the fluid-side interface into the solid at the prescribed angle
3231 // theta, measured THROUGH THE LIQUID (`m . n_w = cos theta`, `vof/wetting.hpp`). Nothing else
3232 // changes: no force is added at the wall, the V3 cascade and the V4 balanced force are the
3233 // unmodified ones, and passes 2-3 of the fill are WO-Q's.
3234 //
3235 // theta is a per-cell FIELD so the dynamic-angle rung (V6) changes only what fills it. Setting
3236 // it needs `set_solid(..., cutcell_pressure=True)` + `enable_vof` (there is no wall otherwise);
3237 // with no call the neutral fill runs and every V5a number is byte-identical.
3238 void setContactAngle(double thetaDeg);
3239
3240
3241 // ISSUES sweep item 3: `set_contact_angle` used to be a silent no-op whenever there was nothing
3242 // for it to bind to -- the theta field simply was never consulted, and
3243 // `contact_angle_diagnostics()['contact_cells']` reading 0 was the only tell. Say so instead.
3245
3246
3247 // Per-cell contact angle in DEGREES on the inner region (flat x-fastest, nx*ny*nz). Only the
3248 // value at the SOLID band cell being filled is read, so cells away from a wall are irrelevant.
3249 void setContactAngleField(const std::vector<double>& thetaDeg);
3250
3251
3252 bool contactAngleSet() const;
3253
3254
3255 double contactAngle() const;
3256
3257
3258 // Which anchor the theta-plane uses (`vof::VofWettingPivot`): 0 volume-consistent (DEFAULT,
3259 // idempotent), 1 the PLIC centroid p_f (Afkhami-Bussmann), 2 the work order's
3260 // `c = p_f - sdf(p_f) n_w` (NOT idempotent — measured to be off by 0.26 in cell fraction at
3261 // theta = 60, gate G0), 3 the contact line on the wall. Ablation only.
3262 void setContactAnglePivot(int mode);
3263
3264
3266
3267
3268
3269 // --- rung V6 (WO-V6): the DYNAMIC contact angle and hysteresis --------------------------------
3270 //
3271 // Nothing in the V5b fill changes; only the VALUE of theta per contact cell does. See
3272 // `vof/wetting_dynamic.hpp` for the model (Afkhami, Zaleski & Bussmann, JCP 228:5370 (2009)):
3273 //
3274 // theta_Delta^3 = theta_e^3 + 9 Ca_cl ln(Delta/lambda), Ca_cl = mu_l U_cl / sigma
3275 //
3276 // with `Delta` the CELL SIZE and `lambda` an EXPLICIT slip length in cells. The explicit slip is
3277 // the whole point: a VoF contact line's numerical slip is proportional to `Delta`, so without it
3278 // the imposed angle is silently grid-dependent (VOF_PLAN §6). NEVER report a dynamic-wetting
3279 // result without stating lambda.
3280 //
3281 // @param thetaEDeg the equilibrium (static base) angle, degrees. Also becomes the static angle.
3282 // @param slipCells lambda / Delta, in CELLS. Must lie in (0, 1) — lambda >= Delta would make
3283 // ln(Delta/lambda) <= 0 and REVERSE the correction.
3284 // @param muLiquid the LIQUID dynamic viscosity entering Ca_cl (solver units).
3285 // @param sigma the surface tension entering Ca_cl; <= 0 means "use set_surface_tension".
3286 void setContactAngleDynamic(double thetaEDeg, double slipCells, double muLiquid,
3287 double sigma = 0.0);
3288
3289
3295 void setWallSlipLength(double lambdaCells);
3296
3297
3299 double wallSlipLength() const;
3300
3301
3303 std::array<int, 3> wallSlipSandwichCells() const;
3304
3305
3306 // theta_a / theta_r, degrees. Composes with the dynamic correction when that is also set: the
3307 // hysteresis selector picks the BASE angle and Cox-Voinov corrects it, except on the PINNED
3308 // branch (theta_r <= theta_app <= theta_a), where the apparent angle itself is imposed and the
3309 // idempotence of the V5b fill (WO-S finding 1) is what makes the contact line stand still.
3310 void setContactAngleHysteresis(double thetaADeg, double thetaRDeg);
3311
3312
3313 // Back to the static V5b angle, byte-identically (the driver's views are kept but never read).
3315
3316
3318
3319
3321
3322
3323 double contactAngleSlip() const;
3324
3325
3326 // ABLATION: the 3-point in-wall mean of U_cl (default ON). Off = the raw per-cell MAC velocity.
3328
3329
3330 // The angle clamp of the Cox-Voinov cube, degrees (default 1 / 179).
3331 void setContactAngleClamp(double loDeg, double hiDeg);
3332
3333
3334 // The sigma the dynamic correction uses: the explicit override if one was given, else the CSF's.
3336
3337
3338 // The per-cell dynamic-wetting state on the inner region: 0 the IMPOSED angle (degrees),
3339 // 1 the measured APPARENT angle (degrees), 2 the smoothed U_cl, 3 Ca_cl, 4 the
3340 // `vof::VofDynamicState`. Non-contact cells read 0 in 1..4 and the static base in 0.
3341 std::vector<double> getVofDynamicField(int which);
3342
3343
3345 long contactCells = 0;
3347 long pureCells = 0;
3348 long parallelCells = 0;
3349 long neutralCells = 0;
3350 long unfilledCells = 0;
3351 double meanApparentAngle = 0.0;
3352 double setAngle = 0.0;
3353 // --- rung V6 (WO-V6), all zero unless a dynamic angle / hysteresis is configured -----------
3354 long dynamicCells = 0;
3355 long pinnedCells = 0;
3357 long recedingCells = 0;
3358 double meanImposedTheta = 0.0;
3359 double meanApparentTheta = 0.0;
3360 double maxCaCl = 0.0;
3361 double maxContactSpeed = 0.0;
3362 };
3363 // The band census of the CURRENT colour field: how many band cells each branch of the fill wrote
3364 // and the mean APPARENT angle the fluid-only normal reported at the contact cells (G1's
3365 // measurement, evaluated on the fill's own data rather than on a post-processed shape).
3366 ContactAngleDiagnostics contactAngleDiagnostics();
3367
3368
3369 // Wire the theta field + the wall SDF onto the colour block. Idempotent; called by the setters
3370 // and again by every geometry rebuild (`buildVofGeometry`), since the block can be re-sized.
3372
3373
3374 // Cell-centre velocity on the colour block, for the V6 contact-line speed. Built from the
3375 // solver's own staggered faces (`0.5*(u(i) + u(i+s_c))`, both valid after `fillVelGhosts`) on
3376 // the INNER region and then run through the colour field's ghost policy, exactly as the wall SDF
3377 // and the fluid-only normals are — that is what keeps the imposed angle decomposition-
3378 // independent (WO-S finding 9 applied to a third field).
3380
3381
3382
3383 // The colour advector itself (its g=3 block, geometry views and planes). For TESTS: gate G3 of
3384 // `tests/kokkos/test_vof_cutcell.cpp` rebuilds the openness/fraction by an independent route and
3385 // compares against these.
3387
3388
3389 // The sweep permutation index of the NEXT colour advection (`kWySweepPerm[n % 6]`). Exposed so a
3390 // benchmark can hold the permutation fixed, or resume one, across a restart.
3391 // The sweep permutation is `kWySweepPerm[n % 6]`, so this counter is STATE: a run resumed with
3392 // it reset takes a different sweep order and its colour differs at the splitting error (measured
3393 // 6.2e-4 after ONE step of `channel_18`, off a bitwise-identical velocity). The BLOCK container
3394 // keeps its own counter — `VofBlockSet::step_`, which drives `WyAdvector::advect(dt, step_)` for
3395 // every marker — so a restart has to set both, and this is the one call that does it.
3396 void setVofStepParity(long n);
3397
3398
3399 long vofStepParity() const;
3400
3401
3402
3403 // KINEMATIC colour advection: advance C ONCE with the solver's CURRENT face velocity and the
3404 // given dt, with no Navier-Stokes step at all. This is the entry point the advection benchmarks
3405 // (Zalesak, LeVeque) and the cut-cell conservation gates use — a frozen Stokes field advecting a
3406 // colour slab is a pure statement about the advection scheme, with the momentum solve and the
3407 // pressure solve out of the picture.
3408 //
3409 // It REFUSES a velocity field that is not discretely divergence-free to 1e-10: Weymouth-Yue's
3410 // exact conservation is conditional on `sum_f o_f u_f = 0` per cell (the dilation term adds
3411 // `H(C-1/2)` times that residual to EVERY full cell's budget), so a run on a non-solenoidal field
3412 // would report a conservation "defect" that is really the caller's velocity. Use the solver's own
3413 // projected output (run `step()` to a steady state, or call `project()`), never an analytic
3414 // sample.
3416 void advectVofKinematic(double dtPhysArg);
3417
3418
3419 // --- Part III rung W0 (WO-W0): the per-bubble VoF BLOCK container -----------------------------
3420 //
3421 // A THIRD container over the same L1 kernels (`suite/docs/VOF_PLAN.md` §10, the TBFsolver
3422 // `vofBlock` pattern): one bubble = one `WyAdvector` on a small moving global index box with a
3423 // master rank of its own, and the registered `"C"` the closures see is the UNION
3424 // `C = max_blocks C_block`, never the source. Two bubbles that touch therefore CANNOT coalesce
3425 // numerically — coalescence becomes an explicit model decision (rung W4) instead of a numerical
3426 // accident. See `vof/block_container.hpp` for the three index boxes and the ghost policy, and
3427 // `vof/block_exchange.hpp` for why the gather is plain Isend/Irecv and not an NBX handshake.
3428 //
3429 // W0 stops at KINEMATIC transport: `advect_vof_blocks(dt)` is the block twin of `advect_vof(dt)`
3430 // and carries the same divergence-free precondition. NS coupling (union -> closures -> varRho
3431 // projection, per-block curvature + CSF scattered UNPACK_SUM) is rung W12.
3432 //
3433 // Scope at W0: all-fluid (no immersed solid — the cut-cell block is W12), and the seeds are
3434 // spheres given in CELL units. Not composable with `enableVofMomentum` (refused in either order:
3435 // that transport advects the structured colour and skips the slot that advects the markers).
3436 void enableVofBlocks(const std::vector<std::array<double, 4>>& seeds);
3437
3438
3439 // Everything `enable_vof_blocks` does EXCEPT the seeding, so the sphere seeds and the
3440 // general (`enable_vof_blocks_from_field`) seeds share one code path.
3442
3443
3444 // The union the closures see, plus the rung-W1 master assignment on the seeded boxes.
3446
3447
3448 bool vofBlocksEnabled() const;
3449
3450
3452
3453
3454 // Kinematic block advection with the CURRENT (projected) face velocity — the block twin of
3455 // `advect_vof`. Same precondition: Weymouth-Yue conservation is conditional on the face field
3456 // being discretely divergence-free, so a field that is not is refused rather than silently
3457 // reported as a conservation defect.
3458 // `requireSolenoidal` is the KINEMATIC precondition: the Python entry point prescribes the
3459 // velocity itself, so a field that is not discretely divergence-free is a user error and is
3460 // refused rather than silently reported as a conservation defect. Inside `step()` the advecting
3461 // field is the projection's own output and its residual divergence IS the conservation floor --
3462 // exactly as for the structured `advectVof()`, which has never carried a check here -- so the
3463 // in-step call passes false. (Rung W2: with variable density the projected residual sits at
3464 // ~1e-7 without the exact level-0 apply, which would refuse every coupled step.)
3466 void advectVofBlocks(double dtPhysArg, bool requireSolenoidal = true);
3470 void advectVofBlocksInternal(double dtInt, bool requireSolenoidal);
3471
3472
3473 // Per-bubble Lagrangian census. Only this rank's MASTER blocks carry numbers (volume, centroid,
3474 // centroid velocity, the central second moments); the box and the master are replicated.
3475 std::vector<vof::VofBlockStats> vofBlockStats() const;
3476
3477
3478 // max/mean of the per-rank block-cell load under the CURRENT master assignment (round robin at
3479 // W0; the weighted-ORB assignment is W1 and these are the numbers to beat). 1.0 = perfect.
3480 double vofBlockImbalance() const;
3481
3482
3483 // Blocks mastered by each rank, and the inner cells those blocks carry.
3484 void vofBlockCensus(std::vector<long>& masters, std::vector<long>& cells) const;
3485
3486
3487
3488 // --- Part III rung W1 (WO-W12) ----------------------------------------------------------------
3489 //
3490 // (a) Master assignment. `mode` 0 = round robin (W0), 1 = LPT greedy on the block cell counts,
3491 // 2 = weighted ORB over a 1-D block space (core's `BlockDecomposer<1>`). `every` re-runs the
3492 // assignment every `every` block steps, MIGRATING the colour of any block that changed
3493 // master (nothing else in a block is state). Applied immediately.
3494 void setVofBlockAssign(int mode, long every);
3495
3496
3497 int vofBlockAssign() const;
3498
3499
3500 // The imbalance the CURRENT `assignMode` would give without applying it — so a study can put the
3501 // three modes side by side on one swarm without perturbing the run.
3502 double vofBlockImbalanceOf(int mode) const;
3503
3504
3505 // (b)/(c) instrumentation: device-resident packing on/off, and the block-pool hit census.
3507
3508
3509 void setVofBlockPool(bool on);
3510
3511
3512 std::array<long, 2> vofBlockPoolStats() const;
3513
3514
3515
3516 // General seeding (rung W1): one block per given GLOBAL index box, with the colour taken from
3517 // the field `set_vof` installed. A sphere seed is a convenience over this; a Hysing bubble, a
3518 // quasi-2-D cylinder or any scanned marker enters here. The boxes are the BUBBLE extents (the
3519 // container grows them by the 3-cell margin itself) and must not overlap in a way that makes a
3520 // cell belong to two markers at seed time -- the gather is a copy, not a union, so a cell inside
3521 // two boxes would be given to both markers.
3522 void enableVofBlocksFromField(const std::vector<std::array<int, 6>>& boxes);
3523
3524
3525
3526 // --- rung W3: checkpoint / restart of the block container ------------------------------------
3527 //
3528 // The block's own inner colour is a block's ONLY state, so {box, colour} per block is a complete
3529 // checkpoint -- and unlike `enableVofBlocksFromField` it is exact when two markers touch (the
3530 // seeding gather out of the UNION would give each a slice of the other; WO-W12 open item 5).
3531 std::vector<double> vofBlockColour(long id);
3532 std::vector<double> vofBlockKappa(long id);
3534 const vof::VofBlockSet* vofBlockSet() const { return vofBlocks_.get(); }
3535
3536
3537 void enableVofBlocksFromColours(const std::vector<std::array<int, 6>>& boxes,
3538 const std::vector<std::vector<double>>& colours);
3539
3540
3541
3542 // --- rung W2: the block CSF ------------------------------------------------------------------
3543 //
3544 // Turn the surface tension of `set_surface_tension` into a PER-BLOCK force: each marker runs its
3545 // own curvature cascade on its own box and forms the V4 balanced-force face force there, and the
3546 // three face fields are summed into the local patch (UNPACK_SUM). Requires the block container.
3548
3549
3550 // Per-block curvature + CSF face force, scattered SUM into the registered face-force fields the
3551 // RHS reads. Called at the head of every step by `updateVofCurvature()`.
3553
3554
3555 // --- vof_overlap_design §5.6 (WO-7): phantom (gas-gas) interfaces of overlapping markers -------
3556 //
3557 // `S = sum_k C_k` is scattered beside the MAX union after every block advection (and when the
3558 // block CSF or the overlap density is switched on). While the block CSF is on and any cell has
3559 // `S > 1 + 1e-2` (a GLOBAL max; §11), the capillary limit --
3560 // `vof_step_limits()['capillary_dt']` and the `step()` check -- uses `2 rho_min` in place of `rho_l + rho_g`: the part of marker A's
3561 // surface inside B is an interface with rho_g on both sides. Detected at the end of step n, it
3562 // binds from step n+1. Not under the opt-in overlap density below, whose phantom is an ordinary
3563 // liquid-gas interface.
3565 double maxSum = 0.0;
3566 double excess = 0.0;
3567 long cells = 0;
3568 bool active = false;
3569 };
3570 VofOverlapCensus vofBlockOverlapCensus() const { return vofOverlap_; }
3571 // Recompute S and the census (collective under MPI). Public for nvcc's extended-lambda rule.
3573 // OPT-IN MODEL, default off (MAX verbatim): the union colour that feeds rho(C), mu(C) (and the
3574 // registered "C") becomes `C_eff = S <= 1 + 1e-8 ? max_k C_k : max(0, 2 - S)` -- the overlap
3575 // volume as film liquid ("the tent"). See vof_overlap_design §5.6 for what it costs.
3576 void setVofBlockOverlapDensity(bool enabled);
3577 // Per-step marker DEBRIS removal with exact volume return (vof_overlap_design §5.3, predicate
3578 // §11). Default: ON under enable_vof_block_csf, OFF otherwise (a kinematic block run is
3579 // unchanged). May be called before or after enable_vof_blocks / enable_vof_block_csf.
3580 void setVofBlockDebris(bool enabled);
3581 // vof_overlap_design §5.6: the phantom-aware capillary bound (2 rho_min while block markers
3582 // overlap). Default ON; `false` restores the pre-§5.6 bound (the ablation, review finding 5).
3584
3585
3586 // DIAGNOSTIC: the scattered block CSF face force on this rank's inner cells, component c (the
3587 // low face of each cell, the same convention `addCsfRhs` uses). This is the field the block mode
3588 // adds to the RHS; comparing it across decompositions is how a scatter defect is localised.
3589 std::vector<double> getVofBlockForce(int c);
3590
3591
3592 // The summed branch census of the last block CSF (LOCAL to this rank).
3594
3595
3596
3597 // Harmonic instead of arithmetic rho_f in the pressure projection (WO-J item 5). DEFAULT OFF and
3598 // it should stay off — read the long note in mac_pressure.hpp before turning it on: arithmetic
3599 // rho_f IS the harmonic mean of the mobility 1/rho (the series-correct choice for a normal flux)
3600 // and is what makes the discrete hydrostatic balance exact, because the momentum time term and
3601 // the face body force interpolate rho arithmetically and are NOT switched by this flag. Shipped
3602 // as a measured knob for the coefficient-coarsening question, not as an alternative scheme.
3603 void setRhoFaceHarmonic(bool on);
3604
3605
3610
3611
3618
3619
3621
3622
3624
3625
3626 bool rhoFaceHarmonic() const;
3627
3628
3629 // WO-R item 4 asked for the `1/rho_f` factor on the high-side outflow correction;
3630 // `doc/variable_density_projection.md` §4 listed its absence as a defect. WO-R measured the
3631 // factor making the outflow divergence SEVEN ORDERS WORSE and recorded the item as refuted —
3632 // correctly, for the operator as it then was. WO-R2 item 1 fixed that operator
3633 // (`CutcellMG::setOutflowCoefficient`: the Dirichlet domain-face rows no longer overwrite
3634 // `buildRhoCoeff`'s `open_f*rho0/rho_f` with the literal 1.0) and the verdict INVERTED:
3635 //
3636 // stratified duct, ratio 10, 5 steps, max|div(open u)| of the PROJECTED field
3637 // operator = raw openness operator = rho0/rho_f (WO-R2)
3638 // without the factor 8.76e-10 9.97e-05
3639 // with the factor (this knob) 9.24e-03 8.31e-10
3640 // (tests/kokkos/test_vof_bc.cpp gate F2; at ratio 1 the two are bitwise equal, 1.40e-17.)
3641 //
3642 // The mechanism is one rule: a projection correction removes the discrete divergence only if it
3643 // uses the SAME face coefficient the operator row used. Both table columns obey it; the fixed
3644 // operator is the one whose coefficient is also the PHYSICALLY right mobility at the outlet
3645 // (the low-side outlet had no consistent pairing at all before the fix — see the Nusselt film).
3646 //
3647 // DEFAULT ON since WO-R2 (`set_outflow_rho_correction(False)` is the ablation). Bitwise inert at
3648 // constant density either way (rho_f == rho0 makes the factor exactly 1), and gated on varRho.
3650
3651
3653
3654
3655
3656 // --- two-phase open boundaries (rung V-BC, WO-R) ---------------------------------------------
3657 //
3658 // Rung V2a gave the colour field one non-periodic ghost rule, `clampFill` (globally-clamped
3659 // zero-gradient). It is the right rule for a WALL and the wrong one for an INFLOW, where the
3660 // colour of the incoming fluid is a prescribed datum. Three API calls cover the three domain-BC
3661 // types; `src/vof/colour_bc.hpp` carries the rules and the reasoning, and this is the plumbing:
3662 //
3663 // set_vof_inflow(face, C) type-2 face: the colour of the incoming fluid
3664 // set_vof_inflow_profile(face, C2d) the same, per position on the face
3665 // set_vof_backflow(face, C) type-3 face: the colour of fluid that flows back IN
3666 // (a type-1 wall keeps `clampFill` = the 90 deg neutral continuation; WO-S replaces it)
3667 //
3668 // Setting any of them ARMS the rung: the advector gets the out-of-domain mask (so a boundary
3669 // donor is fluxed algebraically as `C_donor * a` rather than as a reconstructed PLIC slab — see
3670 // `wyFaceFluxBc`), the per-face boundary liquid volumes start being accumulated
3671 // (`vof_diagnostics()['inflow_volume'] / ['outflow_volume']`, and `vof_bc_volumes()` per face),
3672 // and the property ghosts of an inflow face follow the inflow colour through the closures
3673 // instead of copying the interior (item 5 below). With none of them set NOTHING changes.
3674 //
3675 // The colour of the incoming fluid may be FRACTIONAL and it then means "this fraction of the
3676 // incoming flux is liquid" — a flux statement, not a sub-cell interface position. That is
3677 // exactly what the algebraic boundary flux implements.
3678
3681 void setVofInflow(int f, double value);
3682
3683
3687 void setVofInflowProfile(int f, const std::vector<double>& prof, int nb, int nc);
3688
3689
3694 void setVofBackflow(int f, double value);
3695
3696
3697 bool vofBcActive() const;
3698
3699
3703 std::vector<double> vofBcVolumes() const;
3704
3705
3709 std::vector<double> vofBcVolumesTotal() const;
3710
3711
3713
3714
3715
3716 // nvcc requires the enclosing member of an extended device lambda to be public; these are
3717 // implementation detail (see the same note above `patchScalarDirichletFace`).
3718
3733
3734
3735
3753
3754
3755
3760
3761
3762
3766 CCField resampleFaceScalar(const std::vector<double>& prof, int nb, int nc, int face, C3 ext,
3767 int g, int& outNc);
3768
3769
3770
3774 void checkVofBcFace(int f, int wantType, const char* who);
3775
3776
3778 void vofBcArm();
3779
3780
3783
3784
3785
3786 // --- interface curvature (rung V3, WO-O) -----------------------------------------------------
3787 //
3788 // `compute_vof_curvature()` fills two registered G=2 cell fields from the CURRENT colour field:
3789 //
3790 // "kappa" kappa = 2H in units of 1/h (cell units). Multiply by 1/h for physical units.
3791 // POSITIVE for a convex blob of liquid: a sphere of liquid of radius R cells
3792 // reads +2/R. WO-P (balanced-force CSF) is the consumer.
3793 // "kappa_branch" which tier of the cascade produced it (`vof::CurvatureBranch`): 0 not
3794 // interfacial, 1 HF, 2 HF in a non-preferred direction, 3 mixed-HF fit (off by
3795 // default), 4/5 the PLIC-volumetric paraboloid fit, 6 NO estimate.
3796 //
3797 // Reading "kappa" without reading "kappa_branch" is a mistake: kappa is 0 both where there is no
3798 // interface (branch 0, correct) and where the cascade could not produce an estimate (branch 6,
3799 // which must never happen and is loud when it does). The branch field is the difference.
3800 //
3801 // The whole cascade is a pure local stencil on the colour field's g = 3 block — no reductions,
3802 // no new halo — so it is bitwise decomposition-independent by construction. See
3803 // `vof/curvature.hpp` for the cascade, its literature anchors and its measured branch shares.
3805
3806
3807 // The branch census of the last `computeVofCurvature()` — LOCAL to this rank (the driver is
3808 // MPI-free; a distributed caller sums them).
3810
3811
3814 std::vector<double> getVofCurvature();
3815
3816
3817 std::vector<double> getVofCurvatureBranch();
3818
3819
3820 // Wendland support width of the PV fallback fit, in cell units (Han et al.: 2.5 with a 5^3
3821 // stencil; 3.5 recovers first-order spurious-current convergence on a translating droplet and
3822 // 4.5 over-smooths and destroys it). Exposed for WO-P's sweep.
3824
3825
3827
3828
3829 // Tier 2b, the mixed height-position fit. OFF by default and it should stay off — see
3830 // `vof::VofCurvature::useMixedHeightFit` for the measurement that put it there.
3832
3833
3835
3836
3837
3838 // --- balanced-force surface tension (rung V4, WO-P) -------------------------------------------
3839 //
3840 // `set_surface_tension(sigma)` turns on the continuum surface force
3841 //
3842 // F_c(i) = sigma * kappa_f(i) * ( C(i) - C(i - s_c) ) / h (1)
3843 //
3844 // at every staggered velocity unknown, added to the momentum RHS at the same place, in the same
3845 // units and with the same cut-cell rescale as the incremental scheme's -(P(i) - P(i - s_c)).
3846 // `kappa_f` is the arithmetic mean of the two cells' curvatures where both carry one, the single
3847 // available one where only one does (`vof/surface_tension.hpp`).
3848 //
3849 // WHY (1) AND NOT AN INTERPOLATED CELL FORCE — the whole content of the rung. `C(i) - C(i - s_c)`
3850 // is the projection's OWN face difference. With a constant kappa the force is therefore exactly
3851 // the discrete gradient of `sigma*kappa*C`, i.e. it lies in the range of the operator the
3852 // projection inverts, so the projection removes it completely and a static drop stays at machine
3853 // zero. Face-interpolating a cell-centred `sigma*kappa*grad C` — the obvious way to reuse the
3854 // per-cell body-force machinery — produces a field that is NOT a discrete gradient of anything,
3855 // the projection cannot annihilate it, and what is left is the classical spurious current
3856 // (Francois et al. 2006; Popinet 2009). This is the momentum analogue of the three-way rho_f
3857 // consistency that makes the hydrostatic acid test exact.
3858 //
3859 // SIGN. `kappa` is positive for a convex blob of LIQUID (rung V3) and `C` is the liquid fraction,
3860 // so (1) with a plus sign gives the Young-Laplace overpressure INSIDE the drop: at equilibrium
3861 // `P = sigma*kappa*C + const`, the discrete solution of the projection, exactly.
3862 //
3863 // UNITS. `sigma` is in the solver's own units, in which the cell size is 1 (as are `rho`, `mu`
3864 // and `set_body_force`). `kappa` is in 1/h and `C(i) - C(i-s)` is `h * dC/dx`, so (1) is a force
3865 // per unit volume.
3866 //
3867 // REQUIREMENTS. VoF must be enabled (staggered only). The curvature cascade runs once per step,
3868 // at the head, from the SAME colour field the density closure sees.
3869 void setSurfaceTension(double sigma);
3870
3871
3873 double surfaceTension() const;
3874
3875
3876 // The wisp threshold above, exposed so it can be swept/ablated. Default 1e-8; 0 restores the
3877 // unguarded V3 predicate and, with surface tension on, reproduces the instability it exists for.
3878 void setVofInterfaceEps(double eps);
3879
3880
3881 double vofInterfaceEps() const;
3882
3883
3884 // Curvature admissibility clip (doc/vof_overlap_design.md §5.1, §11): |kappa| <= kappa_max on
3885 // every interfacial cell of every BLOCK marker's cascade (the single-field cascade never clips).
3886 // `kappaMaxPhys` is PHYSICAL (1/length); a negative value selects the default 1/Delta_min.
3887 // `enabled = false` restores the pre-clip block cascade verbatim. Default: ON at 1/Delta_min.
3888 void setVofBlockKappaClip(bool enabled, double kappaMaxPhys = -1.0);
3889
3890
3891 // ABLATION: 0 = the balanced-force face difference (default, the only production mode);
3892 // 1 = a cell-centred sigma*kappa*grad(C) face-interpolated like an ordinary body force. See
3893 // `addCsfRhsCellInterp`. Kept so the ctest can measure what the operator pairing is worth.
3894 void setCsfMode(int m);
3895
3896
3897 int csfMode() const;
3898
3899
3900 // Rung W2: the CSF may be formed on the BLOCKS instead of the global colour+kappa fields, in
3901 // which case there is no `kappaField_` at all. `vofBlockCsf()` is false whenever the block
3902 // container is absent (`vofBlocks_` is null unless `enable_vof_blocks` ran), so the expression
3903 // below reduces to W0's character for character on every non-block path.
3904 bool vofBlockCsf() const;
3905
3906
3907 bool csfActive() const;
3908
3909
3910
3911 // INSTRUMENT (not a configuration): stop recomputing the curvature at the head of each step and
3912 // use whatever is in the "kappa" / "kappa_branch" fields. Together with `set_vof_kappa_constant`
3913 // this isolates the BALANCED-FORCE identity from the curvature estimator — the exactness gate of
3914 // this rung, which must hold at machine zero for a curvature that is merely constant, whether or
3915 // not it is the right one.
3916 void setVofKappaFrozen(bool on);
3917
3918
3919 bool vofKappaFrozen() const;
3920
3921
3922 // INSTRUMENT: set kappa to a constant over the WHOLE block (inner + ghosts) and mark every cell's
3923 // branch as a valid estimate, then freeze it. The force (1) is then exactly the discrete gradient
3924 // of `sigma*kappa*C`, so the projection must annihilate it to round-off from ANY colour field.
3926 void setVofKappaConstant(double kappa);
3927
3928
3929
3930 // The Brackbill (1992) / Denner & van Wachem (2015) capillary time-step limit
3931 // `sqrt((rho_1 + rho_2) h^3 / (4 pi sigma))`. +inf when surface tension is off.
3932 //
3933 // The density SUM is taken from the declared phase pair when momentum consistency is on
3934 // (`enable_vof_momentum` validated it against the closure), and otherwise from `min(rho) +
3935 // max(rho)` over the current density field — an MPI_MIN/MPI_MAX pair, so it is exact and
3936 // decomposition-independent. It is the sum, not a mean: both phases oscillate.
3945 double capillaryDt();
3946
3947
3950
3951
3952 // Safety factor on the capillary limit: `step()` throws when `dt > factor * capillaryDt()`.
3953 // Default 1.0 — Denner & van Wachem measured the Brackbill prefactor to BE the stability
3954 // boundary, so there is no margin built into the formula itself. Set it huge to disable the
3955 // check, exactly as `set_vof_cfl_limit` is the escape hatch for the Weymouth-Yue cap.
3956 void setCapillaryCfl(double f);
3957
3958
3959 double capillaryCfl() const;
3960
3961
3962
3963 // Both explicit two-phase step limits at the CURRENT state, and which one binds. This is the
3964 // number WO-P asks for: at pore-scale capillary numbers the capillary dt, not the Weymouth-Yue
3965 // CFL, is expected to be the binding constraint, and that decides whether implicit surface
3966 // tension is ever worth revisiting.
3968 double courant = 0.0;
3969 double cflDt = 0.0;
3970 double capillaryDt = 0.0;
3971 double binding = 0.0;
3972 bool capillaryBinds = false;
3973 };
3974
3975 VofStepLimits vofStepLimits();
3976
3977
3978 // rho_1 + rho_2 for the capillary limit. Public because nvcc refuses an extended
3979 // __host__ __device__ lambda inside a private member function (the WO-O build note).
3981 // The min and max of the density field behind `phaseDensitySum()` (lo + hi is that sum).
3982 void phaseDensityRange(double& lo, double& hi);
3983
3984
3985 // Head-of-step curvature refresh + the capillary dt check. No-op unless surface tension is on.
3986 //
3987 // The curvature is taken from the colour field the step is ABOUT to run with — the same field
3988 // `updateProperties()` just turned into rho(C) and mu(C), i.e. C^{n+1} under momentum consistency
3989 // (the VoF stage ran at the head) and C^n without it (it runs at the tail). Either way kappa,
3990 // rho and the colour in the force (1) are the same time level, which is what the balance needs.
3991 // ISSUES sweep item 2. One step at a dt re-picked from the CURRENT state, returning the dt used.
3992 //
3993 // Why this exists as an entry point rather than as a recipe in every driver: both limits
3994 // `vof_step_limits()` reports are INSTANTANEOUS. Re-picking every ten steps -- what the free
3995 // bubble and falling film studies do, and what the gallery's rising-bubble driver copied -- is
3996 // safe only where the face field changes slowly. In a packing it is not: a throat jet can grow
3997 // max|uf| by more than 50 % inside ten steps (measured, examples/bubble-through-packing), and
3998 // the Weymouth-Yue cap is a hard throw. And `capillary_dt` is itself STATE-dependent (it reads
3999 // the density field, so the first call on a domain whose closures have not run reports the base
4000 // `set_rho` value -- measured 7.1x too large on a gas-filled pore-scale domain).
4001 //
4002 // dt = min(cfl_target * cfl_dt, capillary_cfl * capillary_dt, dt_max), from the state as it
4003 // stands at the call, then `set_dt` + `step()`. This is EXACTLY what the three gallery drivers
4004 // (rising-bubble, bubble-through-packing, trickle-flow-packing) do in Python -- and bitwise so,
4005 // because IEEE multiplication is monotone, hence `f*min(a,b) == min(f*a,f*b)`.
4006 //
4007 // `set_dt` / `step()` semantics are untouched: this is a wrapper, not a mode.
4008 double stepAdaptive(double cflTarget, double capillaryCflTarget, double dtMax);
4009
4010
4011 // ISSUES sweep item 1: the two explicit two-phase stability caps, evaluated at the head of
4012 // `step()` on the state the call STARTS from, so a rejected dt costs nothing.
4013 //
4014 // What this can and cannot pre-empt, measured rather than assumed:
4015 // * the CAPILLARY cap is a function of dt, sigma, h and the density field only, so hoisting it
4016 // is exact -- it fires here for every dt that would have made `updateVofCurvature` throw
4017 // (the one difference is that rho is the PREVIOUS step's; the authoritative check inside
4018 // `updateVofCurvature`, on this step's rho, is deliberately left in place).
4019 // * the Weymouth-Yue cap is a function of the ADVECTING face field. Under
4020 // `enable_vof_momentum` the colour rides at the head of the step, so the field checked here
4021 // IS the field the advection will use and the pre-check is exact. Without it the advection
4022 // sits at the TAIL and rides THIS step's projected output, which does not exist yet -- so the
4023 // pre-check runs on u^n (the previous step's projected field, i.e. exactly what the previous
4024 // step's advection used) and pre-empts every case where the CAP or the DT moved, but not the
4025 // case where the projection itself accelerates the field inside the step. That residual is
4026 // what `step_adaptive` (item 2) removes, by re-picking dt from the same limits every step.
4028
4029
4030 std::string capillaryThrowMessage(double cap) const;
4031
4032
4034
4035
4036
4037 // Advance the colour field one dt with the just-projected face velocities. Called by step()
4038 // immediately before advanceScalars(); exposed so a test can drive it in isolation.
4039 //
4040 // WHY HERE (the ordering, WO-J item 2). Weymouth-Yue conserves volume exactly only against a
4041 // DISCRETELY divergence-free face field: the dilation term adds H(C-1/2)*div*dt/h to every
4042 // cell's budget, interior full cells included, so the conservation floor is the advecting field's
4043 // own discrete divergence residual (WO-E finding 2 — with an analytically-but-not-discretely
4044 // solenoidal field the floor sits at O(h^2), ten orders above the gate). The only field in the
4045 // step with that property is the OUTPUT of the projection, which is exactly where
4046 // `advanceScalars` already sits and for exactly the same reason. u* is not divergence-free; u^n
4047 // is, but u^n at the top of step n+1 IS u^{n+1} at the bottom of step n, so the two placements
4048 // are the same point in the timeline and differ only in which side of `updateProperties()` they
4049 // fall on. Taking the `advanceScalars` slot therefore means the properties of step n are
4050 // rho(C^n), mu(C^n) — the same time level as the velocity base u^n, and the same segregated
4051 // contract every other multiphysics field in this solver obeys.
4052 //
4053 // HOW WO-K (rung V2b, momentum-consistent transport) DROPS IN. WO-K needs the momentum advection
4054 // to use the same geometric fluxes, the same sweep order and the SAME frozen dilation flag as
4055 // this colour advection, on half-shifted control volumes built by clipping the SAME PLIC planes
4056 // (`plicSlabVolume` is scale/offset invariant, so that is a rescale). Three structural facts make
4057 // that a local change here:
4058 // * everything WO-K must share lives inside `vofAdv_` and survives the call — the frozen flag
4059 // `cc_`, the per-sweep planes `mx_/my_/mz_/alpha_`, the face Courant numbers and the
4060 // permutation index. WO-K adds a sibling advector for rho^c u_c driven from those SAME
4061 // members rather than recomputing anything, so "sharing the fluxes" is a data-flow fact, not
4062 // a convention two call sites have to keep.
4063 // * the colour advection is ONE call (`advectVof()`), not a set of calls scattered through the
4064 // step, so moving it to the head of the predictor (where the momentum advection lives) is a
4065 // one-line move, and it moves to a velocity field — u^n — that is the same field it consumes
4066 // today, one step earlier in wall-clock and identical in content.
4067 // * the half-shifted colour field C^c is a new g=3 field on the SAME advector block, so it
4068 // needs no new bridge and no new halo: `vofFillGhosts` already carries any field on that
4069 // block, and the velocity is already embedded there (`bridgeVelocityToVof`).
4070 // What WO-K must NOT do, and what this structure keeps honest: interpolate C to build C^c. The
4071 // planes are here; clip them.
4073
4074
4075
4076 // --- momentum-consistent transport (rung V2b, WO-K) ------------------------------------------
4077 //
4078 // Turn on the transport of `rho^c u_c` on the half-shifted MAC control volumes by the SAME
4079 // geometric fluxes, the same sweep order and one frozen dilation flag as the colour advection of
4080 // the same step (`vof/momentum_advect.hpp` carries the construction and the consistency identity).
4081 //
4082 // The two phase densities are required EXPLICITLY rather than read off the closure: the momentum
4083 // flux is `rho_g (a - F) + rho_l F` with `F` the geometric LIQUID flux, so the scheme needs to
4084 // know which density each phase carries, and inferring that from a `rho` field would be a silent
4085 // dependence on the closure kind. `enableVofMomentum` validates the pair against the registered
4086 // density field on the spot (see `checkVofPhaseDensities`), so a mismatched call fails loudly.
4087 //
4088 // WHY THE ADVECTION MOVES TO THE HEAD OF THE STEP. WO-J placed `advectVof()` in the
4089 // `advanceScalars()` slot because Weymouth-Yue needs a discretely divergence-free advecting field
4090 // and the projection's output is the only one in the step. With momentum consistency the SAME
4091 // fluxes must also carry the momentum, and the momentum advection has to happen before the
4092 // predictor builds its RHS — so the whole VoF stage moves to the top of `step()`, where the
4093 // advecting field is `u^n`, i.e. the PREVIOUS step's projected output. That is the same field, one
4094 // step earlier in wall-clock: `u^{n+1}` at the bottom of step n IS `u^n` at the top of step n+1
4095 // (WO-J's own note). The one real consequence is at step 0, where `u^0` is whatever the user set
4096 // and is only divergence-free if the user made it so; every gate in this rung starts from rest or
4097 // from a uniform field, both exactly divergence-free.
4098 //
4099 // With this placement `updateProperties()` then sees `C^{n+1}`, so the step runs with
4100 // `rho(C^{n+1})`, `mu(C^{n+1})` — the density of the time level the momentum is being advanced TO,
4101 // which is what the conservative form `rho^{n+1} u^{n+1} = rho^n u^n - div(rho u u) dt + ...`
4102 // wants.
4103 //
4104 // WHAT IS *NOT* CHANGED, DELIBERATELY: the momentum time-term face density, the face body force
4105 // and the projection coefficient all keep the arithmetic face mean `1/2 (rho(i) + rho(i-s_c))`.
4106 // That three-way agreement is what makes discrete hydrostatic balance exact
4107 // (`doc/variable_density_projection.md` §1) and it is a validated kernel. Momentum consistency
4108 // enters as the ADVECTIVE base velocity `u^adv` replacing `u^n - dt*adv(u^n)`: the momentum
4109 // equation solved is `rho_f (u* - u^adv)/dt = -grad p + visc + f`, i.e. exactly the conservative
4110 // update divided through by the face density. Swapping the time term to the clipped `rho^c`
4111 // instead would break the hydrostatic acid test at O(d rho) — measured and recorded in the WO-K
4112 // findings.
4120 void enableVofMomentum(double rhoGasPhys, double rhoLiquidPhys);
4121
4122
4123 // The registered "rho" closure on the colour "C" evaluated at C = 0 and C = 1, in PHYSICAL
4124 // units (the parameters the caller gave). False when there is none, or when the last closure
4125 // writing "rho" is not a function of C alone (another input, a second input, a non-mix kind).
4126 bool vofRhoClosureEnds(double& rho0Phys, double& rho1Phys) const;
4127
4128
4130
4131
4132 // Floor on rho^c in the recovery divide u = (rho^c u)/rho^c, as a FRACTION of min(rho_g, rho_l)
4133 // (default 1e-6). rho^c leaves [rho_g, rho_l] only through a wisp in the half-shifted colour, and
4134 // driving it to zero would need C^c ~ -1/(ratio-1); the floor is a guard, not a model, and
4135 // `vof_momentum_diagnostics()` reports how many control volumes it actually touched.
4136 void setVofRhoFloorFrac(double f);
4137
4138
4139 double vofRhoFloorFrac() const;
4140
4141
4142 double vofRhoFloor() const;
4143
4144
4145 // The transported face velocity of the VoF momentum flux (doc/vof_momentum_second_order.md):
4146 // 'upwind' (donor cell, first order), 'muscl_mixed' (MinMod of the mixed CV velocity; converges
4147 // to a wrong limit at high density ratio), 'muscl_mixed_capped' (that slope times the mass-aware
4148 // cap; the diagnosis ablation) and 'muscl_phase' (per-phase interface-biased MC slopes + the cap:
4149 // second order, bounded at any ratio; the DEFAULT). Any other name throws std::invalid_argument.
4150 void setVofMomentumScheme(const std::string& name);
4151 std::string vofMomentumScheme() const;
4152
4153
4154 // The former spelling of setVofMomentumScheme: true = 'muscl_mixed', false = 'upwind'.
4155 void setVofMomentumMuscl(bool on);
4156
4157
4158 // Ablation: the literal reading of "the same frozen dilation flag" (the PRESSURE-cell flag on the
4159 // shifted control volume instead of its structural analogue).
4161
4162
4163 // Ablation: drop the Weymouth flux clamp on the shifted control volume. With it off the
4164 // half-shifted colour leaves [0,1] by O(a^2) and rho^c goes NEGATIVE at high ratio — the
4165 // measurement that the clamp is a necessity, not a habit. See vof/momentum_advect.hpp point 3.
4166 void setVofFluxClamp(bool on);
4167
4168
4170
4171
4172 // The recovered advected velocity of component c on the inner cells (the momentum RHS's time
4173 // base). Exposed so a test can gate the uniform-velocity identity on the advection ALONE, with
4174 // the projection and the momentum solve out of the picture.
4175 std::vector<double> getVofAdvectedVelocity(int c);
4176
4177
4178
4179 // The coupled colour + momentum advection. Called from the head of step() when momentum
4180 // consistency is on; exposed so a test can drive it in isolation.
4182
4183
4184
4185
4186 // --- Phase change (Part II, rungs P0/P1 — WO-P01) --------------------------------------------
4187 //
4188 // The kernel set of `suite/docs/VOF_PLAN.md` §9 in its planar form, following Boyd & Ling (2023)
4189 // and Malan et al. (2021): a mass flux `mdot` on interfacial cells (prescribed at P0, from
4190 // one-sided pure-cell temperature gradients at P1), interface regression by a PLIC PLANE SHIFT
4191 // with exact clip-and-redistribute, and the volumetric divergence source shifted into the
4192 // compact pure-gas layer behind the interface so the interfacial cell's own face velocity stays
4193 // the LIQUID velocity and Weymouth-Yue advects the colour with a field it is entitled to.
4194 // Container-free geometry/physics lives in `vof/phase_change.hpp`; this is the block walk.
4195 //
4196 // ORDER WITHIN step() (and why). `phaseChangeStep()` runs at the HEAD of the step, before
4197 // `updateProperties()`:
4198 // 1. `mdot`, the PLIC area `A_G` and the unit normal `n` are built from (C^n, T^n);
4199 // 2. the divergence source is deposited into pure gas cells (read by `project()`);
4200 // 3. the regression is applied to the SAME C^n the planes were reconstructed from.
4201 // Doing the regression here rather than after the advection is what keeps the plane, the area
4202 // and the colour it is subtracted from at ONE time level; `updateProperties()` then sees the
4203 // post-regression colour, so rho(C) and the momentum/projection coefficients are consistent with
4204 // the interface the step actually runs with. The colour advection keeps its WO-J slot at the
4205 // bottom of the step (it needs the projected, discretely divergence-free face field).
4206 //
4207 // SCOPE at this rung, all enforced with a message: staggered grid, no immersed solid (the
4208 // solid-clipped flux polygons and the cut-cell source deposit are a later rung), and not
4209 // composable with `enable_vof_momentum` (both own the head of the step and the momentum flux
4210 // would have to carry the phase-change mass transfer as well).
4212 double mdotMin = 0.0, mdotMax = 0.0, mdotMean = 0.0;
4214 double removedVolume = 0.0;
4215 double redistributed = 0.0;
4216 long deficitCells = 0;
4217 long excessCells = 0;
4218 double sourceSum = 0.0;
4219 long sourceCells = 0;
4220 long fallbackCells = 0;
4221 double unresolved = 0.0;
4222 double minC = 0.0, maxC = 0.0;
4223 double area = 0.0;
4224 double bandDiv = 0.0;
4225 double Tmin = 0.0, Tmax = 0.0;
4226 long areaHf = 0;
4227 long areaPv = 0;
4228 long areaNone = 0;
4229 double areaOrphan = 0.0;
4231 double mdotFit = 0.0;
4233 double qOperator = 0.0;
4235 double qOrphan = 0.0;
4237 };
4238
4261 double hOpen = 0.0;
4262 double hOpenNew = 0.0;
4263 double hLiquid = 0.0;
4264 double hMasked = 0.0;
4265 double dEoverwrite = 0.0;
4267 double dEoverwriteNew = 0.0;
4268 double eEnter = 0.0;
4269 double eLeave = 0.0;
4270 double qGfm = 0.0;
4271 double qBehind = 0.0;
4274 long nEnterLiquid = 0;
4275 long nEnterGas = 0;
4276 long nLeaveLiquid = 0;
4277 long nLeaveGas = 0;
4278 long nMasked = 0;
4279 long calls = 0;
4280 };
4281
4289 void enablePhaseChange(double rhoG, double rhoL, double hlv);
4290
4291
4293
4294
4295
4299 void setMassFluxUniform(double v);
4300
4301
4304 void setMassFlux(const std::vector<double>& v);
4305
4306
4313 void setPhaseChangeThermal(const std::string& tname, double Tsat, double kg, double kl,
4314 double Rint);
4315
4316
4318
4319
4320
4321 // --- WO-P23 (rungs P2/P3) --------------------------------------------------------------------
4322
4336
4337
4339
4340
4341
4348
4349
4351
4352
4353
4379 void setPhaseChangeArea(int mode);
4380
4381
4382 int phaseChangeArea() const;
4383
4384
4385
4391
4392
4393
4397
4398
4399
4402
4403
4404
4415 void setPhaseChangeEnergy(double rcpGas, double rcpLiquid);
4416
4417
4421
4422
4424
4425
4427
4428
4429 bool phaseChangeEnergy() const;
4430
4431
4432
4437
4438
4439 bool phaseChangeBudget() const;
4440
4441
4442
4446
4447
4449
4450
4451
4458 void setPhaseChangeFitCurvature(double kappa);
4459
4460
4462
4463
4464
4485
4486
4488
4489
4490
4494
4495
4497
4498
4499
4502 void setPhaseChangeGfmOrder(int order);
4503
4504
4506
4507
4508
4514
4515
4517
4518
4529
4530
4532
4533
4535 double phaseChangeQOperator() const;
4536
4537
4538 double phaseChangeQOrphan() const;
4539
4540
4544
4545
4546 double phaseChangeCarryLost() const;
4547
4548
4551 PhaseChangeBudget phaseChangeBudgetValues() const;
4552
4553
4554
4566
4567
4568
4571
4572
4573
4579
4580
4581
4586 void requireScalesPinned(const char* who, bool needRho) const;
4587
4588
4589
4592 double closureTargetToInt(const std::string& target) const;
4593
4594
4595
4599
4600
4603 void closureUnitsNotice(const std::string& target) const;
4604
4605
4606
4609 double pcLedgerEnergyToPhys() const;
4610
4611
4612
4617
4618
4619
4626 void setDivergenceSource(const std::vector<double>& v);
4627
4628
4630
4631
4632
4641 void setDivergenceSink(const std::vector<double>& w);
4642
4643
4645
4646
4647
4652 void applyPhaseChange(double dtPhysArg);
4653
4654
4655
4659
4660
4661
4662 PhaseChangeDiagnostics phaseChangeDiagnostics();
4663
4664
4665
4666 // nvcc requires members holding extended device lambdas to be public.
4667
4675 // pcBuildInterface() phase (WO-HO), public for its device lambda: the min/max of mdot over the
4676 // interfacial cells into pcDiag_ (zeros when there are none).
4677 void pcMdotExtrema(long nIface);
4678
4679
4680
4687
4688
4689
4697 void pcRegress(double dt);
4698
4699
4700
4711
4712
4713
4729
4730
4731
4733
4734
4735
4739
4740
4741
4774
4775
4776
4780
4781
4782
4788
4789
4790
4800
4801
4802
4806
4807
4808
4822 double pcEffInterfaceEps() const;
4823
4824
4829 double pcEffPureEps() const;
4830
4831
4832
4833 void requirePhaseChange(const char* who) const;
4834
4835
4836 ScalarField& scalarField(const std::string& name);
4837
4838
4841 void scalarDirichletMask(const std::string& name);
4842
4843
4844
4845 // --- Property closures + per-cell body force ------------------------------------------------
4846 // Register a property/force closure. target: a registered field name — a material property
4847 // ("mu"/"rho"/…) or a body-force component ("force_x"/"force_y"/"force_z"). kind: LinearMix /
4848 // BoussinesqForce / ArrheniusMu. in0/in1: input field names (in1 "" if unused). params: up to 4
4849 // doubles (meaning per kind — property_closures.hpp). Applied at the top of step() in
4850 // registration order. Targeting a force component turns on the per-cell body-force RHS path.
4851 // UNITS: the inputs are taken as UNSCALED fields (a phase fraction, a temperature, a
4852 // concentration — never rescaled), so the output's dimension sits in the parameters: on a
4853 // target "rho", "mu" or "force_a" the parameters carrying it (all of LinearMix's p0..p2,
4854 // Boussinesq's rho0, Arrhenius' mu_ref, a table's ys) are PHYSICAL and convert with that target's
4855 // factor (`closureTargetToInt`); the rest enter only as a product with that one (Boussinesq's
4856 // g*beta) or against the unscaled input (T0, B, Tref, xs) and stay as given. Any other target
4857 // is in that field's INTERNAL units (a stderr notice says so under a physical domain).
4858 void setPropertyModel(const std::string& target, ClosureKind kind, const std::string& in0,
4859 const std::string& in1, const std::vector<double>& params);
4860
4861
4862 // Enable/disable variable density: binds the "rho" field (creating it seeded with the scalar rho_
4863 // if absent) into the momentum time term, the advection weight, and the pressure projection
4864 // (face coefficient open/rho_f + 1/rho_f correction). rho_ (set_rho) becomes the REFERENCE
4865 // density rho0 of the projection scaling — a uniform rho field == rho_ reduces exactly to the
4866 // constant solver. Escape hatch: set_field("rho", arr) + set_density_mode(True); or a closure
4867 // targeting "rho" (e.g. rho = LinearMix of a transported phase fraction) enables it
4868 // automatically. Staggered grid only (v1); the velocity multigrid (scalar-coefficient) is
4869 // disabled.
4870 // Rung V8 lifted the collocated throw. On `SolverColocated` the variable-density path is the ABC
4871 // approximate projection with the face coefficient `c_f = o_f rho0/rho_f`, the MOMENTUM-weighted
4872 // centre-to-face map in the constraint, `projectCorrectVar` on the FACE field, and a cell
4873 // correction that is the face-to-cell reconstruction of the face corrections (never a
4874 // cell-centred grad(phi)/rho_c); the pressure and every force enter the implicit predictor as
4875 // the matching face integral (doc/collocated_varrho_forces.md). Scope: ALL-FLUID
4876 // (`set_pressure_geometry`) — an immersed solid still throws, at the first `step()`, and so do
4877 // the ghost projection and `set_rho_face_harmonic` (see requireCollocatedFaceForceScope).
4878 // Momentum consistency (`enable_vof_momentum`) is NOT in this rung: the collocated construction
4879 // needs Favre face states, so the collocated two-phase path is rated to density ratio ~10 for
4880 // cases WITH MOTION (WO-V3: a translating drop throws the VoF CFL cap at ratio 100 and 1000); a
4881 // high-ratio case at REST — hydrostatic, stationary droplet — is exact, measured at ratio 1000.
4882 void setDensityMode(bool variable);
4883
4884
4885 // Enable/disable the volume-averaged (porous) continuity for unresolved CFD-DEM: the projection
4886 // enforces d(eps)/dt + div(eps u) = 0 instead of div(u)=0, so the velocity is NOT solenoidal
4887 // where the void fraction changes. Binds the "eps" field (void fraction from the particle
4888 // deposition; created seeded to 1 if absent). Staggered-only. The coupling deposits eps each step
4889 // BEFORE step().
4890 // Has the cut-cell pressure operator been built (set_solid / set_pressure_geometry)? The porous
4891 // projection requires it — project() throws otherwise; the coupling driver queries this to
4892 // auto-install an all-fluid geometry.
4894
4895
4896 void setPorousContinuity(bool on);
4897
4898
4899 // Reseed eps^n = eps^{n+1} so d(eps)/dt = 0 this step. Call after the FIRST void-fraction
4900 // deposition (the "eps" field starts empty, so without this step 0 sees a spurious d(eps)/dt from
4901 // 0 -> eps).
4903
4904
4905 // Include (default) or drop the d(eps)/dt source in the porous projection RHS. Dropping it
4906 // enforces div(eps u)=0 — useful when eps is a bare per-cell particle deposit whose
4907 // time-derivative is too jagged and drives the eps-weighted pressure solve unstable.
4908 void setPorousDepsDt(bool on);
4909
4910
4912
4913
4914 // Pressure under-relaxation factor omega_p in (0,1] (MFIX-style); 1.0 = off (default).
4916
4917
4918 // Enable/disable variable-coefficient momentum (variable viscosity). variable=true binds the "mu"
4919 // field (creating it, seeded with the current scalar mu, if absent) and forces the stencil solve
4920 // path. harmonic selects the harmonic face mean (continuous shear stress across a viscosity jump)
4921 // vs arithmetic. Escape hatch: set_field("mu", arr) then set_property_mode(True).
4922 void setPropertyMode(bool variable, bool harmonic);
4923
4924
4925 // Rotational-pressure treatment under variable viscosity. The Timmermans rotational term
4926 // P += (rho/dt)phi - mu*div(u*) is only valid for HOMOGENEOUS viscosity (Deteix & Yakoubi, Appl.
4927 // Math. Lett. 2018 / arXiv:1902.05643): with spatially varying mu the pointwise term is no longer
4928 // the gradient part of the viscous stress, and the accumulated inconsistency destabilises the
4929 // incremental scheme at strong contrast (observed: 10x jump + harmonic faces -> divergence).
4930 // Modes (the incremental predictor -grad(P^n) and P accumulation are kept in ALL of them — that
4931 // is what enables large-dt / steady-Stokes stepping):
4932 // 0 "min" (default): rotational coefficient chi*mu_min — a CONSTANT dominated by the true
4933 // local
4934 // dissipation everywhere (mu_min <= mu(x)), so the constant-viscosity stability theory
4935 // carries over; reduces EXACTLY to the validated scheme when mu is uniform.
4936 // 1 "full": chi*mu(i) pointwise — better pressure consistency at MILD contrast; not stable at
4937 // strong contrast (user's responsibility).
4938 // 2 "off" : plain incremental (no rotational term) — unconditionally stable, keeps the
4939 // artificial
4940 // pressure Neumann layer of the non-rotational scheme.
4941 // The fully consistent variable-viscosity correction (shear-rate projection: an extra Poisson
4942 // solve for psi with rhs div(div(2 nu D(u)))) is deferred.
4943 void setVariableRotational(int mode, double chi);
4944
4945
4946 // Tabulated property: out = piecewise-linear interp of (xs, ys) at the input field (xs
4947 // ascending). Units as setPropertyModel: ys in the target's physical units, xs in the input's.
4948 void setPropertyTable(const std::string& target, const std::string& in0,
4949 const std::vector<double>& xs, const std::vector<double>& ys);
4950
4951
4952 // Apply all closures (also called at the top of step()). Exposed for testing.
4954
4955
4956 // Allocate + register the per-cell body-force fields ("force_x/y/z") and route them into the
4957 // momentum RHS, for an EXTERNAL writer (CFD-DEM feedback) to fill directly via field_view — no
4958 // closure needed. buildRhsForced then adds them each step (they persist; the writer overwrites).
4960
4961
4962 // Implicit (semi-implicit) linear drag: a per-cell coefficient field "drag_beta" is added to the
4963 // momentum diagonal each step, so a drag source −β(u − u_p) is treated implicitly (the fluid
4964 // solve becomes (ρ/dt + β)u = … + β u_p). The drag TARGET β·u_p goes into the force_x/y/z fields
4965 // (the RHS). Unconditionally stable for any β (unlike an explicit −β u force, which diverges for
4966 // the stiff β of a dense particle bed). The external writer (CFD-DEM) fills "drag_beta" +
4967 // "force_*" via field_view; enableDrag() allocates them and turns the diagonal path on.
4969
4970
4971 // Porous + implicit drag: the drag-relaxation w_f=idt/(idt+beta) makes the pressure coefficient
4972 // high-ratio (~1 in the freeboard, ->0 in the dense bed). Chebyshev diverges on it; the algebraic
4973 // GraphAMG coarse solve + PCG is robust. Applied whenever BOTH porous_ and hasDrag_ are on
4974 // (either set second). An explicit set_pressure_* afterwards still wins.
4976
4977
4978 // Add the drag coefficient at the unknown's location, Grid::atVelocity(beta) (face mean on the
4979 // MAC grid, cell value collocated), to the momentum diagonal of component c. Called after
4980 // each stencil (re)build when hasDrag_. All-fluid (rscale==1) is exact; the drag×cut-cell-IBM
4981 // interaction (rscale≠1) is untested (documented).
4982 void addDragDiagonal(int c);
4983
4984
4985
4986 private:
4987 // === dynamic load balancing: making EVERY per-block allocation follow the new block ===========
4988 //
4989 // `allocateBlock` re-creates the buffers it names explicitly and re-`adopt`s the five aliased
4990 // registry entries ("u"/"v"/"w"/"p"/"sdf"). Everything the solver has grown SINCE construction
4991 // does not follow it:
4992 //
4993 // 1. the FieldSet's OWN storage (`FieldSet::add` — every transported scalar, every property /
4994 // body-force closure target, VoF's "C" / "kappa" / "kappa_branch", the phase-change fields);
4995 // 2. the member handles that ALIAS one of those records (`cField_`, `rhoField_`, `muField_`,
4996 // `epsField_`, `cellForce_[]`, `ScalarField::c`, every `Closure`'s in/out views);
4997 // 3. the lazily-allocated per-block scratch (`vofCs_`, `uAdv_`, the phase-change and porous
4998 // work arrays, the g=1 MG-bridge coefficients, …), each allocated at the `n_` / `n1_` of
4999 // whichever block was current when its feature was first switched on.
5000 //
5001 // `redistribute` then memcpy'd the NEW block's padded extent into (1)'s OLD allocation: measured
5002 // by AddressSanitizer as a 184320-byte WRITE into a 115328-byte Kokkos HostSpace region at
5003 // `scatterPadded`, i.e. exactly the `free(): invalid pointer` /
5004 // `malloc(): unsorted double linked list corrupted` that made `rebalance_by_weights` unusable on
5005 // any run owning a registry field. (2) and (3) are the same defect one step later — a stale view
5006 // indexed with the NEW `nx_`/`ny_`/`nz_`.
5007 //
5008 // `resizeForBlock()` is the root fix and runs the three passes in this order, immediately after
5009 // `allocateBlock` and BEFORE `initMpi` (which rebuilds the VoF block and writes `cField_`).
5010 void resizeForBlock();
5011
5012
5013 // Pass 1: the FieldSet's own storage. Fresh, zero-initialised, same name/ghost/centering; the
5014 // migrated data is scattered back into it by `redistribute` step 4. Aliased records
5015 // (`ownStorage == false`) are left alone — `allocateBlock` has just re-adopted them.
5016 void reallocOwnedFields();
5017
5018
5019 // Pass 2: re-resolve every member handle that aliases a registry record. A handle whose record
5020 // does not exist is left as it is (the feature was never switched on, so the handle is empty).
5021 void rebindFieldAliases();
5022
5023
5024 // Pass 3: the lazily-allocated per-block scratch. A view that was never allocated (extent 0)
5025 // STAYS unallocated — "inert until its feature is enabled" is load-bearing all over this class
5026 // (every consumer branches on `extent(0)`), so resizing an empty view would switch a feature on.
5027 // Views that carry state across a step are re-derived below rather than left zeroed.
5028 static void resizeIfAllocated(CCField& f, const char* label, std::size_t n);
5029
5030
5031 void resizeBlockScratch();
5032
5033
5034 // Resolve a closure target to a registered buffer. A force component allocates ALL three
5035 // cellForce_ slots (buildRhsForced reads every component) and enables the body-force RHS path.
5036 CCField ensureTarget(const std::string& name);
5037
5038
5039 void ensureCellForceAll();
5040
5041
5042 // Ghost fill for a scalar: periodic (single-rank) / MPI halo base, then override any domain
5043 // Dirichlet/Neumann faces.
5044 void scalarFillGhosts(ScalarField& sc);
5045
5046
5047 // Overwrite the ghost band on each Dirichlet/Neumann domain face (both layers, for the ±2
5048 // advection reach). Distributed: a rank applies a face's BC iff its block TOUCHES that global
5049 // face. The halo fill runs first (and may periodic-wrap those ghosts); the BC overwrite wins,
5050 // exactly matching the single-rank fill-then-BC order. Cross-rank ghost CORNERS on a BC face
5051 // keep their exchanged (pre-BC) values, but the scalar stencils only read axis-aligned ghosts
5052 // (7-point diffusion + straight ±2 advection reach), so those corners are never consumed.
5053 void applyScalarBc(ScalarField& sc);
5054
5055 // The ADVECTIVE inflow state on the frozen c^n (cOld): at a scalar-Dirichlet face that is also a
5056 // velocity INFLOW face (type 2 with a normal velocity or a profile -- the flux-openness rule),
5057 // both ghost layers of cOld take the prescribed value v, so the upwind reconstruction of the
5058 // inflow face returns v and the inflow carries u_n * v. The reflection 2v - c_inner that c's own
5059 // ghost carries is right for the DIFFUSION row (face value v by linear interpolation) and wrong
5060 // for upwinding: it carried u_n (2v - c_inner), +0.5 U dt of excess on a plug's first step.
5061 // Walls (no normal velocity) keep the reflection. doc/uf_outlet_fix.md section B.
5062 void scalarInflowGhosts(ScalarField& sc);
5063
5064
5065 // Does this rank's block touch global domain face f (always true single-rank)?
5066 bool touchesGlobalFace(int f) const;
5067
5068
5069 // Re-open the diffusion face at a Dirichlet domain boundary: set_domain_bc closes the boundary
5070 // openness (ox_=0), which correctly makes Neumann/adiabatic walls zero-flux but would also cut a
5071 // Dirichlet wall's heat path. For each Dirichlet face, restore the face coefficient (band = -D,
5072 // A_C += D); the ghost carries 2*value - inner so the row is the standard Dirichlet operator.
5075 void applyScalarBcStencilVar(ScalarField& sc);
5076
5077
5078 void applyScalarBcStencil(ScalarField& sc);
5079
5080
5081 // nvcc requires member functions that contain extended (device) lambdas to be PUBLIC — the
5082 // OpenMP/host build accepts them private, so the breakage only shows on the CUDA backend.
5083 public:
5084 void patchScalarDirichletFaceVar(CCField AC, CCField band, CCField kc, int a, int side);
5085
5086
5087 void patchScalarDirichletFace(CCField AC, CCField band, double Din, int a, int side);
5088
5089
5090 void applyScalarBcFace(CCField c, int a, int side, int type, double val, bool edges = false);
5091
5092
5093
5094 private:
5095 int nx_, ny_, nz_;
5096 C3 e_, e1_;
5097 std::size_t n_, n1_;
5098 double rho_ = 1.0, mu_ = 0.1, dt_ = 50.0; // INTERNAL (index-unit) values; see UnitScales
5099 UnitScales u_; // the metric + reference scales (all 1 in cell units)
5100 // The caller's own values, kept verbatim so refreshUnitDerived() can re-derive the internal
5101 // ones in any call order. Equal to the internal ones on the cell-unit path.
5102 double rhoPhys_ = 1.0, muPhys_ = 0.1, dtPhys_ = 50.0;
5103 std::array<double, 3> fPhys_{{0, 0, 0}};
5104 double sigmaPhys_ = 0.0;
5105 double slipPhys_ = 0.0;
5106 double bcVelPhys_[6][3] = {};
5107 std::array<double, 3> f_{{0, 0, 0}};
5108 // setSuperficialVelocity: the axis (-1 = off), the target in the CALLER's units (converted at
5109 // each application, so any set_rho/set_dt order works), and the device-resident shift of the
5110 // last application (internal units) -- a 0-d View so the single-rank path needs no host round
5111 // trip.
5112 int superficialAxis_ = -1;
5113 double superficialVelPhys_ = 0.0;
5114 Kokkos::View<double, CCMem> superficialShift_;
5115 int velIters_ = 200, presIters_ = 20;
5116 double velTol_ = 0.0; // momentum tolerance stop (0 = legacy fixed-count loop)
5117 int velMinIters_ = 2;
5118 long lastMomentumSweeps_ = 0; // sweeps actually run last step (summed over components/Picard)
5119 // Residual-based momentum stop (setVelocityResidualTolerance): < 0 follows the pressure rtol
5120 // (DEFAULT since 2026-09-02), 0 = the update criterion, > 0 = a fixed tolerance.
5121 double velResTol_ = -1.0;
5122 double lastMomentumResid_ = -1.0; // max_c max|r|/max|b| at exit (residual mode)
5123 CCField velRes_; // scratch for the stencil-path residual
5124 CCField chebD_; // scratch: the Chebyshev search direction (see chebSolveComp)
5125 double lastAxNorm_ = 0.0; // max|A u| of the last residual evaluation (scale)
5126 double lastBNorm_ = 0.0; // max|b| of the last stencil-functor residual (F-1)
5127 int pcgMaxit_ = 500;
5128 double pcgRtol_ = 1e-10; // cut-cell pressure MG-PCG
5129 bool useChebyshev_ = false,
5130 chebBoundsSet_ = false; // Chebyshev pressure driver (set_pressure_chebyshev)
5131 bool useFcg_ = false; // flexible-CG pressure driver (set_pressure_fcg); OFF by default,
5132 // so the shipped MG-PCG path is untouched (zp1_ is not allocated)
5133 CCField zp1_; // FCG's extra scratch: allocated lazily at the first FCG solve
5134 int chebMaxit_ = 120;
5135 double chebRtol_ = 1e-9, chebA_ = 0.0, chebB_ = 0.0;
5136 // D3 (§5.13): may the next main-bound re-estimate start warm? Set by a coefficient rebuild that
5137 // drops VALID bounds, cleared by every structural invalidation (driver, density, porous setters).
5138 bool chebWarmOk_ = false;
5139 long chebColdRestarts_ = 0; // guard firings (numPressureChebyshevRestarts)
5140 long chebGrowthTrips_ = 0; // cold-bounds growth-guard firings (numPressureChebyshevGrowthTrips)
5141 bool chebGrowthWarned_ = false; // the first growth-guard firing prints one stderr notice
5142 // The bounds ratchet (DECISIONS_GPU.log 2026-10-30 "A3 finish" (b)): the bracketed lambda_max
5143 // of the last growth-guard re-estimate (0 = none). Every later main estimate uses
5144 // max(estimate, floor), so a trip's bounds persist through the warm re-estimates of the
5145 // coefficient rebuilds; a structural invalidation (chebWarmOk_ cleared: the driver, density,
5146 // porous and V-cycle setters) drops it. bfpLmaxFloor_: the same for the balanced-force
5147 // pre-projection's own bounds, dropped when they are re-estimated from scratch.
5148 double chebLmaxFloor_ = 0.0, bfpLmaxFloor_ = 0.0;
5149 // Q18: the CG exit check. A solve is UNCONVERGED when its true residual exceeds
5150 // max(kCgGuardFactor * rtol, kCgGuardFloor) * r0. Measured (z-extruded tilted two-layer VoF box,
5151 // 16x16x4, walls in x/y, ratios 1..1e4; validation/highratio/q18): healthy exits sit at <= 0.9 x
5152 // rtol*r0 for rtol 1e-8, the wrong fields at 3e8..3e10 x; at rtol 1e-13 the TRUE residual of a
5153 // correct field (divergence at the Chebyshev level) floors at 2.6e-14 (ratio 1) .. 3.4e-11
5154 // (ratio 1e3) relative -- round-off, which a factor alone would report. The floor keeps such
5155 // solves silent: a true residual below 1e-8 * r0 is not a wrong field.
5156 static constexpr double kCgGuardFactor = 10.0;
5157 static constexpr double kCgGuardFloor = 1e-8;
5158 double lastPressureTrueResidual_ = 0.0;
5159 long numPressureUnconvergedSolves_ = 0;
5160 long cgGuardNextReport_ = 1; // the next count at which the warning prints (1, 10, 100, ...)
5161 bool cgContrastPending_ = false; // an explicit PCG/FCG selection awaits its contrast notice
5162 CCField chebX0_; // the solve's starting iterate under the pressure warm start
5163 int nLevels_ = 0; // pressure-MG depth, 0 = AUTO (doc/mg_depth_policy.md §3.1)
5164 bool pressGraphAmg_ = false;
5165 // Coarse-solve policy: -1 auto (DEFAULT — agglomerate when the coarsest grid exceeds
5166 // setPressureBottomExtent cells on any axis; identical to the smoothed bottom otherwise),
5167 // 0 smoothed, 1 always. Auto became the default 2026-08-13 after the IBM-path anomaly was
5168 // fixed (per-fluid-component null-space projection; see ../docs/DECOMPOSITION_AND_MULTIGRID.md).
5169 int pressAgglomMode_ = -1;
5170 long lastPressureIters_ = 0;
5171 bool lastPressureFailed_ = false; // ISSUES sweep item 6
5172 // Balanced-force projection (doc/collocated_varrho_forces.md §4.6). `Pb_` (the registered G=2
5173 // field "p_balanced", so redistribute carries it) and `pb1_` (g=1 scratch) exist only once the
5174 // option has run; `coeffBuiltThisStep_` lets project() skip the variable-rho coefficient rebuild
5175 // the balanced-force stage already did this step (rho is frozen within a step).
5176 bool bfpSet_ = false, bfpOn_ = false;
5177 bool bfpOpenNotice_ = false; // the "V8 default resolved OFF: open face" notice, once
5178 CCField Pb_, pb1_;
5179 // Is Pb_ the balanced part of the CURRENT P_ (a valid split)? True for a fresh solver (P = Pb =
5180 // 0); cleared by a step with the option off (P moved without Pb) and by a set_field of "p" or
5181 // "p_balanced" alone (a restart that restored one without the other); set again by every
5182 // balanced-force stage. An invalid split is RE-SPLIT (Pb := X, P unchanged), never P += X - Pb:
5183 // that would add the balanced pressure a second time (doc/collocated_varrho_forces.md §4.6.2).
5184 bool pbValid_ = true;
5185 bool pWritten_ = false, pbWritten_ = false; // set_field("p" / "p_balanced") since the last step
5186 // The pre-projection's OWN Chebyshev bounds (doc §4.8): estimated once, on its own right-hand
5187 // side, and KEPT across the per-step variable-rho coefficient refresh (which invalidates only
5188 // the MAIN bounds, chebBoundsSet_). Re-estimated after a structural operator change (the driver,
5189 // density, porous and rho-face setters, a pressure-MG rebuild) or when a pre-projection
5190 // Chebyshev solve diverges (it ran to the cap and its residual grew). Never shared with the
5191 // main solve, whose bound logic is unchanged.
5192 double bfpChebA_ = 0.0, bfpChebB_ = 0.0;
5193 bool bfpChebSet_ = false;
5194 // A failed pre-projection (a driver breakdown flag, or a non-finite X): P and P_b are kept.
5195 bool lastBalancedForceFailed_ = false;
5196 long balancedForceFailures_ = 0;
5197 bool bfpFailWarned_ = false;
5198 bool coeffBuiltThisStep_ = false;
5199 bool prefactorHoist_ = true; // X (diagnostics switch, setPressurePrefactorHoist)
5200 long lastBalancedForceIters_ = 0;
5201 // The collocated face field with every OPEN (outflow) domain face replaced by its
5202 // zero-gradient extrapolation -- see buildOpenFaceField(). Allocated on first use and only
5203 // when there IS an outflow; `openFaceView` falls through to uf_/vf_/wf_ otherwise.
5204 CCField ufOpen_[3];
5205 // ISSUES sweep item 5: has the collocated MAC face field ever been built (by a projection
5206 // or by `seedFaceFieldFromCells`)? Meaningless on the staggered grid.
5207 bool faceFieldValid_ = false;
5208 // ISSUES sweep items 1+2: `step_adaptive` has just evaluated the two limits on this state, so
5209 // `step()`'s head-of-step pre-check can skip its own (identical) evaluation. One-shot.
5210 bool vofPrecheckDone_ = false;
5211 CutcellMG mg_;
5212 // --- multi-rank (MPI) state, gated (single-GPU module never links MPI -> byte-identical when
5213 // off) ---
5214 // rung W0 (WO-W0): the per-bubble block container. Null unless enable_vof_blocks ran, so
5215 // every existing VoF path is byte-identical.
5216 std::shared_ptr<vof::VofBlockSet> vofBlocks_;
5217 std::shared_ptr<vof::VofBlockExchange> vofBlockExch_;
5218 // rung W2: the block CSF face force -- on the g=3 patch (the scatter's target) and mirrored onto
5219 // the G=2 registry block the RHS reads. Allocated only by `enable_vof_block_csf`.
5220 SField vofBlkF_[3];
5221 CCField csfBlkF_[3];
5222 // vof_overlap_design §5.6: S = sum_k C_k on the g=3 patch, the census, the opt-in tent and its
5223 // scratch patch. Allocated on first use; untouched unless the block CSF or the tent is on.
5224 SField vofBlkS_, vofBlkCeff_;
5225 VofOverlapCensus vofOverlap_{};
5226 bool vofOverlapDensity_ = false;
5227 // The block-path curvature clip in index units (VofCurvature::kappaMax: <0 = 1/Delta_min, 0 =
5228 // off), kept here so a setting made before enable_vof_blocks survives the container's creation.
5229 double vofBlockKappaMax_ = -1.0;
5230 // set_vof_block_debris: -1 = not set (the default: ON under the block CSF), 0 = off, 1 = on.
5231 int vofBlockDebris_ = -1;
5232 bool vofPhantomBound_ = true; // setVofPhantomCapillaryBound
5233 bool distributed_ = false;
5234 C3 og_{0, 0, 0}; // velocity-block inner origin (global red-black parity); {0,0,0} single-rank
5235#ifdef PECLET_FLOW_MPI
5236 std::shared_ptr<GridHaloTopology<3>> velHalo_; // g=2 velocity-block topology
5237 std::shared_ptr<GridHalo<double>> velDev_; // g=2 velocity-block ghost exchange
5238 std::shared_ptr<GridHalo<MReal>> velDevF_; // float twin (momentum-stencil ring, CA sweeps)
5239 // The sharp interface's fit fields (tau_hat x 3, D_nn) in ONE exchange: a depth-kSvHaloDepth
5240 // topology of the velocity block, stacked 4 x at stride n (doc/vof_sharp_viscous_stress.md §7).
5241 // Built at the first fit after a (re)decomposition (collective: sharpActive_ is global).
5242 std::shared_ptr<GridHaloTopology<3>> svHalo_;
5243 std::shared_ptr<GridHalo<double>> svDev_;
5244 // The reads reach one ghost cell, edge ghosts included (edgeTau, cellExtra at q - s_c; review
5245 // F1): proved by the bitwise gates, not assumed (sharp_viscous_mpi_np*, the np-4 trajectory).
5246 static constexpr int kSvHaloDepth = 1;
5247 bool caMomentum_ = false; // communication-avoiding momentum sweeps (setCommAvoiding, extent>=4)
5248 bool momStencilDirty_[3] = {true, true, true}; // per-component: stencil ring needs an exchange
5249 std::shared_ptr<peclet::core::decomp::BlockDecomposer<3>>
5250 dec_; // current partition (redistribute)
5251 MPI_Comm comm_ = MPI_COMM_NULL;
5252 int gnx_ = 0, gny_ = 0, gnz_ = 0; // communicator + GLOBAL dims
5253#endif
5254 int bc_[6] = {0, 0, 0, 0, 0, 0};
5255 double bcVel_[6][3] = {};
5256 bool hasBc_ = false, hasOutflow_ = false; // domain BCs
5257 bool hasSolid_ =
5258 false; // an immersed solid is present (any inner SDF < 0) -- with domain BCs, the
5259 // momentum solve must use the cut-cell IBM stencil, not the all-fluid fold
5260 bool backflowWarned_ = false; // the reversed-outflow-without-stabilization warning, once
5261 double backflowBeta_ =
5262 0.2; // outflow backflow-stabilization coefficient (0 = off; inert unless the
5263 // outflow reverses, so purely-outgoing outlets stay byte-identical)
5264 CCField bcProf_[6];
5265 int bcProfNc_[6] = {0, 0, 0, 0, 0, 0}; // per-position inlet profiles (face grid [Lb*Lc*3])
5266 std::vector<double> bcProfRaw_[6]; // the user's (nb, nc, 3) profile, kept so the resampled
5267 int bcProfNb_[6] = {0, 0, 0, 0, 0, 0}; // buffer above can be rebuilt when the block is resized
5268 int bcProfRawNc_[6] = {0, 0, 0, 0, 0, 0};
5269 CCField bcDcorr_[3], bcBrhs_[3]; // implicit-diffusion face fold (per component)
5270 bool advect_ = true; // momentum advection ON by default (user directive 2026-10-23)
5271 bool cutcellPressure_ = false, implicitFou_ = false;
5272 bool deferredCorr_ = true; // deferred-correction advection (off = pure implicit FOU, 1st order)
5273 int advScheme_ = 0; // high-order advection: 0 = SOU (default), 1 = Koren TVD
5274 bool incremental_ = true,
5275 pwarm_ = false; // incremental-rotational pressure (CUDA default on) + warm-start
5276 // E (doc/vof_projection_cost_design.md §5.3, setPressureInitialGuess): the mode, the basis
5277 // size, the history held (0, 1, 2: phi1_ = phi^n, phiPrev1_ = phi^{n-1}), the driver of the
5278 // solves that built it (1 PCG, 2 FCG), and the second solution buffer (allocated on first use).
5279 int pguessMode_ = 1; // 0 'auto', 1 'zero' (DEFAULT), 2 'projected'
5280 int pguessHistMax_ = 2;
5281 int pguessCount_ = 0;
5282 int pguessDriver_ = 0;
5283 CCField phiPrev1_;
5284 bool dtDirty_ = false; // set_dt/set_rho/set_mu after set_solid: momentum stencil needs a rebuild
5285 // Set once setSolidDevice has built the operators. The settings that are FOLDED INTO that build
5286 // (domain BCs, aperture order, exact crossings / openness overrides, the fluid-only constraint,
5287 // the ghost overlay) refuse a later call instead of being silently ignored (QUALITY_PLAN F).
5288 bool geometryBuilt_ = false;
5289 int faceInterp_ = 9; // collocated scheme: 9 = gauge-exact (DEFAULT), 0 = plain, 5/6/7 = embed
5290 // A0: fill the advection inputs' masked (solid) rows with the WALL velocity instead of zeros.
5291 // ON by default; setAdvectionWallVelocity(false) is the pre-A0 ablation. See advWallInputs.
5292 bool advWallVel_ = true;
5293 // Advect the collocated momentum with the projected divergence-free face field (the shipped
5294 // scheme) instead of the un-projected cell->face average. ON by default;
5295 // setUfAdvection(false) is the developer-tier ablation. See ufAdvVelocity / doc/uf_advection.md.
5296 bool ufAdvect_ = true;
5297 // WO-R2 item 1 — the variable-density coefficient on the operator's Dirichlet (outflow)
5298 // domain-face rows. ON by default; see setOutflowOperatorCoefficient.
5299 bool outflowOpCoeff_ = true;
5300 // P1 — the exact double flux-form level-0 apply (setPressureExactResidual; enableVof turns it
5301 // on). Mirrored into mg_, and read directly by the star overlay's additive delta.
5302 bool exactResidual_ = false;
5303 // Communication-avoiding smoothing mask (kCaMomentum | kCaMg), see setCommAvoiding. kCaDefault
5304 // (host both, device off); the momentum half is additionally gated on the block extent
5305 // (caMomentum_).
5306 int caMode_ = kCaDefault;
5307 // The shared level-0 MPI decomposition (setDecomposition): 0 = auto (default), 1 = the legacy
5308 // aligned ORB, >= 2 = the legacy coarse-first search from that depth (the deepest candidate
5309 // within maxImbalance).
5310 int decompLevels_ = 0;
5311 double decompMaxImbalance_ = 1.05;
5312 // True once rebalanceByWeights has put the solver on a WEIGHTED level-0 decomposition (reset by
5313 // initMpi(gnx, gny, gnz, comm)). It switches the pressure MG's Repartition stages on
5314 // (CutcellMG::setRepartition): a weighted ORB has odd splits, and without them a telescope stage
5315 // can collapse a level far larger than one rank's block onto one rank (SCALING_ISSUES #2).
5316 bool weightedDec_ = false;
5317 double aspectTheta_ = 2.0; // mirror of the two multigrids' threshold
5318 bool rotationalP_ = true; // false = PM I ablation: drop the -mu*div(u*) Timmermans term from
5319 // the incremental pressure accumulation (constant-mu path only)
5320 bool rotFilter_ = false; // filtered rotational: smooth div(u*) (mask-aware axis-wise 1-2-1,
5321 // one-sided toward the fluid at solid neighbours) before accumulating
5322 // -mu*div into P. Kills the wall-normal checkerboard feedback the
5323 // cell-centered rotational update is unstable through, keeps the O(1)
5324 // pressure-relaxation gain and the phi=0 (dt-free) fixed point.
5325 double rotFilterEps_ = 0.05; // S' = eps I + (1-eps) S (see setRotationalFilter)
5326 double rotWeight_ = 1.0; // rotational under-relaxation w (setRotationalWeight)
5327 double rotWallW_ = 0.0; // wall-banded rotational blend w0 (setRotationalWallWeight)
5328 // Face-aperture estimator order (setApertureOrder; DEFAULT 2 = marching-squares since
5329 // 2026-08-26 -- user decision, kills the convexity bias; 1 = the legacy one-sample model).
5330 int apertureOrder_ = 2;
5331 int fluidOnlyMode_ = 0; // fluid-only constraint (setFluidOnlyConstraint): 1=A filter, 2=B star
5332 StarOverlay starOv_; // mode-B Kron star overlay (built in setSolid)
5333 Kokkos::View<int, CCMem> starCounter_;
5334 int nStar_ = 0;
5335 bool useVelocityMg_ = false;
5336 bool vmgExplicit_ = false; // set_velocity_multigrid was called (AUTO rule off)
5337 // The V-cycle is the DEFAULT momentum solver (2026-09-15): no upper bound on the block size,
5338 // no global-size floor. 0 = never; a finite value restores an upper bound (1.0.0 used 65536
5339 // cells/rank with a 1<<23 global floor).
5340 long vmgAutoCells_ = std::numeric_limits<long>::max();
5341 long vmgAutoMinGlobal_ = 0L;
5342 int vmgAutoMinExtent_ = 16; // shortest per-rank inner extent the V-cycle is worth
5343 double vmgAutoMinCond_ = 13.0; // operator condition number above which the V-cycle wins
5344 // (1 + 12 D; measured crossover D ~ 1)
5345 bool vmgDecided_ = false; // the momentum-solver choice has been made (and the MG built)
5346 int vmgLevels_ = 4, vmgVcycles_ = 8; // IBM velocity multigrid (staircase)
5347 bool useVelocityCheb_ = false; // Chebyshev momentum solver (setVelocityChebyshev)
5348 bool vmgCheb_ = false; // Chebyshev smoother INSIDE the velocity MG
5349 int vmgChebDegree_ = 0;
5350 double vmgChebEigRatio_ = 10.0;
5351 int velChebMaxit_ = 400;
5352 VelocityMG vmg_;
5353 CCField vmgTheta_, vmgClean_;
5354 int outerIters_ = 1;
5355 double outerTol_ = 0.0; // Picard outer iteration (CUDA set_outer_iterations)
5356 long lastOuterIters_ = 0;
5357 double lastOuterCorr_ = 0.0;
5358 // per-step phase timers (seconds, this rank; see lastStepSeconds)
5359 double tStep_ = 0.0, tPredictor_ = 0.0, tMomentum_ = 0.0, tProjection_ = 0.0;
5360 // WO-V9: cumulative VoF-stage timers (armed by set_vof_timing; inert and unfenced when off)
5361 bool vofTiming_ = false;
5362 VofTiming vt_;
5363 double tStepSum_ = 0.0, tPredSum_ = 0.0, tMomSum_ = 0.0, tProjSum_ = 0.0;
5364 double vofTick() const;
5365
5366
5367 void vofAdd(double& acc, double t0);
5368
5369
5370 // fence-then-read wall clock: phase boundaries must not attribute queued device work to the
5371 // next phase
5372 static double phaseTick();
5373
5374
5375 CCField sdf_, ox_, oy_, oz_, phi_, div_, P_, ox1_, oy1_, oz1_, rhs1_, phi1_, r_, z_, pp_, Ap_;
5376 bool ghostProjection_ = false; // directional ghost-cell projection (the collocated AUTO default)
5377 bool colSchemeAuto_ = Grid::collocated; // AUTO scheme resolution at setSolid (cleared by any
5378 // explicit scheme selection)
5379 GpOverlayMReal gpOv_; // its per-row overlay (built by setSolid), follows MReal (G.6)
5380 Kokkos::View<int*, CCMem> gpIdMap_;
5381 Kokkos::View<int, CCMem> gpCounter_;
5382 int gpNRows_ = -1; // -1 = overlay not built (set_solid must run with the mode on)
5383 int gpMatrixOrder_ = 2, gpRhsOrder_ = 2; // closure order: implicit phi couplings / RHS
5384 CCField tEx_[3][3]; // exact crossings t[c][k] (inner grid; setExactCrossings)
5385 bool hasExactCross_ = false;
5386 // WO-V6b: the Navier slip length (in cells) shared with the dynamic-wetting cut-off, and the
5387 // switch that makes the MOMENTUM wall closure use it.
5388 double slipLambda_ = 0.0;
5389 bool wallSlip_ = false;
5390 Kokkos::View<int, CCMem> slipSkipDev_;
5391 std::array<int, 3> slipSandwich_{0, 0, 0};
5392 bool sceneCrossings_ = false; // crossings came from the analytic scene (per-rank, no override)
5393 std::shared_ptr<peclet::core::geom::SceneQueryDevice<double, CCMem>> sceneQ_;
5394 bool hasScene_ = false;
5395 // CUT OWNERSHIP (Layer 3 rung 1). Which scene instance owns the nearest surface, per INNER cell
5396 // (x-fastest, nx*ny*nz), filled by set_solid_from_scene in the same traversal that samples the
5397 // SDF (core's evalOwner answers both at once, so the field is free). Meaningful everywhere; only
5398 // the cut cells consume it — moving geometry reads a wall velocity off the owner, and resolved
5399 // CFD-DEM posts the hydrodynamic force back to it. Empty until a scene is sampled.
5400 Kokkos::View<int*, CCMem> cutOwner_;
5401 // MOVING GEOMETRY (Layer 3 rungs 2-3). Per-scene-instance rigid-body motion: host copies (KBs,
5402 // rank-replicated like the scene itself) plus the device mirrors the kernels capture. All-zero
5403 // motion => hasMotion_ stays false and EVERY path below is skipped, so a static solver is
5404 // bit-identical to the build that predates this rung -- "moving with zero velocity" is not the
5405 // same code path and would not be.
5406 std::vector<double> instCen_, instLin_, instAng_; // 3*nInst_ each, world coordinates
5407 Kokkos::View<double*, CCMem> instCenD_, instLinD_, instAngD_;
5408 int nInst_ = 0;
5409 bool hasMotion_ = false;
5410 CCField uBc_[3]; // R2: wall velocity component c AT component c's staggered points
5411 CCField uwCell_[3]; // R3: the whole wall velocity at CELL CENTRES (the wall-flux divergence)
5412 // A0 (advective cut-wall flux): the momentum advection's OWN velocity inputs -- a copy of C[c].u
5413 // whose solid-masked rows carry uBc_ (the local rigid-body wall velocity) instead of the zeros
5414 // maskVelocity pins there. Allocated and filled only while an instance is moving; every other
5415 // configuration keeps reading C[c].u, byte for byte. See buildAdvInputs().
5416 CCField uwAdv_[3];
5417 // Route (b) instrumentation: u* = the LAST momentum solve's solution, stashed (ghosts included,
5418 // exactly as the smoother left them) before the projection overwrites it. The reaction force
5419 // needs the viscous fluxes AT u* -- the implicit solve acted on u*, not on the projected u.
5420 CCField uStar_[3];
5421 bool haveUStar_ = false;
5422 // R0: the explicit advective term EXACTLY as the last Picard RHS used it, per component and per
5423 // staggered cell, in the equation's own units (rho*(aF - aK), i.e. before the rscale descale).
5424 // Written by buildRhs / buildRhsForced when a scene is installed and advection is on; consumed
5425 // by hydroForceTorqueReaction, which must subtract every non-pressure, non-wall RHS term.
5426 CCField advRhs_[3];
5427 bool haveAdvRhs_ = false;
5428 bool wallFluxDiv_ = true; // rung 3 on (correct physics); off only to exhibit its absence
5429 // Fresh-cell seeding (see seedFreshCells). ON by default since 2026-08-30: measured on an
5430 // oscillating sphere that physically translates through the grid, it removes a
5431 // RESOLUTION-INDEPENDENT +2.6..2.9% drag bias, cuts the spurious force oscillation 20-50x to
5432 // within 17% of the non-moving floor, and improves the resolved CFD-DEM loop's total-momentum
5433 // conservation 95x. set_fresh_cell_seed(False) restores the old behaviour.
5434 bool freshSeed_ = true;
5435 // Rung 4: the scene is KEPT (not just its device query), so an instance transform can be updated
5436 // and the whole geometry re-derived without the caller re-encoding anything.
5437 std::shared_ptr<peclet::core::geom::SceneBuilder<double>> sceneB_;
5438 peclet::core::Vec3<double> sceneOrigin_{0, 0, 0}, sceneExtent_{0, 0, 0};
5439 bool scenePeriodic_ = false;
5440 long imageOverlapCells_ = 0; // set_solid_from_scene's periodic-image overlap count
5441 std::vector<long> movingCutCells_; // per-instance cut-cell counts (moving scenes only)
5442 std::vector<int> instCenPinned_; // 1 = centre of rotation pinned (explicit), 0 = follows the body
5443 std::vector<long> movingDegenerate_; // per-instance exactly-on-lattice staggered points
5444 bool sceneDirty_ = false; // a transform changed; the device query must be rebuilt
5445 std::vector<double> oxOverride_, oyOverride_, ozOverride_; // exact apertures (inner)
5446 bool hasOpenOverride_ = false;
5447 CCField oxb_, oyb_, ozb_; // binary (COUPLED) openness on the g=2 block (ghost divergence)
5448 CCField sdfGp_; // the projection's sdf (fragmentation pockets decoupled) — gpCenterGrad reads
5449 // it so the collocated predictor/correction never touch a decoupled cell
5450 CCField gpRh_, gpT_, gpZ2_; // extra BiCGStab scratch (g=1 block)
5451 CCField gpX2_; // distributed BiCGStab matvec staging (g=2 solver block; overlay +/-2 halo)
5452 CCField uf_, vf_, wf_; // collocated: transient face (MAC) field (approx projection)
5453 CCField faceAcc_[3]; // face-range scratch, allocated on first use by either consumer:
5454 // the V8 predictor's face accelerations Phi_c (buildRhsColoVar) and
5455 // the balanced-force projection's c*beta (buildBalancedFaceForce,
5456 // both grids).
5457 CCField tgp_; // collocated: cell pressure-gradient scratch
5458 CCField fvM_, fvL_, cs_; // collocated: embed defect scratch (M·u, L_FV·u) + cell fluid fraction
5459 CCField xcx_, xcy_, xcz_; // collocated: open-centroid wall distance per face (wall-aware map)
5460 CCField old_[3], prev_[3]; // u^n time base + previous Picard iterate
5461 Comp C[3];
5462 peclet::core::FieldSet fields_; // named directory of all cell fields (velocity/p/sdf + user)
5463 std::vector<ScalarField> scalars_; // transported scalars (advection-diffusion)
5464 // Cut-cell scalar geometry record (WO-2) and the geometry version it must match: every geometry
5465 // build bumps scgVersion_ (invalidateScalarCutGeometry), and ensureScalarCutGeometry rebuilds
5466 // when scg_.version differs. scg_.version starts at -1, so nothing is built until first use.
5467 scg::ScalarCutGeometry scg_;
5468 long scgVersion_ = 0;
5469 // WO-5b: the captured open-face flux planes (scalarCaptureOpenFaceFlux), per global face, and
5470 // whether they belong to this block and geometry (cleared by every geometry build).
5471 CCField scalarOpenFlux_[6];
5472 bool scalarOpenValid_ = false;
5473 // --- phase change (WO-P01) -------------------------------------------------------------------
5474 bool pcEnabled_ = false, pcThermal_ = false, pcHasUser_ = false;
5475 double pcRhoG_ = 1.0, pcRhoL_ = 1.0, pcHlv_ = 1.0; // INTERNAL (pcRefreshUnits)
5476 double pcTsat_ = 0.0, pcKg_ = 0.0, pcKl_ = 0.0, pcRint_ = 0.0;
5477 // the caller's PHYSICAL values, kept verbatim (refreshUnitDerived re-derives the internal ones)
5478 double pcRhoGPhys_ = 1.0, pcRhoLPhys_ = 1.0, pcHlvPhys_ = 1.0;
5479 double pcKgPhys_ = 0.0, pcKlPhys_ = 0.0, pcRintPhys_ = 0.0;
5480 double pcRcpGPhys_ = 1.0, pcRcpLPhys_ = 1.0;
5481 double pcInterfaceEps_ = 1e-12, pcPureEps_ = 1e-12;
5482 std::string pcTName_;
5483 CCField pcMdot_, pcSrc_, pcUser_, pcArea_, pcNrm_[3], pcDep_, pcTgt_, pcCnew_, pcDefic_;
5484 PhaseChangeDiagnostics pcDiag_;
5485 // --- WO-P23 (rungs P2/P3) --------------------------------------------------------------------
5486 bool pcPlaneDir_ = true; // plane-anchored (GFM) Dirichlet rows instead of pinning the cell
5487 double pcGfmThMin_ = 0.1, pcGfmThMax_ = 1.9; // the GFM distance clamp (cells)
5488 bool pcQuadFit_ = true; // quadratic (Aslam) one-sided gradient fit (WO-P23 default)
5489 // WO-P3d (2026-09-03, coordinator's decision): the DEFAULT is the joined sheet (marching
5490 // tetrahedra on the PLIC signed-distance level set, centroid deposit). Gate re-derived: it is at
5491 // the floor on every a-priori geometry (sphere 1e-4, tilted planes 2e-6, cylinder order 2.04),
5492 // does not drift with wisps under advection, is byte-identical on every planar phase-change gate,
5493 // makes the P2 MPI gate bitwise, and removes the pure-gas deposit fallback (band_div 2e-3 ->
5494 // 6e-12). The P3 (Scriven) 1 % gate is still open at 1.0-1.5 % and is no longer explained by
5495 // the area (WO-P3e). `set_phase_change_area(0)` reproduces the P0-P3c numbers.
5496 int pcAreaMode_ = vof::kAreaMcPlic; // WO-P3c/P3d: which geometry A_Gamma comes from
5497 vof::VofInterfaceArea pcAreaC_; // the cascade area driver (g = 3 block; lazily initialised)
5498 vof::VofMcArea pcAreaMc_; // WO-P3d: the joined marching-tet area driver
5499 double pcMcOrphanArea_ = 0.0; // WO-P3d: area booked to non-interfacial cells
5500 CCField pcAreaCg2_; // its inner values on the G = 2 phase-change block
5501 // WO-P23 ablation (`set_phase_change_deposit_fallback`): give the interfacial
5502 // cells whose along-the-normal deposit candidates are BOTH still interfacial a target from the
5503 // 5^3 box instead of leaving the source in place. Default OFF — see the findings.
5504 bool pcDepositFallback_ = false;
5505 bool pcEnergy_ = false; // consistent rho c_p T transport + variable k(C)/rho c_p(C) operator
5506 double pcRcpG_ = 1.0, pcRcpL_ = 1.0;
5507 CCField pcKcell_, pcRcp_; // k(C) and (rho c_p)(C) on the G=2 block, refreshed per step
5508 vof::VofEnergyAdvector vofEnergy_;
5509 double pcBandDiv_ = 0.0; // max |div(open u)| over interfacial cells, last diagnostics call
5510 CCField pcGn_[3], pcGphi_, pcTgam_; // plane normal, centre distance, T_Gamma (WO-P23)
5511 CCField pcSink_; // auto-balanced sink weights (WO-P23)
5512 // WO-P3f: the energy-budget instrument. `pcClsPrev_` holds the PREVIOUS step's class of every
5513 // cell (0 gas, 1 interfacial/masked, 2 liquid) so the class CHANGES can be counted and their
5514 // enthalpy accounted; both are unallocated and every kernel is skipped unless the flag is on.
5515 bool pcBudgetOn_ = false;
5516 PhaseChangeBudget pcBudget_;
5517 CCField pcClsPrev_;
5518 // WO-P3f: conserve the enthalpy the per-cell Dirichlet OVERWRITE destroys (see
5519 // `pcCarryDeposit`). Off by default; `pcCarrySrc_` is unallocated until it is turned on.
5520 // WO-P3f: the PRESCRIBED interface curvature `div(n)` used to correct the one-sided fit's
5521 // sample distances (`vof::pcCurvedDistance`). 0 = the shipped tangent-plane distance, bitwise.
5522 double pcFitKappa_ = 0.0;
5523 bool pcCarryConserve_ = false;
5524 CCField pcCarrySrc_;
5525 double pcCarryDeposited_ = 0.0, pcCarryLost_ = 0.0;
5526 // --- WO-P3g: the second-order interfacial energy operator -----------------------------------
5527 // Three independent pieces, each an option so the ablation can be measured, and one package
5528 // switch (`set_phase_change_energy_order`) that turns all of them plus WO-P3f's `carry_conserve`
5529 // on together. Every one is bitwise inert at its default.
5530 bool pcMdotOperator_ = false; // item 1: mdot from the energy operator's OWN interfacial flux
5531 int pcGfmOrder_ = 1; // item 2: 2 = the Gibou-Fedkiw three-point row
5532 bool pcCurvDist_ = false; // item 3: curvature-consistent distances, kappa from the cascade
5533 CCField pcKappa_; // the V3 cascade's kappa on the G = 2 block (item 3)
5534 CCField pcMdotFit_; // the one-sided-fit mdot, kept as a DIAGNOSTIC under item 1
5535 CCField pcInDomain_; // 1 where a cell CARRIES A ROW (inside the global domain), else 0
5536 bool pcMaskFresh_ = false; // is the Dirichlet/plane geometry current for THIS colour field?
5537 double pcQOperator_ = 0.0; // sum of the operator's interfacial heat (W), last build
5538 double pcQOrphan_ = 0.0; // ... the part on cells with no interfacial AREA (dropped)
5539 double pcMdotFitMean_ = 0.0; // area-weighted mean of the diagnostic fit mdot
5540 bool pcHasSink_ = false;
5541 double pcSinkW_ = 0.0;
5542 std::vector<Closure> closures_; // property/body-force closures (applied at top of step())
5543 CCField cellForce_[3]; // per-cell momentum body force (Boussinesq / CFD-DEM feedback)
5544 bool hasCellForce_ = false;
5545 bool varProps_ = false; // variable-coefficient momentum (variable viscosity)
5546 bool harmonicMu_ = false; // harmonic vs arithmetic face-viscosity mean
5547 bool fullStress_ = false; // set_viscous_stress("full"): add the transpose term (staggered)
5548 bool viscousStressAuto_ = true; // set_viscous_stress("auto"), the DEFAULT (WO-7)
5549 bool fullStressAuto_ = false; // AUTO resolved to full at this step's head
5550 bool fullStressAutoNotice_ = false; // the one-time AUTO-fallback notice was printed
5551 bool muUniform_ = true; // this step's exact global test min mu == max mu (full stress skips)
5552 bool regDirty_ = true; // the full-stress regular-node masks need a rebuild (geometry built)
5553 RegMask fsReg_[3]; // full-stress regular-node masks, 1 B/cell each (solids only)
5554 enum class SharpMode { kAuto, kSharp, kAveraged };
5555 SharpMode sharpMode_ = SharpMode::kAuto; // set_vof_viscous_interface; "auto" the DEFAULT
5556 bool sharpActive_ = false; // the sharp interface is in force this step (resolveSharpViscous)
5557 bool sharpAutoNotice_ = false; // the one-time AUTO-fallback notice was printed
5558 vof::SharpGeom sharpGeom_; // this step's band geometry (views into the colour/plane blocks)
5559 vof::SvByte svCls_, svFb_; // band class / fit-fallback flag, 1 B/cell each
5560 CCField svFit_; // tau_hat x 3 then D_nn, 4 n contiguous (one exchange, §7) ...
5561 CCField svTau_[3], svDnn_; // ... and its four n-subviews, dense (§12 Q2)
5562 vof::SvList svList_; // the fit's worklist of interfacial cells (8 B/cell)
5563 vof::SvList svRhsList_; // the band-term worklist (sharpRhsCompact), 8 B/cell
5564 long svRhsN_ = 0; // ... and its length this step
5565 CCField muField_; // per-cell dynamic viscosity (when varProps_)
5566 int varRotMode_ = 0; // rotational term under varProps: 0 chi*mu_min, 1 chi*mu(i), 2 off
5567 double varRotChi_ = 1.0; // rotational coefficient scale chi
5568 bool varRho_ = false; // variable density (momentum + projection); staggered only
5569 CCField rhoField_; // per-cell density (when varRho_); rho_ is the reference rho0
5570 // --- geometric VoF (rung V2a, WO-J) ---
5571 bool vofEnabled_ = false;
5572 // WO-R2 item 4 — see setVofWispEps / defaultVofWispEps.
5573 double vofWispEps_ = defaultVofWispEps();
5574 bool rhoFaceHarmonic_ = false; // harmonic instead of arithmetic rho_f in the projection (OFF)
5575 bool outflowCorrValid_ = false; // the projection's outflow-face correction is still in u
5576 // WO-R item 4 measured NO against the DEFECTIVE operator; WO-R2 item 1 fixed the operator and
5577 // the answer flipped to YES (measured: with the fix, the projected outflow divergence at ratio
5578 // 10 is 8.31e-10 WITH the factor and 9.97e-05 without). DEFAULT ON;
5579 // `set_outflow_rho_correction(False)` restores the plain correction as the ablation.
5580 bool outflowRhoCorr_ = true;
5581 CCField cField_; // the G=2 registry mirror of the colour field ("C")
5582 CCField vofCs_; // rung V5a: cell fluid fraction on the G=2 block (staggered)
5583 CCField vofSolidG2_; // rung V5a: 1 where the cell is SOLID (G=2 mirror), else 0
5584 bool vofSolidZero_ = true; // rung V5a: canonical "C" is 0 in solid cells (see setter)
5585 // rung V5b (WO-S): the static contact angle. Unset => the neutral (90 deg) fill of WO-Q, and the
5586 // whole V5a battery is byte-identical.
5587 bool contactAngleSet_ = false;
5588 double contactAngleDeg_ = 90.0;
5589 int contactPivot_ = vof::kVofPivotVolume;
5590 std::vector<double> contactAngleField_;
5591 // rung V6 (WO-V6): the dynamic angle / hysteresis producer for the theta field. Inert unless
5592 // set_contact_angle_dynamic / _hysteresis is called (`vofDyn_.active()`), in which case the
5593 // whole V5b battery is byte-identical.
5594 vof::VofDynamicWetting vofDyn_;
5595 double contactSigmaOverride_ = 0.0;
5596 bool contactSigmaWarned_ = false;
5597 CCField vofDynVel_[3];
5598 vof::WyAdvector vofAdv_; // the g=3 working block: PLIC + Weymouth-Yue sweeps
5599 C3 e3_{0, 0, 0}; // extended extents of that block (n + 2*kVofG)
5600 double vofCflLimit_ = 0.25; // Weymouth's proven 3D boundedness bound 1/(2(N-1))
5601 double sigmaCsf_ = 0.0; // V4: surface-tension coefficient (0 = the force is off)
5602 double capillaryCfl_ = 1.0; // safety factor on the Brackbill capillary dt
5603 double csfInterfaceEps_ = 1e-8; // V4: wisp threshold on the curvature's interfacial predicate
5604 int csfMode_ = 0; // 0 = balanced-force (production), 1 = cell-interp ablation
5605 bool kappaFrozen_ = false; // V4 instrument: do not recompute kappa at the head of the step
5606 long vofStep_ = 0; // sweep-permutation counter (6-cycle)
5607 // --- two-phase open boundaries (rung V-BC, WO-R) ---
5608 bool vofBcActive_ = false; // any inflow colour / backflow colour set: arms the whole
5609 // rung (the mask, the ghost rules, the property ghosts)
5610 bool vofInflowSet_[6] = {false, false, false, false, false, false};
5611 bool vofBackflowSet_[6] = {false, false, false, false, false, false};
5612 double vofInflowC_[6] = {0, 0, 0, 0, 0, 0}; // uniform inflow colour per face
5613 double vofBackflowC_[6] = {0, 0, 0, 0, 0, 0}; // inletOutlet backflow colour per face
5614 std::vector<double> vofInflowProfRaw_[6]; // the user's (nb, nc) profile, kept so the device
5615 int vofInflowProfNb_[6] = {0, 0, 0, 0, 0, 0}; // views can be rebuilt when the block is rebuilt
5616 int vofInflowProfNc_[6] = {0, 0, 0, 0, 0, 0};
5617 CCField vofInflowProf3_[6], vofInflowProfG2_[6]; // resampled onto the g=3 / G=2 face planes
5618 int vofProf3Nc_[6] = {0, 0, 0, 0, 0, 0}, vofProfG2Nc_[6] = {0, 0, 0, 0, 0, 0};
5619 vof::UCField vofOutside_; // the out-of-domain mask on the g=3 block
5620 // SCALING_ISSUES #3/#8: scratch for fillVelGhostsTo's save/restore of the high-side outflow face
5621 // plane across the distributed halo exchange, one per axis, allocated on first use. Shared
5622 // with fillFaceGhostsKeepBoundary (the two never overlap: each restores before returning).
5623 CCField outflowPlane_[3];
5624 CCField outflowEdgeScratch_; // fillVelGhostsTo(faceEdges): the scratch of the one extra exchange
5625 double vofBcVol_[6] = {0, 0, 0, 0, 0, 0}; // signed liquid volume of the LAST step, + = in
5626 double vofBcVolTotal_[6] = {0, 0, 0, 0, 0, 0}; // running total since enable_vof
5627 // --- curvature (rung V3, WO-O) ---
5628 vof::VofCurvature vofCurv_; // the cascade, on the SAME g=3 block as the colour field
5629 CCField kappaField_, kappaBranch_; // the G=2 registry mirrors ("kappa", "kappa_branch")
5630 vof::VofCurvature::Stats vofCurvStats_{};
5631 // --- momentum-consistent transport (rung V2b, WO-K) ---
5632 bool vofMomEnabled_ = false; // rho^c u_c advected by the SAME geometric fluxes as C
5633 vof::MomentumConsistentAdvector vofMom_; // the half-shifted CVs, on the SAME g=3 block
5634 CCField uAdv_[3]; // the recovered advected velocity on the solver's G=2 block (inner cells)
5635 double vofRhoG_ = 1.0, vofRhoL_ = 1.0; // the two phase densities (C = 0 / C = 1)
5636#ifdef PECLET_FLOW_MPI
5637 std::shared_ptr<GridHaloTopology<3>> vofHalo_; // the colour field's OWN g=3 topology
5638 std::shared_ptr<GridHalo<double>> vofDev_;
5639#endif
5640 CCField rho1_, cx1_, cy1_, cz1_; // g=1 MG-block density bridge + projection face coefficients
5641 bool porous_ = false; // volume-averaged continuity d(eps)/dt+div(eps u)=0 (CFD-DEM)
5642 double pressUnderRelax_ = 1.0; // omega_p for the incremental pressure accumulation (1.0 = off)
5643 bool porousDepsDt_ = true; // include the d(eps)/dt source in the projection RHS. Off ->
5644 // enforce div(eps u)=0 (drop the term, which is jagged/noisy
5645 // because eps is a bare per-cell particle deposit; the noisy
5646 // source can drive the eps-weighted pressure solve unstable).
5647 CCField epsField_, epsPrev_, eps1_, depsdt_; // eps^{n+1}, eps^n, g=1 bridge, stored d(eps)/dt
5648 CCField divAdv_; // cell div(u) — porous advection-form compensation (see buildRhs*)
5649 CCField epsRho_; // rho_eff = eps*rho — eps-conservative porous momentum (updateEpsRho per step)
5650 // eps-CONSERVATIVE porous momentum + projection pair (default): time term (eps_f rho/dt) u,
5651 // eps_f rho-weighted advective form, projection c_f = open*(eps rho idt)/(eps rho idt + beta)
5652 // with correction rho idt/(eps rho idt + beta) grad(phi). False = the legacy plain-u pair
5653 // (for A/B only; it kinematically drags gas with the moving porosity — energy injection).
5654 bool porousCons_ = true;
5655 CCField beta1_; // g=1 bridge of the drag coeff (semi-implicit-drag pressure)
5656 bool hasDrag_ = false; // implicit linear drag (CFD-DEM): beta on the momentum diagonal
5657 CCField dragBeta_; // per-cell drag coefficient (added to AC; target beta*u_p rides
5658 // the force_* cellForce fields)
5659};
5660
5661// The staggered MAC solver — THE flow solver, bit-identical to the pre-policy class. Bindings + the
5662// kokkos_mpi tests reference this name unchanged.
5664
5665} // namespace peclet::flow
5666
5667// The twelve domain headers hold the out-of-line member DEFINITIONS, and since G.8 only the two
5668// instantiation TUs need them: everything else linking `peclet_flow_solver` gets the declarations
5669// above and calls into the library. Narrowing the include to those TUs is what makes an edit to one
5670// domain header rebuild FOUR objects instead of all 49 (measured: 9m10s -> 4m35s of CPU at -j8).
5671//
5672// The one thing this forbids: a member TEMPLATE of `Solver` may not be defined in a domain header
5673// and called from a consumer -- an explicit instantiation of the class does not cover member
5674// templates, so the consumer would need the definition and would fail to link. There is exactly one
5675// member template on the class today (the VoF `template <class Fill, class Color, class ColorDu>`
5676// pair), it is used only from inside the class, and the whole battery links. If you add one that a
5677// test or the bindings must call, declare it in this file and define it HERE, above this point --
5678// not in a domain header.
5679#ifdef PECLET_FLOW_INSTANTIATING
5680#include "flow_ibm_core.hpp"
5681#include "flow_ibm_project.hpp"
5682#include "flow_ibm_scene.hpp"
5683#include "flow_ibm_geometry.hpp"
5684#include "flow_ibm_hydro.hpp"
5685#include "flow_ibm_vof.hpp"
5687#include "flow_ibm_closures.hpp"
5688#include "flow_ibm_scalars.hpp"
5690#include "flow_ibm_bc.hpp"
5691#include "flow_ibm_mpi.hpp"
5692#include "flow_ibm_diagnostics.hpp"
5693#include "policy.hpp"
5694#endif // PECLET_FLOW_INSTANTIATING
5695
5696
5697// The ONE compiled instantiation (suite/docs/QUALITY_PLAN.md §3.G.8). `Solver<Grid>` is a ~12 k-line
5698// class template whose 517 out-of-line members are defined in the twelve domain headers included just
5699// above (in the instantiation TUs only); every
5700// consumer used to instantiate all of it at -O3 for itself (45 test executables plus the bindings,
5701// for both grids), which is what made a full rebuild ~45-50 CPU-minutes and made an edit to any one
5702// domain header invalidate all 45. These declarations suppress that implicit instantiation; the
5703// definitions are compiled once, in src/flow_solver_staggered.cpp and src/flow_solver_colocated.cpp,
5704// into the static library every consumer links (cmake/PecletFlowSolver.cmake).
5705//
5706// Nothing is hidden by this. The class definition above is complete, so a consumer can still derive
5707// from it (the bindings' `BoundSolver final : Solver<Grid>` inherits the constructor) and the
5708// standard exempts inline functions -- everything defined inside the class body -- from an explicit
5709// instantiation declaration, so the small accessors are instantiated and inlined in the consumer
5710// exactly as before. What moves is the out-of-line bulk, compiled from the same source under the
5711// same flags (no LTO, no -march: there is no cross-TU optimization to lose).
5712//
5713// PECLET_FLOW_MPI must match between the instantiation TUs and their consumers -- it changes the
5714// class. The build makes that structural: the macro is a PUBLIC property of the MPI library.
5715#ifndef PECLET_FLOW_INSTANTIATING
5716namespace peclet::flow {
5717extern template class Solver<Staggered>;
5718extern template class Solver<Colocated>;
5719} // namespace peclet::flow
5720#endif
5721
5722#endif // PECLET_FLOW_SDFLOW_IBM_HPP
flow — VoF rung V1: Weymouth & Yue (2010) directionally-split, exactly volume-conserving geometric ad...
flow — VoF Part III rung W0: the per-bubble VoF BLOCK, a third container over the same L1 kernels (su...
flow — VoF Part III rung W0: the block gather/scatter (VOF_PLAN.md §10 design items 2 and 4).
void imposeDomainWallKind(int mask)
void vofExchangeScalar(CCField f)
The colour block's ghost policy WITHOUT the colour-specific rules (no solid-band fill,...
int pressureBottomExtent() const
void setVofMomentumMuscl(bool on)
void setScalarSource(const std::string &name, double S)
void setSolidUploadSdf(CCField din)
void setVofCurvatureMixedHeightFit(bool on)
double wallFluxImbalance()
Net wall flux this rank injects, sum over inner cells of u_w .
void scalarCutMatvecTwo(ScalarField &sc, CCField yf, CCField ys, CCField xf, CCField xs)
void setPressureLineRelaxation(bool enabled)
void setContactAngleClamp(double loDeg, double hiDeg)
const VofTiming & vofTimingReport() const
bool vofBlocksEnabled() const
void setPressureMeanRemoval(bool all)
std::vector< double > getScalarSolid(const std::string &name)
double multigridAspectThreshold() const
std::vector< double > getFaceVelocity(int c)
void setPhaseChangeGfmOrder(int order)
WO-P3g item 2: the order of the one-sided (ghost-fluid) Dirichlet row.
void setVofRhoFloorFrac(double f)
void setPhaseChangeEnergyMuscl(bool on)
MinMod-limited donor reconstruction of the face temperature in the consistent energy flux (vof/energy...
bool pressureVcycleFp32() const
void noteChebyshevGrowthTrip(long iters)
void enableVofBlocksFromField(const std::vector< std::array< int, 6 > > &boxes)
void setScalarWall(const std::string &name, int type, double value, double coefficient, int instance)
void setInstanceTransform(int i, const std::array< double, 3 > &translation, const std::array< double, 4 > &quat)
Move one instance (Layer 3 rung 4).
std::array< int, 3 > globalResolution() const
long numPressureChebyshevRestarts() const
void extendSdfDomainGhosts(CCField f)
Repair a cell-centred geometry field's ghost band on every rank-owned NON-PERIODIC domain face,...
void setContactAngleSmoothing(bool on)
void setPhysicalDomain(const std::array< double, 3 > &extent, const std::array< double, 3 > &origin, const std::array< long, 3 > &globalCells)
Arm the physical domain.
void applyVelocityBcAll(int fold, bool doOutflow)
void vofApplyColourBc(CCField f)
The colour field's boundary rules, applied at the END of vofFillGhosts — i.e.
void fillVelGhosts(int comp, int fold)
void pcZeroDomainGhosts(CCField f)
Zero the two ghost layers on every NON-periodic domain face this rank owns.
std::vector< double > scalarGeometryField(int which)
void setIncrementalPressure(bool on)
void pcCarryDeposit(ScalarField &sc)
WO-P3f — the enthalpy the per-cell Dirichlet overwrite destroys, returned to the phase it came from.
std::function< double()> constCoeffResidual(int c, double bx, double by, double bz, double Ac)
void setVelocityTolerance(double rtol, int minIters)
double maxOpenDivergenceInternal()
The same diagnostic in INDEX units (per tRef), which is what the solver's own guards read.
void addCsfRhs(int c, CCField dst, bool rowScaled, bool faceRange=false)
double capillaryCfl() const
bool pressureCoarseGhost() const
void scatterInner(CCField fld, const std::vector< double > &in)
void setSolid(const std::vector< double > &sdfInner, bool cutcellPressure)
Host entry point: upload the inner SDF once and delegate.
void phaseChangeStep()
The in-step driver: everything applyPhaseChange does, at the head of step().
bool advectsMomentum() const
void setContactAnglePivot(int mode)
void checkCgExit(CCField rhs1, CCField x1, long iters, const char *which, const StarOverlay *star)
void setVofBlockPool(bool on)
bool contactAngleSet() const
ScalarField & scalarField(const std::string &name)
PhaseChangeDiagnostics phaseChangeDiagnostics()
void setVofKappaConstant(double kappa)
kappa is a PHYSICAL curvature, 1/length (the internal field is 1/h; see vof_curvature()).
bool balancedForceProjection() const
void buildOpenFaceField()
Build ufOpen_ = the face field with each open (outflow) domain face overwritten by its zero-gradient ...
void setScalarSourceField(const std::string &name, const std::vector< double > &S)
std::array< double, 3 > scalarMeanFlux(const std::string &name)
bool hasMovingInstance() const
True when at least one instance carries a nonzero velocity – i.e.
long solveBalancedForceSystem(double bref, double r0)
void fillGhosts(CCField f)
std::vector< double > getVofCurvature()
The interface curvature kappa = 2H in the caller's units, i.e.
long lastOuterIterations() const
long pressurePrefactorCount() const
void setMassFluxUniform(double v)
Prescribe a UNIFORM mass flux (P0), in mass per area per time.
double decompositionMaxImbalance() const
void fillDomainPeriodic(CCField f)
void setPressureCoarseGhost(bool on)
Neumann (zero-gradient) coarse ghost on wall/inflow faces before the pressure MG's prolongation — the...
void setDomainBc(int face, int type, double vx, double vy, double vz)
bool advWallInputs() const
R0 helper: allocate (once) and arm the per-component advective-term stash the reaction-force budget c...
void refreshWallVelocity()
Re-derive ONLY the wall-velocity fields and the momentum operator that folds them in.
void setUfAdvection(bool on)
Advect the collocated momentum with the PROJECTED, divergence-free MAC face field uf_/vf_/wf_ (DEFAUL...
void setPhaseChangeFitCurvature(double kappa)
WO-P3f INSTRUMENT: prescribe the interface curvature kappa = div(n) the one-sided fits use to correct...
void fillPropGhosts(CCField f, bool edges=false)
void requireCollocatedFaceForceScope(const char *who)
void patchScalarDirichletFaceVar(CCField AC, CCField band, CCField kc, int a, int side)
void setFaceInterp(int mode)
void applyBackflowStab(int c)
void pcScatterSource()
(2) Deposit each interfacial cell's source into its chosen pure-gas cell, as a GATHER (each receiving...
void checkMovingInstancesAreCut()
A MOVING instance whose surface produces no fractional face aperture has no path for its wall velocit...
sco::MeanGradPosition scalarMeanGradPosition(const double Gphys[3]) const
std::vector< std::array< int, 3 > > pressureMgLevelRatios() const
void pcApplyDivergenceSource(CCField div)
Subtract the phase-change (and any prescribed) divergence source from div_ so the deflated pressure s...
void checkVofBcFace(int f, int wantType, const char *who)
A VoF boundary colour is only meaningful on a face that already carries the matching domain BC,...
void setPhaseChangeMdotOperator(bool on)
WO-P3g item 1: take mdot from the energy operator's own interfacial flux instead of the one-sided lea...
std::vector< double > scalarSolidGeometryField(const std::string &name, int which)
void setVofTiming(bool on)
long numPressureEigenEstimates() const
std::vector< double > getField(const std::string &name)
std::vector< long > movingInstanceDegeneratePoints() const
Per instance: staggered points where the sampled sdf is exactly zero (see the warning).
void setOutflowRhoCorrection(bool on)
void setPropertyMode(bool variable, bool harmonic)
std::vector< double > vofBlockKappa(long id)
double lastPressureAllreduceSeconds() const
bool prefactorHoistEligible() const
void addCsfRhsBlocks(int c)
std::string vofMomentumScheme() const
double phaseChangeCarryDeposited() const
The carry ledger, physical: an energy with the consistent transport on, and a temperature times a vol...
void setVofMomentumCellFlag(bool on)
void setVelocityChebyshev(bool on, int maxit=400)
void applyVelocityBcComp(int comp, int fold, bool doOutflow)
void setOpennessOverride(const std::vector< double > &ox, const std::vector< double > &oy, const std::vector< double > &oz)
void setOuterTolerance(double tol)
CCField addField(const std::string &name)
void vofBcArm()
Arm the rung: install the mask, rebuild the profiles, and zero the boundary volume ledger.
double lastMomentumResidual() const
void scalarCutRefusals(const ScalarField &sc) const
std::string vofViscousInterface() const
std::array< double, 3 > domainOrigin() const
Physical lower corner of the GLOBAL inner grid.
void setPressureGraphAmg(bool on)
bool vofHasGeometry() const
void scalarCutMatvec(ScalarField &sc, CCField y, CCField x)
std::array< long, 3 > fluidMomentumCells()
The number of unmasked (fluid) staggered momentum cells per component – the exact discrete datum the ...
ScalarField & cutcellScalar(const std::string &name, const char *who)
void pcRegress(double dt)
(3) The regression: two Jacobi passes over the exchanged per-cell data, so the clip deficit is redist...
bool vofRhoClosureEnds(double &rho0Phys, double &rho1Phys) const
vof::VofInterfaceArea::Stats pcAreaCascadeCompute()
Run the cascade area driver on the (already bridged) g = 3 colour block.
void advectVofBlocksInternal(double dtInt, bool requireSolenoidal)
The same with dt already in INTERNAL time (step() passes its dt_).
VelocityMG::Comm vmgComm() const
double velocityResidualTolerance() const
ScalarCutFacets scalarFacets(const std::string &name)
SField pcAreaCascadeField() const
The area field the last pcAreaCascadeCompute filled (either driver).
double pcEffPureEps() const
…and the mirror statement: a cell the ADVECTOR treats as a pure phase is a pure phase here too,...
void setPressureTelescope(bool on)
std::vector< double > getVofFilledColour()
void setPressureStrict(bool on)
Throw instead of reporting when the pressure preconditioner returns a non-finite correction (ISSUES s...
void requireFullStressScope(const char *who) const
void enableVofBlocks(const std::vector< std::array< double, 4 > > &seeds)
OutflowBackflow outflowBackflow()
void fillGhostsFaces(CCField f)
bool advectionWallVelocity() const
void debugSetPressureEigenScale(double s)
void applyVelocityBcFace(CCField f, int comp, int a, int s, int fold, bool doOutflow)
void scaleForceTorque(std::vector< double > &out, std::size_t m) const
Hydrodynamic force and torque on each scene instance (Layer 4 rung 2) – the resolved CFD-DEM feedback...
void scalarCutAssembleSolve(ScalarField &sc, bool steady)
std::array< double, 3 > wallAreaProbe()
A_wall EXACTNESS PROBE (diagnostic for the Layer-4 force integral).
void pcUpdateEnergyProps()
Refresh k(C) and (rho c_p)(C) on the G=2 block from the current colour.
void rebuildGeometry()
Re-derive ALL geometry from the current instance transforms (Layer 3 rung 4): rebuild the accelerated...
void exchangeFieldAdd(const std::string &name)
std::vector< double > getVofAdvectedVelocity(int c)
void advanceScalarCutCell(ScalarField &sc)
CCConst advVelView(int c) const
The velocity view the advection operators must read for component c: the wall-corrected scratch while...
void setContactAngleDynamic(double thetaEDeg, double slipCells, double muLiquid, double sigma=0.0)
void requireScalesPinned(const char *who, bool needRho) const
Under an armed extent, refuse a call that writes a dimensional value into a FIELD before the referenc...
void exchangeField(const std::string &name)
void setAdvection(bool on)
std::array< long, 3 > globalCells() const
void bridgeOutflowFacePlanes()
Bridge the HIGH-side boundary-face openness plane of every rank-owned outflow axis from the g=2 block...
void setPressureExactResidual(bool on)
WO-R2 item 3 — the exact (matrix-free, double, flux-form) level-0 operator apply in the residual and ...
std::vector< double > getVofGeometry(int which)
double phaseChangeQOperator() const
The operator's interfacial heat (power), physical.
void setSolidFromScene(bool cutcellPressure)
Sample the scene onto this rank's inner grid and install it as the solid, entirely on device – no nx*...
void vofRebuildBcBlock()
(Re)build everything that lives on the g=3 block for this rung: the out-of-domain mask and the resamp...
void addScalar(const std::string &name, double D, int scheme, int iters, bool cutcell=false)
void setScalarResidualTolerance(const std::string &name, double rtol)
void fillFaceGhostsKeepBoundary(CCField f, int a)
std::vector< double > vofBcVolumes() const
Signed liquid volume that crossed each of the six domain faces during the LAST colour advection,...
void setScalarBcProfile(const std::string &name, int face, const std::vector< double > &prof, int n1, int n2)
vof::SharpCensus vofViscousInterfaceCensus() const
void uploadVelocity(const std::vector< double > &uu, const std::vector< double > &vv, const std::vector< double > &ww)
Upload an initial velocity field in the caller's PHYSICAL units (converted per component to the index...
double maxOpenDivergenceProjectedInternal()
The same diagnostic in INDEX units (per tRef), which is what the solver's own guards read.
std::vector< double > getVof()
double surfaceTension() const
The surface tension in the caller's units (what set_surface_tension was given).
bool outflowRhoCorrection() const
void copyInner(CCField dst, C3 de, int dg, CCConst src, C3 se, int sg)
void requireNoGeometry(const char *who) const
void setDivergenceSink(const std::vector< double > &w)
WO-P23: an AUTO-BALANCED sink region for the phase-change divergence source.
void applyVelocityBcCompTo(CCField f, int comp, int fold, bool doOutflow)
void setPressureVcycleSymmetric(bool enabled)
double capillaryDtInternal()
The same limit in the solver's index time (per tRef) — what the step's own guards compare to.
void setPropertyModel(const std::string &target, ClosureKind kind, const std::string &in0, const std::string &in1, const std::vector< double > &params)
double maxAbsDiffInner(CCConst a, CCConst b)
void fillPeriodicAxes(CCField f, int axes)
void scalarCutAdvection(ScalarField &sc, bool steady)
void requireIsotropic(const char *what) const
Phase 2 §7 — refuse an ANISOTROPIC domain in a consumer this phase does not carry.
double vofTimingProjectionSeconds() const
CsfDiagnostics csfDiagnostics()
const scg::ScalarCutGeometry & scalarCutGeometry()
void setBackflowStab(double beta)
std::array< double, 3 > spacing() const
Cell size per axis (equal on every axis unless the Phase 2 anisotropic path is armed – see unitScales...
void setSurfaceTension(double sigma)
void exchangeExtRaw(CCField f)
Raw ghost fill of an extended-block field: the rank halo exchange under MPI, the periodic wrap single...
bool velocityChebyshevActive() const
void setVelocityIterations(int it)
void vofHarvestBcVolumes()
Move the advector's per-face boundary volume ledger into the solver's, once per advection.
void enableVofMomentum(double rhoGasPhys, double rhoLiquidPhys)
rhoGas / rhoLiquid are PHYSICAL densities, the same numbers the rho closure is given.
ScalarFaceFlux scalarFaceFlux(int a) const
double finishResidual(int c)
ScalarCutBudget scalarBudget(const std::string &name)
bool ufAdvVelocity() const
Are the advection operators reading the projected face field this step?
std::vector< double > getVofCurvatureBranch()
bool bcVelFacePair(int a) const
std::vector< double > scalarWallFlux(const std::string &name)
void setPressureChebyshev(bool on, int maxit, double rtol)
void setVofInflowProfile(int f, const std::vector< double > &prof, int nb, int nc)
Per-position inflow colour on face f: prof is (nb, nc) on the INNER grid of the face's two perpendicu...
double vofBlockImbalanceOf(int mode) const
void scalarCutWarnings(ScalarField &sc)
const UnitScales & unitScales() const
bool lastBalancedForceFailed() const
std::vector< int > getCutOwner() const
Per-inner-cell owning instance (Layer 3 rung 1), x-fastest, -1 where no scene has been sampled yet.
CCConst openFaceView(int c) const
Component c of the face field AS THE ADVECTION AND THE DIVERGENCE DIAGNOSTIC MUST READ IT: advFaceVie...
void applyScalarBcFace(CCField c, int a, int side, int type, double val, bool edges=false)
void requireVofGeometry(const char *who)
void setSolidGhostProjectionOverlay(CCField din)
void addWallFluxDivergence(CCField d)
void ensureScalarSolidRecord(ScalarField &sc, const std::vector< char > &conj)
double capillaryDt()
The Brackbill capillary limit in the CALLER's time unit.
void setVof(const std::vector< double > &c)
void setContactAngleHysteresis(double thetaADeg, double thetaRDeg)
static constexpr double defaultVofWispEps()
The value enableVof starts from.
long lastBalancedForceIterations() const
void setScalarBc(const std::string &name, int face, int type, double value)
std::vector< double > getOpenness(int c)
long periodicImageOverlapCells() const
Cells on this rank whose solid/fluid sign was set by a periodic IMAGE of an instance wider than the b...
bool pressureStrict() const
void buildVelocityOverlays(bool resetU)
Build the three per-component Robust-Scaled cut-cell overlays + solid masks from the CURRENT sdf_ (ex...
Solver(int nx, int ny, int nz)
vof::VofCurvature::Stats vofBlockCurvatureStats() const
void setPressureInitialGuess(int mode, int history)
void applyDomainWallGeometry(int mask)
void setPhaseChangeThermal(const std::string &tname, double Tsat, double kg, double kl, double Rint)
P1: compute mdot each step from the registered scalar tname by the one-sided pure-cell weighted least...
std::vector< double > getVofBlockForce(int c)
void setGhostProjection(bool on, int matrixOrder=2, int rhsOrder=2)
bool scalarRootRank() const
rank 0 (or not distributed): the one that prints a warning
bool vofKappaFrozen() const
void pcBudgetPost(ScalarField &sc)
WO-P3f, part 2: the state AFTER the energy solve, the heat the plane-anchored rows actually delivered...
std::array< long, 2 > vofBlockPoolStats() const
void constraintDivergence(CCConst fx, CCConst fy, CCConst fz, CCField out)
void setVofCutFluxClamp(bool on)
CCConst advFaceView(int c) const
Component c of the collocated MAC face field (uf_/vf_/wf_), flow's low-face convention: entry i is th...
void setPhaseChangePlaneDirichlet(bool on)
The PLANE-ANCHORED (ghost-fluid) Dirichlet condition, ON by default.
ContactAngleDiagnostics contactAngleDiagnostics()
void setPressurePrefactorHoist(bool on)
void setVofCurvatureWeightWidth(double d)
void setVariableRotational(int mode, double chi)
void setWallFluxDivergence(bool on)
Rung 3 on/off.
void setPressureUnderRelax(double w)
long lastMomentumSweeps() const
void setScalarMeanGradient(const std::string &name, const std::array< double, 3 > &G)
bool vofCutFluxClamp() const
double vofRhoFloorFrac() const
double vofTimingPredictorSeconds() const
double vofInterfaceArea()
The summed interfacial area over the inner region, PHYSICAL (globally reduced under MPI) — the E7 gal...
void setPressureLevels(int levels)
long balancedForceFailures() const
void closureUnitsNotice(const std::string &target) const
Under a physical domain, say on stderr that a closure on a target of unknown dimension takes its para...
void vofExchangeRaw(CCField f)
std::array< int, 3 > blockOrigin() const
void setFluidOnlyConstraint(int mode)
double wallSlipLength() const
The Navier slip length in the caller's units (0 = no-slip).
void setRotationalPressure(bool on)
void setInstanceMotion(int i, const std::array< double, 3 > &lin, const std::array< double, 3 > &ang, const double *center=nullptr)
Rigid-body motion of one scene instance (Layer 3 rung 2).
void setPhaseChangeQuadraticFit(bool on)
The QUADRATIC one-sided gradient fit (T - T_G = G phi + Q phi^2) instead of the linear one.
void setDeferredCorrection(bool on)
void setScalarSolid(const std::string &name, double D, double capacity, double partition, double contactResistance, int instance)
double vofInterfaceEps() const
void setPressureGeometry(const std::vector< double > &sdfInner)
void setVofBlockAssign(int mode, long every)
void resampleBcProfile(int face)
double pcBandDivergence()
The BAND-EXTENDED LIQUID VELOCITY of VOF_PLAN §9 item 3, as a MEASUREMENT rather than a switch.
scg::ScalarCutCensus scalarCutCensus()
Solver(int nx, int ny, int nz, const std::array< double, 3 > &extent, const std::array< double, 3 > &origin, const std::array< long, 3 > &globalCells)
Physical-domain constructor (plan §3.3).
void pcBudgetPre(ScalarField &sc)
WO-P3f, the energy-budget instrument, part 1: the state BEFORE the energy solve, and the class-change...
double contactAngle() const
void setWallSlipLength(double lambdaCells)
WO-V6b – the VELOCITY half of the dynamic contact line.
std::array< double, 3 > instanceCenter(int i) const
The resolved centre of rotation of instance i and whether it is pinned (explicit) or follows the body...
void applyPhaseChange(double dtPhysArg)
Kinematic entry point (the P0a/P1 driver): build mdot/A_G/n from the current colour and temperature,...
void requireWettingWall() const
void vofBlockCensus(std::vector< long > &masters, std::vector< long > &cells) const
void setPhaseChangeCarryConserve(bool on)
WO-P3f: make the per-cell Dirichlet overwrite ENTHALPY-CONSERVING.
void setVofBackflow(int f, double value)
inletOutlet backflow colour on outflow face f (default 0 = gas): where the boundary face velocity poi...
vof::MomentumConsistentAdvector::Diagnostics vofMomentumDiagnostics()
bool wallFluxDivergence() const
std::vector< double > vofBlockColour(long id)
std::vector< long > movingInstanceCutCells() const
Per instance: cut rows of the momentum operator (all three components) at inner points this rank owns...
std::vector< double > getVofDynamicField(int which)
std::vector< double > hydroForceTorque()
PHASE 2 (anisotropic cells), doc/anisotropic_metric.md §4.4 — ADMITTED since commit C4.
void setVofCurvatureWorklist(bool on)
VofCurvature::useWorklist — run the height-function cascade and the PV fallback over a COMPACTED list...
void setPressureVcyclePrecision(int mode)
void setContactAngleField(const std::vector< double > &thetaDeg)
void seedFreshCells(CCField mOld[3])
FRESH CELLS: the points a moving body has just uncovered.
int pressureGuessCount() const
void setCapillaryCfl(double f)
SceneMap sceneMap() const
const vof::VofCurvature::Timing & vofCurvatureTiming() const
CCField resampleFaceScalar(const std::vector< double > &prof, int nb, int nc, int face, C3 ext, int g, int &outNc)
Clamp-resample a per-position face scalar from the user's (nb, nc) INNER grid onto the ghost-inclusiv...
bool vofMomentumEnabled() const
vof::VofCurvature::Stats vofCurvatureStats() const
void setCommAvoiding(int mask)
Communication-avoiding red-black smoothing: kCaMomentum | kCaMg.
void fillAxis(CCField f, int axis)
void setAdvectionWallVelocity(bool on)
A0 — wall velocity (not zeros) in the advection inputs' masked rows. DEFAULT true.
void pcBuildInterface()
(1) The interface build: for every inner interfacial cell reconstruct the PLIC plane from the canonic...
void setVofPhantomCapillaryBound(bool enabled)
std::vector< double > getMomentumDiagonal(int c)
std::vector< double > reactionBudgetTerms()
R0 DECOMPOSITION PROBE.
int contactAnglePivot() const
void setField(const std::string &name, const std::vector< double > &v)
void setVofMomentumScheme(const std::string &name)
void setSolidDevice(CCField din, bool cutcellPressure)
Device entry point (Layer 2): the inner SDF is ALREADY on device, so geometry never round-trips throu...
void setApertureOrder(int order)
double lastSuperficialVelocityShift() const
The shift the last step() applied (caller's velocity units; 0 when off).
void setVelocity(int c, const std::vector< double > &v)
Write a component's inner velocity from a host vector (x-fastest, inner region) and re-impose the sol...
void setBodyForce(double fx, double fy, double fz)
Body force per unit volume, in the caller's units (e.g. a mean pressure gradient, or rho*g).
void solveScalarSteady(const std::string &name)
std::vector< double > getOpennessProj(int c)
double pcLedgerEnergyToPhys() const
The factor from an internal phase-change ledger entry (a per-cell sum of rcp' dT) to the caller's uni...
std::vector< double > vofBcVolumesTotal() const
The same, accumulated since enable_vof() (or the last resetVofBcVolumes()).
void closureRefreshUnits(Closure &cl)
Re-derive a closure's internal p / tabY from its physical pPhys / tabYPhys with the current reference...
void setVofWorklist(bool on)
WyAdvector::useWorklist — the compaction of the PLIC reconstruction pass onto the mixed cells.
std::vector< double > getVelocity(int c)
void setPorousConservative(bool on)
std::array< int, 3 > blockShape() const
void vofExtendWallBand(CCField f, int mask)
VofOverlapCensus vofBlockOverlapCensus() const
std::array< std::vector< double >, 5 > vofViscousInterfaceFit()
void setRhoFaceHarmonic(bool on)
void setVofInflow(int f, double value)
Colour of the fluid entering through inflow face f (0..5 = -x,+x,-y,+y,-z,+z), in [0,...
bool pressureExactResidual() const
bool contactAngleHysteresis() const
double lastPressureTrueResidual() const
void setVofStepParity(long n)
long strideOf(int c) const
const vof::WyAdvector::Timing & vofKernelTiming() const
void fillVelGhostsTo(CCField f, int comp, int fold, bool doOutflow=true, bool faceEdges=false)
void collocatedV8AutoFallback(const char *why)
peclet::core::geom::InstanceMotionView< double > motionView() const
bool hasField(const std::string &name) const
void setDomainBcProfile(int face, const std::vector< double > &prof, int nb, int nc)
void debugSetPressureFp32Fault(int kind, int at)
void setVofViscousInterface(const std::string &mode)
void setViscousStress(const std::string &form)
void setAdvectionScheme(int s)
void enablePhaseChange(double rhoG, double rhoL, double hlv)
Turn on phase change.
void throwVelocityMgVariableMu(const char *who) const
int pressureTelescopeCount() const
void setExactCrossingsFromScene()
EXACT wall crossings straight from the scene, on device, on every rank – the in-solver replacement fo...
std::array< int, 3 > wallSlipSandwichCells() const
Cut-cell axes at which a one-cell fluid gap kept the no-slip closure (per component).
void setPressurePcg(bool on, int maxit, double rtol)
void setVelocityMultigridAuto(long cellsPerRank, long minGlobalCells=-1, int minBlockExtent=-1)
long solvePressureSystem(CCField rhs1, CCField x1)
void allocateBlock(int nx, int ny, int nz)
const char * projectedGuessIneligible() const
int pressureVcycleRestarts() const
void setVelocityMultigrid(bool on, int levels, int vcycles)
void setRotationalWeight(double w)
void setVofBlockDeviceStaging(bool on)
void setDensityMode(bool variable)
void gpUploadSdf(const std::vector< double > &sdfGpHost, std::size_t nInner, CCField sdfGp)
bool hasScalar(const std::string &name) const
void setMu(double m)
Dynamic viscosity, in the caller's units.
void setVofKappaFrozen(bool on)
void pcBuildInDomain()
WO-P3g — 1 on every cell that CARRIES A ROW in the energy solve, 0 otherwise.
void setDecomposition(int levels, double maxImbalance=1.05)
How the shared level-0 MPI decomposition is built.
void setExactCrossings(const std::vector< double > &t)
double vofRhoFloor() const
void setPressureWarmstart(bool on)
void superficialVelocityPrecheck() const
void velSweepLoop(Fill &&fill, Color &&sweepColor, ColorDu &&sweepColorDu, std::function< double()> resid=nullptr, double bnorm=0.0)
void setPressureIterations(int it)
void pcCarryApply(ScalarField &sc)
WO-P3f: consume pcCarrySrc_ into the energy solve's time base.
Kokkos::View< MReal *, CCMem > FV
Definition flow_ibm.hpp:81
double stepAdaptive(double cflTarget, double capillaryCflTarget, double dtMax)
void pcUpdateCurvature()
The per-cell Dirichlet mask of the energy scalar: T = T_sat + mdot R_int in every interfacial cell,...
bool velocityMgChebyshev() const
int heldResidualPlane(int c) const
void setVofBlockOverlapDensity(bool enabled)
void refreshUnitDerived()
Re-derive every internal (index-unit) quantity from the stored physical inputs.
void setScene(const std::vector< int > &nodeInts, const std::vector< double > &nodeReals, const std::vector< int > &instInts, const std::vector< double > &instReals, bool periodic=false)
Install an analytic scene from core's flat node/instance encoding (peclet/core/geom/scene_builder....
void setPropertyTable(const std::string &target, const std::string &in0, const std::vector< double > &xs, const std::vector< double > &ys)
void setPressureBottomSolver(int engine)
static double vofWallPlaneSdf(int gx, int gy, int gz, I3 gs, int mask)
void setScalarMaxIterations(const std::string &name, int maxit)
void enableVofBlocksFromColours(const std::vector< std::array< int, 6 > > &boxes, const std::vector< std::vector< double > > &colours)
double pcEffInterfaceEps() const
The colour tolerance that decides which cells are INTERFACIAL, and it has to be at least the colour a...
void setVofBlockDebris(bool enabled)
void setPressureTelescopeForceLevel(int level)
void requireBalancedForceScope(const char *who, bool atStep) const
bool pressurePrefactorHoist() const
void advectVofKinematic(double dtPhysArg)
dt is in the caller's time unit.
void setVofInterfaceEps(double eps)
void checkSealedInflowCells()
Reject geometry that seals fluid cells against a prescribed INFLOW face off from the rest of the doma...
void setVofWispEps(double eps)
WO-R2 item 4 — the wisp threshold on the advector's mixed-cell predicate and on the interface Courant...
double effectiveContactSigma() const
void setVofBlockKappaClip(bool enabled, double kappaMaxPhys=-1.0)
CCField fieldView(const std::string &name)
double vofLastCourant() const
void pushVofMetric()
Hand the anisotropic cell metric to every VoF driver that exists (Phase 3).
std::string capillaryThrowMessage(double cap) const
void setCollocatedScheme(const std::string &name)
void setVelocityMgChebyshev(bool on, int degree=0, double eig_ratio=10.0)
void setFreshCellSeed(bool on)
Fresh-cell policy for moving geometry.
void setPressureBottomExtent(int cells)
The set_pressure_bottom("auto") criterion: agglomerate once the coarsest GLOBAL grid exceeds this man...
void filterCellField(CCField f, int axis)
double closureTargetToInt(const std::string &target) const
The internal-per-physical factor of a closure TARGET: rho, mu, force_x/y/z; 0.0 for any other field (...
bool contactAngleDynamic() const
bool ensureAdvStash(int c, bool adv)
void setOutflowOperatorCoefficient(bool on)
WO-R2 item 1 ABLATION: set_outflow_operator_coefficient(False) restores the pre-WO-R2 operator,...
double vofTimingMomentumSeconds() const
void setImplicitAdvection(bool on)
double vofTimingStepSeconds() const
void setVofSolidColourZero(bool on)
void setPhaseChangeCurvatureDistance(bool on)
WO-P3g item 3: measure the GFM row's theta and the one-sided fits' sample distances to the CURVED int...
std::vector< vof::VofBox > vofBlockRankBoxes(int size) const
bool instanceCenterPinned(int i) const
double vofCurvatureWeightWidth() const
void setVelocityResidualTolerance(double rtol)
vof::SharpFaceProps makeSharpFaceProps(int c, vof::SvRole role)
void setPhaseChangeEnergyOrder(int order)
WO-P3g — the SECOND-ORDER interfacial energy operator, as one package.
long numPressureChebyshevGrowthTrips() const
SharpViscousState sharpViscousState() const
std::function< double()> stencilResidual(int c, bool exchange=false)
void setPressureBottomMode(int mode)
void requirePhaseChange(const char *who) const
void phaseDensityRange(double &lo, double &hi)
void setMassFlux(const std::vector< double > &v)
Prescribe a per-cell mass flux (P0), x-fastest over the inner region; units and call-order rule as se...
sco::MaterialTable scalarMaterialTable(ScalarField &sc, std::vector< char > &conj)
VarFaceProps makeFaceProps(int c)
void setPhaseChangeEnergy(double rcpGas, double rcpLiquid)
Turn on the CONSISTENT energy transport (VOF_PLAN §9 item 6) for the scalar set_phase_change_thermal ...
void setRotationalWallWeight(double w0)
long numPressureUnconvergedSolves() const
void vofBcPropGhosts(CCField f)
WO-R item 5 — the Neumann property policy at an inflow face.
void vofFillGhosts(CCField f)
bool pressureTelescope() const
void addCsfRhsCellInterp(int c, CCField dst, bool rowScaled, bool faceRange=false)
void setBalancedForceProjection(bool enabled)
const vof::WyAdvector & vofAdvector() const
double reduceMaxAbsInner(CCConst f)
void setPorousContinuity(bool on)
void setRho(double r)
Fluid density, in the caller's units.
vof::WyAdvector::Diagnostics vofDiagnostics()
bool vofAxisPeriodic(int a) const
void patchScalarDirichletFace(CCField AC, CCField band, double Din, int a, int side)
void setVofCflLimit(double v)
void scalarDirichletMask(const std::string &name)
Allocate (idempotently) the per-cell Dirichlet mask + value of a registered scalar.
VofStepLimits vofStepLimits()
Both limits at the current state, in the CALLER's time unit (courant is dimensionless).
void setRotationalFilter(bool on, double eps=0.05)
bool velocityMultigridActive() const
std::array< double, 3 > domainExtent() const
Physical extent of the GLOBAL inner grid (cell counts without a physical domain).
std::vector< std::string > fieldNames() const
std::vector< double > gatherInner(CCField fld)
void setSuperficialVelocity(bool on, int axis, double velocity)
Hold the SUPERFICIAL velocity along a periodic axis: at the end of every step() one uniform shift is ...
double vofWispEps() const
bool vofSolidColourZero() const
bool vofCurvatureWorklist() const
double vofBlockImbalance() const
std::vector< double > cellCentres(int axis) const
Physical cell-centre coordinates of THIS rank's inner block along axis (nx/ny/nz values).
void copyBlockShifted(CCField dst, C3 de, CCConst src, C3 se, int off)
void pcRefreshUnits()
Re-derive the INTERNAL phase-change constants (pcRhoG_ ... pcRcpL_) from the caller's physical ones (...
int decompositionLevels() const
std::vector< vof::VofBlockStats > vofBlockStats() const
CCConst wallVelView(int c) const
void advectVofBlocks(double dtPhysArg, bool requireSolenoidal=true)
dt is in the caller's time unit.
void setContactAngle(double thetaDeg)
void setVofFluxClamp(bool on)
void setPhaseChangeBudget(bool on)
WO-P3f: turn the ENERGY BUDGET instrument on.
PhaseChangeBudget phaseChangeBudgetValues() const
The budget, physical: energies and powers with the consistent transport on, temperature x volume (and...
bool vofCurvatureMixedHeightFit() const
void setDivergenceSource(const std::vector< double > &v)
A PRESCRIBED extra divergence source (1/time, physical; set_dt must precede it under an extent,...
double contactAngleSlip() const
std::vector< double > hydroForceTorqueReaction()
Hydrodynamic force and torque per instance from the DISCRETE REACTION (route (b) of the design note's...
double vofCflLimit() const
bool outflowOperatorCoefficient() const
void setPressureFcg(bool on, int maxit, double rtol)
std::vector< double > getPressure()
const vof::VofBlockSet * vofBlockSet() const
The block container itself, read-only (tests: the metric and tunables its cascades carry).
void setMultigridAspectThreshold(double theta)
The anisotropic-coarsening aspect threshold theta shared by the pressure and velocity multigrids (doc...
void setOuterIterations(int iters)
void setPhaseChangeDepositFallback(bool on)
WO-P3f open item 6 / WO-P3g — the divergence source's 5^3 fallback target, as a setter (it was only r...
bool isCutcellScalar(const std::string &name) const
void setPhaseChangeArea(int mode)
WO-P3c — which geometry the interfacial AREA comes from.
bool hasPhysicalDomain() const
The container: a replicated table of blocks, the per-step orchestration (gather → advect → re-centre ...
Weymouth-Yue split advection of a colour field on an extended (inner + ghost) block.
flow — collocated (ABC approximate-projection) variable-density kernels: the mass-adjoint pair of run...
flow — VoF rung V-BC (WO-R): the colour field's OPEN-BOUNDARY ghost rules and the out-of-domain mask ...
flow — VoF rung V2a (WO-J): the bridge between the solver's G = 2 block and the colour field's own g ...
flow — VoF rung V3 (WO-O): the view-level driver for the curvature cascade.
flow — VoF Part II (WO-P23): CONSISTENT rho c_p T transport, driven by the SAME geometric fluxes as t...
flow — face/cell material-property accessors for the variable-coefficient momentum operator.
flow — IbmSolver domain boundary conditions: setDomainBc/profiles, pressureBcGhost,...
flow — IbmSolver property closures: property/density modes, porous continuity, drag,...
flow — IbmSolver core: allocation, physical-domain scales, rho/mu/dt and pressure/velocity driver set...
flow — IbmSolver diagnostics: state getters, divergence probes, timers and the outflow/backflow censu...
flow — IbmSolver static solid geometry: setSolid / setSolidDevice and its stages, pressure geometry.
flow — IbmSolver hydrodynamic force and torque: the reaction-budget terms and wall probes.
flow — IbmSolver MPI: initMpi, redistribute, rebalanceByWeights and the post-repartition field-resize...
flow — IbmSolver phase change: interface area, mass flux, energy transport, budget accounting,...
flow — IbmSolver pressure projection: step(), the project() stages, the buildRhs family,...
flow — IbmSolver transported scalars: addScalar/setScalarBc/advanceScalars and their BC application.
flow — IbmSolver cut-cell scalar transport (doc/scalar_ibm_design.md): the geometry record of WO-2 — ...
flow — IbmSolver scene and moving geometry: scene instances and motion upload, wall velocity,...
flow — IbmSolver Volume-of-Fluid: the colour field, cut-cell VoF geometry, contact angle,...
flow — the transpose half of the full deviatoric viscous stress on the staggered grid.
flow — the gauge-exact directional cell-centre pressure gradient.
flow — OPT-IN forensics for the ghost-projection overlay (PECLET_FLOW_GP_DEBUG).
flow — GridLayout policy traits (placement of the velocity unknowns).
flow — WO-P3c: the view-level driver of the cascade-consistent interfacial area.
flow — collocated approximate (MAC) projection helpers (Almgren–Bell–Colella style).
flow — Chebyshev semi-iteration as a standalone momentum (implicit-diffusion) solver,...
flow — portable (Kokkos) geometric multigrid for the cut-cell (variable-openness) pressure Poisson.
flow — portable (Kokkos) IBM geometric fields + variable-coefficient RB-GS smoother.
flow — portable (Kokkos) cut-cell pressure operator + Chorin projection.
flow — portable (Kokkos) MAC stencil operators: Red-Black Gauss-Seidel smoothers + divergence.
flow — portable (Kokkos) velocity (momentum) multigrid for the IBM diffusion solve: the STAIRCASE coa...
flow — WO-P3d: the block driver of the marching-tetrahedra interfacial area.
flow — VoF rung V2b (WO-K): momentum-consistent transport of rho^c u_c on the half-shifted (MAC) mome...
Definition conj.py:1
Kokkos::View< unsigned char *, SMem > UCField
Definition advect_wy.hpp:89
Kokkos::View< std::uint8_t *, CCMem > SvByte
Per-cell byte fields on the solver block: the band class and the fit-fallback flag.
Kokkos::View< long *, CCMem > SvList
The compacted interfacial cells of a fit (local linear indices), the device fit's worklist.
@ kAreaMcPlic
the PLIC signed-distance level set, centroid deposit
SvRole
Which half of the time split a SharpFaceProps feeds (§6.1, WO-5b): the implicit band (ibmBuildDiffusi...
Kokkos::View< double *, SMem > SField
GpOverlayReal< mreal > GpOverlayMReal
Definition mac_ibm.hpp:38
Kokkos::View< const double *, CCMem > CCConst
constexpr int kCaDefault
Kokkos::View< double *, CCMem > CCField
IbmOverlayT< IMem, mreal > IbmOverlay
Definition mac_ibm.hpp:33
Kokkos::View< std::uint8_t *, CCMem > RegMask
Per-component regular-node mask (§5.4): 1 = a velocity node with neither a solid nor a cut row.
Solver< Staggered > IbmSolver
Definition prof.py:1
flow — VoF phase change (Part II, rungs P0/P1): the container-free kernel set.
flow — the multidimensional iteration policies: iteration order follows storage.
flow — device property closures: material properties / body forces as functions of fields.
flow — cell-centred scalar transport (advection–diffusion) on the cut-cell grid.
flow — the sharp conservative viscous stress at a VoF interface on the staggered MAC grid: band geome...
flow — portable (Kokkos) staggered MAC momentum advection (Koren TVD + FOU).
long unfilledCells
SOLID cells pass 1 left untouched (passes 2-3 then fill them).
double meanApparentAngle
mean measured apparent angle over contactCells, degrees
long dynamicCells
band cells the V6 pass produced an angle for
double setAngle
the prescribed angle, degrees (uniform case)
double maxContactSpeed
max |U_cl| (smoothed), solver velocity units
double meanApparentTheta
mean apparent angle over the same set, degrees
long neighbourCells
band cells written by the mean of the anchor's MIXED neighbours
double maxCaCl
max |Ca_cl| = |mu_l U_cl / sigma|
long parallelCells
band cells whose interface was parallel to the wall
long contactCells
band cells written by the theta plane of their own anchor
long pinnedCells
of those, cells whose contact line is PINNED
long pureCells
band cells that took the pure-phase continuation
double meanImposedTheta
mean IMPOSED angle over the V6 contact cells, degrees
long neutralCells
band cells that fell back to WO-Q's neutral mean
std::vector< peclet::core::solver::AndersonRole > roles
std::array< double, 9 > signature
std::vector< CCField > fields
OUTFLOW REVERSAL CENSUS – the regime in which the zero-gradient (do-nothing) outflow is only conditio...
WO-P3f — the ENERGY BUDGET of the phase-change energy solve.
long nLeaveGas
interfacial -> gas (the bubble swallowing a cell)
double hMasked
the same over MASKED (interfacial) cells
double hOpenNew
the same, after the solve
double qGfm
heat INTO the unmasked set across the plane-anchored rows (W)
double dEoverwrite
sum rcp (dval - T) over masked cells: what the Dirichlet rows inject when they overwrite the transpor...
long nEnterLiquid
liquid -> interfacial transitions this step
double qBehind
WO-P3g: the second-order row's one-sided rescaling of the band BEHIND each interfacial face,...
long calls
how many energy solves have been instrumented
double eLeave
... and of the cells that LEFT it (carrying pcCarriedValue)
double dEoverwriteNew
the part of it on cells that were NOT masked last step
double eEnter
sum rcp (T - T_sat) of the cells that JOINED the masked set
double hLiquid
sum rcp (T - T_sat) over PURE LIQUID cells, before the solve
long nMasked
size of the masked set
double hOpen
sum rcp (T - T_sat) over UNMASKED cells, before the solve
long nLeaveLiquid
interfacial -> liquid
long sourceCells
cells that RECEIVED a deposit
long deficitCells
cells that clipped at C = 0
double bandDiv
max |div(open u)| over interfacial cells (WO-P23; see pcBandDivergence)
double redistributed
|clip deficit| pushed into neighbours this step
long areaNone
WO-P3c: cells with NO cascade geometry (kept their MYC PLIC area).
double qOperator
WO-P3g: the heat (W) the operator's Dirichlet rows draw across the interface, i.e.
double mdotFit
WO-P3g: the AREA-WEIGHTED one-sided-fit mdot, kept as the diagnostic that item 1 replaced (0 unless t...
double areaOrphan
WO-P3d: area the JOINED sheet booked to cells that are not interfacial, i.e.
long areaPv
WO-P3c: cells whose area came from the PV paraboloid (tier 3).
long fallbackCells
interfacial cells whose +n walk found no pure gas cell
long areaHf
WO-P3c: cells whose area came from a height function (tiers 1/2a).
double sourceSum
sum of the deposited divergence source over inner cells (1/s)
double area
sum of the PLIC polygon areas over interfacial cells (h^2)
double removedVolume
sum of dV actually subtracted this step (+ = evaporated)
double Tmax
energy-scalar extrema (consistent transport only)
double unresolved
clip residue no neighbour could absorb (pushed anyway)
double qOrphan
... the part of it on interfacial cells with NO area, which the regression drops: the ONE non-conserv...
long excessCells
cells that clipped at C = 1
diagnostics.scalar_budget (§8.2), physical; collective under MPI.
diagnostics.scalar_facets (§8.2): this rank's facets, physical; per facet 3 values for the centroid a...
The ONE predicate for the cut-cell scalar's advective face flux (doc/scalar_ibm_design....
CCField vel
face-normal index velocity at the low a-face of cell i (internal)
CCField open
the projection's openness of that face
The map between the solver's INDEX coordinates and the coordinate system the analytic scene is writte...
Definition flow_ibm.hpp:243
double a[3]
scene_a = a[a] + b[a]*xi_a (xi = global index)
Definition flow_ibm.hpp:244
double velToInt[3]
scene velocity -> index velocity
Definition flow_ibm.hpp:247
double dToInt
scene signed distance -> index distance (1/hRef)
Definition flow_ibm.hpp:246
double angToInt
scene angular velocity -> index (omega*tRef)
Definition flow_ibm.hpp:248
double w[3]
w_a = 1 / h_a'^2 (<= 1)
Definition flow_ibm.hpp:181
double org[3]
physical lower corner of the GLOBAL inner grid
Definition flow_ibm.hpp:141
double rhoRef
reference density = the first set_rho
Definition flow_ibm.hpp:145
double forceToInt(int a) const
Definition flow_ibm.hpp:159
vof::VofMetric vofMetric() const
Definition flow_ibm.hpp:191
bool physical
an extent was given (the scales are armed)
Definition flow_ibm.hpp:139
double h[3]
cell size per axis = extent / cells
Definition flow_ibm.hpp:140
double hp[3]
h_a' = h_a / hRef (>= 1, exactly 1 on the finest axis)
Definition flow_ibm.hpp:180
double velToPhys(int a) const
Definition flow_ibm.hpp:153
double vol
V' = h_x' h_y' h_z' (cell volume in hRef^3).
Definition flow_ibm.hpp:182
long cells[3]
the GLOBAL cell counts the extent spans
Definition flow_ibm.hpp:143
bool aniso
some h_a' != 1 — kernels dispatch the per-axis body
Definition flow_ibm.hpp:183
double energyToPhys() const
An internal energy (rho c_p T summed over cells of volume hRef^3) to joules: the internal energy unit...
Definition flow_ibm.hpp:224
double tRef
reference time = the first set_dt
Definition flow_ibm.hpp:146
double hRef
reference length = min_a h_a (== h_a, Phase 1)
Definition flow_ibm.hpp:144
double ext[3]
physical extent of the GLOBAL inner grid
Definition flow_ibm.hpp:142
double velToInt(int a) const
Definition flow_ibm.hpp:152
long cells
cells with S > 1 + 1e-8 (global)
bool active
the phantom-aware capillary bound is in force
double maxSum
max_cells S (global)
double excess
sum over cells of (S - 1)^+ (global, cell volumes)
double courant
the interface-local Courant number at the current dt
double cflDt
the largest dt the WY boundedness cap admits
double capillaryDt
the largest dt the Brackbill capillary constraint admits
double binding
min(cflDt, capillaryCfl * capillaryDt)
double bridge
... of which: the G=2 <-> g=3 bridges + the C ghost policy
double curvature
the V3 height-function cascade + the capillary dt check
double momBridge
... of which: its bridges
double blockAdvect
the block-container colour stage as a whole (advectVofBlocks)
double csf
the V4 balanced-force CSF added to the three momentum RHSs
double momAdvect
the momentum-consistent colour+rho^c u stage (advectVofMomentum)
double blockDebris
... of which: the debris/residue pass (§5.3/§13 of the note)
double phaseChange
the Part II phase-change stage (mdot, deposit, regression)
One entry per eliminated solid-centered cell: packed INNER flat index + the apertures of its (up to 6...
The geometry part of diagnostics.scalar_census (§8.2).
The whole record: per-cell fields on the extended block (kappa and unknown haloed; the apertures comp...
The per-body material of a conjugate scalar, internal units (§4.2): conj 1 on a conjugate body; lam =...
G.x at the centre of extended-block cell j (physical; cellCentres' formula, unwrapped).
The census of the band (§9, G-SV10) over [lo, hi), LOCAL to this block: interfacial cells,...
The face viscosity under the sharp interface (§5.4 a, §6): a band edge across a (a ≠ c) takes μ̄_c,...
The band geometry and the closure constants, by value into every kernel.
Per-call census of the cascade over this block's inner region (LOCAL; a distributed caller sums them ...
Per-call census over the inner region (LOCAL; a distributed caller sums it).
flow — VoF rung V4 (WO-P): balanced-force continuum surface force + the capillary Δt.
static double val(long gi)
Definition symconv.cpp:27
static constexpr double AC
static double value(int gx, int gy, int gz)
flow — VoF rung V6 (WO-V6): the DYNAMIC contact angle (Cox-Voinov with an explicit slip length) and a...