flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
gsv9_split.py
Go to the documentation of this file.
1"""Architect round 3, Q1 (doc/vof_sharp_viscous_stress.md §6.1): is the 3-D G-SV9(b) blow-up a
2departure of the production step from the 2-D harness, or a genuine 3-D mode?
3
4harness : 2-D dense rho(G), G = P (M+K)^-1 (M+K-A), for two implicit splits of the cell normal
5 stress 2 mu(C) m_cc:
6 'K2' -- all of it implicit (what stab.py / gsv9a.py / §6 measured);
7 'K1' -- mu(C) m_cc implicit, mu(C) m_cc explicit on u^n (what the production kernels do:
8 the Laplacian band ibmBuildDiffusionVar + the normal element N_c of
9 full_stress.hpp, §5.4(b)).
10 A = sharp (§5.7 interfacial-mean tau) or averaged (today's arithmetic operator).
11prod : the PRODUCTION step map on a 3-D case, linear with the colour frozen, by Arnoldi
12 (scipy eigs) on u -> step(u). Non-incremental projection and converged solves by default
13 (RB-GS to an update of 1e-15 of the first, residual stop off; the Chebyshev pressure
14 driver to 1e-13 -- the CG drivers return wrong
15 fields at density ratio 1e4), so that it is the harness's G. --incremental runs the
16 production incremental-rotational step on the full state (u, v, w, p), p through
17 get_field/set_field("p") with its mean removed (G-SV9(e)); --prodsolve keeps gsv9.py's
18 PCG(800). Geometries: 'ext' = the 2-D harness plane extruded in z (exact harness
19 fractions, z periodic, walls on x and y; --kz0 restricts to z-independent fields with
20 u_z = 0, the harness subspace); 'plane' = the G-SV9(b) plane n(22.5,22.5), offset 0.3,
21 walls on all faces, exact fractions (--sub8 = gsv9.py's 8^3 sub-sampled colour);
22 'film' = the G-SV9(d) slab. 'pplane' = the (b') periodic twin; there the three translations
23 are deflated M-orthogonally from every Arnoldi vector (WO-6a', §6.5).
24
25 nice -n 10 python gsv9_split.py harness [--N 16]
26 nice -n 10 python gsv9_split.py prod --geom ext --N 16 --Nz 4 --mode sharp --pair 1e-3,1e-4 --D 1e4 [--kz0]
27 nice -n 10 python gsv9_split.py prod --geom plane --N 16 --mode sharp --pair 1e-3,1e-4 --D 1e4 --incremental
28"""
29import argparse
30import math
31import os
32import sys
33import time
34
35import numpy as np
36
37HERE = os.path.dirname(os.path.abspath(__file__))
38sys.path.insert(0, HERE)
39
40
41def harness_case(N, ang, off, muA, rA, Ds, scheme):
42 import mac2d as M
43 from stab import blocks, rho_face
44 M.TAU_RULE = "mixed-avg"
45 case = M.Case(N, ang, off, muA, 1.0, "couette")
46 rf = rho_face(case, *blocks(case, "facef", "arith", None, None)[3:], rA, 1.0)
47 if scheme == "sharp":
48 M.CELL_VOL = True
49 K2 = blocks(case, "facef", "arith", None, {"xx", "yy", "yu", "xv"})[0]
50 Kc = blocks(case, "facef", "arith", None, {"xx", "yy"})[0]
51 M.CELL_VOL = False
52 At, G, D, _, _ = blocks(case, "sharp", "facef", "fit", None)
53 else:
54 K2 = blocks(case, "arith", "arith", None, {"xx", "yy", "yu", "xv"})[0]
55 Kc = blocks(case, "arith", "arith", None, {"xx", "yy"})[0]
56 At, G, D, _, _ = blocks(case, "arith", "arith", None, None)
57 K1 = K2 - 0.5 * Kc
58 # 'Kb': the full 2 mu(C) m_cc implicit on INTERFACIAL cells only (eps < C < 1 - eps), K1 elsewhere
59 _, _, _, uidx, mm = blocks(case, "arith", "arith", None, {"xx"})
60 N, h = case.N, case.h
61 nv = len(uidx)
62 Kcf = np.zeros((nv, nv))
63 Kcb = np.zeros((nv, nv))
64 for i in range(N):
65 for j in range(N):
66 f = case.frac_cell(i * h, j * h)
67 w = 2.0 * (f * muA + (1.0 - f) * 1.0) / h**2
68 for ip, im in ((mm.iu(i + 1, j), mm.iu(i, j)), (mm.iv(i, j + 1), mm.iv(i, j))):
69 g = np.zeros(nv)
70 if ip in uidx:
71 g[uidx[ip]] += 1.0
72 if im in uidx:
73 g[uidx[im]] -= 1.0
74 Kcf += w * np.outer(g, g)
75 if 1e-8 < f < 1.0 - 1e-8:
76 Kcb += w * np.outer(g, g)
77 chk = float(np.max(np.abs(Kcf - Kc)) / np.max(np.abs(Kc)))
78 assert chk < 1e-10, chk
79 Kb = K1 + 0.5 * Kcb
80 out = {}
81 for Dn in Ds:
82 dt = Dn * case.h**2 * (1.0 if muA < 1 else rA / muA)
83 Mm = np.diag(rf / dt)
84 Mi = np.diag(dt / rf)
85 P = np.eye(len(rf)) - Mi @ G @ np.linalg.pinv(D @ Mi @ G) @ D
86 for nm, K in (("K2", K2), ("K1", K1), ("Kb", Kb)):
87 out[(nm, Dn)] = float(np.max(np.abs(np.linalg.eigvals(P @ np.linalg.solve(Mm + K, Mm + K - At)))))
88 return out
89
90
92 N, mu, r, ang, off, sch, Ds = a
93 return a, harness_case(N, ang, off, mu, r, Ds, sch)
94
95
97 from multiprocessing import Pool
98 geoms = ((0.0, 0.6), (0.0, 0.2), (22.5, 0.0), (22.5, 0.3), (45.0, 0.3), (67.5, 0.5))
99 pairs = ((1e-3, 1e-4), (1e-2, 1e-3), (1e2, 1e3), (1e3, 1e4))
100 Ds = (0.1, 1.0, 10.0, 100.0, 1e4)
101 jobs = [(a.N, m, r, g, o, sch, Ds) for sch in ("sharp", "averaged") for (m, r) in pairs for (g, o) in geoms]
102 with Pool(a.procs) as p:
103 res = p.map(_harness_job, jobs)
104 for (N, m, r, g, o, sch, _), out in res:
105 print("HARN N=%d %-8s mu=%g rho=%g geom=(%g,%g) | %s" % (N, sch, m, r, g, o, " | ".join(
106 "%s: %s" % (nm, " ".join("%.4f" % out[(nm, d)] for d in Ds)) for nm in ("K2", "K1", "Kb"))), flush=True)
107 for sch in ("sharp", "averaged"):
108 for nm in ("K2", "K1", "Kb"):
109 w = [max(out[(nm, d)] for (j, out) in res if j[5] == sch) for d in Ds]
110 print("HARN-WORST N=%d %s %s rho(G) at D_hi=%s: %s" % (a.N, sch, nm, Ds, " ".join("%.4f" % x for x in w)))
111
112
113def cube_frac(m, al):
114 import itertools
115 m = np.array(m, float)
116 al = al - sum(x for x in m if x < 0)
117 m = np.abs(m)
118 nz = [x for x in m if x > 1e-300]
119 d = len(nz)
120 if d == 0:
121 return 1.0 if al > 0 else 0.0
122 tot = 0.0
123 for S in itertools.product((0, 1), repeat=d):
124 r = al - sum(x for x, s in zip(nz, S) if s)
125 if r > 0:
126 tot += (-1) ** sum(S) * r**d
127 return min(1.0, max(0.0, tot / (math.factorial(d) * float(np.prod(nz)))))
128
129
130def colour(a, N, Nz):
131 if a.geom == "ext":
132 import mac2d as M
133 case = M.Case(N, a.ang, a.off, 1.0, 1.0, "couette")
134 h = case.h
135 C2 = np.array([[case.frac_cell(i * h, j * h) for j in range(N)] for i in range(N)])
136 return np.asfortranarray(np.repeat(C2[:, :, None], Nz, axis=2))
137 if a.geom == "pplane": # gsv9.py's (b') periodic twin: m = (2,1,1), two planes per period, offset 0.3
138 # (architect round 4: --m, --frac generalise it; m = (2,1,1), frac 0.5 is gsv9.colour("pplane"));
139 # --roll translates the colour by whole cells: on a periodic grid the step map must be
140 # conjugate to the unrolled one (identical spectrum) unless the seam is treated differently.
141 from gsv1 import layered_fractions
142 m = np.array(a.m if a.m else (2.0, 1.0, 1.0), float)
143 nrm = m / np.linalg.norm(m)
144 P = 1.0 / float(np.linalg.norm(m))
145 C = layered_fractions(nrm, float(nrm @ np.full(3, 0.5)) + 0.3 / N, P, a.frac * P, 0.0, N)
146 if a.roll:
147 C = np.roll(C, a.roll, axis=(0, 1, 2))
148 return np.asfortranarray(C)
149 if a.geom == "film":
150 lowA = a.muA < 1.0
151 C = np.zeros((N, N, N)) if lowA else np.ones((N, N, N))
152 C[N // 2, :, :] = 1.0 if lowA else 0.0
153 return np.asfortranarray(C)
154 b = g = math.radians(22.5)
155 n = np.array([math.cos(b) * math.cos(g), math.cos(b) * math.sin(g), math.sin(b)])
156 if a.m: # architect round 4: the walled single plane with another normal (e.g. the (b') m = (2,1,1))
157 n = np.array(a.m, float) / np.linalg.norm(a.m)
158 x0 = np.array([0.5 * N + 0.3 * c for c in n]) # index units, as gsv9.py
159 if a.sub8:
160 sys.path.insert(0, HERE)
161 import gsv9
162 gsv9.N = N
163 return gsv9.plane_fractions(N, n, x0)
164 C = np.zeros((N, N, N))
165 for i in range(N):
166 for j in range(N):
167 for k in range(N):
168 C[i, j, k] = cube_frac(n, float(n @ (x0 - np.array([i, j, k]))))
169 return np.asfortranarray(C)
170
171
172def cmd_prod(a):
173 import peclet.flow as pf
174 from scipy.sparse.linalg import ArpackNoConvergence, LinearOperator, eigs
175 N = a.N
176 Nz = a.Nz if a.geom == "ext" else N
177 h = 1.0 / N
178 muA, rA = a.muA, a.rA
179 dt = a.D * h * h * (1.0 if muA < 1 else rA / muA)
180 s = pf.Solver((N, N, Nz), extent=(1.0, 1.0, Nz * h))
181 s.set_dt(dt)
182 for f in ("-x", "+x", "-y", "+y"):
183 s.set_domain_bc(f, "periodic" if a.geom == "pplane" else "wall")
184 for f in ("-z", "+z"):
185 s.set_domain_bc(f, "periodic" if a.geom in ("ext", "pplane") else "wall")
186 s.set_rho(1.0)
187 s.set_mu(1.0)
188 s.set_pressure_geometry(np.full((N, N, Nz), 1.0, order="F"))
189 s.enable_vof()
190 C0 = colour(a, N, Nz)
191 s.set_vof(C0)
192 s.set_property_model("mu", "linear", "C", [1.0, muA - 1.0])
193 s.set_property_model("rho", "linear", "C", [1.0, rA - 1.0])
194 s.set_advection(False)
195 dg = s.diagnostics
196 s.set_vof_viscous_interface(a.mode)
197 dg.set_incremental_pressure(bool(a.incremental))
198 if a.prodsolve:
199 s.set_pressure_pcg(True, 800, 1e-12)
200 else:
201 {"pcg": s.set_pressure_pcg, "fcg": s.set_pressure_fcg, "cheb": s.set_pressure_chebyshev}[a.pdriver](
202 True, 20000, 1e-13)
203 dg.set_velocity_solver("gauss_seidel")
204 if a.mom_fixed: # WO-A5 (§6.8 A): a FIXED sweep count per component, update stop off -- an exactly linear map
205 dg.set_velocity_solver_params(a.mom_fixed, 0.0, 2)
206 else:
207 dg.set_velocity_solver_params(200000, a.mom_tol, 2)
208 # The update stop above only binds with the residual stop off: the default residual mode
209 # (following the pressure rtol) has a stagnation guard that exits early on the stiff sharp
210 # rows after WO-5b (measured: exit residual 1.6e-4, linearity 2.5e-2 on ext N16 D_hi 1e4).
211 s.set_velocity_residual_tolerance(0.0)
212 zper = a.geom == "ext"
213 shp = (N, N, Nz)
214 lo = [0, 0, 0] if a.geom == "pplane" else [1, 1, 0 if zper else 1] # face index 0 is the wall face (zero) on a walled axis
215 sls = [tuple(slice(lo[c], None) if d == c else slice(None) for d in range(3)) for c in range(3)]
216 sizes = [int(np.prod([n - (lo[c] if d == c else 0) for d, n in enumerate(shp)])) for c in range(3)]
217 npc = N * N * Nz if a.incremental else 0 # the incremental state carries p (internal units, mean removed)
218 nd = sum(sizes) + npc
219 amp = 1e-6 * h / dt # colour CFL ~1e-6 for a unit-max vector; the map is linear
220 stats = {"n": 0, "pit": 0, "leak": 0.0, "msw": 0}
221 # WO-6a' (§6.5 finding 1): on the triply periodic box the three uniform translations are exact
222 # lambda = 1 eigenvectors of any momentum-conserving step; deflate them M-orthogonally (M = the
223 # solver's face density rho_F, the mean of the two cells' rho(C)) out of every Arnoldi vector, so
224 # that the reported rho is that of the invariant complement and is not pinned at 1.
225 if a.geom == "pplane":
226 rho_c = 1.0 + (rA - 1.0) * C0
227 wts = [(0.5 * (rho_c + np.roll(rho_c, 1, axis=c))).ravel(order="F") for c in range(3)]
228 offs = np.cumsum([0] + sizes)
229
230 def deflate(x):
231 x = np.array(x, dtype=float, copy=True)
232 for c in range(3):
233 seg = x[offs[c]:offs[c + 1]]
234 seg -= float(wts[c] @ seg) / float(np.sum(wts[c]))
235 return x
236 else:
237 deflate = lambda x: x
238
239 def unpack(x):
240 arrs, o = [], 0
241 for c in range(3):
242 A = np.zeros(shp)
243 A[sls[c]] = x[o:o + sizes[c]].reshape(A[sls[c]].shape, order="F")
244 o += sizes[c]
245 arrs.append(A)
246 return arrs
247
248 def pack(arrs, P=None):
249 out = [np.asarray(arrs[c])[sls[c]].ravel(order="F") for c in range(3)]
250 if npc:
251 P = np.asarray(P).ravel(order="F")
252 out.append(P - P.mean())
253 return np.concatenate(out)
254
255 def proj(x):
256 u = unpack(x)
257 u = [np.repeat(u[0].mean(axis=2, keepdims=True), Nz, 2), np.repeat(u[1].mean(axis=2, keepdims=True), Nz, 2),
258 np.zeros(shp)]
259 return pack(u)
260
261 def mv(x):
262 x = deflate(np.real(np.asarray(x)).ravel())
263 sc = amp / max(np.max(np.abs(x)), 1e-300)
264 for c, A in enumerate(unpack(x * sc)):
265 s.set_velocity(c, np.asfortranarray(A))
266 if npc:
267 P = x[nd - npc:] * sc
268 s.set_field("p", np.asfortranarray((P - P.mean()).reshape(shp, order="F")))
269 s.step()
270 s.set_vof(C0)
271 stats["n"] += 1
272 stats["pit"] = max(stats["pit"], dg.last_pressure_iterations())
273 stats["msw"] = max(stats["msw"], int(dg.last_step_timers()["momentum_sweeps"]))
274 y = pack([s.get_u(), s.get_v(), s.get_w()], s.get_field("p") if npc else None) / sc
275 if a.kz0:
276 yp = proj(y)
277 stats["leak"] = max(stats["leak"], float(np.linalg.norm(y - yp) / max(np.linalg.norm(y), 1e-300)))
278 y = yp
279 return deflate(y)
280
281 rng = np.random.default_rng(7)
282 v0 = deflate(rng.standard_normal(nd))
283 if a.kz0:
284 v0 = proj(v0)
285 x1, x2 = deflate(rng.standard_normal(nd)), deflate(rng.standard_normal(nd))
286 if a.kz0:
287 x1, x2 = proj(x1), proj(x2)
288 cpu0 = time.process_time()
289 lin = np.linalg.norm(mv(0.3 * x1 + 0.7 * x2) - 0.3 * mv(x1) - 0.7 * mv(x2)) / np.linalg.norm(mv(x1))
290 cpu_mv = (time.process_time() - cpu0) / 4.0
291 dbl = ""
292 nu = nd - npc
293 if a.mom_fixed:
294 # WO-A5 doubling certificate (§6.8 A (ii)), before ARPACK: for x1 and x_s (30 power steps of the map from
295 # x1), max|y(2N) - y(N)| <= 1e-12 max|y(N)|, separately for u and for p. gsv9e.py judges it and reruns at 2N.
296 xs = x1.copy()
297 for _ in range(30):
298 y = mv(xs)
299 xs = y / np.linalg.norm(y)
300 du = dp = 0.0
301 for x in (x1, xs):
302 y1 = mv(x)
303 dg.set_velocity_solver_params(2 * a.mom_fixed, 0.0, 2)
304 y2 = mv(x)
305 dg.set_velocity_solver_params(a.mom_fixed, 0.0, 2)
306 d = y2 - y1
307 du = max(du, float(np.max(np.abs(d[:nu]))) / max(float(np.max(np.abs(y1[:nu]))), 1e-300))
308 if npc:
309 dp = max(dp, float(np.max(np.abs(d[nu:]))) / max(float(np.max(np.abs(y1[nu:]))), 1e-300))
310 dbl = " dbl_u=%.1e dbl_p=%.1e mom_fixed=%d cpu_per_mv=%.3f" % (du, dp, a.mom_fixed, cpu_mv)
311 if a.ref_check: # WO-A5 acceptance: y(x1) at N against a fixed REF-sweep reference (exp_a.py's fixed rows)
312 y1 = mv(x1)
313 dg.set_velocity_solver_params(a.ref_check, 0.0, 2)
314 yr = mv(x1)
315 dg.set_velocity_solver_params(a.mom_fixed, 0.0, 2)
316 d = y1 - yr
317 print("REFCHK lin=%.1e%s | fixed %d vs %d: du %.2e dp %.2e" % (
318 lin, dbl, a.mom_fixed, a.ref_check, float(np.max(np.abs(d[:nu]))) / float(np.max(np.abs(yr[:nu]))),
319 float(np.max(np.abs(d[nu:]))) / float(np.max(np.abs(yr[nu:]))) if npc else 0.0), flush=True)
320 return 0
321 if max(du, dp) > 1e-12: # the run cannot be judged at this N: skip ARPACK (gsv9e.py reruns at 2N once)
322 print("PROD %s geom=%s N=%d D_hi=%g | rho=nan | top: - | matvecs=%d max_pcg_it=%d lin=%.1e kz0_leak=0.0e+00 "
323 "solver=%s conv=0 ncv=%d max_momentum_sweeps=%d%s dbl_fail=1" % (
324 a.mode, a.geom, N, a.D, stats["n"], stats["pit"], lin, dg.velocity_solver(), a.ncv, stats["msw"],
325 dbl), flush=True)
326 return 0
327 op = LinearOperator((nd, nd), matvec=mv, dtype=float)
328 conv = 1
329 try:
330 vals = eigs(op, k=a.k, which="LM", v0=v0, ncv=a.ncv, tol=1e-9, maxiter=a.maxiter,
331 return_eigenvectors=False)
332 except ArpackNoConvergence as ex: # report what converged; the caller decides (G-SV9(e))
333 conv, vals = 0, ex.eigenvalues
334 vals = sorted(vals, key=lambda z: -abs(z)) if len(vals) else [complex("nan")]
335 tag = "%s geom=%s%s N=%d Nz=%d mu=%g rho=%g D_hi=%g incr=%d prodsolve=%d kz0=%d p=%s mom_tol=%g" % (
336 a.mode, a.geom, "(%g,%g)" % (a.ang, a.off) if a.geom == "ext" else (("/sub8" if a.sub8 else "") + (
337 "/m=%s" % (a.m,) if a.m else "") + ("/frac=%g" % a.frac if a.geom == "pplane" else "") + (
338 "/roll=%s" % (a.roll,) if a.roll else "") + ("/deflated" if a.geom == "pplane" else "")), N, Nz,
339 muA, rA, a.D, a.incremental, a.prodsolve, a.kz0, a.pdriver, a.mom_tol)
340 print("PROD %s | rho=%.6f | top: %s | matvecs=%d max_pcg_it=%d lin=%.1e kz0_leak=%.1e solver=%s "
341 "conv=%d ncv=%d max_momentum_sweeps=%d" % (
342 tag, abs(vals[0]), " ".join("%.5f%+.5fi" % (z.real, z.imag) for z in vals[:4]), stats["n"],
343 stats["pit"], lin, stats["leak"], dg.velocity_solver(), conv, a.ncv, stats["msw"]) + dbl, flush=True)
344
345
346def main():
347 p = argparse.ArgumentParser()
348 sp = p.add_subparsers(dest="cmd", required=True)
349 h = sp.add_parser("harness")
350 h.add_argument("--N", type=int, default=16)
351 h.add_argument("--procs", type=int, default=12)
352 q = sp.add_parser("prod")
353 q.add_argument("--geom", choices=("ext", "plane", "film", "pplane"), default="ext")
354 q.add_argument("--N", type=int, default=16)
355 q.add_argument("--Nz", type=int, default=4)
356 q.add_argument("--ang", type=float, default=22.5)
357 q.add_argument("--off", type=float, default=0.3)
358 q.add_argument("--mode", choices=("sharp", "averaged"), default="sharp")
359 q.add_argument("--pair", default="1e-3,1e-4")
360 q.add_argument("--D", type=float, default=1e4)
361 q.add_argument("--kz0", action="store_true")
362 q.add_argument("--incremental", action="store_true")
363 q.add_argument("--prodsolve", action="store_true")
364 q.add_argument("--sub8", action="store_true")
365 q.add_argument("--pdriver", choices=("pcg", "fcg", "cheb"), default="cheb")
366 q.add_argument("--k", type=int, default=4)
367 q.add_argument("--ncv", type=int, default=30)
368 q.add_argument("--maxiter", type=int, default=200)
369 # the RB-GS update stop (residual stop off); G-SV9(e) runs 1e-13 (coordinator F1, 2026-11-01)
370 q.add_argument("--mom-tol", type=float, default=1e-15)
371 # WO-A5 (§6.8 A): fixed RB-GS sweeps per component (0 = off: the update stop above); G-SV9(e) runs 2000
372 q.add_argument("--mom-fixed", type=int, default=0)
373 q.add_argument("--ref-check", type=int, default=0) # WO-A5 acceptance only (needs --mom-fixed); no ARPACK
374 q.add_argument("--m", type=lambda t: tuple(float(x) for x in t.split(",")), default=None)
375 q.add_argument("--frac", type=float, default=0.5) # pplane layer fraction of phase A
376 q.add_argument("--roll", type=lambda t: tuple(int(x) for x in t.split(",")), default=None)
377 a = p.parse_args()
378 if a.cmd == "harness":
379 return cmd_harness(a)
380 a.muA, a.rA = (float(x) for x in a.pair.split(","))
381 return cmd_prod(a)
382
383
384if __name__ == "__main__":
385 sys.exit(main())
_harness_job(a)
Definition gsv9_split.py:91
cube_frac(m, al)
harness_case(N, ang, off, muA, rA, Ds, scheme)
Definition gsv9_split.py:41
colour(a, N, Nz)
plane_fractions(n, nrm, x0, sub=8)
Definition gsv9.py:57
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)