flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
test_vof_viscous_interface_auto.py
Go to the documentation of this file.
1#!/usr/bin/env python
2"""Gate: set_vof_viscous_interface('auto' | 'sharp' | 'averaged') resolves per flow
3doc/vof_sharp_viscous_stress.md ยง9 (USER 2026-11-04: 'auto' is the default).
4
5One step of a small periodic VoF drop (mu = LinearMix(C), ratio 10) per configuration; the sharp
6interface is in force iff diagnostics.vof_viscous_interface_census()['band_cells'] > 0.
7 1. the default is 'auto', and every mode round-trips; an unknown one raises ValueError and leaves
8 the selection unchanged;
9 2. 'auto' -> sharp on the staggered Solver with VoF, mu = LinearMix(C) and the full stress;
10 'sharp' -> sharp; 'averaged' -> not; a uniform mixture colour (mu globally uniform, every
11 cell interfacial) leaves 'auto' inert and bitwise 'averaged' (review F6);
12 3. 'auto' -> averaged, with ONE stderr notice over two steps, for: the Laplacian viscous stress,
13 an immersed solid, porous momentum, phase change, the harmonic face viscosity, and
14 SolverColocated; silently for a uniform mu (LinearMix with mu_1 = mu_0);
15 4. an explicit 'sharp' raises at step() in each of those staggered configurations and without VoF;
16 SolverColocated raises at the setter.
17
18Run: OMP_NUM_THREADS=4 OMP_PROC_BIND=false PYTHONPATH=<build> \
19 python tests/python/test_vof_viscous_interface_auto.py
20Exit 0 pass, 1 fail, 77 skipped (no module).
21"""
22import os
23import sys
24import tempfile
25
26import numpy as np
27
28N = 12
29NOTICE = "AUTO viscous interface fell back to 'averaged'"
30
31
32def drop(n):
33 x = np.arange(n) + 0.5
34 X, Y, Z = np.meshgrid(x, x, x, indexing="ij")
35 r = np.sqrt((X - 0.5 * n - 0.13) ** 2 + (Y - 0.5 * n - 0.27) ** 2 + (Z - 0.5 * n - 0.11) ** 2)
36 return np.asfortranarray(np.clip(0.5 * n * 0.3 - r + 0.5, 0.0, 1.0))
37
38
39def build(pf, cls=None, vof=True, mu1=10.0, setup=None):
40 s = (cls or pf.Solver)(N, N, N)
41 s.set_advection(False)
42 s.set_rho(1.0)
43 s.set_mu(1.0)
44 s.set_dt(0.1)
45 s.set_pressure_geometry(np.asfortranarray(np.full((N, N, N), 10.0)))
46 if vof:
47 s.enable_vof()
48 s.set_vof(drop(N))
49 s.set_property_model("mu", "linear", "C", [1.0, mu1 - 1.0])
50 if setup is not None:
51 setup(s)
52 return s
53
54
55def run(s, steps=1):
56 """Step `steps` times capturing fd 2; returns (band_cells after the last step, stderr text)."""
57 sys.stderr.flush()
58 saved = os.dup(2)
59 with tempfile.TemporaryFile(mode="w+b") as f:
60 os.dup2(f.fileno(), 2)
61 try:
62 for _ in range(steps):
63 s.step()
64 finally:
65 sys.stderr.flush()
66 os.dup2(saved, 2)
67 os.close(saved)
68 f.seek(0)
69 err = f.read().decode(errors="replace")
70 return s.diagnostics.vof_viscous_interface_census()["band_cells"], err
71
72
73def main():
74 try:
75 import peclet.flow as pf
76 except ImportError as e:
77 print(f"SKIP: peclet.flow not importable ({e})")
78 return 77
79 fails = []
80
81 def check(cond, msg):
82 print(("ok " if cond else "FAIL ") + msg)
83 if not cond:
84 fails.append(msg)
85
86 # 1. names
87 s = build(pf)
88 check(s.vof_viscous_interface() == "auto", f"default is {s.vof_viscous_interface()!r}")
89 for m in ("sharp", "averaged", "auto"):
90 s.set_vof_viscous_interface(m)
91 check(s.vof_viscous_interface() == m, f"{m!r} round-trips to {s.vof_viscous_interface()!r}")
92 try:
93 s.set_vof_viscous_interface("harmonic")
94 check(False, "'harmonic' did not raise")
95 except ValueError as e:
96 check(s.vof_viscous_interface() == "auto", f"'harmonic' -> ValueError ({e}), selection kept")
97 check(not hasattr(s.diagnostics, "set_vof_viscous_interface"),
98 "the developer-tier diagnostics.set_vof_viscous_interface is gone")
99
100 # 2. in scope
101 for mode, want in (("auto", True), ("sharp", True), ("averaged", False)):
102 s = build(pf, setup=lambda t, m=mode: t.set_vof_viscous_interface(m))
103 band, err = run(s, 2)
104 check((band > 0) == want and NOTICE not in err,
105 f"in scope, {mode!r}: band_cells {band}, sharp {'on' if want else 'off'}, no notice")
106
107 # 3./4. out of scope: (label, setup) on the staggered Solver
108 def solid(t):
109 x = np.arange(N) + 0.5
110 X, Y, Z = np.meshgrid(x, x, x, indexing="ij")
111 sdf = np.sqrt((X - 1.5) ** 2 + (Y - 1.5) ** 2 + (Z - 1.5) ** 2) - 1.0
112 t.set_solid(np.asfortranarray(sdf), cutcell_pressure=True)
113
114 out = (
115 ("laplacian stress", lambda t: t.set_viscous_stress("laplacian")),
116 ("immersed solid", solid),
117 ("porous momentum", lambda t: t.set_porous_continuity(True)),
118 ("phase change", lambda t: t.enable_phase_change(1.0, 10.0, 1.0)),
119 ("harmonic face mu", lambda t: t.diagnostics.set_property_mode("variable", True)),
120 )
121 for label, setup in out:
122 try:
123 band, err = run(build(pf, setup=setup), 2)
124 check(band == 0 and err.count(NOTICE) == 1,
125 f"{label}, 'auto': band_cells {band}, notices {err.count(NOTICE)} (want 0, 1)")
126 except Exception as e: # noqa: BLE001 -- any raise under AUTO is a failure
127 check(False, f"{label}, 'auto' raised {type(e).__name__}: {e}")
128
129 def both(t, setup=setup):
130 setup(t)
131 t.set_vof_viscous_interface("sharp")
132
133 try:
134 run(build(pf, setup=both))
135 check(False, f"{label}, 'sharp': did not raise")
136 except RuntimeError as e:
137 check("set_vof_viscous_interface('sharp')" in str(e), f"{label}, 'sharp' raises: {e}")
138
139 # a uniform "mixture" colour (every cell interfacial, mu globally uniform at the step head):
140 # the transpose is skipped, so the sharp interface must be inert -- 'auto' bitwise 'averaged'
141 # (review F6; before the fix 'auto' differed and its census read 1728 band cells). One step:
142 # the colour transport moves C off exact uniformity at round-off, and mu with it.
143 x = (np.arange(N) + 0.5) / N
144 X, Y, Z = np.meshgrid(x, x, x, indexing="ij")
145
146 def mixture(t, m):
147 t.set_vof(np.asfortranarray(np.full((N, N, N), 0.5)))
148 for c, A in enumerate((Y, Z, X)):
149 t.set_velocity(c, np.asfortranarray(0.01 * np.sin(2.0 * np.pi * A)))
150 t.set_vof_viscous_interface(m)
151
152 got = {}
153 for m in ("auto", "averaged"):
154 t = build(pf, setup=lambda u, m=m: mixture(u, m))
155 band, _ = run(t, 1)
156 got[m] = (band, b"".join(np.ascontiguousarray(a).tobytes()
157 for a in (t.get_u(), t.get_v(), t.get_w(), t.get_p())))
158 check(got["auto"][0] == 0 and got["auto"][1] == got["averaged"][1],
159 f"uniform mixture C, 'auto': band_cells {got['auto'][0]}, bitwise 'averaged'")
160 # uniform mu: silent and inert
161 band, err = run(build(pf, mu1=1.0), 2)
162 check(band == 0 and NOTICE not in err, f"uniform mu, 'auto': band_cells {band}, no notice")
163 # no VoF: silent under AUTO, refused under 'sharp'
164 band, err = run(build(pf, vof=False), 1)
165 check(band == 0 and NOTICE not in err, f"no VoF, 'auto': band_cells {band}, no notice")
166 try:
167 run(build(pf, vof=False, setup=lambda t: t.set_vof_viscous_interface("sharp")))
168 check(False, "no VoF, 'sharp': did not raise")
169 except RuntimeError as e:
170 check("enable_vof" in str(e), f"no VoF, 'sharp' raises: {e}")
171
172 # SolverColocated: 'auto' -> averaged with the notice; 'sharp' raises at the setter
173 s = build(pf, cls=pf.SolverColocated)
174 check(s.vof_viscous_interface() == "auto", "SolverColocated default is 'auto'")
175 band, err = run(s, 2)
176 check(band == 0 and err.count(NOTICE) == 1,
177 f"SolverColocated, 'auto': band_cells {band}, notices {err.count(NOTICE)} (want 0, 1)")
178 try:
179 s.set_vof_viscous_interface("sharp")
180 check(False, "SolverColocated 'sharp' did not raise")
181 except RuntimeError as e:
182 check(s.vof_viscous_interface() == "auto", f"SolverColocated 'sharp' raises: {e}")
183
184 print("PASS" if not fails else f"FAIL ({len(fails)})")
185 return 1 if fails else 0
186
187
188if __name__ == "__main__":
189 sys.exit(main())
build(pf, cls=None, vof=True, mu1=10.0, setup=None)
static void check(bool ok, const std::string &what)