flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
probe_budget.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""Case A G5 diagnosis, step 1: the discrete momentum budget behind the closure acceleration.
3
4set_superficial_velocity applies, at the end of every step, one uniform shift s of u_x on every
5face, i.e. a uniform ACCELERATION a = s/dt, which in the velocity form is the force density
6rho_f * a. In the continuum the steady (translating) state has a = 0: the total momentum
7P = sum_f rho_f u_f is constant and every other force sums to zero. Discretely
8
9 P^{n+1} - P^n = sum rho^n_f (u* - u^n) [predictor; the projection sums to zero]
10 + sum (rho^{n+1}_f - rho^n_f) u^{n+1,pre} [the density change, VoF]
11 + sum rho^{n+1}_f s [the closure]
12
13and the predictor part is dt * sum(-rho_f A(u) + f_csf + T_fullstress + f_grav). Per term, as a
14mean force density in units of <rho> g (so that, at steady state, the terms sum to +a/g... with
15the sign below: closure = -(sum of the others)):
16
17 ADV -sum rho_f A(u) from a twin solver stepped once with advection toggled
18 (the solver default and the case-A runs: advection OFF; the twin
19 then measures what the missing term would contribute)
20 VISC sum T (transpose part) from a twin stepped once with set_viscous_stress('laplacian')
21 CSF sum f_csf diagnostics.vof_block_force (the field the RHS adds)
22 GRAV sum -(rho - <rho>) g from C^n (zero by construction)
23 DRHO sum (rho^{n+1}-rho^n) u^{n+1,pre} / dt
24 PRED sum rho^n_f (u^{n+1,pre} - u^n) / dt (= ADV + VISC + CSF + GRAV + solver residual)
25
26The twins are bitwise copies of the main solver up to the probe step (checked). After the probe
27the main solver alone runs on over --avg-crossings box crossings, recording PRED, CSF, DRHO,
28GRAV and the closure every step; with --advection, ADV over the window = PRED - CSF - VISC - GRAV.
29
30Also: the projection of each recorded force field on the buoyancy pattern (C - alpha), relative
31to the buoyancy's own, i.e. the fraction by which the term adds to the effective buoyancy.
32
33Usage (host, <= 4 threads):
34 OMP_NUM_THREADS=4 OMP_PROC_BIND=false PYTHONPATH=$PWD/build_host \\
35 python tests/study/case_a/probe_budget.py --d-over-h 20 --t-probe 10 --out DIR
36Prints one summary line; DIR/budget.csv per step, DIR/summary.txt.
37"""
38
39import argparse
40import os
41import sys
42
43import numpy as np
44
45sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
46import run_case_a as ca
47
48
49def fields(s):
50 return [np.array(g()) for g in (s.get_u, s.get_v, s.get_w)], np.array(s.get_vof())
51
52
53SHIFT = [
54 1
55] # inner u[i] pairs with cells i-1, i (rhoF = 0.5 (rf(i) + rf(i - strd)), buildRhsVar)
56
57
58def face_rho(C, c):
59 rho = ca.RHO_L + (ca.RHO_G - ca.RHO_L) * C
60 return 0.5 * (rho + np.roll(rho, SHIFT[0], axis=c))
61
62
63def face_avg(F, c):
64 return 0.5 * (F + np.roll(F, 1, axis=c))
65
66
67def main():
68 p = argparse.ArgumentParser()
69 p.add_argument("--d-over-h", type=int, default=20)
70 p.add_argument("--t-probe", type=float, default=10.0)
71 p.add_argument("--avg-crossings", type=float, default=2.0)
72 p.add_argument("--stress", default="full")
73 p.add_argument("--advection", action="store_true")
74 p.add_argument(
75 "--twin-tol",
76 type=float,
77 default=None,
78 help="instead of toggling advection, the twin B runs the probe step at this "
79 "momentum residual tolerance; TOL = PRED_A - PRED_B is the solve residual",
80 )
81 p.add_argument("--out", required=True)
82 a = p.parse_args()
83 os.makedirs(a.out, exist_ok=True)
84 n = round(ca.L_OVER_D * a.d_over_h)
85 mk = lambda: ca.build(n, ca.MU_G, "arithmetic", a.stress, advection=a.advection)
86 (A, _, alpha), (B, _, _), (Cs, _, _) = mk(), mk(), mk()
87 rho_av = ca.RHO_L + (ca.RHO_G - ca.RHO_L) * alpha
88 unit = rho_av * ca.G # N/m^3: force densities reported in <rho> g
89 buoy_c = lambda C: (
90 (ca.RHO_L - ca.RHO_G) * ca.G * face_avg(C - alpha, 0)
91 ) # +x on gas
92 t, t_end = 0.0, a.t_probe * ca.T_REF
93 step = 0
94 while t < t_end:
95 L_ = A.vof_step_limits()
96 dt = 0.25 * min(L_["cfl_dt"], L_["capillary_dt"])
97 for s in (A, B, Cs):
98 s.set_dt(dt)
99 s.step()
100 t += dt
101 step += 1
102 # the internal force unit is fixed by the FIRST set_dt (tRef): read it only after stepping
103 fi = A.unit_scales["force_density_to_internal"]
104 uA, CA = fields(A)
105 same = all(
106 np.array_equal(x, y)
107 for s in (B, Cs)
108 for x, y in zip(uA + [CA], fields(s)[0] + [fields(s)[1]])
109 )
110
111 def probe(s, un, Cn, dt):
112 s.set_dt(dt)
113 s.step()
114 u1, C1 = fields(s)
115 sh = s.diagnostics.last_superficial_velocity_shift()
116 u1[0] = u1[0] - sh
117 pred = [np.sum(face_rho(Cn, c) * (u1[c] - un[c])) / dt for c in range(3)]
118 drho = [
119 np.sum((face_rho(C1, c) - face_rho(Cn, c)) * u1[c]) / dt for c in range(3)
120 ]
121 SHIFT[0] = -SHIFT[0]
122 alt = [np.sum(face_rho(Cn, c) * (u1[c] - un[c])) / dt for c in range(3)]
123 SHIFT[0] = -SHIFT[0]
124 probe.alt = alt
125 return pred, drho, u1, C1, sh
126
127 L_ = A.vof_step_limits()
128 dt = 0.25 * min(L_["cfl_dt"], L_["capillary_dt"])
129 if a.twin_tol is None:
130 B.set_advection(
131 not a.advection
132 ) # the twin toggles advection; ADV = +-(PRED_B - PRED_A)
133 else:
134 B.set_velocity_residual_tolerance(a.twin_tol)
135 Cs.set_viscous_stress("laplacian")
136 N = float(n**3)
137 predB = probe(B, uA, CA, dt)[0]
138 predB_alt = probe.alt
139 csfB = [
140 float(np.sum(np.array(B.diagnostics.vof_block_force(c)) / fi[c]))
141 for c in range(3)
142 ]
143 resB_pair = [
144 [(pb[c] - csfB[c]) / N / unit for c in range(3)] for pb in (predB, predB_alt)
145 ]
146 predC = probe(Cs, uA, CA, dt)[0]
147 rows = []
148 un, Cn = uA, CA
149 n_avg = None
150 k = 0
151 P_hist = []
152 while True:
153 pred, drho, u1, C1, sh = probe(A, un, Cn, dt)
154 csf_f = [np.array(A.diagnostics.vof_block_force(c)) / fi[c] for c in range(3)]
155 csf = [float(np.sum(f)) for f in csf_f]
156 grav = float(
157 np.sum(-(ca.RHO_L - rho_av) * ca.G - (ca.RHO_G - ca.RHO_L) * ca.G * Cn)
158 )
159 P = float(np.sum(face_rho(Cn, 0) * un[0]))
160 P_hist.append((k, P))
161 # projections on the buoyancy pattern (x component): fraction of the buoyancy drive
162 bx = buoy_c(Cn)
163 nb = float(np.sum(bx * face_avg(Cn - alpha, 0)))
164 wb = face_avg(Cn - alpha, 0)
165
166 def proj(F, wb=wb, nb=nb):
167 return float(np.sum(F * wb)) / nb
168
169 clos_field = face_rho(C1, 0) * sh / dt
170 rows.append(
171 [k, dt, sh / dt / ca.G]
172 + [x / N / unit for x in pred]
173 + [x / N / unit for x in drho]
174 + [x / N / unit for x in csf]
175 + [
176 grav / N / unit,
177 proj(csf_f[0]),
178 proj(clos_field),
179 float(np.sum(face_rho(C1, 0) * sh)) / dt / N / unit,
180 ]
181 )
182 if k == 0:
183 sg = (1.0 if a.advection else -1.0) if a.twin_tol is None else 1.0
184 adv0 = [sg * (pred[c] - predB[c]) / N / unit for c in range(3)]
185 visc0 = [(pred[c] - predC[c]) / N / unit for c in range(3)]
186 resB = [
187 (predB[c] - csf[c] - grav * (c == 0) - (pred[c] - predC[c])) / N / unit
188 for c in range(3)
189 ]
190 # cell-centre u_x of cell i = faces i, i+1 (face_avg is cell -> face, the other way)
191 ub = float(np.sum(C1 * 0.5 * (u1[0] + np.roll(u1[0], -1, axis=0))) / np.sum(C1))
192 n_avg = int(a.avg_crossings * ca.L_OVER_D * ca.D / max(ub, 1e-9) / dt)
193 un = [x.copy() for x in u1]
194 un[0] = un[0] + sh
195 Cn = C1
196 k += 1
197 if k > n_avg:
198 break
199 L_ = A.vof_step_limits()
200 dt = 0.25 * min(L_["cfl_dt"], L_["capillary_dt"])
201 R = np.array(rows)
202 hdr = (
203 "k,dt,a_g,pred_x,pred_y,pred_z,drho_x,drho_y,drho_z,csf_x,csf_y,csf_z,grav,"
204 "csf_proj_buoy,closure_proj_buoy,closure_force"
205 )
206 np.savetxt(os.path.join(a.out, "budget.csv"), R, delimiter=",", header=hdr)
207 m = R.mean(axis=0)
208 adv_mean = (m[3] - m[9] - visc0[0] - m[12]) if a.advection else 0.0
209 P0, P1 = P_hist[0][1], P_hist[-1][1]
210 dPdt = (P1 - P0) / (R[:, 1].sum()) / N / unit
211 line = (
212 f"BUDGET d/h={a.d_over_h} stress={a.stress} adv={a.advection} twin={'adv' if a.twin_tol is None else f'tol {a.twin_tol:g} (ADV(step0) := TOL)'} t_probe*={a.t_probe} twins_bitwise={same} "
213 f"steps_avg={len(R)} [units <rho>g, x] closure a/g={m[2]:+.5e} "
214 f"closure_force={m[15]:+.5e} PRED={m[3]:+.5e} DRHO={m[6]:+.5e} CSF={m[9]:+.5e} "
215 f"GRAV={m[12]:+.2e} ADV(step0)={adv0[0]:+.5e} VISC(step0)={visc0[0]:+.3e} "
216 f"ADV(win)={adv_mean:+.5e} residB(x,y,z)=({resB[0]:+.1e},{resB[1]:+.1e},{resB[2]:+.1e}) "
217 f"predB-csfB(pair i-1,i)={resB_pair[0]} (pair i,i+1)={resB_pair[1]} "
218 f"dP/dt={dPdt:+.2e} sum(PRED+DRHO+clos)={m[3] + m[6] + m[15]:+.2e} "
219 f"pred_yz=({m[4]:+.1e},{m[5]:+.1e}) csf_yz=({m[10]:+.1e},{m[11]:+.1e}) "
220 f"proj_buoy: CSF={m[13]:+.5f} closure={m[14]:+.5f} "
221 f"step0: PRED={rows[0][3]:+.5e} CSF={rows[0][9]:+.5e} DRHO={rows[0][6]:+.5e}"
222 )
223 with open(os.path.join(a.out, "summary.txt"), "w") as f:
224 f.write(line + "\n")
225 print(line)
226
227
228if __name__ == "__main__":
229 main()