flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
vardensity_solver_probe.py
Go to the documentation of this file.
1#!/usr/bin/env python
2"""WO-B (VoF rung S0) -- pressure-driver measurement battery on STATIC two-phase coefficients.
3
4Purpose (see `doc/vof_workorders.md` WO-B and `suite/docs/VOF_PLAN.md` section 5, the S-ladder):
5decide, from measurement rather than from the single anecdote in
6`doc/variable_density_projection.md` section 2, how far up the S-ladder the variable-density
7pressure solver work has to climb. NO VoF is needed: the density field is manufactured and
8static, so this probes the *linear solver* on the exact coefficient operator a VoF interface
9would present.
10
11What is swept
12-------------
13 geometry x rho-shape x edge x density ratio x driver x forcing case
14
15 geometry `box` open box, no immersed solid (`set_pressure_geometry`), walls +-z
16 `cyl` immersed cylinder along y, R = 0.25 N (cut-cell IBM)
17 `rings` 3 Raschig rings (the regression suite's `hollow_rings` bed) -- a genuinely
18 tortuous cut-cell pore geometry
19 `pack` `data/packing_ring.vti` strided onto the run grid (opt-in, N = 64)
20 rho-shape `slab` flat film normal to z, heavy below (the only true hydrostatic rest state)
21 `blob` sphere of heavy fluid at the domain centre
22 `tilt` film with normal (1,0,1)/sqrt2 -- deliberately NOT aligned with the MG
23 coarsening axes
24 `const` THE CONTROL: constant density, `set_density_mode` never called, gravity as
25 a uniform body force. Same geometry, same BCs, same driver, unit
26 coefficient -- so `pack/const` vs `pack/slab@1e4` is exactly the
27 "geometry alone" vs "geometry x coefficient" separation. Recorded with
28 ratio 1.
29 edge `smooth` tanh over ~2 cells `sharp` a one-cell step (what a real VoF
30 interface presents to the operator)
31 ratio 1e2, 1e3, 1e4
32 driver `cheb` (`set_pressure_chebyshev`) `pcg` (`set_pressure_pcg`)
33 `fcg` (`set_pressure_fcg`, added by WO-C / rung S1) -- the SAME V-cycle-preconditioned
34 CG as `pcg` with the same cap/tolerance/stopping estimate, differing only in
35 the beta recurrence (Polak-Ribiere instead of Fletcher-Reeves). `fcg` is NOT
36 in the default `--drivers` set, so the WO-B battery reproduces unchanged; ask
37 for it with `--drivers pcg,fcg` (or `cheb,pcg,fcg`).
38
39**Driver selection (historical trap, REPAIRED 2026-08-30 by WO-H).** `set_pressure_pcg(on, ...)`
40now genuinely selects MG-PCG (it clears both `useChebyshev_` and `useFcg_`), so the plain
41`set_pressure_pcg(True, cap, rtol)` after `set_density_mode` is correct. Until WO-H its `on` flag
42was **discarded** -- `IbmSolver::setPressurePcg(bool /*on*/, ...)` only stored
43`pcgMaxit_`/`pcgRtol_` -- so a "PCG" run after `set_density_mode("variable")` silently measured
44**Chebyshev** (the tell: it capped at exactly **120**, `chebMaxit_`'s default, not the cap passed),
45and the only working spelling was `set_pressure_chebyshev(False, ...)`. `run_one` still issues that
46`set_pressure_chebyshev(False, ...)` before `set_pressure_pcg` -- redundant now, kept so this script
47reproduces WO-B's and WO-C's recorded batteries byte-for-byte on an older build.
48 case `hydro` quiescent + gravity closure force_z = -g*rho (the hydrostatic setup);
49 periodic x/y, walls +-z
50 `lid` lid-driven flow: walls -x/+x/-z, the +z face translating at U in x,
51 periodic y.
52 `per` THE PRODUCTION CONFIGURATION: fully periodic + a uniform body force in x
53 -- pore-scale flow through the packing, no domain BC anywhere. This case
54 is where the two drivers swap places, so it is not optional. It is
55 skipped for (box, const) and (box, slab), where a z-only stratification in
56 a periodic box leaves u* already x-uniform, div(u*) = 0 identically, and
57 the pressure solve returns after 0 iterations -- a degenerate cell, not a
58 measurement.
59
60What is recorded, per configuration
61-----------------------------------
62 * pressure iterations per step (`last_pressure_iterations()`) -- median / max / total;
63 * "final residual" = `max_open_divergence()` = max|div(open*u)| after the step. This IS the
64 residual of the pressure system in the divergence normalisation: the projection solves
65 div(open*(rho0/rho_f) grad phi) = div(open*u*) and then subtracts the gradient, so whatever
66 divergence survives is exactly what the linear solve failed to remove;
67 * wall time: whole step and the `projection` phase alone (device-fenced per-phase timers);
68 * converged: whether the driver stayed strictly below its iteration cap on every step.
69
70Both drivers get the SAME rtol (1e-8) and the SAME cap (200), so "hit the cap" means the same
71thing for both and a stalling configuration terminates instead of burning the device.
72
73Run:
74 OMP_NUM_THREADS=8 OMP_PROC_BIND=false PYTHONPATH=<build> \
75 python tests/study/vardensity_solver_probe.py --out tests/study/vardensity_solver_probe.json
76 ... --pack add the `data/packing_ring.vti` sub-sweep (N=64)
77 ... --trace print the PCG residual history of one stalling configuration
78 ... --geoms box,cyl restrict the sweep
79 ... --per-solve run every configuration under 'fp64', 'fp32' and 'auto' and print
80 the PER-SOLVE (d) table (doc/vof_projection_distributed_design.md §9
81 F-4): every solve where 'fp64' converges must converge under 'auto';
82 every FP64 restart of 'auto' is listed (step, discarded iterations)
83 and must sit where forced 'fp32' capped or broke down
84
85FP64 restarts ('auto', doc/vof_projection_distributed_design.md §4) are read per step from the
86solver's one-line stderr warning (no Python counter exists, Q-4): each record carries `restarts`
87(step, reason, discarded and FP64 iterations), `vprec_steps` (the precision each step's last
88attempt used) and `p1_sha` (SHA-256 of p after step 1, for G-R (i)).
89"""
90import argparse
91import hashlib
92import json
93import os
94import platform
95import re
96import sys
97import tempfile
98import time
99
100import numpy as np
101
102# --------------------------------------------------------------------------- knobs
103N_DEFAULT = 32
104N_PACK = 64
105STEPS = 20
106MAXIT = 200 # same cap for both drivers -- a stall terminates instead of running away
107RTOL = 1e-8 # same tolerance for both drivers
108MU = 0.01
109DT = 1.0
110GRAV = 0.1 # hydrostatic case: force_z = -g*rho
111ULID = 1.0 # lid case: +z face translating at U in x
112FBODY = 1e-3 # per case: uniform body force in x (creeping pore-scale flow)
113VEL_SWEEPS = 40 # RB-GS momentum sweeps (velocity MG is disabled under varRho)
114
115RATIOS = (1e2, 1e3, 1e4)
116SHAPES = ("slab", "blob", "tilt")
117GEOM_ORDER = ("box", "cyl", "rings", "pack")
118SHAPE_ORDER = ("const", "slab", "blob", "tilt")
119EDGES = ("smooth", "sharp")
120DRIVERS = ("cheb", "pcg", "fcg")
121DRIVERS_DEFAULT = ("cheb", "pcg") # WO-B's battery; `fcg` (WO-C) is opt-in via --drivers
122CASES = ("hydro", "lid", "per")
123
124
125# The 'auto' FP64 restart's one stderr line (mac_cutcell_mg.hpp solveWithRestart).
126RESTART_RE = re.compile(r"the FP32 V-cycle did not converge this solve \‍((capped after|non-finite at "
127 r"iteration|degenerate direction at) (\d+)\‍); re-solved with the FP64 "
128 r"V-cycle in (\d+) iterations")
129
130
132 """s.step() with the C-level stderr (fd 2) captured; returns the text and re-emits it."""
133 sys.stderr.flush()
134 saved = os.dup(2)
135 with tempfile.TemporaryFile(mode="w+b") as tmp:
136 os.dup2(tmp.fileno(), 2)
137 try:
138 s.step()
139 finally:
140 os.dup2(saved, 2)
141 os.close(saved)
142 tmp.seek(0)
143 text = tmp.read().decode(errors="replace")
144 if text:
145 sys.stderr.write(text)
146 sys.stderr.flush()
147 return text
148
149
150# --------------------------------------------------------------------------- geometry (sdf[x,y,z], <0 solid)
151def _grid(N):
152 g = np.arange(N) + 0.5
153 return np.meshgrid(g, g, g, indexing="ij")
154
155
156def _minimg(d, N):
157 return d - N * np.round(d / N)
158
159
160def sdf_box(N):
161 """No immersed solid: an all-fluid field for `set_pressure_geometry`."""
162 return None
163
164
165def sdf_cyl(N):
166 """Immersed cylinder along y, centred, R = 0.25 N."""
167 X, _, Z = _grid(N)
168 c, R = N / 2.0, 0.25 * N
169 return np.sqrt((X - c) ** 2 + (Z - c) ** 2) - R
170
171
172def _hollow_cyl_sdf(X, Y, Z, c, axis, r_out, r_in, H, N):
173 """One Raschig ring (hollow cylinder): annulus [r_in,r_out] intersect the slab |axial| <= H/2."""
174 ax = np.asarray(axis, float)
175 ax = ax / np.linalg.norm(ax)
176 dx = _minimg(X - c[0], N)
177 dy = _minimg(Y - c[1], N)
178 dz = _minimg(Z - c[2], N)
179 z = dx * ax[0] + dy * ax[1] + dz * ax[2]
180 rx, ry, rz = dx - z * ax[0], dy - z * ax[1], dz - z * ax[2]
181 rho = np.sqrt(rx * rx + ry * ry + rz * rz)
182 return np.maximum(np.maximum(r_in - rho, rho - r_out), np.abs(z) - 0.5 * H)
183
184
186 """The regression suite's `hollow_rings` bed: 3 Raschig rings, fixed positions/orientations."""
187 rO, rI, H = 0.22 * N, 0.12 * N, 0.34 * N
188 rings = [((0.30 * N, 0.32 * N, 0.30 * N), (1, 0, 0)),
189 ((0.70 * N, 0.68 * N, 0.55 * N), (0, 1, 0)),
190 ((0.45 * N, 0.50 * N, 0.78 * N), (0, 0, 1))]
191 X, Y, Z = _grid(N)
192 sdf = np.full((N, N, N), 1e30)
193 for c, axis in rings:
194 sdf = np.minimum(sdf, _hollow_cyl_sdf(X, Y, Z, c, axis, rO, rI, H, N))
195 return sdf
196
197
198def sdf_pack(N):
199 """`data/packing_ring.vti` (256^3, physical units) strided onto an N^3 grid, in CELL units."""
200 import pyvista as pv
201 here = os.path.dirname(os.path.abspath(__file__))
202 path = os.path.join(here, "..", "..", "data", "packing_ring.vti")
203 g = pv.read(path)
204 dims = g.dimensions
205 a = g.point_data["SDF"].reshape(dims, order="F")
206 if dims[0] % N:
207 raise SystemExit(f"packing_ring.vti is {dims[0]}^3; N={N} must divide it")
208 st = dims[0] // N
209 return np.ascontiguousarray(a[::st, ::st, ::st]) / (g.spacing[0] * st)
210
211
212GEOMS = {"box": sdf_box, "cyl": sdf_cyl, "rings": sdf_rings, "pack": sdf_pack}
213
214
215# --------------------------------------------------------------------------- manufactured rho
216def level_set(shape, N):
217 """psi > 0 in the HEAVY fluid, in units of cells (so `psi/w` is a cell-width argument)."""
218 X, Y, Z = _grid(N)
219 if shape == "slab": # flat film normal to z, heavy below -> a true rest state
220 return N / 2.0 - Z
221 if shape == "blob": # sphere of heavy fluid at the centre
222 c, R = N / 2.0, 0.25 * N
223 return R - np.sqrt((X - c) ** 2 + (Y - c) ** 2 + (Z - c) ** 2)
224 if shape == "tilt": # film whose normal is NOT a grid/coarsening axis
225 c = N / 2.0
226 return ((c - X) + (c - Z)) / np.sqrt(2.0)
227 raise ValueError(shape)
228
229
230def rho_field(shape, edge, ratio, N):
231 psi = level_set(shape, N)
232 if edge == "smooth": # tanh over ~2 cells (psi/w, w = 1 cell)
233 h = 0.5 * (1.0 + np.tanh(psi / 1.0))
234 elif edge == "sharp": # a one-cell step: what a real VoF interface presents
235 h = (psi > 0.0).astype(np.float64)
236 else:
237 raise ValueError(edge)
238 return 1.0 + (ratio - 1.0) * h
239
240
241# --------------------------------------------------------------------------- one configuration
242def run_one(geom, shape, edge, ratio, driver, case, N, quiet=True, bottom=None, levels=None,
243 vprec=None):
244 from peclet import flow as F
245
246 sdf = GEOMS[geom](N)
247 levels = levels or max(2, int(np.floor(np.log2(N))) - 1)
248
249 s = F.Solver(N, N, N)
250 s.set_rho(1.0)
251 s.set_mu(MU)
252 s.set_dt(DT)
253 s.set_advection(False) # creeping Stokes: isolate the pressure solve
254 s.diagnostics.set_velocity_solver_params(VEL_SWEEPS)
255 if case == "hydro": # periodic x/y, walls +-z
256 s.set_domain_bc("-z", "wall", (0, 0, 0))
257 s.set_domain_bc("+z", "wall", (0, 0, 0))
258 elif case == "lid": # walls -x/+x/-z, lid at +z, periodic y
259 s.set_domain_bc("-x", "wall", (0, 0, 0))
260 s.set_domain_bc("+x", "wall", (0, 0, 0))
261 s.set_domain_bc("-z", "wall", (0, 0, 0))
262 s.set_domain_bc("+z", "inflow", (ULID, 0.0, 0.0))
263 elif case == "per": # fully periodic + uniform body force in x
264 s.set_body_force((FBODY, 0.0, 0.0))
265 else:
266 raise ValueError(case)
267 s.set_pressure_multigrid(True, levels=levels)
268 if bottom:
269 s.set_pressure_bottom(bottom)
270
271 if sdf is None:
272 s.set_pressure_geometry(np.asfortranarray(np.full((N, N, N), 10.0)))
273 else:
274 s.set_solid(np.asfortranarray(sdf), cutcell_pressure=True)
275
276 if shape == "const": # the constant-density control: varRho never on
277 ratio = 1.0
278 if case == "hydro":
279 s.set_body_force((0.0, 0.0, -GRAV)) # uniform gravity replaces the rho closure
280 else:
281 s.add_field("rho")
282 s.set_field("rho", np.asfortranarray(rho_field(shape, edge, ratio, N)))
283 s.diagnostics.set_density_mode("variable") # (defaults the driver to Chebyshev)
284 if case == "hydro":
285 s.set_property_model("force_z", "linear", "rho", [0.0, -GRAV])
286
287 # Driver selection AFTER set_density_mode. All three setters genuinely select since WO-H; the
288 # extra `set_pressure_chebyshev(False, ...)` in the `pcg` branch is the pre-WO-H spelling, kept
289 # so this script also selects correctly on an older build (see the module docstring).
290 if driver == "cheb":
291 s.set_pressure_pcg(True, MAXIT, RTOL)
292 s.set_pressure_chebyshev(True, MAXIT, RTOL)
293 elif driver == "pcg":
294 s.set_pressure_chebyshev(False, MAXIT, RTOL)
295 s.set_pressure_pcg(True, MAXIT, RTOL)
296 elif driver == "fcg":
297 # set_pressure_fcg has always honoured its flag (it clears useChebyshev_ itself), so unlike
298 # the `pcg` branch above no set_pressure_chebyshev(False) dance is needed on any build.
299 s.set_pressure_fcg(True, MAXIT, RTOL)
300 else:
301 raise ValueError(driver)
302 if vprec: # doc/vof_projection_cost_design.md §4: the FP32 V-cycle A/B (G-D3)
303 s.diagnostics.set_pressure_vcycle_precision(vprec)
304
305 iters, divs, t_step, t_proj, failed = [], [], [], [], []
306 restarts, vprec_steps, p1_sha = [], [], None
307 t_wall0 = time.perf_counter()
308 for k in range(STEPS):
309 for m in RESTART_RE.finditer(step_capturing_stderr(s)):
310 restarts.append({"step": k + 1, "reason": m.group(1), "discarded": int(m.group(2)),
311 "fp64_iters": int(m.group(3))})
312 vprec_steps.append(s.diagnostics.pressure_vcycle_precision())
313 if k == 0:
314 p1_sha = hashlib.sha256(np.ascontiguousarray(s.get_p()).tobytes()).hexdigest()
315 iters.append(int(s.diagnostics.last_pressure_iterations()))
316 failed.append(bool(s.diagnostics.pressure_solve_failed()))
317 tm = s.diagnostics.last_step_timers()
318 t_step.append(float(tm["step"]))
319 t_proj.append(float(tm["projection"]))
320 divs.append(float(s.max_open_divergence()))
321 wall = time.perf_counter() - t_wall0
322 umax = max(float(np.abs(s.get_u()).max()), float(np.abs(s.get_v()).max()),
323 float(np.abs(s.get_w()).max()))
324
325 # A low iteration count does NOT imply a good solve: PCG's breakdown guard (`pAp <= 1e-300`
326 # or a non-finite recurrence scalar in `CutcellMG::solvePCG`) exits early and keeps the last
327 # finite iterate. So health is judged on the PHYSICS: max|div(open*u)| after the step,
328 # normalised by the case's own velocity scale.
329 it = np.asarray(iters, float)
330 uscale = max(umax, {"lid": ULID, "hydro": GRAV * DT, "per": FBODY * DT}[case])
331 div_rel = divs[-1] / uscale
332 rec = dict(
333 geom=geom, shape=shape, edge=edge, ratio=ratio, driver=driver, case=case, N=N,
334 levels=levels, bottom=bottom or "auto", steps=STEPS, maxit=MAXIT, rtol=RTOL,
335 iters=iters,
336 it_median=float(np.median(it)), it_max=int(it.max()), it_min=int(it.min()),
337 it_total=int(it.sum()),
338 capped_steps=int((it >= MAXIT).sum()),
339 converged=bool((it < MAXIT).all()),
340 div_final=divs[-1], div_max=float(max(divs)), div_rel=float(div_rel),
341 healthy=bool((it < MAXIT).all() and np.isfinite(umax) and div_rel < 1e-8),
342 wall_s=wall,
343 t_step_median=float(np.median(t_step)), t_proj_median=float(np.median(t_proj)),
344 t_proj_min=float(np.min(t_proj)), t_proj_total=float(np.sum(t_proj)),
345 umax=umax,
346 vprec=vprec or "default", vprec_used=s.diagnostics.pressure_vcycle_precision(),
347 failed_steps=int(sum(failed)), failed=failed,
348 restarts=restarts, vprec_steps=vprec_steps, p1_sha=p1_sha,
349 )
350 if not quiet:
351 print(f" {geom:5s} {shape:4s} {edge:6s} r={ratio:<7.0e} {driver:4s} {case:6s} "
352 f"it med {rec['it_median']:6.1f} max {rec['it_max']:4d} "
353 f"{'CAPPED' if not rec['converged'] else ('ok ' if rec['healthy'] else 'BADDIV')} "
354 f"div/u {rec['div_rel']:.1e} proj {rec['t_proj_min']*1e3:7.1f} ms "
355 f"(med {rec['t_proj_median']*1e3:7.1f})", flush=True)
356 return rec
357
358
359# --------------------------------------------------------------------------- reporting
360def markdown(records):
361 out = []
362 out.append("`proj ms` is the FASTEST of the 20 steps' projection times, not the median: this "
363 "host is shared with other agents, and a median picks up their load.\n")
364 out.append("`ok` = stayed below the iteration cap AND left max|div(open u)|/u_scale < 1e-8; "
365 "`CAP` = hit the cap; `BAD` = finished but the projection did not close.\n")
366 # Columns follow whichever drivers are present, in DRIVERS order (cheb, pcg, fcg): a cheb+pcg
367 # run reproduces WO-B's table exactly, a --drivers pcg,fcg run gets the FCG trio instead.
368 label = {"cheb": "Cheb", "pcg": "PCG", "fcg": "FCG"}
369 present = [d for d in DRIVERS if any(r["driver"] == d for r in records)]
370 head = ["geom", "shape", "edge", "ratio", "case"]
371 for d in present:
372 head += [f"{label[d]} its (med/max)", label[d], f"{label[d]} div/u", f"{label[d]} proj ms"]
373 out.append("| " + " | ".join(head) + " |")
374 out.append("|" + "---|" * len(head))
375 key = lambda r: (r["geom"], r["shape"], r["edge"], r["ratio"], r["case"])
376 idx = {}
377 for r in records:
378 idx.setdefault(key(r), {})[r["driver"]] = r
379 for k in sorted(idx, key=lambda k: (GEOM_ORDER.index(k[0]), SHAPE_ORDER.index(k[1]),
380 ("smooth", "sharp").index(k[2]), k[3],
381 CASES.index(k[4]))):
382 g, sh, e, ra, ca = k
383 def cell(r):
384 if r is None:
385 return ["-", "-", "-", "-"]
386 state = ("ok" if r["healthy"]
387 else (f"**CAP** ({r['capped_steps']}/{r['steps']})"
388 if not r["converged"] else "**BAD**"))
389 return [f"{r['it_median']:.0f}/{r['it_max']}", state,
390 f"{r['div_rel']:.1e}", f"{r['t_proj_min']*1e3:.1f}"]
391 row = [g, sh, e, f"{ra:.0e}", ca]
392 for d in present:
393 row += cell(idx[k].get(d))
394 out.append("| " + " | ".join(row) + " |")
395 return "\n".join(out)
396
397
398def summarize(records):
399 """The two questions the S-ladder decision turns on."""
400 lines = []
401 for ca in CASES:
402 for drv in DRIVERS:
403 lines.append(f"\ncase {ca}, driver {drv}: median-of-medians / worst-step iterations, "
404 f"aggregated over rho-shape")
405 lines.append("| geom | edge | ratio 1e2 | ratio 1e3 | ratio 1e4 |")
406 lines.append("|---|---|---|---|---|")
407 for g in ("box", "cyl", "rings", "pack"):
408 for e in EDGES:
409 cells, any_here = [], False
410 for ra in RATIOS:
411 sel = [r for r in records if r["driver"] == drv and r["geom"] == g
412 and r["edge"] == e and r["ratio"] == ra and r["case"] == ca]
413 if not sel:
414 cells.append("-")
415 continue
416 any_here = True
417 med = np.median([r["it_median"] for r in sel])
418 mx = max(r["it_max"] for r in sel)
419 bad = sum(0 if r["healthy"] else 1 for r in sel)
420 cells.append(f"{med:.0f} / {mx}"
421 + (f" (**{bad}/{len(sel)} unhealthy**)" if bad else ""))
422 if any_here:
423 lines.append("| " + " | ".join([g, e] + cells) + " |")
424
425 # The separation the S-ladder decision turns on: how much of the iteration count is the
426 # GEOMETRY (constant-density control on the same grid) and how much is the rho jump on top.
427 lines.append("\ngeometry vs coefficient: median iterations, constant-rho control vs the "
428 "sharp-edge varRho runs")
429 lines.append("| geom | case | driver | const rho | sharp 1e2 | sharp 1e3 | sharp 1e4 | "
430 "jump cost (1e4 / const) |")
431 lines.append("|---|---|---|---|---|---|---|---|")
432 for g in GEOM_ORDER:
433 for ca in CASES:
434 for drv in DRIVERS:
435 ctrl = [r for r in records if r["geom"] == g and r["shape"] == "const"
436 and r["case"] == ca and r["driver"] == drv]
437 if not ctrl:
438 continue
439 c0 = np.median([r["it_median"] for r in ctrl])
440 cells = []
441 for ra in RATIOS:
442 sel = [r for r in records if r["geom"] == g and r["shape"] != "const"
443 and r["edge"] == "sharp" and r["case"] == ca
444 and r["driver"] == drv and r["ratio"] == ra]
445 cells.append(f"{np.median([r['it_median'] for r in sel]):.0f}" if sel else "-")
446 last = [r for r in records if r["geom"] == g and r["shape"] != "const"
447 and r["edge"] == "sharp" and r["case"] == ca and r["driver"] == drv
448 and r["ratio"] == RATIOS[-1]]
449 fac = (np.median([r["it_median"] for r in last]) / c0) if (last and c0) else 0.0
450 lines.append("| " + " | ".join([g, ca, drv, f"{c0:.0f}"] + cells
451 + [f"{fac:.2f}x" if fac else "-"]) + " |")
452 return "\n".join(lines)
453
454
455def cheb_overhead(geom, N, ratio=1e3):
456 """Quantify what rung S2 (bound amortization) would actually buy.
457
458 Under varRho the coefficient operator is rebuilt every step and `chebBoundsSet_` is
459 invalidated with it (`flow_ibm.hpp` project()), so `estimateEigenvalues(..., iters=15, ...)`
460 runs EVERY step -- two 15-step power loops, each applying M^{-1}A once, i.e. **30 extra
461 V-cycles per step** on top of the ~15-25 the solve itself needs. Constant density estimates
462 the bounds once (step 1) and reuses them, so the A/B below isolates the cost.
463 """
464 from peclet import flow as F
465
466 def run(varrho, driver):
467 sdf = GEOMS[geom](N)
468 levels = max(2, int(np.floor(np.log2(N))) - 1)
469 s = F.Solver(N, N, N)
470 s.set_rho(1.0)
471 s.set_mu(MU)
472 s.set_dt(DT)
473 s.set_advection(False)
474 s.diagnostics.set_velocity_solver_params(VEL_SWEEPS)
475 s.set_domain_bc("-x", "wall", (0, 0, 0))
476 s.set_domain_bc("+x", "wall", (0, 0, 0))
477 s.set_domain_bc("-z", "wall", (0, 0, 0))
478 s.set_domain_bc("+z", "inflow", (ULID, 0.0, 0.0))
479 s.set_pressure_multigrid(True, levels=levels)
480 if sdf is None:
481 s.set_pressure_geometry(np.asfortranarray(np.full((N, N, N), 10.0)))
482 else:
483 s.set_solid(np.asfortranarray(sdf), cutcell_pressure=True)
484 if varrho:
485 s.add_field("rho")
486 s.set_field("rho", np.asfortranarray(rho_field("slab", "sharp", ratio, N)))
487 s.diagnostics.set_density_mode("variable")
488 if driver == "cheb":
489 s.set_pressure_chebyshev(True, MAXIT, RTOL)
490 else:
491 s.set_pressure_chebyshev(False, MAXIT, RTOL) # the actual switch (see the docstring)
492 s.set_pressure_pcg(True, MAXIT, RTOL)
493 tp, it = [], []
494 for _ in range(STEPS):
495 s.step()
496 tp.append(float(s.diagnostics.last_step_timers()["projection"]))
497 it.append(int(s.diagnostics.last_pressure_iterations()))
498 return np.asarray(tp), np.asarray(it)
499
500 out = {}
501 for varrho in (False, True):
502 for drv in ("cheb", "pcg"):
503 tp, it = run(varrho, drv)
504 k = f"{'varrho' if varrho else 'constrho'}_{drv}"
505 out[k] = dict(t_first=float(tp[0]), t_median=float(np.median(tp[1:])),
506 it_first=int(it[0]), it_median=float(np.median(it[1:])))
507 c = out["constrho_cheb"]
508 est = c["t_first"] - c["t_median"] # the one-off bound estimate, isolated
509 v = out["varrho_cheb"]
510 print("\n--- Chebyshev bound-estimation overhead (rung S2's target) ---")
511 for k, r in out.items():
512 print(f" {k:14s} step1 {r['t_first']*1e3:7.1f} ms ({r['it_first']:3d} it) "
513 f"steady {r['t_median']*1e3:7.1f} ms ({r['it_median']:5.1f} it)")
514 print(f" isolated bound estimate (const-rho step1 - steady): {est*1e3:.1f} ms")
515 print(f" varRho Chebyshev pays it EVERY step: {est/max(v['t_median'],1e-12)*100:.0f} % of "
516 f"its steady projection time; amortizing it (S2) would leave "
517 f"{(v['t_median']-est)*1e3:.1f} ms")
518 out["estimate_cost_s"] = est
519 out["geom"] = geom
520 out["N"] = N
521 out["ratio"] = ratio
522 return out
523
524
525def trace_pcg(geom, shape, edge, ratio, case, N):
526 """Re-run one configuration with the MG residual trace on (PCG only -- Chebyshev has none)."""
527 os.environ["PECLET_FLOW_MG_DEBUG"] = "2"
528 os.environ["PECLET_FLOW_MG_DEBUG_SOLVES"] = "3"
529 print(f"\n--- PCG residual trace: {geom}/{shape}/{edge}/ratio {ratio:.0e}/{case} ---",
530 flush=True)
531 run_one(geom, shape, edge, ratio, "pcg", case, N, quiet=False)
532 os.environ.pop("PECLET_FLOW_MG_DEBUG", None)
533
534
535def _conv(r, i): # step i + 1 of record r met its stop test: below the cap and not failed
536 return r["iters"][i] < r["maxit"] and not r["failed"][i]
537
538
539def _nconv(r):
540 return sum(_conv(r, i) for i in range(len(r["iters"])))
541
542
543def per_solve_table(records):
544 """F-4 (doc/vof_projection_distributed_design.md §9; review finding 3): per configuration and
545 per SOLVE, 'auto' against 'fp64' and forced 'fp32' on the same build. A violation is a step
546 where 'fp64' converged (< cap, not failed) and 'auto''s final attempt did not. A restart is
547 legitimate where forced 'fp32' -- bitwise 'auto' up to that step -- capped or broke down at the
548 same step with the same iteration count. Returns (markdown, n_violations, n_restarts,
549 n_restarts_not_legit, n_configurations)."""
550 key = lambda r: (r["geom"], r["shape"], r["edge"], r["ratio"], r["driver"], r["case"])
551 idx = {}
552 for r in records:
553 idx.setdefault(key(r), {})[r["vprec"]] = r
554 out = [("| geom | shape | ratio | driver | case | fp64 conv | fp32 conv | auto conv | "
555 "violations | restarts (step: discarded, reason -> fp64 its) | at fp32 cap/brk | "
556 "p1 auto==fp64 |"), "|" + "---|" * 12]
557 nv = nr = nbad = ncfg = 0
558 for k in sorted(idx, key=lambda k: (GEOM_ORDER.index(k[0]), SHAPE_ORDER.index(k[1]), k[2],
559 k[3], k[4], CASES.index(k[5]))):
560 d = idx[k]
561 if not all(m in d for m in ("fp64", "fp32", "auto")):
562 continue
563 ncfg += 1
564 f64, f32, au = d["fp64"], d["fp32"], d["auto"]
565 viol = [i + 1 for i in range(len(f64["iters"])) if _conv(f64, i) and not _conv(au, i)]
566 legit = []
567 for rs in au["restarts"]:
568 i = rs["step"] - 1
569 cap_or_brk = f32["iters"][i] >= f32["maxit"] or f32["failed"][i] or \
570 rs["reason"] == "degenerate direction at"
571 legit.append(cap_or_brk and f32["iters"][i] == rs["discarded"])
572 nv += len(viol)
573 nr += len(au["restarts"])
574 nbad += legit.count(False)
575 p1 = ("yes" if au["p1_sha"] == f64["p1_sha"] else "no") if any(
576 rs["step"] == 1 for rs in au["restarts"]) else "-"
577 rst = "; ".join(f"{rs['step']}: {rs['discarded']}, {rs['reason'].split()[0]} -> "
578 f"{rs['fp64_iters']}" for rs in au["restarts"]) or "-"
579 out.append("| " + " | ".join([
580 k[0], k[1], f"{k[3]:.0e}", k[4], k[5], f"{_nconv(f64)}/{len(f64['iters'])}",
581 f"{_nconv(f32)}/{len(f32['iters'])}", f"{_nconv(au)}/{len(au['iters'])}",
582 (",".join(map(str, viol)) if viol else "0"), rst,
583 ("all" if all(legit) else f"**{legit.count(False)} not**") if legit else "-",
584 p1]) + " |")
585 return "\n".join(out), nv, nr, nbad, ncfg
586
587
588# --------------------------------------------------------------------------- main
589def main():
590 ap = argparse.ArgumentParser()
591 ap.add_argument("--out", default=os.path.join(os.path.dirname(os.path.abspath(__file__)),
592 "vardensity_solver_probe.json"))
593 ap.add_argument("--md", default=None, help="also write the markdown table to this path")
594 ap.add_argument("--n", type=int, default=N_DEFAULT)
595 ap.add_argument("--geoms", default="box,cyl,rings")
596 ap.add_argument("--shapes", default="const," + ",".join(SHAPES))
597 ap.add_argument("--edges", default=",".join(EDGES))
598 ap.add_argument("--ratios", default=",".join(f"{r:.0e}" for r in RATIOS))
599 ap.add_argument("--drivers", default=",".join(DRIVERS_DEFAULT),
600 help="cheb, pcg, fcg (comma-separated); default cheb,pcg = WO-B's battery")
601 ap.add_argument("--cases", default=",".join(CASES))
602 ap.add_argument("--pack", action="store_true",
603 help="append the data/packing_ring.vti sub-sweep at N=64 (shapes slab,blob)")
604 ap.add_argument("--trace", action="store_true")
605 ap.add_argument("--cheb-overhead", action="store_true",
606 help="also measure the per-step Chebyshev bound-estimation cost (rung S2)")
607 ap.add_argument("--overhead-geoms", default="box,rings",
608 help="geometries for --cheb-overhead (independent of --geoms)")
609 ap.add_argument("--tag", default="", help="label stored in the JSON (e.g. the backend)")
610 ap.add_argument("--bottom", default=None,
611 help="set_pressure_bottom mode ('auto'/'smoother'/'agglomerated'); "
612 "default = the shipped 'auto'")
613 ap.add_argument("--vcycle-precision", default=None,
614 help="diagnostics.set_pressure_vcycle_precision(MODE) after the driver "
615 "(auto | fp64 | fp32; doc/vof_projection_cost_design.md §4, G-D3)")
616 ap.add_argument("--per-solve", action="store_true",
617 help="run each configuration under 'fp64', 'fp32' and 'auto' and print the "
618 "per-solve (d) table (doc/vof_projection_distributed_design.md §9 F-4); "
619 "overrides --vcycle-precision")
620 ap.add_argument("--levels", type=int, default=None,
621 help="pressure MG depth (default floor(log2 N) - 1)")
622 args = ap.parse_args()
623
624 geoms = [g for g in args.geoms.split(",") if g]
625 shapes = [s for s in args.shapes.split(",") if s]
626 edges = [e for e in args.edges.split(",") if e]
627 ratios = [float(r) for r in args.ratios.split(",") if r]
628 drivers = [d for d in args.drivers.split(",") if d]
629 cases = [c for c in args.cases.split(",") if c]
630
631 def expand(gs, shs, n):
632 # `const` is the unit-coefficient control: edge and ratio are meaningless there, so it is
633 # emitted once per (geom, driver, case) instead of once per (edge, ratio).
634 out = []
635 for g in gs:
636 for sh in shs:
637 ee = [edges[0]] if sh == "const" else edges
638 rr = [1.0] if sh == "const" else ratios
639 cc = [c for c in cases
640 # degenerate: a z-only rho in a periodic box gives div(u*) == 0 exactly
641 if not (c == "per" and g == "box" and sh in ("const", "slab"))]
642 out += [(g, sh, e, ra, d, ca, n)
643 for e in ee for ra in rr for d in drivers for ca in cc]
644 return out
645
646 plan = expand(geoms, shapes, args.n)
647 if args.pack:
648 plan += expand(["pack"], [s for s in ("const", "slab", "blob") if s in shapes], N_PACK)
649
650 print(f"{len(plan)} configurations x {STEPS} steps", flush=True)
651 records = []
652 t0 = time.perf_counter()
653 precisions = ("fp64", "fp32", "auto") if args.per_solve else (args.vcycle_precision,)
654 for i, (g, sh, e, ra, d, ca, n) in enumerate(plan):
655 for vp in precisions:
656 print(f"[{i+1}/{len(plan)}]" + (f" {vp:4s}" if args.per_solve else ""), end=" ",
657 flush=True)
658 records.append(run_one(g, sh, e, ra, d, ca, n, quiet=False,
659 bottom=args.bottom, levels=args.levels, vprec=vp))
660 wall = time.perf_counter() - t0
661
662 overhead = None
663 if args.cheb_overhead:
664 overhead = [cheb_overhead(g, args.n)
665 for g in args.overhead_geoms.split(",") if g]
666
667 if args.per_solve: # the per-precision tables would interleave three runs per cell
668 md, nv, nr, nbad, ncfg = per_solve_table(records)
669 md += (f"\n\nPER-SOLVE (d): {ncfg} configurations x {STEPS} steps; violations {nv} (a "
670 f"solve 'fp64' converged and 'auto' did not); restarts {nr}, {nbad} not at a "
671 f"forced-'fp32' cap/breakdown -> F-4 {'PASS' if nv == 0 and nbad == 0 else 'MISS'}")
672 print("\n" + md)
673 else:
674 md = markdown(records)
675 print("\n" + md)
676 print(summarize(records))
677 print(f"\ntotal wall {wall:.1f} s")
678
679 meta = dict(tag=args.tag, steps=STEPS, maxit=MAXIT, rtol=RTOL, mu=MU, dt=DT,
680 g=GRAV, u_lid=ULID, vel_sweeps=VEL_SWEEPS, wall_s=wall,
681 python=sys.version.split()[0], host=platform.node(),
682 argv=" ".join(sys.argv[1:]))
683 if os.path.exists(args.out):
684 with open(args.out) as f:
685 blob = json.load(f)
686 else:
687 blob = {"runs": []}
688 blob.setdefault("runs", []).append({"meta": meta, "records": records,
689 "cheb_overhead": overhead})
690 with open(args.out, "w") as f:
691 json.dump(blob, f, indent=1)
692 print(f"wrote {args.out} ({len(blob['runs'])} run(s))")
693 if args.md:
694 with open(args.md, "w") as f:
695 f.write(md + "\n" + summarize(records) + "\n")
696
697 if args.trace:
698 trace_pcg("box", "slab", "sharp", 1e3, "hydro", args.n)
699
700
701if __name__ == "__main__":
702 main()
_hollow_cyl_sdf(X, Y, Z, c, axis, r_out, r_in, H, N)
run_one(geom, shape, edge, ratio, driver, case, N, quiet=True, bottom=None, levels=None, vprec=None)
trace_pcg(geom, shape, edge, ratio, case, N)
rho_field(shape, edge, ratio, N)
static int run(int bc)