2"""MG-depth measurement driver (doc/mg_depth_policy.md ยง6 WO-0; reused by the WO-2 gates).
4One process = one case at one pressure-multigrid depth. Every case takes
6 --levels L L >= 1: set_pressure_multigrid(True, L) BEFORE the geometry (an exact depth);
7 L = 0 (the default): do NOT call set_pressure_multigrid -- the solver default
8 (depth 4 on the pre-WO-2 module, AUTO after WO-2).
9 --steps N timed steps (default 30); --warm W untimed warm-up steps (default 5)
10 --dump F.npz u, v, w, p (and C where present) at the end; per rank under MPI (keys u_r<k>, ...,
12 --json F the per-row metrics below plus the per-step lists
13 --rtol R the case's Krylov tolerance, where the case has a Krylov driver (see each case)
14 --line-relaxation on|off
15 diagnostics.set_pressure_line_relaxation (doc/mg_depth_policy.md A2.4) before the
16 geometry; absent: no call (the solver default, on since WO-7)
17 --vcycle-symmetric on|off
18 diagnostics.set_pressure_vcycle_symmetric (doc/mg_depth_policy.md A3) before the
19 geometry; absent: no call (the solver default)
22 swarm periodic bubble swarm, case A groups, single rank: the --single path of
23 tests/study/vof_perf/weak_swarm.py, code for code (--cells n, default 192;
24 --d-over-h 20, --bubbles-per-axis 2). --driver pcg (default; MG-PCG cap 800 at
25 --rtol, default 1e-8, as weak_swarm) or --driver default (no driver call: the
26 variable-density default, Chebyshev).
27 --dims NX NY NZ: an anisotropic box instead of --cells^3 (row M10: an axis that
28 stops coarsening early, doc/mg_depth_policy_log.md); the bubble lattice then has
29 max(1, N_axis // 64) bubbles along each axis (measurement choice) unless
30 --bubbles-per-axis is given, which stays one count for every axis.
31 bc the peclet-examples bubble column (run_peclet.build(), MG-PCG rtol 1e-8 as built)
32 at --cells-per-d S (default 32: 256 x 192 x 128), FRESH START from the seeded
33 spheres at rest (the 128 x 96 x 64 checkpoint does not exist at other
34 resolutions). --rtol re-selects MG-PCG cap 800 at R.
35 zh_sphere / random_spheres
36 the cut-cell Stokes geometries of tests/regression/sdflow_regression.py at --n N
37 with its CFG (MG-PCG cap 300 rtol 1e-8; --rtol overrides), marched to steady with
38 its stop test (--max-steps, default 400; --steps is ignored, --warm 0). Records K / k*.
39 --solver colocated: SolverColocated with NO scheme call, i.e. the AUTO default
40 ('ghost': BiCGStab preconditioned by the V-cycle, at the MG-PCG cap / rtol above);
41 --dump then also writes the fluid-cell mask `fluid` (sdf > 0 at the cell centres,
42 where every colocated field lives). Row M9 (doc/mg_depth_policy_log.md); its exit
43 trace is the solver's PECLET_FLOW_MG_DEBUG=2 line (debug output only).
44 channel single-phase all-fluid channel --nx x --ny x --nz (default 2048 x 64 x 64):
45 periodic x, walls on +-y and +-z, body force along x, from rest plus a fixed-seed
46 non-solenoidal low-mode perturbation (--perturb, default 1e-2). Single rank:
47 the default driver (MG-PCG, auto-enabled); --rtol selects MG-PCG cap 800 at R.
48 Under mpirun (np > 1): mpi_block + init_mpi, the multi-rank default (the
49 standalone V-cycle, no Krylov driver selected; --rtol is refused).
50 anchored inflow/outflow channel --nx x --ny x --nz (default 128 x 32 x 32): uniform inflow
51 U at -x, outflow at +x, walls on +-y, +-z, all fluid; MG-PCG cap --maxit
52 (default 300) at --rtol (default 1e-12) -- the divergence floor at an identical
53 budget at every depth.
54 porous CFD-DEM-style fixed porous bed --n^3 (default 128): add 'eps' via
55 set_porous_continuity(True) with implicit drag (enable_drag), drag_beta from the
56 viscous Ergun term, advection + implicit advection ON (as peclet_coupling's
57 CfdDem), periodic, body force along x; the driver is the solver default for that
58 configuration (no driver call). --no-drag drops enable_drag.
60Per step: wall ms of step() alone, last_pressure_iterations(), max_open_divergence_projected()
61(read after the step, outside the timer), pressure_vcycle_precision(), pressure_solve_failed(),
62and for the porous case max_porous_residual() (the continuity the porous projection solves).
63At the end: the level ratios, the bottom's global dims, the load average before/after. The bottom
64ENGINE is not visible through the API; run_matrix.sh reads it from a short probe run with
65PECLET_FLOW_MG_DEBUG=1 PECLET_FLOW_AGMG_DEBUG=1 (debug output only).
66Rank 0 prints one `RESULT key=value ...` line.
79def arg(name, default, cast=str):
80 return cast(A[A.index(name) + 1])
if name
in A
else default
83CASE =
arg(
"--case",
None)
85 sys.exit(
"mgd_case: --case swarm|bc|zh_sphere|random_spheres|channel|anchored|porous")
86LEVELS =
arg(
"--levels", 0, int)
87STEPS =
arg(
"--steps", 30, int)
88WARM =
arg(
"--warm", 5, int)
89DUMP =
arg(
"--dump",
None)
90JSON =
arg(
"--json",
None)
91RTOL =
arg(
"--rtol",
None, float)
93LINE =
arg(
"--line-relaxation",
None)
94if LINE
not in (
None,
"on",
"off"):
95 sys.exit(
"mgd_case: --line-relaxation on|off")
96SYM =
arg(
"--vcycle-symmetric",
None)
97if SYM
not in (
None,
"on",
"off"):
98 sys.exit(
"mgd_case: --vcycle-symmetric on|off")
99load0 = os.getloadavg()
102NP_ENV = int(os.environ.get(
"OMPI_COMM_WORLD_SIZE", os.environ.get(
"PMI_SIZE",
"1")))
104 from mpi4py
import MPI
105 comm = MPI.COMM_WORLD
106 rank, size = comm.Get_rank(), comm.Get_size()
108 comm, rank, size =
None, 0, 1
116 """--levels L >= 1: an exact depth, before the geometry; 0: leave the solver default.
117 --line-relaxation on|off: the A2.4 line smoother switch (absent: the default).
118 --vcycle-symmetric on|off: the A3 symmetric V-cycle switch (absent: the default)."""
120 s.set_pressure_multigrid(
True, LEVELS)
122 s.diagnostics.set_pressure_line_relaxation(LINE ==
"on")
124 s.diagnostics.set_pressure_vcycle_symmetric(SYM ==
"on")
129 """weak_swarm.py --single, code for code (case A groups, cell units)."""
132 AR, BO, RHO_RATIO, MU_RATIO = 29.9, 2.0, 0.1, 0.1
133 RHO_L, G, D = 1.0, 1.0, 1.0
134 RHO_G = RHO_RATIO * RHO_L
135 MU_L = np.sqrt(RHO_L * abs(RHO_G - RHO_L) * G * D ** 3) / AR
136 MU_G = MU_RATIO * MU_L
137 SIGMA = abs(RHO_G - RHO_L) * G * D ** 2 / BO
138 SEED, PERTURB = 20261024, 0.25
139 CELLS =
arg(
"--cells", 192, int)
140 S =
arg(
"--d-over-h", 20.0, float)
141 DRIVER =
arg(
"--driver",
"pcg")
142 rtol = RTOL
if RTOL
is not None else 1e-8
144 k0 = A.index(
"--dims")
145 NX, NY, NZ = (int(v)
for v
in A[k0 + 1:k0 + 4])
146 Bv = np.array([
arg(
"--bubbles-per-axis", max(1, n // 64), int)
for n
in (NX, NY, NZ)])
149 Bv = np.full(3,
arg(
"--bubbles-per-axis", 2, int))
150 rng = np.random.default_rng(SEED)
151 spv = np.array([NX, NY, NZ]) / Bv
153 if (gapv <= 0).any():
154 sys.exit(f
"swarm: bubbles (d/h {S}) do not fit a lattice spacing of {spv} cells")
156 for k
in range(Bv[2]):
157 for j
in range(Bv[1]):
158 for i
in range(Bv[0]):
159 c = (np.array([i, j, k]) + 0.5) * spv + (rng.random(3) - 0.5) * PERTURB * gapv
160 seeds.append((float(c[0]), float(c[1]), float(c[2]), 0.5 * S))
165 s.set_mu(S * S * MU_L)
166 s.set_pressure_geometry(np.full(siz, 10.0, order=
"F"))
168 s.set_vof(np.zeros(siz, order=
"F"))
169 s.set_property_model(
"rho",
"linear",
"C", [RHO_L, RHO_G - RHO_L])
170 s.set_property_model(
"mu",
"linear",
"C", [S * S * MU_L, S * S * (MU_G - MU_L)])
171 s.set_surface_tension(S ** 3 * SIGMA)
172 s.enable_vof_blocks(seeds)
173 s.enable_vof_block_csf()
174 vol = sum(b[
"volume"]
for b
in s.diagnostics.vof_block_stats())
175 alpha = vol / (NX * NY * NZ)
176 rho_av = RHO_L + (RHO_G - RHO_L) * alpha
177 s.set_property_model(
"force_x",
"linear",
"C",
178 [-S * (RHO_L - rho_av) * G, -S * (RHO_G - RHO_L) * G])
179 s.set_superficial_velocity(
True,
"x", 0.0)
181 s.set_pressure_pcg(
True, 800, rtol)
182 elif DRIVER !=
"default":
183 sys.exit(
"swarm: --driver pcg|default")
184 s.update_properties()
186 info.update(cells=CELLS
if "--dims" not in A
else [NX, NY, NZ], d_over_h=S, bubbles=len(seeds),
187 alpha=alpha, driver=DRIVER,
188 rtol=rtol
if DRIVER ==
"pcg" else "solver default")
191 lim = s.vof_step_limits()
192 return 0.25 * min(lim[
"cfl_dt"], lim[
"capillary_dt"])
193 return s, (NX, NY, NZ), dt_of,
None
199 spd =
arg(
"--cells-per-d", 32, int)
202 os.environ[
"BUBBLE_COLUMN_CELLS_PER_D"] = str(spd)
203 sys.path.insert(0,
arg(
"--case-dir", os.path.expanduser(
204 "~/Codes/peclet-examples/benchmarks/bubble-column/scripts")))
205 import run_peclet
as rp
210 def __new__(cls, *a, **k):
212 o.set_pressure_multigrid(
True, LEVELS)
217 s.diagnostics.set_pressure_vcycle_symmetric(SYM ==
"on")
219 s.set_pressure_pcg(
True, 800, RTOL)
221 info.update(cells_per_d=spd, start=
"fresh (seeded spheres at rest)",
222 rtol=RTOL
if RTOL
is not None else 1e-8)
225 lim = s.vof_step_limits()
226 return min(0.25 * lim[
"cfl_dt"], 0.25 * lim[
"capillary_dt"])
227 return s, (rp.NX, rp.NY, rp.NZ), dt_of,
None
232 g = np.arange(N) + 0.5
233 X, Y, Z = np.meshgrid(g, g, g, indexing=
"ij")
234 if name ==
"zh_sphere":
236 R = (phi * 3.0 / (4.0 * np.pi)) ** (1.0 / 3.0) * N
238 sdf = np.sqrt((X - c) ** 2 + (Y - c) ** 2 + (Z - c) ** 2) - R
241 rng = np.random.default_rng(12345)
243 base = np.array([[(i + 0.5) / 2.0, (j + 0.5) / 2.0, (k + 0.5) / 2.0]
244 for i
in range(2)
for j
in range(2)
for k
in range(2)])
245 centres = ((base + 0.06 * rng.standard_normal(base.shape)) % 1.0) * N
246 sdf = np.full((N, N, N), 1e30)
247 mi =
lambda d: d - N * np.round(d / N)
248 for cx, cy, cz
in centres:
249 dx, dy, dz = mi(X - cx), mi(Y - cy), mi(Z - cz)
250 sdf = np.minimum(sdf, np.sqrt(dx * dx + dy * dy + dz * dz) - R)
256 N =
arg(
"--n", 128, int)
257 CFG = dict(rho=1.0, mu=0.1, dt=60.0, F=1e-3, vel_sweeps=80, pcg_maxit=300, pcg_rtol=1e-8)
258 rtol = RTOL
if RTOL
is not None else CFG[
"pcg_rtol"]
260 solver =
arg(
"--solver",
"staggered")
261 if solver
not in (
"staggered",
"colocated"):
262 sys.exit(
"mgd_case: --solver staggered|colocated")
263 s = (pf.SolverColocated
if solver ==
"colocated" else pf.Solver)(N, N, N)
264 s.set_rho(CFG[
"rho"]); s.set_mu(CFG[
"mu"]); s.set_dt(CFG[
"dt"])
265 s.set_body_force((CFG[
"F"], 0.0, 0.0))
266 s.set_advection(
False)
267 s.diagnostics.set_velocity_solver_params(CFG[
"vel_sweeps"])
269 s.set_pressure_pcg(
True, CFG[
"pcg_maxit"], rtol)
270 s.set_solid(sdf, cutcell_pressure=
True)
271 info.update(n=N, R=R, rtol=rtol, cfg=CFG, solver=solver, _sdf=sdf)
272 return s, (N, N, N),
None, CFG
278 G = (
arg(
"--nx", 2048, int),
arg(
"--ny", 64, int),
arg(
"--nz", 64, int))
279 mu, dt, F =
arg(
"--mu", 0.05, float),
arg(
"--dt", 1.0, float),
arg(
"--force", 1e-5, float)
282 sys.exit(
"channel np > 1: the standalone V-cycle default has no Krylov driver (--rtol)")
283 org, siz = pf.mpi_block(*G)
285 org, siz = (0, 0, 0), G
290 s.set_rho(1.0); s.set_mu(mu); s.set_dt(dt)
291 for f
in (
"-y",
"+y",
"-z",
"+z"):
292 s.set_domain_bc(f,
"wall", (0.0, 0.0, 0.0))
293 s.set_pressure_geometry(np.full(tuple(siz), 10.0, order=
"F"))
294 s.set_body_force((F, 0.0, 0.0))
296 s.set_pressure_pcg(
True, 800, RTOL)
300 amp =
arg(
"--perturb", 1e-2, float)
301 rng = np.random.default_rng(20261024)
302 xs = [np.arange(org[d], org[d] + siz[d]) + 0.5
for d
in range(3)]
303 X, Y, Z = np.meshgrid(*xs, indexing=
"ij")
305 a = np.zeros(tuple(siz))
307 n = (rng.integers(1, 17), rng.integers(1, 5), rng.integers(1, 5))
308 ph = rng.random() * 2 * np.pi
309 a += np.sin(2 * np.pi * (n[0] * X / G[0] + n[1] * Y / G[1] + n[2] * Z / G[2]) + ph)
310 s.set_velocity(c, np.asfortranarray(amp / 8.0 * a))
312 info.update(mu=mu, dt=dt, force=F, origin=list(org), block=list(siz), perturb=amp,
313 driver=(
"pcg rtol %g" % RTOL)
if RTOL
is not None else
314 (
"default (standalone V-cycle)" if size > 1
else "default (MG-PCG)"))
315 return s, G,
None,
None
320 G = (
arg(
"--nx", 128, int),
arg(
"--ny", 32, int),
arg(
"--nz", 32, int))
321 mu, dt, U =
arg(
"--mu", 0.1, float),
arg(
"--dt", 1.0, float),
arg(
"--u-in", 0.05, float)
322 maxit =
arg(
"--maxit", 300, int)
323 rtol = RTOL
if RTOL
is not None else 1e-12
326 s.set_rho(1.0); s.set_mu(mu); s.set_dt(dt)
327 s.set_domain_bc(
"-x",
"inflow", (U, 0.0, 0.0))
328 s.set_domain_bc(
"+x",
"outflow", (0.0, 0.0, 0.0))
329 for f
in (
"-y",
"+y",
"-z",
"+z"):
330 s.set_domain_bc(f,
"wall", (0.0, 0.0, 0.0))
331 s.set_pressure_geometry(np.full(G, 10.0, order=
"F"))
332 s.set_pressure_pcg(
True, maxit, rtol)
333 info.update(mu=mu, dt=dt, u_in=U, maxit=maxit, rtol=rtol)
334 return s, G,
None,
None
339 N =
arg(
"--n", 128, int)
340 mu, dt, F, dp =
arg(
"--mu", 0.05, float),
arg(
"--dt", 1.0, float), 1e-4, 4.0
341 drag =
"--no-drag" not in A
345 rng = np.random.default_rng(20261024)
346 noise = rng.standard_normal(G)
347 k = np.fft.fftfreq(N)
348 KX, KY, KZ = np.meshgrid(k, k, k, indexing=
"ij")
349 noise = np.real(np.fft.ifftn(np.fft.fftn(noise) * np.exp(-(KX**2 + KY**2 + KZ**2) * (N / 8.0) ** 2)))
350 noise /= np.abs(noise).max()
351 x = np.arange(N) + 0.5
352 w = 0.5 * (1.0 - np.tanh((x - 0.6 * N) / 4.0))[:,
None,
None]
353 eps = np.asfortranarray(1.0 - w * (0.55 - 0.1 * noise))
354 beta = np.asfortranarray(150.0 * mu * (1.0 - eps) ** 2 / (eps * dp * dp))
357 s.set_rho(1.0); s.set_mu(mu); s.set_dt(dt)
358 s.set_advection(
True)
359 s.set_implicit_advection(
True)
360 s.set_pressure_geometry(np.full(G, 10.0, order=
"F"))
363 s.set_porous_continuity(
True)
364 s.set_field(
"eps", eps)
365 s.diagnostics.exchange_field(
"eps")
367 s.set_field(
"drag_beta", beta)
368 s.diagnostics.exchange_field(
"drag_beta")
370 s.set_body_force((F, 0.0, 0.0))
372 sys.exit(
"porous: the default driver only (no --rtol)")
373 info.update(n=N, mu=mu, dt=dt, force=F, dp=dp, drag=drag, eps_min=float(eps.min()),
374 beta_max=float(beta.max())
if drag
else 0.0)
375 return s, G,
None,
None
378BUILD = {
"swarm": build_swarm,
"bc": build_bc,
"zh_sphere": build_ibm,
"random_spheres": build_ibm,
379 "channel": build_channel,
"anchored": build_anchored,
"porous": build_porous}
381 sys.exit(f
"mgd_case: unknown case {CASE}")
382t_setup0 = time.perf_counter()
383s, GRID, dt_of, IBM = BUILD[CASE]()
386t_setup = time.perf_counter() - t_setup0
389step_ms, iters, divs, prec, failed, pres = [], [], [], [], [], []
390POROUS = CASE ==
"porous"
394 if dt_of
is not None:
396 t0 = time.perf_counter()
398 t1 = time.perf_counter()
400 step_ms.append(1000.0 * (t1 - t0))
401 iters.append(int(s.diagnostics.last_pressure_iterations()))
402 divs.append(float(s.max_open_divergence_projected()))
403 prec.append(s.diagnostics.pressure_vcycle_precision())
404 failed.append(bool(s.diagnostics.pressure_solve_failed()))
406 pres.append(float(s.max_porous_residual()))
410 for _
in range(WARM):
414 w0 = time.perf_counter()
415 for _
in range(STEPS):
419 wall = time.perf_counter() - w0
422 w0 = time.perf_counter()
423 for it
in range(
arg(
"--max-steps", 400, int)):
427 if it >= 15
and abs(m - prev) < 1e-5 * (abs(m) + 1e-30):
430 wall = time.perf_counter() - w0
431 STEPS, WARM = len(step_ms), 0
433 umean = float(u.mean())
434 sdf = info.pop(
"_sdf")
435 if info.get(
"solver") ==
"colocated":
436 FLUID_MASK = sdf > 0.0
438 if CASE ==
"zh_sphere":
439 info[
"K"] = IBM[
"F"] * GRID[0] ** 3 / (6.0 * np.pi * IBM[
"mu"] * info[
"R"] * umean)
441 info[
"k_star"] = IBM[
"mu"] * umean / (IBM[
"F"] * GRID[0] ** 2)
442 info[
"divergence_end"] = float(s.max_open_divergence())
443 info[
"max_u_solid"] = float(np.abs(u[deep]).max())
if deep.any()
else 0.0
444 info[
"iters_median_2nd_half"] = float(np.median(iters[len(iters) // 2:]))
445 info[
"iters_total"] = int(sum(iters))
448ratios = [tuple(int(v)
for v
in r)
for r
in s.diagnostics.pressure_mg_level_ratios()]
452 g = [g[0] // r[0], g[1] // r[1], g[2] // r[2]]
453 dims.append(tuple(g))
457fx = {
"u": s.get_u,
"v": s.get_v,
"w": s.get_w,
"p":
lambda: s.get_field(
"p")}
459 fx[
"C"] =
lambda: s.get_field(
"C")
460arrs = {k: np.ascontiguousarray(f())
for k, f
in fx.items()}
462 h.update(arrs[k].tobytes())
465 np.savez(DUMP, **arrs, **({}
if FLUID_MASK
is None else {
"fluid": FLUID_MASK}))
467 allv = comm.gather((list(info.get(
"origin", [0, 0, 0])), arrs), root=0)
470 for r, (o, a)
in enumerate(allv):
471 out[f
"origin_r{r}"] = np.asarray(o)
472 for k, v
in a.items():
474 np.savez(DUMP, **out)
475digest = h.hexdigest()
477 ds = comm.gather(digest, root=0)
479 gg = hashlib.sha256()
481 gg.update(d.encode())
482 digest = gg.hexdigest()
483load1 = os.getloadavg()
486 sm = np.asarray(step_ms)
487 prec_flips = sum(1
for a, b
in zip(prec, prec[1:])
if a ==
"fp32" and b ==
"fp64")
489 "case": CASE,
"tag": TAG,
"np": size,
"grid": list(GRID),
"levels_req": LEVELS,
490 "line_relaxation": LINE
or "default",
"vcycle_symmetric": SYM
or "default",
491 "levels": len(ratios),
"ratios": [list(r)
for r
in ratios],
"bottom": list(bottom),
492 "bottom_cells": int(np.prod(bottom)),
"dims": [list(d)
for d
in dims],
493 "space": str(getattr(pf,
"execution_space",
"?")),
494 "flow_module": os.path.dirname(pf.__file__),
495 "omp_threads": os.environ.get(
"OMP_NUM_THREADS",
"unset"),
496 "warm": WARM,
"steps": STEPS,
"setup_s": t_setup,
"wall_ms": 1000.0 * wall / max(STEPS, 1),
497 "step_ms_mean": float(sm.mean()),
"step_ms_median": float(np.median(sm)),
498 "iters_mean": float(np.mean(iters)),
"iters_min": int(min(iters)),
499 "iters_max": int(max(iters)),
"div_max": float(max(divs)),
"div_last": divs[-1],
500 "prec_first": prec[0],
"prec_last": prec[-1],
"fp32_restart_flips": prec_flips,
501 "solve_failed": int(sum(failed)),
502 "cheb_restarts": int(getattr(s.diagnostics,
"num_pressure_chebyshev_restarts", -1)),
503 "cheb_growth_trips": int(getattr(s.diagnostics,
"num_pressure_chebyshev_growth_trips", -1)),
504 "load_before": list(load0),
"load_after": list(load1),
"hash": digest,
506 res.update({k: v
for k, v
in info.items()})
508 res.update(porous_res_max=max(pres), porous_res_last=pres[-1])
509 keep = (
"case",
"tag",
"np",
"levels_req",
"levels",
"bottom",
"steps",
"wall_ms",
510 "step_ms_median",
"iters_mean",
"iters_min",
"iters_max",
"div_max",
"prec_last",
511 "fp32_restart_flips",
"solve_failed",
"cheb_restarts",
"cheb_growth_trips",
512 "porous_res_max",
"K",
"k_star")
515 if isinstance(v, float):
517 return "x".join(map(str, v))
if isinstance(v, list)
else str(v)
518 print(
"RESULT " +
" ".join(f
"{k}={fmt(res[k])}" for k
in keep
if k
in res)
519 + f
" load={load0[0]:.1f}/{load1[0]:.1f}", flush=
True)
521 res.update(step_ms_list=step_ms, iters_list=iters, div_list=divs, prec_list=prec,
522 failed_list=failed, porous_res_list=pres)
523 with open(JSON,
"w")
as fo:
524 json.dump(res, fo, indent=1, default=str)
arg(name, default, cast=str)
static double mean(const std::vector< double > &a)