1"""Quantitative validation of pnm.extract_network_flow against a peclet.flow DNS.
3Geometry: a periodic chamber-tube chain — two spherical chambers connected by a straight
4cylindrical tube along x (also through the periodic boundary). The watershed segments this into
54 pores (2 chambers + 2 tube segments) in a single loop, so by mass conservation EVERY pore-pore
6throat must carry the full DNS flux F (measured independently as the openness-weighted x-flux
7through a grid plane). Checks:
8 1. per-pore residual (signed flux over the whole pore boundary) ~ solver tolerance,
9 2. |Q_throat| == F for every throat (small leakage through near-wall faces allowed),
10 3. Q and the total-pressure drop dp agree in sign on every throat (g = Q/dp > 0),
11 4. the DNS plane flux is x-independent (steady, converged).
13Run: PYTHONPATH=<pnm/build>:<flow/build> python scripts/verify_network_flow.py
20import peclet.pnm
as pnm
23NX, NY, NZ = 48, 32, 32
25CY, CZ = NY / 2.0, NZ / 2.0
26CENTERS_X = (12.0, 36.0)
28x, y, z = np.meshgrid(np.arange(NX), np.arange(NY), np.arange(NZ), indexing=
"ij")
29x = x.astype(np.float64); y = y.astype(np.float64); z = z.astype(np.float64)
30sdf = np.full((NX, NY, NZ), -1e30)
33 dx = np.minimum(dx, NX - dx)
34 d = np.sqrt(dx**2 + (y - CY) ** 2 + (z - CZ) ** 2)
35 sdf = np.maximum(sdf, RC - d)
36sdf = np.maximum(sdf, RT - np.sqrt((y - CY) ** 2 + (z - CZ) ** 2))
40s = peclet.flow.Solver(NX, NY, NZ)
44s.set_body_force((FX, 0.0, 0.0))
46s.set_solid(np.asfortranarray(sdf), cutcell_pressure=
True)
50u, v, w = s.get_uf(), s.get_vf(), s.get_wf()
52ox, oy, oz = s.get_ox(), s.get_oy(), s.get_oz()
55F_planes = np.array([(ox[i, :, :] * u[i, :, :]).sum()
for i
in range(NX)])
57plane_dev = np.abs(F_planes - F).max() / abs(F)
58print(f
"DNS flux F = {F:.6e} (max plane deviation {plane_dev:.2e})")
61net = pnm.extract_network_flow(
62 np.ascontiguousarray(sdf.T, dtype=np.float32), [0.0, 0.0, 0.0], [1.0, 1.0, 1.0],
63 np.ascontiguousarray(u.T), np.ascontiguousarray(v.T), np.ascontiguousarray(w.T),
64 np.ascontiguousarray(p.T), np.ascontiguousarray(ox.T), np.ascontiguousarray(oy.T),
65 np.ascontiguousarray(oz.T), grad_p_zyx=[0.0, 0.0, -FX])
68Q = np.array(net[
"throat_flow"])
69dp = np.array(net[
"throat_dp"])
70res = np.array(net[
"pore_residual"])
71print(f
"pores: {len(pores)} throats: {len(net['throats'])}")
72for k, po
in enumerate(pores):
73 print(f
" pore {k+1}: x=({po.x:6.2f},{po.y:6.2f},{po.z:6.2f}) r={po.radius:5.2f} "
74 f
"p={net['pore_pressure'][k]: .4e} residual={res[k]: .3e}")
75for t, (a, b)
in enumerate(net[
"throats"]):
76 print(f
" throat {a}-{b}: Q={Q[t]: .6e} dp={dp[t]: .4e} A={net['throat_area'][t]:7.2f} "
77 f
"g=Q/dp={Q[t]/dp[t]: .4e}")
83 print(f
" [{'PASS' if ok else 'FAIL'}] {name}: {detail}")
84 fails += 0
if ok
else 1
88 """The momentum/volume extension on a tube network (Stokes, all tubes along x).
90 * Cauchy-Schwarz with the SAME discrete weights w = o*A as Q and A_t: on a PLANAR throat (all
91 faces share one normal, |n| = 1) M.n = sum w*un^2 >= Q^2/A_t. (A chamber-tube watershed
92 interface is a staircased cone, |n| ~ 0.5: there M.n is not sum w*un^2 and the bound is not
93 a theorem, so it is only reported.)
94 * Jensen with u.n > 0 (Stokes tube flow, throats oriented along Q): KE flux
95 sum w*|u|^2/2*un >= sum w*un^3/2 >= Q^3/(2 A_t^2), on every throat.
96 * the mean normal points along the tube axis (n/|n| = +-e_x) on the throats of on-axis tubes
97 (`on_axis`, default all; an off-axis capsule meets its chamber on a tilted interface), and
98 on the mirror-symmetric chain (`symmetric`) the momentum flux has no component across it
99 (|M_t| <= 1e-8 |M.n^|);
100 * the pore volumes partition the fluid (sdf > 0 cells) exactly;
101 * the volume-mean total pressure falls along the flow: throat_dp_mean has the sign of Q."""
102 Q = np.asarray(net[
"throat_flow"])
103 At = np.asarray(net[
"throat_area"])
104 M = np.asarray(net[
"throat_momentum_flux_zyx"])[:, ::-1]
105 K = np.asarray(net[
"throat_kinetic_energy_flux"])
106 N = np.asarray(net[
"throat_normal_zyx"])[:, ::-1]
107 dpm = np.asarray(net[
"throat_dp_mean"])
108 nrm = np.linalg.norm(N, axis=1)
109 Nh = N / nrm[:,
None]
110 planar = np.abs(nrm - 1.0) < 1e-12
111 Mn = np.einsum(
"ij,ij->i", M, Nh)
112 Mt = np.linalg.norm(M - Mn[:,
None] * Nh, axis=1)
113 cs = Mn / (Q**2 / At)
114 je = K / (Q**3 / (2 * At**2))
115 for t
in range(len(Q)):
116 print(f
" {tag} throat {t}: |n|={nrm[t]:.6f} n^_x={Nh[t,0]: .12f} M.n^/(Q^2/A)={cs[t]:.6f} "
117 f
"K/(Q^3/2A^2)={je[t]:.6f} |M_t|/|M.n^|={Mt[t]/abs(Mn[t]):.2e} dp_mean={dpm[t]: .4e}")
119 check(f
"{tag} momentum flux >= Q^2/A_t on planar throats (Cauchy-Schwarz)",
120 bool(planar.any()
and np.all(cs[planar] >= 1 - eps)),
121 f
"{int(planar.sum())}/{len(Q)} planar, min ratio {np.min(cs[planar]):.6f}")
122 check(f
"{tag} KE flux >= Q^3/(2 A_t^2) (Jensen, u.n > 0)", bool(np.all(je >= 1 - eps)),
123 f
"min ratio {np.min(je):.6f}")
124 ax = np.arange(len(Q))
if on_axis
is None else np.asarray(on_axis, int)
125 dev = np.abs(np.abs(Nh[ax, 0]) - 1)
126 check(f
"{tag} throat normal along the tube axis", bool(np.all(dev < 1e-12)),
127 f
"{len(ax)} on-axis throats, max ||n^_x|-1| = {np.max(dev):.2e}")
129 check(f
"{tag} tangential momentum flux ~ 0 (mirror-symmetric tube)",
130 bool(np.all(Mt <= 1e-8 * np.abs(Mn))), f
"max |M_t|/|M.n^| = {np.max(Mt / np.abs(Mn)):.2e}")
131 nfluid = int((sdf_xyz.astype(np.float32) > 0).sum())
132 vol = np.asarray(net[
"pore_volume"])
133 check(f
"{tag} pore volumes partition the fluid", abs(vol.sum() - nfluid) <= 1e-12 * nfluid,
134 f
"sum = {vol.sum():.1f} vs {nfluid} fluid cells")
135 check(f
"{tag} volume-mean pressure falls along the flow", bool(np.all(Q * dpm > 0)),
136 f
"signs Q*dp_mean: {np.sign(Q * dpm).astype(int).tolist()}")
139 W = np.asarray(net[
"throat_pressure_work_flux"])
140 th = np.asarray(net[
"throats"])
141 npo = len(net[
"pores"])
143 np.add.at(out, th[:, 0] - 1, W + K)
144 np.add.at(out, th[:, 1] - 1, -(W + K))
145 Vp = np.asarray(net[
"pore_volume"])
146 ux = np.asarray(net[
"pore_mean_velocity_zyx"])[:, 2]
149 print(f
" {tag} pore energy: body-force power {np.round(power, 6).tolist()}, "
150 f
"net (pW + KE) outflow {np.round(out, 6).tolist()}, D_p {np.round(D, 6).tolist()}")
151 check(f
"{tag} per-pore dissipation D_p > 0", bool(np.all(D > 0)),
152 f
"min D_p / body-force power = {np.min(D / power):.4f}")
154 check(f
"{tag} throat energy fluxes cancel globally", abs(out.sum()) <= 1e-12 * power.sum(),
155 f
"|sum net outflow| / sum power = {abs(out.sum()) / power.sum():.2e}")
157check(
"steady plane flux", plane_dev < 1e-6, f
"max deviation {plane_dev:.2e}")
160check(
"pore count", len(pores) == 3, f
"{len(pores)} (expect 3: 2 chambers + wrap tube segment)")
161check(
"single loop", len(net[
"throats"]) == len(pores),
162 f
"{len(net['throats'])} throats vs {len(pores)} pores")
163check(
"mass residuals", np.abs(res).max() < 1e-4 * abs(F),
164 f
"max |residual|/F = {np.abs(res).max()/abs(F):.2e}")
165check(
"throat flux = DNS flux", np.abs(np.abs(Q) - abs(F)).max() < 1e-3 * abs(F),
166 f
"max ||Q|-F|/F = {np.abs(np.abs(Q)-abs(F)).max()/abs(F):.2e}")
167check(
"Q, dp sign-consistent (g>0)", bool(np.all(Q * dp > 0)),
168 f
"signs: {np.sign(Q*dp).astype(int).tolist()}")
175print(
"\n=== case 2: asymmetric tube lattice ===")
177NX2, NY2, NZ2 = 48, 48, 48
178sdf2 = np.full((NX2, NY2, NZ2), -1e30)
179x, y, z = np.meshgrid(*(np.arange(d, dtype=np.float64)
for d
in (NX2, NY2, NZ2)), indexing=
"ij")
181for (cy, cz, rt)
in ((12.0, 12.0, 3.0), (12.0, 36.0, 4.0), (36.0, 12.0, 5.0), (36.0, 36.0, 6.0)):
182 for cx
in (12.0, 36.0):
183 dx = np.abs(x - cx); dx = np.minimum(dx, NX2 - dx)
184 sdf2 = np.maximum(sdf2, 9.0 - np.sqrt(dx**2 + (y - cy) ** 2 + (z - cz) ** 2))
185 sdf2 = np.maximum(sdf2, rt - np.sqrt((y - cy) ** 2 + (z - cz) ** 2))
186s = peclet.flow.Solver(NX2, NY2, NZ2)
187s.set_rho(1.0); s.set_mu(MU); s.set_dt(100.0)
188s.set_body_force((FX, 0.0, 0.0))
189s.set_advection(
False)
190s.set_solid(np.asfortranarray(sdf2), cutcell_pressure=
True)
193u, v, w, p = s.get_uf(), s.get_vf(), s.get_wf(), s.get_p()
194ox, oy, oz = s.get_ox(), s.get_oy(), s.get_oz()
195net2 = pnm.extract_network_flow(
196 np.ascontiguousarray(sdf2.T, dtype=np.float32), [0.0, 0.0, 0.0], [1.0, 1.0, 1.0],
197 np.ascontiguousarray(u.T), np.ascontiguousarray(v.T), np.ascontiguousarray(w.T),
198 np.ascontiguousarray(p.T), np.ascontiguousarray(ox.T), np.ascontiguousarray(oy.T),
199 np.ascontiguousarray(oz.T), grad_p_zyx=[0.0, 0.0, -FX])
200Q2 = np.array(net2[
"throat_flow"])
201dp2 = np.array(net2[
"throat_dp"])
202res2 = np.array(net2[
"pore_residual"])
203F2 = np.array([(ox[i, :, :] * u[i, :, :]).sum()
for i
in range(NX2)]).mean()
204print(f
"pores {len(net2['pores'])}, throats {len(Q2)}, F = {F2:.4e}")
205for t, (a, b)
in enumerate(net2[
"throats"]):
206 print(f
" throat {a}-{b}: Q={Q2[t]: .4e} dp={dp2[t]: .4e} g={Q2[t]/dp2[t]: .4e}")
207check(
"case2 mass residuals", np.abs(res2).max() < 1e-4 * abs(F2),
208 f
"max |residual|/F = {np.abs(res2).max()/abs(F2):.2e}")
209check(
"case2 g>0 on all throats", bool(np.all(Q2 * dp2 > 0)),
210 f
"{int((Q2*dp2 > 0).sum())}/{len(Q2)}")
213check(
"case2 total flux", abs(np.abs(Q2).sum() / 3.0 - abs(F2)) < 1e-2 * abs(F2),
214 f
"sum|Q|/3 = {np.abs(Q2).sum()/3.0:.4e} vs F = {F2:.4e}")
220print(
"\n=== case 3: chamber-tube chain, ghost-cell IBM ===")
222s = peclet.flow.Solver(NX, NY, NZ)
223s.set_rho(1.0); s.set_mu(MU); s.set_dt(100.0)
224s.set_body_force((FX, 0.0, 0.0))
225s.set_advection(
False)
226s.diagnostics.set_ghost_projection(
True)
227s.set_solid(np.asfortranarray(sdf), cutcell_pressure=
True)
230u, v, w, p = s.get_uf(), s.get_vf(), s.get_wf(), s.get_p()
231ox, oy, oz = s.get_ox_proj(), s.get_oy_proj(), s.get_oz_proj()
232F3_planes = np.array([(ox[i, :, :] * u[i, :, :]).sum()
for i
in range(NX)])
234plane_dev3 = np.abs(F3_planes - F3).max() / abs(F3)
235net3 = pnm.extract_network_flow(
236 np.ascontiguousarray(sdf.T, dtype=np.float32), [0.0, 0.0, 0.0], [1.0, 1.0, 1.0],
237 np.ascontiguousarray(u.T), np.ascontiguousarray(v.T), np.ascontiguousarray(w.T),
238 np.ascontiguousarray(p.T), np.ascontiguousarray(ox.T), np.ascontiguousarray(oy.T),
239 np.ascontiguousarray(oz.T), grad_p_zyx=[0.0, 0.0, -FX])
240Q3 = np.array(net3[
"throat_flow"])
241dp3 = np.array(net3[
"throat_dp"])
242res3 = np.array(net3[
"pore_residual"])
243print(f
"ghost DNS flux F = {F3:.6e} (vs cut-cell {F:.6e}); "
244 f
"{len(net3['pores'])} pores, {len(Q3)} throats")
245for t, (a, b)
in enumerate(net3[
"throats"]):
246 print(f
" throat {a}-{b}: Q={Q3[t]: .6e} dp={dp3[t]: .4e}")
252check(
"case3 steady plane flux (truncation)", plane_dev3 < 5e-2,
253 f
"max deviation {plane_dev3:.2e} (wall transpiration, converges ~O(h^2))")
254check(
"case3 mass residuals (truncation)", np.abs(res3).max() < 5e-2 * abs(F3),
255 f
"max |residual|/F = {np.abs(res3).max()/abs(F3):.2e}")
256check(
"case3 throat flux = DNS flux (truncation)",
257 np.abs(np.abs(Q3) - abs(F3)).max() < 6e-2 * abs(F3),
258 f
"max ||Q|-F|/F = {np.abs(np.abs(Q3)-abs(F3)).max()/abs(F3):.2e}")
259check(
"case3 g>0 on all throats", bool(np.all(Q3 * dp3 > 0)),
260 f
"signs: {np.sign(Q3*dp3).astype(int).tolist()}")
261check(
"case3 flux agrees with cut-cell IBM", abs(F3 - F) < 0.10 * abs(F),
262 f
"rel diff {(F3-F)/F:.2%} (coarse tube: r = 4 cells)")
269print(
"\n=== case 4: parallel capsule throats ===")
271NX4, NY4, NZ4 = 48, 32, 32
272x, y, z = np.meshgrid(*(np.arange(d, dtype=np.float64)
for d
in (NX4, NY4, NZ4)), indexing=
"ij")
273sdf4 = np.full((NX4, NY4, NZ4), -1e30)
274for cx
in (12.0, 36.0):
275 dx = np.abs(x - cx); dx = np.minimum(dx, NX4 - dx)
276 sdf4 = np.maximum(sdf4, 8.0 - np.sqrt(dx**2 + (y - 16.0) ** 2 + (z - 16.0) ** 2))
279for (cy, rt)
in ((12.0, 3.0), (20.0, 4.2)):
280 xs = np.clip(x, 12.0, 36.0)
281 sdf4 = np.maximum(sdf4, rt - np.sqrt((x - xs) ** 2 + (y - cy) ** 2 + (z - 16.0) ** 2))
282xw = np.where(x < 12.0, x + NX4, x)
283xs = np.clip(xw, 36.0, 12.0 + NX4)
284sdf4 = np.maximum(sdf4, 4.0 - np.sqrt((xw - xs) ** 2 + (y - 16.0) ** 2 + (z - 16.0) ** 2))
286s = peclet.flow.Solver(NX4, NY4, NZ4)
287s.set_rho(1.0); s.set_mu(MU); s.set_dt(100.0)
288s.set_body_force((FX, 0.0, 0.0))
289s.set_advection(
False)
290s.set_solid(np.asfortranarray(sdf4), cutcell_pressure=
True)
293u, v, w, p = s.get_uf(), s.get_vf(), s.get_wf(), s.get_p()
294ox, oy, oz = s.get_ox(), s.get_oy(), s.get_oz()
295F4 = np.array([(ox[i, :, :] * u[i, :, :]).sum()
for i
in range(NX4)]).mean()
296net4 = pnm.extract_network_flow(
297 np.ascontiguousarray(sdf4.T, dtype=np.float32), [0.0, 0.0, 0.0], [1.0, 1.0, 1.0],
298 np.ascontiguousarray(u.T), np.ascontiguousarray(v.T), np.ascontiguousarray(w.T),
299 np.ascontiguousarray(p.T), np.ascontiguousarray(ox.T), np.ascontiguousarray(oy.T),
300 np.ascontiguousarray(oz.T), grad_p_zyx=[0.0, 0.0, -FX])
301Q4 = np.array(net4[
"throat_flow"])
302dp4 = np.array(net4[
"throat_dp"])
303res4 = np.array(net4[
"pore_residual"])
304th4 = net4[
"throats"].tolist()
305print(f
"pores {len(net4['pores'])}, throats {len(Q4)}, F = {F4:.4e}")
306for t, (a, b)
in enumerate(th4):
307 print(f
" throat {a}-{b}: Q={Q4[t]: .6e} dp={dp4[t]: .4e} A={net4['throat_area'][t]:7.2f}")
308par = [t
for t, ab
in enumerate(th4)
if ab == [1, 2]]
309check(
"case4 pore count", len(net4[
"pores"]) == 3, f
"{len(net4['pores'])} (2 chambers + wrap pore)")
310check(
"case4 parallel pair (1,2) twice", len(par) == 2,
311 f
"pair (1,2) appears {len(par)}x of {len(Q4)} throats")
312check(
"case4 mass residuals", np.abs(res4).max() < 1e-4 * abs(F4),
313 f
"max |residual|/F = {np.abs(res4).max()/abs(F4):.2e}")
315 qA, qB = Q4[par[0]], Q4[par[1]]
316 check(
"case4 parallel split sums to F", abs(qA + qB - F4) < 1e-3 * abs(F4),
317 f
"Q_A + Q_B = {qA+qB:.6e} vs F = {F4:.6e}")
318 check(
"case4 both capsules carry forward flow", qA > 0
and qB > 0,
319 f
"Q_A = {qA:.3e}, Q_B = {qB:.3e}")
320 check(
"case4 fatter capsule carries more", max(qA, qB) > 1.5 * min(qA, qB),
321 f
"ratio {max(qA,qB)/min(qA,qB):.2f} (radii 4.5 vs 3)")
322wrapT = [t
for t, ab
in enumerate(th4)
if ab != [1, 2]]
323check(
"case4 wrap throats carry F", bool(np.all(np.abs(np.abs(Q4[wrapT]) - abs(F4)) < 1e-3 * abs(F4))),
324 f
"|Q| = {np.abs(Q4[wrapT]).tolist()}")
325check(
"case4 g>0 on all throats", bool(np.all(Q4 * dp4 > 0)),
326 f
"signs: {np.sign(Q4*dp4).astype(int).tolist()}")
329print(
"PASS" if fails == 0
else f
"FAIL ({fails})")
331sys.exit(1
if fails
else 0)
check_momentum(tag, net, sdf_xyz, symmetric, on_axis=None)