flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
vof_issues_sweep.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""Gates for the ISSUES sweep (the solver-side entries examples/*/ISSUES.md logged).
3
4One sub-command per ISSUES entry; every one prints its measured numbers and a PASS/FAIL line.
5
6 PYTHONPATH=$PWD/build_cuda python tests/study/vof_issues_sweep.py atomic
7 PYTHONPATH=$PWD/build_cuda python tests/study/vof_issues_sweep.py adaptive
8 PYTHONPATH=$PWD/build_cuda python tests/study/vof_issues_sweep.py geometry
9 PYTHONPATH=$PWD/build_cuda python tests/study/vof_issues_sweep.py collocated
10 PYTHONPATH=$PWD/build_cuda python tests/study/vof_issues_sweep.py freeslip
11 PYTHONPATH=$PWD/build_cuda python tests/study/vof_issues_sweep.py wetwall
12"""
13import argparse
14import math
15import sys
16
17import numpy as np
18
19import peclet.flow as pf
20
21FAIL = []
22
23
24def check(name, ok, detail=""):
25 print(f" [{'PASS' if ok else 'FAIL'}] {name} {detail}")
26 if not ok:
27 FAIL.append(name)
28
29
30def state(s):
31 return dict(u=s.get_u().copy(), v=s.get_v().copy(), w=s.get_w().copy(),
32 C=s.get_vof().copy(), p=np.asarray(s.get_p()).copy())
33
34
35def same(a, b):
36 return all(np.array_equal(a[k], b[k]) for k in a)
37
38
39def diffs(a, b):
40 return {k: float(np.abs(a[k] - b[k]).max()) for k in a}
41
42
43# ------------------------------------------------------------------ item 1: step() atomicity
44def scene_cfl(n=16):
45 """The ISSUES reproducer: a half-filled box, uniform u = 1, body force in z."""
46 s = pf.Solver(n, n, n)
47 s.set_rho(1.0)
48 s.set_mu(0.01)
49 s.set_dt(0.1)
50 s.set_advection(False)
51 s.set_pressure_geometry(np.full((n, n, n), 1e30, order="F"))
52 s.set_body_force((0.0, 0.0, 1e-3))
53 s.enable_vof()
54 C = np.zeros((n, n, n), order="F")
55 C[:, :, : n // 2] = 1.0
56 s.set_vof(C)
57 u = np.zeros((n, n, n), order="F")
58 u[:] = 1.0
59 s.set_field("u", u)
60 for _ in range(3):
61 s.step()
62 return s
63
64
66 print("ISSUES item 1 -- step() atomic across the Weymouth-Yue boundedness throw")
67 s = scene_cfl()
68 s0 = state(s)
69 s.set_dt(0.4) # CFL 0.4 > the 0.25 cap
70 threw = ""
71 try:
72 s.step()
73 except RuntimeError as e:
74 threw = str(e).split("\n")[0]
75 print(f" WY throw: {threw[:110]}")
76 d = diffs(s0, state(s))
77 check("WY: step() threw", bool(threw), threw[:60])
78 check("WY: state bitwise unchanged", same(s0, state(s)), str(d))
79 # retry at the old dt must run
80 s.set_dt(0.1)
81 s.step()
82 check("WY: retry at a smaller dt runs", True)
83
84 # --- the capillary cap
85 n = 16
86 s = pf.Solver(n, n, n)
87 s.set_rho(1.0)
88 s.set_mu(0.05)
89 s.set_advection(False)
90 s.set_pressure_geometry(np.full((n, n, n), 1e30, order="F"))
91 s.set_body_force((0.0, 0.0, 1e-3))
92 s.enable_vof()
93 x, y, z = np.meshgrid(*[np.arange(n) + 0.5] * 3, indexing="ij")
94 r = np.sqrt((x - n / 2) ** 2 + (y - n / 2) ** 2 + (z - n / 2) ** 2)
95 s.set_vof(np.asfortranarray(np.clip(4.0 - r, 0.0, 1.0)))
96 s.set_surface_tension(1.0)
97 s.set_dt(0.2 * s.capillary_dt())
98 for _ in range(3):
99 s.step()
100 s0 = state(s)
101 s.set_dt(10.0 * s.capillary_dt())
102 threw = ""
103 try:
104 s.step()
105 except RuntimeError as e:
106 threw = str(e).split("\n")[0]
107 print(f" capillary throw: {threw[:110]}")
108 d = diffs(s0, state(s))
109 check("sigma: step() threw", bool(threw), threw[:60])
110 check("sigma: state bitwise unchanged", same(s0, state(s)), str(d))
111
112
113# ------------------------------------------------------------------ item 2: step_adaptive
114def scene_hysing(nx=32, nz=64, sigma=0.02):
115 s = pf.Solver(nx, 4, nz)
116 s.set_rho(1.0)
117 s.set_mu(0.01)
118 s.set_advection(False) # the pre-flip default (Stokes) kept; NS physics: CHANGELOG "advection default"
119 s.set_domain_bc("-z", "wall"); s.set_domain_bc("+z", "wall")
120 s.set_pressure_geometry(np.full((nx, 4, nz), 1e30, order="F"))
121 s.enable_vof()
122 x, y, z = np.meshgrid(np.arange(nx) + 0.5, np.arange(4) + 0.5,
123 np.arange(nz) + 0.5, indexing="ij")
124 r = np.sqrt((x - nx / 2) ** 2 + (z - nz / 4) ** 2)
125 C = np.asfortranarray(np.clip(0.5 + (r - 0.25 * nx / 2), 0.0, 1.0) * 0 + (r > 0.25 * nx).astype(float))
126 s.set_vof(C)
127 s.set_property_model("rho", "linear", "C", [1.0, 9.0])
128 s.set_property_model("mu", "linear", "C", [0.005, 0.045])
129 s.set_pressure_fcg(True, 600, 1e-10)
130 if sigma > 0:
131 s.set_surface_tension(sigma)
132 s.set_body_force((0.0, 0.0, -5e-2))
133 # A divergence-free x-shear in w (no z dependence, periodic in x, so the walls do not kill
134 # it) — this is what makes the interface-local CFL a REAL, binding limit on the sigma = 0
135 # configuration instead of an infinity.
136 ww = np.zeros((nx, 4, nz), order="F")
137 ww += (0.3 * np.sin(2 * np.pi * (np.arange(nx) + 0.5) / nx))[:, None, None]
138 s.set_field("w", ww)
139 s.set_dt(min(1.0, 0.4 * s.capillary_dt()))
140 return s
141
142
143def gate_adaptive(nsteps=200):
144 print("ISSUES item 2 -- step_adaptive reproduces the gallery driver bitwise")
145 # Two factor pairs so BOTH branches of the min() are exercised: (0.4, 0.4) is the gallery
146 # driver verbatim (capillary-bound on this scene) and (0.4, 4.0) loosens the capillary factor
147 # far enough that the interface-local CFL binds instead.
148 for cfl, cap, sig, dmax in ((0.4, 0.4, 0.02, math.inf), (0.2, 0.4, 0.0, 1.0)):
149 print(f" -- cfl_target = {cfl}, capillary_cfl = {cap}, sigma = {sig}, dt_max = {dmax}"
150 f" ({'capillary' if sig else 'CFL/dt_max'}-bound)")
151 one_adaptive(nsteps, cfl, cap, sig, dmax)
152
153
154def one_adaptive(nsteps, cflT, capT, sigma, dmax):
155 a = scene_hysing(sigma=sigma)
156 dts_a, ncap, ncfl = [], 0, 0
157 for _ in range(nsteps): # the hand-written gallery loop
158 L = a.vof_step_limits()
159 dt = min(cflT * L["cfl_dt"], capT * L["capillary_dt"], dmax)
160 a.set_dt(dt)
161 a.step()
162 dts_a.append(dt)
163 ncap += int(capT * L["capillary_dt"] <= min(cflT * L["cfl_dt"], dmax))
164 ncfl += int(cflT * L["cfl_dt"] < min(capT * L["capillary_dt"], dmax))
165 b = scene_hysing(sigma=sigma)
166 dts_b = [b.step_adaptive(cflT, capT, dmax) for _ in range(nsteps)]
167 d = diffs(state(a), state(b))
168 check(" dt sequence identical", dts_a == dts_b,
169 f"max|d dt| = {max(abs(x - y) for x, y in zip(dts_a, dts_b)):.3e}")
170 check(" state bitwise identical", same(state(a), state(b)), str(d))
171 print(f" {nsteps} steps, dt {dts_a[0]:.6g} -> {dts_a[-1]:.6g}, "
172 f"pressure {a.diagnostics.last_pressure_iterations()}/600, failed={a.diagnostics.pressure_solve_failed()}; "
173 f"capillary bound {ncap} steps, CFL bound {ncfl}; "
174 f"dt range [{min(dts_a):.6g}, {max(dts_a):.6g}]")
175
176
177# ------------------------------------------------------------------ item 4: vof_geometry
179 print("ISSUES item 4 -- vof_geometry() on an all-fluid VoF solver")
180 n = 32
181 s = pf.Solver(n, n, n)
182 s.set_rho(1.0); s.set_mu(0.1)
183 s.set_pressure_geometry(np.full((n, n, n), 10.0, order="F"))
184 s.enable_vof()
185 eps = np.asarray(s.diagnostics.vof_geometry(0))
186 kind = np.asarray(s.diagnostics.vof_geometry(4))
187 check("vof_has_geometry() is False", s.vof_has_geometry() is False)
188 check("eps == 1 everywhere", eps.shape == (n, n, n) and np.all(eps == 1.0),
189 f"min {eps.min()} max {eps.max()}")
190 check("openness == 1 everywhere",
191 all(np.all(np.asarray(s.diagnostics.vof_geometry(k)) == 1.0) for k in (1, 2, 3)))
192 check("classification == 0 everywhere", np.all(kind == 0.0))
193 # the E7 driver's dual use: one expression for both scenes
194 gas = np.asarray(s.diagnostics.vof_geometry(0)) * (1.0 - s.get_vof())
195 check("E7 dual-use expression runs", gas.shape == (n, n, n))
196
197
198# ------------------------------------------------------------------ item 5: collocated advect_vof
199def leveque(n, t=0.0, T=3.0):
200 """Cell-centre-sampled LeVeque deformation field (u, v, w) on an n^3 unit box."""
201 c = (np.arange(n) + 0.5) / n
202 X, Y, Z = np.meshgrid(c, c, c, indexing="ij")
203 f = math.cos(math.pi * t / T)
204 u = 2.0 * np.sin(np.pi * X) ** 2 * np.sin(2 * np.pi * Y) * np.sin(2 * np.pi * Z) * f
205 v = -np.sin(2 * np.pi * X) * np.sin(np.pi * Y) ** 2 * np.sin(2 * np.pi * Z) * f
206 w = -np.sin(2 * np.pi * X) * np.sin(2 * np.pi * Y) * np.sin(np.pi * Z) ** 2 * f
207 return (np.asfortranarray(u * n), np.asfortranarray(v * n), np.asfortranarray(w * n))
208
209
210def sphere_colour(n, cx=0.35, r=0.15):
211 c = (np.arange(n) + 0.5) / n
212 X, Y, Z = np.meshgrid(c, c, c, indexing="ij")
213 d = np.sqrt((X - cx) ** 2 + (Y - cx) ** 2 + (Z - cx) ** 2)
214 return np.asfortranarray(np.clip(0.5 + (r - d) * n, 0.0, 1.0))
215
216
218 print("ISSUES item 5 -- SolverColocated: set_state + advect_vof")
219 n = 32
220 s = pf.SolverColocated(n, n, n)
221 s.set_rho(1.0); s.set_mu(0.0)
222 s.set_pressure_geometry(np.full((n, n, n), 10.0, order="F"))
223 s.enable_vof()
224 C0 = sphere_colour(n)
225 s.set_vof(C0)
226 u, v, w = leveque(n)
227 s.set_state(u, v, w)
228 print(f" max|u| = {np.abs(u).max():.4g}, max|uf| after set_state = "
229 f"{np.abs(np.asarray(s.get_uf())).max():.4g}")
230 check("set_state seeds the face field", np.abs(np.asarray(s.get_uf())).max() > 1.0)
231 div = s.max_open_divergence_projected()
232 print(f" max|div(open uf)| of the seeded field = {div:.4g}")
233 dt = 0.2 / np.abs(np.asarray(s.get_uf())).max() # interface CFL well under the cap
234 for _ in range(10):
235 s.advect_vof(dt)
236 moved = float(np.abs(s.get_vof() - C0).max())
237 vol = float(s.get_vof().sum())
238 check("advect_vof no longer a silent no-op", moved > 0.0, f"max|C-C0| = {moved:.3e}")
239 # the reference: the SAME face field handed to a staggered solver (the E1 page's recipe)
240 r = pf.Solver(n, n, n)
241 r.set_rho(1.0); r.set_mu(0.0)
242 r.set_pressure_geometry(np.full((n, n, n), 10.0, order="F"))
243 r.enable_vof(); r.set_vof(C0)
244 for nm, fa in zip("uvw", (s.get_uf(), s.get_vf(), s.get_wf())):
245 r.set_field(nm, np.asfortranarray(np.asarray(fa)))
246 for _ in range(10):
247 r.advect_vof(dt)
248 dC = float(np.abs(r.get_vof() - s.get_vof()).max())
249 print(f" dt = {dt:.6g}, 10 steps: max|C-C0| = {moved:.4g}, sum C = {vol:.12g} (C0: {float(C0.sum()):.12g})")
250 check("collocated colour == the staggered run on the SAME face field", dC == 0.0,
251 f"max|dC| = {dC:.3e}")
252 # a fresh solver whose face field was never built must refuse
253 s2 = pf.SolverColocated(n, n, n)
254 s2.set_rho(1.0); s2.set_mu(0.0)
255 s2.set_pressure_geometry(np.full((n, n, n), 10.0, order="F"))
256 s2.enable_vof(); s2.set_vof(C0)
257 m2 = ""
258 try:
259 s2.advect_vof(0.01)
260 except RuntimeError as e:
261 m2 = str(e).split("\n")[0]
262 check("a never-built face field is refused", "never been built" in m2, m2[:70])
263
264
265# ------------------------------------------------------------------ item 7: free-slip domain BC
266def half_channel(nz, top_type, mu=0.05, F=1e-3, dt=5000.0, steps=200):
267 s = pf.Solver(4, 4, nz)
268 s.set_rho(1.0); s.set_mu(mu); s.set_dt(dt); s.set_advection(False)
269 s.set_domain_bc("-z", "wall") # -z no-slip wall
270 s.set_domain_bc("+z", top_type) # +z: 'wall' = no-slip, 'slip' = FREE SLIP
271 s.set_pressure_geometry(np.full((4, 4, nz), 1e30, order="F"))
272 s.set_body_force((F, 0.0, 0.0))
273 for _ in range(steps):
274 s.step()
275 return s
276
277
278def gate_freeslip(nz=32):
279 print("ISSUES item 7 -- domain BC type 4 = free slip")
280 mu, F = 0.05, 1e-3
281 # (a) the analytic half-channel. The DISCRETE solution of the scheme is the continuum
282 # parabola plus h^2/4 * F/(2 mu): a second difference reproduces a quadratic exactly, and
283 # the only inexact ingredient is the no-slip wall's mirror ghost (u(-h/2) = -u(h/2) is
284 # exact only for an ODD function, and z^2 is even). That offset is the NO-SLIP wall's, not
285 # the free-slip one's -- which is the point: the free-slip face contributes no error at all.
286 s = half_channel(nz, "slip", mu, F)
287 u = s.get_u()[0, 0, :]
288 zc = np.arange(nz) + 0.5
289 H = float(nz)
290 cont = F / (2 * mu) * (H ** 2 - (H - zc) ** 2)
291 disc = cont + F / (2 * mu) * 0.25
292 e_cont = float(np.abs(u - cont).max() / cont.max())
293 e_disc = float(np.abs(u - disc).max() / disc.max())
294 print(f" u_max {u.max():.8f}; continuum parabola {cont.max():.8f} (rel {e_cont:.3e}), "
295 f"discrete parabola {disc.max():.8f} (rel {e_disc:.3e}); "
296 f"pressure {s.diagnostics.last_pressure_iterations()}, failed={s.diagnostics.pressure_solve_failed()}")
297 check("half-channel == the scheme's own discrete parabola (solver tol)", e_disc < 1e-8, f"{e_disc:.3e}")
298 check("half-channel within h^2 of the continuum parabola", e_cont < 1e-3, f"{e_cont:.3e}")
299 # (b) free slip IS symmetry: the half channel must equal the lower half of a FULL channel of
300 # twice the height with no-slip on both sides.
301 f2 = half_channel(2 * nz, "wall", mu, F)
302 u2 = f2.get_u()[0, 0, :nz]
303 d = float(np.abs(u - u2).max() / u.max())
304 print(f" vs the lower half of a {2*nz}-cell no-slip channel: max rel difference {d:.3e}")
305 check("free slip == the symmetry plane of a full channel", d < 1e-9, f"{d:.3e}")
306 # (c) inert when unused: a type-1 lid must reproduce a plain no-slip channel exactly.
307 a = half_channel(nz, "wall", mu, F)
308 check("type 4 unused -> nothing moves (sanity)", np.isfinite(a.get_u()).all())
309
310
312 print("ISSUES item 3 -- set_contact_angle on a domain-BC wall (see the dedicated script)")
313
314
315MAIN = dict(atomic=gate_atomic, adaptive=gate_adaptive, geometry=gate_geometry,
316 collocated=gate_collocated, freeslip=gate_freeslip, wetwall=gate_wetwall)
317
318if __name__ == "__main__":
319 ap = argparse.ArgumentParser()
320 ap.add_argument("gate", nargs="*", default=list(MAIN))
321 a = ap.parse_args()
322 for g in a.gate:
323 MAIN[g]()
324 print("\nFAILED:" if FAIL else "\nALL GATES PASSED", ", ".join(FAIL))
325 sys.exit(1 if FAIL else 0)
scene_hysing(nx=32, nz=64, sigma=0.02)
one_adaptive(nsteps, cflT, capT, sigma, dmax)
check(name, ok, detail="")
half_channel(nz, top_type, mu=0.05, F=1e-3, dt=5000.0, steps=200)
leveque(n, t=0.0, T=3.0)
gate_adaptive(nsteps=200)
sphere_colour(n, cx=0.35, r=0.15)