flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
vof_open_boundaries.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""VoF rung V-BC (WO-R) — two-phase open boundaries: the physics battery.
3
4The *algebraic* gates of this rung (the out-of-domain mask, the bitwise inertness of the boundary
5flux rule, the backflow rule, the inflow property ghost, the variable-density outflow correction
6and the exact colour budget under a prescribed divergence-free field) live in
7`tests/kokkos/test_vof_bc.cpp` and run in the `vof_bc` ctest. What is here is the part that needs a
8COUPLED solve and a number somebody else published:
9
10 budget WO-R gate G1, COUPLED: the same slug injection driven by step(), so the advecting
11 field is the projection's own output and the budget's floor is the projection's
12 divergence residual rather than zero. Records the pressure iteration count.
13 nusselt WO-R gate G2: a falling liquid film fed by a prescribed Nusselt inlet profile,
14 against the analytical flow rate. Run at density ratio 100 (V2a regime) and at
15 1000 with momentum consistency. This is the gate on the 1/rho_f outflow
16 correction: `--no-outflow-rho` restores the pre-WO-R correction and the
17 script reports BOTH columns.
18 pool WO-R gate G3: gas blown over a resting liquid pool at ratio 1000. Gates the pool's
19 volume, the velocity it is allowed to pick up, and the inflow ghost DENSITY.
20
21Units: cell size 1, time in seconds, exactly as `vof_surface_tension.py`; the cases here are
22stated directly in solver units because the reference (Nusselt) is a similarity solution and only
23the dimensionless groups matter.
24
25EVERY gate that reports a functional records the max pressure-iteration count against its cap and
26marks a capped run INVALID rather than merely flagging it (shared preamble rule 3b).
27
28Usage: PYTHONPATH=<build> python tests/study/vof_open_boundaries.py [gate ...] [--quick]
29"""
30import os
31import sys
32import time
33
34import numpy as np
35
36import peclet.flow as pf
37
38QUICK = "--quick" in sys.argv
39GATES = [a for a in sys.argv[1:] if not a.startswith("--")]
40
41
42class Solve:
43 """A run's solver health, per the shared preamble's rule 3b."""
44
45 def __init__(self, cap):
46 self.cap = cap
47 self.iters = 0
48 self.div = 0.0
49
50 def sample(self, s):
51 self.iters = max(self.iters, s.diagnostics.last_pressure_iterations())
52 # max_open_divergence() RE-IMPOSES the zero-gradient outflow face before measuring, which
53 # both destroys bcCorrectOutflow's correction (so calling it once per step changes the run)
54 # and reports a field the solver never used. On an open boundary use the projected sibling.
55 self.div = max(self.div, s.max_open_divergence_projected())
56
57 @property
58 def valid(self):
59 return self.iters < self.cap
60
61 def __str__(self):
62 return (f"pressure {self.iters}/{self.cap} "
63 f"{'OK' if self.valid else '*** CAPPED -> RUN INVALID ***'}, "
64 f"max|div(open u)| {self.div:.2e}")
65
66
67def to_host(view):
68 """`field_view` returns the PADDED buffer — NumPy on a host build, DLPack on a device one."""
69 try:
70 a = np.asarray(view)
71 if a.ndim == 3:
72 return a
73 except Exception:
74 pass
75 import cupy as cp
76 return cp.asnumpy(cp.from_dlpack(view))
77
78
79def maxvel(s):
80 return max(np.abs(s.get_u()).max(), np.abs(s.get_v()).max(), np.abs(s.get_w()).max())
81
82
83# --------------------------------------------------------------------------- G1 coupled budget
85 print("\n" + "=" * 96)
86 print("G1 COLOUR BUDGET, COUPLED (WO-R gate G1 driven by step(), not by a prescribed field)")
87 print("=" * 96)
88 print(" A liquid slug is injected through a uniform -z inlet and flushed out of the +z")
89 print(" outlet, with the full momentum + projection step in between. The gate is")
90 print(" sum(C)(t) - integral(inflow liquid) + integral(outflow liquid) = const,")
91 print(" the fluxes being the ADVECTOR's own boundary face fluxes (vof_bc_volumes). Unlike the")
92 print(" kinematic ctest twin, the advecting field here is the projection's output, so the")
93 print(" floor is the projection's discrete divergence residual (WO-J finding 3).\n")
94 nx = ny = 32 if not QUICK else 16
95 nz = 64 if not QUICK else 32
96 nslug, nafter = (60, 740) if not QUICK else (20, 120)
97 W, dt = 0.5, 0.2
98 s = pf.Solver(nx, ny, nz)
99 s.set_rho(1.0)
100 s.set_mu(0.5)
101 s.set_dt(dt)
102 s.set_advection(False)
103 for f in ("-x", "+x", "-y", "+y"):
104 s.set_domain_bc(f, "wall", (0, 0, 0))
105 s.set_domain_bc("-z", "inflow", (0.0, 0.0, W))
106 s.set_domain_bc("+z", "outflow", (0, 0, 0))
107 # the open-boundary duct settings the validated channel case uses
108 # (scripts/verify_channel_sdflow.py): a deep semi-coarsening hierarchy, enough momentum
109 # sweeps, and the all-fluid SDF far from every cell. With the defaults this configuration
110 # diverges — see the findings entry.
111 s.diagnostics.set_velocity_solver_params(60)
112 s.set_pressure_multigrid(True, levels=8)
113 s.set_pressure_solver_params(80)
114 s.set_pressure_geometry(np.full((nx, ny, nz), 1e30, order="F"))
115 s.set_pressure_chebyshev(True, 400, 1e-12)
116 s.enable_vof()
117 s.set_vof(np.zeros((nx, ny, nz), order="F"))
118 s.set_vof_inflow("-z", 1.0)
119 s.set_vof_backflow("+z", 0.0)
120 h = Solve(400)
121 ledger, budget0, drift = 0.0, None, 0.0
122 cmin, cmax = 1.0, 0.0
123 t0 = time.time()
124 for i in range(nslug + nafter):
125 if i == nslug:
126 s.set_vof_inflow("-z", 0.0)
127 s.step()
128 h.sample(s)
129 d = s.diagnostics.vof_diagnostics()
130 ledger += sum(s.vof_bc_volumes())
131 b = d["sum"] - ledger
132 if budget0 is None:
133 budget0 = b
134 drift = max(drift, abs(b - budget0))
135 cmin, cmax = min(cmin, d["min"]), max(cmax, d["max"])
136 tot = s.vof_bc_volumes_total()
137 injected, left = tot[4], -tot[5]
138 d = s.diagnostics.vof_diagnostics()
139 print(f" injected {injected:.10g}, left {left:.10g}, remaining sum(C) {d['sum']:.3e}")
140 print(f" |budget drift| {drift:.3e} (relative to the injected volume {drift/injected:.3e})")
141 print(f" C in [{cmin:.3e}, {cmax:.17g}]")
142 print(f" {h} ({time.time()-t0:.0f} s)")
143 ok = (drift / injected < 1e-10) and h.valid and cmin > -1e-12 and cmax < 1 + 1e-12
144 print(f" GATE: {'PASS' if ok else 'FAIL'} (budget <= 1e-10 relative, C bounded, no cap)")
145 return ok
146
147
148# ------------------------------------------------------------------------ G2 Nusselt falling film
149# Both legs keep rho_l = 100, mu_l = 50, delta = 8 and the SAME film Reynolds number 5 and the
150# same Nusselt flow rate Q: only the gas is made lighter and the body force is rescaled by
151# 99/drho, so the two rows differ in the density RATIO and in nothing else. dt is set by the WY
152# Courant cap on the film's own velocity (the same u_max in both rows) with margin for the gas.
153NUSSELT = {
154 100: dict(rho_l=100.0, rho_g=1.0, mu_l=50.0, mu_g=1.0, dt=0.5, mom=True, cap=400),
155 1000: dict(rho_l=100.0, rho_g=0.1, mu_l=50.0, mu_g=1.0, dt=0.25, mom=True, cap=2000),
156}
157
158
159def gate_nusselt(ratio=100, steps=None, outflow_rho=True):
160 p = NUSSELT[ratio]
161 nx, ny, nz = 32, 4, 64
162 delta = 8.0
163 drho = p["rho_l"] - p["rho_g"]
164 p = dict(p, g=4.93e-3 * 99.0 / drho)
165 umax = drho * p["g"] * delta ** 2 / (2 * p["mu_l"])
166 Q = drho * p["g"] * delta ** 3 / (3 * p["mu_l"]) # flow rate per unit width, cells^2/s
167 Re = p["rho_l"] * umax * delta / p["mu_l"]
168 steps = steps or (900 if QUICK else 2400)
169 print("\n" + "=" * 96)
170 print(f"G2 NUSSELT FALLING FILM, density ratio {ratio}, mu ratio {p['mu_l']/p['mu_g']:.0f}"
171 f"{'' if outflow_rho else ' [ABLATION: --no-outflow-rho]'}")
172 print("=" * 96)
173 print(" A liquid film of thickness delta = 8 cells runs down the -x wall of a quasi-2D duct,")
174 print(" fed at the +z inlet with the exact Nusselt profile and leaving through the -z outlet.")
175 print(" The body force is the REDUCED gravity -(rho_l - rho_g) g C: the gas is then exactly")
176 print(" force-free and hydrostatic, which is what the Nusselt similarity solution assumes")
177 print(" (with gravity on the gas too, the Dirichlet p=0 outlet would accelerate the gas")
178 print(" column instead of supporting it — a different problem).")
179 print(f" u_max {umax:.5g} cells/s, Q {Q:.5g} cells^2/s, film Reynolds {Re:.2f}\n")
180 s = pf.Solver(nx, ny, nz)
181 s.set_rho(p["rho_l"])
182 s.set_mu(p["mu_l"])
183 s.set_dt(p["dt"])
184 s.set_advection(False)
185 s.set_domain_bc("-x", "wall", (0, 0, 0))
186 s.set_domain_bc("+x", "wall", (0, 0, 0)) # walls +-x (the film wall and the far wall)
187 s.set_domain_bc("-z", "outflow", (0, 0, 0)) # outflow at the BOTTOM
188 # inlet velocity profile on face 5 (+z): axes (b, c) = (x, y)
189 xc = np.arange(nx) + 0.5
190 wprof = np.where(xc < delta, -(drho * p["g"] / p["mu_l"]) * (delta * xc - 0.5 * xc ** 2), 0.0)
191 prof = np.zeros((nx, ny, 3))
192 prof[:, :, 2] = wprof[:, None]
193 s.set_domain_bc_profile("+z", np.ascontiguousarray(prof))
194 # the open-boundary duct settings the validated channel case uses
195 # (scripts/verify_channel_sdflow.py): a deep semi-coarsening hierarchy, enough momentum
196 # sweeps, and the all-fluid SDF far from every cell. With the defaults this configuration
197 # diverges — see the findings entry.
198 s.diagnostics.set_velocity_solver_params(60)
199 s.set_pressure_multigrid(True, levels=8)
200 s.set_pressure_solver_params(80)
201 s.set_pressure_geometry(np.full((nx, ny, nz), 1e30, order="F"))
202 s.enable_vof()
203 # the initial state IS the developed film, so the run only has to hold it
204 C = np.zeros((nx, ny, nz), order="F")
205 frac = np.clip(delta - np.arange(nx), 0.0, 1.0) # exact fractions of the x < delta slab
206 C[:, :, :] = frac[:, None, None]
207 s.set_vof(np.asfortranarray(C))
208 s.set_property_model("rho", "linear", "C", [p["rho_g"], p["rho_l"] - p["rho_g"]])
209 s.set_property_model("mu", "linear", "C", [p["mu_g"], p["mu_l"] - p["mu_g"]])
210 s.set_property_model("force_z", "linear", "C", [0.0, -drho * p["g"]])
211 if p["mom"]:
212 s.enable_vof_momentum(p["rho_g"], p["rho_l"])
213 # THE DRIVER IS SELECTED LAST, AND IT IS FCG. Two measured reasons, both recorded in the
214 # findings: (i) `set_property_model("rho", ...)` fires `set_density_mode`, which reselects
215 # Chebyshev — a driver chosen BEFORE the closure is silently discarded (this is the WO-H
216 # "capped at 120" tell, alive and well); (ii) on this configuration Chebyshev DIVERGES (the
217 # film accelerates until the WY cap throws) and MG-PCG burns any cap, while FCG converges.
218 s.set_pressure_fcg(True, p["cap"], 1e-11)
219 # the inlet carries the same film: colour profile 1 in the film, 0 in the gas
220 s.set_vof_inflow_profile("+z", np.ascontiguousarray(np.repeat(frac[:, None], ny, axis=1)))
221 s.set_vof_backflow("-z", 0.0)
222 # seed the interior with the analytical velocity so the transient is short
223 w0 = np.zeros((nx, ny, nz), order="F")
224 w0[:, :, :] = wprof[:, None, None]
225 s.set_field("w", np.asfortranarray(w0))
226
227 h = Solve(p["cap"])
228 hist = []
229 t0 = time.time()
230 # ADAPTIVE dt, re-picked every 20 steps from the solver's own interface-local Weymouth-Yue
231 # limit — the same pattern `vof_surface_tension.py::gate_hysing` uses, and necessary rather
232 # than cosmetic: the film's free surface speeds up as it develops and a fixed dt sized on the
233 # ANALYTICAL u_max trips the WY boundedness cap part-way through the run.
234 dt = p["dt"]
235 ncap = 0
236 for i in range(steps):
237 if i % 20 == 0:
238 L = s.vof_step_limits()
239 dt = min(p["dt"], 0.4 * L["cfl_dt"]) if L["cfl_dt"] > 0 else p["dt"]
240 s.set_dt(dt)
241 ncap += int(dt < p["dt"])
242 s.step()
243 h.sample(s)
244 hist.append(s.diagnostics.vof_diagnostics()["sum"])
245 C = s.get_vof()
246 w = s.get_w()
247 zmid = nz // 2
248 dmeas = float(C[:, :, zmid].sum() / ny)
249 qmeas = float(-(C[:, :, zmid] * w[:, :, zmid]).sum() / ny)
250 tail = np.array(hist[-200:])
251 steady = float(np.abs(tail - tail.mean()).max() / max(tail.mean(), 1e-300))
252 print(f" at z = nz/2: film thickness {dmeas:.4f} cells (target {delta}) "
253 f"[error {dmeas-delta:+.4f}]")
254 print(f" flow rate {qmeas:.6g} (Nusselt {Q:.6g}) "
255 f"[{100*(qmeas/Q-1):+.2f} %]")
256 print(f" sum(C) steadiness over the last 200 steps: {steady:.3e} relative")
257 print(f" dt: nominal {p['dt']}, throttled by the WY cap on {ncap} of the "
258 f"{(steps + 19)//20} re-picks; final {dt:.4g}")
259 print(f" {h} ({time.time()-t0:.0f} s)")
260 ok = (abs(qmeas / Q - 1) < 0.03 and abs(dmeas - delta) < 0.5 and steady < 1e-4 and h.valid)
261 print(f" GATE: {'PASS' if ok else 'FAIL'} (Q within 3 %, delta within 0.5 cell, "
262 f"sum(C) steady to 1e-4, no cap)")
263 return ok, qmeas / Q - 1, dmeas - delta, steady, h.iters
264
265
266# ------------------------------------------------------------------------- G3 gas over a pool
268 print("\n" + "=" * 96)
269 print("G3 GAS OVER A RESTING POOL, density ratio 1000, momentum-consistent transport")
270 print("=" * 96)
271 print(" Gas enters at -x above a liquid pool that fills the lower half, and leaves at +x. The")
272 print(" pool must not move and must not lose volume, and the inflow ghost DENSITY must be the")
273 print(" INLET fluid's — gas above the pool, liquid at the pool's own inlet plane.")
274 print("")
275 print(" NOTE ON THE GATE AS WRITTEN. WO-R asks for the ghost density 'through get_field(rho)")
276 print(" on the first inner plane'. That measures the wrong quantity: get_field returns the")
277 print(" INNER cells, whose rho is rho(C_inner) whatever the ghost policy does. The ghost is")
278 print(" what the inlet FACE density is built from, and it is reachable only through")
279 print(" field_view('rho'), which returns the padded buffer. That is what is gated below.\n")
280 nx = 64 if not QUICK else 32
281 ny = 4
282 nz = 32 if not QUICK else 16
283 steps = 500 if not QUICK else 150
284 rho_l, rho_g = 1000.0, 1.0
285 mu_l, mu_g = 10.0, 0.1
286 U = 0.4
287 s = pf.Solver(nx, ny, nz)
288 s.set_rho(rho_l)
289 s.set_mu(mu_l)
290 s.set_dt(0.2)
291 s.set_advection(False)
292 s.set_domain_bc("-z", "wall", (0, 0, 0))
293 s.set_domain_bc("+z", "wall", (0, 0, 0)) # walls +-z (the pool floor and the lid)
294 s.set_domain_bc("+x", "outflow", (0, 0, 0)) # outflow at +x
295 # inflow at -x: gas only above the pool. Face 0 -> (b, c) = (y, z).
296 zc = np.arange(nz) + 0.5
297 gas = zc >= nz / 2
298 prof = np.zeros((ny, nz, 3))
299 prof[:, :, 0] = np.where(gas, U, 0.0)[None, :]
300 s.set_domain_bc_profile("-x", np.ascontiguousarray(prof))
301 # the open-boundary duct settings the validated channel case uses
302 # (scripts/verify_channel_sdflow.py): a deep semi-coarsening hierarchy, enough momentum
303 # sweeps, and the all-fluid SDF far from every cell. With the defaults this configuration
304 # diverges — see the findings entry.
305 s.diagnostics.set_velocity_solver_params(60)
306 s.set_pressure_multigrid(True, levels=8)
307 s.set_pressure_solver_params(80)
308 s.set_pressure_geometry(np.full((nx, ny, nz), 1e30, order="F"))
309 s.enable_vof()
310 C = np.zeros((nx, ny, nz), order="F")
311 C[:, :, : nz // 2] = 1.0
312 s.set_vof(np.asfortranarray(C))
313 s.set_property_model("rho", "linear", "C", [rho_g, rho_l - rho_g])
314 s.set_property_model("mu", "linear", "C", [mu_g, mu_l - mu_g])
315 s.enable_vof_momentum(rho_g, rho_l)
316 s.set_pressure_fcg(True, 800, 1e-11) # driver LAST — see gate_nusselt
317 # the inlet colour is the pool's own: liquid below, gas above
318 cprof = np.where(gas, 0.0, 1.0)
319 s.set_vof_inflow_profile("-x", np.ascontiguousarray(np.repeat(cprof[None, :], ny, axis=0)))
320 s.set_vof_backflow("+x", 0.0)
321
322 h = Solve(800)
323 v0 = s.diagnostics.vof_diagnostics()["sum"]
324 t0 = time.time()
325 for _ in range(steps):
326 s.step()
327 h.sample(s)
328 v1 = s.diagnostics.vof_diagnostics()["sum"]
329 C = s.get_vof()
330 u, v, w = s.get_u(), s.get_v(), s.get_w()
331 liq = C > 0.999
332 umax_liq = float(np.max([np.abs(f[liq]).max() for f in (u, v, w)]))
333 rho = to_host(s.diagnostics.field_view("rho"))
334 G = (rho.shape[0] - nx) // 2
335 ghost = rho[G - 1, G + ny // 2, :] # the -x inflow ghost column
336 gh_gas = float(np.mean(ghost[G + nz // 2: G + nz]))
337 gh_liq = float(np.mean(ghost[G: G + nz // 2]))
338 print(f" pool volume {v0:.10g} -> {v1:.10g} (relative change {abs(v1-v0)/v0:.3e})")
339 print(f" max|u| in the liquid {umax_liq:.4e} ({umax_liq/U:.3e} of the gas inlet speed)")
340 print(f" inflow ghost rho: {gh_gas:.6g} above the pool (want {rho_g}), "
341 f"{gh_liq:.6g} at the pool (want {rho_l})")
342 print(f" {h} ({time.time()-t0:.0f} s)")
343 ok = (abs(v1 - v0) / v0 < 1e-10 and umax_liq / U < 1e-3 and h.valid
344 and abs(gh_gas - rho_g) < 1e-9 * rho_l and abs(gh_liq - rho_l) < 1e-9 * rho_l)
345 print(f" GATE: {'PASS' if ok else 'FAIL'}")
346 return ok
347
348
349if __name__ == "__main__":
350 todo = GATES or ["budget", "nusselt", "pool"]
351 results = {}
352 if "budget" in todo:
353 results["budget"] = gate_budget()
354 if "nusselt" in todo:
355 ablation = "--no-outflow-rho" in sys.argv
356 rows = []
357 for r in (100, 1000):
358 ok, dq, dd, st, it = gate_nusselt(r, outflow_rho=not ablation)
359 results[f"nusselt{r}"] = ok
360 rows.append((r, dq, dd, st, it))
361 print("\n ratio dQ/Q d(delta) sum(C) steadiness pressure iters"
362 f" [1/rho_f outflow correction: {'OFF (ablation)' if ablation else 'ON'}]")
363 for r, dq, dd, st, it in rows:
364 print(f" {r:5d} {100*dq:+7.2f} % {dd:+8.4f} {st:.3e} {it}")
365 if "pool" in todo:
366 results["pool"] = gate_pool()
367 print("\n" + "=" * 96)
368 for k, v in results.items():
369 print(f" {k:12s} {'PASS' if v else 'FAIL'}")
370 sys.exit(0 if all(results.values()) else 1)
gate_nusselt(ratio=100, steps=None, outflow_rho=True)