1"""G-SV1 family (doc/vof_sharp_viscous_stress.md §11, third pass §6.3/§6.4): the 3-D sharp viscous
2operator on planar-interface Stokes flows, through the production stepper; steady states by WO-6s.
4STEADY STATE (WO-6s, §6.4). The colour is frozen (set_vof(C0) after every step), so the step is an
5affine map S(x) = G x + b on x = (u, v, w, p), p through get_field/set_field("p") in internal units
6with its mean removed in and out. GMRES(60) solves (I - G) x = b with the matvec v -> v - S(v) + S(0)
7(one production step; S(0) once), started from the exact face averages with p = 0. Every restart
8cycle begins with a PLAIN production step: its increment S(x) - x is the residual and the
9certificate, ||S(x) - x||_inf <= 1e-12 max|u| over u (the pre-registered criterion); cap 3000
10steps, a case at the cap is NOT CONVERGED. Pressure: the production driver (Chebyshev under
11variable rho, MG-PCG under uniform rho at np 1) with rtol 1e-13 and a cap of 20000. Momentum (§6.6 rule,
12WO-6q, binding): every step of every steady set runs the converged solve (RB-GS update stop 1e-15 --
13coordinator decision 2026-11-01, superseding §6.6's 1e-13 --
14residual stop off, cap 200000 sweeps); one production-default step from the certified state is
15taken afterwards and its increment reported ('inc_default_step', expected <= 1e-11, not judged).
17PERIODIC GATES (USER Q16 pending: they replace the walled box; WO-6p):
18 gsv1p G-SV1P layered flow: m in NORMALS, n = m/|m|, P = 1/|m|; phase A where
19 frac((n.x - s0)/P) < 3/8, s0 = n.(1/2,1/2,1/2) + (k/8) h, k = 0..7; mu_A/mu_B = 1e-2, 1e2;
20 rho_A/rho_B = 1/2; force (rho(C) - rho_bar) g t1 through the closures
21 force_c = linear(rho, [-rho_bar g t1_c, g t1_c]), t1 = tangents(n)[0]; exact u = U(n.x) t1,
22 U periodic piecewise quadratic (mu_k U'' = -(rho_k - rho_bar) g, U and mu U' continuous).
23 gsv1dp the same at mu ratio 1e-3, 1e3.
24 gsv1cp the along mode: phase A where s' mod P in (P/4, 3P/4), s' = n.x - s0; t1 = t/|t| from
25 TANG_CP; u = -a sin(a eta) cos(b s') n + b cos(a eta) sin(b s') t1, a = 2 pi |t|,
26 b = 2 pi |m|, eta = t1.x; p_k = 2 mu_k a b sin sin; force mu(C_i) F(x_i) as a cell field
27 (set_field, internal units); kinds 'along' (rho = 1) and 'along+layered' (plus G-SV1P's
28 layered flow on the same interfaces, rho_A/rho_B = 1/2). Face averages: 4x4 Gauss-Legendre
29 for the smooth part, exact for the layered part.
30 Gauge: per component the rho_F-weighted mean of the exact face averages is removed (the discrete
31 momentum sum rho_F u_c is invariant, 0 from the gauged start). D_hi = 100. Error e = max|u_h -
32 u_bar| / max|u_bar|. PASS per normal x ratio (x kind): the LS order of the offset envelope
33 e_env(N) over N = 24, 32, 48, 64 is >= 1.8; e_env N^2 and the per-offset orders are reported.
34 gsv1w G-SV1W: walled Couette 22.5/22.5, offset 0, mu ratio 1e-2, N 24/32, option-A BCs with
35 wall-face-AVERAGED Dirichlet data (tangential components averaged over the h-square of the
36 wall plane), both modes; PASS iff at both N the 'sharp' max error over faces within one
37 cell of a wall <= the 'averaged' one.
38 pilot the WO-6s pilot (cmd_prun).
39 check WO-6p acceptance: equations and jump conditions at 100 random points, the layered
40 profile's closure, the exact face averages against brute-force quadrature.
42 nice -n 10 python gsv1.py run --set gsv1p --N 24,32,48,64 --mode sharp --procs 8 --out res.jsonl
43 python gsv1.py table --out res.jsonl ; python gsv1.py check
45WALLED (the pre-registered box; a reported diagnostic since the third pass).
46Cases (one planar interface, phase A = C = 1 on the side xi < 0; mu_B = 1, mu_A = ratio):
47 normal n = (cos b cos g, cos b sin g, sin b), b, g in {0, 22.5, 45} deg (9 orientations)
48 plane xi = n.(x - c) - s, c = (1/2, 1/2, 1/2), s = (k/8) h, k = 0..7
49 tangents (coordinator ruling B2, 2026-10-31):
50 t1 = normalize(e_z x n) (t1 = e_x if |n x e_z| < 1e-12), t2 = n x t1,
51 t = (t1 + t2)/sqrt(2) -- the shear direction AND the extension tangent
52 couette u = U(xi) t, U = xi/mu (tau = 1)
53 poiseuille u = U(xi) t, U = (xi - xi^2/2)/mu, uniform body force along t (tau_0 = 1)
54 extension u = eps (xi n - eta t), eta = t.x (B2), eps = 1 (the stepper finds the pressure
55 jump 2 eps [mu] itself)
56 general poiseuille + extension
57Gate sets: gsv1 = couette, poiseuille at ratio 1e-2, 1e2; gsv1c = extension, general at 1e-2, 1e2;
58gsv1d = couette, poiseuille at 1e-3, 1e3. N = 24, 32, 48, 64 (note §5.7 Q-C).
59PASS (note §11, USER 2026-10-31): per kind x ratio x orientation, the LS order of the offset envelope
60e_env(N) = max over k of err is >= 1.8 over N 24/32/48/64; couette also passes if err <= 1e-10 at every
61N; extension needs err <= 1e-9 at every N. Per-offset orders are reported, not gating.
63Discretization of the data: C is the exact cell volume fraction of the half-space; every velocity
64datum is the exact face average of the analytic field (piecewise polynomial in xi, integrated
65exactly). Boundary (coordinator ruling B1, option A): the production Dirichlet profile
66(set_domain_bc_profile) on all six faces, fed with the EXACT wall-plane values: the normal
67component's average over the wall face, each tangential component's average over the wall-plane
68segment of its own face. Uniform rho = 1, D_hi = mu_hi dt/(rho h^2) = 100, momentum advection off,
69sharp viscous interface. The colour is frozen: set_vof(C0) after every step. Start from the exact
70face averages; the steady state by WO-6s (GMRES, below) to a step increment
71<= 1e-12 max|u_exact| (ruling B3's criterion). Error = max|u_h - u_face| / max|u_face| over the
74Also recorded per case (instruments, not gate measures): the max error binned by the face's
75distance to the nearest wall (half-cell bins, `wallmap`), the same joined with the distance to the
76interface (`wximap[wall bin 0..3, >=4][|xi|/h in [0,1), [1,2), [2,4), >=4]`), and the location of
77the max error (its wall distance and |xi|/h).
79 nice -n 10 python gsv1.py run --set gsv1 --N 24,32 --procs 4 --out res.jsonl (resumes)
80 python gsv1.py table --out res.jsonl (verdict lines)
81 python gsv1.py one KIND BETA GAMMA K RATIO N (one JSON line)
89from multiprocessing
import Pool
93GX, GW = np.polynomial.legendre.leggauss(6)
94ANGLES = (0.0, 22.5, 45.0)
96 "gsv1": ((
"couette",
"poiseuille"), (1e-2, 1e2)),
97 "gsv1c": ((
"extension",
"general"), (1e-2, 1e2)),
98 "gsv1d": ((
"couette",
"poiseuille"), (1e-3, 1e3)),
100D_HI, TOL, MAX_STEPS = 100.0, 1e-12, 200000
104 """Volume fraction of {y in [0,1]^3 : m.y < al} (inclusion-exclusion, exact)."""
105 m = np.array(m, float)
106 al = al - sum(x
for x
in m
if x < 0)
108 nz = [x
for x
in m
if x > 1e-300]
111 return 1.0
if al > 0
else 0.0
113 for S
in itertools.product((0, 1), repeat=d):
114 r = al - sum(x
for x, s
in zip(nz, S)
if s)
116 tot += (-1) ** sum(S) * r**d
117 return min(1.0, max(0.0, tot / (math.factorial(d) * float(np.prod(nz)))))
121 ez = np.array([0.0, 0.0, 1.0])
123 t1 = np.array([1.0, 0.0, 0.0])
if np.linalg.norm(np.cross(n, ez)) < 1e-12
else c / np.linalg.norm(c)
125 return t1, t2, (t1 + t2) / math.sqrt(2.0)
129 def __init__(self, kind, beta, gamma, k, ratio, N):
130 b, g = math.radians(beta), math.radians(gamma)
131 self.
n = np.array([math.cos(b) * math.cos(g), math.cos(b) * math.sin(g), math.sin(b)])
133 self.
kind, self.
N, self.
h = kind, N, 1.0 / N
134 self.
s = k / 8.0 * self.
h
136 self.
c = np.array([0.5, 0.5, 0.5])
139 return self.
n @ (x - self.
c) - self.
s
142 mu = np.where(xi < 0, self.
muA, self.
muB)
143 if self.
kind ==
"couette":
145 if self.
kind in (
"poiseuille",
"general"):
146 return (xi - 0.5 * xi * xi) / mu
150 if self.
kind not in (
"extension",
"general"):
152 return self.
xi(x) * self.
n - float(self.
t @ x) * self.
t
155 """E[U(xi0 + X)], X = sum of two centred uniforms of widths |wa|, |wb| (exact)."""
156 a, b = abs(wa), abs(wb)
157 if a < 1e-15
and b < 1e-15:
158 return float(self.
U(np.array(xi0)))
159 if b < 1e-15
or a < 1e-15:
161 pts = sorted({-w / 2, w / 2} | ({-xi0}
if -w / 2 < -xi0 < w / 2
else set()))
162 dens =
lambda x: np.full_like(x, 1.0 / w)
164 br = {-(a + b) / 2, (a + b) / 2, -abs(a - b) / 2, abs(a - b) / 2}
165 if -(a + b) / 2 < -xi0 < (a + b) / 2:
168 dens =
lambda x: np.clip((a + b) / 2 - np.abs(x), 0.0, min(a, b)) / (a * b)
170 for lo, hi
in itertools.pairwise(pts):
173 x = 0.5 * (lo + hi) + 0.5 * (hi - lo) * GX
174 tot += 0.5 * (hi - lo) * float(np.dot(GW, self.
U(xi0 + x) * dens(x)))
178 """Average of u_comp over the h-square (two axes) or h-segment (one axis) centred x."""
179 w = [self.
n[a] * self.
h for a
in axes] + [0.0] * (2 - len(axes))
180 return self.
t[comp] * self.
avgU(self.
xi(x), w[0], w[1]) + self.
ext(x)[comp]
184 """Per component: distance (cells) of each face position to the nearest domain wall."""
186 for comp
in range(3):
189 idx = np.arange(N, dtype=float)
190 pos = idx
if a == comp
else idx + 0.5
191 g.append(np.minimum(pos, N - pos))
192 out.append(np.minimum(np.minimum(g[0][:,
None,
None], g[1][
None, :,
None]), g[2][
None,
None, :]))
197 kind, beta, gamma, k, ratio, N = key
198 os.environ.setdefault(
"OMP_PROC_BIND",
"false")
202 cs =
Case(kind, beta, gamma, k, ratio, N)
204 C = np.zeros((N, N, N))
205 ex = np.zeros((3, N, N, N))
206 xin = np.zeros((3, N, N, N))
207 for i, j, kk
in itertools.product(range(N), repeat=3):
208 xc = np.array([i, j, kk], float) * h
209 C[i, j, kk] =
cube_frac(cs.n, (cs.s - cs.n @ (xc - cs.c)) / h)
210 for comp
in range(3):
211 x = (np.array([i, j, kk], float) + 0.5) * h
213 ex[comp, i, j, kk] = cs.face_avg(comp, x, tuple(a
for a
in range(3)
if a != comp))
214 xin[comp, i, j, kk] = abs(cs.xi(x)) / h
215 dt = D_HI * h * h / max(cs.muA, cs.muB)
216 amp = 0.01 * h / (dt * float(np.max(np.abs(ex))))
218 s =
pf.Solver((N, N, N), extent=(1.0, 1.0, 1.0))
221 b, c = (a + 1) % 3, (a + 2) % 3
223 prof = np.zeros((N, N, 3))
228 x[b], x[c] = (ib + 0.5) * h, (ic + 0.5) * h
229 prof[ib, ic, a] = cs.face_avg(a, x, (b, c))
232 prof[ib, ic, b] = cs.face_avg(b, xb, (c,))
235 prof[ib, ic, c] = cs.face_avg(c, xc, (b,))
236 s.set_domain_bc_profile((
"-" if side == 0
else "+") +
"xyz"[a], np.ascontiguousarray(amp * prof))
238 s.set_mu(max(cs.muA, cs.muB))
239 s.set_pressure_geometry(np.full((N, N, N), 1.0, order=
"F"))
241 C = np.asfortranarray(C)
243 s.set_property_model(
"mu",
"linear",
"C", [cs.muB, cs.muA - cs.muB])
244 s.set_advection(
False)
245 if kind
in (
"poiseuille",
"general"):
246 s.set_body_force(tuple(amp * cs.t))
247 s.set_pressure_pcg(
True, PCAP, PRTOL)
248 s.set_vof_viscous_interface(
"sharp")
250 for comp
in range(3):
251 s.set_velocity(comp, np.asfortranarray(ex[comp]))
252 U = float(np.max(np.abs(ex)))
254 x0 = np.concatenate([ex[c].ravel(order=
"F")
for c
in range(3)] + [np.zeros(N**3)])
255 xs, status, it, inc, _ =
gmres_steady(Smap, x0, 3 * N**3, U)
257 prev = np.stack([xs[c * N**3:(c + 1) * N**3].reshape((N, N, N), order=
"F")
for c
in range(3)])
258 e = np.abs(prev - ex) / U
259 err = float(np.max(e))
261 bins = np.floor(2.0 * wd + 1e-9).astype(int)
262 wallmap = [float(np.max(e[bins == q]))
if np.any(bins == q)
else 0.0
for q
in range(int(bins.max()) + 1)]
263 xbins = np.digitize(xin, (1.0, 2.0, 4.0))
264 wb = np.minimum(bins, 4)
265 wximap = [[float(np.max(e[(wb == q) & (xbins == r)]))
if np.any((wb == q) & (xbins == r))
else 0.0
266 for r
in range(4)]
for q
in range(5)]
267 am = np.unravel_index(int(np.argmax(e)), e.shape)
268 return {
"kind": kind,
"beta": beta,
"gamma": gamma,
"k": k,
"ratio": ratio,
"N": N,
"status": status,
"steps": it,
269 "inc": inc,
"err": err,
"at_comp": int(am[0]),
"at_cell": [int(v)
for v
in am[1:]],
270 "at_walldist": float(wd[am]),
"at_xi": float(xin[am]),
"wallmap": wallmap,
"wximap": wximap,
271 "inc_default_step": inc_def,
"max_momentum_sweeps": Smap.max_msw,
"converged_momentum":
True,
272 "secs": round(time.time() - t0, 1)}
276 return (r[
"kind"], r[
"beta"], r[
"gamma"], r[
"k"], r[
"ratio"], r[
"N"])
281 if os.path.exists(path):
282 with open(path)
as f:
292 return (f
"GSV1CASE {r['kind']} b={r['beta']:g} g={r['gamma']:g} k={r['k']} ratio={r['ratio']:g} N={r['N']} "
293 f
"{r['status']} steps={r['steps']} inc={r['inc']:.1e} err={r['err']:.3e} "
294 f
"at(wall={r['at_walldist']:g},xi={r['at_xi']:.2f}) {r['secs']}s")
298 kinds, ratios = SETS[a.set]
299 Ns = [int(v)
for v
in a.N.split(
",")]
301 keys = [(kd, b, g, k, r, n)
for n
in Ns
for r
in ratios
for kd
in kinds
302 for b
in ANGLES
for g
in ANGLES
for k
in range(8)]
303 todo = [kk
for kk
in keys
if kk
not in done]
304 print(f
"GSV1RUN set={a.set} N={a.N} total={len(keys)} todo={len(todo)}", flush=
True)
305 with Pool(a.procs)
as pool, open(a.out,
"a")
as f:
306 for r
in pool.imap_unordered(run_case, todo, chunksize=1):
307 f.write(json.dumps(r) +
"\n")
309 print(
line(r), flush=
True)
310 print(
"EXIT", flush=
True)
314 x, y = np.log(1.0 / np.array(Ns, float)), np.log(np.maximum(np.array(es, float), 1e-300))
315 return float(np.polyfit(x, y, 1)[0])
320 for name, (kinds, ratios)
in SETS.items():
322 exact_thr = {
"couette": 1e-10,
"extension": 1e-9}.get(kd)
324 for b, g
in itertools.product(ANGLES, ANGLES):
325 rows = {k: sorted((n, res[(kd, b, g, k, r, n)])
for n
in (24, 32, 48, 64)
326 if (kd, b, g, k, r, n)
in res)
for k
in range(8)}
327 if not any(rows.values()):
329 Ns = sorted({n
for v
in rows.values()
for n, _
in v})
330 bad = [rr[
"status"]
for v
in rows.values()
for _, rr
in v
if rr[
"status"] !=
"ok"]
331 full = Ns == [24, 32, 48, 64]
and all(len(v) == len(Ns)
for v
in rows.values())
332 orders, exact_all = [],
True
333 for v
in rows.values():
334 es = [rr[
"err"]
for _, rr
in v]
335 exact_all &= exact_thr
is not None and all(e <= exact_thr
for e
in es)
337 orders.append(
lsorder([n
for n, _
in v], es))
338 env = [max(res[(kd, b, g, k, r, n)][
"err"]
for k
in range(8)
if (kd, b, g, k, r, n)
in res)
340 envo =
lsorder(Ns, env)
if len(Ns) >= 2
else float(
"nan")
341 if exact_thr
is not None and kd ==
"extension":
343 elif exact_thr
is not None:
344 ok = exact_all
or (len(Ns) >= 2
and envo >= 1.8)
346 ok = len(Ns) >= 2
and envo >= 1.8
347 verdict = (
"PASS" if ok
else "MISS")
if (full
and not bad)
else "NOT_JUDGED(partial)"
349 verdict += f
" status={','.join(sorted(set(bad)))}"
350 print(f
"{name.upper()} {kd} ratio={r:g} b={b:g} g={g:g} N={','.join(map(str, Ns))} "
351 f
"{'exact' if exact_all else 'not-exact'} min_offset_order="
352 f
"{min(orders) if orders else float('nan'):.2f} env={','.join(f'{e:.2e}' for e in env)} "
353 f
"env_order={envo:.2f} envN2={','.join(f'{e * n * n:.3g}' for e, n in zip(env, Ns))} "
360NORMALS = ((1, 0, 0), (2, 1, 0), (1, 1, 0), (0, 1, 2), (1, 0, 1), (2, 1, 1), (1, 2, 1), (1, 1, 2), (1, 1, 1))
361TANG_CP = {(1, 0, 0): (0, 1, 0), (2, 1, 0): (-1, 2, 0), (1, 1, 0): (-1, 1, 0), (0, 1, 2): (0, -2, 1),
362 (1, 0, 1): (-1, 0, 1), (2, 1, 1): (-1, 2, 0), (1, 2, 1): (2, -1, 0), (1, 1, 2): (1, -1, 0),
363 (1, 1, 1): (1, -1, 0)}
365 "gsv1p": ((
"layered",), (1e-2, 1e2)),
366 "gsv1dp": ((
"layered",), (1e-3, 1e3)),
367 "gsv1cp": ((
"along",
"along+layered"), (1e-2, 1e2)),
370PCAP, PRTOL = 20000, 1e-13
377MOM_CAP, MOM_UTOL = 200000, 1e-15
378DEF_MOM_ITERS, DEF_MOM_RES = 200, -1.0
385 global MOM_UTOL, MOM_FIXED
387 MOM_FIXED = int(fixed)
393 s.diagnostics.set_velocity_solver(
"gauss_seidel")
395 s.diagnostics.set_velocity_solver_params(MOM_FIXED, 0.0, 2)
397 s.diagnostics.set_velocity_solver_params(MOM_CAP, MOM_UTOL, 2)
398 s.set_velocity_residual_tolerance(0.0)
402 s.diagnostics.set_velocity_solver(
"auto")
403 s.diagnostics.set_velocity_solver_params(DEF_MOM_ITERS, 0.0, 2)
404 s.set_velocity_residual_tolerance(DEF_MOM_RES)
408 """The reported production-default step from the certified state xs: max|S_def(xs) - xs|_u / max|xs_u|."""
412 return float(np.max(np.abs((y - xs)[:nu]))) / max(float(np.max(np.abs(xs[:nu]))), 1e-300)
417GM_RESTART, GM_CAP = 60, 3000
418Pl = np.polynomial.Polynomial
422 """Periodic layered shear profile U(r), r = (xi - o) mod P, phase A on [0, a), B on [a, P):
423 mu_k U'' = -q_k, U and mu U' continuous (periodic), mean of U over a period removed. Also V,
424 W0: V(r) = int_0^r U (periodic), W0(r) = int_0^r (V - Vbar) (periodic), for exact face
425 averages by double differences (the linear part Vbar*xi of the second antiderivative cancels)."""
428 self.
P, self.
a, self.
o, self.
mu = P, a, o, (muA, muB)
432 UA = (tA / muA).integ()
433 tB =
Pl([tA(a) + qB * a, -qB])
434 UB = (tB / muB).integ()
435 return UA, UB + (UA(a) - UB(a))
439 t0 = -B0(P) / (B1(P) - B0(P))
441 mean = ((UA.integ()(a) - UA.integ()(0.0)) + (UB.integ()(P) - UB.integ()(a))) / P
442 UA, UB = UA - mean, UB - mean
445 VB = VB + (VA(a) - VB(a))
446 Vbar = (VA.integ()(a) + VB.integ()(P) - VB.integ()(a)) / P
447 WA = (VA - Vbar).integ()
448 WB = (VB - Vbar).integ()
449 WB = WB + (
WA(a) - WB(a))
450 self.
U, self.
V, self.
W = (UA, UB), (VA - 0.0, VB), (WA, WB)
454 r = np.mod(np.asarray(xi, float) - self.
o, self.
P)
455 return np.where(r < self.
a, pair[0](r), pair[1](r))
458 return self.
_ev(self.
U, xi)
460 def avg(self, xi, wa, wb):
461 """E[U(xi + Y + Z)], Y, Z centred uniforms of widths |wa|, |wb| (exact)."""
462 a, b = abs(wa), abs(wb)
468 return (self.
_ev(self.
V, xi + a / 2) - self.
_ev(self.
V, xi - a / 2)) / a
469 W =
lambda z: self.
_ev(self.
W, z)
470 return (
W(xi + (a + b) / 2) -
W(xi + (a - b) / 2) -
W(xi - (a - b) / 2) +
W(xi - (a + b) / 2)) / (a * b)
474 """Exact cell volume fraction of {(n.x - s0 - o) mod P < a} on the N^3 unit grid."""
476 lo, hi = h * sum(min(v, 0.0)
for v
in n), h * sum(max(v, 0.0)
for v
in n)
477 C = np.zeros((N, N, N))
478 for i, j, k
in itertools.product(range(N), repeat=3):
479 x0 = np.array([i, j, k], float) * h
480 base = float(n @ x0) - s0
481 F =
lambda c:
cube_frac(n, (c - base) / h)
483 for q
in range(int(math.floor((base + lo - o) / P)) - 1, int(math.ceil((base + hi - o) / P)) + 1):
485 tot +=
F(c0 + a) -
F(c0)
486 C[i, j, k] = min(1.0, max(0.0, tot))
492 g = (np.arange(N) + 0.5) * h
493 axes = [g.copy(), g.copy(), g.copy()]
494 axes[c] = np.arange(N) * h
495 return np.meshgrid(*axes, indexing=
"ij")
499 """The solver's face density (face_props.hpp idiag): the mean of the two cells, periodic."""
500 return [0.5 * (rho + np.roll(rho, 1, axis=c))
for c
in range(3)]
504 """One periodic case: kind in layered | along | along+layered; m the integer normal."""
507 self.
kind, self.
m, self.
k, self.
ratio, self.
N = kind, tuple(m), k, ratio, N
508 mv = np.array(m, float)
509 self.
n = mv / np.linalg.norm(mv)
510 self.
P = 1.0 / np.linalg.norm(mv)
512 self.
s0 = float(self.
n @ np.full(3, 0.5)) + k / 8.0 * self.
h
514 if kind ==
"layered":
515 self.
a, self.
o = 3.0 * self.
P / 8.0, 0.0
518 self.
a, self.
o = self.
P / 2.0, self.
P / 4.0
519 self.
rhoA = RHO_A_LAYERED
if kind ==
"along+layered" else 1.0
522 t = np.array(TANG_CP[self.
m], float)
523 self.
tc = t / np.linalg.norm(t)
524 self.
ka, self.
kb = 2 * math.pi * np.linalg.norm(t), 2 * math.pi * np.linalg.norm(mv)
528 """X: (..., 3) points -> (..., 3) velocity."""
529 eta, sp = X @ self.
tc, X @ self.
n - self.
s0
530 a, b = self.
ka, self.
kb
531 A = -a * np.sin(a * eta) * np.cos(b * sp)
532 B = b * np.cos(a * eta) * np.sin(b * sp)
533 return A[...,
None] * self.
n + B[...,
None] * self.
tc
536 """The force divided by the phase viscosity: f_k = mu_k F."""
537 eta, sp = X @ self.
tc, X @ self.
n - self.
s0
538 a, b = self.
ka, self.
kb
539 Fn = a * (b * b - a * a) * np.sin(a * eta) * np.cos(b * sp)
540 Ft = b * (3 * a * a + b * b) * np.cos(a * eta) * np.sin(b * sp)
541 return Fn[...,
None] * self.
n + Ft[...,
None] * self.
tc
544 eta, sp = X @ self.
tc, X @ self.
n - self.
s0
545 return 2.0 * mu * self.
ka * self.
kb * np.sin(self.
ka * eta) * np.sin(self.
kb * sp)
548 r = np.mod(X @ self.
n - self.
s0 - self.
o, self.
P)
552 """C, the exact face averages (3, N, N, N) before the gauge, the cell force F_cell (3,
553 N,N,N) with g = 1 (layered part) or unit amplitude (along part), and the Layered."""
554 N, h = self.
N, self.
h
557 rbar = float(np.mean(rho))
558 ex = np.zeros((3, N, N, N))
559 force = np.zeros((3, N, N, N))
561 if self.
kind in (
"layered",
"along+layered"):
562 phi = self.
a / self.
P
563 rbar_c = phi * self.
rhoA + (1 - phi) * self.
rhoB
567 xi = self.
n[0] * X[0] + self.
n[1] * X[1] + self.
n[2] * X[2] - self.
s0
568 w = [self.
n[b] * h
for b
in range(3)
if b != c]
569 ex[c] += self.
t1[c] * lay.avg(xi, w[0], w[1])
570 force += ((rho - rbar)[
None] * self.
t1[:,
None,
None,
None])
571 if self.
kind in (
"along",
"along+layered"):
572 gx, gw = np.polynomial.legendre.leggauss(4)
575 bb = [b
for b
in range(3)
if b != c]
576 acc = np.zeros((N, N, N, 3))
577 for (p, wp), (q, wq)
in itertools.product(zip(gx, gw), zip(gx, gw)):
579 Y[..., bb[0]] += 0.5 * h * p
580 Y[..., bb[1]] += 0.5 * h * q
581 acc += 0.25 * wp * wq * self.
along_u(Y)
583 Xc = np.stack(np.meshgrid(*([(np.arange(N) + 0.5) * h] * 3), indexing=
"ij"), axis=-1)
584 muC = self.
muB + (self.
muA - self.
muB) * C
585 force += np.moveaxis(muC[...,
None] * self.
along_F(Xc), -1, 0)
586 return C, rho, rbar, ex, force, lay
590 return np.stack([ex[c] - float(np.sum(rf[c] * ex[c]) / np.sum(rf[c]))
for c
in range(3)])
597 """G-SV12 owner-tie census (WO-9.4, study only): max over steps of 'tied_edges' and 'max_tie_spread', min
598 of 'min_untied_gap'; 'tie_reads' counts the steps read (0 on a build without the owner-set keys). With the
599 eighth-pass ramp (§5.9): max over steps of 'blended_edges' and of (tied + blended) / band_cells -- an upper
600 proxy for the §5.9 (b) trigger 4 fraction of band EDGES (a band cell carries several band edges)."""
601 return {
"tied_max": 0,
"spread_max": 0.0,
"gap_min": float(
"inf"),
"tie_reads": 0,
"blended_max": 0,
606 """Read the census after one step into acc (rank-local keys: summed / max / min over ranks under comm)."""
608 if not hasattr(dg,
"vof_viscous_interface_census"):
610 c = dg.vof_viscous_interface_census()
611 if "tied_edges" not in c:
613 t, sp, g = int(c[
"tied_edges"]), float(c[
"max_tie_spread"]), float(c[
"min_untied_gap"])
614 bl, nb = int(c.get(
"blended_edges", 0)), int(c[
"band_cells"])
616 from mpi4py
import MPI
617 t, sp, g = comm.allreduce(t), comm.allreduce(sp, op=MPI.MAX), comm.allreduce(g, op=MPI.MIN)
618 bl, nb = comm.allreduce(bl), comm.allreduce(nb)
619 acc[
"blended_max"] = max(acc.get(
"blended_max", 0), bl)
620 acc[
"tb_frac_max"] = max(acc.get(
"tb_frac_max", 0.0), (t + bl) / max(nb, 1))
621 acc[
"tied_max"] = max(acc[
"tied_max"], t)
622 acc[
"spread_max"] = max(acc[
"spread_max"], sp)
623 acc[
"gap_min"] = min(acc[
"gap_min"], g)
624 acc[
"tie_reads"] += 1
628 if "tie_reads" not in r:
630 return (f
"tied={r['tied_max']} spread={r['spread_max']:.1e} gap={r['gap_min']:.1e} reads={r['tie_reads']}"
631 f
" blended={r.get('blended_max', 'n/a')} tb/band={r.get('tb_frac_max', float('nan')):.3f}")
635 """S: x = (u, v, w, p) -> one production step, colour frozen (set_vof(C0) after the step); p
636 through get_field/set_field("p") in internal units, its mean removed on input and output."""
639 self.
s, self.
C0, self.
shp, self.
n = s, np.asfortranarray(C0), (N, N, N), N**3
646 self.
rfs = [float(np.sum(f))
for f
in self.
rf]
if self.
rf is not None else None
649 """Remove each velocity component's rho_F-weighted mean (periodic box only) and p's mean."""
652 y, n = x.copy(), self.
n
654 a = y[c * n:(c + 1) * n].reshape(self.
shp, order=
"F")
655 a -= float(np.sum(self.
rf[c] * a)) / self.
rfs[c]
656 y[c * n:(c + 1) * n] = a.ravel(order=
"F")
657 y[3 * n:] -= y[3 * n:].
mean()
661 s, n = self.
s, self.
n
663 s.set_velocity(c, np.asfortranarray(x[c * n:(c + 1) * n].reshape(self.
shp, order=
"F")))
665 s.set_field(
"p", np.asfortranarray((p - p.mean()).reshape(self.
shp, order=
"F")))
667 cin = float(s.vof_max_courant())
681 self.
max_pit = max(self.
max_pit, int(dg.last_pressure_iterations()))
682 self.
max_msw = max(self.
max_msw, int(dg.last_step_timers()[
"momentum_sweeps"]))
684 U = [np.asarray(a)
for a
in (s.get_u(), s.get_v(), s.get_w())]
685 if track
and self.
rf is not None:
686 um = max(float(np.max(np.abs(a)))
for a
in U)
688 self.
mom = max(self.
mom, abs(float(np.sum(self.
rf[c] * U[c]))) / (float(np.sum(self.
rf[c])) * um))
689 P = np.asarray(s.get_field(
"p")).ravel(order=
"F")
690 return np.concatenate([a.ravel(order=
"F")
for a
in U] + [P - P.mean()])
694 """Restarted GMRES(m) on (I - G) x = b, G v = S(v) - S(0). Every cycle starts with a PLAIN
695 production step: r = S(x) - x is both the residual and the certificate (increment of u <=
696 tol * max|u|). Returns (state after the certifying step, status, steps, increment, cycles).
697 Periodic box: I - G is singular on the uniform-velocity modes (the momentum invariant), and the
698 solver's round-off-level momentum error would put a component there that GMRES amplifies by
699 1/lambda; the Krylov vectors are therefore kept in the gauge subspace (rho_F-weighted mean of
700 each velocity component removed), as p is kept mean-free. The certificate is the unprojected
701 plain-step increment.
703 WO-C5 (§6.8 C): an evaluation the colour-CFL guard refuses (the tail advection of the step's
704 OUTPUT) is re-evaluated by affinity at sigma' = sigma * 0.01 / CFL_out (sigma = 1 for a restart step,
705 the Krylov scaling for a matvec): S(sigma x) -> S0 + (S(sigma' x) - S0) sigma / sigma'. Bitwise no-op
706 for every evaluation that did not refuse. The certifying step stays a plain production step: a
707 restart step that refuses can never certify, and if its rescaled increment is within tol the row is
708 NOT CONVERGED ('certify_refused'). S(0) carries no amplitude to rescale: its refusal is not retried."""
710 S0 = S(np.zeros_like(x0))
711 x, cycles = x0.copy(), 0
715 Sx = S(x, track=
True)
717 sg = 0.01 / S.refused_cfl
720 Sx = S0 + (S(sg * x) - S0) / sg
722 inc = float(np.max(np.abs(r[:nu]))) / max(float(np.max(np.abs(x[:nu]))), 1e-300)
723 if not math.isfinite(inc):
724 return Sx,
"blowup", S.steps, inc, cycles
726 return Sx, (
"certify_refused" if refused
else "ok"), S.steps, inc, cycles
728 return Sx,
"not_converged", S.steps, inc, cycles
730 beta = float(np.linalg.norm(r))
732 H = np.zeros((m + 1, m))
733 cs, sn = np.zeros(m), np.zeros(m)
741 sc = umax / max(float(np.max(np.abs(v[:nu]))), float(np.max(np.abs(v))), 1e-300)
745 sc = sc * 0.01 / S.refused_cfl
748 w = gauge(v - (y - S0) / sc)
750 for i
in range(j + 1):
751 hij = float(V[i] @ w)
754 H[j + 1, j] = float(np.linalg.norm(w))
756 t = cs[i] * H[i, j] + sn[i] * H[i + 1, j]
757 H[i + 1, j] = -sn[i] * H[i, j] + cs[i] * H[i + 1, j]
759 d = math.hypot(H[j, j], H[j + 1, j])
760 cs[j], sn[j] = H[j, j] / d, H[j + 1, j] / d
762 H[j, j], H[j + 1, j] = d, 0.0
763 g[j + 1], g[j] = -sn[j] * g[j], cs[j] * g[j]
765 if hn <= 1e-300
or abs(g[j + 1]) <= 0.1 * tol * umax:
770 y = np.linalg.solve(np.triu(H[:kk, :kk]), g[:kk])
771 x = x + sum(yi * V[i]
for i, yi
in enumerate(y))
778 Sx = S(x, track=
True)
779 inc = float(np.max(np.abs((Sx - x)[:nu]))) / max(float(np.max(np.abs(x[:nu]))), 1e-300)
780 if not math.isfinite(inc):
781 return Sx,
"blowup", S.steps, inc
783 return Sx,
"ok", S.steps, inc
785 return Sx,
"max_steps", S.steps, inc
790 pset, kind, m, k, ratio, N, mode = key
791 os.environ.setdefault(
"OMP_PROC_BIND",
"false")
795 cs =
PCase(kind, m, k, ratio, N)
797 C, rho, rbar, ex, force, lay = cs.build()
798 hi_A = cs.muA > cs.muB
799 mu_hi, rho_hi = (cs.muA, cs.rhoA)
if hi_A
else (cs.muB, cs.rhoB)
800 dt = D_HI * h * h * rho_hi / mu_hi
801 amp = 0.01 * h / (dt * float(np.max(np.abs(ex))))
802 ex, force = amp * ex, amp * force
803 exg = cs.gauge(ex, rho)
804 s =
pf.Solver((N, N, N), extent=(1.0, 1.0, 1.0))
808 s.set_pressure_geometry(np.full((N, N, N), 1.0, order=
"F"))
810 s.set_vof(np.asfortranarray(C))
811 s.set_property_model(
"mu",
"linear",
"C", [cs.muB, cs.muA - cs.muB])
812 varrho = cs.rhoA != cs.rhoB
814 s.set_property_model(
"rho",
"linear",
"C", [cs.rhoB, cs.rhoA - cs.rhoB])
815 s.enable_cell_force()
816 if kind ==
"layered":
818 s.set_property_model(
"force_" +
"xyz"[c],
"linear",
"rho",
819 [-rbar * amp * cs.t1[c], amp * cs.t1[c]])
821 fi = s.unit_scales[
"force_density_to_internal"]
823 s.set_field(
"force_" +
"xyz"[c], np.asfortranarray(np.atleast_1d(fi)[c
if np.size(fi) == 3
else 0] * force[c]))
824 s.set_advection(
False)
826 s.set_pressure_chebyshev(
True, PCAP, PRTOL)
828 s.set_pressure_pcg(
True, PCAP, PRTOL)
829 s.set_vof_viscous_interface(mode)
831 s.update_properties()
832 fsum = max(abs(float(np.sum(np.asarray(s.get_field(
"force_" + a)))))
for a
in "xyz")
833 fmax = max(float(np.max(np.abs(np.asarray(s.get_field(
"force_" + a)))))
for a
in "xyz")
836 x0 = np.concatenate([exg[c].ravel(order=
"F")
for c
in range(3)] + [np.zeros(N**3)])
837 U = float(np.max(np.abs(exg)))
838 if steady ==
"gmres":
839 xs, status, steps, inc, cycles =
gmres_steady(S, x0, nu, U)
843 vsolver = s.diagnostics.velocity_solver()
845 uh = np.stack([xs[c * N**3:(c + 1) * N**3].reshape((N, N, N), order=
"F")
for c
in range(3)])
846 e = np.abs(uh - exg) / U
847 uhg = cs.gauge(uh, rho)
848 err_g = float(np.max(np.abs(uhg - exg))) / U
849 am = np.unravel_index(int(np.argmax(e)), e.shape)
851 rr = float(np.mod(sum(cs.n[q] * Xf[q][am[1:]]
for q
in range(3)) - cs.s0 - cs.o, cs.P))
852 dist = min(rr, abs(rr - cs.a), cs.P - rr) / h
853 out = {
"set": pset,
"kind": kind,
"m": list(m),
"k": k,
"ratio": ratio,
"N": N,
"mode": mode,
854 "steady": steady,
"status": status,
"steps": steps,
"cycles": cycles,
"inc": inc,
855 "err": float(np.max(e)),
"err_gauged": err_g,
"at_comp": int(am[0]),
"at_cell": [int(v)
for v
in am[1:]],
856 "at_xi": float(dist),
"mom": S.mom,
"force_sum_rel": fsum / max(fmax, 1e-300),
857 "max_p_it": S.max_pit,
"max_momentum_sweeps": S.max_msw,
"secs": round(time.time() - t0, 1),
858 "max_momentum_residual": S.max_mres,
"converged_momentum":
True,
"mom_utol": MOM_UTOL,
859 "velocity_solver": vsolver,
"inc_default_step": inc_def,
"rescaled": S.rescaled,
"max_gain": S.max_gain, **S.tie}
861 out[
"mom_fixed"] = MOM_FIXED
868 """G-SV1W (§11): the walled Couette contact check, option-A BCs with wall-face-AVERAGED data
869 (each tangential component's Dirichlet value is its average over the h-square of the wall plane
870 centred at its node), steady state by WO-6s, error binned by wall distance."""
871 pset, kind, beta, gamma, k, ratio, N, mode = key
872 os.environ.setdefault(
"OMP_PROC_BIND",
"false")
876 cs =
Case(kind, beta, gamma, k, ratio, N)
878 C = np.zeros((N, N, N))
879 ex = np.zeros((3, N, N, N))
880 for i, j, kk
in itertools.product(range(N), repeat=3):
881 xc = np.array([i, j, kk], float) * h
882 C[i, j, kk] =
cube_frac(cs.n, (cs.s - cs.n @ (xc - cs.c)) / h)
883 for comp
in range(3):
884 x = (np.array([i, j, kk], float) + 0.5) * h
886 ex[comp, i, j, kk] = cs.face_avg(comp, x, tuple(a
for a
in range(3)
if a != comp))
887 dt = D_HI * h * h / max(cs.muA, cs.muB)
888 amp = 0.01 * h / (dt * float(np.max(np.abs(ex))))
890 s =
pf.Solver((N, N, N), extent=(1.0, 1.0, 1.0))
893 b, c = (a + 1) % 3, (a + 2) % 3
895 prof = np.zeros((N, N, 3))
900 x[b], x[c] = (ib + 0.5) * h, (ic + 0.5) * h
901 prof[ib, ic, a] = cs.face_avg(a, x, (b, c))
904 prof[ib, ic, b] = cs.face_avg(b, xb, (b, c))
907 prof[ib, ic, c] = cs.face_avg(c, xc, (b, c))
908 s.set_domain_bc_profile((
"-" if side == 0
else "+") +
"xyz"[a], np.ascontiguousarray(amp * prof))
910 s.set_mu(max(cs.muA, cs.muB))
911 s.set_pressure_geometry(np.full((N, N, N), 1.0, order=
"F"))
913 s.set_vof(np.asfortranarray(C))
914 s.set_property_model(
"mu",
"linear",
"C", [cs.muB, cs.muA - cs.muB])
915 s.set_advection(
False)
916 s.set_pressure_pcg(
True, PCAP, PRTOL)
917 s.set_vof_viscous_interface(mode)
921 x0 = np.concatenate([ex[c].ravel(order=
"F")
for c
in range(3)] + [np.zeros(N**3)])
922 U = float(np.max(np.abs(ex)))
923 xs, status, steps, inc, cycles =
gmres_steady(S, x0, nu, U)
925 uh = np.stack([xs[c * N**3:(c + 1) * N**3].reshape((N, N, N), order=
"F")
for c
in range(3)])
926 e = np.abs(uh - ex) / U
928 return {
"set": pset,
"kind": kind,
"beta": beta,
"gamma": gamma,
"k": k,
"ratio": ratio,
"N": N,
929 "mode": mode,
"status": status,
"steps": steps,
"cycles": cycles,
"inc": inc,
"err": float(np.max(e)),
930 "err_wall1": float(np.max(e[wd <= 1.0])),
"err_interior": float(np.max(e[wd > 1.0])),
931 "max_p_it": S.max_pit,
"max_momentum_sweeps": S.max_msw,
"converged_momentum":
True,
932 "rescaled": S.rescaled,
"max_gain": S.max_gain, **({
"mom_fixed": MOM_FIXED}
if MOM_FIXED
else {}),
933 "mom_utol": MOM_UTOL,
"inc_default_step": inc_def,
"secs": round(time.time() - t0, 1), **S.tie}
940 if r[
"set"] ==
"gsv1w":
941 return (r[
"set"], r[
"kind"], r[
"beta"], r[
"gamma"], r[
"k"], r[
"ratio"], r[
"N"], r[
"mode"])
942 return (r[
"set"], r[
"kind"], tuple(r[
"m"]), r[
"k"], r[
"ratio"], r[
"N"], r[
"mode"], r.get(
"steady",
"gmres"))
947 if os.path.exists(path):
948 with open(path)
as f:
958 geo = (f
"b={r['beta']:g} g={r['gamma']:g}" if r[
"set"] ==
"gsv1w" else f
"m={''.join(map(str, r['m']))}")
959 extra = (f
"err_wall1={r['err_wall1']:.3e} err_int={r['err_interior']:.3e}" if r[
"set"] ==
"gsv1w" else
960 f
"mom={r['mom']:.1e} fsum={r['force_sum_rel']:.1e} at_xi/h={r['at_xi']:.2f}")
961 return (f
"GSV1CASE {r['set']} {r['kind']} {geo} k={r['k']} ratio={r['ratio']:g} N={r['N']} {r['mode']} "
962 f
"{r.get('steady', 'gmres')} {r['status']} steps={r['steps']} cycles={r['cycles']} inc={r['inc']:.1e} "
963 f
"err={r['err']:.3e} err_g={r.get('err_gauged', float('nan')):.3e} {extra} max_p_it={r['max_p_it']} max_mres={r.get('max_momentum_residual', -1):.1e} {tie_str(r)} {r['secs']}s")
967 if key[0] ==
"gsv1w":
969 if key[7] !=
"march":
972 except RuntimeError
as ex:
975 pset, kind, m, k, ratio, N, mode = key[:7]
976 return {
"set": pset,
"kind": kind,
"m": list(m),
"k": k,
"ratio": ratio,
"N": N,
"mode": mode,
977 "steady": key[7],
"status":
"step_error",
"error": str(ex)[:200],
"steps": -1,
"cycles": -1,
978 "inc": nan,
"err": nan,
"err_gauged": nan,
"at_xi": nan,
"mom": nan,
"force_sum_rel": nan,
979 "max_p_it": -1,
"max_momentum_residual": nan,
"secs": 0.0,
"converged_momentum":
True,
980 "mom_utol": MOM_UTOL,
"inc_default_step": nan}
981 rg, ug =
run_pcase(key[:7], steady=
"gmres", want_state=
True)
982 rm, um =
run_pcase(key[:7], steady=
"march", want_state=
True)
983 cs =
PCase(*key[1:6])
984 C, rho, _, ex, _, _ = cs.build()
985 U = float(np.max(np.abs(ug)))
986 rm[
"diff_vs_gmres"] = [float(np.max(np.abs(um - ug))) / U,
987 float(np.max(np.abs(cs.gauge(um, rho) - cs.gauge(ug, rho)))) / U]
992 Ns = [int(v)
for v
in a.N.split(
",")]
994 keys = [(
"gsv1w",
"couette", 22.5, 22.5, 0, 1e-2, n, md)
for n
in Ns
for md
in (
"sharp",
"averaged")]
995 elif a.set ==
"pilot":
998 keys = [(
"gsv1p",
"layered", m, 3, r, n, a.mode,
"gmres")
for n
in (24, 48)
for r
in (1e-2, 1e2)
999 for m
in ((1, 0, 0), (2, 1, 0), (2, 1, 1))]
1000 keys += [(
"gsv1p",
"layered", (2, 1, 0), 3, 1e-2, 24, a.mode,
"march"),
1001 (
"gsv1p",
"layered", (2, 1, 1), 3, 1e2, 24, a.mode,
"march")]
1003 kinds, ratios = PSETS[a.set]
1004 keys = [(a.set, kd, m, k, r, n, a.mode,
"gmres")
for n
in Ns
for r
in ratios
for kd
in kinds
1005 for m
in NORMALS
for k
in range(8)]
1006 done = {k: r
for k, r
in pload(a.out).items()
if r.get(
"mom_utol", 1.0) <= a.mom_utol}
1007 todo = [kk
for kk
in keys
if kk
not in done]
1008 print(f
"GSV1RUN set={a.set} N={a.N} total={len(keys)} todo={len(todo)} mom_utol={a.mom_utol:g}", flush=
True)
1009 with Pool(a.procs, initializer=_set_mom_utol, initargs=(a.mom_utol, a.mom_fixed))
as pool, open(a.out,
"a")
as f:
1010 for r
in pool.imap_unordered(_run_any, todo, chunksize=1):
1011 f.write(json.dumps(r) +
"\n")
1013 print(
pline(r), flush=
True)
1014 print(
"EXIT", flush=
True)
1021 void = [k
for k, r
in res.items()
if not (r.get(
"converged_momentum")
is True and r.get(
"mom_utol", 1.0) <= MOM_UTOL)]
1023 print(f
"GSV1-VOID {len(void)} rows without the §6.6 converged momentum solve dropped (not judged)")
1024 res = {k: r
for k, r
in res.items()
if k
not in void}
1025 pr = [r
for r
in res.values()
if r[
"set"] !=
"gsv1w" and r[
"status"] ==
"ok"]
1027 mm = max(r[
"mom"]
for r
in pr)
1028 nbad = sum(1
for r
in pr
if not r[
"mom"] <= 1e-13)
1029 print(f
"WO6Q-INVARIANCE cases={len(pr)} max sum rho_F u_c/(sum rho_F max|u|)={mm:.2e} (<= 1e-13) "
1030 f
"over={nbad} {'PASS' if nbad == 0 else 'MISS'}")
1031 ok_rows = [r
for r
in res.values()
if r[
"status"] ==
"ok"]
1032 idf = [r.get(
"inc_default_step", float(
"nan"))
for r
in ok_rows]
1034 big = [r
for r, v
in zip(ok_rows, idf)
if not v <= 1e-11]
1035 print(f
"GSV1-DEFAULT-STEP (reported) max increment/max|u|={float(np.nanmax(idf)):.2e} over 1e-11: {len(big)}")
1037 print(f
" default-step increment {r.get('inc_default_step', float('nan')):.2e}: {pline(r)[9:120]}")
1039 capped =
lambda rows: sum(1
for r
in rows
if r.get(
"max_momentum_sweeps", 0) >= MOM_CAP)
1040 print(f
"GSV1-MOMCAP rows with a momentum component at the {MOM_CAP}-sweep cap: {capped(res.values())}/{len(res)} "
1041 f
"(reported, not voiding; §6.8 A)")
1042 nc = [r
for r
in res.values()
if r[
"status"] !=
"ok"]
1044 print(f
"GSV1-NOTCONV {pline(r)[9:160]}")
1046 gm = [r
for r
in res.values()
if r[
"set"] ==
"gsv1p" and r.get(
"steady") ==
"gmres"]
1047 for r
in res.values():
1048 if r.get(
"steady") ==
"march":
1049 g = res.get(
pkey(dict(r, steady=
"gmres")))
1051 d = r.get(
"diff_vs_gmres")
1052 print(f
"GSV1-PILOT march-agreement m={''.join(map(str, r['m']))} ratio={r['ratio']:g} N={r['N']}: "
1053 f
"err gmres {g['err']:.6e} march {r['err']:.6e}; max|u_march - u_gmres|/max|u| raw "
1054 f
"{d[0] if d else float('nan'):.1e} gauged {d[1] if d else float('nan'):.1e} (<= 1e-11) "
1055 f
"(steps gmres {g['steps']} march {r['steps']} {r['status']})")
1057 st = sorted(r[
"steps"]
for r
in gm)
1058 print(f
"GSV1-STEPS gmres cases={len(gm)} steps min/median/max={st[0]}/{st[len(st) // 2]}/{st[-1]} "
1059 f
"not_ok={sum(1 for r in gm if r['status'] != 'ok')}")
1060 for name, (kinds, ratios)
in PSETS.items():
1063 for mode
in (
"sharp",
"averaged"):
1065 rows = {k: sorted((n, res[(name, kd, m, k, r, n, mode,
"gmres")])
for n
in (24, 32, 48, 64)
1066 if (name, kd, m, k, r, n, mode,
"gmres")
in res)
for k
in range(8)}
1067 if not any(rows.values()):
1069 Ns = sorted({n
for v
in rows.values()
for n, _
in v})
1070 bad = [rr[
"status"]
for v
in rows.values()
for _, rr
in v
if rr[
"status"] !=
"ok"]
1071 full = Ns == [24, 32, 48, 64]
and all(len(v) == 4
for v
in rows.values())
1072 orders = [
lsorder([n
for n, _
in v], [rr[
"err"]
for _, rr
in v])
for v
in rows.values()
1074 env = [max(rr[
"err"]
for v
in rows.values()
for n2, rr
in v
if n2 == n)
for n
in Ns]
1075 envo =
lsorder(Ns, env)
if len(Ns) >= 2
else float(
"nan")
1076 verdict = (
"PASS" if envo >= 1.8
else "MISS")
if (full
and not bad)
else "NOT_JUDGED(partial)"
1078 verdict += f
" status={','.join(sorted(set(bad)))}"
1079 print(f
"{name.upper()} {kd} ratio={r:g} m={''.join(map(str, m))} {mode} N={','.join(map(str, Ns))} "
1080 f
"min_offset_order={min(orders) if orders else float('nan'):.2f} "
1081 f
"env={','.join(f'{e:.2e}' for e in env)} env_order={envo:.2f} "
1082 f
"envN2={','.join(f'{e * n * n:.3g}' for e, n in zip(env, Ns))} "
1083 f
"momcap={capped([rr for v in rows.values() for _, rr in v])}/{sum(len(v) for v in rows.values())} "
1085 w = {(r[
"N"], r[
"mode"]): r
for r
in res.values()
if r[
"set"] ==
"gsv1w"}
1087 Ns = sorted({n
for n, _
in w})
1088 ok = all((n,
"sharp")
in w
and (n,
"averaged")
in w
and w[(n,
"sharp")][
"status"] ==
"ok"
1089 and w[(n,
"averaged")][
"status"] ==
"ok" and w[(n,
"sharp")][
"err_wall1"] <= w[(n,
"averaged")][
"err_wall1"]
1091 print(
"GSV1W " +
" ".join(f
"N={n}: sharp {w[(n, 'sharp')]['err_wall1']:.3e} averaged "
1092 f
"{w[(n, 'averaged')]['err_wall1']:.3e}" for n
in Ns
if (n,
'sharp')
in w
and (n,
'averaged')
in w)
1093 + f
" momcap={capped(w.values())}/{len(w)}"
1094 + f
" {'PASS' if ok and Ns == [24, 32] else ('MISS' if Ns == [24, 32] else 'NOT_JUDGED(partial)')}")
1098 """WO-6p acceptance: the manufactured fields satisfy the continuous equations and the jump
1099 conditions to <= 1e-12 at 100 random points; the exact face averages against brute-force
1100 quadrature on random faces; Layered's closure (periodic V, W0)."""
1101 rng = np.random.default_rng(1)
1102 worst = {
"along_div": 0.0,
"along_mom": 0.0,
"along_jump": 0.0,
"layered_ode": 0.0,
"layered_jump": 0.0,
1103 "layered_closure": 0.0,
"face_avg": 0.0}
1106 for ratio
in (1e-2, 1e2, 1e-3, 1e3):
1107 cs =
PCase(
"along", m, 3, ratio, 24)
1109 sc = b * (a * a + b * b) * max(1.0, ratio)
1110 for _
in range(100):
1112 J = np.array([np.imag(cs.along_u(X + 1j * eps * np.eye(3)[q])) / eps
for q
in range(3)]).T
1113 mu = cs.muA
if cs.phaseA(X)
else cs.muB
1114 gp = np.array([np.imag(cs.along_p(X + 1j * eps * np.eye(3)[q], mu)) / eps
for q
in range(3)])
1115 lap = -(a * a + b * b) * cs.along_u(X)
1116 res = mu * lap - gp + mu * cs.along_F(X)
1117 worst[
"along_div"] = max(worst[
"along_div"], abs(np.trace(J)) / (a * b))
1118 worst[
"along_mom"] = max(worst[
"along_mom"], float(np.max(np.abs(res))) / sc)
1120 Y = X - (X @ cs.n - cs.s0 - cs.P / 4 - cs.P / 2 * rng.integers(0, 2)) * cs.n
1121 Jy = np.array([np.imag(cs.along_u(Y + 1j * eps * np.eye(3)[q])) / eps
for q
in range(3)]).T
1122 Dy = 0.5 * (Jy + Jy.T)
1123 tr = [(-cs.along_p(Y, mu_) * cs.n + 2 * mu_ * Dy @ cs.n)
for mu_
in (cs.muA, cs.muB)]
1124 worst[
"along_jump"] = max(worst[
"along_jump"], float(np.max(np.abs(tr[0] - tr[1]))) / sc)
1125 for kd
in (
"layered",
"along+layered"):
1126 cl =
PCase(kd, m, 3, ratio, 24)
1128 rb = phi * cl.rhoA + (1 - phi) * cl.rhoB
1129 L =
Layered(cl.P, cl.a, cl.o, cl.muA, cl.muB, cl.rhoA - rb, cl.rhoB - rb)
1130 usc = max(float(np.max(np.abs(L.Uf(np.linspace(0, cl.P, 257))))), 1e-300)
1131 qsc = max(abs(cl.rhoA - rb), abs(cl.rhoB - rb))
1132 for r_
in rng.random(50) * cl.P:
1134 U2 = (L.U[0]
if inA
else L.U[1]).deriv(2)(r_)
1135 mu_, q_ = (cl.muA, cl.rhoA - rb)
if inA
else (cl.muB, cl.rhoB - rb)
1136 worst[
"layered_ode"] = max(worst[
"layered_ode"], abs(mu_ * U2 + q_) / qsc)
1138 jumps = [abs(UA(cl.a) - UB(cl.a)) / usc, abs(UA(0.0) - UB(cl.P)) / usc,
1139 abs(cl.muA * UA.deriv()(cl.a) - cl.muB * UB.deriv()(cl.a)) / (qsc * cl.P),
1140 abs(cl.muA * UA.deriv()(0.0) - cl.muB * UB.deriv()(cl.P)) / (qsc * cl.P)]
1141 worst[
"layered_jump"] = max(worst[
"layered_jump"], max(jumps))
1142 worst[
"layered_closure"] = max(worst[
"layered_closure"], L.closure[0] / (usc * cl.P),
1143 L.closure[1] / (usc * cl.P * cl.P))
1147 xi0 = rng.random() * cl.P
1148 wa, wb = cl.n[0] * h, cl.n[1] * h
1149 ex_ = float(L.avg(np.array(xi0), wa, wb))
1150 gx, gw = np.polynomial.legendre.leggauss(8)
1152 yy = ((np.arange(M)[:,
None] + 0.5 * (gx[
None, :] + 1)) / M - 0.5).ravel()
1153 ww = (np.tile(gw, M) / (2 * M))
1154 Y_, Z_ = np.meshgrid(yy * wa, yy * wb, indexing=
"ij")
1155 bf = float(np.sum(np.outer(ww, ww) * L.Uf(xi0 + Y_ + Z_)))
1156 worst[
"face_avg"] = max(worst[
"face_avg"], abs(ex_ - bf) / usc)
1157 ok = all(v <= 1e-12
for kk, v
in worst.items()
if kk !=
"face_avg")
and worst[
"face_avg"] <= 1e-8
1158 print(
"GSV1P-CHECK " +
" ".join(f
"{kk}={v:.1e}" for kk, v
in worst.items())
1159 + f
" {'PASS' if ok else 'MISS'} (equations/jumps <= 1e-12; face averages vs brute-force quadrature <= 1e-8,"
1160 " the quadrature's own error at a kink)")
1164 p = argparse.ArgumentParser()
1165 sp = p.add_subparsers(dest=
"cmd", required=
True)
1166 r = sp.add_parser(
"run")
1167 r.add_argument(
"--set", choices=tuple(SETS) + tuple(PSETS) + (
"gsv1w",
"pilot"), required=
True)
1168 r.add_argument(
"--N", default=
"24,32")
1169 r.add_argument(
"--procs", type=int, default=4)
1170 r.add_argument(
"--mode", choices=(
"sharp",
"averaged"), default=
"sharp")
1171 r.add_argument(
"--out", required=
True)
1174 r.add_argument(
"--converged-momentum", action=
"store_true")
1175 r.add_argument(
"--mom-utol", type=float, default=MOM_UTOL)
1176 r.add_argument(
"--mom-fixed", type=int, default=0)
1177 t = sp.add_parser(
"table")
1178 t.add_argument(
"--out", required=
True)
1179 sp.add_parser(
"check")
1180 o = sp.add_parser(
"one")
1181 o.add_argument(
"case", nargs=6)
1184 kd, b, g, k, r, n = a.case
1185 print(json.dumps(
run_case((kd, float(b), float(g), int(k), float(r), int(n)))), flush=
True)
1187 if a.cmd ==
"check":
1192 if any(k[0]
in PSETS
or k[0]
in (
"gsv1w",
"gsv1p")
for k
in res):
1198if __name__ ==
"__main__":
__init__(self, kind, beta, gamma, k, ratio, N)
face_avg(self, comp, x, axes)
__init__(self, P, a, o, muA, muB, qA, qB)
__init__(self, kind, m, k, ratio, N)
__init__(self, s, C0, N, rho=None)
__call__(self, x, track=False)
gmres_steady(S, x0, nu, umax, m=GM_RESTART, cap=GM_CAP, tol=TOL)
plain_march(S, x0, nu, cap=MAX_STEPS, tol=TOL)
run_pcase(key, steady="gmres", want_state=False)
tie_read(s, acc, comm=None)
_set_mom_utol(v, fixed=0)
default_step_increment(S, xs, nu)
layered_fractions(n, s0, P, a, o, N)
static constexpr double F
static constexpr double U
static void build(IbmSolver &s, std::size_t cells)
static double mean(const std::vector< double > &a)
static constexpr double WA