flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
full_stress_gates.py
Go to the documentation of this file.
1#!/usr/bin/env python
2"""Gates of the full viscous stress wiring (doc/full_viscous_stress.md §8, §5.5, §5.6, §13 G2).
3
4Subcommands (default: all but rotcore):
5 bit §8.2 feature on with a UNIFORM mu field (variable mode, walled channel + periodic box):
6 u, v, w, p bitwise equal to the feature off.
7 wall §5.5 walled channel (+-y walls) and an inflow/outflow x channel with a 3-D variable mu,
8 full stress on: the wall-normal / inflow-normal face values stay bitwise equal to
9 the imposed value.
10 couette §8.3 two-layer plane Couette (mu(y), 10x, arithmetic mean): full stress against
11 laplacian at dt = 20 and dt = 100, same error to a relative 1e-6.
12 refuse §5.6 the refusals: collocated setter, harmonic, porous; a bad form name.
13 rotcore G2 the rotating-core manufactured steady Stokes problem (sharp, kinked, curved mu
14 jump): e = max|u - u_ex|/U0 at N = 32, 64, 128 for mu_in/mu_out = 0.1 and 10, full
15 stress (order >= 0.8) against laplacian (>= 5x larger at 128, not converging).
16 Options: --n 32,64,128 --ratios 0.1,10 --D 10 --max-steps N.
17
18Run: OMP_NUM_THREADS=8 PYTHONPATH=<build> python tests/study/full_stress_gates.py [cmd ...]
19Prints one verdict line per gate and exits 1 on any MISS.
20"""
21import argparse
22import sys
23import time
24
25import numpy as np
26import peclet.flow as pf
27
28F = np.asfortranarray
29OK = True
30
31
32def verdict(name, good, detail):
33 global OK
34 OK &= bool(good)
35 print(f"{name:34s} {'PASS' if good else 'MISS'} {detail}", flush=True)
36
37
38def fields(s):
39 return [np.array(a) for a in (s.get_u(), s.get_v(), s.get_w(), s.get_p())]
40
41
42# --- bit ------------------------------------------------------------------------------------------
43def make_channel(full, mu_field, walls=True, n=(16, 12, 8), steps=12):
44 nx, ny, nz = n
45 s = pf.Solver(nx, ny, nz)
46 s.set_rho(1.0)
47 s.set_mu(0.05)
48 s.set_dt(0.5)
49 if walls:
50 s.set_domain_bc("-y", "wall", (0, 0, 0))
51 s.set_domain_bc("+y", "wall", (0, 0, 0))
52 s.set_pressure_geometry(F(np.full(n, 10.0)))
53 s.set_body_force((1e-3, 0.0, 0.0))
54 s.add_field("mu")
55 s.set_field("mu", F(mu_field))
56 s.diagnostics.set_property_mode("variable", False)
57 if full:
58 s.set_viscous_stress("full")
59 rng = np.random.default_rng(3)
60 for k in range(3):
61 a = F(0.01 * rng.standard_normal(n))
62 if walls and k == 1:
63 a[:, 0, :] = 0.0
64 s.set_velocity(k, a)
65 for _ in range(steps):
66 s.step()
67 return fields(s)
68
69
71 n = (16, 12, 8)
72 for walls in (True, False):
73 mu = np.full(n, 0.05)
74 off = make_channel(False, mu, walls)
75 on = make_channel(True, mu, walls)
76 same = all(np.array_equal(a, b) for a, b in zip(off, on))
77 verdict(f"G-bit uniform mu ({'walls' if walls else 'periodic'})", same,
78 "u,v,w,p bitwise on == off" if same else "DIFFERS")
79 # the term is really active once mu varies (guards against a skip that is always taken)
80 mu = np.full(n, 0.05)
81 mu[4:9, 3:8, 2:6] = 0.5
82 off, on = make_channel(False, mu), make_channel(True, mu)
83 d = max(np.abs(a - b).max() for a, b in zip(off[:3], on[:3]))
84 verdict("G-bit control: variable mu acts", d > 0, f"max|du| on vs off = {d:.3e}")
85
86
87# --- wall -------------------------------------------------------------------------------------------
89 n = (16, 12, 8)
90 x, y, z = np.meshgrid(*(np.arange(k) + 0.5 for k in n), indexing="ij")
91 mu = 0.05 * (1.0 + 4.0 * (np.sqrt((x - 6) ** 2 + (y - 4) ** 2 + (z - 4) ** 2) < 3.5))
92 v = make_channel(True, mu, walls=True, steps=20)[1]
93 lo = v[:, 0, :]
94 verdict("wall: v on the -y wall face", np.all(lo == 0.0),
95 f"max|v(-y face)| = {np.abs(lo).max():.3e} (imposed 0)")
96 # inflow -x (U, 0, 0), outflow +x, walls +-y: u on the inflow face must stay U bitwise
97 U = 0.02
98 s = pf.Solver(*n)
99 s.set_rho(1.0)
100 s.set_mu(0.05)
101 s.set_dt(0.5)
102 s.set_domain_bc("-x", "inflow", (U, 0.0, 0.0))
103 s.set_domain_bc("+x", "outflow")
104 s.set_domain_bc("-y", "wall", (0, 0, 0))
105 s.set_domain_bc("+y", "wall", (0, 0, 0))
106 s.set_pressure_geometry(F(np.full(n, 10.0)))
107 s.add_field("mu")
108 s.set_field("mu", F(mu))
109 s.diagnostics.set_property_mode("variable", False)
110 s.set_viscous_stress("full")
111 for _ in range(20):
112 s.step()
113 u, vv = np.array(s.get_u()), np.array(s.get_v())
114 good = np.all(u[0] == U) and np.all(vv[:, 0, :] == 0.0) and np.isfinite(u).all()
115 verdict("wall: inflow u and wall v faces", good,
116 f"max|u(-x)-U| = {np.abs(u[0] - U).max():.3e}, max|v(-y)| = "
117 f"{np.abs(vv[:, 0, :]).max():.3e}")
118
119
120# --- couette ----------------------------------------------------------------------------------------
121def couette(full, dt, N=32, steps=4000, tol=1e-9):
122 nz = 4
123 mu1, mu2, U = 1.0, 0.1, 1.0
124 s = pf.Solver(N, N, nz)
125 s.set_rho(1.0)
126 s.set_mu(mu1)
127 s.set_dt(dt)
128 s.set_domain_bc("-y", "wall", (0.0, 0.0, 0.0))
129 s.set_domain_bc("+y", "inflow", (U, 0.0, 0.0))
130 s.set_pressure_geometry(F(np.full((N, N, nz), 10.0)))
131 y = np.arange(N)
132 muy = np.where(y < N // 2, mu1, mu2).astype(np.float64)
133 s.add_field("mu")
134 s.set_field("mu", F(np.repeat(muy[None, :, None], N, 0).repeat(nz, 2)))
135 s.diagnostics.set_property_mode("variable", False)
136 if full:
137 s.set_viscous_stress("full")
138 prev, conv = None, -1
139 for it in range(steps):
140 s.step()
141 if it % 100 == 99:
142 u = np.array(s.get_u())
143 um = np.abs(u).max()
144 if prev is not None and np.abs(u - prev).max() / (um + 1e-30) < tol:
145 conv = it + 1
146 break
147 prev = u.copy()
148 u = np.array(s.get_u())[N // 2, :, 0]
149 ui = U * mu2 / (mu1 + mu2)
150 yc = (y + 0.5) / N
151 exact = np.where(yc < 0.5, ui * yc / 0.5, ui + (U - ui) * (yc - 0.5) / 0.5)
152 return np.max(np.abs(u - exact)) / U, conv
153
154
156 for dt in (20.0, 100.0):
157 e0, c0 = couette(False, dt)
158 e1, c1 = couette(True, dt)
159 rel = abs(e1 - e0) / e0
160 verdict(f"couette arithmetic dt={dt:g}", rel <= 1e-6 and c1 > 0,
161 f"laplacian err {e0 * 100:.6f}% conv@{c0}; full err {e1 * 100:.6f}% conv@{c1}; "
162 f"rel diff {rel:.2e}")
163
164
165# --- refuse -----------------------------------------------------------------------------------------
167 try:
168 fn()
169 except (RuntimeError, ValueError) as e:
170 return str(e).splitlines()[0][:90]
171 return None
172
173
175 msgs = {}
176 msgs["collocated setter"] = expect_raise(
177 lambda: pf.SolverColocated(8, 8, 8).set_viscous_stress("full"))
178 msgs["bad form"] = expect_raise(lambda: pf.Solver(8, 8, 8).set_viscous_stress("fulll"))
179
180 def var_solver(harmonic=False, porous=False):
181 s = pf.Solver(8, 8, 8)
182 s.set_rho(1.0)
183 s.set_mu(0.1)
184 s.set_dt(0.5)
185 s.set_pressure_geometry(F(np.full((8, 8, 8), 10.0)))
186 s.add_field("mu")
187 mu = np.full((8, 8, 8), 0.1)
188 mu[2:5, 2:5, 2:5] = 1.0
189 s.set_field("mu", F(mu))
190 s.diagnostics.set_property_mode("variable", harmonic)
191 if porous:
192 s.set_porous_continuity(True)
193 s.set_viscous_stress("full")
194 return s
195
196 msgs["harmonic at step"] = expect_raise(lambda: var_solver(harmonic=True).step())
197 msgs["porous at step"] = expect_raise(lambda: var_solver(porous=True).step())
198 ok_laplacian = expect_raise(lambda: pf.SolverColocated(8, 8, 8).set_viscous_stress("laplacian"))
199 for k, m in msgs.items():
200 verdict(f"refuse: {k}", m is not None, m or "did NOT raise")
201 verdict("refuse: collocated 'laplacian' accepted", ok_laplacian is None, ok_laplacian or "ok")
202
203
204# --- rotcore (G2) -----------------------------------------------------------------------------------
205def quintic(R, R2, U0, dH):
206 # H(R)=U0, H'(R)=dH, H''(R)=0, H(R2)=H'(R2)=H''(R2)=0
207 def row(r, d):
208 c = np.zeros(6)
209 for k in range(6):
210 if k >= d:
211 f = 1.0
212 for j in range(d):
213 f *= (k - j)
214 c[k] = f * r ** (k - d)
215 return c
216
217 A = np.array([row(R, 0), row(R, 1), row(R, 2), row(R2, 0), row(R2, 1), row(R2, 2)])
218 b = np.array([U0, dH, 0.0, 0.0, 0.0, 0.0])
219 return np.linalg.solve(A, b)
220
221
222def rotcore_exact(N, ratio, U0):
223 L = float(N)
224 R, R2 = 0.25 * L, 0.45 * L
225 mu_out, mu_in = 1.0, ratio
226 a = quintic(R, R2, U0, (U0 / R) * (1.0 + 2.0 * mu_in / mu_out))
227
228 def H(r, d=0):
229 out = np.zeros_like(r)
230 for k in range(d, 6):
231 f = 1.0
232 for j in range(d):
233 f *= (k - j)
234 out += a[k] * f * r ** (k - d)
235 return out
236
237 def u_theta(r):
238 return np.where(r <= R, U0 * (r / R) ** 3, np.where(r < R2, H(r), 0.0))
239
240 def f_theta(r): # -mu (u'' + u'/r - u/r^2) per region
241 inner = -mu_in * 8.0 * U0 * r / R ** 3
242 rr = np.maximum(r, 1e-300)
243 outer = -mu_out * (H(r, 2) + H(r, 1) / rr - H(r) / rr ** 2)
244 return np.where(r <= R, inner, np.where(r < R2, outer, 0.0))
245
246 return R, R2, mu_in, mu_out, u_theta, f_theta
247
248
249def rotcore(N, ratio, full, D=10.0, U0=1e-3, max_steps=200000, tol=1e-12, nz=4, init=None):
250 R, _R2, mu_in, mu_out, u_theta, f_theta = rotcore_exact(N, ratio, U0)
251 c0 = N / 2.0
252 i = np.arange(N, dtype=np.float64)
253 # mu: cell volume fraction of the core, 8x8 sub-samples per cell (z-independent)
254 sub = (np.arange(8) + 0.5) / 8.0
255 xs = (i[:, None] + sub[None, :]).ravel()
256 XS, YS = np.meshgrid(xs, xs, indexing="ij")
257 inside = (np.hypot(XS - c0, YS - c0) < R).astype(np.float64)
258 C = inside.reshape(N, 8, N, 8).mean(axis=(1, 3))
259 mu = mu_in * C + mu_out * (1.0 - C)
260 rep = lambda a: F(np.repeat(a[:, :, None], nz, axis=2))
261 # forcing at cell centres
262 Xc, Yc = np.meshgrid(i + 0.5, i + 0.5, indexing="ij")
263 rc = np.hypot(Xc - c0, Yc - c0)
264 ft = f_theta(rc)
265 with np.errstate(invalid="ignore", divide="ignore"):
266 sn, cs = np.where(rc > 0, (Yc - c0) / rc, 0.0), np.where(rc > 0, (Xc - c0) / rc, 0.0)
267 fx, fy = -ft * sn, ft * cs
268 # exact velocity on the faces
269 Xu, Yu = np.meshgrid(i, i + 0.5, indexing="ij")
270 Xv, Yv = np.meshgrid(i + 0.5, i, indexing="ij")
271 ru, rv = np.hypot(Xu - c0, Yu - c0), np.hypot(Xv - c0, Yv - c0)
272 ue = -u_theta(ru) * (Yu - c0) / np.maximum(ru, 1e-300)
273 ve = u_theta(rv) * (Xv - c0) / np.maximum(rv, 1e-300)
274 s = pf.Solver(N, N, nz)
275 s.set_rho(1.0)
276 s.set_mu(mu_out)
277 s.set_dt(D / min(mu_in, mu_out)) # D = mu_min dt / (rho h^2), h = 1
278 s.set_advection(False)
279 s.set_pressure_pcg(True, 400, 1e-13)
280 s.diagnostics.set_velocity_solver_params(400, 1e-12, 2)
281 s.set_pressure_geometry(F(np.full((N, N, nz), 10.0)))
282 s.enable_cell_force()
283 s.diagnostics.set_property_mode("variable", False) # registers the "mu" field
284 s.set_field("mu", rep(mu))
285 s.diagnostics.set_property_mode("variable", False)
286 if full:
287 s.set_viscous_stress("full")
288 for nm, a in (("force_x", rep(fx)), ("force_y", rep(fy)), ("force_z", rep(0 * fx))):
289 s.set_field(nm, a)
290 s.diagnostics.exchange_field(nm)
291 if init is None:
292 s.set_velocity(0, rep(ue))
293 s.set_velocity(1, rep(ve))
294 else:
295 for k in range(3):
296 s.set_velocity(k, F(init[k]))
297 prev = np.array(s.get_u())
298 steps, hist = 0, []
299 for steps in range(1, max_steps + 1):
300 s.step()
301 u = np.array(s.get_u())
302 du = np.abs(u - prev).max()
303 prev = u
304 if steps % 50 == 0:
305 hist.append(np.abs(u).max())
306 if du < tol * U0:
307 break
308 u, v = np.array(s.get_u())[:, :, 0], np.array(s.get_v())[:, :, 0]
309 e = max(np.abs(u - ue).max(), np.abs(v - ve).max()) / U0
310 return e, steps, du / U0, hist, s
311
312
313def gate_rotcore(Ns, ratios, D, max_steps):
314 for ratio in ratios:
315 ef, el = {}, {}
316 for N in Ns:
317 t0 = time.time()
318 ef[N], nf, df, _, _ = rotcore(N, ratio, True, D=D, max_steps=max_steps)
319 el[N], nl, dl, _, _ = rotcore(N, ratio, False, D=D, max_steps=max_steps)
320 print(f" rotcore ratio {ratio:g} N {N:4d}: full e {ef[N]:.4e} ({nf} steps, last "
321 f"du {df:.1e}); laplacian e {el[N]:.4e} ({nl} steps, last du {dl:.1e}) "
322 f"[{time.time() - t0:.0f} s]", flush=True)
323 if len(Ns) >= 3:
324 a, b = Ns[-2], Ns[-1]
325 rf, rl = ef[a] / ef[b], el[a] / el[b]
326 verdict(f"G2 ratio {ratio:g} full order", rf >= 1.75,
327 f"e({a})/e({b}) = {rf:.3f} (>= 1.75, order {np.log2(rf):.2f})")
328 verdict(f"G2 ratio {ratio:g} laplacian", el[b] >= 5 * ef[b] and rl <= 1.25,
329 f"e_lap({b}) / e_full({b}) = {el[b] / ef[b]:.2f} (>= 5); e_lap({a})/e_lap({b}) "
330 f"= {rl:.3f} (<= 1.25)")
331
332
333def main():
334 ap = argparse.ArgumentParser()
335 ap.add_argument("cmd", nargs="*", default=["bit", "wall", "couette", "refuse"])
336 ap.add_argument("--n", default="32,64,128")
337 ap.add_argument("--ratios", default="0.1,10")
338 ap.add_argument("--D", type=float, default=10.0)
339 ap.add_argument("--max-steps", type=int, default=200000)
340 a = ap.parse_args()
341 for c in a.cmd:
342 if c == "rotcore":
343 gate_rotcore([int(x) for x in a.n.split(",")], [float(x) for x in a.ratios.split(",")],
344 a.D, a.max_steps)
345 else:
346 globals()["gate_" + c]()
347 print("ALL PASS" if OK else "SOME MISS")
348 return 0 if OK else 1
349
350
351if __name__ == "__main__":
352 sys.exit(main())
gate_rotcore(Ns, ratios, D, max_steps)
rotcore(N, ratio, full, D=10.0, U0=1e-3, max_steps=200000, tol=1e-12, nz=4, init=None)
verdict(name, good, detail)
couette(full, dt, N=32, steps=4000, tol=1e-9)
rotcore_exact(N, ratio, U0)
quintic(R, R2, U0, dH)
make_channel(full, mu_field, walls=True, n=(16, 12, 8), steps=12)
static double mean(const std::vector< double > &a)