flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
flow_bindings_core.hpp
Go to the documentation of this file.
1
9#pragma once
10
12
13namespace peclet::flow::bindings {
14
17template <class Grid, class C>
18inline void bindSolverSetup(C& cls) {
19 using S = BoundSolver<Grid>;
20 using D = Diagnostics<Grid>;
21 cls.def_prop_ro(
22 "diagnostics", [](S& s) { return D{&s}; }, nb::keep_alive<0, 1>(),
23 "The developer tier of this solver (instruments, tuning, ablations, internals).");
24 cls.def("__init__", &chk::initCells<S>, nb::arg("nx"), nb::arg("ny"), nb::arg("nz"),
25 "Create a solver on an nx x ny x nz grid of UNIT cells (x-fastest, I = x + y*nx + "
26 "z*nx*ny). Everything is then in cell units: the cell size is 1 and lengths, "
27 "velocities and the SDF are measured in cells. Prefer the physical form "
28 "Solver((nx,ny,nz), extent=(Lx,Ly,Lz)). Set the domain BCs before the geometry (a later "
29 "set_domain_bc raises).");
30 cls.def("__init__", &chk::initPhysical<S>, nb::arg("cells"), nb::arg("extent") = nb::none(),
31 nb::arg("origin") = std::array<double, 3>{0.0, 0.0, 0.0},
32 nb::arg("global_cells") = nb::none(),
33 "Create a solver on a PHYSICAL domain: `cells` = (nx, ny, nz), `extent` = the box side "
34 "lengths (Lx, Ly, Lz) and `origin` = its lower corner, all in the caller's own "
35 "consistent units. The cell size is extent/cells and is never written by the user: "
36 "rho, mu, dt, body forces, boundary velocities, surface tension, the SDF handed to "
37 "set_solid and the coordinates of set_scene are all physical, and the velocity, "
38 "pressure and curvature that come back are physical too.\n\n"
39 "extent=None (the default) keeps the historical CELL-UNIT behaviour, bit for bit: the "
40 "spacing is 1 and every quantity is in cells.\n\n"
41 "ANISOTROPIC cells (extent/cells different per axis) are supported since Phase 2 on the "
42 "staggered Solver AND (since commit C4) on SolverColocated: sampled or scene geometry, "
43 "constant or variable properties, variable density, porous continuity with or without "
44 "implicit drag, every domain-BC type, every pressure driver and bottom, the velocity "
45 "multigrid, scalar transport, the hydrodynamic force and torque integrals, and MPI. "
46 "moving geometry included. What still REFUSES one, with a message naming the three "
47 "spacings and what lifts it: enable_vof (Phase 3). "
48 "Three spacings that agree to 1e-12 relative are SNAPPED "
49 "to one, so an isotropic domain stays bit-identical however its extent was written. "
50 "Under MPI `cells` is this rank's block (from "
51 "mpi_block) while `extent`/`origin` describe the GLOBAL domain, so pass the global "
52 "grid as `global_cells` - the same numbers init_mpi gets.");
53 cls.def_prop_ro(
54 "cells", [](S& s) { return std::array<long, 3>{s.nx(), s.ny(), s.nz()}; },
55 "This rank's inner block resolution (nx, ny, nz) -- the shape of every field array "
56 "(get_u, get_p, the SDF for set_solid). Under MPI it is the LOCAL block from mpi_block().");
57 cls.def_prop_ro(
58 "global_cells", [](S& s) { return s.globalCells(); },
59 "The GLOBAL grid resolution (gnx, gny, gnz); == `cells` single-rank, the numbers "
60 "init_mpi gets under MPI (the CFD-DEM co-decomposition weight field is this shape).");
61 cls.def_prop_ro(
62 "extent", [](S& s) { return s.domainExtent(); },
63 "The GLOBAL domain side lengths. Equal to the cell counts without a physical domain.");
64 cls.def_prop_ro(
65 "origin", [](S& s) { return s.domainOrigin(); },
66 "The physical lower corner of the GLOBAL domain (0,0,0 by default).");
67 cls.def_prop_ro(
68 "spacing", [](S& s) { return s.spacing(); },
69 "The cell size [dx, dy, dz] = extent/cells as three floats; [1.0, 1.0, 1.0] "
70 "without a physical domain (the cell-unit default). Three spacings within 1e-12 "
71 "relative are snapped to one value, so an isotropic box is exactly isotropic.");
72 cls.def_prop_ro(
73 "unit_scales",
74 [](S& s) {
75 const auto& u = s.unitScales();
76 nb::dict d;
77 d["identity"] = !u.physical;
78 d["h_ref"] = u.hRef;
79 d["rho_ref"] = u.rhoRef;
80 d["t_ref"] = u.tRef;
81 d["length_to_internal"] = u.lenToInt();
82 d["velocity_to_internal"] =
83 std::vector<double>{u.velToInt(0), u.velToInt(1), u.velToInt(2)};
84 d["time_to_internal"] = u.timeToInt();
85 d["density_to_internal"] = u.rhoToInt();
86 d["viscosity_to_internal"] = u.muToInt();
87 d["pressure_to_internal"] = u.pToInt();
88 d["force_density_to_internal"] =
89 std::vector<double>{u.forceToInt(0), u.forceToInt(1), u.forceToInt(2)};
90 d["force_to_physical"] = u.forceTotalToPhys();
91 d["torque_to_physical"] = u.torqueToPhys();
92 // scalar transport + the phase-change energy path (a transported scalar itself, a
93 // temperature or a concentration, is never rescaled)
94 d["diffusivity_to_internal"] = u.diffToInt();
95 d["mass_flux_to_internal"] = u.mdotToInt();
96 d["latent_heat_to_internal"] = u.latentToInt();
97 d["conductivity_to_internal"] = u.condToInt();
98 d["heat_capacity_to_internal"] = u.rcpToInt(); // volumetric, rho*c_p
99 d["interface_resistance_to_internal"] = u.rintToInt();
100 d["divergence_to_internal"] = u.divToInt();
101 return d;
102 },
103 "The factors between the caller's units and the ones the solver computes in.\n\n"
104 "The solver keeps computing on the UNIT LATTICE and folds the metric into constants at "
105 "its API boundary, so every array reached through the RAW field registry "
106 "(diagnostics.field_view / get_field / set_field) is in those INTERNAL units, unlike "
107 "get_u/get_p, "
108 "which convert. `identity` is True when no extent was given, and then every factor is "
109 "exactly 1.0 and internal == physical. Multiply a physical value by *_to_internal, and "
110 "an internal one by force_to_physical (a total force) to come back. The registered "
111 "'mdot' field is in mass_flux_to_internal units and 'pc_source' / 'div_source' in "
112 "divergence_to_internal units; a transported scalar is never rescaled.");
113 cls.def_prop_ro(
114 "physical_units", [](S& s) { return s.hasPhysicalDomain(); },
115 "True when the solver was given an extent, i.e. lengths are physical rather than cells.");
116 cls.def(
117 "cell_centers",
118 [](S& s) { return nb::make_tuple(s.cellCentres(0), s.cellCentres(1), s.cellCentres(2)); },
119 "The physical cell-center coordinates of THIS rank's inner block as three 1-D float64 "
120 "arrays (x, y, z), i.e. origin + (i + 1/2) * spacing per axis. "
121 "np.meshgrid(*s.cell_centers(), indexing='ij') is the grid an SDF for set_solid is "
122 "sampled on. Under MPI these are the LOCAL block's centers in GLOBAL coordinates. "
123 "CELL-UNIT TRAP: without an extent this is i + 1/2, while set_scene puts cell i's centre "
124 "at i -- the same body given as a scene and as an SDF sampled here lands half a cell "
125 "apart. With an extent both use origin + (i + 1/2) * spacing. Unifying the cell-unit "
126 "convention changes results; deferred to 2.0.0.");
127 cls.def("set_rho", &chk::setRho<S>, nb::arg("rho"),
128 "Set the fluid density rho (the caller's units). Under a physical domain the FIRST call "
129 "pins the reference density the internal scales are built on; a later change rebuilds "
130 "the momentum operator at the next step.");
131 cls.def("set_mu", &chk::setMu<S>, nb::arg("mu"),
132 "Set the dynamic viscosity mu (the caller's units); a change after the geometry "
133 "rebuilds the momentum operator at the next step.");
134 cls.def("set_viscous_stress", &S::setViscousStress, nb::arg("form"),
135 "Viscous stress form under variable viscosity: 'auto' (default), 'full' or "
136 "'laplacian'. 'full' = div(mu (grad u + grad u^T)), the transpose term explicit on u^n "
137 "as conservative MAC stress elements (doc/full_viscous_stress.md); 'laplacian' = "
138 "div(mu grad u), the form before the AUTO default (it reproduces earlier variable-mu "
139 "numbers). The Laplacian form imposes the wrong tangential stress condition at a "
140 "viscosity jump (an "
141 "h-independent interface force: +19.5 % rise velocity for a drop at viscosity ratio "
142 "0.1). 'auto' resolves at each step to 'full' on the staggered Solver with the "
143 "arithmetic face viscosity, no porous momentum, no moving scene instances and no "
144 "immersed solid, else to 'laplacian' with a one-time stderr notice. Inert for a "
145 "constant mu. An explicit 'full' is staggered-only (SolverColocated raises) and is "
146 "refused at step() with the harmonic face viscosity, porous momentum or moving scene "
147 "instances. With solids it stays allowed, but it drops the transpose flux across the "
148 "staircase face: an O(gamma h) near-wall error on oblique walls (gamma the wall shear "
149 "rate), present for any non-uniform mu; the repair is open. "
150 "The form is a name, not a physical quantity.");
151}
152
155template <class Grid, class C>
156inline void bindSolverControls(C& cls) {
157 using S = BoundSolver<Grid>;
158 cls.def("set_dt", &chk::setDt<S>, nb::arg("dt"),
159 "Set the time step dt (the caller's time unit); the momentum solve is scaled by 1/dt "
160 "(well-conditioned at large dt). Under a physical domain the FIRST call pins the "
161 "reference time the internal scales are built on; any later call (step_adaptive "
162 "makes them) rebuilds the momentum operator at the next step.");
163 cls.def("set_body_force", &chk::setBodyForce<S>, nb::arg("force"),
164 "Set the body force per unit volume (fx, fy, fz) as one 3-sequence — e.g. a mean "
165 "pressure gradient.");
166 cls.def(
167 "set_superficial_velocity",
168 [](S& s, bool enabled, const std::string& axis, double velocity) {
169 chk::finite("set_superficial_velocity", "velocity", velocity, "length/time");
170 s.setSuperficialVelocity(
171 enabled, enum_index(axis, kAxes, "set_superficial_velocity", "axis"), velocity);
172 },
173 nb::arg("enabled"), nb::arg("axis") = "x", nb::arg("velocity") = 0.0,
174 "Hold the SUPERFICIAL velocity along a periodic axis at `velocity` (physical units): "
175 "the volume mean of that velocity component, i.e. the volume flux of the MIXTURE "
176 "through any cross-section divided by the cross-section's full area. In multiphase "
177 "flow 'velocity' alone is ambiguous between superficial and interstitial (per-phase); "
178 "this is the superficial one. At the end of every step() one uniform shift is "
179 "added to that component on every face; on an axis with no boundary a uniform shift "
180 "of the normal velocity leaves every cell divergence unchanged, so the field stays "
181 "discretely divergence-free. `velocity = 0` is a closed (batch) column: the flow can "
182 "circulate but not pass through (TBFsolver's constant flow rate at 0). The mean is a "
183 "device reduction, global under MPI; single-rank the step makes no host round trip for "
184 "it. Staggered Solver, all-fluid domain (set_pressure_geometry), periodic `axis` only "
185 "-- step() raises otherwise. set_superficial_velocity(False) turns it off. "
186 "diagnostics.last_superficial_velocity_shift() is the shift the last step applied.");
187 cls.def("set_balanced_force_projection", &S::setBalancedForceProjection, nb::arg("enabled"),
188 "Balanced-force projection (flow doc/collocated_varrho_forces.md §4.6), on both grids. "
189 "Once per step, before the momentum predictor, the gradient part of the forces "
190 "(set_body_force, the per-cell force fields, the CSF) is moved into the pressure with "
191 "one extra solve of the projection's own operator, so static balances -- a hydrostatic "
192 "column, a constant-curvature drop -- are exact from the first step at every "
193 "viscosity, dt, density ratio and immersed-solid aperture. The solve does not depend "
194 "on the flow state, so stability and the converged steady state are identical on and "
195 "off; off leaves a decaying transient balance residue. get_p() stays the total "
196 "physical pressure; its balanced part is the registered field 'p_balanced', which is "
197 "RESTART STATE: registered as soon as the option is active, restoring it with 'p' "
198 "(set_field) keeps the split, and omitting it (or switching the option on after steps "
199 "with it off) re-splits P -- never a second copy of the balanced pressure. "
200 "Cost: one extra pressure solve per step while the forces change, "
201 "solved for the increment of the previous split and skipped when that is already "
202 "converged -- a static interface costs no iterations. Default: "
203 "ON on SolverColocated with variable density or surface tension, OFF otherwise; with "
204 "an inflow/outflow face that default resolves OFF (a one-time stderr notice says "
205 "so); an explicit call always wins. Refused (named error) with porous continuity, the "
206 "ghost projection, "
207 "set_fluid_only_constraint(2), the block CSF, inflow/outflow faces, the "
208 "non-incremental pressure, and on the constant-density SolverColocated path (nothing "
209 "to balance there).");
210 cls.def_prop_ro(
211 "balanced_force_projection", [](S& s) { return s.balancedForceProjection(); },
212 "Whether the balanced-force projection runs (see "
213 "set_balanced_force_projection).");
214 cls.def("set_advection", &S::setAdvection, nb::arg("on"),
215 "Enable/disable momentum advection (high-order scheme SOU by default; implicit FOU + "
216 "deferred correction on the domain-BC path). ON by default since 2026-10-23; False => "
217 "Stokes (no inertia), which a creeping-flow script must now ask for. Inert under "
218 "enable_vof_momentum, whose VoF fluxes carry the momentum advection.");
219 cls.def(
220 "set_advection_scheme",
221 [](S& s, const std::string& scheme) {
222 s.setAdvectionScheme(enum_index(scheme, kAdvSchemes, "set_advection_scheme", "scheme"));
223 },
224 nb::arg("scheme"),
225 "High-order momentum advection scheme: 'sou' (second-order upwind, the default) or "
226 "'koren' (Koren TVD).");
227 cls.def("set_collocated_scheme", &S::setCollocatedScheme, nb::arg("name"),
228 "Collocated cut-cell projection scheme (no effect on the staggered solver). DEFAULT "
229 "since 2026-08-25: AUTO = 'ghost' where supported, falling back to 'gauge-exact' with "
230 "a stderr notice on porous/variable-rho/domain-BC/Chebyshev configurations (ghost v1 "
231 "limits); any explicit selection here disables AUTO.\n"
232 " 'ghost' -- the fluid-only constraint scheme (binary-openness divergence + directional "
233 "closures + the same gauge-exact gradient). Family-free, unconditionally stable "
234 "(dt 60..1e20, no stabilizer), protocol-independent (C2), both-bed clean ladder "
235 "-1.4% (R=8) -> +0.22% asymptote, Z&H anchor -0.018% at N=128. Costs: nonsymmetric "
236 "BiCGStab pressure solve (~2.3-2.7x), ~1.6 KB/cell overlay (single-GPU size cap), "
237 "fragmentation guard. MPI-capable (np=1,2,4 ctests); at-scale np>=16 hardening in "
238 "progress. Equivalent to diagnostics.set_ghost_projection(True, 2, 2); the (1, 2) "
239 "mixed mode stays quarantined there.\n"
240 " 'gauge-exact' (the AUTO fallback) -- the aperture constraint with the directional "
241 "gauge-exact pressure gradient. Cheapest scheme measured (symmetric MG-PCG, no "
242 "fragmentation guard). CAVEATS from the 2026-08 campaign "
243 "(doc/collocated_invisible_subspace.md): possesses an attractor FAMILY of steady states "
244 "(support-inconsistent gradient/constraint pair) selected by march protocol, and a "
245 "rotational-update instability whose wall-blend stopgap "
246 "(diagnostics.set_rotational_wall_weight) has a resolution-dependent margin -- UNSTABLE "
247 "at (R>=16 cells/radius, dt>=600); use fixed dt<=60 protocols at high resolution. "
248 "Clean-protocol bias vs the staggered reference: -2.5% (R=8) -> ~+0.2% asymptote.\n"
249 " 'embed' -- the complete Basilisk embed.h port (doc/history/"
250 "collocated_embed_port_plan.md): the finite-volume momentum operator with the "
251 "true-normal dirichlet_gradient wall drag applied as a defect correction on the IBM "
252 "matrix, the openness-weighted -grad(P) predictor and cell correction, the wall-aware "
253 "face map and the solid-cut-cell sliver mask. The live candidate for removing the "
254 "collocated accuracy ceiling; its two intermediate rungs are "
255 "diagnostics.set_face_interp(5 | 6).\n"
256 " 'plain' -- the legacy path: plain 1/2-1/2 face average + central-difference grad(P). "
257 "FIRST order at curved cut cells (the cell gradient reads the decoupled p=0 of "
258 "solid-centred neighbours, an O(1/h) gauge error), and on a dense bed it also fails to "
259 "reach steady state within 800 steps at coarse resolution. Kept for reproducing "
260 "published results.");
261 cls.def("set_decomposition", &S::setDecomposition, nb::arg("levels"),
262 nb::arg("max_imbalance") = 1.05,
263 "Choose how this solver's shared MPI decomposition is built. levels=0 (DEFAULT) = AUTO: "
264 "the aligned ORB (split positions on the FINE grid snapped to a power of two, capped at "
265 "16, i.e. 5 nested multigrid levels) whenever it is exactly balanced; otherwise the "
266 "coarse-first partition at depth 5, then 4, built with a balance-aware split axis, the "
267 "first whose max-block/min-block ratio stays within max_imbalance (default 1.05) and "
268 "that nests at least as many levels in place as the aligned ORB (every block even and "
269 "at least 4 cells wide at each); otherwise the balance-aware aligned ORB if it has a "
270 "smaller largest block and nests at least min(3, the aligned ORB's) levels; otherwise "
271 "the aligned ORB. AUTO "
272 "never cuts an axis the aligned ORB leaves whole, and changes its set of cut axes only "
273 "when the aligned ORB's largest block is at least 5/4 of the mean. levels=1 = the "
274 "aligned ORB as is "
275 "(the default before 2026-10: use it to reproduce an older np > 1 partition). "
276 "levels >= 2 = COARSE-FIRST: build the ORB on the grid coarsened levels-1 times and "
277 "refine the partition upward, so every block is a multiple of the coarsening factor BY "
278 "CONSTRUCTION and the hierarchy nests for the full requested depth; each depth from "
279 "`levels` down to 2 is built and MEASURED, and the deepest one within max_imbalance is "
280 "taken, else the aligned ORB. levels < 0 or max_imbalance <= 1.0 raise ValueError. Call "
281 "BEFORE init_mpi() (a later call raises), and pass "
282 "the SAME levels / max_imbalance to flow.mpi_block() -- both derive the same partition "
283 "and must agree.");
284 cls.def_prop_ro("decomposition_levels", &S::decompositionLevels,
285 "This solver's decomposition mode (0 = auto, 1 = aligned ORB, >= 2 = "
286 "coarse-first with that depth).");
287 cls.def_prop_ro("decomposition_max_imbalance", &S::decompositionMaxImbalance,
288 "The load-imbalance budget the auto and coarse-first searches stay within.");
289 cls.def("set_pressure_bottom_extent", &S::setPressureBottomExtent, nb::arg("cells"),
290 "The threshold set_pressure_bottom('auto') applies: agglomerate the coarsest level "
291 "onto a global operator once the coarsest GLOBAL grid exceeds this many cells on any "
292 "AXIS (not cell count -- what a few smoother sweeps cannot fix is a mode spanning many "
293 "cells along one axis). DEFAULT 4. Under the automatic depth (set_pressure_multigrid "
294 "levels=0) it also enters the depth, at the geometry build: a later call changes the "
295 "agglomeration but not the depth already resolved. "
296 "`cells` is in cells (a count, not a length); <= 0 restores the default.");
297 cls.def_prop_ro("pressure_bottom_extent", &S::pressureBottomExtent,
298 "The agglomerated-bottom extent threshold (see set_pressure_bottom_extent). "
299 "Measured in cells (a count, not a length).");
300 cls.def("set_implicit_advection", &S::setImplicitAdvection, nb::arg("on"),
301 "Use implicit-FOU advection with deferred-correction TVD.");
302 cls.def("set_velocity_residual_tolerance", &chk::setVelocityResidualTolerance<S>, nb::arg("rtol"),
303 "Residual-based momentum stop: a component's implicit solve ends once max|b - A u| <= "
304 "rtol * max(max|b|, max|A u|) over the solved unknowns (at least one sweep always runs; "
305 "a round-off floor stops a solve that cannot improve). rtol < 0 (DEFAULT) FOLLOWS THE "
306 "PRESSURE SOLVER'S rtol -- the projection consumes u* and resolves the divergence the "
307 "momentum residual leaves to its own tolerance; rtol > 0 fixes it; rtol == 0 restores "
308 "the legacy update criterion (relative to the FIRST sweep's update, which on a "
309 "warm-started near-steady step is noise and cost the whole sweep cap). Every path.");
310 cls.def("velocity_residual_tolerance", &S::velocityResidualTolerance,
311 "The momentum residual tolerance in force (resolves the follow-the-pressure default).");
312 cls.def("set_backflow_stabilization", &chk::setBackflowStabilization<S>, nb::arg("beta"),
313 "Outflow backflow-stabilization coefficient (Bazilevs 2009 / Esmaily-Moghadam 2011): "
314 "beta "
315 "in [0,1] scales the dissipative outflow term that prevents backflow divergence when "
316 "flow "
317 "reverses at the outlet (e.g. a separated wake / BFS recirculation). Default 0.2; 0 = "
318 "off. "
319 "Inert where the outlet is purely outgoing.");
320 cls.def("set_pressure_solver_params", &chk::setPressureSolverParams<S>, nb::arg("iters"),
321 "Set the pressure smoother iteration count.");
322 cls.def("set_pressure_multigrid", &chk::setPressureMultigrid<S>, nb::arg("on"),
323 nb::arg("levels") = 0,
324 "Set the pressure multigrid depth, fixed at the next geometry build. levels=0 (the "
325 "default) derives it: the shallowest depth >= 4 whose global coarsest grid the exact "
326 "bottom solver admits (<= 8192 cells, a plane of <= 192; an operator with an outflow "
327 "face keeps depth 4), or where coarsening ends by itself. levels=1 => pure RB-GS, no "
328 "coarse grid; levels >= 2 => exactly that depth. The resolved depth is "
329 "len(diagnostics.pressure_mg_level_ratios()). set_pressure_bottom_extent must precede "
330 "the geometry to enter the depth (doc/mg_depth_policy.md).");
331 cls.def("set_pressure_chebyshev", &chk::setPressureChebyshev<S>, nb::arg("on"),
332 nb::arg("max_iter") = 120, nb::arg("rtol") = 1e-9,
333 "Use the communication-light Chebyshev pressure accelerator. Mutually exclusive with the "
334 "two CG drivers (on=True clears an FCG selection); on=False deselects Chebyshev and "
335 "falls back to FCG if that is selected, otherwise to MG-PCG.");
336 cls.def("set_pressure_telescope", &S::setPressureTelescope, nb::arg("on"),
337 "Coarse-level TELESCOPING of the pressure multigrid (multi-rank). The geometric "
338 "hierarchy coarsens a level in place, which needs every rank's block even on that axis; "
339 "once a block turns odd the hierarchy used to STOP, leaving a coarsest grid far too "
340 "large to solve (384^3 on 1536 ranks: blocks die at 3x6x4 with the coarsest extent "
341 "still 48, and the pressure iteration count grows 16.6 -> 38.7 across the ladder). With "
342 "this on, a blocked level instead merges ORB siblings onto fewer ranks (the merged "
343 "block's origin is its parent's split value, so parity is restored), moves the residual "
344 "down / correction up within rank groups, and the roots keep coarsening on a "
345 "sub-communicator to a tiny bottom. Idle ranks below the telescope point cost nothing "
346 "that matters; the iteration count becomes a property of the problem rather than the "
347 "rank count. ON by default since 2026-09-02 (the FoxBerry ladder); False restores the "
348 "in-place-only hierarchy, byte-identical to before telescoping existed. See "
349 "suite/docs/archive/MG_TELESCOPING_PLAN.md.");
350 cls.def("pressure_telescope", &S::pressureTelescope,
351 "Whether the pressure multigrid's coarse levels telescope (merge ORB siblings onto "
352 "fewer ranks once a level's block turns odd) rather than stop coarsening in place. "
353 "Reads back set_pressure_telescope's current setting; ON by default since 2026-09-02 "
354 "(the FoxBerry ladder), so this is normally True even though it was never called "
355 "explicitly -- check it rather than assuming the legacy in-place-only hierarchy.");
356 cls.def(
357 "set_pressure_bottom",
358 [](S& s, const std::string& m) {
359 if (m == "auto")
360 s.setPressureBottomMode(-1);
361 else if (m == "smoother")
362 s.setPressureBottomMode(0);
363 else if (m == "agglomerated")
364 s.setPressureBottomMode(1);
365 else
366 throw std::runtime_error("set_pressure_bottom: 'auto' | 'smoother' | 'agglomerated'");
367 },
368 nb::arg("mode"),
369 "Coarse-level (bottom) solve of the pressure multigrid. A V-cycle converges at a "
370 "domain-independent rate only if its COARSEST level is effectively solved, and a geometric "
371 "hierarchy cannot always get small enough: an axis stops coarsening once it turns odd, and "
372 "under MPI once ANY rank's block turns odd -- so at fixed cells/rank the coarsest GLOBAL "
373 "grid grows with the rank count and the bottom is progressively under-solved. "
374 "'auto' (DEFAULT) agglomerates the coarsest level onto a global operator and solves it "
375 "exactly whenever it exceeds set_pressure_bottom_extent (4) cells on any axis, and uses "
376 "the cheap smoothed bottom otherwise (byte-identical to 'smoother' then). 'smoother' = "
377 "never agglomerate (legacy). 'agglomerated' = always. Measured on one GPU (2048x64x64 "
378 "channel): a smoothed bottom needs 13.5 pressure iterations/step at 4 levels and 6.0 at "
379 "6, against 4.4 at full geometric depth; agglomerated it is 4.0 at BOTH depths, and "
380 "faster in wall-clock than the deep hierarchy. Works on the cut-cell IBM and "
381 "ghost-projection paths (per-fluid-component null-space projection, 2026-08-13). Under "
382 "the automatic depth (set_pressure_multigrid levels=0) the mode also enters the depth, at "
383 "the geometry build: a later call changes the bottom solve but not the depth already "
384 "resolved.");
385 cls.def("set_pressure_pcg", &chk::setPressurePcg<S>, nb::arg("on"), nb::arg("max_iter") = 200,
386 nb::arg("rtol") = 1e-8,
387 "Use the MG-PCG pressure accelerator (single-GPU default) and set its iteration cap and "
388 "relative tolerance. on=True GENUINELY selects: it clears both competing selections "
389 "(Chebyshev and FCG), so it works after diagnostics.set_density_mode / set_porous -- "
390 "last set wins. "
391 "on=False RAISES: MG-PCG is the terminal fallback of the driver dispatch, so it cannot "
392 "be deselected on its own -- select the driver you want instead "
393 "(set_pressure_chebyshev(True, ...) or set_pressure_fcg(True, ...)). Under "
394 "diagnostics.set_ghost_projection the nonsymmetric operator is solved by BiCGStab; this "
395 "call still "
396 "sets that solve's cap/tolerance (they are shared) and does not change its method.");
397 cls.def("set_pressure_fcg", &chk::setPressureFcg<S>, nb::arg("on"), nb::arg("max_iter") = 200,
398 nb::arg("rtol") = 1e-8,
399 "Use the FLEXIBLE MG-CG pressure accelerator: the same V-cycle-preconditioned CG as "
400 "set_pressure_pcg, the same stopping estimate/mean removal, and the same cap+tolerance "
401 "(they are shared -- it is the same solve), differing only in the beta recurrence "
402 "(Polak-Ribiere r^T(z_{k+1}-z_k)/r^T z_k instead of Fletcher-Reeves). Costs one extra "
403 "level-0 vector and one extra global dot per iteration; buys tolerance of a "
404 "preconditioner that is not symmetric with respect to the fine operator. On a symmetric "
405 "preconditioner the two betas are algebraically identical, so FCG reproduces PCG's "
406 "iteration count. Unlike set_pressure_pcg this flag GENUINELY selects: on=True clears "
407 "the Chebyshev selection (so it works after diagnostics.set_density_mode/set_porous), "
408 "on=False "
409 "returns to MG-PCG, and a later set_pressure_chebyshev(True, ...) wins over it.");
410 cls.def("set_velocity_multigrid", &chk::setVelocityMultigrid<S>, nb::arg("on"),
411 nb::arg("levels") = 4, nb::arg("vcycles") = 8,
412 "Enable velocity (momentum) multigrid for the implicit diffusion solve.");
413}
414
416template <class Grid, class C>
417inline void bindSolverState(C& cls) {
418 using S = BoundSolver<Grid>;
419 cls.def(
420 "set_state",
421 [](S& s, nb::ndarray<double, nb::f_contig> u, nb::ndarray<double, nb::f_contig> v,
422 nb::ndarray<double, nb::f_contig> w) {
423 s.uploadVelocity(grid_in(u), grid_in(v), grid_in(w));
424 },
425 nb::arg("u"), nb::arg("v"), nb::arg("w"),
426 "Upload an initial velocity field (u,v,w each a Fortran-order (nx,ny,nz) float64 array).");
427 cls.def("step", &S::step,
428 "Advance the solver one time step (semi-implicit: diffusion + projection).\n\n"
429 "ATOMIC across the two explicit two-phase stability caps: the Weymouth-Yue "
430 "boundedness cap and the Brackbill capillary limit are evaluated at the HEAD of the "
431 "call, so a rejected dt leaves every field bitwise as it was and a retry at a smaller "
432 "dt is exact. (Before 2026-09-04 the momentum half had already advanced by the "
433 "rejected dt, so catch-and-halve desynchronised colour and momentum.) The WY "
434 "pre-check reads the field the call starts from; where the projection itself "
435 "accelerates the field inside the step, use step_adaptive().");
436 cls.def(
437 "step_adaptive",
438 [](S& s, double cfl, double capCfl, double dtMax) {
439 return s.stepAdaptive(cfl, capCfl, dtMax);
440 },
441 nb::arg("cfl_target") = 0.4, nb::arg("capillary_cfl") = 0.4,
442 nb::arg("dt_max") = std::numeric_limits<double>::infinity(),
443 "One step at a dt re-picked from the CURRENT state; returns the dt used.\n\n"
444 "dt = min(cfl_target * cfl_dt, capillary_cfl * capillary_dt, dt_max) with both limits "
445 "taken from vof_step_limits() at the moment of the call, then set_dt(dt) + step(). "
446 "Needs enable_vof().\n\n"
447 "WHY: both limits are INSTANTANEOUS. Re-picking every ten steps is safe for a free "
448 "bubble or a falling film and is NOT safe in a packing -- a throat jet can grow "
449 "max|uf| by more than 50 %% inside ten steps (measured, examples/bubble-through-packing) "
450 "and the WY cap is a hard throw; and capillary_dt itself reads the density field, so a "
451 "value taken before the closures have run can be 7x too large (measured, "
452 "examples/pore-scale-imbibition). This is bitwise the "
453 "`dt = 0.4*min(L['cfl_dt'], L['capillary_dt']); s.set_dt(dt); s.step()` loop the "
454 "gallery drivers write by hand (IEEE multiplication is monotone, so "
455 "f*min(a,b) == min(f*a,f*b)). set_dt/step semantics are unchanged. "
456 "cfl_target and capillary_cfl are dimensionless; dt_max and the returned dt are in the "
457 "caller's time units.");
458 cls.def(
459 "set_velocity",
460 [](S& s, int c, nb::ndarray<double, nb::f_contig> a) { s.setVelocity(c, grid_in(a)); },
461 nb::arg("c"), nb::arg("array"),
462 "Write component c's inner velocity from a Fortran-order (nx,ny,nz) float64 array "
463 "(solid rows re-masked). Initial-condition hook: a uniform stream around a fixed body "
464 "is the Galilean twin of the same body towed through fluid at rest. "
465 "The array is in the caller's velocity units (length/time), as get_u returns it.");
466 cls.def(
467 "get_u", [](S& s) { return field_out(s, s.getVelocity(0)); },
468 "Return the x-velocity component as a Fortran-order (nx,ny,nz) float64 array (index "
469 "[x,y,z]).");
470 cls.def(
471 "get_v", [](S& s) { return field_out(s, s.getVelocity(1)); },
472 "Return the y-velocity component as a Fortran-order (nx,ny,nz) float64 array (index "
473 "[x,y,z]).");
474 cls.def(
475 "get_w", [](S& s) { return field_out(s, s.getVelocity(2)); },
476 "Return the z-velocity component as a Fortran-order (nx,ny,nz) float64 array (index "
477 "[x,y,z]).");
478 cls.def(
479 "get_p", [](S& s) { return field_out(s, s.getPressure()); },
480 "Return the physical pressure as a Fortran-order (nx,ny,nz) float64 array (index "
481 "[x,y,z]).");
482 cls.def(
483 "get_ox", [](S& s) { return field_out(s, s.getOpenness(0)); },
484 "The -x face openness field of the cut-cell operator: the fluid area fraction (0..1, "
485 "dimensionless) of the face between cells (i-1,j,k) and (i,j,k), as a Fortran-order "
486 "(nx,ny,nz) float64 array over THIS rank's inner cells. Computed by set_solid from the "
487 "SDF (1 everywhere without a solid); it is what the momentum operator and the geometric "
488 "cut-cell projection see. get_ox_proj is the openness the PROJECTION actually conserves "
489 "fluxes through, which differs under diagnostics.set_ghost_projection (binary/coupled "
490 "faces).");
491 cls.def(
492 "get_oy", [](S& s) { return field_out(s, s.getOpenness(1)); },
493 "The geometric -y face openness per inner cell, (nx,ny,nz); see get_ox.");
494 cls.def(
495 "get_oz", [](S& s) { return field_out(s, s.getOpenness(2)); },
496 "The geometric -z face openness per inner cell, (nx,ny,nz); see get_ox.");
497 cls.def(
498 "get_ox_proj", [](S& s) { return field_out(s, s.getOpennessProj(0)); },
499 "-x face openness whose fluxes the projection CONSERVES (binary/COUPLED under "
500 "diagnostics.set_ghost_projection, geometric cut-cell otherwise). Use for flux bookkeeping "
501 "(peclet.pnm extract_network_flow).");
502 cls.def(
503 "get_oy_proj", [](S& s) { return field_out(s, s.getOpennessProj(1)); },
504 "-y face openness the projection conserves (see get_ox_proj).");
505 cls.def(
506 "get_oz_proj", [](S& s) { return field_out(s, s.getOpennessProj(2)); },
507 "-z face openness the projection conserves (see get_ox_proj).");
508 cls.def(
509 "get_uf", [](S& s) { return field_out(s, s.getFaceVelocity(0)); },
510 "Return the divergence-free FACE x-velocity (collocated: projected MAC field; staggered: "
511 "== get_u).");
512 cls.def(
513 "get_vf", [](S& s) { return field_out(s, s.getFaceVelocity(1)); },
514 "Return the divergence-free FACE y-velocity (collocated: projected MAC field; staggered: "
515 "== get_v).");
516 cls.def(
517 "get_wf", [](S& s) { return field_out(s, s.getFaceVelocity(2)); },
518 "Return the divergence-free FACE z-velocity (collocated: projected MAC field; staggered: "
519 "== get_w).");
520 // --- Named field registry (multiphysics field container) ---------------------------------
521 cls.def(
522 "add_field", [](S& s, const std::string& name) { s.addField(name); }, nb::arg("name"),
523 "Register a new zero-initialised cell-centred field on the grid (for transported scalars "
524 "or material properties). Idempotent.");
525 cls.def(
526 "has_field", [](S& s, const std::string& name) { return s.hasField(name); }, nb::arg("name"),
527 "Whether a field of this name is registered.");
528 cls.def(
529 "field_names", [](S& s) { return s.fieldNames(); },
530 "Names of all registered fields (velocity u/v/w, p, sdf, plus any added), sorted.");
531 cls.def(
532 "get_field", [](S& s, const std::string& name) { return field_out(s, s.getField(name)); },
533 nb::arg("name"),
534 "Return a registered field's inner region as a Fortran-order (nx,ny,nz) float64 array.");
535 cls.def(
536 "set_field",
537 [](S& s, const std::string& name, nb::ndarray<double, nb::f_contig> a) {
538 s.setField(name, grid_in(a));
539 },
540 nb::arg("name"), nb::arg("array"),
541 "Write a Fortran-order (nx,ny,nz) float64 array into a registered field's inner region "
542 "(ghosts refilled on the next diagnostics.exchange_field/step).");
543}
544
547template <class Grid, class C>
548inline void bindSolverPorousMpi(C& cls) {
549 using S = BoundSolver<Grid>;
550 cls.def(
551 "ghost_width", [](S& s) { return s.ghostWidth(); },
552 "Ghost-layer width g of the velocity block (diagnostics.field_view returns an (n+2g) "
553 "buffer).");
554 cls.def(
555 "has_cutcell_pressure", [](S& s) { return s.hasCutcellPressure(); },
556 "True once the cut-cell pressure operator exists (set_solid or set_pressure_geometry was "
557 "called). The porous continuity requires it; the coupling driver auto-sets an all-fluid "
558 "geometry when absent.");
559 cls.def(
560 "set_porous_continuity", [](S& s, bool on) { s.setPorousContinuity(on); },
561 nb::arg("on") = true,
562 "Enable the volume-averaged (porous) continuity for unresolved CFD-DEM (staggered only): "
563 "the projection enforces d(eps)/dt + div(eps u) = 0 instead of div(u)=0, so the fluid "
564 "velocity is NOT solenoidal where the void fraction changes (bubbling/expansion). Binds "
565 "the 'eps' field (void fraction from the particle deposition, created seeded to 1 if "
566 "absent; the coupling writes it each step BEFORE step()). eps=1 everywhere reduces "
567 "exactly "
568 "to div(u)=0. Pair with max_porous_residual() for the meaningful convergence check.");
569 cls.def(
570 "max_open_divergence_projected", [](S& s) { return s.maxOpenDivergenceProjected(); },
571 "max|div(open*u)| of the field the projection ACTUALLY produced — the outflow-face "
572 "correction included, and WITHOUT mutating the velocity.\n\n"
573 "Use this instead of max_open_divergence() on any domain with an OUTFLOW face. "
574 "max_open_divergence() re-imposes the zero-gradient outflow velocity before measuring "
575 "(its own comment says so), which (a) DESTROYS bcCorrectOutflow's correction — the "
576 "mechanism by which mass leaves — as a side effect, so calling it once per step inside a "
577 "time loop changes the run, and (b) reports the divergence of a field the solver never "
578 "used. Measured on a stratified ratio-1000 outflow box: 5e-3 from the mutating "
579 "diagnostic, flat in the iteration count, flat in the density ratio and bit-identical in "
580 "a -DPECLET_FLOW_OPERATOR_DOUBLE build (i.e. not a solver residual), against the projected "
581 "field's own residual from this call. Identical to max_open_divergence() when there is "
582 "no outflow face, and on the collocated grid (which already measures the face field).");
583 cls.def("max_open_divergence", &S::maxOpenDivergence,
584 "Return the max cut-cell velocity-flux divergence max|div(open*u)|. With porous "
585 "continuity this is NOT ~0 -- it equals -d(eps)/dt (the bed expanding). Use "
586 "max_porous_residual() for the continuity residual.");
587 cls.def("sync_porous_prev", &S::syncPorousPrev,
588 "Reseed eps^n = eps^{n+1} (d(eps)/dt = 0 for the next step). Call it once the first "
589 "void-fraction field has been written into 'eps' and before the first step, so that "
590 "step sees no spurious d(eps)/dt source; any later call simply restarts the "
591 "d(eps)/dt bookkeeping from the current field.");
592 cls.def("max_porous_residual", &S::maxPorousResidual,
593 "Residual of the volume-averaged continuity max|div(open*eps*u) + d(eps)/dt| -- the "
594 "quantity the porous projection drives to zero. 0 unless set_porous_continuity(True).");
595 cls.def(
596 "block_origin",
597 [](S& s) {
598 auto o = s.blockOrigin();
599 return std::vector<int>{o[0], o[1], o[2]};
600 },
601 "This rank's inner-block origin in GLOBAL cells ([0,0,0] single-rank). Shift the "
602 "coupling "
603 "deposit origin by this so particles in global coordinates land in the local block. "
604 "The offset is in cells (a count, not a length).");
605#ifdef PECLET_FLOW_MPI
606 // Distributed path (built with -DPECLET_FLOW_MPI): construct the Solver with this rank's
607 // LOCAL block dims (see the module-level mpi_block()), then init_mpi with the GLOBAL grid
608 // dims. step() then does the g=2 velocity-block halo exchange + the distributed cut-cell
609 // pressure MG. Bit-exact to single-rank.
610 cls.def(
611 "init_mpi",
612 [](S& s, int gnx, int gny, int gnz) {
613 chk::globalDims("init_mpi", gnx, gny, gnz);
614 ensure_mpi_init();
615 s.initMpi(gnx, gny, gnz, MPI_COMM_WORLD);
616 },
617 nb::arg("gnx"), nb::arg("gny"), nb::arg("gnz"),
618 "Wire the multi-rank step: pass the GLOBAL grid dims (gnx,gny,gnz). The Solver must have "
619 "been "
620 "constructed with this rank's LOCAL block dims (from mpi_block). MPI_Init is called if "
621 "needed. Call it BEFORE the geometry (set_solid / set_pressure_geometry / "
622 "set_solid_from_scene): the geometry builds the pressure and velocity multigrids for "
623 "the partition in force when it runs, so init_mpi raises if a geometry already exists "
624 "(built first, every rank would solve its own block-periodic pressure problem).\n\n"
625 "Placement (host OpenMP builds): threads per rank should divide the cores per L3 cache "
626 "domain (AMD EPYC Zen 4: 8; Threadripper 5965WX: 6), ideally one rank per domain -- a "
627 "rank whose threads span two domains runs measurably slower (up to +18 % step time) "
628 "and no partition fixes it. With more than one rank, when every OpenMP thread is "
629 "pinned to one CPU, rank 0 prints one stderr line naming the ranks that straddle; "
630 "nothing else changes.");
631 cls.def(
632 "rank",
633 [](S&) {
634 ensure_mpi_init();
635 int r = 0;
636 MPI_Comm_rank(MPI_COMM_WORLD, &r);
637 return r;
638 },
639 "This rank's index in MPI_COMM_WORLD.");
640 cls.def(
641 "size",
642 [](S&) {
643 ensure_mpi_init();
644 int n = 1;
645 MPI_Comm_size(MPI_COMM_WORLD, &n);
646 return n;
647 },
648 "The number of ranks in MPI_COMM_WORLD.");
649#else
650 cls.def(
651 "rank", [](S&) { return 0; },
652 "MPI rank (always 0: this module was built without PECLET_FLOW_MPI; a build with it "
653 "exposes init_mpi / mpi_block and the real rank).");
654 cls.def(
655 "size", [](S&) { return 1; },
656 "MPI size (always 1: this module was built without PECLET_FLOW_MPI).");
657#endif
658}
659
662template <class Grid, class C>
663inline void bindDiagnosticsPorousMpi(C& cls) {
664 using D = Diagnostics<Grid>;
665 cls.def(
666 "set_pressure_underrelax", [](D& diag, double w) { diag.s->setPressureUnderRelax(w); },
667 nb::arg("omega"),
668 "Pressure under-relaxation factor omega_p in (0,1] for the incremental accumulation "
669 "(MFIX "
670 "§10.1); 1.0 = off (default). <1 damps the incremental predictor overshoot on stiff "
671 "porous+drag.");
672 cls.def(
673 "set_porous_deps_dt", [](D& diag, bool on) { diag.s->setPorousDepsDt(on); }, nb::arg("on"),
674 "Include (default True) or drop the d(eps)/dt source in the porous projection RHS. Drop "
675 "it "
676 "to enforce div(eps u)=0 when the per-cell eps deposit's time-derivative is too jagged "
677 "and "
678 "destabilizes the eps-weighted pressure solve.");
679 cls.def(
680 "set_porous_conservative", [](D& diag, bool on) { diag.s->setPorousConservative(on); },
681 nb::arg("on"),
682 "eps-conservative porous momentum + projection pair (default True): time term "
683 "(eps_f rho/dt) u, eps rho-weighted advective form, projection coefficients "
684 "open*(eps rho idt)/(eps rho idt+beta) with matching correction. False = the legacy "
685 "plain-u pair (A/B only; it lets the projection drag gas with the moving porosity at "
686 "zero inertia cost — a spurious late-time energy source in clustering flows).");
687#ifdef PECLET_FLOW_MPI
688 // Distributed path (built with -DPECLET_FLOW_MPI): construct the Solver with this rank's
689 // LOCAL block dims (see the module-level mpi_block()), then init_mpi with the GLOBAL grid
690 // dims. step() then does the g=2 velocity-block halo exchange + the distributed cut-cell
691 // pressure MG. Bit-exact to single-rank.
692 cls.def(
693 "rebalance_by_weights",
694 [](D& diag, const std::vector<double>& w) { return diag.s->rebalanceByWeights(w); },
695 nb::arg("weights"),
696 "Dynamic load balancing: redistribute the solver's state onto the weighted ORB of "
697 "per-cell weights (global x-fastest, gnx*gny*gnz), its split planes aligned to 2^a "
698 "cells with a the largest alignment whose weight imbalance stays within 1.05, so the "
699 "pressure multigrid keeps coarsening in place for a levels. Returns that alignment "
700 "(1 = the plain weighted ORB). Pass fluid work + gamma*particle_count; a coupled dem "
701 "migrates onto the SAME partition with migrate_to_weights(weights, align=<the "
702 "return value>). State-preserving (bit-exact at np=1, reduction floor at np>1).");
703#else
704#endif
705 cls.def(
706 "bcast_from_root", [](D&, nb::object v) { return v; }, nb::arg("value"),
707 "Broadcast a value from rank 0 (identity in the single-rank module; mirrors the MPI "
708 "API).");
709}
710
711} // namespace peclet::flow::bindings
Shared helpers of the peclet.flow Python binding: array conversion, the string-enum tables,...
int enum_index(const std::string &v, const std::vector< std::string > &names, const char *who, const char *what)
void bindSolverControls(C &cls)
Solver (and its collocated twin): time step, body force, advection, decomposition and the pressure / ...
const std::vector< std::string > kAdvSchemes
void bindSolverState(C &cls)
Solver (and its collocated twin): state, stepping, velocity and field read-outs.
std::vector< double > grid_in(nb::ndarray< double, nb::f_contig > a)
nb::ndarray< nb::numpy, double > field_out(S &s, std::vector< double > &&v)
void bindDiagnosticsPorousMpi(C &cls)
SolverDiagnostics (and its collocated twin): pressure under-relaxation, porous options,...
void bindSolverSetup(C &cls)
Solver (and its collocated twin): the diagnostics tier, constructors, domain read-outs,...
const std::vector< std::string > kAxes
void bindSolverPorousMpi(C &cls)
Solver (and its collocated twin): ghost width, porous continuity, divergence read-outs and MPI.
The developer tier: a view onto one Solver<Grid> (no state of its own).