flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
gsv9.py
Go to the documentation of this file.
1"""G-SV9 (b) and (d) (doc/vof_sharp_viscous_stress.md §11): the 3-D homogeneous march of the sharp
2viscous split with the production stepper.
3
4Unit box, N = 16, no-slip walls on all six faces (homogeneous Dirichlet), Stokes (momentum
5advection off, no body force), sharp viscous interface. The colour is FROZEN: it is reset to the
6initial field after every step (the step builds mu, rho and the band from the colour it starts
7with; its colour stage at the tail is discarded), so the march is the linear operator of §6.
8 (b) plane: the plane with normal n(22.5, 22.5 deg) through the centre, offset 0.3 cell along n
9 (C = 1, phase A, on the side n.(x - x0) < 0);
10 (d) film: a grid-aligned 1-cell slab of the low-mu phase normal to x (cells x = N/2), both of
11 its faces carrying virtual planes.
12 (b') pplane: the periodic twin, reported only (§11 third-pass amendment, WO-6a): a TRIPLY PERIODIC
13 box with the rational normal m = (2,1,1), n = m/|m|, period P = 1/|m| along n; two
14 parallel planes per period, the first at offset 0.3 cell (s0 = n.(1/2,1/2,1/2) + 0.3 h),
15 the second half a period further (layer fraction 0.5, coordinator 2026-11-01): phase A
16 where frac((n.x - s0)/P) < 1/2, exact cell fractions (gsv1.layered_fractions). The
17 initial field is the periodic MAC curl of a random edge potential with each
18 component's rho_F-weighted mean removed (the momentum invariant of the periodic box,
19 which no step can decay; DECISION, reported); E sums every face. WO-6a' (§6.5): on the
20 periodic box the verdicts judge E' = E - sum_c (sum_F rho_F u_c)^2/(2 sum_F rho_F), the
21 energy of the M-orthogonal complement of the translations (the inexact default momentum
22 solve deposits momentum, which the undamped translations accumulate); E is reported.
23 --frac sets the layer fraction, --D the D_hi list, --pairs the PAIRS indices (WO-6f).
24mu_A/mu_B = 1e-2, 1e2, 1e-3, 1e3 with rho_A/rho_B = 1e-3, 1e3, 1e-4, 1e4 (the high-mu phase has
25mu = rho = 1); D_hi = mu_hi dt/(rho_hi h^2) in {0.1, 1, 10, 100, 1e4}; 2000 steps.
26Initial field: the discrete MAC curl of a random edge vector potential (zero on the walls), so it
27is exactly solenoidal with zero wall-normal velocity; its amplitude keeps the colour CFL <= 1e-3
28(the problem is linear, so the scale is immaterial).
29Kinetic energy: E = 1/2 sum_faces rho_F u^2 h^3, rho_F the solver's face density (the mean of the
30two cells' rho(C), face_props.hpp) -- the M-norm of the §6 analysis.
31PASS (per run): E_n <= E_0 for every n, and E_{n+100}/E_n <= 1 + 1e-10 for every n >= 200.
32Pressure (WO-6a, §6.2): the production driver the rho property model selects (Chebyshev), never a
33forced CG driver, with rtol 1e-12 and a cap (PCAP) that must never bind: a capped step makes the
34run NOT JUDGED. Two growth verdicts per run (§6.2, USER Q15 pending): 'as written' above, and
35'floor-excluded', the growth ratio judged only over windows with E_n >= 1e-20 E_0 (the ratio
36below that level is reported, not judged).
37
38 nice -n 10 python gsv9.py [--geom plane|film|pplane|both] [--procs 6] [--mode sharp|averaged] (one line per run + a verdict)
39"""
40import argparse
41import math
42import os
43import sys
44from multiprocessing import Pool
45
46import numpy as np
47
48from gsv1 import tie_init, tie_read, tie_str # G-SV12 owner-tie census (WO-9.4)
49
50N, STEPS = 16, 2000
51PCAP, PRTOL = 20000, 1e-12 # the Chebyshev cap must never bind (§6.2)
52FLOOR = 1e-20 # the Q15 floor: windows with E_n < FLOOR * E_0 are reported, not judged
53PAIRS = ((1e-2, 1e-3), (1e2, 1e3), (1e-3, 1e-4), (1e3, 1e4))
54DS = (0.1, 1.0, 10.0, 100.0, 1e4)
55
56
57def plane_fractions(n, nrm, x0, sub=8):
58 off = (np.arange(sub) + 0.5) / sub
59 g = (np.arange(n)[:, None] + off[None, :]).ravel()
60 out = np.zeros((n, n, n))
61 for k in range(n):
62 X, Y, Z = np.meshgrid(g, g, k + off, indexing="ij")
63 ins = (nrm[0] * (X - x0[0]) + nrm[1] * (Y - x0[1]) + nrm[2] * (Z - x0[2]) < 0).astype(np.float64)
64 out[:, :, k] = ins.reshape(n, sub, n, sub, sub).mean(axis=(1, 3, 4))
65 return np.asfortranarray(out)
66
67
68def colour(geom, lowA, frac=0.5):
69 if geom == "pplane":
70 from gsv1 import layered_fractions
71 m = np.array((2.0, 1.0, 1.0))
72 nrm = m / np.linalg.norm(m)
73 P = 1.0 / float(np.linalg.norm(m))
74 s0 = float(nrm @ np.full(3, 0.5)) + 0.3 / N
75 return np.asfortranarray(layered_fractions(nrm, s0, P, frac * P, 0.0, N))
76 if geom == "plane":
77 b = g = math.radians(22.5)
78 nrm = (math.cos(b) * math.cos(g), math.cos(b) * math.sin(g), math.sin(b))
79 return plane_fractions(N, nrm, [0.5 * N + 0.3 * c for c in nrm])
80 C = np.zeros((N, N, N)) if lowA else np.ones((N, N, N))
81 C[N // 2, :, :] = 1.0 if lowA else 0.0 # the slab is the low-mu phase
82 return np.asfortranarray(C)
83
84
85def solenoidal(seed):
86 """u = curl(psi) on the MAC grid, psi on edges, zero on every wall edge (index units)."""
87 r = np.random.default_rng(seed)
88 px = r.standard_normal((N, N + 1, N + 1)) # psi_x at (i+1/2, j, k)
89 py = r.standard_normal((N + 1, N, N + 1)) # psi_y at (i, j+1/2, k)
90 pz = r.standard_normal((N + 1, N + 1, N)) # psi_z at (i, j, k+1/2)
91 px[:, [0, N], :] = 0.0; px[:, :, [0, N]] = 0.0
92 py[[0, N], :, :] = 0.0; py[:, :, [0, N]] = 0.0
93 pz[[0, N], :, :] = 0.0; pz[:, [0, N], :] = 0.0
94 u = (pz[:, 1:, :] - pz[:, :-1, :]) - (py[:, :, 1:] - py[:, :, :-1]) # (N+1, N, N) at x-faces
95 v = (px[:, :, 1:] - px[:, :, :-1]) - (pz[1:, :, :] - pz[:-1, :, :]) # (N, N+1, N)
96 w = (py[1:, :, :] - py[:-1, :, :]) - (px[:, 1:, :] - px[:, :-1, :]) # (N, N, N+1)
97 div = (u[1:] - u[:-1]) + (v[:, 1:] - v[:, :-1]) + (w[:, :, 1:] - w[:, :, :-1])
98 assert np.max(np.abs(div)) < 1e-12 and not u[0].any() and not u[N].any()
99 return u[:N], v[:, :N], w[:, :, :N] # the -c face of every cell; the +wall face is 0
100
101
103 """u = curl(psi) on the periodic MAC grid (index units): psi_x at (i+1/2, j, k), psi_y at
104 (i, j+1/2, k), psi_z at (i, j, k+1/2); face c index i is the -c face of cell i."""
105 r = np.random.default_rng(seed)
106 px, py, pz = (r.standard_normal((N, N, N)) for _ in range(3))
107 d = lambda a, ax: np.roll(a, -1, axis=ax) - a
108 u = d(pz, 1) - d(py, 2)
109 v = d(px, 2) - d(pz, 0)
110 w = d(py, 0) - d(px, 1)
111 div = d(u, 0) + d(v, 1) + d(w, 2)
112 assert np.max(np.abs(div)) < 1e-12
113 return u, v, w
114
115
117 """The solver's face density: the mean of the two cells, face c index i between cells i-1 and i."""
118 return [0.5 * (rho + np.roll(rho, 1, axis=c)) for c in range(3)]
119
120
121def energy_periodic(vel, rho):
122 return sum(0.5 * float(np.sum(rf * np.asarray(vel[c]) ** 2)) for c, rf in enumerate(rho_face_periodic(rho))) / N**3
123
124
126 """WO-6a' (§6.5 finding 1): E' = E - sum_c (sum_F rho_F u_c)^2 / (2 sum_F rho_F), the energy of the
127 M-orthogonal complement of the three translations (exact lambda = 1 eigenvectors of any
128 momentum-conserving step on a periodic box). Same h^3 = 1/N^3 normalisation as energy_periodic."""
129 e = energy_periodic(vel, rho)
130 for c, rf in enumerate(rho_face_periodic(rho)):
131 e -= float(np.sum(rf * np.asarray(vel[c]))) ** 2 / (2.0 * float(np.sum(rf))) / N**3
132 return e
133
134
135def energy(vel, rho):
136 e = 0.0
137 for c in range(3):
138 sl_hi = [slice(None)] * 3; sl_lo = [slice(None)] * 3
139 sl_hi[c] = slice(1, N); sl_lo[c] = slice(0, N - 1)
140 rf = 0.5 * (rho[tuple(sl_hi)] + rho[tuple(sl_lo)])
141 e += 0.5 * float(np.sum(rf * vel[c][tuple(sl_hi)] ** 2)) # the wall faces (index 0) carry 0
142 return e / N**3
143
144
145def run(args):
146 geom, muR, rhoR, Dn, mode, frac = args
147 import peclet.flow as pf
148 lowA = muR < 1.0
149 muA, muB = (muR, 1.0) if lowA else (1.0, 1.0 / muR)
150 rA, rB = (rhoR, 1.0) if lowA else (1.0, 1.0 / rhoR)
151 h = 1.0 / N
152 dt = Dn * h * h # mu_hi = rho_hi = 1
153 s = pf.Solver((N, N, N), extent=(1.0, 1.0, 1.0))
154 s.set_dt(dt) # FIRST: the first set_dt pins the internal time scale (set_dt docstring)
155 for f in ("-x", "+x", "-y", "+y", "-z", "+z"):
156 s.set_domain_bc(f, "periodic" if geom == "pplane" else "wall")
157 s.set_rho(1.0)
158 s.set_mu(1.0)
159 s.set_pressure_geometry(np.full((N, N, N), 1.0, order="F"))
160 s.enable_vof()
161 C0 = colour(geom, lowA, frac)
162 s.set_vof(C0)
163 s.set_property_model("mu", "linear", "C", [muB, muA - muB])
164 s.set_property_model("rho", "linear", "C", [rB, rA - rB])
165 s.set_advection(False)
166 # Keep the driver the rho model selected (Chebyshev); only its tolerance and cap are set.
167 s.set_pressure_chebyshev(True, PCAP, PRTOL)
168 s.set_vof_viscous_interface(mode)
169 rho = rB + (rA - rB) * C0
170 if geom == "pplane":
171 u, v, w = solenoidal_periodic(12345)
172 u, v, w = (a - float(np.sum(rf * a)) / float(np.sum(rf)) for a, rf in zip((u, v, w), rho_face_periodic(rho)))
173 en = energy_periodic_deflated # judged (WO-6a'); E itself is reported
174 else:
175 u, v, w = solenoidal(12345)
176 en = energy
177 amp = 1e-3 * h / (dt * max(np.max(np.abs(a)) for a in (u, v, w))) # colour CFL <= 1e-3
178 for c, a in enumerate((u, v, w)):
179 s.set_velocity(c, np.asfortranarray(amp * a))
180 E = [en([s.get_u(), s.get_v(), s.get_w()], rho)]
181 Efull = [energy_periodic([s.get_u(), s.get_v(), s.get_w()], rho)] if geom == "pplane" else None
182 cen = {"band_cells": 0, "virtual_cells": 0, "film_cells": 0, "fit_fallbacks": 0}
183 tie = tie_init()
184 capped = 0
185 first_cap = None
186 pmax = 0
187 blow = None
188 for n in range(STEPS):
189 try:
190 s.step()
191 except RuntimeError as ex: # the colour CFL cap: the field has grown ~1e3x in amplitude
192 blow = f"step {n + 1}: {str(ex)[:60]}"
193 break
194 s.set_vof(C0)
195 pit = s.diagnostics.last_pressure_iterations()
196 pmax = max(pmax, pit)
197 if pit >= PCAP:
198 capped += 1
199 first_cap = n + 1 if first_cap is None else first_cap
200 if mode == "sharp":
201 c = s.diagnostics.vof_viscous_interface_census()
202 for k in cen:
203 cen[k] += c[k]
204 tie_read(s, tie)
205 vel = [s.get_u(), s.get_v(), s.get_w()]
206 E.append(en(vel, rho))
207 if Efull is not None:
208 Efull.append(energy_periodic(vel, rho))
209 E = np.array(E)
210 rep = ""
211 if Efull is not None: # E reported, E' judged (WO-6a')
212 Ef = np.array(Efull)
213 lo_ = min(200, max(len(Ef) - 101, 0))
214 wf = Ef[lo_ + 100:] / Ef[lo_:-100] if len(Ef) > 101 else np.array([np.nan])
215 rep = (f"[judged E'=E-translations; reported E: E_end/E0={Ef[-1] / Ef[0]:.6f} "
216 f"max E(n+100)/E(n)={float(np.max(wf)):.6f}] frac={frac:g} ")
217 up = np.nonzero(E[1:] > E[:-1])[0]
218 first_grow = int(up[0]) + 1 if up.size else None
219 tag = "GSV9" + {"plane": "b", "film": "d", "pplane": "b'"}[geom] + ("" if mode == "sharp" else "-AVG")
220 timing = (f"{rep}pdriver=chebyshev(rtol={PRTOL:g},cap={PCAP}) max_p_it={pmax} capped_steps={capped} "
221 f"first_cap_step={first_cap} first_energy_growth_step={first_grow} {tie_str(tie)}")
222 if capped:
223 return (f"{tag} NOT_JUDGED geom={geom} muA/muB={muR:g} rhoA/rhoB={rhoR:g} D_hi={Dn:g} "
224 f"(a capped pressure step) steps_run={len(E) - 1} {timing}", None, None)
225 if blow is not None:
226 grow = E[1:] / E[:-1]
227 return (f"{tag} MISS/MISS geom={geom} muA/muB={muR:g} rhoA/rhoB={rhoR:g} "
228 f"D_hi={Dn:g} BLOWUP at {blow} E_last/E0={E[-1] / E[0]:.3e} min_n E_n/E0={float(np.min(E) / E[0]):.3e} "
229 f"last-100-step mean growth/step={float(np.exp(np.mean(np.log(grow[-100:])))):.6f} "
230 f"{timing}", False, False)
231 above = int(np.sum(E[1:] > E[0]))
232 lo = min(200, max(len(E) - 101, 0)) # 200 for the 2000-step run; shorter runs are smoke tests
233 En, Ew = E[lo:-100], E[lo + 100:]
234 win = Ew / np.where(En > 0, En, np.nan)
235 gmax = float(np.max(win)) if np.all(En > 0) else float("nan")
236 keep = En >= FLOOR * E[0]
237 gfl = float(np.max(win[keep])) if np.any(keep) else float("nan")
238 gbel = float(np.nanmax(win[~keep])) if np.any(~keep) else float("nan")
239 ok = above == 0 and gmax <= 1.0 + 1e-10
240 okf = above == 0 and not (gfl > 1.0 + 1e-10) # no window above the floor: nothing to judge
241 vd = lambda b: "PASS" if b else "MISS"
242 return (f"{tag} {vd(ok)}/{vd(okf)} geom={geom} "
243 f"muA/muB={muR:g} rhoA/rhoB={rhoR:g} D_hi={Dn:g} E_end/E0={E[-1] / E[0]:.3e} "
244 f"max_n E_n/E0={float(np.max(E[1:]) / E[0]):.6f} steps_above_E0={above} "
245 f"max E(n+100)/E(n),n>=200={gmax:.6f} [E_n>=1e-20E0: {gfl:.6f}, below: {gbel:.6f}] "
246 f"band/step={cen['band_cells'] / STEPS:.0f} "
247 f"virt/step={cen['virtual_cells'] / STEPS:.0f} film/step={cen['film_cells'] / STEPS:.0f} "
248 f"fallbacks={cen['fit_fallbacks']} {timing}", ok, okf)
249
250
251def main():
252 p = argparse.ArgumentParser()
253 p.add_argument("--geom", choices=("plane", "film", "pplane", "both"), default="both")
254 p.add_argument("--procs", type=int, default=6)
255 p.add_argument("--mode", choices=("sharp", "averaged"), default="sharp")
256 p.add_argument("--frac", type=float, default=0.5) # pplane layer fraction of phase A (WO-6f: 0.5, 0.75)
257 p.add_argument("--D", type=lambda t: tuple(float(x) for x in t.split(",")), default=DS) # D_hi list
258 p.add_argument("--pairs", type=lambda t: tuple(int(x) for x in t.split(",")), default=None) # PAIRS indices
259 a = p.parse_args()
260 geoms = ("plane", "film") if a.geom == "both" else (a.geom,)
261 pairs = PAIRS if a.pairs is None else tuple(PAIRS[i] for i in a.pairs)
262 jobs = [(g, m, r, d, a.mode, a.frac) for g in geoms for (m, r) in pairs for d in a.D]
263 res = []
264 with Pool(a.procs) as pool:
265 for line, ok, okf in pool.imap_unordered(run, jobs):
266 print(line, flush=True)
267 res.append((ok, okf))
268 tag = f"GSV9{'' if a.mode == 'sharp' else '-AVG'}"
269 nj = sum(1 for ok, _ in res if ok is None)
270 rc = 0
271 for k, nm in ((0, "as-written"), (1, "floor-excluded")):
272 npass = sum(1 for r in res if r[k] is True)
273 verdict = "PASS" if npass == len(res) else ("MISS" if npass + nj < len(res) else "NOT_JUDGED")
274 rc |= verdict != "PASS"
275 print(f"{tag} {nm} {verdict} {npass}/{len(res)} runs pass, {nj} not judged (geom={a.geom})")
276 return rc
277
278
279if __name__ == "__main__":
280 sys.exit(main())
solenoidal_periodic(seed)
Definition gsv9.py:102
energy_periodic_deflated(vel, rho)
Definition gsv9.py:125
run(args)
Definition gsv9.py:145
solenoidal(seed)
Definition gsv9.py:85
colour(geom, lowA, frac=0.5)
Definition gsv9.py:68
rho_face_periodic(rho)
Definition gsv9.py:116
plane_fractions(n, nrm, x0, sub=8)
Definition gsv9.py:57
energy(vel, rho)
Definition gsv9.py:135
main()
Definition gsv9.py:251
energy_periodic(vel, rho)
Definition gsv9.py:121
static std::vector< double > slice(const std::vector< double > &g, int ox, int oy, int oz, int lnx, int lny, int lnz)
static double mean(const std::vector< double > &a)