flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
vof_blocks_overlap.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""Overlapping markers in the block VoF container: what actually goes wrong when two bubbles'
3markers interpenetrate (the channel_18 blow-up, WO-W3 section 7).
4
5 static two spheres at rest, zero gravity, centre distance d swept from separated to
6 overlapping by several cells. If the summed per-marker CSF were NOT balanced
7 against the union-colour projection (the W3 hypothesis), the parasitic current
8 would jump at d < 2R. If it stays at the single-bubble level, the static balance
9 holds and the blow-up has to be dynamic.
10 squeeze the same pair driven into each other by opposite body forces on the two markers'
11 regions -- the controlled version of a turbulent collision.
12
13The case numbers mirror channel_18 in cell units: D = 10 cells, rho_g/rho_l = 0.1,
14mu_g = mu_l, sigma = 320 (S^3 * 5e-3 at S = 40 cells per unit length).
15
16Usage: PYTHONPATH=<build> python tests/study/vof_blocks_overlap.py [static|squeeze ...]
17"""
18import math
19import sys
20import time
21
22import numpy as np
23
24import os
25
26import peclet.flow as pf
27
28sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
29
30GATES = [a for i, a in enumerate(sys.argv[1:], 1)
31 if not a.startswith("--") and not sys.argv[i - 1].startswith("--")] or ["static"]
32
33
34def arg(name, default, cast=float):
35 if name in sys.argv:
36 return cast(sys.argv[sys.argv.index(name) + 1])
37 return default
38
39
40R = arg("--R", 5.0)
41RHO_L, RHO_G = 1.0, arg("--rho-g", 0.1)
42MU = arg("--mu", 0.5333)
43MU_G = arg("--mu-g", MU) # gas viscosity (default: the liquid's, as channel_18)
44TENT = "--tent" in sys.argv # vof_overlap_design 5.6: the opt-in overlap density
45REPICK = "--repick" in sys.argv # re-pick dt every step from vof_step_limits() (static gate)
46SIGMA = arg("--sigma", 320.0)
47STEPS = arg("--steps", 400, int)
48
49
50def solver(n, seeds, blocks=True, csf=True):
51 nx, ny, nz = n
52 s = pf.Solver(nx, ny, nz)
53 s.set_rho(RHO_L)
54 s.set_mu(MU)
55 s.set_advection(False) # the pre-flip default (Stokes) kept; NS physics: CHANGELOG "advection default"
56 s.set_pressure_geometry(np.full((nx, ny, nz), 10.0, order="F"))
57 s.set_pressure_chebyshev(True, 800, 1e-12)
58 s.enable_vof()
59 s.set_vof(np.zeros((nx, ny, nz), order="F"))
60 s.set_property_model("rho", "linear", "C", [RHO_L, RHO_G - RHO_L])
61 s.set_property_model("mu", "linear", "C", [MU, MU_G - MU])
62 s.set_surface_tension(SIGMA)
63 s.enable_vof_blocks(seeds)
64 if csf:
65 s.enable_vof_block_csf()
66 if TENT:
67 s.diagnostics.set_vof_block_overlap_density(True)
68 return s
69
70
71def counters(s):
72 """The overlap-design counters: clip (block cascade), debris census, overlap census."""
73 st = s.diagnostics.vof_block_stats()
74 cs = s.diagnostics.vof_block_curvature_stats()
75 return {"clipped": cs.get("clipped", 0),
76 "debris_cells": sum(b.get("debris_cells", 0) for b in st),
77 "debris_volume": sum(b.get("debris_volume", 0.0) for b in st),
78 "returned": [b.get("debris_returned", 0.0) for b in st],
79 "lost": sum(b.get("debris_lost", 0.0) for b in st),
80 "unresolved": sum(b.get("debris_unresolved", 0) for b in st),
81 "overlap_cells": st[0].get("overlap_cells", 0) if st else 0,
82 "overlap_excess": st[0].get("overlap_excess", 0.0) if st else 0.0,
83 "bound": bool(st[0].get("overlap_bound_active", False)) if st else False}
84
85
86def umax(s):
87 return max(np.abs(s.get_u()).max(), np.abs(s.get_v()).max(), np.abs(s.get_w()).max())
88
89
90RUNSTAT = {}
91
92
93def run(s, steps, dt=None, every=50, tag="", safety=None):
94 L = s.vof_step_limits()
95 if dt is None:
96 dt = 0.25 * min(L["cfl_dt"], L["capillary_dt"])
97 s.set_dt(dt)
98 hist = []
99 RUNSTAT.update(bound_steps=0, dt_min=dt, clipped=0, debris=0, ov_cells=0)
100 for i in range(steps):
101 if REPICK and safety is not None:
102 L = s.vof_step_limits()
103 dt = safety * L["capillary_dt"]
104 s.set_dt(dt)
105 RUNSTAT["dt_min"] = min(RUNSTAT["dt_min"], dt)
106 try:
107 s.step()
108 if hasattr(s.diagnostics, "vof_block_stats"):
109 k = counters(s)
110 RUNSTAT["bound_steps"] += int(k["bound"])
111 RUNSTAT["clipped"] += k["clipped"]
112 RUNSTAT["debris"] = max(RUNSTAT["debris"], k["debris_cells"])
113 RUNSTAT["ov_cells"] = max(RUNSTAT["ov_cells"], k["overlap_cells"])
114 except Exception as exc:
115 print(f" {tag} step {i}: THREW {exc}")
116 hist.append(float("nan"))
117 break
118 u = umax(s)
119 hist.append(u)
120 if not math.isfinite(u):
121 break
122 return dt, np.array(hist)
123
124
126 print("=" * 96)
127 print("STATIC — two spheres at rest, no gravity: parasitic current vs centre distance d")
128 print("=" * 96)
129 n = (int(8 * R), int(5 * R), int(5 * R))
130 cy, cz = n[1] / 2, n[2] / 2
131 cx = n[0] / 2
132 cap = math.sqrt((RHO_L + RHO_G) / (4 * math.pi * SIGMA))
133 print(f" R = {R} cells, box {n}, rho_g/rho_l = {RHO_G}, mu = {MU}, sigma = {SIGMA}; "
134 f"Brackbill dt = {cap:.4e}; Laplace dp = {2*SIGMA/R:.2f}")
135 rows = []
136 ds = [float(x) for x in arg("--d", "14,10.5,10,9,8,6,4", str).split(",")]
137 cases = ([("single", None)] if "--no-single" not in sys.argv else []) + \
138 [(f"d={d:g}", d) for d in ds]
139 for name, d in cases:
140 if d is None:
141 seeds = [(cx, cy, cz, R)]
142 else:
143 seeds = [(cx - d / 2, cy, cz, R), (cx + d / 2, cy, cz, R)]
144 s = solver(n, seeds)
145 v0 = [b["volume"] for b in s.diagnostics.vof_block_stats()]
146 t0 = time.time()
147 dt, h = run(s, STEPS, dt=arg("--cap-safety", 0.25) * cap, tag=name,
148 safety=arg("--cap-safety", 0.25))
149 v1 = [b["volume"] for b in s.diagnostics.vof_block_stats()]
150 C = s.get_field("C")
151 dv = max(abs(a / b - 1) for a, b in zip(v1, v0))
152 rows.append((name, h))
153 print(f" {name:8s} max|u| @50 {h[min(49,len(h)-1)]:.3e} @end {h[-1]:.3e} peak {np.nanmax(h):.3e} "
154 f"maxC {float(C.max()):.6f} dV {dv:.1e} ({time.time()-t0:.0f} s) "
155 f"bound-steps {RUNSTAT['bound_steps']} dt_min/Brackbill {RUNSTAT['dt_min']/cap:.3f} "
156 f"clipped {RUNSTAT['clipped']} debris<= {RUNSTAT['debris']} "
157 f"ov_cells<= {RUNSTAT['ov_cells']}", flush=True)
158 if "--dump" in sys.argv:
159 np.savez(f"{arg('--dump', 'static', str)}_{name}.npz", h=h, u=s.get_u(), v=s.get_v(),
160 w=s.get_w(), C=C)
161 return rows
162
163
165 """Two bubbles in a Couette flow, offset in y by b < D so they collide glancingly -- the
166 deterministic stand-in for the channel's turbulent collisions. Per step: max|u|, union max C,
167 marker overlap (sum V_k - sum C_union), and the step at which anything goes non-finite."""
168 print("=" * 96)
169 print("SHEAR — two bubbles colliding in Couette flow (walls at +-y moving at +-U)")
170 print("=" * 96)
171 U = arg("--U", 16.0)
172 b = arg("--b", 6.0)
173 gap0 = arg("--gap", 20.0)
174 blocks = "--single-field" not in sys.argv
175 n = (int(round(13 * R)), int(round(8 * R)), int(round(6 * R)))
176 nx, ny, nz = n
177 s = pf.Solver(nx, ny, nz)
178 s.set_rho(RHO_L)
179 s.set_mu(MU)
180 s.set_domain_bc("-y", "wall", (-U, 0, 0))
181 s.set_advection(False) # the pre-flip default (Stokes) kept; NS physics: CHANGELOG "advection default"
182 s.set_domain_bc("+y", "wall", (U, 0, 0))
183 s.set_pressure_geometry(np.full(n, 10.0, order="F"))
184 s.set_pressure_chebyshev(True, 800, 1e-12)
185 y = (np.arange(ny) + 0.5) / ny
186 u0 = np.broadcast_to((-U + 2 * U * y)[None, :, None], n)
187 s.set_velocity(0, np.asfortranarray(u0))
188 s.enable_vof()
189 s.set_vof(np.zeros(n, order="F"))
190 s.set_property_model("rho", "linear", "C", [RHO_L, RHO_G - RHO_L])
191 s.set_property_model("mu", "linear", "C", [MU, MU_G - MU])
192 s.set_surface_tension(SIGMA)
193 seeds = [(nx / 2 - gap0 / 2, ny / 2 + b / 2, nz / 2, R), (nx / 2 + gap0 / 2, ny / 2 - b / 2, nz / 2, R)]
194 if blocks:
195 s.enable_vof_blocks(seeds)
196 s.enable_vof_block_csf()
197 if TENT:
198 s.diagnostics.set_vof_block_overlap_density(True)
199 else:
200 from vof_surface_tension import sphere_fractions
201 C = np.zeros(n)
202 for q in seeds:
203 C = np.maximum(C, sphere_fractions(n, q[3], q[:3]))
204 s.set_vof(np.asfortranarray(C))
205 rel = 2 * U / ny * b
206 print(f" box {n}, R = {R}, b = {b}, U = {U} -> approach speed {rel:.2f} cells/time; "
207 f"We = {RHO_L*rel**2*2*R/SIGMA:.2f}; {'BLOCKS' if blocks else 'single field'}")
208 T = arg("--T", 3.0 * gap0 / max(rel, 1e-9))
209 t, i = 0.0, 0
210 t0 = time.time()
211 V0 = [q["volume"] for q in s.diagnostics.vof_block_stats()] if blocks else None
212 agg = dict(umax=0.0, bound=0, contact=0, ovmax=0.0, clipped=0, debris=0, dvol=0.0,
213 first_contact=None, last_contact=None, debris_steps=0, debris_vol_max=0.0)
214 while t < T:
215 L = s.vof_step_limits()
216 dt = 0.25 * min(L["cfl_dt"], L["capillary_dt"])
217 if not (dt > 0 and math.isfinite(dt)):
218 print(f" step {i}: limits non-finite {L}")
219 break
220 s.set_dt(dt)
221 try:
222 s.step()
223 except Exception as exc:
224 print(f" step {i} t={t:.3f}: THREW {exc}")
225 break
226 t += dt
227 i += 1
228 if blocks and hasattr(s.diagnostics, "vof_block_curvature_stats"):
229 k = counters(s)
230 agg["umax"] = max(agg["umax"], umax(s))
231 agg["bound"] += int(k["bound"])
232 if k["overlap_cells"] > 0:
233 agg["contact"] += 1
234 agg["first_contact"] = agg["first_contact"] or i
235 agg["last_contact"] = i
236 agg["ovmax"] = max(agg["ovmax"], k["overlap_excess"])
237 agg["clipped"] += k["clipped"]
238 agg["debris"] = max(agg["debris"], k["debris_cells"])
239 agg["debris_steps"] += int(k["debris_cells"] > 0)
240 agg["debris_vol_max"] = max(agg["debris_vol_max"], k["debris_volume"])
241 if i % 20 == 0:
242 C = s.get_field("C")
243 um = umax(s)
244 if blocks:
245 st = s.diagnostics.vof_block_stats()
246 vols = [q["volume"] for q in st]
247 ov = sum(vols) - float(C.sum())
248 cen = [q["centroid"] for q in st]
249 dx = cen[1][0] - cen[0][0]
250 extra = f"V {vols[0]:.4f}/{vols[1]:.4f} overlap {ov:8.4f} dx {dx:6.2f}"
251 else:
252 extra = f"sumC {float(C.sum()):.4f}"
253 print(f" step {i:5d} t={t:7.3f} dt={dt:.2e} max|u| {um:8.3f} maxC {float(C.max()):.6f} "
254 f"{extra} ({time.time()-t0:.0f} s)", flush=True)
255 if not math.isfinite(um) or um > 20 * U:
256 print(" BLOW-UP")
257 break
258 if blocks:
259 V1 = [q["volume"] for q in s.diagnostics.vof_block_stats()]
260 agg["dvol"] = max(abs(a / b - 1) for a, b in zip(V1, V0))
261 print(f" SUMMARY steps {i} t {t:.3f}/{T:.3f} max|u| {agg['umax']:.3f} "
262 f"max rel dV {agg['dvol']:.2e} contact steps {agg['contact']} "
263 f"({agg['first_contact']}..{agg['last_contact']}) max overlap excess "
264 f"{agg['ovmax']:.4f} phantom-bound steps {agg['bound']} clipped cells (sum) "
265 f"{agg['clipped']} debris: max cells {agg['debris']}, steps with debris "
266 f"{agg['debris_steps']}, max volume {agg['debris_vol_max']:.3e}; ledger returned per "
267 f"marker {[f'{r:.3e}' for r in k['returned']]}, lost {k['lost']:.3e}, unresolved "
268 f"{k['unresolved']}", flush=True)
269
270
271ALL = {"static": gate_static, "shear": gate_shear}
272
273if __name__ == "__main__":
274 for g in GATES:
275 ALL[g]()
arg(name, default, cast=float)
run(s, steps, dt=None, every=50, tag="", safety=None)