flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
full_stress_large_dt.py
Go to the documentation of this file.
1#!/usr/bin/env python
2"""Large dt and steady marches with the full viscous stress (doc/full_viscous_stress.md §6, WO-3, G3).
3
4 couette G3(i) two-layer Couette (10x mu(y), arithmetic mean) at dt = 20 and 100: full stress
5 against laplacian, the same error to 1e-8 relative (design Amendment A2).
6 rotcore G3(ii) the rotating-core problem of G2 (full_stress_gates.py) at mu_in/mu_out = 0.01 and
7 100, D = 1e4, 2000 steps: no growth as design Amendment A3 states it -- with
8 d_n = max|u^n - u^2000| (all components), d_n <= 2 d_0 for every n < 2000 and
9 d_1999 <= 1e-8 d_0 (u^0 = the continuum field the march starts from); the
10 laplacian control is info. And the same steady error as at D = 10 (relative
11 1e-8). --n N (default 64).
12 spheres G3(iii) steady Stokes through the periodic sphere array (sdflow set-up, N = 32) with a
13 smooth 10x mu(x) = mu0 10^((1 - cos 2 pi x/L)/2): dt = 20 and dt = 100 give the
14 same steady K = mu0 <u>/F to 1e-6; steps to steady (max|du| <= 1e-10 max|u|),
15 full against laplacian (target <= 2x, else Q3).
16 outflow S2 an OPEN face (review S2, outside the §6 proof): a 32 x 16 x 4 channel, plug inflow
17 -x, outflow +x, no-slip walls in y, periodic z, mu = mu0 10^((x/Lx + y/Ly)/2)
18 (10x, gradients in x and y up to the outflow face), steady Stokes marched at
19 dt = 20 and 1000 (D = mu dt/h^2 up to 1000). Pass: both forms reach steady
20 (max|du| <= 1e-10 max|u|) with no growth (max|u| never above 2x its final
21 value) and give the same steady field at the two dt to 1e-6 (max|u_20 -
22 u_1000| / max|u|); full against laplacian is info.
23 ctest the short ctest `full_stress_large_dt`: rotating core N = 32, ratio 100, D = 1e4,
24 500 steps, full stress: the A3 no-growth test against u^500.
25
26Run: OMP_NUM_THREADS=8 PYTHONPATH=<build> python tests/study/full_stress_large_dt.py [cmd ...]
27Exit 0 pass, 1 miss, 77 skipped (no module).
28"""
29import argparse
30import os
31import sys
32
33import numpy as np
34
35try:
36 import peclet.flow as pf
37except ImportError:
38 print("SKIP: peclet.flow not importable")
39 sys.exit(77)
40
41sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
42from full_stress_gates import couette, rotcore, rotcore_exact
43
44F = np.asfortranarray
45OK = True
46
47
48def verdict(name, good, detail):
49 global OK
50 OK &= bool(good)
51 print(f"{name:34s} {'PASS' if good else 'MISS'} {detail}", flush=True)
52
53
54def no_growth(d):
55 """Amendment A3: d_n = max|u^n - u^N| for n = 0..N-1; d_n <= 2 d_0 for all n, d_{N-1} <= 1e-8 d_0."""
56 d = np.asarray(d)
57 if len(d) < 2 or not np.isfinite(d).all() or d[0] <= 0.0:
58 return False, float("inf"), float("inf")
59 peak, last = float(d.max() / d[0]), float(d[-1] / d[0])
60 return peak <= 2.0 and last <= 1e-8, peak, last
61
62
63def initial_field(N, ratio, nz=4, U0=1e-3):
64 """u^0: the exact (continuum) face velocity rotcore() sets before the first step."""
65 u_theta = rotcore_exact(N, ratio, U0)[4]
66 c0 = N / 2.0
67 i = np.arange(N, dtype=np.float64)
68 Xu, Yu = np.meshgrid(i, i + 0.5, indexing="ij")
69 Xv, Yv = np.meshgrid(i + 0.5, i, indexing="ij")
70 ru, rv = np.hypot(Xu - c0, Yu - c0), np.hypot(Xv - c0, Yv - c0)
71 ue = -u_theta(ru) * (Yu - c0) / np.maximum(ru, 1e-300)
72 ve = u_theta(rv) * (Xv - c0) / np.maximum(rv, 1e-300)
73 rep3 = lambda a: np.repeat(a[:, :, None], nz, axis=2)
74 return np.stack([rep3(ue), rep3(ve), np.zeros((N, N, nz))])
75
76
77def march_rotcore(N, ratio, D, steps, full=True):
78 """Fixed-length march (the G2 set-up, exact initial field). Returns the solver, max|u| after
79 every step, and d_n = max|u^n - u^steps| for n = 0..steps-1 (Amendment A3)."""
80 *_, s = rotcore(N, ratio, full, D=D, max_steps=1, tol=-1.0)
81 state = lambda: np.stack([np.array(s.get_u()), np.array(s.get_v()), np.array(s.get_w())])
82 hist = [initial_field(N, ratio), state()]
83 for _ in range(steps - 1):
84 s.step()
85 hist.append(state())
86 mx = [float(np.abs(h[:2]).max()) for h in hist[1:]]
87 ref = hist[-1]
88 d = [float(np.abs(h - ref).max()) for h in hist[:-1]]
89 return s, mx, d
90
91
92def rotcore_error(s, N, ratio, U0=1e-3):
93 u_theta = rotcore_exact(N, ratio, U0)[4]
94 c0 = N / 2.0
95 i = np.arange(N, dtype=np.float64)
96 Xu, Yu = np.meshgrid(i, i + 0.5, indexing="ij")
97 Xv, Yv = np.meshgrid(i + 0.5, i, indexing="ij")
98 ru, rv = np.hypot(Xu - c0, Yu - c0), np.hypot(Xv - c0, Yv - c0)
99 ue = -u_theta(ru) * (Yu - c0) / np.maximum(ru, 1e-300)
100 ve = u_theta(rv) * (Xv - c0) / np.maximum(rv, 1e-300)
101 u, v = np.array(s.get_u())[:, :, 0], np.array(s.get_v())[:, :, 0]
102 return max(np.abs(u - ue).max(), np.abs(v - ve).max()) / U0
103
104
106 # Amendment A2: on the arithmetic mean the transpose term vanishes for layered mu(y), so full and
107 # laplacian give the same Couette error to <= 1e-8 relative at dt 20 and 100.
108 for dt in (20.0, 100.0):
109 e0, c0 = couette(False, dt)
110 e1, c1 = couette(True, dt)
111 rel = abs(e1 - e0) / e0
112 verdict(f"G3(i) couette dt={dt:g}", rel <= 1e-8 and c1 > 0,
113 f"laplacian {e0 * 100:.6f}% conv@{c0}; full {e1 * 100:.6f}% conv@{c1}; rel {rel:.2e}")
114
115
117 for ratio in (0.01, 100.0):
118 e10, n10, *_ = rotcore(N, ratio, True, D=10.0)
119 s, mx, d = march_rotcore(N, ratio, 1e4, 2000)
120 good_g, peak, last = no_growth(d)
121 e4 = rotcore_error(s, N, ratio)
122 rel = abs(e4 - e10) / e10
123 print(f" ratio {ratio:g} N {N}: D=10 e {e10:.10e} ({n10} steps); D=1e4 2000 steps e "
124 f"{e4:.10e}; max|u| first/50/last {mx[0]:.6e} {mx[49]:.6e} {mx[-1]:.6e}; d_0 "
125 f"{d[0]:.3e}, d_1/50/200/1000/1999 {d[1]:.3e} {d[50]:.3e} {d[200]:.3e} {d[1000]:.3e} "
126 f"{d[-1]:.3e}", flush=True)
127 verdict(f"G3(ii) ratio {ratio:g} no growth (A3)", good_g,
128 f"max d_n/d_0 {peak:.4f} (<= 2), d_1999/d_0 {last:.2e} (<= 1e-8)")
129 _, _, dl = march_rotcore(N, ratio, 1e4, 2000, full=False)
130 gl, pl, ll = no_growth(dl)
131 print(f" (info) laplacian ratio {ratio:g}: A3 {'pass' if gl else 'miss'}, max d_n/d_0 "
132 f"{pl:.4f}, d_1999/d_0 {ll:.2e}", flush=True)
133 verdict(f"G3(ii) ratio {ratio:g} same steady", rel <= 1e-8,
134 f"|e(D=1e4) - e(D=10)| / e = {rel:.2e} (<= 1e-8)")
135
136
137def spheres(full, dt, N=32, mu0=0.1, Fb=1e-3, max_steps=20000, tol=1e-10):
138 R = 0.18 * N
139 cs = np.array([0.25 * N, 0.75 * N])
140 xs = np.arange(N) + 0.5
141 X, Y, Z = np.meshgrid(xs, xs, xs, indexing="ij")
142 sdf = np.full((N, N, N), 1e30)
143 for sx in cs:
144 for sy in cs:
145 for sz in cs:
146 dx = X - sx
147 dx -= N * np.round(dx / N)
148 dy = Y - sy
149 dy -= N * np.round(dy / N)
150 dz = Z - sz
151 dz -= N * np.round(dz / N)
152 sdf = np.minimum(sdf, np.sqrt(dx * dx + dy * dy + dz * dz) - R)
153 mu = mu0 * 10.0 ** ((1.0 - np.cos(2 * np.pi * X / N)) / 2.0)
154 s = pf.Solver(N, N, N)
155 s.set_rho(1.0)
156 s.set_mu(mu0)
157 s.set_dt(dt)
158 s.set_body_force((Fb, 0.0, 0.0))
159 s.set_advection(False)
160 s.set_pressure_pcg(True, 400, 1e-12)
161 s.set_solid(F(sdf), cutcell_pressure=True)
162 s.diagnostics.set_property_mode("variable", False)
163 s.set_field("mu", F(mu))
164 # explicit both ways: with a solid AUTO resolves to laplacian (review B1, Amendment A4)
165 s.set_viscous_stress("full" if full else "laplacian")
166 prev = np.array(s.get_u())
167 for n in range(1, max_steps + 1):
168 s.step()
169 u = np.array(s.get_u())
170 d = np.abs(u - prev).max() / max(np.abs(u).max(), 1e-300)
171 prev = u
172 if d <= tol:
173 break
174 return mu0 * float(u.mean()) / Fb, n, d
175
176
178 res = {}
179 for full in (False, True):
180 for dt in (20.0, 100.0):
181 res[(full, dt)] = spheres(full, dt)
182 K, n, d = res[(full, dt)]
183 print(f" spheres {'full' if full else 'laplacian':9s} dt={dt:5g}: K {K:.10e} steps "
184 f"{n} last rel du {d:.1e}", flush=True)
185 for full in (False, True):
186 k20, k100 = res[(full, 20.0)][0], res[(full, 100.0)][0]
187 rel = abs(k20 - k100) / abs(k100)
188 verdict(f"G3(iii) {'full' if full else 'laplacian'} K(dt=20)==K(100)", rel <= 1e-6,
189 f"rel {rel:.2e} (<= 1e-6)")
190 for dt in (20.0, 100.0):
191 r = res[(True, dt)][1] / res[(False, dt)][1]
192 verdict(f"G3(iii) steps full/laplacian dt={dt:g}", r <= 2.0,
193 f"{res[(True, dt)][1]} / {res[(False, dt)][1]} = {r:.2f} (target <= 2, else Q3)")
194 dK = abs(res[(True, 100.0)][0] - res[(False, 100.0)][0]) / res[(False, 100.0)][0]
195 print(f" (info) K full vs laplacian at dt=100: rel diff {dK:.3e}")
196
197
198def channel_outflow(full, dt, nx=32, ny=16, nz=4, mu0=0.1, U=1e-3, max_steps=20000, tol=1e-10):
199 xs = np.arange(nx) + 0.5
200 ys = np.arange(ny) + 0.5
201 X, Y, _ = np.meshgrid(xs, ys, np.arange(nz) + 0.5, indexing="ij")
202 mu = mu0 * 10.0 ** ((X / nx + Y / ny) / 2.0)
203 s = pf.Solver(nx, ny, nz)
204 s.set_rho(1.0)
205 s.set_mu(mu0)
206 s.set_dt(dt)
207 s.set_advection(False)
208 s.set_domain_bc("-x", "inflow", (U, 0.0, 0.0))
209 s.set_domain_bc("+x", "outflow")
210 s.set_domain_bc("-y", "wall")
211 s.set_domain_bc("+y", "wall")
212 s.set_pressure_geometry(F(np.ones((nx, ny, nz))))
213 s.set_pressure_pcg(True, 400, 1e-12)
214 s.diagnostics.set_property_mode("variable", False)
215 s.set_field("mu", F(mu))
216 s.set_viscous_stress("full" if full else "laplacian")
217 prev = np.array(s.get_u())
218 peak = 0.0
219 for n in range(1, max_steps + 1):
220 s.step()
221 u = np.array(s.get_u())
222 if not np.isfinite(u).all():
223 return None, n, float("inf"), float("inf")
224 m = np.abs(u).max()
225 peak = max(peak, m)
226 d = np.abs(u - prev).max() / max(m, 1e-300)
227 prev = u
228 if d <= tol:
229 break
230 return u, n, d, peak / m
231
232
234 res = {}
235 for full in (False, True):
236 for dt in (20.0, 1000.0):
237 res[(full, dt)] = channel_outflow(full, dt)
238 u, n, d, pk = res[(full, dt)]
239 ok = u is not None and d <= 1e-10 and pk <= 2.0
240 verdict(f"S2 outflow {'full' if full else 'laplacian'} dt={dt:g} steady", ok,
241 f"{n} steps, last rel du {d:.1e} (<= 1e-10), peak/final max|u| {pk:.4f} (<= 2)")
242 for full in (False, True):
243 a, b = res[(full, 20.0)][0], res[(full, 1000.0)][0]
244 rel = float("inf") if a is None or b is None else np.abs(a - b).max() / np.abs(b).max()
245 verdict(f"S2 outflow {'full' if full else 'laplacian'} u(dt=20)==u(1000)", rel <= 1e-6,
246 f"rel {rel:.2e} (<= 1e-6)")
247 a, b = res[(True, 1000.0)][0], res[(False, 1000.0)][0]
248 if a is not None and b is not None:
249 print(f" (info) outflow full vs laplacian at dt=1000: max|du|/max|u| "
250 f"{np.abs(a - b).max() / np.abs(b).max():.3e}", flush=True)
251
252
254 _, mx, d = march_rotcore(32, 100.0, 1e4, 1000)
255 good, peak, last = no_growth(d)
256 verdict("full_stress_large_dt ratio 100 D=1e4", good,
257 f"1000 steps, max|u| {mx[-1]:.6e}, max d_n/d_0 {peak:.4f} (<= 2), d_999/d_0 {last:.2e} "
258 f"(<= 1e-8)")
259
260
261def main():
262 ap = argparse.ArgumentParser()
263 ap.add_argument("cmd", nargs="*", default=["couette", "rotcore", "spheres", "outflow"])
264 ap.add_argument("--n", type=int, default=64)
265 a = ap.parse_args()
266 for c in a.cmd:
267 if c == "rotcore":
268 cmd_rotcore(a.n)
269 else:
270 globals()["cmd_" + c]()
271 print("PASS" if OK else "FAIL")
272 return 0 if OK else 1
273
274
275if __name__ == "__main__":
276 sys.exit(main())
march_rotcore(N, ratio, D, steps, full=True)
initial_field(N, ratio, nz=4, U0=1e-3)
channel_outflow(full, dt, nx=32, ny=16, nz=4, mu0=0.1, U=1e-3, max_steps=20000, tol=1e-10)
verdict(name, good, detail)
rotcore_error(s, N, ratio, U0=1e-3)
spheres(full, dt, N=32, mu0=0.1, Fb=1e-3, max_steps=20000, tol=1e-10)