flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
run_case_a.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""Case A of the bubble-swarm validation: the Esmaeeli-Tryggvason (1999) ordered bubble array.
3
4One bubble in a triply periodic cube is an infinite simple-cubic array. Parameters as rerun by
5Innocenti, Jaccod, Popinet & Chibbaro (2021, JFM 918:A23, arXiv 2002.02209, sec. 3 and Table 3)
6and Loisy, Naso & Spelt (2017, JFM 816:94, case E1, fig. 1a):
7
8 Ar = sqrt(rho_l |rho_b - rho_l| g d^3) / mu_l = 29.9, Bo = |rho_b - rho_l| g d^2 / sigma = 2,
9 rho_b/rho_l = mu_b/mu_l = 0.1, L = 1.6 d (Table 3: 16^3 cells at d/h = 10), phi = 12.8 %.
10
11Re = rho_l U d / mu_l with U the DRIFT velocity U = <u>_d - <u> (Loisy 2017 eq. 2.3: the volume
12average over the gas minus the volume average over the whole cell). Targets (Table 3): Basilisk
1323.05/22.01/21.275/21.0 at d/h 10/20/40/80, Loisy 19.05/20.22/20.58 at 10/20/40, E&T 20.49 at 40.
14
15Set-up: the bubble-column driver's (peclet-examples benchmarks/bubble-column/scripts/run_peclet.py)
16multiple-marker VoF with its solver settings, in a PHYSICAL domain (metres, SI properties).
17Gravity points along -x, so the bubble rises along +x:
18 * buoyancy with the mixture weight removed, f_x = -(rho(C) - <rho>) g, <rho> from the discrete
19 gas volume (the -<rho>g body force of Innocenti sec. 3 / Loisy eq. 3.1);
20 * set_superficial_velocity(True, 'x', 0): the volume mean <u_x> is held at 0, so the computational
21 frame is Loisy's zero-mixture-velocity frame and the drift velocity is the gas-averaged u_x.
22 The lateral means <u_y>, <u_z> are free (zero by symmetry) and are written out as a check.
23
24Usage:
25 PYTHONPATH=<flow build> OMP_NUM_THREADS=8 OMP_PROC_BIND=false \\
26 python tests/study/case_a/run_case_a.py --d-over-h 10 --backend host --t-end 20 --out runA10
27
28 --d-over-h {10,20,40,80} cells per bubble diameter; box = (1.6 d/h)^3 cells
29 --backend {host,cuda} checked against the imported module's Kokkos execution space (the
30 backend is chosen by PYTHONPATH, i.e. by which build is imported)
31 --t-end T end time in units of sqrt(d/g) (default 20)
32 --out DIR writes DIR/case_a.csv (one row per sample) and DIR/summary.txt;
33 a_closure_g = the superficial-velocity closure's acceleration
34 (last_superficial_velocity_shift / dt) in units of g
35 --dt-out T sample interval in sqrt(d/g) (default 0.05)
36 --max-steps N, --wall S stop early (timing / smoke runs)
37 --dt-safety F fraction of the CFL and capillary limits (default 0.25, the driver's)
38 --mu-ratio R ablation: mu_b/mu_l (default 0.1, the case); Ar and Bo are unchanged
39 (both use mu_l and the density difference)
40 --rho-ratio R ablation: the INERTIAL density ratio rho_b/rho_l (default 0.1, the case).
41 The buoyancy force keeps the case density, -(rho_case(C) - <rho_case>) g
42 with rho_b = 0.1 rho_l, so at R = 1 the buoyancy is Boussinesq and Ar,
43 Bo, mu_l, sigma are unchanged (refused with --vof-momentum)
44 --face-mu {arithmetic,harmonic} ablation: face-viscosity mean (default arithmetic, the driver's)
45 --viscous-stress {laplacian,full} the viscous stress form (set_viscous_stress). Absent: no setter
46 call, the solver's own default (AUTO = full for case A since WO-7;
47 doc/full_viscous_stress.md)
48 --no-advection momentum advection off (unsteady Stokes momentum). The default is ON
49 (set_advection(True), explicit SOU): case A is Navier-Stokes. The
50 solver's own default is OFF, and every case-A run before 2026-10-23
51 ran without it (G5 diagnosis, validation/G5_DIAG.md); `--advection`
52 is accepted and is the default
53 --single-vof ablation: the structured VoF + CSF without the block container (the
54 bubble seeded as 8x8x8 sub-sampled sphere fractions)
55 --vof-momentum ablation: enable_vof_momentum(rho_g, rho_l) (implies --single-vof:
56 the momentum-consistent transport is refused with the blocks)
57 --vof-mom-muscl ablation (with --vof-momentum): MinMod-limited donor velocity in the
58 momentum flux (diagnostics.set_vof_momentum_muscl) instead of the
59 default first-order donor cell
60 --mpi distributed run under mpirun (mpi4py; needs a PECLET_FLOW_MPI build):
61 mpi_block + init_mpi before the geometry; the fields are gathered for
62 the samples, rank 0 writes. At one rank the single-rank solver runs (no
63 mpi_block, no init_mpi), so `--mpi` at np 1 equals a run without it.
64 --dump FILE.npz write the final global u, v, w, p, C (decomposition-invariance checks,
65 doc/full_viscous_stress.md G4)
66
67Prints one summary line.
68"""
69import argparse
70import math
71import os
72import resource
73import sys
74import time
75
76import numpy as np
77import peclet.flow as pf
78
79# --- physics: dimensionless groups (verified against the sources, see docstring) -------------
80AR, BO, RHO_RATIO, MU_RATIO, L_OVER_D = 29.9, 2.0, 0.1, 0.1, 1.6
81# --- dimensional realisation (SI): a 1 mm bubble; mu_l and sigma follow from Ar and Bo ---------
82D = 1.0e-3 # m, volume-equivalent diameter
83RHO_L = 1000.0 # kg/m^3
84RHO_G = RHO_RATIO * RHO_L
85G = 9.81 # m/s^2, along -x
86MU_L = math.sqrt(RHO_L * abs(RHO_G - RHO_L) * G * D ** 3) / AR # 3.1426e-3 Pa s
87MU_G = MU_RATIO * MU_L
88SIGMA = abs(RHO_G - RHO_L) * G * D ** 2 / BO # 4.4145e-3 N/m
89T_REF = math.sqrt(D / G) # time unit of the literature plots (Loisy fig. 1a)
90
91
92def parse():
93 p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
94 p.add_argument("--d-over-h", type=int, required=True, choices=(10, 20, 40, 80))
95 p.add_argument("--backend", required=True, choices=("host", "cuda"))
96 p.add_argument("--t-end", type=float, default=20.0)
97 p.add_argument("--out", required=True)
98 p.add_argument("--dt-out", type=float, default=0.05)
99 p.add_argument("--max-steps", type=int, default=None)
100 p.add_argument("--wall", type=float, default=float("inf"))
101 p.add_argument("--dt-safety", type=float, default=0.25)
102 p.add_argument("--mu-ratio", type=float, default=MU_RATIO)
103 p.add_argument("--rho-ratio", type=float, default=RHO_RATIO)
104 p.add_argument("--face-mu", choices=("arithmetic", "harmonic"), default="arithmetic")
105 p.add_argument("--viscous-stress", choices=("laplacian", "full"), default=None)
106 p.add_argument("--advection", action=argparse.BooleanOptionalAction, default=True,
107 help="momentum advection (default on; --no-advection: unsteady Stokes)")
108 p.add_argument("--single-vof", action="store_true")
109 p.add_argument("--vof-momentum", action="store_true")
110 p.add_argument("--vof-mom-muscl", action="store_true")
111 p.add_argument("--mpi", action="store_true")
112 p.add_argument("--dump", default=None)
113 return p.parse_args()
114
115
117 space = getattr(pf, "execution_space", "unknown")
118 got = "cuda" if "cuda" in str(space).lower() else "host"
119 if got != want:
120 sys.exit(f"--backend {want} but the imported peclet.flow runs on '{space}' "
121 f"({pf.__file__}); point PYTHONPATH at the matching build")
122 return str(space)
123
124
125def sphere_fractions(n, c, r, sub=8):
126 """Cell volume fractions of a sphere (centre c, radius r, both in cells), sub^3 samples."""
127 off = (np.arange(sub) + 0.5) / sub
128 g = (np.arange(n)[:, None] + off[None, :]).ravel()
129 out = np.zeros((n, n, n))
130 for k in range(n): # z slabs keep the memory at n^2 sub^3
131 zs = k + off
132 X, Y, Z = np.meshgrid(g, g, zs, indexing="ij")
133 ins = ((X - c) ** 2 + (Y - c) ** 2 + (Z - c) ** 2 < r * r).astype(np.float64)
134 out[:, :, k] = ins.reshape(n, sub, n, sub, sub).mean(axis=(1, 3, 4))
135 return np.asfortranarray(out)
136
137
138class Dist:
139 """The rank's block of the global n^3 box; single-rank when comm is None."""
140
141 def __init__(self, n, comm=None):
142 self.n, self.comm = n, comm
143 if comm is None:
144 self.org, self.siz = (0, 0, 0), (n, n, n)
145 else:
146 self.org, self.siz = pf.mpi_block(n, n, n)
147 self.sl = tuple(slice(o, o + m) for o, m in zip(self.org, self.siz))
148
149 def gather(self, a):
150 """The global array from every rank's local block (identity single-rank)."""
151 if self.comm is None:
152 return a
153 out = np.zeros((self.n,) * 3, order="F")
154 for sl, blk in self.comm.allgather((self.sl, np.asarray(a))):
155 out[sl] = blk
156 return out
157
158 def any(self, flag):
159 return flag if self.comm is None else bool(self.comm.allreduce(bool(flag)))
160
161
162def build(n, mu_g=MU_G, face_mu="arithmetic", stress=None, single=False, vof_mom=False,
163 dist=None, advection=True, rho_g_in=RHO_G, vof_mom_muscl=False):
164 L = L_OVER_D * D
165 dist = dist or Dist(n)
166 if dist.comm is None:
167 s = pf.Solver((n, n, n), extent=(L, L, L))
168 else:
169 s = pf.Solver(dist.siz, extent=(L, L, L), global_cells=(n, n, n))
170 s.init_mpi(n, n, n) # before the geometry
171 s.set_rho(RHO_L)
172 s.set_mu(MU_L)
173 s.set_pressure_geometry(np.full(dist.siz, 1.0, order="F")) # all fluid (SDF > 0)
174 s.enable_vof()
175 s.set_vof(np.zeros(dist.siz, order="F"))
176 # C = 1 is GAS (the block container's union starts empty)
177 s.set_property_model("rho", "linear", "C", [RHO_L, rho_g_in - RHO_L]) # inertial density
178 s.set_property_model("mu", "linear", "C", [MU_L, mu_g - MU_L])
179 if face_mu == "harmonic":
180 s.diagnostics.set_property_mode("variable", True)
181 if stress is not None: # None: the solver's default form
182 s.set_viscous_stress(stress)
183 if advection:
184 s.set_advection(True)
185 s.set_surface_tension(SIGMA)
186 s.set_pressure_pcg(True, 800, 1e-8) # last; the bubble-column driver's setting
187 # One marker at the box centre. enable_vof_blocks takes GRID coordinates (cells) even under a
188 # physical domain -- derived here from the physical centre and radius, never user input.
189 h = L / n
190 if single or vof_mom:
191 s.set_vof(np.asfortranarray(sphere_fractions(n, 0.5 * L / h, 0.5 * D / h)[dist.sl]))
192 if vof_mom:
193 # enable_vof_momentum(rho_c0, rho_c1) takes the closure's densities at C = 0 and
194 # C = 1 (the advector's rho(C) = rho_c0 (1 - C) + rho_c1 C). Here C = 1 is the GAS,
195 # so rho(C=0) = RHO_L goes first. Passing (RHO_G, RHO_L) swapped the phases in the
196 # momentum transport (the Q6 runs before 2026-10-23; validation/Q6_DIAG.md).
197 s.enable_vof_momentum(RHO_L, RHO_G)
198 if vof_mom_muscl:
199 s.diagnostics.set_vof_momentum_muscl(True)
200 else:
201 s.enable_vof_blocks([(0.5 * L / h, 0.5 * L / h, 0.5 * L / h, 0.5 * D / h)])
202 s.enable_vof_block_csf()
203 alpha = float(np.mean(dist.gather(s.get_vof()))) # discrete gas fraction (exactly conserved)
204 rho_av = RHO_L + (RHO_G - RHO_L) * alpha
205 s.set_property_model("force_x", "linear", "C",
206 [-(RHO_L - rho_av) * G, -(RHO_G - RHO_L) * G])
207 s.set_superficial_velocity(True, "x", 0.0)
208 s.update_properties() # so the first capillary_dt sees rho(C)
209 return s, h, alpha
210
211
212def sample(s, h, x_prev, t_prev, t, dist, with_blocks=True):
213 C = dist.gather(s.get_vof())
214 u, v, w = dist.gather(s.get_u()), dist.gather(s.get_v()), dist.gather(s.get_w())
215 # staggered: get_u()[i] is the face between cells i-1 and i (suite CONVENTIONS: u at
216 # (i, j+1/2, k+1/2)); the cell-centre value of cell i averages faces i and i+1 (periodic)
217 uc = 0.5 * (u + np.roll(u, -1, axis=0))
218 rho = RHO_L + (RHO_G - RHO_L) * C
219 vg = C.sum()
220 ub_abs = float((C * uc).sum() / vg) # <u_x>_d, computational frame
221 u_mix = float(uc.mean()) # <u_x> (held 0)
222 u_liq = float(((1.0 - C) * uc).sum() / (1.0 - C).sum()) # <u_x>_l
223 u_zm = float((rho * uc).sum() / rho.sum()) # mass-mean (zero-momentum frame)
224 # gas centroid along x, unwrapped: minimal image about the previous (continuous) position
225 n = C.shape[0]
226 L = n * h
227 dxi = (np.arange(n) + 0.5) * h - x_prev
228 dxi -= L * np.round(dxi / L)
229 x = x_prev + float((C.sum(axis=(1, 2)) * dxi).sum() / vg)
230 u_cent = (x - x_prev) / (t - t_prev) if t > t_prev else float("nan")
231 blocks = s.diagnostics.vof_block_stats() if with_blocks else [] # none under --single-vof
232 if dist.comm is not None: # each block's stats live on its master rank
233 blocks = [b for lst in dist.comm.allgather(blocks) for b in lst]
234 return {
235 "u_abs": ub_abs, "u_mix": u_mix, "u_liq": u_liq, "u_zm": u_zm,
236 "u_drift": ub_abs - u_mix, "u_slip": ub_abs - u_liq, "u_rel_zm": ub_abs - u_zm,
237 "u_cent": u_cent, "v_mean": float(v.mean()), "w_mean": float(w.mean()),
238 "gas_vol": float(vg) * h ** 3,
239 "block_vol": float(blocks[0]["volume"]) if blocks else float("nan"), "x_cent": x}
240
241
242def main():
243 a = parse()
244 space = check_backend(a.backend)
245 n = round(L_OVER_D * a.d_over_h)
246 comm = None
247 if a.mpi:
248 from mpi4py import MPI
249
250 comm = MPI.COMM_WORLD if MPI.COMM_WORLD.Get_size() > 1 else None
251 dist = Dist(n, comm)
252 root = comm is None or comm.Get_rank() == 0
253 nranks = 1 if comm is None else comm.Get_size()
254 if root:
255 os.makedirs(a.out, exist_ok=True)
256 t0 = time.perf_counter()
257 if a.vof_momentum and a.rho_ratio != RHO_RATIO:
258 sys.exit("--rho-ratio is refused with --vof-momentum")
259 if a.vof_mom_muscl and not a.vof_momentum:
260 sys.exit("--vof-mom-muscl needs --vof-momentum")
261 s, h, alpha = build(n, a.mu_ratio * MU_L, a.face_mu, a.viscous_stress, a.single_vof,
262 a.vof_momentum, dist, a.advection, a.rho_ratio * RHO_L, a.vof_mom_muscl)
263 t_setup = time.perf_counter() - t0
264 re_of = lambda U: RHO_L * U * D / MU_L
265 cols = ["t", "t_star", "step", "dt", "binding", "u_abs", "u_mix", "u_liq", "u_zm", "u_drift",
266 "u_slip", "u_rel_zm", "u_cent", "Re_drift", "Re_abs", "Re_slip", "Re_rel_zm",
267 "v_mean", "w_mean", "gas_vol", "vol_err", "block_vol", "x_cent", "a_closure_g"]
268 f = open(os.path.join(a.out, "case_a.csv") if root else os.devnull, "w") # noqa: SIM115
269 f.write(f"# case A d/h={a.d_over_h} n={n} L={L_OVER_D * D} d={D} rho_l={RHO_L} "
270 f"rho_g={RHO_G} rho_g_inertial={a.rho_ratio * RHO_L} mu_l={MU_L:.6e} mu_g={a.mu_ratio * MU_L:.6e} sigma={SIGMA:.6e} g={G} "
271 f"alpha={alpha:.6f} space={space} t_ref={T_REF:.6e} dt_safety={a.dt_safety} "
272 f"face_mu={a.face_mu} viscous_stress={a.viscous_stress or 'default'} single_vof={a.single_vof} "
273 f"vof_momentum={a.vof_momentum} vof_mom_muscl={a.vof_mom_muscl} advection={a.advection}" + (f" np={nranks}" if comm is not None else "") + "\n")
274 f.write(",".join(cols) + "\n")
275
276 t, step, binding, dt = 0.0, 0, "-", 0.0
277 with_blocks = not (a.single_vof or a.vof_momentum)
278 r0 = sample(s, h, 0.5 * L_OVER_D * D, 0.0, 0.0, dist, with_blocks)
279 vol0 = r0["gas_vol"]
280 x_prev, t_prev = r0["x_cent"], 0.0
281 t_end = a.t_end * T_REF
282 next_out = a.dt_out * T_REF
283 last = None
284 hist = [] # (t_star, Re_drift, Re_rel_zm, x_cent, a_closure_g)
285 t_loop = time.perf_counter()
286 stop = "t_end"
287 while t < t_end * (1 - 1e-12):
288 L_ = s.vof_step_limits()
289 dt = a.dt_safety * min(L_["cfl_dt"], L_["capillary_dt"])
290 binding = "cap" if L_["capillary_dt"] < L_["cfl_dt"] else "cfl"
291 s.set_dt(dt)
292 s.step()
293 t += dt
294 step += 1
295 done = t >= t_end * (1 - 1e-12)
296 if a.max_steps is not None and step >= a.max_steps:
297 done, stop = True, "max_steps"
298 if dist.any(time.perf_counter() - t0 > a.wall):
299 done, stop = True, "wall"
300 if t >= next_out or done:
301 r = sample(s, h, x_prev, t_prev, t, dist, with_blocks)
302 x_prev, t_prev = r["x_cent"], t
303 r.update(t=t, t_star=t / T_REF, step=step, dt=dt, binding=binding,
304 Re_drift=re_of(r["u_drift"]), Re_abs=re_of(r["u_abs"]),
305 Re_slip=re_of(r["u_slip"]), Re_rel_zm=re_of(r["u_rel_zm"]),
306 vol_err=r["gas_vol"] / vol0 - 1.0,
307 a_closure_g=s.diagnostics.last_superficial_velocity_shift() / dt / G)
308 f.write(",".join(str(r[c]) for c in cols) + "\n")
309 f.flush()
310 hist.append((r["t_star"], r["Re_drift"], r["Re_rel_zm"], r["x_cent"], r["a_closure_g"]))
311 last = r
312 while next_out <= t:
313 next_out += a.dt_out * T_REF
314 if done:
315 break
316 wall_loop = time.perf_counter() - t_loop
317 f.close()
318 if a.dump:
319 flds = {k: dist.gather(g()) for k, g in
320 (("u", s.get_u), ("v", s.get_v), ("w", s.get_w), ("p", s.get_p), ("C", s.get_vof))}
321 if root:
322 np.savez(a.dump, step=step, t=t, **flds)
323
324 # Steady state. Re(t) carries a component periodic in the bubble's position in the box (period
325 # L/U, measured at d/h 10), so the averaging windows are whole box crossings: A = the last two
326 # crossings (gas displacement 2L), B = the two before. steady <=> |<Re>_A - <Re>_B| < 1e-3 <Re>_A.
327 H = np.array(hist)
328 Lb = L_OVER_D * D
329
330 def window_mean(col, x_hi, x_lo):
331 m = (H[:, 3] > x_lo) & (H[:, 3] <= x_hi)
332 if m.sum() < 2:
333 return float("nan")
334 return float(np.trapezoid(H[m, col], H[m, 0]) / (H[m, 0][-1] - H[m, 0][0]))
335
336 xe = H[-1, 3]
337 re_a = window_mean(1, xe, xe - 2 * Lb) if xe - H[0, 3] >= 2 * Lb else float("nan")
338 re_b = window_mean(1, xe - 2 * Lb, xe - 4 * Lb) if xe - H[0, 3] >= 4 * Lb else float("nan")
339 zm_a = window_mean(2, xe, xe - 2 * Lb) if xe - H[0, 3] >= 2 * Lb else float("nan")
340 acc_a = window_mean(4, xe, xe - 2 * Lb) if xe - H[0, 3] >= 2 * Lb else float("nan")
341 wa = (H[:, 3] > xe - 2 * Lb)
342 re_lo, re_hi = float(H[wa, 1].min()), float(H[wa, 1].max())
343 drel = abs(re_a - re_b) / abs(re_a)
344 steady = bool(drel < 1e-3)
345 rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024.0
346 line = (f"CASE_A d/h={a.d_over_h} n={n} mu_ratio={a.mu_ratio:g} rho_ratio={a.rho_ratio:g} face_mu={a.face_mu} "
347 f"stress={a.viscous_stress or 'default'} adv={'on' if a.advection else 'off'} vof={('mom+muscl' if a.vof_mom_muscl else 'mom') if a.vof_momentum else ('single' if a.single_vof else 'blocks')} "
348 f"dt_safety={a.dt_safety:g} space={space} stop={stop} t*={last['t_star']:.3f} "
349 f"steps={step} Re_drift(2L-mean)={re_a:.4f} [min {re_lo:.3f} max {re_hi:.3f}] "
350 f"Re_rel_zm(2L-mean)={zm_a:.4f} dRe/Re(2L vs prev 2L)={drel:.2e} steady={steady} "
351 f"vol_err={last['vol_err']:.2e} <u>={last['u_mix']:.1e} <v>={last['v_mean']:.1e} "
352 f"<w>={last['w_mean']:.1e} u_cent/u_abs={last['u_cent'] / last['u_abs']:.4f} "
353 f"setup={t_setup:.1f}s ms/step={1e3 * wall_loop / max(step, 1):.2f} "
354 f"maxrss={rss:.0f}MB a_closure/g(2L-mean)={acc_a:.4e}"
355 + (f" np={nranks}" if comm is not None else ""))
356 if root:
357 with open(os.path.join(a.out, "summary.txt"), "w") as g:
358 g.write(line + "\n")
359 print(line)
360
361
362if __name__ == "__main__":
363 main()
gather(self, a)
any(self, flag)
__init__(self, n, comm=None)
check_backend(want)
sample(s, h, x_prev, t_prev, t, dist, with_blocks=True)
sphere_fractions(n, c, r, sub=8)
build(n, mu_g=MU_G, face_mu="arithmetic", stress=None, single=False, vof_mom=False, dist=None, advection=True, rho_g_in=RHO_G, vof_mom_muscl=False)
static std::vector< double > slice(const std::vector< double > &g, int ox, int oy, int oz, int lnx, int lny, int lnz)
static double mean(const std::vector< double > &a)