flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
mgd_case.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""MG-depth measurement driver (doc/mg_depth_policy.md ยง6 WO-0; reused by the WO-2 gates).
3
4One process = one case at one pressure-multigrid depth. Every case takes
5
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>, ...,
11 origin_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)
20
21Cases (--case):
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.
59
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.
67"""
68import hashlib
69import json
70import os
71import sys
72import time
73
74import numpy as np
75
76A = list(sys.argv)
77
78
79def arg(name, default, cast=str):
80 return cast(A[A.index(name) + 1]) if name in A else default
81
82
83CASE = arg("--case", None)
84if CASE is 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)
92TAG = arg("--tag", "")
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()
100
101# MPI only when launched under mpirun (the channel at np > 1)
102NP_ENV = int(os.environ.get("OMPI_COMM_WORLD_SIZE", os.environ.get("PMI_SIZE", "1")))
103if NP_ENV > 1:
104 from mpi4py import MPI
105 comm = MPI.COMM_WORLD
106 rank, size = comm.Get_rank(), comm.Get_size()
107else:
108 comm, rank, size = None, 0, 1
109
110info = {} # case-specific end-of-run numbers
111FLUID_MASK = None # colocated IBM: dumped beside the fields (G-CONV (b) on fluid cells)
112fields_C = False # dump C too
113
114
115def depth(s):
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)."""
119 if LEVELS >= 1:
120 s.set_pressure_multigrid(True, LEVELS)
121 if LINE is not None:
122 s.diagnostics.set_pressure_line_relaxation(LINE == "on")
123 if SYM is not None:
124 s.diagnostics.set_pressure_vcycle_symmetric(SYM == "on")
125
126
127# ------------------------------------------------------------------------------------- swarm
129 """weak_swarm.py --single, code for code (case A groups, cell units)."""
130 global fields_C
131 import peclet.flow as pf
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
143 if "--dims" in A: # anisotropic box (M10); default lattice max(1, N // 64) per axis
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)])
147 else: # the cube, code for code as before
148 NX = NY = NZ = CELLS
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
152 gapv = spv - S
153 if (gapv <= 0).any():
154 sys.exit(f"swarm: bubbles (d/h {S}) do not fit a lattice spacing of {spv} cells")
155 seeds = []
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))
161 siz = (NX, NY, NZ)
162 s = pf.Solver(*siz)
163 depth(s)
164 s.set_rho(RHO_L)
165 s.set_mu(S * S * MU_L)
166 s.set_pressure_geometry(np.full(siz, 10.0, order="F"))
167 s.enable_vof()
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)
180 if DRIVER == "pcg":
181 s.set_pressure_pcg(True, 800, rtol) # last (the rho closure re-selects); case A's driver
182 elif DRIVER != "default":
183 sys.exit("swarm: --driver pcg|default")
184 s.update_properties()
185 fields_C = True
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")
189
190 def dt_of():
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
194
195
196# ------------------------------------------------------------------------------- bubble column
198 global fields_C
199 spd = arg("--cells-per-d", 32, int)
200 # the example's own resolution parameter; read by case.py at import (an example-script input,
201 # not a solver setting)
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
206 if LEVELS >= 1:
207 orig = rp.pf.Solver
208
209 class _Shim: # set_pressure_multigrid right after construction, as prof.py --levels
210 def __new__(cls, *a, **k):
211 o = orig(*a, **k)
212 o.set_pressure_multigrid(True, LEVELS)
213 return o
214 rp.pf.Solver = _Shim
215 s = rp.build(None)
216 if SYM is not None: # the A3 switch is live (read at V-cycle time): after the build
217 s.diagnostics.set_pressure_vcycle_symmetric(SYM == "on")
218 if RTOL is not None:
219 s.set_pressure_pcg(True, 800, RTOL)
220 fields_C = True
221 info.update(cells_per_d=spd, start="fresh (seeded spheres at rest)",
222 rtol=RTOL if RTOL is not None else 1e-8)
223
224 def dt_of():
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
228
229
230# ------------------------------------------------------------------------------------- IBM
231def _ibm_sdf(name, N):
232 g = np.arange(N) + 0.5
233 X, Y, Z = np.meshgrid(g, g, g, indexing="ij")
234 if name == "zh_sphere": # sdflow_regression.sdf_zh_sphere (phi 0.216)
235 phi = 0.216
236 R = (phi * 3.0 / (4.0 * np.pi)) ** (1.0 / 3.0) * N
237 c = N / 2.0
238 sdf = np.sqrt((X - c) ** 2 + (Y - c) ** 2 + (Z - c) ** 2) - R
239 return sdf, R
240 # sdflow_regression.sdf_random_spheres (n 8, r_frac 0.18, jit 0.06, seed 12345)
241 rng = np.random.default_rng(12345)
242 R = 0.18 * N
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)
251 return sdf, R
252
253
255 import peclet.flow as pf
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"]
259 sdf, R = _ibm_sdf(CASE, N)
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) # creeping Stokes
267 s.diagnostics.set_velocity_solver_params(CFG["vel_sweeps"])
268 depth(s)
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
273
274
275# ------------------------------------------------------------------------------------- channel
277 import peclet.flow as pf
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)
280 if size > 1:
281 if RTOL is not None:
282 sys.exit("channel np > 1: the standalone V-cycle default has no Krylov driver (--rtol)")
283 org, siz = pf.mpi_block(*G)
284 else:
285 org, siz = (0, 0, 0), G
286 s = pf.Solver(*siz)
287 if size > 1:
288 s.init_mpi(*G)
289 depth(s)
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))
295 if RTOL is not None:
296 s.set_pressure_pcg(True, 800, RTOL)
297 # a fixed-seed, non-solenoidal low-mode initial perturbation (8 modes per component, amplitude
298 # --perturb), evaluated at GLOBAL cell coordinates so every np sees the same field: without it
299 # the body-force channel is unidirectional and the projection has nothing to do
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")
304 for c in range(3):
305 a = np.zeros(tuple(siz))
306 for _ in range(8):
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))
311 del X, Y, Z
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
316
317
319 import peclet.flow as pf
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
324 s = pf.Solver(*G)
325 depth(s)
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
335
336
338 import peclet.flow as pf
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
342 G = (N, N, N)
343 # a fixed bed: eps 0.45 +- 0.1 (smoothed fixed-seed noise) for x < 0.6 N, 1 above, a smooth
344 # 4-cell transition; drag_beta = the viscous Ergun term 150 mu (1-eps)^2 / (eps dp^2)
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))
355 s = pf.Solver(*G)
356 depth(s)
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"))
361 if drag:
362 s.enable_drag()
363 s.set_porous_continuity(True)
364 s.set_field("eps", eps)
365 s.diagnostics.exchange_field("eps")
366 if drag:
367 s.set_field("drag_beta", beta)
368 s.diagnostics.exchange_field("drag_beta")
369 s.sync_porous_prev()
370 s.set_body_force((F, 0.0, 0.0))
371 if RTOL is not None:
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
376
377
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}
380if CASE not in BUILD:
381 sys.exit(f"mgd_case: unknown case {CASE}")
382t_setup0 = time.perf_counter()
383s, GRID, dt_of, IBM = BUILD[CASE]()
384if comm is not None:
385 comm.Barrier()
386t_setup = time.perf_counter() - t_setup0
387import peclet.flow as pf
388
389step_ms, iters, divs, prec, failed, pres = [], [], [], [], [], []
390POROUS = CASE == "porous"
391
392
393def one(timed):
394 if dt_of is not None:
395 s.set_dt(dt_of())
396 t0 = time.perf_counter()
397 s.step()
398 t1 = time.perf_counter()
399 if timed:
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()))
405 if POROUS: # the porous continuity residual (div(open u) is -d(eps)/dt-shaped there)
406 pres.append(float(s.max_porous_residual()))
407
408
409if IBM is None:
410 for _ in range(WARM):
411 one(False)
412 if comm is not None:
413 comm.Barrier()
414 w0 = time.perf_counter()
415 for _ in range(STEPS):
416 one(True)
417 if comm is not None:
418 comm.Barrier()
419 wall = time.perf_counter() - w0
420else: # sdflow_regression.run_case's march and stop test (check every 5, min 15, tol 1e-5, max 400)
421 prev = 0.0
422 w0 = time.perf_counter()
423 for it in range(arg("--max-steps", 400, int)):
424 one(True)
425 if it % 5 == 4:
426 m = float(s.get_u().mean())
427 if it >= 15 and abs(m - prev) < 1e-5 * (abs(m) + 1e-30):
428 break
429 prev = m
430 wall = time.perf_counter() - w0
431 STEPS, WARM = len(step_ms), 0
432 u = s.get_u()
433 umean = float(u.mean())
434 sdf = info.pop("_sdf")
435 if info.get("solver") == "colocated":
436 FLUID_MASK = sdf > 0.0
437 deep = sdf < -2.0
438 if CASE == "zh_sphere":
439 info["K"] = IBM["F"] * GRID[0] ** 3 / (6.0 * np.pi * IBM["mu"] * info["R"] * umean)
440 else:
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))
446
447# the hierarchy: per-level ratios; the bottom's global dims = grid / prod(ratios of the levels above)
448ratios = [tuple(int(v) for v in r) for r in s.diagnostics.pressure_mg_level_ratios()]
449g = list(GRID)
450dims = [tuple(g)]
451for r in ratios[:-1]:
452 g = [g[0] // r[0], g[1] // r[1], g[2] // r[2]]
453 dims.append(tuple(g))
454bottom = dims[-1]
455
456h = hashlib.sha256()
457fx = {"u": s.get_u, "v": s.get_v, "w": s.get_w, "p": lambda: s.get_field("p")}
458if fields_C:
459 fx["C"] = lambda: s.get_field("C")
460arrs = {k: np.ascontiguousarray(f()) for k, f in fx.items()}
461for k in arrs:
462 h.update(arrs[k].tobytes())
463if DUMP:
464 if comm is None:
465 np.savez(DUMP, **arrs, **({} if FLUID_MASK is None else {"fluid": FLUID_MASK}))
466 else:
467 allv = comm.gather((list(info.get("origin", [0, 0, 0])), arrs), root=0)
468 if rank == 0:
469 out = {}
470 for r, (o, a) in enumerate(allv):
471 out[f"origin_r{r}"] = np.asarray(o)
472 for k, v in a.items():
473 out[f"{k}_r{r}"] = v
474 np.savez(DUMP, **out)
475digest = h.hexdigest()
476if comm is not None:
477 ds = comm.gather(digest, root=0)
478 if rank == 0:
479 gg = hashlib.sha256()
480 for d in ds:
481 gg.update(d.encode())
482 digest = gg.hexdigest()
483load1 = os.getloadavg()
484
485if rank == 0:
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")
488 res = {
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,
505 }
506 res.update({k: v for k, v in info.items()})
507 if POROUS:
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")
513
514 def fmt(v):
515 if isinstance(v, float):
516 return f"{v:.6g}"
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)
520 if JSON:
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)
one(timed)
Definition mgd_case.py:393
arg(name, default, cast=str)
Definition mgd_case.py:79
_ibm_sdf(name, N)
Definition mgd_case.py:231
build_ibm()
Definition mgd_case.py:254
build_anchored()
Definition mgd_case.py:318
build_swarm()
Definition mgd_case.py:128
build_channel()
Definition mgd_case.py:276
build_porous()
Definition mgd_case.py:337
static double mean(const std::vector< double > &a)