flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
flow_bindings_vof_blocks.hpp
Go to the documentation of this file.
1
9#pragma once
10
12
13namespace peclet::flow::bindings {
14
15// One VoF marker block's own inner colour as a Fortran-order (nx,ny,nz) array over its block box
16// (bound as `vof_block_color`, suite/docs/NAMING.md 1.6).
17template <class S>
18inline nb::ndarray<nb::numpy, double> vofBlockColourArray(S& s, long id) {
19 std::vector<double> v = s.vofBlockColour(id);
20 const auto st = s.vofBlockStats();
21 std::size_t nx = 0, ny = 0, nz = 0;
22 for (const auto& b : st)
23 if (b.id == id) {
24 nx = static_cast<std::size_t>(b.hi[0] - b.lo[0]);
25 ny = static_cast<std::size_t>(b.hi[1] - b.lo[1]);
26 nz = static_cast<std::size_t>(b.hi[2] - b.lo[2]);
27 }
28 if (v.size() != nx * ny * nz)
29 return peclet::core::python::vector_to_ndarray(std::move(v), {v.size()}, {1});
30 return peclet::core::python::vector_to_ndarray(
31 std::move(v), {nx, ny, nz},
32 {1, static_cast<std::int64_t>(nx), static_cast<std::int64_t>(nx * ny)});
33}
34
35// One marker block's own inner curvature, same layout as `vofBlockColourArray` (diagnostic).
36template <class S>
37inline nb::ndarray<nb::numpy, double> vofBlockKappaArray(S& s, long id) {
38 std::vector<double> v = s.vofBlockKappa(id);
39 const auto st = s.vofBlockStats();
40 std::size_t nx = 0, ny = 0, nz = 0;
41 for (const auto& b : st)
42 if (b.id == id) {
43 nx = static_cast<std::size_t>(b.hi[0] - b.lo[0]);
44 ny = static_cast<std::size_t>(b.hi[1] - b.lo[1]);
45 nz = static_cast<std::size_t>(b.hi[2] - b.lo[2]);
46 }
47 if (v.size() != nx * ny * nz)
48 return peclet::core::python::vector_to_ndarray(std::move(v), {v.size()}, {1});
49 return peclet::core::python::vector_to_ndarray(
50 std::move(v), {nx, ny, nz},
51 {1, static_cast<std::int64_t>(nx), static_cast<std::int64_t>(nx * ny)});
52}
53
55template <class Grid, class C>
56inline void bindSolverVofBlocks(C& cls) {
57 using S = BoundSolver<Grid>;
58 // --- Part III rung W0 (WO-W0): the per-bubble block container ----------------------------
59 cls.def(
60 "enable_vof_blocks",
61 [](S& s, std::optional<std::vector<std::array<double, 4>>> seeds) {
62 chk::vofSeeds(seeds);
63 if (seeds)
64 s.enableVofBlocks(*seeds);
65 else
66 s.disableVofBlocks();
67 },
68 nb::arg("seeds") = nb::none(),
69 "Carry each bubble on its OWN VoF block (the TBFsolver vofBlock pattern, VOF_PLAN §10): "
70 "one Weymouth-Yue advector per marker on a small moving global index box (bubble extent "
71 "+ 3 cells, its own g = 3 halo on top) with a master rank of its own, and the registered "
72 "'C' the closures see is the UNION C = max_blocks C_block.\n\n"
73 "WHY: two bubbles that touch CANNOT coalesce numerically — colliding markers overlap in "
74 "space but never merge, so coalescence becomes an explicit model decision (rung W4) "
75 "instead of a numerical accident of a single global colour field. Measured on the gate: "
76 "236 cells carry BOTH markers at closest approach (30.0 cells of shared liquid) while "
77 "each marker's own volume is conserved to 2.6e-15, and the single-field control merges "
78 "them irreversibly (neck colour 0.77 against the blocks' 0.00 after the reversal).\n\n"
79 "`seeds=None` DROPS the container (the structured colour field 'C' and advect_vof are "
80 "unaffected). Otherwise 'seeds' is a list of (cx, cy, cz, radius) spheres in CELL "
81 "units, global indices -- these "
82 "are GRID coordinates and a physical domain does not convert them. The "
83 "colour is the same exact sphere fraction set_vof would take.\n\n"
84 "SCOPE at W0: ALL-FLUID (an immersed solid raises — the cut-cell block is rung W12) and "
85 "KINEMATIC (advect_vof_blocks(dt); NS coupling is W12). Masters are assigned round robin "
86 "by block id, deliberately independent of where the bubble's cells live — the weighted-"
87 "ORB assignment is rung W1; diagnostics.vof_block_imbalance() is the number to beat.");
88 cls.def(
89 "vof_blocks_enabled", [](S& s) { return s.vofBlocksEnabled(); },
90 "True while the block container exists (enable_vof_blocks with seeds; None drops it).");
91 cls.def(
92 "advect_vof_blocks", [](S& s, double dt) { s.advectVofBlocks(dt); }, nb::arg("dt"),
93 "Advance every block by dt with the CURRENT (projected) face velocity and union the "
94 "result into 'C' — the block twin of advect_vof(dt), and it carries the same "
95 "precondition: it RAISES unless the face field is discretely divergence-free to 1e-10, "
96 "because Weymouth-Yue's exact conservation is conditional on it.\n\n"
97 "Per step: gather the face velocity from the ranks that own each block's cells to its "
98 "master (plain Isend/Irecv — the block table and the decomposition are both replicated, "
99 "so every rank knows every message size and an NBX handshake would only rediscover it), "
100 "run the three sweeps on the dense block, re-centre the box, replicate the table, and "
101 "scatter the inner colour back with UNPACK_MAX.\n\n"
102 "NOTE on the union: max() from an empty union CLIPS the negative Weymouth-Yue round-off "
103 "residue to an exact 0 — measured up to 6.2e-17 on the LeVeque gate, and every measured "
104 "union/global-field difference was exactly that and nothing else. "
105 "dt is in the caller's time units.");
106 // --- Part III rungs W1/W2 (WO-W12) --------------------------------------------------------
107 cls.def(
108 "enable_vof_blocks_from_field",
109 [](S& s, const std::vector<std::array<int, 6>>& boxes) { s.enableVofBlocksFromField(boxes); },
110 nb::arg("boxes"),
111 "Seed the block container from the CURRENT colour field: one marker per given global "
112 "index box (lo_x, lo_y, lo_z, hi_x, hi_y, hi_z; half-open), its colour copied out of the "
113 "field set_vof installed. The general seeding path — enable_vof_blocks(spheres) is a "
114 "convenience over it — and the way a marker of any shape enters (a quasi-2-D Hysing "
115 "cylinder, a scanned bubble, an arbitrary blob found with a host connected-component "
116 "labelling).\n\n"
117 "The boxes are the BUBBLE extents; the container grows each by its own 3-cell margin. "
118 "They must not share a cell: the seeding gather is a copy, not a union, so a cell inside "
119 "two boxes would be handed to both markers.");
120 // --- Part III rung W3: checkpoint / restart of the block container ----------------------
121 cls.def("vof_block_color", &vofBlockColourArray<S>, nb::arg("id"),
122 "One marker's OWN inner color as a Fortran-order (nx,ny,nz) float64 array over its "
123 "block box (diagnostics.vof_block_stats()['lo'/'hi']); empty on a rank that does not "
124 "master it.\n\n"
125 "This is the block's ONLY state, so {box, color} per marker is a COMPLETE checkpoint "
126 "of the container -- and it is the only exact one: re-seeding from the union color "
127 "field (enable_vof_blocks_from_field) hands each of two TOUCHING markers a slice of the "
128 "other, because that gather is a copy of the union clipped to the seed extent. "
129 "enable_vof_blocks_from_colors(boxes, colors) restarts the container from these.");
130 cls.def(
131 "enable_vof_blocks_from_colors",
132 [](S& s, const std::vector<std::array<int, 6>>& boxes, nb::list colours) {
133 std::vector<std::vector<double>> c;
134 c.reserve(nb::len(colours));
135 for (std::size_t i = 0; i < nb::len(colours); ++i) {
136 auto a = nb::cast<nb::ndarray<double, nb::f_contig>>(colours[i]);
137 c.push_back(peclet::core::python::ndarray_to_vector<double>(nb::ndarray<>(a)));
138 }
139 s.enableVofBlocksFromColours(boxes, c);
140 },
141 nb::arg("boxes"), nb::arg("colors"),
142 "Restart the block container from a vof_block_color() checkpoint: one marker per "
143 "(lo_x, lo_y, lo_z, hi_x, hi_y, hi_z) INNER box (exactly the 'lo'/'hi' of "
144 "diagnostics.vof_block_stats(), NOT grown by the margin again) with its colour written "
145 "directly. "
146 "Exact whatever the markers are doing -- nothing is gathered out of the union field.");
147 cls.def(
148 "set_vof_block_assign",
149 [](S& s, const std::string& mode, long every) {
150 chk::count("set_vof_block_assign", "every", every, 0);
151 s.setVofBlockAssign(enum_index(mode, kBlockAssign, "set_vof_block_assign", "mode"), every);
152 },
153 nb::arg("mode"), nb::arg("every") = 0,
154 "Master assignment of the block container (rung W1). 'round-robin' by block id (rung "
155 "W0's, blind to block SIZE), 'lpt' = LONGEST-PROCESSING-TIME greedy on the block cell "
156 "counts, 'orb' = weighted ORB over a 1-D block space (core's BlockDecomposer<1> with the "
157 "cell counts as weights). 'every' > 0 re-runs the assignment every 'every' block steps "
158 "and MIGRATES the colour of any block that changed master (nothing else in a block is "
159 "state, so the migration is exact and the bitwise gates hold across it).\n\n"
160 "All three are pure functions of the REPLICATED block table, so every rank computes the "
161 "same assignment without an exchange -- which is what lets a re-assignment happen "
162 "mid-run without breaking a bitwise gate. LPT is the measured winner (see the WO-W12 "
163 "findings): the ORB's blocks must be CONTIGUOUS in block id, which LPT is free of.");
164 cls.def(
165 "vof_block_assign", [](S& s) { return kBlockAssign.at(s.vofBlockAssign()); },
166 "The current master-assignment mode ('round-robin' | 'lpt' | 'orb').");
167 cls.def(
168 "enable_vof_block_csf", [](S& s) { s.enableVofBlockCsf(); },
169 "Form the surface-tension force PER BLOCK (rung W2): each marker runs its own curvature "
170 "cascade on its own dense box and forms the V4 balanced-force face force there "
171 "(sigma kappa_f (C(i) - C(i-s))/h with the same selective face-curvature rule "
172 "addCsfRhs uses), and the three face fields are scattered into the global RHS with "
173 "UNPACK_SUM — TBFsolver's VOF.f90::computeSurfaceTension structure on the suite's "
174 "kernels.\n\n"
175 "WHY THE FORCE AND NOT THE CURVATURE IS SCATTERED: kappa is not additive and the union "
176 "colour is a max, so a face between two OVERLAPPING markers has no single (kappa, dC) "
177 "pair to build a force from. The force is the additive quantity, and forming it where "
178 "each marker's own colour still exists is the only place the balanced-force pairing (the "
179 "same face difference the projection's gradient uses) is available per marker.\n\n"
180 "Requires set_surface_tension(sigma) and the block container; STAGGERED only. Once on, "
181 "step() drives the whole two-phase stage through the blocks: the union C feeds the "
182 "closures exactly as before, and the colour is advected by the blocks in the "
183 "advect_vof slot.");
184 // --- two-phase open boundaries (rung V-BC, WO-R) ------------------------------------------
185 cls.def(
186 "set_vof_inflow",
187 [](S& s, const std::string& face, double value) {
188 chk::fraction("set_vof_inflow", "value", value);
189 s.setVofInflow(face_index(face, "set_vof_inflow"), value);
190 },
191 nb::arg("face"), nb::arg("value"),
192 "Colour of the fluid ENTERING through inflow face 'face' ('-x', '+x', '-y', '+y', '-z', "
193 "'+z'); 1 = liquid, 0 = gas. The face must already be an inflow (set_domain_bc(face, "
194 "'inflow', ...)) "
195 "or this raises.\n\n"
196 "The value may be FRACTIONAL, and it then means 'this fraction of the incoming flux is "
197 "liquid' — a flux statement, not a sub-cell interface position. That is exactly how it "
198 "is implemented: on a face whose donor is outside the domain the geometric flux is "
199 "replaced by the algebraic C_donor*a (wyFaceFluxBc), because a uniform prescribed ghost "
200 "band has no usable MYC normal and the inflow colour is boundary DATA.\n\n"
201 "Setting this also makes the property ghosts of that face follow the inflow colour "
202 "through the registered closures (rho_ghost = rho(C_inflow)) instead of copying the "
203 "interior — without it the inlet FACE density is the interior's, wrong by up to the "
204 "density ratio at a liquid inlet into a gas domain. Default (nothing set): the "
205 "zero-gradient copy, i.e. today's behaviour, bit for bit.");
206 cls.def(
207 "set_vof_inflow_profile",
208 [](S& s, const std::string& face, nb::ndarray<double, nb::c_contig> prof) {
209 if (prof.ndim() != 2)
210 throw std::runtime_error("vof inflow profile must be (Nb,Nc)");
211 const int nb_ = (int)prof.shape(0), nc = (int)prof.shape(1);
212 s.setVofInflowProfile(face_index(face, "set_vof_inflow_profile"),
213 peclet::core::python::ndarray_to_vector<double>(nb::ndarray<>(prof)),
214 nb_, nc);
215 },
216 nb::arg("face"), nb::arg("profile"),
217 "Per-position inflow colour (Nb,Nc) on the INNER grid of the face's two perpendicular "
218 "axes, resampled with the same clamp rule set_domain_bc_profile uses for the velocity. "
219 "This is how a liquid distributor over part of an inlet is expressed: the colour "
220 "profile says WHERE liquid enters, the velocity profile says how fast.");
221 cls.def(
222 "set_vof_backflow",
223 [](S& s, const std::string& face, double value) {
224 chk::fraction("set_vof_backflow", "value", value);
225 s.setVofBackflow(face_index(face, "set_vof_backflow"), value);
226 },
227 nb::arg("face"), nb::arg("value") = 0.0,
228 "inletOutlet colour on OUTFLOW face 'face' ('-x' ... '+z'; default 0 = gas): where the "
229 "boundary face "
230 "velocity points back INTO the domain, the colour ghost carries this value instead of "
231 "the zero-gradient copy. This is OpenFOAM's inletOutletFvPatchField (Rusche 2002 thesis "
232 "section 4), the standard VoF outlet — an outlet is a place where you know what leaves "
233 "(whatever is inside) but must STATE what comes back. Zero-gradient on a reversing face "
234 "re-injects whatever happens to be sitting at the outlet, which for a draining film "
235 "feeds the film back into the domain. Where the fluid leaves, zero-gradient is kept.");
236 cls.def(
237 "vof_bc_volumes", [](S& s) { return s.vofBcVolumes(); },
238 "Signed liquid volume that crossed each of the six domain faces during the LAST colour "
239 "advection, in cell-volume units, POSITIVE for liquid ENTERING the domain. Local to this "
240 "rank. Six entries in face order (-x,+x,-y,+y,-z,+z); only faces carrying a domain BC "
241 "are meaningful.");
242 cls.def(
243 "vof_bc_volumes_total", [](S& s) { return s.vofBcVolumesTotal(); },
244 "The same, accumulated since enable_vof() or the last reset_vof_bc_volumes().");
245 cls.def(
246 "reset_vof_bc_volumes", [](S& s) { s.resetVofBcVolumes(); },
247 "Zero the per-face boundary liquid ledger (both the per-step and the running totals).");
248 cls.def(
249 "compute_vof_curvature",
250 [](S& s) {
251 s.computeVofCurvature();
252 const auto d = s.vofCurvatureStats();
253 nb::dict r;
254 r["interfacial"] = d.interfacial;
255 r["hf"] = d.hf;
256 r["hf_mixed"] = d.hfMixed;
257 r["hf_fit"] = d.hfFit;
258 r["pv"] = d.pv;
259 r["pv_reduced"] = d.pvReduced;
260 r["no_estimate"] = d.noEstimate;
261 r["clipped"] = d.clipped;
262 return r;
263 },
264 "VoF rung V3: compute the interface curvature from the CURRENT colour field and store it "
265 "in the registered cell fields 'kappa' and 'kappa_branch'. Returns THIS RANK's branch "
266 "census as a dict.\n\n"
267 "'kappa' is the RAW registered field, kappa = 2H in 1/h (cell units); vof_curvature() "
268 "returns the same thing in 1/length. POSITIVE for a convex blob of liquid: a sphere of "
269 "liquid of radius R cells "
270 "reads +2/R, an infinite cylinder +1/R, a plane 0.\n\n"
271 "The cascade is Popinet's (2009): a standard height function on 7-cell column sums of C "
272 "over the 3x3 transverse patch in the direction of the largest |n| (branch 1), the same "
273 "in the other two directions (branch 2), then the PLIC-VOLUMETRIC paraboloid fit of "
274 "Jibben et al. on a 5^3 Wendland-weighted stencil (branches 4/5) — the best "
275 "cost/accuracy fallback per Han, Evrard & Desjardins, IJMF 174:104769 (2024). Branch 3 "
276 "(the mixed height-position fit) is off by default; branch 0 is 'not an interfacial "
277 "cell' and branch 6 is 'NO estimate', which must never occur.\n\n"
278 "ALWAYS read 'kappa_branch' alongside 'kappa': kappa is 0 both where there is no "
279 "interface (branch 0) and where no estimate could be made (branch 6).\n\n"
280 "Two things the literature settles and this is NOT a bug: the fallback ALWAYS fires "
281 "somewhere below ~5 cells per diameter (measured here: 100% of interfacial cells at "
282 "D/dx = 2.8-4.4, ~19% at D/dx = 38-48 on a sphere), and with advection-realistic volume "
283 "fractions the curvature error STOPS CONVERGING below C*dx ~ 1e-2 for every known "
284 "method. Curvature order is not the thing to chase; transport fidelity is.");
285 cls.def(
286 "vof_curvature", [](S& s) { return field_out(s, s.getVofCurvature()); },
287 "The curvature field's inner region as a Fortran-order (nx,ny,nz) float64 array, in 1/h "
288 "in 1/LENGTH. Call compute_vof_curvature() first; get_field('kappa') is the RAW "
289 "solver-internal field, which is 1/h.");
290 cls.def(
291 "vof_curvature_branch", [](S& s) { return field_out(s, s.getVofCurvatureBranch()); },
292 "Which cascade branch produced each cell's curvature, as a Fortran-order (nx,ny,nz) "
293 "float64 array: 0 not interfacial, 1 height function, 2 height function in a "
294 "non-preferred direction, 3 mixed height-position fit, 4 PLIC-volumetric paraboloid fit, "
295 "5 the same with the rank-deficient 3-parameter model, 6 NO estimate. == "
296 "get_field('kappa_branch').");
297 // --- VoF rung V4 (WO-P): balanced-force surface tension ----------------------------------
298 cls.def(
299 "set_surface_tension", [](S& s, double sigma) { s.setSurfaceTension(sigma); },
300 nb::arg("sigma"),
301 "VoF rung V4: turn on the BALANCED-FORCE continuum surface force with coefficient sigma "
302 "(0 = off, the default). Enables VoF and the curvature cascade, which then runs once per "
303 "step at the head, from the same colour field the density closure sees.\n\n"
304 "The force at the staggered velocity unknown u_c(i) is\n\n"
305 " F = sigma * kappa_f * (C(i) - C(i - s_c)) / h\n\n"
306 "i.e. the colour difference is the projection's OWN face difference — the identical "
307 "discrete gradient operator the pressure uses (Francois et al. 2006; Popinet 2009). That "
308 "is the whole content of 'balanced force': with a constant kappa the force is exactly a "
309 "discrete gradient, so the projection annihilates it and a static drop stays at machine "
310 "zero. Face-interpolating a cell-centred sigma*kappa*grad(C) instead — the obvious way "
311 "to reuse the per-cell body force — is not a discrete gradient of anything and leaves "
312 "spurious currents of order sigma*kappa/mu that no curvature accuracy removes.\n\n"
313 "UNITS: sigma is a force per unit LENGTH in the caller's own units -- the system rho, mu "
314 "and set_body_force are stated in (so per CELL without a physical domain, where the "
315 "cell size is 1). SIGN: kappa is positive for a convex blob of liquid and C is the "
316 "liquid fraction, so the equilibrium pressure is P = sigma*kappa*C + const — the "
317 "Young-Laplace overpressure INSIDE the drop.\n\n"
318 "Surface tension is EXPLICIT, so step() enforces the Brackbill capillary time step "
319 "(see capillary_dt()).");
320 cls.def(
321 "surface_tension", [](S& s) { return s.surfaceTension(); },
322 "The surface-tension coefficient (0 when the CSF is off).");
323 cls.def(
324 "capillary_dt", [](S& s) { return s.capillaryDt(); },
325 "The Brackbill (1992) capillary time-step limit sqrt((rho_1+rho_2) h^3 / (4 pi sigma)), "
326 "+inf when surface tension is off. Denner & van Wachem (2015) verified this IS the "
327 "stability boundary of an explicit CSF — the prefactor 1/(4 pi), the h^{3/2} scaling and "
328 "the SUM of the phase densities (both phases oscillate). The density sum is the declared "
329 "phase pair under enable_vof_momentum, otherwise min(rho)+max(rho) over the field. "
330 "In the caller's time units.");
331 cls.def("set_capillary_cfl", &chk::setCapillaryCfl<S>, nb::arg("factor"),
332 "Safety factor on the capillary limit: step() raises when dt > factor * capillary_dt(). "
333 "Default 1.0 — the Brackbill formula was measured to be the boundary itself, so it "
334 "carries no built-in margin. Set it huge to disable the check, the same escape hatch "
335 "set_vof_cfl_limit is for the Weymouth-Yue cap.");
336 cls.def(
337 "vof_step_limits",
338 [](S& s) {
339 const auto L = s.vofStepLimits();
340 nb::dict r;
341 r["courant"] = L.courant;
342 r["cfl_dt"] = L.cflDt;
343 r["capillary_dt"] = L.capillaryDt;
344 r["binding"] = L.binding;
345 r["capillary_binds"] = L.capillaryBinds;
346 return r;
347 },
348 "Both explicit two-phase step limits at the current state, and which one binds: the "
349 "largest dt the interface-local Weymouth-Yue CFL cap admits ('cfl_dt'), the Brackbill "
350 "capillary limit ('capillary_dt'), and min(cfl_dt, capillary_cfl*capillary_dt) with a "
351 "'capillary_binds' flag. At pore-scale capillary numbers the capillary limit is expected "
352 "to bind first.");
353}
354
357template <class Grid, class C>
358inline void bindDiagnosticsVofBlocks(C& cls) {
359 using D = Diagnostics<Grid>;
360 cls.def(
361 "vof_diagnostics",
362 [](D& diag) {
363 const auto d = diag.s->vofDiagnostics();
364 nb::dict r;
365 r["sum"] = d.sumC;
366 r["min"] = d.minC;
367 r["max"] = d.maxC;
368 r["mixed"] = d.mixed;
369 r["wisps"] = d.wisps;
370 r["volume"] = d.volume;
371 r["raw_volume"] = d.rawVolume;
372 r["solid_sum"] = d.solidSumC;
373 r["solid_fill_sum"] = d.solidFillSum;
374 r["min_fluid"] = d.minCFluid;
375 r["max_fluid"] = d.maxCFluid;
376 r["clipped_volume"] = d.clippedVolume;
377 r["clipped_signed"] = d.clippedSigned;
378 r["cut_cells"] = d.cutCells;
379 r["clamped_faces"] = d.clampedFaces;
380 r["solid_cells"] = d.solidCells;
381 // rung V-BC (WO-R): the boundary term of the exact colour budget
382 const auto v = diag.s->vofBcVolumes();
383 double in = 0.0, out = 0.0;
384 for (int f = 0; f < 6; ++f) {
385 if (v[f] > 0.0)
386 in += v[f];
387 else
388 out -= v[f];
389 }
390 r["inflow_volume"] = in;
391 r["outflow_volume"] = out;
392 return r;
393 },
394 "Colour census over THIS RANK's inner cells: sum (cell-volume units), min, max, the "
395 "number of mixed cells (0<C<1) and of wisps (C within 1e-8 of 0 or 1). No clipping is "
396 "applied at this rung, so min/max may leave [0,1] if the CFL cap is raised.\n\n"
397 "With an immersed solid (rung V5a) the dict also carries the cut-cell quantities, all "
398 "zero without one: 'volume' = sum eps_eff*C over fluid cells, the functional the "
399 "openness-weighted scheme conserves EXACTLY (eps_eff = max(eps, 1/64), the 4^3 "
400 "subsampling resolution — see src/vof/cutcell.hpp rule 1); 'raw_volume' = sum eps*C, "
401 "which differs only on eps==0 cells that still own an open face and is therefore NOT the "
402 "conserved functional; 'solid_sum' = sum of C over solid cells (0 by construction — the "
403 "neutral band fill lives on the working block, not on 'C'); 'min_fluid'/'max_fluid' over "
404 "UNCUT fluid cells (eps==1), where Weymouth's boundedness applies verbatim; "
405 "'clipped_volume' / 'clipped_signed' = the liquid volume the cut-cell clip moved during "
406 "the last advection (a TRIPWIRE on the flux approximation, not a mechanism: if it is not "
407 "negligible the fix is the solid-clipped flux polygon); 'cut_cells' / 'solid_cells'.\n\n"
408 "'inflow_volume' / 'outflow_volume' are the liquid volume that ENTERED / LEFT through "
409 "the domain faces during the LAST colour advection, in the same cell-volume units as "
410 "'sum' (0 unless a VoF boundary colour is set — rung V-BC). They are the advector's OWN "
411 "face fluxes, so sum(C) - sum(C_0) = integral(inflow - outflow) holds to round-off "
412 "whatever the interface does; vof_bc_volumes() breaks them out per face.");
413 cls.def(
414 "vof_block_stats",
415 [](D& diag) {
416 nb::list out;
417 const auto ov = diag.s->vofBlockOverlapCensus();
418 for (const auto& b : diag.s->vofBlockStats()) {
419 nb::dict r;
420 r["id"] = b.id;
421 r["master"] = b.master;
422 r["lo"] = nb::make_tuple(b.lo[0], b.lo[1], b.lo[2]);
423 r["hi"] = nb::make_tuple(b.hi[0], b.hi[1], b.hi[2]);
424 r["cells"] = b.cells;
425 r["volume"] = b.volume;
426 r["centroid"] = nb::make_tuple(b.centroid[0], b.centroid[1], b.centroid[2]);
427 r["velocity"] = nb::make_tuple(b.velocity[0], b.velocity[1], b.velocity[2]);
428 r["moments"] = nb::make_tuple(b.moment[0], b.moment[1], b.moment[2], b.moment[3],
429 b.moment[4], b.moment[5]);
430 r["recentred"] = b.recentred;
431 r["discarded"] = b.discarded;
432 r["area"] = b.area;
433 r["debris_cells"] = b.debrisCells;
434 r["debris_volume"] = b.debrisVolume;
435 r["debris_returned"] = b.debrisReturned;
436 r["debris_lost"] = b.debrisLost;
437 r["debris_unresolved"] = b.debrisUnresolved;
438 r["full_axis"] = b.fullAxis;
439 r["residue_returned"] = b.residueReturned;
440 r["overlap_max_sum"] = ov.maxSum;
441 r["overlap_excess"] = ov.excess;
442 r["overlap_cells"] = ov.cells;
443 r["overlap_bound_active"] = ov.active;
444 out.append(r);
445 }
446 return out;
447 },
448 "Per-bubble Lagrangian census, one dict per block, in block-id order. 'lo'/'hi' (the "
449 "global index box) and 'master' are replicated on every rank; the MEASURED entries — "
450 "'volume' (sum of C over the box, cell volumes), 'centroid', 'velocity' (d(centroid)/dt "
451 "of the last advection), 'moments' (the central second moments xx, yy, zz, xy, xz, yz "
452 "divided by the volume, i.e. the deformation) — are filled only on the block's MASTER "
453 "and are zero elsewhere.\n\n"
454 "'discarded' is the colour a re-centring dropped, cumulatively: Weymouth-Yue leaves "
455 "round-off residue in every cell its sweeps touch and the box tracks the BUBBLE, not "
456 "that wake, so the residue falling outside the new box is discarded. Never physical "
457 "liquid (measured -9.5e-17 over a 20-cell translation, against a bubble volume of 524), "
458 "but it is reported rather than hidden — a container that silently loses mass is not "
459 "acceptable.\n\n"
460 "'debris_cells' / 'debris_volume' are this step's marker DEBRIS removal (block CSF on "
461 "only; master only; see set_vof_block_debris): interfacial cells with every cell of the "
462 "marker within two cells below C = 1/2, and their summed colour. 'debris_returned', "
463 "'debris_lost' and 'debris_unresolved' are the cumulative ledger "
464 "(doc/vof_overlap_design.md 5.3): volume + discarded + debris_lost is conserved. "
465 "'full_axis' counts re-centrings whose box had to span a whole periodic axis (it is "
466 "then [0, L) and copied with the wrap, losslessly; 12.3). 'residue_returned' is the "
467 "cumulative SIGNED sub-wisp-threshold residue cleared after each advection and returned "
468 "to the interface with the debris (13): volume + discarded + debris_lost is exact.\n\n"
469 "'overlap_*' are the GLOBAL marker-overlap census of the last block advection "
470 "(vof_overlap_design 5.6; block CSF or the overlap density on), the same in every dict: "
471 "'overlap_max_sum' = max over cells of S = sum_k C_k, 'overlap_excess' = sum of "
472 "(S - 1)^+ (cell volumes), 'overlap_cells' = cells with S > 1 + 1e-8, and "
473 "'overlap_bound_active' = the phantom-aware capillary limit (2 rho_min in place of "
474 "rho_l + rho_g) is in force for the next step (triggered by max S > 1 + 1e-2).");
475 cls.def(
476 "set_vof_phantom_capillary_bound",
477 [](D& diag, bool enabled) { diag.s->setVofPhantomCapillaryBound(enabled); },
478 nb::arg("enabled") = true,
479 "The phantom-aware capillary limit of the block container (doc/vof_overlap_design.md "
480 "5.6, 11.3), DEFAULT True: while two block markers overlap (max S > 1 + 1e-2) the "
481 "capillary limit of vof_step_limits() and step() uses 2 rho_min in place of "
482 "rho_l + rho_g -- the part of one marker's surface inside another is an interface with "
483 "gas on both sides. False restores the pre-5.6 bound (the ablation; a fixed-dt driver "
484 "at a density ratio above ~31 otherwise throws at first contact).");
485 cls.def(
486 "set_vof_block_debris", [](D& diag, bool enabled) { diag.s->setVofBlockDebris(enabled); },
487 nb::arg("enabled"),
488 "Per-step marker DEBRIS removal of the block container (doc/vof_overlap_design.md 5.3, "
489 "11). Default: ON under enable_vof_block_csf, off otherwise. A debris cell is an "
490 "interfacial cell of a marker (1e-8 < C < 1-1e-8) with every cell of that marker within "
491 "two cells below C = 1/2: colour with no resolvable interface near it (what two "
492 "overlapping markers tear off each other). Its colour is zeroed and the volume is "
493 "returned to the marker's attached interfacial cells weighted C(1-C), in a fixed "
494 "summation order, so the marker volume is exact and the state decomposition-"
495 "independent. Ledger in vof_block_stats(): debris_cells / debris_volume (this step), "
496 "debris_returned, debris_lost, debris_unresolved (cumulative, migrate with the block). "
497 "enabled=False keeps the census (what WOULD be removed) and moves nothing.");
498 cls.def(
499 "set_vof_block_overlap_density",
500 [](D& diag, bool enabled) { diag.s->setVofBlockOverlapDensity(enabled); }, nb::arg("enabled"),
501 "OPT-IN MODEL, default False (the MAX union verbatim). With it the union colour that "
502 "feeds rho(C) and mu(C) -- and the registered 'C' -- becomes C_eff = max_k C_k where "
503 "S = sum_k C_k <= 1 + 1e-8 and max(0, 2 - S) where markers overlap: the overlap volume "
504 "is treated as the sub-grid FILM liquid (the 'tent'), so the phantom interface of one "
505 "marker inside another is an ordinary liquid-gas interface under the base capillary "
506 "bound. Its cost: the lens holds liquid the real state does not (buoyancy and mixture "
507 "weight off by 2 V_overlap during a contact), and it changes collision dynamics. See "
508 "doc/vof_overlap_design.md 5.6.");
509 cls.def(
510 "vof_block_imbalance", [](D& diag) { return diag.s->vofBlockImbalance(); },
511 "max/mean of the per-rank block-cell load under the CURRENT master assignment "
512 "(round robin by block id at rung W0). 1.0 is perfect; the weighted-ORB assignment of "
513 "rung W1 is what this number is here to grade.");
514 cls.def(
515 "vof_block_census",
516 [](D& diag) {
517 std::vector<long> m, c;
518 diag.s->vofBlockCensus(m, c);
519 nb::dict r;
520 nb::list lm, lc;
521 for (long v : m)
522 lm.append(v);
523 for (long v : c)
524 lc.append(v);
525 r["masters"] = lm;
526 r["cells"] = lc;
527 return r;
528 },
529 "Per-rank load census of the block container: 'masters'[r] = blocks rank r masters, "
530 "'cells'[r] = the inner cells those blocks carry (the actual VoF work).");
531 cls.def(
532 "vof_block_imbalance_of", [](D& diag, int mode) { return diag.s->vofBlockImbalanceOf(mode); },
533 nb::arg("mode"),
534 "The max/mean per-rank block-cell load the given assignment mode WOULD give on the "
535 "current blocks, without applying it — so a study can put the three modes side by side "
536 "on one swarm without perturbing the run.");
537 cls.def(
538 "set_vof_block_device_staging",
539 [](D& diag, bool on) { diag.s->setVofBlockDeviceStaging(on); }, nb::arg("on"),
540 "Pack/unpack the block gather and scatter in the block's own MEMORY SPACE (rung W1 item "
541 "b, default True), with a host staging copy only per MPI MESSAGE — and none at all for "
542 "the master's own cells, which are a device-to-device copy. False selects rung W0's "
543 "host-staged path (a full mirror of the local patch per step), which is what the "
544 "device-vs-host measurement compares against. Every step is a copy of a double, so the "
545 "two paths are BITWISE identical; the ctest gates that rather than asserting it.");
546 cls.def(
547 "set_vof_block_pool", [](D& diag, bool on) { diag.s->setVofBlockPool(on); }, nb::arg("on"),
548 "Recycle the advectors a re-centring retires, keyed by the exact box extent (rung W1 "
549 "item c, default True). A translating bubble keeps its box SIZE and only moves its "
550 "origin, so the hit rate is ~100 % and the ten Views of the new box are not allocated. "
551 "A recycled advector is handed back in the state a freshly initialised one is in "
552 "(colour and the three face-velocity fields zeroed), so the pool is bitwise inert.");
553 cls.def(
554 "vof_block_pool_stats",
555 [](D& diag) {
556 const auto q = diag.s->vofBlockPoolStats();
557 nb::dict r;
558 r["hits"] = q[0];
559 r["misses"] = q[1];
560 return r;
561 },
562 "Block-pool census: 'hits' = advectors recycled, 'misses' = advectors allocated.");
563 cls.def(
564 "vof_block_kappa", [](D& diag, long id) { return vofBlockKappaArray(*diag.s, id); },
565 nb::arg("id"),
566 "One marker's OWN curvature (internal units, 1/cell) over its block box, the layout of "
567 "vof_block_color; empty unless this rank masters it and the block CSF is on. A "
568 "diagnostic.");
569 cls.def(
570 "vof_block_force",
571 [](D& diag, int c) { return field_out(*diag.s, diag.s->getVofBlockForce(c)); },
572 nb::arg("component"),
573 "The block CSF face force of component c (0,1,2) as scattered (summed over markers) into "
574 "the solver's LOW-face slot of each cell, internal units; the field the momentum RHS "
575 "adds. "
576 "A diagnostic.");
577 cls.def(
578 "vof_block_curvature_stats",
579 [](D& diag) {
580 const auto st = diag.s->vofBlockCurvatureStats();
581 nb::dict r;
582 r["interfacial"] = st.interfacial;
583 r["hf"] = st.hf;
584 r["hf_mixed"] = st.hfMixed;
585 r["hf_fit"] = st.hfFit;
586 r["pv"] = st.pv;
587 r["pv_reduced"] = st.pvReduced;
588 r["no_estimate"] = st.noEstimate;
589 r["clipped"] = st.clipped;
590 return r;
591 },
592 "Branch census of the last block-CSF curvature pass, SUMMED over this rank's blocks "
593 "(local to the rank). 'no_estimate' must be 0 on any gated case. 'clipped' = cells whose "
594 "|kappa| the admissibility clip bounded (set_vof_block_kappa_clip; a NaN counts too); 0 "
595 "on a resolved interface.");
596 cls.def(
597 "set_outflow_rho_correction", [](D& diag, bool on) { diag.s->setOutflowRhoCorrection(on); },
598 nb::arg("on") = true,
599 "The 1/rho_f mobility factor on the HIGH-side outflow face correction. DEFAULT TRUE "
600 "since WO-R2; pass False for the ablation.\n\n"
601 "A projection correction cancels the discrete divergence only if it uses the SAME face "
602 "coefficient the operator row used. Until WO-R2 the multigrid re-imposed the literal "
603 "openness 1.0 at every Dirichlet domain face, overwriting buildRhoCoeff's "
604 "open_f*rho0/rho_f, so the plain phi difference was the consistent partner and WO-R "
605 "measured this factor making things seven orders WORSE. WO-R2 fixed the operator "
606 "(CutcellMG::setOutflowCoefficient) and the verdict inverted. Stratified duct, ratio "
607 "10, 5 steps, max|div(open u)| of the PROJECTED field:\n"
608 " old operator fixed operator\n"
609 " without the factor 8.76e-10 9.97e-05\n"
610 " with the factor 9.24e-03 8.31e-10\n"
611 "(tests/kokkos/test_vof_bc.cpp gate F2.) Bitwise inert at constant density (rho_f == "
612 "rho0 makes the factor exactly 1) and gated on the variable-density path.");
613 cls.def(
614 "outflow_rho_correction", [](D& diag) { return diag.s->outflowRhoCorrection(); },
615 "Whether the 1/rho_f factor is applied to the outflow face correction (WO-R item 4, "
616 "reversed by WO-R2's operator fix; default True).");
617 cls.def(
618 "set_vof_curvature_weight_width",
619 [](D& diag, double d) { diag.s->setVofCurvatureWeightWidth(d); }, nb::arg("width"),
620 "Wendland support width of the PLIC-volumetric fallback fit, in CELL units. Default 2.5, "
621 "which is Han et al.'s recommended pairing with the 5^3 stencil. Their translating "
622 "droplet recovers first-order convergence of the spurious currents at 3.5 and loses "
623 "convergence entirely at 4.5 (over-smoothing), so this is a real trade-off between the "
624 "locality of the estimate and its robustness to transport error — not a free knob.");
625 cls.def(
626 "set_vof_curvature_mixed_height_fit",
627 [](D& diag, bool on) { diag.s->setVofCurvatureMixedHeightFit(on); }, nb::arg("on") = true,
628 "Enable cascade branch 3, the mixed height-position fit (a paraboloid through the "
629 "interface positions of whichever columns closed). DEFAULT OFF and it should stay off: "
630 "measured on an exact-fraction sphere at 16/32/64 it takes over the 19.5-59.6% of cells "
631 "the height function cannot serve and DESTROYS the convergence of the max curvature "
632 "error (order 0.00 vs 1.86 with the PLIC-volumetric fallback instead), because its data "
633 "set is the columns that closed - a slope-selected, asymmetric subset whose lever-arm "
634 "bias is scale invariant. Shipped as a re-measurable instrument, not a configuration.");
635 cls.def(
636 "csf_diagnostics",
637 [](D& diag) {
638 const auto d = diag.s->csfDiagnostics();
639 nb::dict r;
640 r["max_force"] = nb::make_tuple(d.maxForce[0], d.maxForce[1], d.maxForce[2]);
641 r["orphan_faces"] = nb::make_tuple(d.orphanFaces[0], d.orphanFaces[1], d.orphanFaces[2]);
642 r["forced_faces"] = nb::make_tuple(d.forcedFaces[0], d.forcedFaces[1], d.forcedFaces[2]);
643 return r;
644 },
645 "Census of the CSF face force on THIS RANK: per component the max |F|, the number of "
646 "faces that carried a force, and the number of ORPHAN faces — faces the colour jumps "
647 "across but where neither cell has a curvature estimate, so the force was dropped. An "
648 "orphan is a defect and must be 0; it is counted rather than hidden.");
649}
650
651} // namespace peclet::flow::bindings
Shared helpers of the peclet.flow Python binding: array conversion, the string-enum tables,...
int face_index(const std::string &f, const char *who)
int enum_index(const std::string &v, const std::vector< std::string > &names, const char *who, const char *what)
const std::vector< std::string > kBlockAssign
nb::ndarray< nb::numpy, double > vofBlockKappaArray(S &s, long id)
nb::ndarray< nb::numpy, double > field_out(S &s, std::vector< double > &&v)
nb::ndarray< nb::numpy, double > vofBlockColourArray(S &s, long id)
void bindDiagnosticsVofBlocks(C &cls)
SolverDiagnostics (and its collocated twin): VoF census, block container, outflow density correction,...
void bindSolverVofBlocks(C &cls)
Solver (and its collocated twin): VoF blocks, open boundaries, curvature and surface tension.
Definition prof.py:1
The developer tier: a view onto one Solver<Grid> (no state of its own).
static double value(int gx, int gy, int gz)