flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
test_projected_guess.py
Go to the documentation of this file.
1#!/usr/bin/env python
2"""Gate: the projected initial guess of the projection solve (E, doc/vof_projection_cost_design.md
3§5.3; `diagnostics.set_pressure_initial_guess`), opt-in, on the single-rank PCG and FCG drivers.
4
5Configuration: the IBM cylinder (16^3, cylinder along y of radius N/4, cut-cell pressure, Stokes,
6body force 1e-3, rtol 1e-8), 'projected' with history 2 against 'zero' on the same build.
7 G-E3 step 1 of 'projected' (empty history: the cold solve) is bitwise step 1 of 'zero'; after a
8 state write (set_velocity: the history restarts) the next step is bitwise the same step
9 of a twin switched to 'zero' -- and the twin continued under 'projected' is NOT, so the
10 guess was live;
11 G-E2 every guessed solve ends at max|P(b - A x)| <= 1.5 rtol max|P b| (recomputed; the trace of
12 a child run under PECLET_FLOW_MG_DEBUG=2 and _SOLVES, debug output only), x0 = 0 on
13 every non-fluid cell, and 'projected' saves iterations over the run;
14 raise 'projected' under the Chebyshev driver raises at the step, naming the condition; 'auto'
15 there runs the cold solve, bitwise 'zero'.
16
17Run: OMP_NUM_THREADS=4 OMP_PROC_BIND=false PYTHONPATH=<build> python tests/python/test_projected_guess.py
18Exit 0 pass, 1 fail, 77 skipped (no module).
19"""
20import os
21import re
22import subprocess
23import sys
24
25import numpy as np
26
27try:
28 import peclet.flow as pf
29except ImportError:
30 print("SKIP: peclet.flow not importable")
31 sys.exit(77)
32
33N, RTOL, STEPS = 16, 1e-8, 12
34fails = 0
35
36
37def check(ok, what):
38 global fails
39 print(f" {what:96s} {'PASS' if ok else 'FAIL'}", flush=True)
40 if not ok:
41 fails += 1
42
43
44def solver(guess, driver="pcg"):
45 X, _, Z = np.meshgrid(*(np.arange(N) + 0.5,) * 3, indexing="ij")
46 sdf = np.sqrt((X - N / 2) ** 2 + (Z - N / 2) ** 2) - 0.25 * N
47 s = pf.Solver(N, N, N)
48 s.set_rho(1.0)
49 s.set_mu(0.01)
50 s.set_dt(1.0)
51 s.set_advection(False)
52 s.set_body_force((1e-3, 0.0, 0.0))
53 s.set_pressure_multigrid(True, levels=3)
54 s.set_solid(np.asfortranarray(sdf), cutcell_pressure=True)
55 if driver == "fcg":
56 s.set_pressure_fcg(True, 400, RTOL)
57 elif driver == "cheb":
58 s.set_pressure_chebyshev(True, 400, RTOL)
59 else:
60 s.set_pressure_pcg(True, 400, RTOL)
61 s.diagnostics.set_pressure_initial_guess(guess, 2)
62 return s
63
64
65def state(s):
66 return np.concatenate([np.asarray(a, dtype=np.float64).ravel()
67 for a in (s.get_u(), s.get_v(), s.get_w(), s.get_p())])
68
69
70def same(a, b):
71 return a.shape == b.shape and np.array_equal(a.view(np.uint64), b.view(np.uint64))
72
73
74def child(driver):
75 """G-E2 run: 'projected' for STEPS steps (traced by the parent's env)."""
76 s = solver("projected", driver)
77 for _ in range(STEPS):
78 s.step()
79
80
81def e3(driver):
82 a, z = solver("projected", driver), solver("zero", driver)
83 a.step()
84 z.step()
85 check(same(state(a), state(z)), f"{driver}: G-E3 step 1 of 'projected' == 'zero', bitwise")
86 b = solver("projected", driver) # twin of a
87 b.step()
88 for _ in range(4):
89 a.step()
90 b.step()
91 c = solver("projected", driver) # a continued without any reset
92 for _ in range(5):
93 c.step()
94 for k in range(3): # the state write: restarts a's history, same values
95 a.set_velocity(k, np.asfortranarray(np.asarray((a.get_u(), a.get_v(), a.get_w())[k])))
96 b.diagnostics.set_pressure_initial_guess("zero", 2)
97 for t in (a, b, c):
98 t.step()
99 check(same(state(a), state(b)),
100 f"{driver}: G-E3 the step after set_velocity == the twin's 'zero' step, bitwise")
101 check(not same(state(c), state(b)), f"{driver}: the guess is live (no reset: not bitwise 'zero')")
102
103
104def e2(driver):
105 env = dict(os.environ, PECLET_FLOW_MG_DEBUG="2", PECLET_FLOW_MG_DEBUG_SOLVES=str(STEPS + 2))
106 out = subprocess.run([sys.executable, __file__, "--child", driver], env=env,
107 capture_output=True, text=True, check=False)
108 rows = re.findall(r"\‍[mg\‍] guess solve \d+: hist (\d) .*? iters (\d+) .*?resid/rref (\S+) "
109 r"x0_nonfluid_nonzero (\d+)", out.stdout)
110 guessed = [r for r in rows if int(r[0]) > 0]
111 worst = max((float(r[2]) for r in guessed), default=float("nan"))
112 nz = sum(int(r[3]) for r in guessed)
113 check(out.returncode == 0 and len(guessed) >= STEPS - 2 and worst <= 1.5 * RTOL and nz == 0,
114 f"{driver}: G-E2 {len(guessed)} guessed solves, max resid/rref {worst:.3e} <= 1.5 rtol, "
115 f"x0 on solids {nz}")
116 zero = solver("zero", driver)
117 proj = solver("projected", driver)
118 iz = ip = 0
119 for _ in range(STEPS):
120 zero.step()
121 proj.step()
122 iz += zero.diagnostics.last_pressure_iterations()
123 ip += proj.diagnostics.last_pressure_iterations()
124 check(ip < iz, f"{driver}: iterations over {STEPS} steps 'zero' {iz} -> 'projected' {ip}")
125
126
127def raises():
128 s = solver("projected", "cheb")
129 what = ""
130 try:
131 s.step()
132 except RuntimeError as e:
133 what = str(e)
134 check("not eligible here" in what and "Chebyshev" in what,
135 "Chebyshev: 'projected' raises at the step: " + (what[:60] or "(no raise!)"))
136 a, z = solver("auto", "cheb"), solver("zero", "cheb")
137 for _ in range(3):
138 a.step()
139 z.step()
140 check(same(state(a), state(z)), "Chebyshev: 'auto' == 'zero', bitwise")
141
142
143if __name__ == "__main__":
144 if len(sys.argv) >= 3 and sys.argv[1] == "--child":
145 child(sys.argv[2])
146 sys.exit(0)
147 print("projected_guess (doc/vof_projection_cost_design.md §5.3, G-E2, G-E3)")
148 for d in ("pcg", "fcg"):
149 e3(d)
150 e2(d)
151 raises()
152 print(f"{'FAIL' if fails else 'PASS'} ({fails} failure{'s' if fails != 1 else ''})")
153 sys.exit(1 if fails else 0)