flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
vof_blocks_ns.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""VoF Part III rung W2 (WO-W12) — the block container coupled to Navier-Stokes.
3
4Every marker carries its own Weymouth-Yue colour field on its own moving box, forms its own
5curvature and its own balanced-force CSF face force there, and the three face-force fields are
6summed into the global RHS (UNPACK_SUM). The union `C = max_blocks C_block` is what the closures
7(rho, mu) see. Two markers that touch therefore cannot coalesce numerically.
8
9 hysing gate 1: Hysing case 1 through the BLOCK path against the same case through the
10 GLOBAL colour field, both without momentum consistency (quasi-2D 64x128x4).
11 grace gate 2: one 3-D bubble at Eo = 10, Mo = 1e-3, density ratio 100, against the
12 Grace-diagram terminal velocity / shape regime.
13 pair gate 3: two bubbles in line, the trailing one catching the leading one -- the film
14 drains to one cell and the two blocks stay two.
15 swarm rung W1 in Python: the master-assignment imbalance of the three modes on a 64-bubble
16 swarm, the per-bubble Lagrangian outputs, and the device-vs-host packing ratio.
17
18COLOUR CONVENTION. With the block container the union C is the DISPERSED phase (C = 1 inside a
19marker), because UNPACK_MAX starts from an empty union and a cell no marker covers must read 0.
20Every property model here is therefore written with C = 1 = GAS, the mirror of the structured
21scripts. The CSF force is unaffected by the flip: kappa(1-C) = -kappa(C) and grad(1-C) = -grad(C),
22so sigma kappa grad C is invariant -- which is what makes the gate-1 comparison meaningful.
23
24Usage: PYTHONPATH=<build> python tests/study/vof_blocks_ns.py [gate ...] [--quick]
25"""
26import math
27import os
28import sys
29import time
30
31import numpy as np
32
33import peclet.flow as pf
34
35sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
36from vof_surface_tension import Scale, Solve, cylinder_fractions, sphere_fractions # noqa: E402
37
38QUICK = "--quick" in sys.argv
39# --rtol R: the hysing gate's pressure-driver rtol (default 1e-12); the momentum solve follows it.
40# An instrument for the tolerance study (tests/study/vof_perf/d1_tolerance.py).
41RTOL = float(sys.argv[sys.argv.index("--rtol") + 1]) if "--rtol" in sys.argv else None
42GATES = [a for i, a in enumerate(sys.argv[1:], 1)
43 if not a.startswith("--") and sys.argv[i - 1] != "--rtol"]
44
45
46def marker_box(C, pad=1):
47 """Tight global index box of C > 0.5, grown by `pad`, clamped to the grid."""
48 idx = np.argwhere(C > 0.5)
49 lo = idx.min(axis=0) - pad
50 hi = idx.max(axis=0) + 1 + pad
51 lo = np.maximum(lo, 0)
52 hi = np.minimum(hi, C.shape)
53 return [int(lo[0]), int(lo[1]), int(lo[2]), int(hi[0]), int(hi[1]), int(hi[2])]
54
55
56HYSING1 = dict(rho1=1000.0, rho2=100.0, mu1=10.0, mu2=1.0, g=0.98, sigma=24.5,
57 ref_vmax=0.2417, ref_tvmax=0.9215, ref_yc=1.081)
58
59
60def build_hysing(nx, blocks):
61 """Hysing case 1, quasi-2D. `blocks` selects the container; the physics is identical."""
62 p = HYSING1
63 Lx = 1.0
64 nz, ny = 2 * nx, 4
65 sc = Scale(nx / Lx)
66 R = sc.len_to_cells(0.25)
67 s = pf.Solver(nx, ny, nz)
68 s.set_rho(p["rho1"])
69 s.set_mu(sc.mu(p["mu1"]))
70 s.set_advection(False) # the pre-flip default (Stokes) kept; NS physics: CHANGELOG "advection default"
71 s.set_domain_bc("-z", "wall", (0, 0, 0))
72 s.set_domain_bc("+z", "wall", (0, 0, 0))
73 s.set_pressure_geometry(np.full((nx, ny, nz), 10.0, order="F"))
74 s.set_pressure_chebyshev(True, 600, RTOL or 1e-12)
75 s.enable_vof()
76 B = cylinder_fractions((nx, ny, nz), R, nx / 2.0, sc.len_to_cells(0.5)) # 1 inside the bubble
77 if blocks:
78 s.set_vof(np.asfortranarray(B)) # marker convention: C = 1 = GAS
79 s.set_property_model("rho", "linear", "C", [p["rho1"], p["rho2"] - p["rho1"]])
80 s.set_property_model("mu", "linear", "C",
81 [sc.mu(p["mu1"]), sc.mu(p["mu2"] - p["mu1"])])
82 s.set_surface_tension(sc.sigma(p["sigma"]))
83 s.set_property_model("force_z", "linear", "C",
84 [-sc.bodyforce(p["rho1"] * p["g"]),
85 -sc.bodyforce((p["rho2"] - p["rho1"]) * p["g"])])
86 s.enable_vof_blocks_from_field([marker_box(B)])
87 s.enable_vof_block_csf()
88 else:
89 s.set_vof(np.asfortranarray(1.0 - B)) # structured convention: C = 1 = LIQUID
90 s.set_property_model("rho", "linear", "C", [p["rho2"], p["rho1"] - p["rho2"]])
91 s.set_property_model("mu", "linear", "C",
92 [sc.mu(p["mu2"]), sc.mu(p["mu1"] - p["mu2"])])
93 s.set_surface_tension(sc.sigma(p["sigma"]))
94 s.set_property_model("force_z", "linear", "C",
95 [-sc.bodyforce(p["rho2"] * p["g"]),
96 -sc.bodyforce((p["rho1"] - p["rho2"]) * p["g"])])
97 return s, sc, nz, ny
98
99
100def run_hysing(nx, blocks, T=3.0, verbose=True):
101 s, sc, nz, ny = build_hysing(nx, blocks)
102 zs = (np.arange(nz) + 0.5) / sc.s
103 h = Solve(600)
104 dt = 0.4 * min(s.vof_step_limits()["cfl_dt"], s.capillary_dt())
105 s.set_dt(dt)
106 t, i, vmax, tvmax, yc = 0.0, 0, 0.0, 0.0, 0.0
107 v0 = None
108 t0 = time.time()
109 while t < T:
110 if i % 10 == 0:
111 L = s.vof_step_limits()
112 dt = 0.4 * min(L["cfl_dt"], L["capillary_dt"])
113 s.set_dt(dt)
114 t += dt
115 i += 1
116 s.step()
117 h.sample(s)
118 C = s.get_vof()
119 B = C if blocks else 1.0 - C
120 vb = B.sum()
121 if v0 is None:
122 v0 = vb
123 yc = float((B.sum(axis=(0, 1)) * zs).sum() / vb)
124 vrise = float((B * s.get_w()).sum() / vb) / sc.s
125 if vrise > vmax:
126 vmax, tvmax = vrise, t
127 if verbose and i % 200 == 0:
128 print(f" t = {t:5.3f} dt = {dt:.3e} y_c = {yc:.4f} v = {vrise:.4f} "
129 f"V/V0 = {vb/v0:.6f}")
130 return dict(vmax=vmax, tvmax=tvmax, yc=yc, steps=i, solve=h, vdrift=vb / v0 - 1.0,
131 wall=time.time() - t0, s=s)
132
133
135 nx = 32 if QUICK else 64
136 print("\n" + "=" * 96)
137 print(f"GATE 1 — Hysing case 1 through the BLOCK path vs the GLOBAL colour field, nx = {nx}")
138 print("=" * 96)
139 print(" Same physics, same discretisation, same dt schedule; the ONLY difference is which")
140 print(" container carries the colour and where the CSF face force is formed. No momentum")
141 print(" consistency in either (the work order's gate: both without enable_vof_momentum).")
142 T = 1.0 if QUICK else 3.0
143 out = {}
144 for name, blk in (("global field", False), ("blocks", True)):
145 print(f"\n -- {name}")
146 out[name] = run_hysing(nx, blk, T)
147 r = out[name]
148 print(f" v_rise max {r['vmax']:.4f} at t = {r['tvmax']:.3f}; y_c({T:g}) = {r['yc']:.4f}"
149 f"; volume drift {r['vdrift']:+.2e}")
150 print(f" {r['steps']} steps, {r['solve']} ({r['wall']:.0f} s)")
151 a, b = out["global field"], out["blocks"]
152 dv = 100.0 * (b["vmax"] / a["vmax"] - 1.0)
153 dy = 100.0 * (b["yc"] / a["yc"] - 1.0)
154 print(f"\n BLOCK vs GLOBAL: v_rise {dv:+.2f} %, y_c {dy:+.2f} % "
155 f"(gate: both within 1 %) -> {'PASS' if max(abs(dv), abs(dy)) <= 1.0 else 'FAIL'}")
156 p = HYSING1
157 print(f" reference (Hysing): v_rise max {p['ref_vmax']:.4f} at t = {p['ref_tvmax']:.3f}, "
158 f"y_c(3) = {p['ref_yc']:.4f}")
159 print(f" global vs reference: {100*(a['vmax']/p['ref_vmax']-1):+.1f} % / "
160 f"{100*(a['yc']/p['ref_yc']-1):+.1f} %; blocks vs reference: "
161 f"{100*(b['vmax']/p['ref_vmax']-1):+.1f} % / {100*(b['yc']/p['ref_yc']-1):+.1f} %")
162
163
164# --------------------------------------------------------------------------- gate 2: Grace
165def grace_terminal(Eo, Mo, d, rho_l, mu_l, sigma, g, mu_ratio_to_water=None):
166 """Grace (1973), as tabulated by Clift, Grace & Weber (1978) ch. 7, eqs (7-10)/(7-11):
167
168 H = (4/3) Eo Mo^-0.149 (mu_l/mu_w)^-0.14 mu_w = 0.9 cP
169 J = 0.94 H^0.757 (2 < H <= 59.3), 3.42 H^0.441 (H > 59.3)
170 U_T = (mu_l/(rho_l d)) Mo^-0.149 (J - 0.857)
171
172 THE TRAP, and it is the reason this gate was nearly reported wrong. The correlation contains a
173 DIMENSIONAL factor, `(mu_l/mu_water)^-0.14`, which a purely dimensionless (Eo, Mo, ratio)
174 specification does NOT determine: at Eo = 10, Mo = 1e-3 the "Grace-diagram terminal velocity"
175 is 0.959 cells/s if one silently sets that factor to 1 and 0.579 if the liquid is the one that
176 actually HAS Mo = 1e-3. It has to be the latter: Mo = 1e-3 at water-like rho and sigma forces
177 mu_l ~ 0.073 Pa s ~ 81 x water (water itself is Mo ~ 2.5e-11), so a factor of 1 describes no
178 liquid at all. `mu_ratio_to_water = None` therefore DERIVES the factor from the physical
179 system that the dimensionless pair implies at rho_l = 1000 kg/m^3, sigma = 0.065 N/m,
180 g = 9.81 m/s^2 -- a glycerol/water mixture, the standard Mo = 1e-3 fluid.
181 """
182 if mu_ratio_to_water is None:
183 RHO_P, SIG_P, G_P, MU_W = 1000.0, 0.065, 9.81, 9.0e-4
184 mu_phys = (Mo * RHO_P * SIG_P ** 3 / G_P) ** 0.25
185 mu_ratio_to_water = mu_phys / MU_W
186 H = (4.0 / 3.0) * Eo * Mo ** -0.149 * mu_ratio_to_water ** -0.14
187 if H <= 59.3:
188 J = 0.94 * H ** 0.757
189 else:
190 J = 3.42 * H ** 0.441
191 return (mu_l / (rho_l * d)) * Mo ** -0.149 * (J - 0.857)
192
193
195 print("\n" + "=" * 96)
196 print("GATE 2 — a single 3-D bubble at Eo = 10, Mo = 1e-3 vs the Grace-diagram terminal velocity")
197 print("=" * 96)
198 # physical set (cell units directly: h = 1). Choose D, rho_l, sigma, then mu from Mo and g
199 # from Eo, with ratio 100 for both density and viscosity.
200 Eo, Mo, ratio = 10.0, 1e-3, 100.0
201 D = 12.0 if QUICK else 16.0
202 R = 0.5 * D
203 rho_l, sigma = 1.0, 1.0
204 g = Eo * sigma / (rho_l * D * D) # Eo = rho g D^2 / sigma (dRho ~ rho_l)
205 mu_l = (Mo * rho_l ** 2 * sigma ** 3 / g) ** 0.25 # Mo = g mu^4 / (rho sigma^3)
206 rho_g, mu_g = rho_l / ratio, mu_l / ratio
207 nx = int(round(4 * D))
208 nz = int(round(9 * D))
209 ny = nx
210 print(f" D = {D:g} cells, box {nx}x{ny}x{nz}, rho_l {rho_l}, rho_g {rho_g}, mu_l {mu_l:.4e}, "
211 f"sigma {sigma}, g {g:.4e}")
212 Ut = grace_terminal(Eo, Mo, D, rho_l, mu_l, sigma, g)
213 Ut1 = grace_terminal(Eo, Mo, D, rho_l, mu_l, sigma, g, mu_ratio_to_water=1.0)
214 Ub = math.sqrt(g * D)
215 mu_phys = (Mo * 1000.0 * 0.065 ** 3 / 9.81) ** 0.25
216 print(f" the physical system this (Eo, Mo) implies at rho = 1000, sigma = 0.065, g = 9.81: "
217 f"d = {math.sqrt(Eo*0.065/(1000*9.81))*1e3:.2f} mm, mu_l = {mu_phys*1e3:.1f} cP "
218 f"({mu_phys/9e-4:.0f} x water)")
219 print(f" Grace/Clift U_T = {Ut:.4f} cells/s (Re = {rho_l*Ut*D/mu_l:.1f}, "
220 f"Fr = U/sqrt(gD) = {Ut/Ub:.3f})")
221 print(f" [the same formula with the viscosity factor set to 1 -- i.e. pretending the liquid "
222 f"is water, which cannot have Mo = 1e-3 -- reads {Ut1:.4f}; see grace_terminal()]")
223 s = pf.Solver(nx, ny, nz)
224 s.set_rho(rho_l)
225 s.set_mu(mu_l)
226 s.set_advection(False) # the pre-flip default (Stokes) kept; NS physics: CHANGELOG "advection default"
227 s.set_domain_bc("-z", "wall", (0, 0, 0))
228 s.set_domain_bc("+z", "wall", (0, 0, 0))
229 s.set_pressure_geometry(np.full((nx, ny, nz), 10.0, order="F"))
230 s.set_pressure_chebyshev(True, 800, 1e-12)
231 s.enable_vof()
232 B = sphere_fractions((nx, ny, nz), R, (nx / 2.0, ny / 2.0, 1.6 * D))
233 s.set_vof(np.asfortranarray(B))
234 s.set_property_model("rho", "linear", "C", [rho_l, rho_g - rho_l])
235 s.set_property_model("mu", "linear", "C", [mu_l, mu_g - mu_l])
236 s.set_surface_tension(sigma)
237 s.set_property_model("force_z", "linear", "C",
238 [-rho_l * g, -(rho_g - rho_l) * g])
239 s.enable_vof_blocks_from_field([marker_box(B)])
240 s.enable_vof_block_csf()
241 T = (3.0 if QUICK else 6.0) * D / Ut
242 h = Solve(800)
243 t, i = 0.0, 0
244 dt = 0.0
245 hist = []
246 t0 = time.time()
247 while t < T:
248 if i % 10 == 0:
249 L = s.vof_step_limits()
250 dt = 0.4 * min(L["cfl_dt"], L["capillary_dt"])
251 s.set_dt(dt)
252 t += dt
253 i += 1
254 s.step()
255 h.sample(s)
256 st = s.diagnostics.vof_block_stats()[0]
257 if st["volume"] > 0:
258 hist.append((t, st["centroid"][2], st["volume"], st["area"],
259 st["moments"][2], st["moments"][0]))
260 if i % 200 == 0:
261 w = s.get_w()
262 C = s.get_vof()
263 ur = float((C * w).sum() / C.sum())
264 print(f" t = {t:8.2f} z_c = {hist[-1][1]:8.3f} U = {ur:.4f} "
265 f"V/V0 = {hist[-1][2]/hist[0][2]:.6f} A = {hist[-1][3]:.1f}")
266 hist = np.array(hist)
267 # terminal velocity from the last third of the trajectory
268 k = len(hist) // 3
269 U = np.polyfit(hist[-k:, 0], hist[-k:, 1], 1)[0]
270 # aspect ratio from the second moments: E = sqrt(m_xx/m_zz) (horizontal over vertical)
271 E = math.sqrt(hist[-1, 5] / hist[-1, 4])
272 print(f"\n measured terminal velocity {U:.4f} cells/s ({100*(U/Ut-1):+.1f} % of Grace)")
273 print(f" Re = {rho_l*U*D/mu_l:.1f}; aspect ratio (sqrt(m_xx/m_zz)) {E:.3f} "
274 f"(ellipsoidal regime: E > 1)")
275 print(f" volume drift {hist[-1,2]/hist[0,2]-1:+.2e}; interface area "
276 f"{hist[-1,3]:.1f} vs the sphere's {4*math.pi*R*R:.1f} cells^2")
277 print(f" {i} steps, {h} ({time.time()-t0:.0f} s)")
278 print(f" GATE: |U/U_Grace - 1| <= 10 % -> "
279 f"{'PASS' if abs(U/Ut - 1) <= 0.10 else 'FAIL'}")
280
281
282# --------------------------------------------------------------------------- gate 3: two bubbles
284 print("\n" + "=" * 96)
285 print("GATE 3 — two bubbles in line, the larger catching the smaller: no numerical coalescence")
286 print("=" * 96)
287 print(" A LARGE bubble rising in line behind a SMALL one closes the gap deterministically (at")
288 print(" fixed Mo the terminal velocity grows with D), so the collision happens on a schedule")
289 print(" instead of waiting on the wake. In a single global colour field the two merge the")
290 print(" moment their PLIC bands touch -- the film is sub-grid and the field has no way to")
291 print(" represent two interfaces in one cell. With one marker each they cannot merge, and the")
292 print(" union carries CELLS THAT BELONG TO BOTH. The control is the same case, same numbers,")
293 print(" on the structured field.")
294 Eo, Mo, ratio = 10.0, 1e-3, 100.0
295 D = 10.0 if QUICK else 12.0
296 Rs, Rl = 0.40 * D, 0.60 * D # leading (small) and trailing (large)
297 rho_l, sigma = 1.0, 1.0
298 g = Eo * sigma / (rho_l * D * D)
299 mu_l = (Mo * rho_l ** 2 * sigma ** 3 / g) ** 0.25
300 rho_g, mu_g = rho_l / ratio, mu_l / ratio
301 nx = ny = int(round(5 * D))
302 nz = int(round(11 * D))
303 # Seed them nearly touching (a 2-cell film): the large one closes the last two cells within a
304 # few hundred steps, which is what makes the gate affordable. Starting them a diameter apart
305 # measured nothing in 20 minutes of wall clock -- the approach is slow and the answer is at
306 # contact.
307 zc_l = 2.0 * D
308 zc_s = zc_l + Rs + Rl + 2.0
309 print(f" D_small = {2*Rs:.1f}, D_large = {2*Rl:.1f} cells; box {nx}x{ny}x{nz}; "
310 f"centres z = {zc_l:.1f} / {zc_s:.1f} (gap {zc_s-zc_l-Rs-Rl:.1f} cells)")
311
312 def build(blocks):
313 s = pf.Solver(nx, ny, nz)
314 s.set_rho(rho_l)
315 s.set_mu(mu_l)
316 s.set_advection(False) # the pre-flip default (Stokes) kept; NS physics: CHANGELOG "advection default"
317 s.set_domain_bc("-z", "wall", (0, 0, 0))
318 s.set_domain_bc("+z", "wall", (0, 0, 0))
319 s.set_pressure_geometry(np.full((nx, ny, nz), 10.0, order="F"))
320 s.set_pressure_chebyshev(True, 800, 1e-12)
321 s.enable_vof()
322 B0 = sphere_fractions((nx, ny, nz), Rl, (nx / 2.0, ny / 2.0, zc_l))
323 B1 = sphere_fractions((nx, ny, nz), Rs, (nx / 2.0, ny / 2.0, zc_s))
324 s.set_vof(np.asfortranarray(np.maximum(B0, B1)))
325 s.set_property_model("rho", "linear", "C", [rho_l, rho_g - rho_l])
326 s.set_property_model("mu", "linear", "C", [mu_l, mu_g - mu_l])
327 s.set_surface_tension(sigma)
328 s.set_property_model("force_z", "linear", "C", [-rho_l * g, -(rho_g - rho_l) * g])
329 if blocks:
330 b0, b1 = marker_box(B0), marker_box(B1)
331 mid = (b0[5] + b1[2]) // 2 # split the boxes at the midplane: one sphere each
332 b0[5] = min(b0[5], mid)
333 b1[2] = max(b1[2], mid)
334 s.enable_vof_blocks_from_field([b0, b1])
335 s.enable_vof_block_csf()
336 return s, 4 / 3 * math.pi * Rl ** 3, 4 / 3 * math.pi * Rs ** 3
337
338 def axis_gap(C):
339 """Empty cells on the axis BETWEEN the two blobs; 0 = they have merged there."""
340 col = C[nx // 2, ny // 2, :]
341 occ = np.argwhere(col > 0.5).ravel()
342 if len(occ) == 0:
343 return -1
344 inside = col[occ.min():occ.max() + 1]
345 return int((inside < 0.5).sum())
346
347 Ut = grace_terminal(Eo, Mo, D, rho_l, mu_l, sigma, g)
348 T = (3.0 if QUICK else 6.0) * D / Ut
349 res = {}
350 for name, blk in (("blocks", True), ("single field (control)", False)):
351 s, v0l, v0s = build(blk)
352 h = Solve(800)
353 t, i, dt = 0.0, 0, 0.0
354 mingap, overlap_max = 10 ** 9, 0.0
355 merged_at = None
356 t0 = time.time()
357 while t < T:
358 if i % 10 == 0:
359 L = s.vof_step_limits()
360 dt = 0.4 * min(L["cfl_dt"], L["capillary_dt"])
361 s.set_dt(dt)
362 t += dt
363 i += 1
364 s.step()
365 h.sample(s)
366 if i % 5 == 0:
367 C = s.get_vof()
368 gap = axis_gap(C)
369 mingap = min(mingap, gap)
370 if gap == 0 and merged_at is None:
371 merged_at = t
372 if blk:
373 vols = [b["volume"] for b in s.diagnostics.vof_block_stats()]
374 overlap_max = max(overlap_max, sum(vols) - float(C.sum()))
375 if i % 100 == 0:
376 print(f" t = {t:7.2f} gap {axis_gap(s.get_vof()):3d} cells "
377 f"({time.time()-t0:.0f} s)")
378 C = s.get_vof()
379 info = dict(steps=i, solve=h, gap=axis_gap(C), mingap=mingap, merged=merged_at,
380 wall=time.time() - t0)
381 print(f"\n -- {name}: {i} steps, {info['solve']} ({info['wall']:.0f} s)")
382 if blk:
383 st = s.diagnostics.vof_block_stats()
384 info["vols"] = [b["volume"] for b in st]
385 info["zc"] = [b["centroid"][2] for b in st]
386 info["overlap"] = overlap_max
387 print(f" marker volumes {info['vols'][0]:.4f} / {info['vols'][1]:.4f} "
388 f"(seed {v0l:.4f} / {v0s:.4f}; drift "
389 f"{info['vols'][0]/v0l-1:+.2e} / {info['vols'][1]/v0s-1:+.2e})")
390 print(f" centroids z {info['zc'][0]:.2f} / {info['zc'][1]:.2f}; final film gap on "
391 f"the axis {info['gap']} cells, MINIMUM over the run {mingap}")
392 print(f" peak shared liquid (sum V_marker - sum C_union) {overlap_max:.3f} cells")
393 else:
394 print(f" final film gap on the axis {info['gap']} cells, MINIMUM {mingap}; "
395 f"merged at t = {merged_at}")
396 res[name] = info
397 b, c = res["blocks"], res["single field (control)"]
398 ok = (b["mingap"] >= 1) and (c["mingap"] == 0)
399 print(f"\n GATE: the control MERGES (gap -> 0) while the blocks keep two markers with their")
400 print(f" own volumes and a film at least one cell thick.")
401 print(f" blocks min gap {b['mingap']} cells (peak shared liquid "
402 f"{b['overlap']:.3f}); control min gap {c['mingap']} cells "
403 f"(merged at t = {c['merged']}) -> {'PASS' if ok else 'INCONCLUSIVE'}")
404
405
406# ------------------------------------------------------------------- gate 3b: markers in contact
408 """The discriminating half of gate 3, when the film gate does not reach contact on its own.
409
410 Seed the two markers ALREADY TOUCHING -- the centre distance is one cell less than the sum of
411 the radii, so their PLIC bands share cells from step 0 -- and run a real two-phase step. A
412 single global colour field has one blob there and can never have two again; two markers have
413 two, each conserving its own volume, and the union carries the shared liquid explicitly.
414 """
415 print("\n" + "=" * 96)
416 print("GATE 3b — two markers seeded IN CONTACT under a real NS step: the union carries cells")
417 print(" that belong to both, and the control is one blob for ever")
418 print("=" * 96)
419 Eo, Mo, ratio = 10.0, 1e-3, 100.0
420 D = 12.0
421 Rs, Rl = 0.40 * D, 0.60 * D
422 rho_l, sigma = 1.0, 1.0
423 g = Eo * sigma / (rho_l * D * D)
424 mu_l = (Mo * rho_l ** 2 * sigma ** 3 / g) ** 0.25
425 rho_g, mu_g = rho_l / ratio, mu_l / ratio
426 nx = ny = int(round(4 * D))
427 nz = int(round(7 * D))
428 zc_l = 1.6 * D
429 zc_s = zc_l + Rs + Rl - 1.0 # ONE cell of band overlap
430 steps = 100 if QUICK else 400
431 print(f" D_small = {2*Rs:.1f}, D_large = {2*Rl:.1f}; box {nx}x{ny}x{nz}; centre distance "
432 f"{zc_s-zc_l:.1f} = R_s + R_l - 1")
433
434 def build(blocks):
435 s = pf.Solver(nx, ny, nz)
436 s.set_rho(rho_l)
437 s.set_mu(mu_l)
438 s.set_advection(False)
439 s.set_domain_bc("-z", "wall", (0, 0, 0))
440 s.set_domain_bc("+z", "wall", (0, 0, 0))
441 s.set_pressure_geometry(np.full((nx, ny, nz), 10.0, order="F"))
442 s.set_pressure_chebyshev(True, 800, 1e-12)
443 s.enable_vof()
444 B0 = sphere_fractions((nx, ny, nz), Rl, (nx / 2.0, ny / 2.0, zc_l))
445 B1 = sphere_fractions((nx, ny, nz), Rs, (nx / 2.0, ny / 2.0, zc_s))
446 s.set_vof(np.asfortranarray(np.maximum(B0, B1)))
447 s.set_property_model("rho", "linear", "C", [rho_l, rho_g - rho_l])
448 s.set_property_model("mu", "linear", "C", [mu_l, mu_g - mu_l])
449 s.set_surface_tension(sigma)
450 s.set_property_model("force_z", "linear", "C", [-rho_l * g, -(rho_g - rho_l) * g])
451 if blocks:
452 # SPHERE seeding, not `enable_vof_blocks_from_field`: with the two markers already
453 # overlapping there is no way to split a union field between them without giving one
454 # marker a slice of the other (measured: -2.7 % / +7.1 % on the two volumes when the
455 # boxes are clipped at the midplane). `enable_vof_blocks` paints each block's colour
456 # from the exact sphere fraction, so each marker starts as its own whole bubble --
457 # which is the state a single colour field cannot hold, and the point of the gate.
458 s.enable_vof_blocks([(nx / 2.0, ny / 2.0, zc_l, Rl), (nx / 2.0, ny / 2.0, zc_s, Rs)])
459 s.enable_vof_block_csf()
460 return s, 4 / 3 * math.pi * Rl ** 3, 4 / 3 * math.pi * Rs ** 3
461
462 out = {}
463 for name, blk in (("blocks", True), ("single field (control)", False)):
464 s, v0l, v0s = build(blk)
465 h = Solve(800)
466 dt = 0.0
467 t0 = time.time()
468 for i in range(steps):
469 if i % 5 == 0:
470 L = s.vof_step_limits()
471 dt = 0.2 * min(L["cfl_dt"], L["capillary_dt"])
472 s.set_dt(dt)
473 s.step()
474 h.sample(s)
475 C = s.get_vof()
476 col = C[nx // 2, ny // 2, :]
477 occ = np.argwhere(col > 0.5).ravel()
478 blobs = 0
479 prev = False
480 for v in (col > 0.5):
481 if v and not prev:
482 blobs += 1
483 prev = v
484 info = dict(blobs=blobs, union=float(C.sum()), solve=h, wall=time.time() - t0)
485 if blk:
486 st = s.diagnostics.vof_block_stats()
487 info["vols"] = [b["volume"] for b in st]
488 info["shared"] = sum(info["vols"]) - info["union"]
489 info["cells_both"] = None
490 out[name] = info
491 print(f"\n -- {name}: {steps} steps, {h} ({info['wall']:.0f} s)")
492 if blk:
493 print(f" TWO markers, volumes {info['vols'][0]:.3f} / {info['vols'][1]:.3f} "
494 f"(seed {v0l:.3f} / {v0s:.3f}, drift {info['vols'][0]/v0l-1:+.2e} / "
495 f"{info['vols'][1]/v0s-1:+.2e})")
496 print(f" union {info['union']:.3f} cells; SHARED liquid "
497 f"sum(V_marker) - sum(C_union) = {info['shared']:.3f} cells")
498 print(f" blobs along the axis in the union field: {blobs}")
499 else:
500 print(f" ONE colour field: {blobs} blob(s) along the axis, "
501 f"union {info['union']:.3f} cells")
502 b, c = out["blocks"], out["single field (control)"]
503 ok = b["shared"] > 0.0
504 print(f"\n GATE: the blocks carry {b['shared']:.3f} cells of liquid that belong to BOTH "
505 f"markers -- a state a single colour field cannot represent (the control's union is "
506 f"{c['union']:.3f} cells in {c['blobs']} blob). -> {'PASS' if ok else 'FAIL'}")
507
508
509# --------------------------------------------------------------------------- W1 in Python
511 print("\n" + "=" * 96)
512 print("RUNG W1 — 64-bubble swarm: master assignment, per-bubble outputs, packing")
513 print("=" * 96)
514 n = 48
515 s = pf.Solver(n, n, n)
516 s.set_rho(1.0)
517 s.set_mu(0.01)
518 s.set_advection(False)
519 s.set_pressure_geometry(np.full((n, n, n), 10.0, order="F"))
520 s.enable_vof()
521 s.set_vof(np.zeros((n, n, n), order="F"))
522 seeds = []
523 k = 0
524 for i in range(4):
525 for j in range(4):
526 for m in range(4):
527 r = 2.0 + 7.0 * ((k % 8) / 7.0)
528 seeds.append(((i + 0.5) * n / 4, (j + 0.5) * n / 4, (m + 0.5) * n / 4, r))
529 k += 1
530 s.enable_vof_blocks(seeds)
531 print(f" {len(s.diagnostics.vof_block_stats())} markers seeded")
532 print(f" {'mode':<16}{'imbalance (np = 1 here; the census is the replicated table)':<40}")
533 for mode, name in ((0, "round robin"), (1, "LPT"), (2, "weighted ORB")):
534 print(f" {name:<16}{s.diagnostics.vof_block_imbalance_of(mode):.4f}")
535 st = s.diagnostics.vof_block_stats()
536 tot_v = sum(b["volume"] for b in st)
537 tot_a = sum(b["area"] for b in st)
538 print(f" per-bubble outputs: total volume {tot_v:.2f} cells, total interface area "
539 f"{tot_a:.2f} cells^2")
540 b = max(st, key=lambda q: q["volume"])
541 R = (3 * b["volume"] / (4 * math.pi)) ** (1 / 3)
542 print(f" largest marker id {b['id']}: V {b['volume']:.3f} -> R {R:.3f} cells, area "
543 f"{b['area']:.2f} vs 4 pi R^2 {4*math.pi*R*R:.2f} ({100*(b['area']/(4*math.pi*R*R)-1):+.2f} %)")
544 print(f" centroid {tuple(round(q,3) for q in b['centroid'])} moments "
545 f"{tuple(round(q,3) for q in b['moments'])}")
546
547
548ALL = {"hysing": gate_hysing, "grace": gate_grace, "pair": gate_pair,
549 "contact": gate_contact, "swarm": gate_swarm}
550
551if __name__ == "__main__":
552 for g in (GATES or list(ALL)):
553 ALL[g]()
build_hysing(nx, blocks)
run_hysing(nx, blocks, T=3.0, verbose=True)
marker_box(C, pad=1)
grace_terminal(Eo, Mo, d, rho_l, mu_l, sigma, g, mu_ratio_to_water=None)
static void build(IbmSolver &s, std::size_t cells)