flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
flow_bindings_vof_momentum.hpp
Go to the documentation of this file.
1
9#pragma once
10
12
13namespace peclet::flow::bindings {
14
16template <class Grid, class C>
17inline void bindSolverVofMomentum(C& cls) {
18 using S = BoundSolver<Grid>;
19 // --- Momentum-consistent VoF transport (rung V2b, WO-K) ----------------------------------
20 cls.def(
21 "enable_vof_momentum", [](S& s, double rg, double rl) { s.enableVofMomentum(rg, rl); },
22 nb::arg("rho_c0"), nb::arg("rho_c1"),
23 "Advect rho*u on the HALF-SHIFTED momentum control volumes with the SAME geometric "
24 "fluxes, the same sweep order and one frozen dilation flag as the colour field, then "
25 "recover u = (rho^c u)/rho^c. This is what makes the scheme usable above density ratio "
26 "~100 (Rudman 1998; Arrufat 2021: a raindrop accurate within 15% at 15 cells/diameter "
27 "instead of ~200).\n\n"
28 "The two densities are REQUIRED, and must be the ones the rho closure produces at "
29 "C=0 and C=1 — the momentum flux is rho_c0*(a-F) + rho_c1*F with F the geometric "
30 "flux of the C = 1 phase, so the scheme has to know which density each side carries. "
31 "ORDER: rho_c0 is the density at C = 0 and rho_c1 the density at C = 1, whichever "
32 "phase that is (when C = 1 marks the gas, a bubble colour, rho_c1 is the gas density). "
33 "When a 'rho' closure on 'C' is already "
34 "registered (set_property_model / set_property_table), the pair is checked against it "
35 "at C = 0 and C = 1 and a mismatch raises, naming both; registered after this call, it "
36 "is not checked.\n\n"
37 "Turning this on MOVES the VoF advection from the end of step() to its head (the momentum "
38 "advection must precede the predictor that consumes it), so the advecting field is u^n — "
39 "the previous step's projected output. u at step 0 must therefore be discretely "
40 "divergence-free (rest or a uniform field both are). Requires the variable-density path, "
41 "staggered layout, explicit advection, no immersed solid and no porous continuity, and is "
42 "refused together with the per-bubble block container (enable_vof_blocks*, in either "
43 "order): the momentum rides the structured colour's fluxes, not the markers'. "
44 "rho_c0 and rho_c1 are in the caller's density units.");
45 cls.def(
46 "enable_vof_momentum", [](S& s, double rg, double rl) { s.enableVofMomentum(rg, rl); },
47 nb::arg("rho_gas"), nb::arg("rho_liquid"),
48 "Former keyword names of enable_vof_momentum(rho_c0, rho_c1), the canonical spelling: "
49 "rho_gas = rho_c0 (density at C = 0), rho_liquid = rho_c1 (density at C = 1), whichever "
50 "phase each is. Deprecated in the next release, removed at 2.0.0.");
51 cls.def(
52 "vof_momentum_enabled", [](S& s) { return s.vofMomentumEnabled(); },
53 "Whether momentum-consistent transport is on.");
54 // --- Property closures + Boussinesq body force -------------------------------------------
55 cls.def(
56 "set_property_model",
57 [](S& s, const std::string& target, const std::string& kind, const std::string& in0,
58 const std::vector<double>& params, const std::string& in1) {
60 if (kind == "linear")
62 else if (kind == "boussinesq")
64 else if (kind == "arrhenius")
66 else
67 throw std::runtime_error("set_property_model: unknown kind '" + kind + "'");
68 chk::finiteEach("set_property_model", "params", params, "the closure's units");
69 s.setPropertyModel(target, k, in0, in1, params);
70 },
71 nb::arg("target"), nb::arg("kind"), nb::arg("field"),
72 nb::arg("params") = std::vector<double>{}, nb::arg("field2") = std::string{},
73 "Register a device closure writing a property/body-force field from input field(s). "
74 "target: a registered field (a property 'mu'/'rho'/… or a body-force component "
75 "'force_x'/'force_y'/'force_z'). kind: 'linear' (params [p0,p1,p2]: "
76 "p0+p1*field+p2*field2), "
77 "'boussinesq' (params [rho0,g,beta,T0]: rho0*g*beta*(field-T0) buoyancy), 'arrhenius' "
78 "(params [mu_ref,B,Tref]: mu_ref*exp(B*(1/field-1/Tref))). Applied at the top of step().\n\n"
79 "Units: the input fields are taken as UNSCALED quantities (a phase fraction, a "
80 "temperature, a concentration -- the solver never rescales a transported scalar), so on "
81 "a target 'rho', 'mu' or 'force_x/y/z' the parameters are in the solver's PHYSICAL "
82 "units (a density, a viscosity, a force per volume: rho0*g*beta*(T-T0) as written); "
83 "any other target takes its field's INTERNAL units (see unit_scales).");
84 cls.def("set_property_table", &chk::setPropertyTable<S>, nb::arg("target"), nb::arg("field"),
85 nb::arg("x"), nb::arg("y"),
86 "Register a tabulated property: target = piecewise-linear interpolation of (x, y) at the "
87 "input field value (x ascending, clamped at the ends). Units as set_property_model: y in "
88 "the target's physical units on 'rho'/'mu'/'force_*', x in the input field's.");
89 cls.def(
90 "update_properties", [](S& s) { s.updateProperties(); },
91 "Apply all registered property/force closures now (also done at the top of step()).");
92 cls.def(
93 "enable_cell_force", [](S& s) { s.enableCellForce(); },
94 "Allocate + register the per-cell body-force fields force_x/force_y/force_z and route "
95 "them "
96 "into the momentum RHS, for an external writer (e.g. CFD-DEM drag feedback) to fill "
97 "directly via diagnostics.field_view('force_z'). They persist across steps until "
98 "overwritten. "
99 "They are raw registry fields: a force per unit volume in INTERNAL units (multiply a "
100 "physical one by unit_scales['force_density_to_internal']).");
101 cls.def(
102 "enable_drag", [](S& s) { s.enableDrag(); },
103 "Enable implicit (semi-implicit) linear drag for CFD-DEM: allocate the per-cell "
104 "'drag_beta' "
105 "field (added to the momentum diagonal so a -beta*(u-u_p) source is treated implicitly "
106 "-> "
107 "unconditionally stable for the stiff beta of a dense bed) plus force_x/y/z (which carry "
108 "beta*u_p, the RHS target). Fill 'drag_beta' and 'force_*' via diagnostics.field_view each "
109 "step.");
110}
111
114template <class Grid, class C>
115inline void bindDiagnosticsVofForces(C& cls) {
116 using D = Diagnostics<Grid>;
117 cls.def(
118 "set_csf_mode",
119 [](D& diag, const std::string& mode) {
120 diag.s->setCsfMode(enum_index(mode, kCsfModes, "set_csf_mode", "mode"));
121 },
122 nb::arg("mode"),
123 "ABLATION. 'face' (default, the only production mode) evaluates the surface-tension "
124 "force as sigma*kappa_f*(C(i)-C(i-s))/h at the face -- the projection's own gradient "
125 "operator. 'cell' evaluates a CELL-CENTRED sigma*kappa*grad(C) and face-interpolates it "
126 "with the arithmetic mean, exactly as the per-cell body-force machinery carries a rho*g "
127 "field: consistent, convergent, and wrong for surface tension, because the result is not "
128 "in the range of the operator the projection inverts. Shipped so the difference is a "
129 "measured number (see the vof_surface_tension ctest), not an argument.");
130 cls.def(
131 "set_vof_interface_eps", [](D& diag, double eps) { diag.s->setVofInterfaceEps(eps); },
132 nb::arg("eps"),
133 "Wisp threshold on the curvature cascade's interfacial predicate once surface tension is "
134 "on: a cell carries an interface only while eps < C < 1-eps. Default 1e-8.\n\n"
135 "This is NOT optional and it is not cosmetic. Weymouth-Yue leaves round-off colour "
136 "residue (measured down to -3e-35) in every cell its sweeps touch; those cells satisfy "
137 "0 < C < 1, so the cascade builds a PLIC polygon of area ~0 for them and returns "
138 "|kappa| up to 1e8 where the physical value is 0.125. A face between such a cell and a "
139 "REAL interfacial cell then carries a surface-tension force eight orders too large. "
140 "Measured on a 32^3 static droplet with eps = 0: max|u| 4.5e-4 at step 1 -> 2.7e-1 by "
141 "step 20, and at 96^3 the run trips the Weymouth-Yue CFL cap. Setting eps = 0 "
142 "reproduces that, which is the ablation. compute_vof_curvature() called WITHOUT surface "
143 "tension keeps the rung-V3 predicate (0 < C < 1) unchanged.");
144 cls.def(
145 "vof_interface_eps", [](D& diag) { return diag.s->vofInterfaceEps(); },
146 "The wisp threshold set by set_vof_interface_eps.");
147 cls.def(
148 "set_vof_block_kappa_clip",
149 [](D& diag, bool enabled, std::optional<double> kappaMax) {
150 diag.s->setVofBlockKappaClip(enabled, kappaMax ? *kappaMax : -1.0);
151 },
152 nb::arg("enabled"), nb::arg("kappa_max") = nb::none(),
153 "Curvature admissibility clip of the BLOCK container (doc/vof_overlap_design.md 5.1, "
154 "11): after each marker's cascade every interfacial cell gets |kappa| <= kappa_max. "
155 "DEFAULT ON at kappa_max = 1/Delta_min. kappa_max is PHYSICAL (1/length); None selects "
156 "the default. enabled=False restores the pre-clip block cascade verbatim (the "
157 "ablation). The single-field cascade never clips: there a large |kappa| is legitimate "
158 "(an under-resolved droplet, a contact-line cell).\n\n"
159 "Why: a mixed cell with no body of its marker near it (debris left where two markers "
160 "overlapped) has no closing height-function column and a PLIC-volumetric fit through "
161 "polygons of area ~0, so its paraboloid is arbitrary (measured |kappa| 273 and 428 per "
162 "cell against a true 0.4 on channel_18; one-step velocity blow-up). |kappa| <= 1/Delta "
163 "is a sphere of R >= 2 Delta, the smallest the height function can see, and bounds every "
164 "CSF face force by sigma |dC| / Delta^2. The value is written only where it changes, so "
165 "a resolved interface is bit-identical; vof_block_curvature_stats() reports 'clipped'.");
166 cls.def(
167 "set_vof_kappa_frozen", [](D& diag, bool on) { diag.s->setVofKappaFrozen(on); },
168 nb::arg("on") = true,
169 "INSTRUMENT: stop recomputing the curvature at the head of each step and use whatever is "
170 "in the 'kappa'/'kappa_branch' fields. With set_vof_kappa_constant this isolates the "
171 "balanced-force identity from the curvature estimator.");
172 cls.def(
173 "set_vof_kappa_constant", [](D& diag, double k) { diag.s->setVofKappaConstant(k); },
174 nb::arg("kappa"),
175 "INSTRUMENT: set kappa to a constant everywhere (inner + ghosts), mark every cell as "
176 "carrying a valid estimate, and freeze it. The CSF force is then EXACTLY the discrete "
177 "gradient of sigma*kappa*C, so the projection must annihilate it to round-off from any "
178 "colour field whatsoever — the exactness gate of rung V4, independent of curvature "
179 "accuracy and of resolution.");
180 cls.def(
181 "set_rho_face_harmonic", [](D& diag, bool on) { diag.s->setRhoFaceHarmonic(on); },
182 nb::arg("on") = true,
183 "Use the HARMONIC instead of the arithmetic face mean of rho in the pressure projection "
184 "(both the operator coefficient and the velocity correction, so the projection stays "
185 "exact). DEFAULT OFF, and it should stay off: the arithmetic mean of rho IS the harmonic "
186 "mean of the mobility 1/rho — the series-correct choice for a normal flux — and it is "
187 "what makes the discrete hydrostatic balance EXACT, because the momentum time term and "
188 "the face body force interpolate rho arithmetically and are not switched by this flag. "
189 "Shipped as a measured knob for the coefficient-coarsening question (VOF_PLAN S3), not "
190 "as an alternative scheme.");
191 cls.def(
192 "set_vof_rho_floor", [](D& diag, double f) { diag.s->setVofRhoFloorFrac(f); },
193 nb::arg("fraction"),
194 "Floor on rho^c in the recovery divide u = (rho^c u)/rho^c, as a FRACTION of "
195 "min(rho_c0, rho_c1). Default 1e-6. rho^c leaves [rho_c0, rho_c1] only through "
196 "a wisp in the half-shifted colour and reaching zero would need C^c ~ -1/(ratio-1), so "
197 "this is a guard, not a model — vof_momentum_diagnostics()['floored'] reports how many "
198 "control volumes it actually touched.");
199 cls.def(
200 "vof_rho_floor", [](D& diag) { return diag.s->vofRhoFloor(); },
201 "The absolute rho^c floor used by the last recovery.");
202 cls.def(
203 "set_vof_momentum_scheme",
204 [](D& diag, const std::string& name) { diag.s->setVofMomentumScheme(name); }, nb::arg("name"),
205 "The transported face velocity of the VoF momentum flux (flow "
206 "doc/vof_momentum_second_order.md). 'upwind': donor cell, convex at every density "
207 "ratio, first order (the default until 2026-10-31). 'muscl_mixed': a MinMod slope of "
208 "the MIXED control-volume velocity; it converges to a WRONG limit at high ratio (P1, "
209 "ratio ~1e3: +3.0/+3.1 % at d/h 16/24; the mechanism is open). 'muscl_mixed_capped': "
210 "that slope times the mass-aware cap (the diagnosis ablation). 'muscl_phase': each "
211 "phase's mass flux carries its own face velocity from an interface-biased MC slope, "
212 "scaled by the cap - second order, a discrete maximum principle at any ratio, the "
213 "uniform-velocity identity bit-exact; the DEFAULT. vof_momentum_diagnostics()['capped'] "
214 "counts the faces the cap scaled in the last step. Any other name raises ValueError.");
215 cls.def(
216 "vof_momentum_scheme", [](D& diag) { return diag.s->vofMomentumScheme(); },
217 "The selected VoF momentum scheme (see set_vof_momentum_scheme).");
218}
219
222template <class Grid, class C>
223inline void bindDiagnosticsVofMomentum(C& cls) {
224 using D = Diagnostics<Grid>;
225 cls.def(
226 "set_vof_momentum_muscl", [](D& diag, bool on) { diag.s->setVofMomentumMuscl(on); },
227 nb::arg("on") = true,
228 "Former spelling of set_vof_momentum_scheme: on = 'muscl_mixed' (a MinMod slope of the "
229 "mixed control-volume velocity), off = 'upwind'. Use set_vof_momentum_scheme; "
230 "'muscl_phase' is the second-order scheme that stays bounded at high density ratio.");
231 cls.def(
232 "set_vof_momentum_cell_flag", [](D& diag, bool on) { diag.s->setVofMomentumCellFlag(on); },
233 nb::arg("on") = true,
234 "ABLATION: use the PRESSURE-cell frozen dilation flag H(C^n-1/2) on the shifted control "
235 "volume instead of its structural analogue H(C^c,n-1/2). The flag that must be shared is "
236 "the one of the pair that telescopes, and both members of that pair live on the shifted "
237 "volume — this switch is the literal reading of the work order, kept as a measurement.");
238 cls.def(
239 "set_vof_flux_clamp", [](D& diag, bool on) { diag.s->setVofFluxClamp(on); },
240 nb::arg("on") = true,
241 "ABLATION: drop the Weymouth flux clamp max(0,|a|-(1-C^c_don)) <= |F| <= "
242 "min(|a|,C^c_don) "
243 "on the half-shifted control volume. The geometric flux is bounded by what the CURRENT "
244 "cell planes see in the donor, not by the ADVECTED C^c; the gap is O(a^2) and at density "
245 "ratio 1e4 a 2.6e-2 undershoot drives rho^c to -255, which the recovery would divide by. "
246 "Default ON; off is how that statement stays a measured number.");
247 cls.def(
248 "vof_momentum_diagnostics",
249 [](D& diag) {
250 const auto d = diag.s->vofMomentumDiagnostics();
251 nb::dict r;
252 r["min_Cc"] = nb::make_tuple(d.minCc[0], d.minCc[1], d.minCc[2]);
253 r["max_Cc"] = nb::make_tuple(d.maxCc[0], d.maxCc[1], d.maxCc[2]);
254 r["sum_momentum"] = nb::make_tuple(d.sumM[0], d.sumM[1], d.sumM[2]);
255 r["min_rho_c"] = d.minRhoC;
256 r["floored"] = d.floored;
257 r["clamped"] = d.clamped;
258 r["capped"] = d.capped;
259 return r;
260 },
261 "Census over THIS RANK's momentum control volumes: per-component min/max of the "
262 "half-shifted colour C^c, the summed momentum rho^c u_c (the conservation census), the "
263 "minimum rho^c before the floor, and the number of control volumes the floor touched; "
264 "'clamped' and 'capped' count the faces "
265 "the Weymouth clamp and the mass-aware cap (set_vof_momentum_scheme) touched in the last "
266 "step.");
267 cls.def(
268 "vof_advected_velocity",
269 [](D& diag, int c) { return field_out(*diag.s, diag.s->getVofAdvectedVelocity(c)); },
270 nb::arg("component"),
271 "The recovered advected velocity (rho^c u_c)/rho^c of component c on the inner cells — "
272 "the momentum RHS's time base. Exposed so the uniform-velocity consistency identity can "
273 "be gated on the ADVECTION ALONE, with the projection and the momentum solve out of the "
274 "picture.");
275 cls.def(
276 "set_property_mode",
277 [](D& diag, const std::string& mode, bool harmonic) {
278 diag.s->setPropertyMode(mode == "variable", harmonic);
279 },
280 nb::arg("mode") = "variable", nb::arg("harmonic") = false,
281 "Enable variable-coefficient momentum (variable viscosity): mode 'variable' binds the "
282 "'mu' "
283 "field (get/set_field('mu')) into the diffusion operator; 'constant' reverts. harmonic = "
284 "harmonic face-viscosity mean (continuous shear stress across a jump) vs arithmetic. A "
285 "closure targeting 'mu' enables this automatically. The incremental-rotational pressure "
286 "scheme (large-dt / steady-Stokes) stays active — see set_variable_rotational.");
287 cls.def(
288 "set_variable_rotational",
289 [](D& diag, const std::string& mode, double chi) {
290 int m = 0;
291 if (mode == "min")
292 m = 0;
293 else if (mode == "full")
294 m = 1;
295 else if (mode == "off")
296 m = 2;
297 else
298 throw std::runtime_error("set_variable_rotational: mode must be min/full/off");
299 diag.s->setVariableRotational(m, chi);
300 },
301 nb::arg("mode") = "min", nb::arg("chi") = 1.0,
302 "Rotational-pressure term under variable viscosity (the constant-mu Timmermans term "
303 "-mu*div(u*) is only valid for homogeneous viscosity — Deteix & Yakoubi 2018). 'min' "
304 "(default): constant coefficient chi*mu_min — provably stable at any contrast, exact "
305 "fallback to the constant-mu scheme for uniform mu. 'full': pointwise chi*mu(i) — better "
306 "pressure consistency at MILD contrast only. 'off': plain incremental (no rotational "
307 "term). All modes keep the incremental predictor (large-dt / steady-Stokes capability).");
308 cls.def(
309 "set_density_mode",
310 [](D& diag, const std::string& mode) { diag.s->setDensityMode(mode == "variable"); },
311 nb::arg("mode") = "variable",
312 "Enable variable density: binds the 'rho' field "
313 "(get/set_field('rho'), created seeded with set_rho's value if absent) into the momentum "
314 "time term, the advection weight, the per-cell body force (face-interpolated), and the "
315 "pressure projection (face coefficient openness*rho0/rho_f with the matching 1/rho_f "
316 "velocity correction; rho0 = set_rho's value, so a uniform field reduces exactly to the "
317 "constant solver). A closure targeting 'rho' (e.g. a linear mixture of a transported "
318 "phase fraction) enables this automatically. For gravity, register a closure "
319 "force_z = linear(rho, params=[0, -g]).\n\n"
320 "COLLOCATED (SolverColocated, rung V8): supported since 2026-09-02, ALL-FLUID only "
321 "(set_pressure_geometry; an immersed solid, the ghost projection and "
322 "set_rho_face_harmonic throw). The face coefficient and the face correction are the same "
323 "as on the staggered grid, applied to the ABC projection's MAC face field, which is the "
324 "MOMENTUM-weighted map (rho_L u_L + rho_R u_R)/(rho_L + rho_R) of the cell velocities; "
325 "the "
326 "CELL correction is the average of the two face corrections of each axis (never a "
327 "cell-centred grad(phi)/rho_c). The pressure, the CSF and set_body_force (a mean "
328 "pressure "
329 "gradient) enter the implicit momentum predictor as the matching face integral "
330 "rho_c * avg_faces((f - grad_f P)/rho_f); a per-cell force enters at the cell value. The "
331 "pair is adjoint, so the step is stable at every dt and density ratio and its steady "
332 "state is dt-independent (doc/collocated_varrho_forces.md). Rated to density ratio ~10 "
333 "for cases WITH MOTION (a translating drop exceeds the VoF CFL cap at ratio 100 and "
334 "1000; momentum consistency needs Favre face states and is not in this rung); exact at "
335 "rest at ratio 1000.");
336}
337
338} // 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 bindDiagnosticsVofMomentum(C &cls)
SolverDiagnostics (and its collocated twin): VoF momentum options and read-outs, property and density...
void bindSolverVofMomentum(C &cls)
Solver (and its collocated twin): VoF momentum and property closures, cell force and drag.
void bindDiagnosticsVofForces(C &cls)
SolverDiagnostics (and its collocated twin): CSF mode, interface width, curvature clips,...
nb::ndarray< nb::numpy, double > field_out(S &s, std::vector< double > &&v)
const std::vector< std::string > kCsfModes
The developer tier: a view onto one Solver<Grid> (no state of its own).