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)
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)
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))]
192 sdf = np.full((N, N, N), 1e30)
193 for c, axis
in rings:
242def run_one(geom, shape, edge, ratio, driver, case, N, quiet=True, bottom=None, levels=None,
244 from peclet
import flow
as F
247 levels = levels
or max(2, int(np.floor(np.log2(N))) - 1)
249 s = F.Solver(N, N, N)
253 s.set_advection(
False)
254 s.diagnostics.set_velocity_solver_params(VEL_SWEEPS)
256 s.set_domain_bc(
"-z",
"wall", (0, 0, 0))
257 s.set_domain_bc(
"+z",
"wall", (0, 0, 0))
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))
264 s.set_body_force((FBODY, 0.0, 0.0))
266 raise ValueError(case)
267 s.set_pressure_multigrid(
True, levels=levels)
269 s.set_pressure_bottom(bottom)
272 s.set_pressure_geometry(np.asfortranarray(np.full((N, N, N), 10.0)))
274 s.set_solid(np.asfortranarray(sdf), cutcell_pressure=
True)
279 s.set_body_force((0.0, 0.0, -GRAV))
282 s.set_field(
"rho", np.asfortranarray(
rho_field(shape, edge, ratio, N)))
283 s.diagnostics.set_density_mode(
"variable")
285 s.set_property_model(
"force_z",
"linear",
"rho", [0.0, -GRAV])
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":
299 s.set_pressure_fcg(
True, MAXIT, RTOL)
301 raise ValueError(driver)
303 s.diagnostics.set_pressure_vcycle_precision(vprec)
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):
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())
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()))
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
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,
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),
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)),
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,
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)
456 """Quantify what rung S2 (bound amortization) would actually buy.
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.
464 from peclet
import flow
as F
466 def run(varrho, driver):
468 levels = max(2, int(np.floor(np.log2(N))) - 1)
469 s = F.Solver(N, N, N)
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)
481 s.set_pressure_geometry(np.asfortranarray(np.full((N, N, N), 10.0)))
483 s.set_solid(np.asfortranarray(sdf), cutcell_pressure=
True)
486 s.set_field(
"rho", np.asfortranarray(
rho_field(
"slab",
"sharp", ratio, N)))
487 s.diagnostics.set_density_mode(
"variable")
489 s.set_pressure_chebyshev(
True, MAXIT, RTOL)
491 s.set_pressure_chebyshev(
False, MAXIT, RTOL)
492 s.set_pressure_pcg(
True, MAXIT, RTOL)
494 for _
in range(STEPS):
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)
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"]
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
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()
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]
631 def expand(gs, shs, n):
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
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]
646 plan = expand(geoms, shapes, args.n)
648 plan += expand([
"pack"], [s
for s
in (
"const",
"slab",
"blob")
if s
in shapes], N_PACK)
650 print(f
"{len(plan)} configurations x {STEPS} steps", flush=
True)
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=
" ",
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
663 if args.cheb_overhead:
665 for g
in args.overhead_geoms.split(
",")
if g]
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'}")
677 print(f
"\ntotal wall {wall:.1f} s")
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:
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))")
694 with open(args.md,
"w")
as f:
695 f.write(md +
"\n" +
summarize(records) +
"\n")
698 trace_pcg(
"box",
"slab",
"sharp", 1e3,
"hydro", args.n)