flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
probe_vofmom_rho.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""Case A Q6 diagnosis, lead L2: the density the vof_momentum predictor puts on the advected momentum.
3
4Under enable_vof_momentum the momentum rho^e u_e is carried on the half-shifted control volume (CV)
5with its own colour C^e, and the advected velocity is uAdv = (rho^e u)/rho^e. The predictor then
6builds its time term as rhoF * uAdv with rhoF = 0.5 (rho(C_i) + rho(C_i-1)), the arithmetic face
7mean of the CELL densities at n+1 (flow_ibm_project.hpp buildRhsVarMom), not rho^e. Per step the
8momentum the projection conserves, P_f = sum rhoF u, therefore changes by two reinterpretations:
9 SEED sum rho(C^{e,n}) u^n - sum rhoF^n u^n (advection start: C^e clipped from the C^n planes)
10 PRED sum (rhoF^{n+1} - rho^{e,n+1}) uAdv (predictor: the brief's L2 term)
11and the advection itself conserves sum rho^e u exactly (periodic box). Both are reported as a mean
12force density in units of <rho> g (sum / (n^3 dt <rho> g)), next to the closure's a/g, which must
13cancel every net momentum source at steady state (G5 probe_budget.py; a/g = s / dt / g).
14
15The march is the case-A driver's (run_case_a.build, full stress, single colour, vof_momentum).
16PRED and SEED need only Python accessors (vof_advected_velocity, vof_momentum_diagnostics).
17The FACE-WISE mismatch |rhoF - rho^e| / rho_l needs C^e, which is not exposed: each probe step is
18replayed by vofmom_probe (C++, the same MomentumConsistentAdvector on the dumped C^n, u^n), and the
19replay is accepted only if its uAdv and C^{n+1} match the solver's.
20
21Usage (host):
22 cmake -S tests/study/case_a/vofmom_probe -B build_vofmom_probe \\
23 -DCMAKE_PREFIX_PATH=$PWD/../extern/install/host-openmp && cmake --build build_vofmom_probe
24 OMP_NUM_THREADS=8 OMP_PROC_BIND=false PYTHONPATH=$PWD/build_host \\
25 python tests/study/case_a/probe_vofmom_rho.py --d-over-h 20 --t-probe 12 --out DIR
26Prints one summary line; DIR/steps.csv (one row per probe step), DIR/summary.txt.
27"""
28import argparse
29import os
30import subprocess
31import sys
32import time
33
34import numpy as np
35
36sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
37import run_case_a as ca # noqa: E402
38
39HERE = os.path.dirname(os.path.abspath(__file__))
40FLOW = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
41
42
43def rho_of(C):
44 return ca.RHO_L + (ca.RHO_G - ca.RHO_L) * C
45
46
47def face_rho(C, c):
48 """The predictor's rhoF: inner u_c[i] is the low face of cell i, pairs cells i-1 and i."""
49 r = rho_of(C)
50 return 0.5 * (r + np.roll(r, 1, axis=c))
51
52
53def put(path, a):
54 np.asarray(a, dtype=np.float64).ravel(order="F").tofile(path)
55
56
57def get(path, n):
58 return np.fromfile(path, dtype=np.float64).reshape((n, n, n), order="F")
59
60
61def main():
62 p = argparse.ArgumentParser()
63 p.add_argument("--d-over-h", type=int, default=20)
64 p.add_argument("--t-probe", type=float, default=12.0, help="march length in sqrt(d/g)")
65 p.add_argument("--n-probe", type=int, default=24, help="probe steps (a multiple of 6 sweeps)")
66 p.add_argument("--muscl", action="store_true")
67 p.add_argument("--out", required=True)
68 p.add_argument("--probe-bin", default=os.path.join(FLOW, "build_vofmom_probe", "vofmom_probe"))
69 a = p.parse_args()
70 os.makedirs(a.out, exist_ok=True)
71 n = round(ca.L_OVER_D * a.d_over_h)
72 s, h, alpha = ca.build(n, ca.MU_RATIO * ca.MU_L, "arithmetic", "full", single=True,
73 vof_mom=True, advection=True, vof_mom_muscl=a.muscl)
74 rho_av = ca.RHO_L + (ca.RHO_G - ca.RHO_L) * alpha
75 weps = s.diagnostics.vof_wisp_eps()
76 t, step, t0 = 0.0, 0, time.perf_counter()
77
78 def dt_rule():
79 L_ = s.vof_step_limits()
80 return 0.25 * min(L_["cfl_dt"], L_["capillary_dt"])
81
82 t_end = a.t_probe * ca.T_REF
83 while t < t_end:
84 dt = dt_rule()
85 s.set_dt(dt)
86 s.step()
87 t += dt
88 step += 1
89 t_march = time.perf_counter() - t0
90
91 rows = []
92 for k in range(a.n_probe):
93 C0 = np.array(s.get_vof())
94 U0 = [np.array(g()) for g in (s.get_u, s.get_v, s.get_w)]
95 parity = s.diagnostics.vof_step_parity()
96 dt = dt_rule()
97 s.set_dt(dt)
98 s.step()
99 t += dt
100 step += 1
101 C1 = np.array(s.get_vof())
102 # Both accessors hand out INTERNAL units (the raw uAdv_ field, the advector's census).
103 us = s.unit_scales
104 vti, dti = us["velocity_to_internal"], us["density_to_internal"]
105 UA = [np.array(s.diagnostics.vof_advected_velocity(c)) / vti[c] for c in range(3)]
106 sumM = [m_ / (dti * vti[c]) for c, m_ in
107 enumerate(s.diagnostics.vof_momentum_diagnostics()["sum_momentum"])]
108 shift = s.diagnostics.last_superficial_velocity_shift()
109 unit = n**3 * dt * rho_av * ca.G # sum of momentum density -> mean force / (<rho> g)
110 Pf0 = float(np.sum(face_rho(C0, 0) * U0[0]))
111 pred = float(np.sum(face_rho(C1, 0) * UA[0])) - sumM[0]
112 seed = sumM[0] - Pf0
113
114 # Replay for the face-wise C^e.
115 d = os.path.join(a.out, "replay")
116 os.makedirs(d, exist_ok=True)
117 # the advector's (rho_c0, rho_c1) = rho(C=0), rho(C=1); C = 1 is the gas here
118 with open(os.path.join(d, "meta.txt"), "w") as f:
119 f.write(f"{n} {dt / h!r} {parity} {ca.RHO_L!r} {ca.RHO_G!r} {weps!r} 0.25 {int(a.muscl)}\n")
120 put(os.path.join(d, "C.bin"), C0)
121 for c, nm in enumerate("uvw"):
122 put(os.path.join(d, f"{nm}.bin"), U0[c])
123 r = subprocess.run([a.probe_bin, d], capture_output=True, text=True,
124 env=dict(os.environ, OMP_NUM_THREADS="8", OMP_PROC_BIND="false"))
125 if r.returncode != 0:
126 sys.exit(f"vofmom_probe failed: {r.stderr[-400:]}")
127 Cn = get(os.path.join(d, "Cnew.bin"), n)
128 ua = [get(os.path.join(d, f"ua{c}.bin"), n) for c in range(3)]
129 Ce = [get(os.path.join(d, f"Ce{c}.bin"), n) for c in range(3)]
130 Cs = [get(os.path.join(d, f"Ce{c}_seed.bin"), n) for c in range(3)]
131 uscale = max(float(np.max(np.abs(UA[c]))) for c in range(3))
132 err_ua = max(float(np.max(np.abs(ua[c] - UA[c]))) for c in range(3)) / uscale
133 err_c = float(np.max(np.abs(Cn - C1)))
134 row = dict(k=k, step=step, parity=parity, dt=dt, err_ua=err_ua, err_c=err_c,
135 pred=pred / unit, seed=seed / unit, a_g=shift / dt / ca.G)
136 for c in range(3):
137 m = (face_rho(C1, c) - rho_of(Ce[c])) / ca.RHO_L # PRED mismatch, per face
138 ms = (face_rho(C0, c) - rho_of(Cs[c])) / ca.RHO_L # SEED mismatch, per face
139 nz = np.abs(m) > 1e-12
140 row[f"max_m{c}"] = float(np.max(np.abs(m)))
141 row[f"mean_m{c}"] = float(np.mean(np.abs(m[nz]))) if nz.any() else 0.0
142 row[f"nface{c}"] = int(nz.sum())
143 row[f"max_ms{c}"] = float(np.max(np.abs(ms)))
144 # the replay's own PRED / SEED sums (cross-check of the Python-only ones)
145 row[f"pred_r{c}"] = float(np.sum(m * ca.RHO_L * UA[c])) / unit
146 row[f"seed_r{c}"] = float(np.sum(-ms * ca.RHO_L * U0[c])) / unit
147 # Buoyancy projection (as probe_budget.py): the step's net reinterpretation force field
148 # f = [SEED + PRED] per face / dt against the buoyancy -(rho_f - <rho>) g, both weighted
149 # by the face gas pattern (C_f - alpha): the fraction by which it adds to the buoyancy.
150 Cf = 0.5 * (C1 + np.roll(C1, 1, axis=0))
151 f_x = ((face_rho(C1, 0) - rho_of(Ce[0])) * UA[0] + (rho_of(Cs[0]) - face_rho(C0, 0)) * U0[0]) / dt
152 b_x = -(face_rho(C1, 0) - rho_av) * ca.G
153 row["buoy_frac"] = float(np.sum(f_x * (Cf - alpha)) / np.sum(b_x * (Cf - alpha)))
154 rows.append(row)
155
156 keys = list(rows[0].keys())
157 with open(os.path.join(a.out, "steps.csv"), "w") as f:
158 f.write(",".join(keys) + "\n")
159 for r_ in rows:
160 f.write(",".join(repr(r_[k_]) for k_ in keys) + "\n")
161 M = {k_: np.array([r_[k_] for r_ in rows]) for k_ in keys}
162 line = (f"VOFMOM_RHO d/h={a.d_over_h} n={n} muscl={a.muscl} t*={t / ca.T_REF:.3f} steps={step} "
163 f"probe={a.n_probe} replay_err ua={M['err_ua'].max():.1e} C={M['err_c'].max():.1e} | "
164 f"PRED={M['pred'].mean():+.4e} (replay {M['pred_r0'].mean():+.4e}) "
165 f"SEED={M['seed'].mean():+.4e} (replay {M['seed_r0'].mean():+.4e}) "
166 f"PRED+SEED={(M['pred'] + M['seed']).mean():+.4e} a/g={M['a_g'].mean():+.4e} "
167 f"buoy_frac={M['buoy_frac'].mean():+.3e} (sd {M['buoy_frac'].std():.1e}) "
168 f"[<rho>g] | face |rhoF-rho^e|/rho_l x: max {M['max_m0'].max():.3e} "
169 f"mean(nonzero) {M['mean_m0'].mean():.3e} faces {M['nface0'].mean():.0f}/{n**3} "
170 f"seed max {M['max_ms0'].max():.3e}; y,z PRED {M['pred_r1'].mean():+.1e},"
171 f"{M['pred_r2'].mean():+.1e} | march {t_march:.0f}s")
172 with open(os.path.join(a.out, "summary.txt"), "w") as f:
173 f.write(line + "\n")
174 print(line)
175
176
177if __name__ == "__main__":
178 main()