22 [](D& diag,
int mode) {
23 if (mode != 5 && mode != 6)
24 throw std::invalid_argument(
25 "diagnostics.set_face_interp: mode must be 5 or 6 (the two intermediate rungs "
26 "of the embed port); the complete schemes are Solver.set_collocated_scheme("
27 "'plain' | 'gauge-exact' | 'embed' | 'ghost')");
28 diag.s->setFaceInterp(mode);
31 "The two INTERMEDIATE rungs of the Basilisk embed.h port on the collocated grid "
32 "(doc/history/collocated_embed_port_plan.md), reachable for the ladder that measures "
33 "what each piece of the complete port ('embed' = mode 7) is worth: 5 = the FV momentum "
34 "operator with the true-normal dirichlet_gradient wall drag as a defect correction, on "
35 "the wall-aware face map with the transpose-gradient pressure force; 6 = plus the "
36 "openness-weighted -grad(P) predictor and cell correction, on the plain face map "
37 "(7 adds the wall-aware face map and the solid-cut-cell sliver mask). CHANGES RESULTS; "
38 "no effect on the staggered solver. Modes 1-4 and 10-13 (ablations) were deleted with "
39 "their kernels at 1.0.0.");
41 "set_incremental_pressure",
42 [](D& diag,
bool on) {
return diag.s->setIncrementalPressure(on); }, nb::arg(
"on"),
43 "Toggle the rotational incremental-pressure projection.");
45 "set_pressure_warmstart", [](D& diag,
bool on) {
return diag.s->setPressureWarmstart(on); },
46 nb::arg(
"on"),
"Seed each pressure solve from the previous step's phi (default off).");
48 "set_rotational_pressure", [](D& diag,
bool on) {
return diag.s->setRotationalPressure(on); },
50 "PM I ablation (Guy-Fogelson 2005): False drops the rotational -mu*div(u*) term from "
51 "the incremental pressure accumulation (constant-mu path only). Default True = shipped "
52 "rotational (Timmermans) update.");
54 "set_rotational_filter",
55 [](D& diag,
bool on,
double eps) {
return diag.s->setRotationalFilter(on, eps); },
56 nb::arg(
"on"), nb::arg(
"eps") = 0.05,
57 "Experimental filtered rotational update: smooth div(u*) (mask-aware axis-wise 1-2-1, "
58 "one-sided into the fluid at walls) before accumulating -mu*div into P. Keeps the O(1) "
59 "pressure-relaxation gain, removes the checkerboard feedback channel.");
61 "set_rotational_weight", [](D& diag,
double w) {
return diag.s->setRotationalWeight(w); },
63 "Under-relax the rotational term: P += ct*phi - w*mu*div(u*). 1 = shipped, 0 = PM I; "
64 "small w raises the boundary-mode stability threshold ~1/w at ~1/w slower smooth-mode "
65 "pressure relaxation. phi=0 stays the unique fixed point for any w>0 at every dt.");
67 "set_rotational_wall_weight",
68 [](D& diag,
double w0) {
return diag.s->setRotationalWallWeight(w0); }, nb::arg(
"w0"),
69 "Wall-banded rotational blend: at fluid cells with a solid axis-neighbour use "
70 "P += (rho/dt + w0*mu/dx^2)*phi - (1-w0)*mu*div(u*); bulk keeps the full rotational "
71 "update. Stabilizes the boundary rows without slowing bulk pressure relaxation, and "
72 "keeps them relaxing at dt->infinity. 0 (default) = off.");
74 "set_aperture_order", [](D& diag,
int order) {
return diag.s->setApertureOrder(order); },
76 "Face-aperture estimator (DEFAULT 2 since 2026-08-26): 1 = legacy one-sample linear "
78 "marching-squares (5 samples/face, O(h^2); removes the convexity bias measured at "
79 "+0.59/+0.27% bed permeability at R=8/12 -- see doc/collocated_paper_plan.md row 51). "
80 "For analytic geometry, exact apertures via set_openness_override are better still. "
81 "Call before set_solid (a later call raises).");
83 "set_advection_wall_velocity",
84 [](D& diag,
bool on) {
return diag.s->setAdvectionWallVelocity(on); }, nb::arg(
"on"),
85 "A0: fill the advection inputs' masked (solid) rows with the instantaneous WALL "
86 "velocity instead of zeros, so a MOVING body's advective term sees the body's own "
87 "motion. DEFAULT True; False is the pre-A0 ablation (measurement only). Inert on a "
88 "static scene and on the collocated grid.");
90 "advection_wall_velocity", [](D& diag) {
return diag.s->advectionWallVelocity(); },
91 "Whether the wall-velocity advection inputs are in force.");
93 "set_uf_advection", [](D& diag,
bool on) {
return diag.s->setUfAdvection(on); },
95 "Advect the COLLOCATED momentum with the projected, divergence-free MAC face field "
96 "uf/vf/wf of the last projection instead of the un-projected cell->face average "
97 "0.5*(u_i+u_j). DEFAULT True -- the shipped scheme: doc/flow_colocated_plan.md "
98 "step 3, the Almgren-Bell-Colella prescription (the field the projection just made "
99 "solenoidal IS the conservative advective flux), and what the FOU operator's "
100 "conservative row-sum identity needs. False is the ablation that restores the phase-2 "
101 "average (measurement only; see doc/uf_advection.md). Inert on the staggered grid (the "
102 "stored velocity already IS the projected face velocity) and before the first "
103 "projection or set_velocity has built a face field.");
105 "uf_advection", [](D& diag) {
return diag.s->ufAdvection(); },
106 "Whether the projected face field is the collocated advecting velocity.");
109 [](D& diag,
const std::string& mode) {
113 else if (mode ==
"off")
115 else if (mode ==
"momentum")
117 else if (mode ==
"pressure")
120 throw std::runtime_error(
"set_comm_avoiding: 'both' | 'off' | 'momentum' | 'pressure'");
121 diag.s->setCommAvoiding(mask);
124 "Communication-avoiding red-black smoothing (multi-rank): exchange a 2-deep ghost layer "
125 "once per red-black PAIR instead of a 1-deep layer before every colour, redundantly "
126 "re-smoothing the first colour's ghost ring so the second colour reads exactly what a "
127 "per-colour exchange would have delivered. BIT-IDENTICAL, at half the halo events "
128 "(measured on host: np=32 weak efficiency 35% -> 62%). 'both' (DEFAULT on a host "
129 "backend) | 'off' (DEFAULT on a device backend: USER 2026-10-29, H100 weak scaling "
130 "measured CA off 21-39 ms/step faster) | 'momentum' "
131 "(the velocity RB-GS only) | 'pressure' (the pressure-multigrid coarse levels only) -- "
132 "the split exists to ATTRIBUTE a measured regression to one subsystem. Set it BEFORE "
133 "init_mpi (a later call raises: the momentum half is latched with the halo topology); "
134 "either half is inert on blocks smaller than 4 cells on any axis, and on a periodic axis "
135 "of odd global extent (the pressure half per multigrid level).");
139 const int m = diag.s->commAvoiding();
145 "The communication-avoiding smoothing mode in force (see set_comm_avoiding).");
147 "set_multigrid_aspect_threshold",
148 [](D& diag,
double theta) {
return diag.s->setMultigridAspectThreshold(theta); },
150 "Anisotropic-coarsening aspect threshold theta shared by the pressure and velocity "
151 "multigrids (doc/anisotropic_metric.md §5.1): an axis is coarsened only while its cell "
152 "size stays within theta of the smallest one, so a stretched grid semi-coarsens instead "
153 "of building levels whose operator is dominated by one direction. DEFAULT 2.0; must be "
154 "> 1; 1e9 restores full coarsening on every axis (the §8.5 item (c) ablation). Only "
155 "ever consulted on an ANISOTROPIC metric, so it is inert on cubic cells.");
157 "multigrid_aspect_threshold", [](D& diag) {
return diag.s->multigridAspectThreshold(); },
158 "The anisotropic-coarsening threshold in force (see "
159 "set_multigrid_aspect_threshold).");
161 "set_pressure_strict", [](D& diag,
bool on) {
return diag.s->setPressureStrict(on); },
163 "Raise instead of report when the pressure preconditioner returns a non-finite "
164 "correction. DEFAULT False: the shipped behaviour caps the solve, prints one line, and "
165 "raises the pressure_solve_failed() flag, so a check can catch it without changing "
166 "control flow. True turns the same event into an exception.");
168 "pressure_strict", [](D& diag) {
return diag.s->pressureStrict(); },
169 "Whether a non-finite pressure preconditioner output raises (see "
170 "set_pressure_strict).");
172 "set_pressure_coarse_ghost",
173 [](D& diag,
bool on) {
return diag.s->setPressureCoarseGhost(on); }, nb::arg(
"on"),
174 "Zero-gradient (Neumann) coarse ghost on wall/inflow faces before the pressure "
175 "multigrid's prolongation -- the WO-H symmetry repair. DEFAULT True. False restores "
176 "the pre-2026-08-30 periodic-wrap ghost, which reinstates the asymmetry that stalls "
177 "MG-PCG on every 3-D wall-bounded grid: a MEASUREMENT ABLATION, never a production "
178 "setting. Inert on periodic / IBM problems, where the two are the same.");
180 "pressure_coarse_ghost", [](D& diag) {
return diag.s->pressureCoarseGhost(); },
181 "Whether the Neumann coarse ghost is in force (see set_pressure_coarse_ghost).");
183 "set_fluid_only_constraint",
184 [](D& diag,
const std::string& mode) {
185 diag.s->setFluidOnlyConstraint(
189 "Fluid-only pressure constraint (route 2b, a collocated mechanism instrument; call "
191 "set_solid): 'filter' = Design A (openness filter), 'star' = Design B (SPD Kron star "
192 "elimination), 'off'. Any setting other than 'off' disables the AUTO scheme.");
194 "set_outer_iterations", [](D& diag,
int iters) {
return diag.s->setOuterIterations(iters); },
195 nb::arg(
"n"),
"Set the number of Picard/outer iterations per step.");
197 "set_outer_tolerance", [](D& diag,
double tol) {
return diag.s->setOuterTolerance(tol); },
198 nb::arg(
"tol"),
"Set the outer (Picard) convergence tolerance.");
200 "last_outer_iterations", [](D& diag) {
return diag.s->lastOuterIterations(); },
201 "Return the outer-iteration count from the last step().");
203 "set_velocity_solver",
204 [](D& diag,
const std::string& name) {
206 diag.s->setVelocitySolverAuto();
207 else if (name ==
"gauss_seidel") {
208 diag.s->setVelocityChebyshev(
false);
209 diag.s->setVelocityMultigrid(
false, 3, 40);
210 }
else if (name ==
"multigrid") {
211 diag.s->setVelocityChebyshev(
false);
212 diag.s->setVelocityMultigrid(
true, 3, 40);
213 }
else if (name ==
"chebyshev") {
214 diag.s->setVelocityMultigrid(
false, 3, 40);
215 diag.s->setVelocityChebyshev(
true);
217 throw std::invalid_argument(
218 "set_velocity_solver: expected 'auto', 'gauss_seidel', 'multigrid' or "
219 "'chebyshev', got '" +
223 "Which solver runs the implicit momentum (diffusion) equation. 'auto' (DEFAULT) picks by "
224 "the operator's condition number kappa = 1 + 4 dt mu (sum w)/rho -- the multigrid at "
225 "kappa >= 13, the smoother below -- and names no geometry, so an immersed body and a "
226 "domain-BC box at the same dt get the same solver. 'gauss_seidel' is the red-black "
227 "smoother; 'multigrid' the 3-level velocity V-cycle; 'chebyshev' Chebyshev "
228 "semi-iteration over a Gershgorin interval. ALL FOUR SOLVE THE SAME EQUATION TO THE SAME "
229 "TOLERANCE, so this changes cost and not the answer -- except that 'gauss_seidel' runs "
230 "out of sweeps above kappa ~ 50 and then returns a solution that never met it. "
231 "MEASURED (384^3 cut-cell bed, Snellius): multigrid beats gauss_seidel 1.66x-2.23x "
232 "across the CPU ladder and 2.19x on one H100; chebyshev beats gauss_seidel by the "
233 "sqrt(kappa) factor theory predicts but loses to multigrid except at the smallest "
234 "per-rank blocks, where the evidence is suggestive and not conclusive.");
236 "set_velocity_mg_smoother",
237 [](D& diag,
const std::string& name,
int degree,
double eig_ratio) {
238 if (name ==
"gauss_seidel")
239 diag.s->setVelocityMgChebyshev(
false);
240 else if (name ==
"chebyshev")
241 diag.s->setVelocityMgChebyshev(
true, degree, eig_ratio);
243 throw std::invalid_argument(
244 "set_velocity_mg_smoother: expected 'gauss_seidel' or 'chebyshev', got '" + name +
247 nb::arg(
"name"), nb::arg(
"degree") = 0, nb::arg(
"eig_ratio") = 10.0,
248 "Which smoother the velocity multigrid uses on every level -- orthogonal to "
249 "set_velocity_solver, and read only when that selects 'multigrid'. 'gauss_seidel' "
250 "(DEFAULT) or 'chebyshev'. ABLATION, AND CHEBYSHEV IS MEASURED SLOWER: at degree 4 / "
251 "eig_ratio 6 it IS the stronger smoother per cycle (8.0 V-cycles against red-black's "
252 "9.3) and still loses 1.21x on wall time, because matching red-black's smoothing "
253 "strength costs the same four halo exchanges two sweeps cost, while Chebyshev needs a "
254 "separate residual and update pass where a Gauss-Seidel sweep fuses the two. Kept "
255 "because it is the apparatus for a question that gets asked repeatedly. degree=0 "
256 "follows the V-cycle's own pre/post/bottom counts.");
260 return diag.s->velocityChebyshevActive() ? std::string(
"chebyshev")
261 : diag.s->velocityMultigridActive() ? std::string(
"multigrid")
262 : std::string(
"gauss_seidel");
264 "The momentum solver actually in force, resolving 'auto'. Only meaningful after the "
265 "first step(), which is where the choice is made (dt and mu are final only then).");
267 "velocity_mg_smoother",
269 return diag.s->velocityMgChebyshev() ? std::string(
"chebyshev")
270 : std::string(
"gauss_seidel");
272 "The velocity multigrid's smoother.");
274 "set_velocity_solver_params",
275 [](D& diag,
int iters,
double rtol,
int min_iters) {
276 diag.s->setVelocityIterations(iters);
277 diag.s->setVelocityTolerance(rtol, min_iters);
279 nb::arg(
"iters"), nb::arg(
"rtol") = 0.0, nb::arg(
"min_iters") = 2,
280 "Momentum smoother control: `iters` RB-GS sweeps per component, or with rtol > 0 a "
281 "TOLERANCE STOP — end the loop once the sweep's max velocity increment has contracted "
282 "to rtol of the first sweep's (iters becomes the cap, min_iters the floor). Easy "
283 "regimes (small nu*dt/dx^2) exit after ~3-5 sweeps; stiff regimes run to the cap "
284 "unchanged. rtol = 0 (default) is the legacy fixed count, byte-identical.");
286 "set_velocity_multigrid_auto",
287 [](D& diag,
long cellsPerRank,
long minGlobalCells,
int minBlockExtent) {
288 return diag.s->setVelocityMultigridAuto(cellsPerRank, minGlobalCells, minBlockExtent);
290 nb::arg(
"cells_per_rank"), nb::arg(
"min_global_cells") = -1, nb::arg(
"min_block_extent") = -1,
291 "Narrow the rule that selects the momentum solver. Since 2026-09-15 the DEFAULT is the "
292 "velocity V-cycle on every validated operator mode and at every rank count: measured on "
293 "the 1.0.0 scaling benchmark it is faster at every rung of both the CPU and the GPU "
294 "ladder (2.23x at 147k cells/rank, 2.19x on one H100), and the red-black smoother it "
295 "replaced was running at its sweep cap -- not converging -- on every rung of both. "
296 "cells_per_rank sets an upper bound in cells per rank (0 = never use the V-cycle); "
297 "set_velocity_multigrid_auto(65536, 1 << 23) restores the 1.0.0 behaviour exactly. "
298 "min_block_extent (default 16) is the shortest per-rank inner extent worth building a "
299 "hierarchy on. An explicit set_velocity_multigrid() overrides all of it.");
301 "velocity_multigrid_active", [](D& diag) {
return diag.s->velocityMultigridActive(); },
302 "Whether the velocity (momentum) solve uses the multigrid V-cycle rather than plain "
303 "RB-GS. Reads back the OUTCOME, not the setting: an explicit set_velocity_multigrid("
304 "on=...) call always wins, but absent one the AUTO rule (set_velocity_multigrid_auto) "
305 "decides it when the geometry is built (set_solid / set_pressure_geometry / "
306 "set_solid_from_scene) -- on for a distributed run (np > 1) in an eligible operator "
307 "mode with a global problem of at least min_global_cells (default 8M) and fewer than "
308 "cells_per_rank (default 65536) cells per rank, off otherwise. So the value can differ "
309 "from what the caller last set explicitly, and is only meaningful after geometry has "
310 "been installed (False on a fresh solver).");
321 const auto ob = diag.s->outflowBackflow();
323 d[
"max_reverse"] = ob.maxReverse;
324 d[
"fraction"] = ob.fraction;
325 d[
"energy_influx"] = ob.energyInflux;
326 d[
"reversed_faces"] = ob.reversed;
327 d[
"outlet_faces"] = ob.total;
330 "Outflow REVERSAL census over the outflow faces (collective under MPI): 'max_reverse' = "
331 "the largest reversed normal velocity max(0, -u.n), 'fraction' = reversed / all outlet "
332 "faces, 'energy_influx' = sum over the reversed faces of rho |u.n| |u|^2 / 2 -- the "
333 "kinetic-energy production the zero-gradient (do-nothing) outflow admits where the flow "
334 "re-enters, which is the mechanism that diverges an inflow/outflow run whose "
335 "recirculation reaches the outlet (a BFS bubble at x_r ~ L, a shed vortex). The "
336 "backflow stabilization (set_backflow_stabilization, default beta 0.2) removes beta rho "
337 "|u.n| |u_n|^2 of it; beta >= 0.5 is the unconditional energy bound. All zeros without "
338 "an outflow face or without reversal. step() warns once, on stderr, when reversal "
339 "appears while the stabilization is switched off.");
341 "last_momentum_residual", [](D& diag) {
return diag.s->lastMomentumResidual(); },
342 "max over components of max|r|/max|b| at exit of the last step's momentum solves "
343 "(residual mode only; -1 otherwise).");
345 "set_deferred_correction", [](D& diag,
bool on) {
return diag.s->setDeferredCorrection(on); },
347 "Deferred-correction advection: True (default) = 2nd order (implicit FOU + explicit "
348 "high-order correction, the high-order scheme being SOU by default or Koren TVD via "
349 "set_advection_scheme); False = pure implicit FOU (1st-order upwind, more dissipative "
351 "unconditionally stable at sharp shear layers).");
353 "set_pressure_mean_removal",
354 [](D& diag,
const std::string& scope) {
355 if (scope !=
"all" && scope !=
"fine")
356 throw std::runtime_error(
"set_pressure_mean_removal: scope must be 'all' or 'fine'");
357 diag.s->setPressureMeanRemoval(scope ==
"all");
360 "Nullspace (mean) removal scope in the pressure solve: 'fine' (DEFAULT — only the "
361 "projections the Krylov iteration needs: rhs/residual, the fine-level V-cycle exit, the "
362 "final iterate; ~3x fewer global-reduction latency hits per iteration, the measured "
363 "winner of the multi-GPU ablation) or 'all' (legacy — every V-cycle level + after every "
364 "matvec). Iteration counts are identical (A preserves mean-freeness); results equal "
365 "within solver tolerance, not bit-identical.");
367 "set_pressure_bottom_solver",
368 [](D& diag,
const std::string& engine) {
369 if (engine ==
"auto")
370 diag.s->setPressureBottomSolver(0);
371 else if (engine ==
"direct")
372 diag.s->setPressureBottomSolver(1);
373 else if (engine ==
"algebraic")
374 diag.s->setPressureBottomSolver(2);
376 throw std::runtime_error(
"set_pressure_bottom_solver: 'auto' | 'direct' | 'algebraic'");
379 "Engine of the AGGLOMERATED pressure bottom (set_pressure_bottom 'auto' / "
380 "'agglomerated'). 'auto' (DEFAULT): single rank, the singular (periodic / wall) "
381 "operator, a bottom of at most 8192 cells with at most 64 fluid components (solids "
382 "allowed) and an axis whose planes hold at most 192 cells, 'direct': one team launch "
383 "runs flexible CG in FP64 (inner tolerance 1e-5, cap 100) preconditioned by a "
384 "block-tridiagonal FP32 direct factor of the bottom (planes along one axis, explicit "
385 "Schur-complement inverses), refactored once per operator change -- no host transfer "
386 "on a GPU; on a host backend the team has min(8, team_size_max) threads and the FCG's "
387 "reductions run on one lane, so the result does not depend on the thread count. "
388 "Everywhere else the GraphAMG solve. 'direct' forces that engine and raises at the "
389 "bottom solve, naming the failed condition, where it is not eligible; 'algebraic' "
390 "forces GraphAMG (the A/B instrument). doc/vof_step_performance_design.md §13, §14 "
393 "set_pressure_line_relaxation",
394 [](D& diag,
bool enabled) { diag.s->setPressureLineRelaxation(enabled); }, nb::arg(
"enabled"),
395 "Zebra line relaxation in the pressure multigrid (DEFAULT True). On a level whose "
396 "finest axis has stopped coarsening (its extent no longer halves) while the other two "
397 "keep coarsening, so that the coarse cells are more than 2:1 elongated across it, the "
398 "smoother solves each line along that axis exactly (tridiagonal; cyclic for a periodic "
399 "axis) instead of relaxing point by point, which damps the error modes the coarse grid "
400 "cannot see. Every other level, and every grid without such a level, is unchanged; "
401 "False restores the point red-black smoother everywhere, bit for bit. Under MPI a level "
402 "whose line axis is split across ranks keeps the point smoother. Live. "
403 "doc/mg_depth_policy.md Amendment A2.");
405 "set_pressure_vcycle_symmetric",
406 [](D& diag,
bool enabled) { diag.s->setPressureVcycleSymmetric(enabled); },
408 "The symmetric pressure V-cycle (DEFAULT True since doc/mg_depth_policy.md A3, WO-S3). "
409 "True: every coarse-to-fine transfer adds the coarse parent's value to each fine cell "
410 "(piecewise-constant prolongation, the transpose of the cell-average restriction up to "
411 "the factor 2^k) and the smoothed coarsest level sweeps forward then in reverse, so the "
412 "V-cycle is a symmetric positive definite preconditioner and the CG drivers keep their "
413 "optimality on high-contrast and thin-slab grids. False: the pre-A3 trilinear "
414 "prolongation and forward bottom, bit for bit (the A/B lever). Applies to every "
415 "pressure driver (PCG, FCG, Chebyshev, the standalone V-cycle, the ghost projection's "
416 "BiCGStab), single rank and distributed, FP64 and FP32. Live. "
417 "doc/mg_depth_policy.md Amendment A3.");
419 "set_pressure_vcycle_precision",
420 [](D& diag,
const std::string& mode) {
422 diag.s->setPressureVcyclePrecision(0);
423 else if (mode ==
"fp64")
424 diag.s->setPressureVcyclePrecision(1);
425 else if (mode ==
"fp32")
426 diag.s->setPressureVcyclePrecision(2);
428 throw std::runtime_error(
"set_pressure_vcycle_precision: 'auto' | 'fp64' | 'fp32'");
431 "Precision of the V-cycle that preconditions the pressure PCG / FCG (single rank and "
432 "distributed). 'auto' (DEFAULT since 2026-10-19): 'fp32' where eligible, else 'fp64', "
433 "on a DEVICE backend (CUDA, HIP), with the FP64 restart below; on a host backend "
434 "(OpenMP, Serial) 'auto' is 'fp64' -- the host saves too little (~5-8 %) to pay for "
435 "FP32's risks. 'fp64': the FP64 V-cycle. 'fp32': FP32 face weights (the diagonal "
437 "stored), FP32 iterates and flux-form arithmetic on every level above the bottom, the "
438 "input scaled by an exact power of two; the Krylov matvec, dots, mean projection and "
439 "stop test stay FP64 -- raises at the solve, naming the failed condition, where not "
440 "eligible (an outflow face, an overlay solve, a non-bottom level with an odd inner "
441 "dimension, a float outer operator, a face weight outside [1e-30, 1e30], the "
442 "mean-removal scope 'all', a driver other than PCG / FCG); forced 'fp32' runs on host "
443 "backends too. Distributed, FP32 runs down to the first telescope point (FP64 below) "
444 "and an np=1 run is bitwise the single-rank run in every mode. Takes effect at once. "
445 "Its weight rounding is not invariant under a non-power-of-two change of units, and it "
446 "can cap where 'fp64' converges (hence the restart); pass 'fp64' for an FP64-only run. "
447 "RESTART: under 'auto' a PCG / FCG solve whose FP32 attempt does not meet "
448 "its stop test (a cap, a non-finite breakdown) is re-solved from x = 0 with the FP64 "
449 "V-cycle -- the 'fp64' solve of the same right-hand side -- with one warning line, and "
450 "'auto' then stays FP64 for the rest of the run (pressure_vcycle_precision() reads "
451 "'fp64'); calling this setter again re-arms it. Forced 'fp32' is never restarted (the "
452 "A/B mode). doc/vof_projection_distributed_design.md §4, §9 (the default). It saves ~19 "
454 "projection on a GPU "
455 "(bubble column, RTX 5080), ~11 % on a CPU. Outside the CG drivers' rated contrast "
456 "(density ratio above ~1e3 with walls) both precisions may cap; FP32 may cap earlier. "
457 "doc/vof_projection_cost_design.md §4.");
459 "set_pressure_initial_guess",
460 [](D& diag,
const std::string& mode,
int history) {
464 else if (mode ==
"zero")
466 else if (mode ==
"projected")
469 throw std::runtime_error(
"set_pressure_initial_guess: 'auto' | 'zero' | 'projected'");
470 diag.s->setPressureInitialGuess(m, history);
472 nb::arg(
"mode"), nb::arg(
"history") = 2,
473 "Initial guess of the pressure PCG / FCG solve of the projection (single rank and "
474 "distributed). 'zero' "
475 "(DEFAULT): x0 = 0. 'projected': the A-norm projection of the solution onto the span of "
476 "the last `history` (1 or 2) projection solutions, x0 = c1 phi^n + c2 phi^(n-1) with "
477 "the 2x2 Galerkin system of the current operator (never worse than x0 = 0 in the A-norm;"
478 " 0 on non-fluid cells), and the stop stays relative to the ZERO-guess residual "
479 "max|P b|, so the solve is never looser than the cold one. Raises at the solve, naming "
480 "the failed condition, where not eligible (the Chebyshev driver, the ghost projection, "
481 "set_pressure_warmstart(True)). 'auto': 'projected' where eligible, else 'zero', on "
483 "backend. 'projected' and 'auto' are opt-in, not the default (decided 2026-10-15). "
484 "Distributed, the Gram system is allreduced, so every rank takes the same guess; an "
485 "np=1 run is bitwise the single-rank run. The history "
486 "restarts empty (a cold solve, then one increment, then two) after "
487 "this call, a geometry change (set_solid, set_pressure_geometry, init_mpi, "
488 "redistribute / rebalance_by_weights), a state write (set_field of u/v/w/p/phi, "
489 "set_state, set_velocity), a "
490 "driver change, and a failed or capped solve. RESTARTS: no history is checkpointed, so"
491 " a run restarted from saved fields takes those two cold-history steps and agrees with "
492 "the uninterrupted run to the solver tolerance, not bitwise. "
493 "doc/vof_projection_cost_design.md §5, doc/vof_projection_distributed_design.md §6.");
495 "set_pressure_prefactor_hoist",
496 [](D& diag,
bool on) { diag.s->setPressurePrefactorHoist(on); }, nb::arg(
"on"),
497 "Switch the side-instance bottom prefactor (doc/vof_gpu_coarse_tail_design.md §5.6, "
498 "default ON) off: the variable-rho coefficients are then built in the projection and "
499 "the direct bottom factored lazily in the bottom solve. Same state bit for bit; for "
500 "tests and timing comparisons.");
502 "num_pressure_prefactors", [](D& diag) {
return diag.s->pressurePrefactorCount(); },
503 "Side-instance bottom factors launched so far (0 where the prefactor is ineligible: "
504 "host backends, MPI, constant density, a balanced-force or Chebyshev configuration).");
506 "pressure_vcycle_precision",
507 [](D& diag) {
return std::string(diag.s->pressureVcycleFp32() ?
"fp32" :
"fp64"); },
508 "The precision ('fp32' or 'fp64') the last pressure solve's V-cycles used "
509 "(set_pressure_vcycle_precision); 'fp64' before any FP32 solve.");
511 "set_pressure_graph_amg", [](D& diag,
bool on) {
return diag.s->setPressureGraphAmg(on); },
513 "Solve the pressure MG's coarsest level with an agglomerated mesh-agnostic algebraic "
514 "multigrid (core GraphAMG), decomposition-agnostic: with levels=1 this gives a "
515 "mesh-independent pressure solve that works under a WEIGHTED ORB (where the geometric "
516 "coarse levels can't cleanly coarsen). Applied at the next set_solid.");
518 "set_exact_crossings",
519 [](D& diag,
const std::vector<double>& t) {
return diag.s->setExactCrossings(t); },
521 "Analytic-SDF capability: exact wall-crossing fractions overriding the "
522 "linear-interpolated theta in the momentum cut-cell overlay AND the ghost-projection "
523 "closures. Flat array of 9*nx*ny*nz values, blocks [(c*3+k)]: component c's staggered "
524 "point at inner cell i toward its +k neighbour; NaN = no crossing. Call BEFORE "
525 "set_solid (a later call raises); empty list clears. Single-rank, staggered momentum "
528 "set_openness_override",
529 [](D& diag,
const std::vector<double>& ox,
const std::vector<double>& oy,
530 const std::vector<double>& oz) {
return diag.s->setOpennessOverride(ox, oy, oz); },
531 nb::arg(
"ox"), nb::arg(
"oy"), nb::arg(
"oz"),
532 "Analytic-SDF capability: exact face-aperture (openness) fields for the cut-cell "
533 "projection, overriding the sampled-SDF openness. Inner nx*ny*nz arrays, x-fastest; "
534 "ox[i] = fluid fraction of the -x face of cell i. Call BEFORE set_solid (a later call "
535 "raises); empty ox clears. Single-rank.");
537 "set_ghost_projection",
538 [](D& diag,
bool on,
int matrixOrder,
int rhsOrder) {
539 return diag.s->setGhostProjection(on, matrixOrder, rhsOrder);
541 nb::arg(
"on"), nb::arg(
"matrix_order") = 2, nb::arg(
"rhs_order") = 2,
542 "QUARANTINED 2026-08-18 (verification only, unsupported): superseded by the gauge-exact "
543 "collocated scheme, which matches its accuracy at 5-6x lower cost. Kept as the "
544 "independent second discretization behind the cross-IBM physics gate. Enabling it on the "
545 "collocated grid silently selects the plain face map, since it owns the operators the "
546 "gauge-exact scheme replaces. EXPERIMENTAL directional ghost-cell projection (second "
547 "staggered IBM): point-based FD "
548 "divergence with wall-anchored directional closures instead of the openness-weighted "
549 "cut-cell projection; solved by MG-preconditioned BiCGStab. Call BEFORE set_solid (a "
550 "later call raises). "
551 "Closure orders (1=linear, 2=quadratic): (matrix_order, rhs_order) = (2,2) full "
552 "quadratic 13-point matrix; (1,1) linear 7-point; (1,2) mixed/deferred — 2nd-order "
553 "steady constraint on a 7-point matrix. Collocated: the same closures/matrix on the "
554 "face-averaged field, plus a directional (one-sided 2nd-order) cell gradient for the "
555 "-grad(P) predictor and cell correction; requires face_interp 0. v1: single-rank, "
556 "periodic + IBM, stationary walls; incompatible with "
557 "porous/variable-rho/domain-BC/Chebyshev.");
559 "pressure_mg_level_ratios", [](D& diag) {
return diag.s->pressureMgLevelRatios(); },
560 "The pressure multigrid's per-level coarsening ratio, one (rx, ry, rz) per level "
562 "On an isotropic domain every coarsenable axis halves, as it always has. On an "
563 "ANISOTROPIC one (extent giving different spacings per axis) the hierarchy coarsens "
564 "the FINEST coarsenable axis and defers one that is already at least "
565 "set_multigrid_aspect_threshold (default 2) times coarser, so the coarse operators stay "
567 "to isotropic and the point smoother keeps its rate -- e.g. cells (N, 2N, N/2) on a "
568 "cube gives (1,2,1), (2,2,1), (2,2,2), ... Empty until set_solid/"
569 "set_pressure_geometry has built the operator. See flow/doc/anisotropic_metric.md "
572 "last_superficial_velocity_shift",
573 [](D& diag) {
return diag.s->lastSuperficialVelocityShift(); },
574 "The uniform velocity shift set_superficial_velocity applied at the end of the last "
575 "step() (physical velocity units; 0 when it is off). Reading it synchronises with the "
578 "last_balanced_force_iterations",
579 [](D& diag) {
return diag.s->lastBalancedForceIterations(); },
580 "Pressure-driver iterations of the last step's balanced-force solve "
581 "(set_balanced_force_projection); 0 when it is off, the force divergence was zero, or "
582 "the previous split already met the stop.");
584 "last_balanced_force_failed", [](D& diag) {
return diag.s->lastBalancedForceFailed(); },
585 "Whether the last step's balanced-force solve FAILED (driver breakdown or a non-finite "
586 "result). A failed solve keeps P and p_balanced unchanged for that step; the first one "
589 "balanced_force_failures", [](D& diag) {
return diag.s->balancedForceFailures(); },
590 "How many balanced-force solves have failed over the solver's lifetime (see "
591 "last_balanced_force_failed).");
593 "anderson_accelerator",
594 [](D& diag,
int window,
double mixing) {
597 nb::arg(
"window") = 5, nb::arg(
"mixing") = 1.0, nb::rv_policy::take_ownership,
598 nb::keep_alive<0, 1>(),
599 "A new Anderson accelerator of this solver's steady march "
600 "(doc/steady_acceleration.md; the public driver is peclet.flow.march_to_steady). "
601 "window in [1, 8] (default 5), mixing in (0, 1] (default 1.0). Raises on an "
602 "unsupported configuration (a collocated scheme other than 'ghost', VoF, phase change, "
603 "scalars, porous, variable properties, drag, cell forces, moving scenes, superficial "
604 "velocity, pressure warm start, the balanced-force projection) and when the history, "
605 "(2m+3) * n_fields * 8 * n_padded bytes, does not fit. Collective under MPI.");
607 "last_pressure_iterations", [](D& diag) {
return diag.s->lastPressureIterations(); },
608 "Return the pressure-solver iteration count from the last step().\n\n"
609 "A solve that BROKE DOWN (non-finite preconditioner output) reports the iteration "
610 "CAP, so the usual rule-3b 'a capped pressure solve invalidates the run' check sees "
611 "it; pressure_solve_failed() distinguishes the two.");
613 "num_pressure_chebyshev_restarts",
614 [](D& diag) {
return diag.s->numPressureChebyshevRestarts(); },
615 "How many Chebyshev pressure solves were redone on cold spectral bounds since "
616 "construction. Under variable density the bounds are re-estimated every step "
617 "from the previous estimate's power iterates (5 + 5 iterations instead of "
618 "15 + 15 from the right-hand side); a solve on such bounds that reaches the "
619 "cap, or whose residual after 3 iterations exceeds the initial one, is redone "
620 "on a cold estimate and counted here; the abandoned attempt's V-cycles count in "
621 "last_pressure_iterations().");
623 "num_pressure_chebyshev_growth_trips",
624 [](D& diag) {
return diag.s->numPressureChebyshevGrowthTrips(); },
625 "How many Chebyshev pressure solves on cold spectral bounds (the main projection's "
626 "and the balanced-force pre-projection's) saw their residual rise above the initial "
627 "one, since construction. Chebyshev converges for every eigenvalue below the sum of "
628 "its two bounds, so a growing residual means lambda_max was underestimated: the bounds "
629 "are re-estimated with a bracketing margin (1.15 on lambda_max) and the solve is "
630 "redone once from its starting iterate; the first such case prints a stderr notice. "
631 "Expected 0; a solve that does not trip is unchanged bit for bit. "
632 "doc/mg_depth_policy_log.md 2026-10-30.");
634 "num_pressure_unconverged_solves",
635 [](D& diag) {
return diag.s->numPressureUnconvergedSolves(); },
636 "How many MG-PCG / flexible-CG pressure solves (main and balanced-force projection) "
637 "since construction ended UNCONVERGED: capped, broken down, or stopped on their "
638 "recurrence residual while the TRUE residual max|b - A x| (the stop test's norm and "
639 "mean removal) exceeded max(10 rtol, 1e-8) * r0 -- the floor keeps a round-off-limited "
640 "solve at a near-machine rtol silent. Each is also reported on "
641 "stderr (the first, then the 10th, 100th, ...). Under the trilinear V-cycle "
642 "(set_pressure_vcycle_symmetric(False)) above a density ratio of ~1e3 the preconditioner "
643 "turns indefinite and both CG drivers can stop 'converged' on a field that is not a "
644 "projection; the default SPD V-cycle keeps them healthy there. The check reads the "
645 "result only: fields and iteration counts are unchanged. "
646 "Identical on every rank.");
648 "last_pressure_true_residual", [](D& diag) {
return diag.s->lastPressureTrueResidual(); },
649 "The last MG-PCG / flexible-CG pressure solve's TRUE residual max|b - A x| divided by "
650 "its stop tolerance rtol * r0 (r0 the initial residual, or the balanced-force "
651 "projection's full right-hand side): <= 1 means the exit really meets the tolerance; "
652 "above max(10, 1e-8 / rtol) the solve counts in num_pressure_unconverged_solves. "
653 "Unit-free. Not updated "
654 "by Chebyshev or ghost-projection (BiCGStab) solves; 0 before the first CG solve and "
655 "after one with a zero right-hand side.");
657 "pressure_solve_failed", [](D& diag) {
return diag.s->pressureSolveFailed(); },
658 "Did the last pressure solve break down on a non-finite recurrence scalar (a "
659 "preconditioner or operator that produced NaN/Inf)?\n\n"
660 "The driver then zeroes the correction and continues -- so the projection was handed "
661 "NOTHING for that step and the run is invalid. Until 2026-09-04 the only trace was one "
662 "line on stdout ('preconditioner produced non-finite z') while "
663 "last_pressure_iterations() reported 0, i.e. a perfectly healthy-looking solve "
664 "(measured: examples/pore-scale-imbibition, a 3.1-cell throat). Set "
665 "set_pressure_strict(True) to raise instead.");
670 d[
"step"] = diag.s->lastStepSeconds();
671 d[
"predictor"] = diag.s->lastPredictorSeconds();
672 d[
"momentum"] = diag.s->lastMomentumSeconds();
673 d[
"projection"] = diag.s->lastProjectionSeconds();
674 d[
"pressure_allreduce"] = diag.s->lastPressureAllreduceSeconds();
675 d[
"pressure_allreduce_count"] = diag.s->lastPressureAllreduceCount();
676 d[
"momentum_sweeps"] = diag.s->lastMomentumSweeps();
679 "Per-phase wall times (seconds, THIS rank, device-fenced) of the last step(): "
681 "(ghost fills + RHS/advection/stencil builds), 'momentum' (implicit-diffusion solves), "
682 "'projection' (cut-cell pressure projection), 'step' (whole step). "
683 "'pressure_allreduce'/'pressure_allreduce_count' = time in / number of global reductions "
684 "(MPI_Allreduce) inside the pressure solve — the latency-bound term of the distributed "
685 "solve (0 on a single rank).");