flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
gsv2.py
Go to the documentation of this file.
1"""G-SV2 -- Hadamard-Rybczynski drag of a buoyant drop in a periodic box (doc/vof_sharp_viscous_stress.md
2§6.7, fourth pass, which binds; §11 G-SV2; WO-G2).
3
4Box [0, L]^3, L = 8R (here L = 1, R = 1/8), triply periodic, isotropic h; d = 2R, d/h in
5{8, 12, 16, 24, 32}, N = 4 d/h. Phase A (C = 1) is the sphere |x - x_c| < R, x_c = (L/2, L/2, L/2), a
6cell vertex at every N. C_i is the exact z-chord average over 32 x 32 midpoint sub-columns of cell i;
7cells with all 8 corners inside (outside) the closed (open) ball are exactly 1 (0) -- with the centre
8on a vertex and R/h an integer this is exact integer arithmetic. The colour is frozen. sigma = 0;
9rho = 1 in both phases; mu = LinearMix(C), mu_out = mu_B = 1, mu_A = kappa, kappa in {1e-2, 1, 1e2}
10(kappa = 1 is the uniform-mu control of the forcing and the base scheme: 'sharp' is bitwise skipped
11there, so it is run once). Force (Boussinesq, Hasimoto): the cell field f_z = drg (C_i - phi_h),
12phi_h = mean C_i, written with set_field("force_z") in internal units; F = drg V_h, V_h = h^3 sum C_i.
13drg = 1e-3 (h/dt) 9 mu_out K_HR / (2 R^2) (colour CFL ~1e-3 at the unbounded HR speed).
14Steady Stokes (advection off) by gsv1.py's WO-6s GMRES(60) under the §6.6 rule (converged momentum on
15every step, RB-GS update stop 1e-15 = gsv1.MOM_UTOL, coordinator decision 2026-11-01; rows taken at a
16looser stop are void and rerun), from u = 0, p = 0; D_hi = mu_hi dt / (rho h^2) = 100, mu_hi = max(kappa, 1) mu_out;
17certificate 1e-12 max|u|; cap 3000 matvecs (at the cap: NOT CONVERGED, not judged).
18U_d = sum_i C_i wbar_i / sum_i C_i - <w>, wbar_i the mean of w on the -z and +z faces of cell i, <w> the
19mean over all z-faces. K = F / (6 pi mu_out U_d R_h), R_h = (3 V_h / 4 pi)^(1/3).
20PASS ('sharp', kappa = 1e-2 and 1e2): the unweighted nonlinear LS fit K(h) = K_inf + C h^p over the
21five levels, p in [0.5, 4], gives p >= 1.8 and |K_inf - K_per| / K_per <= 3 %,
22K_per = K_HR / (1 - 1.7601 K_HR phi^(1/3)), K_HR = (2 + 3 kappa) / (3 (1 + kappa)), phi = pi/384.
23kappa = 1 must pass the same criteria, else G-SV2 is NOT JUDGED (instrument or base scheme).
24Reported: K per level, the four-finest fit (12-32), 'averaged''s p and K_inf, matvecs per case.
25Acceptance before the gate (WO-G2): kappa = 1, d/h 8 and 12: sum force = 0 to 1e-14 relative,
26momentum invariant <= 1e-13, CFL <= 1.1e-3.
27
28 nice -n 10 python gsv2.py run --doh 8,12,16 [--kappa 1e-2,1,1e2] [--modes sharp,averaged] --procs 3 --out F.jsonl
29 python gsv2.py accept --out F.jsonl
30 python gsv2.py table --out F.jsonl
31"""
32import argparse
33import json
34import math
35import os
36import sys
37import time
38from multiprocessing import Pool
39
40import numpy as np
41
42HERE = os.path.dirname(os.path.abspath(__file__))
43sys.path.insert(0, HERE)
44import gsv1 # the WO-6s GMRES driver and the §6.6 momentum rule
45
46L = 1.0
47R = L / 8.0
48DOH = (8, 12, 16, 24, 32)
49KAPPAS = (1e-2, 1.0, 1e2)
50SUB = 32
51PHI = math.pi / 384.0
52
53
54def k_hr(kappa):
55 return (2.0 + 3.0 * kappa) / (3.0 * (1.0 + kappa))
56
57
58def k_per(kappa):
59 kh = k_hr(kappa)
60 return kh / (1.0 - 1.7601 * kh * PHI ** (1.0 / 3.0))
61
62
63def colour(N):
64 """Exact z-chord average over SUB x SUB midpoint sub-columns; exact 0/1 by the corner test."""
65 h = L / N
66 xc = 0.5 * L
67 off = (np.arange(SUB) + 0.5) / SUB * h
68 g = (np.arange(N)[:, None] * h + off[None, :]).ravel() # sub-column midpoints, cell-major
69 X, Y = np.meshgrid(g, g, indexing="ij")
70 s = np.sqrt(np.maximum(R * R - (X - xc) ** 2 - (Y - xc) ** 2, 0.0))
71 lo, hi = xc - s, xc + s
72 C = np.zeros((N, N, N))
73 for k in range(N):
74 zk = k * h
75 ln = np.clip(np.minimum(zk + h, hi) - np.maximum(zk, lo), 0.0, h) / h
76 C[:, :, k] = ln.reshape(N, SUB, N, SUB).mean(axis=(1, 3))
77 # corner test in integer units of h: the centre is the vertex N/2, R/h = N/8 an integer
78 r2 = (N // 8) ** 2
79 q = np.arange(N + 1) - N // 2 # vertex offsets from the centre
80 d2 = q[:, None, None] ** 2 + q[None, :, None] ** 2 + q[None, None, :] ** 2
81 cmax = np.zeros((N, N, N), dtype=np.int64)
82 cmin = np.full((N, N, N), np.iinfo(np.int64).max, dtype=np.int64)
83 for a in (0, 1):
84 for b in (0, 1):
85 for c in (0, 1):
86 v = d2[a:a + N, b:b + N, c:c + N]
87 cmax = np.maximum(cmax, v)
88 cmin = np.minimum(cmin, v)
89 C[cmax <= r2] = 1.0 # all 8 corners in the closed ball: the cell lies in it
90 C[cmin >= r2] = 0.0 # nearest point of a cell to a vertex is a corner: no overlap with the open ball
91 return np.asfortranarray(C)
92
93
94def run_case(key):
95 kappa, doh, mode = key
96 os.environ.setdefault("OMP_PROC_BIND", "false")
97 import peclet.flow as pf
98
99 t0 = time.time()
100 N = 4 * doh
101 h = L / N
102 mu_out = 1.0
103 mu_hi = max(kappa, 1.0) * mu_out
104 dt = gsv1.D_HI * h * h * 1.0 / mu_hi
105 C = colour(N)
106 phi_h = float(np.mean(C))
107 Vh = h**3 * float(np.sum(C))
108 Rh = (3.0 * Vh / (4.0 * math.pi)) ** (1.0 / 3.0)
109 U_hr = 1e-3 * h / dt
110 drg = U_hr * 9.0 * mu_out * k_hr(kappa) / (2.0 * R * R)
111 F = drg * Vh
112 s = pf.Solver((N, N, N), extent=(L, L, L))
113 s.set_dt(dt) # first: pins the internal time scale
114 s.set_rho(1.0)
115 s.set_mu(mu_out)
116 s.set_pressure_geometry(np.full((N, N, N), 1.0, order="F"))
117 s.enable_vof()
118 s.set_vof(C)
119 s.set_property_model("mu", "linear", "C", [mu_out, kappa * mu_out - mu_out])
120 s.enable_cell_force()
121 fi = np.atleast_1d(s.unit_scales["force_density_to_internal"])
122 fz = drg * (C - phi_h)
123 for c in range(3):
124 sc = float(fi[c if fi.size == 3 else 0])
125 s.set_field("force_" + "xyz"[c], np.asfortranarray(sc * fz if c == 2 else np.zeros((N, N, N))))
126 s.set_advection(False)
127 s.set_pressure_pcg(True, gsv1.PCAP, gsv1.PRTOL) # uniform rho: the single-rank default driver
128 s.set_vof_viscous_interface(mode)
129 gsv1.converge_momentum(s) # §6.6 rule
130 s.update_properties()
131 fr = np.asarray(s.get_field("force_z"))
132 fsum_abs = abs(float(np.sum(fr))) / max(float(np.sum(np.abs(fr))), 1e-300)
133 fsum_max = abs(float(np.sum(fr))) / max(float(np.max(np.abs(fr))), 1e-300)
134 rho = np.ones((N, N, N))
135 S = gsv1.StepMap(s, C, N, rho)
136 nu = 3 * N**3
137 x0 = np.zeros(4 * N**3)
138 xs, status, steps, inc, cycles = gsv1.gmres_steady(S, x0, nu, U_hr)
139 vsolver = s.diagnostics.velocity_solver()
140 inc_def = gsv1.default_step_increment(S, xs, nu)
141 w = xs[2 * N**3:3 * N**3].reshape((N, N, N), order="F")
142 wbar = 0.5 * (w + np.roll(w, -1, axis=2)) # -z face of cell i is w[i]; +z face is w[i+1]
143 Ud = float(np.sum(C * wbar)) / float(np.sum(C)) - float(np.mean(w))
144 K = F / (6.0 * math.pi * mu_out * Ud * Rh) if Ud != 0.0 else float("nan")
145 umax = float(np.max(np.abs(xs[:nu])))
146 return {"kappa": kappa, "doh": doh, "N": N, "mode": mode, "status": status, "steps": steps, "cycles": cycles,
147 "inc": inc, "K": K, "Ud": Ud, "U_hr": U_hr, "F": F, "Vh": Vh, "Rh": Rh, "phi_h": phi_h,
148 "mom": S.mom, "fsum_rel_abs": fsum_abs, "fsum_rel_max": fsum_max, "cfl": umax * dt / h,
149 "inc_default_step": inc_def, "velocity_solver": vsolver, "mom_utol": gsv1.MOM_UTOL,
150 "max_p_it": S.max_pit, "max_momentum_sweeps": S.max_msw, "secs": round(time.time() - t0, 1),
151 "rescaled": S.rescaled, "max_gain": S.max_gain, **S.tie, **({"mom_fixed": gsv1.MOM_FIXED} if gsv1.MOM_FIXED else {})}
152
153
154def _run(key):
155 try:
156 return run_case(key)
157 except RuntimeError as ex: # a refused production step: NOT CONVERGED, listed, never judged
158 kappa, doh, mode = key
159 return {"kappa": kappa, "doh": doh, "N": 4 * doh, "mode": mode, "status": "step_error",
160 "error": str(ex)[:200], "steps": -1, "K": float("nan"), "secs": 0.0}
161
162
163def line(r):
164 if r["status"] == "step_error":
165 return f"GSV2CASE kappa={r['kappa']:g} d/h={r['doh']} {r['mode']} step_error {r.get('error', '')[:100]}"
166 return (f"GSV2CASE kappa={r['kappa']:g} d/h={r['doh']} N={r['N']} {r['mode']} {r['status']} steps={r['steps']} "
167 f"cycles={r['cycles']} inc={r['inc']:.1e} K={r['K']:.6f} Ud/U_hr={r['Ud'] / r['U_hr']:.6f} "
168 f"mom={r['mom']:.1e} fsum(abs)={r['fsum_rel_abs']:.1e} fsum(max)={r['fsum_rel_max']:.1e} "
169 f"cfl={r['cfl']:.2e} inc_def={r['inc_default_step']:.1e} vsolver={r['velocity_solver']} "
170 f"max_p_it={r['max_p_it']} max_msw={r['max_momentum_sweeps']} {gsv1.tie_str(r)} {r['secs']}s")
171
172
173def load(path):
174 out = {}
175 if os.path.exists(path):
176 with open(path) as f:
177 rows = f.readlines()
178 for ln in rows:
179 ln = ln.strip()
180 if ln:
181 r = json.loads(ln)
182 if r.get("mom_utol", 1.0) > gsv1.MOM_UTOL: # taken at a looser update stop: void, rerun
183 continue
184 out[(r["kappa"], r["doh"], r["mode"])] = r
185 return out
186
187
188def cmd_run(a):
189 dohs = [int(v) for v in a.doh.split(",")]
190 kap = [float(v) for v in a.kappa.split(",")]
191 modes = a.modes.split(",")
192 keys = []
193 for k in kap:
194 for d in dohs:
195 for m in (("sharp",) if k == 1.0 else modes): # kappa = 1: uniform mu, one control run
196 keys.append((k, d, m))
197 done = load(a.out)
198 todo = [k for k in keys if k not in done]
199 print(f"GSV2RUN total={len(keys)} todo={len(todo)} mom_utol={gsv1.MOM_UTOL:g}", flush=True)
200 with Pool(a.procs, initializer=gsv1._set_mom_utol, initargs=(gsv1.MOM_UTOL, a.mom_fixed)) as pool, \
201 open(a.out, "a") as f:
202 for r in pool.imap_unordered(_run, todo, chunksize=1):
203 f.write(json.dumps(r) + "\n")
204 f.flush()
205 print(line(r), flush=True)
206 print("EXIT", flush=True)
207
208
209def fit(hs, Ks):
210 from scipy.optimize import least_squares
211 hs, Ks = np.asarray(hs, float), np.asarray(Ks, float)
212 best = None
213 for p0 in (1.0, 2.0, 3.0):
214 x0 = [Ks[-1], (Ks[0] - Ks[-1]) / max(hs[0] ** p0 - hs[-1] ** p0, 1e-300), p0]
215 r = least_squares(lambda x: x[0] + x[1] * hs ** x[2] - Ks, x0,
216 bounds=([-np.inf, -np.inf, 0.5], [np.inf, np.inf, 4.0]), xtol=1e-15, ftol=1e-15, gtol=1e-15)
217 if best is None or r.cost < best.cost:
218 best = r
219 return float(best.x[0]), float(best.x[1]), float(best.x[2])
220
221
223 res = load(a.out)
224 rows = [res.get((1.0, d, "sharp")) for d in (8, 12)]
225 if any(r is None or r["status"] != "ok" for r in rows):
226 print("GSV2-ACCEPT NOT_JUDGED (kappa = 1, d/h 8 and 12 not both converged)")
227 return 1
228 fa = max(r["fsum_rel_abs"] for r in rows)
229 fm = max(r["fsum_rel_max"] for r in rows)
230 mm = max(r["mom"] for r in rows)
231 cf = max(r["cfl"] for r in rows)
232 ok = fa <= 1e-14 and mm <= 1e-13 and cf <= 1.1e-3
233 print(f"GSV2-ACCEPT kappa=1 d/h 8,12: sum f / sum|f| = {fa:.1e} (sum f / max|f| = {fm:.1e}) (<= 1e-14), "
234 f"momentum invariant {mm:.1e} (<= 1e-13), CFL {cf:.2e} (<= 1.1e-3) {'PASS' if ok else 'MISS'}"
235 + ("" if fm <= 1e-14 else " [the max-normalised force sum exceeds 1e-14]"))
236 return 0 if ok else 1
237
238
240 res = load(a.out)
241 verdict = {}
242 for kappa in KAPPAS:
243 for mode in (("sharp",) if kappa == 1.0 else ("sharp", "averaged")):
244 rows = [res.get((kappa, d, mode)) for d in DOH]
245 ks = " ".join(f"{d}:{r['K']:.6f}" if r and r["status"] == "ok" else f"{d}:{r['status'] if r else '-'}"
246 for d, r in zip(DOH, rows))
247 mv = " ".join(f"{r['steps']}" if r else "-" for r in rows)
248 # WO-A5b: rows with a momentum component at the 200000-sweep cap, reported, NOT voiding (§6.8 A)
249 mv += f" | momcap {sum(1 for r in rows if r and r.get('max_momentum_sweeps', 0) >= gsv1.MOM_CAP)}/{len(rows)}"
250 kp = k_per(kappa)
251 if all(r and r["status"] == "ok" for r in rows):
252 hs = [1.0 / d for d in DOH]
253 Ki, _, p = fit(hs, [r["K"] for r in rows])
254 Ki4, _, p4 = fit(hs[1:], [r["K"] for r in rows[1:]])
255 ok = p >= 1.8 and abs(Ki - kp) / kp <= 0.03
256 ok4 = p4 >= 1.8 and abs(Ki4 - kp) / kp <= 0.03
257 v = "PASS" if ok else ("MISS (four-level pass: Q10, the user rules)" if ok4 else "MISS")
258 verdict[(kappa, mode)] = ok
259 print(f"GSV2 kappa={kappa:g} {mode} K[d/h]={ks} | fit5: K_inf={Ki:.5f} p={p:.3f} "
260 f"dev={abs(Ki - kp) / kp * 100:.2f}% | fit4(12-32): K_inf={Ki4:.5f} p={p4:.3f} "
261 f"dev={abs(Ki4 - kp) / kp * 100:.2f}% | K_per={kp:.4f} | matvecs {mv} | "
262 f"{v if mode == 'sharp' else 'reported'}")
263 else:
264 verdict[(kappa, mode)] = None
265 print(f"GSV2 kappa={kappa:g} {mode} K[d/h]={ks} | matvecs {mv} | NOT_JUDGED (levels missing or not converged)")
266 c = verdict.get((1.0, "sharp"))
267 g = [verdict.get((k, "sharp")) for k in (1e-2, 1e2)]
268 if c is None or any(v is None for v in g):
269 out = "NOT_JUDGED (levels missing or not converged)"
270 elif not c:
271 out = "NOT_JUDGED (kappa = 1 control misses: instrument or base scheme -> architect)"
272 else:
273 out = "PASS" if all(g) else "MISS"
274 print(f"GSV2 VERDICT {out}")
275
276
277def main():
278 p = argparse.ArgumentParser()
279 sp = p.add_subparsers(dest="cmd", required=True)
280 r = sp.add_parser("run")
281 r.add_argument("--doh", default="8,12,16")
282 r.add_argument("--kappa", default="1e-2,1,1e2")
283 r.add_argument("--modes", default="sharp,averaged")
284 r.add_argument("--procs", type=int, default=3)
285 r.add_argument("--out", required=True)
286 r.add_argument("--mom-fixed", type=int, default=0) # WO-A5b: fixed RB-GS sweeps per component (0 = off)
287 for nm in ("accept", "table"):
288 q = sp.add_parser(nm)
289 q.add_argument("--out", required=True)
290 a = p.parse_args()
291 return {"run": cmd_run, "accept": cmd_accept, "table": cmd_table}[a.cmd](a)
292
293
294if __name__ == "__main__":
295 sys.exit(main())
gmres_steady(S, x0, nu, umax, m=GM_RESTART, cap=GM_CAP, tol=TOL)
Definition gsv1.py:693
converge_momentum(s)
Definition gsv1.py:390
default_step_increment(S, xs, nu)
Definition gsv1.py:407
line(r)
Definition gsv2.py:163
_run(key)
Definition gsv2.py:154
cmd_run(a)
Definition gsv2.py:188
k_hr(kappa)
Definition gsv2.py:54
load(path)
Definition gsv2.py:173
cmd_table(a)
Definition gsv2.py:239
colour(N)
Definition gsv2.py:63
cmd_accept(a)
Definition gsv2.py:222
k_per(kappa)
Definition gsv2.py:58
fit(hs, Ks)
Definition gsv2.py:209
main()
Definition gsv2.py:277
run_case(key)
Definition gsv2.py:94
static double mean(const std::vector< double > &a)