2"""Cut-cell scalar transport: the accuracy and iteration gates of WO-3 to WO-6 (doc/scalar_ibm_design.md §11).
4Single phase; diffusion, and advection by the projection's face flux (WO-5); BiCGStab preconditioned by one ScalarMG V-cycle (WO-4; level 0 alone
5under the transient level rule). Every case is in PHYSICAL units (an extent), so the unit
6conversions of §1.2 are on the path.
8 api the opt-in, the refusals and the name checks (cheap).
9 g1 Dirichlet sphere, steady: Nu -> 2 (order >= 1.7), field L1 / Linf orders (>= 1.8 / 1.5),
10 the steady budget identity, R0 = 100 %; plus the anisotropic h' = (1, 1, 2) ladder.
11 g2 concentric shells, steady: Neumann flux q on the inner sphere, an immersed Dirichlet outer
12 sphere (a two-instance scene): area-mean wall value c_Gamma (order >= 1.7), field L1.
13 g3a Robin external sphere, steady, Da = kR/D in {0.1, 1, 10, 100}: Sh = 2 Da/(1 + Da).
14 g3b Robin interior sphere, transient, Bi in {0.1, 1, 10, 100, inf}: the backward-Euler
15 late-time ratio of the total mass gives the spatial eigenvalue mu = D lam^2/R^2,
16 lam cot lam = 1 - Bi; the budget identity every step.
17 g7 pipe (an SDF along z, nz = 4 periodic): Dirichlet decay j01^2 and Neumann dipole decay
18 j'11^2 (BE ratio), and the Graetz number Nu_T = 3.656793 by inverse iteration with
19 solve_scalar_steady (G7a, G7b).
20 g9 advection in an annulus (WO-5): solid-body rotation carrying a Gaussian blob one revolution,
21 fou / koren at bulk Courant 0.5 / 0.9: per-step budget identity, conservation against the
22 accounted defects, positivity (koren gated at bulk Courant <= 1/2, ruling D-WO5-1; its 0.9
23 row is information), finiteness, slivers (min kappa < 1e-2).
24 g9c open domain faces (WO-5b, ruling D-WO5-3): a channel with a solid sphere, inflow / walls /
25 outflow, the scalar carried by flow's own projection: the per-step budget, boundary
26 advective and diffusive fluxes included, closes to <= 1e-13 of the mass change; constant
27 preservation; boundedness; a steady row; the collocated grid is refused (open question).
28 g9b constant preservation under flow's own projection (Stokes through an SC array, c = 1):
29 staggered and the collocated 'gauge-exact', 'plain', 'embed' pass; the ghost projection
31 gadv §11 G-adv (WO-5c, design Amendment A2: the steady advective surrogate), Pe_h = the census
32 max_cell_peclet 0.1 / 1 / 10 by rescaling the face field: (a) WO-5's C3 problem (periodic
33 box 4R, a Dirichlet sphere with a source, a projected Stokes field) at R/h 16 and 32;
34 (b) the closure on G9b's SC array (Neumann spheres, singular, the mean-gradient mode of
35 WO-6 with G = e_x) and (b')
36 the same with Dirichlet spheres, 32^3 and 64^3; (c) G9c's channel (open faces), Pe_h 1 and
37 10 (set through D). (i) converged, (ii) iteration bounds (Q20: min(prov., 2x measured)), (iii) growth per
38 doubling <= 1.7x, (v) the steady budget identity <= 1e-11 of the gross budget (D-WO5c-1). (iv) C4 is in the
39 `scalar_mg` ctest, (vi) a one-time logged check.
40 g8 Taylor-Aris (WO-6): G7's pipe, frozen face-averaged Poiseuille fluxes (D-WO6-1), insulating walls, the
41 mean-gradient mode G = e_z, steady (advecting, singular): -<u'theta> -> Pe^2 D/48 at
42 Pe = 10 (order >= 1.8, <= 1e-3 at R/h 32), scalar_mean_flux = its field sums to 1e-10;
43 G-iter (<= 30, growth <= 5) on multigrid-friendly boxes (ruling D-WO4-1).
44 g5b the insulating periodic SC array (c = 0.3) in the mean-gradient mode (WO-6): k* =
45 -J_x/(D G_x) from scalar_mean_flux, self-convergence order >= 1.7, k* below the
46 Hashin-Shtrikman bound; G-iter on multigrid-friendly boxes; the no-solid identity k* = 1
47 to 1e-12 (at rest, and under a uniform flow: the moving frame).
48 giter §11 G-iter, the rows not carried by g1/g2/g3a: transient at dt D/h^2 = 1 (<= 10 per warm
49 step, ruling D-WO4-3 restating the provisional 8; <= 12 on the cold first step, ruling
50 D-WO9-3, which moved the level-rule switch so that this row runs level 0 alone) and the singular
51 steady problem on G5b's geometry (periodic simple-cubic array, c = 0.3, insulating + flux +
52 source; <= 30, growth <= 5 per rung) on multigrid-friendly n.
54 g13 contacts (WO-8): two spheres R in a box (6R, 4R, 4R), R/h 8 / 16 / 32, steady: Dirichlet
55 spheres at a gap R/32 and in contact (overlap R/64), far field 0, and the contacting pair
56 conjugate at Lam_s/Lam_f = 100 under a far-field gradient: converged, <= 50 iterations,
57 census two-sided > 0 (where the gap is under a cell), R2 <= 1 % of the probes, total-flux
58 self-convergence order >= 1.0; the 0.4 h thin plate: num_thin_solid > 0 and the §9
61Every gate runs its FULL resolution ladder (WO-4; ruling D-WO3-1 had deferred the steady ones).
62"Order" is between successive rungs of the RMS error over 3 random grid offsets; every successive
63pair is gated. G-iter on g1/g2/g3a (Da = 1): <= 20 BiCGStab iterations at every rung, growth <= 3
64per doubling (the max over the offsets of each rung). Ruling Q-C (WO-4): G-iter is gated on
65multigrid-friendly boxes (n rounded up to a multiple of 2^(rungs + 1) = 16); a box with few factors
66of two stays gated for correctness only (G2's native box). Iteration counts are printed.
68Run: OMP_NUM_THREADS=4 PYTHONPATH=<build> python tests/python/test_scalar_cutcell_gates.py <gate>
69Exit 0 pass, 1 fail, 77 skipped (no module).
80 print(
"SKIP: peclet.flow not importable")
83FACES = (
"-x",
"+x",
"-y",
"+y",
"-z",
"+z")
84OFFSETS = np.random.default_rng(20261003).uniform(-0.5, 0.5, size=(3, 3))
89 print((
" ok " if cond
else " FAIL ") + msg)
95 v = np.asarray(v, dtype=float)
96 return float(np.sqrt(np.mean(v * v)))
100 return math.log2(ec / ef)
if ec > 0
and ef > 0
else float(
"inf")
104 x, y, z = s.cell_centers()
105 return np.meshgrid(x, y, z, indexing=
"ij")
109 """Face-centre coordinates (X, Y, Z) of a domain face, shaped (N_t1, N_t2)."""
110 x, y, z = s.cell_centers()
111 lo = [x[0] - 0.5 * (x[1] - x[0]), y[0] - 0.5 * (y[1] - y[0]), z[0] - 0.5 * (z[1] - z[0])]
112 hi = [x[-1] + 0.5 * (x[1] - x[0]), y[-1] + 0.5 * (y[1] - y[0]), z[-1] + 0.5 * (z[1] - z[0])]
113 a, side = FACES.index(face) // 2, FACES.index(face) % 2
115 t = [k
for k
in range(3)
if k != a]
116 T1, T2 = np.meshgrid(c[t[0]], c[t[1]], indexing=
"ij")
117 P = [
None,
None,
None]
118 P[a] = np.full(T1.shape, hi[a]
if side
else lo[a])
119 P[t[0]], P[t[1]] = T1, T2
123def walled(cells, extent, origin=(0.0, 0.0, 0.0), periodic_z=
False):
124 s =
pf.Solver(cells, extent=extent, origin=origin)
125 s.set_advection(
False)
127 if not (periodic_z
and f
in (
"-z",
"+z")):
128 s.set_domain_bc(f,
"wall")
134def add_cc(s, D, box="neumann", periodic_z=False):
135 s.add_scalar(
"c", diffusivity=D, cutcell=
True)
137 if periodic_z
and f
in (
"-z",
"+z"):
139 s.set_scalar_bc(
"c", f, box)
143 """§11 G-iter on a ladder: {rung: [iterations per offset]} -> <= 20 each, growth <= 3."""
145 mx = [max(its[k])
for k
in rungs]
146 check(max(mx) <= 20, f
"{tag}: G-iter <= 20 iterations at every rung ({mx})")
147 gr = [b - a
for a, b
in zip(mx, mx[1:])]
148 check(all(g <= 3
for g
in gr), f
"{tag}: G-iter growth <= 3 per doubling ({gr})")
152 geo = s.diagnostics.scalar_geometry(
"c")
153 unk = geo[
"unknown"] > 0.5
154 w = geo[
"kappa"][unk]
155 e = (s.get_field(
"c") - exact)[unk]
156 return float(np.sum(w * np.abs(e)) / np.sum(w)), float(np.max(np.abs(e)))
160 c = s.diagnostics.scalar_census(
"c")
161 return c[
"krylov_iterations"], c[
"krylov_converged"], c[
"probe_rungs"][
"fluid"]
169 cells = (int(round(L / h)), int(round(L / h)), int(round(L / (2 * h
if aniso
else h))))
170 s =
walled(cells, (L, L, L))
172 c0 = np.array([0.5 * L + off[0] * h, 0.5 * L + off[1] * h, 0.5 * L + off[2] * hz])
174 r = np.sqrt((X - c0[0]) ** 2 + (Y - c0[1]) ** 2 + (Z - c0[2]) ** 2)
175 s.set_solid(np.asfortranarray(r - R))
176 add_cc(s, D, box=
"neumann")
179 rf = np.sqrt((P[0] - c0[0]) ** 2 + (P[1] - c0[1]) ** 2 + (P[2] - c0[2]) ** 2)
180 s.set_scalar_bc(
"c", f,
"dirichlet", R / rf)
181 s.set_scalar_wall(
"c",
"dirichlet", 1.0)
182 s.solve_scalar_steady(
"c")
183 flux = float(s.scalar_wall_flux(
"c")[0])
184 nu = flux / (2.0 * math.pi * R * D)
186 b = s.diagnostics.scalar_budget(
"c")
188 return dict(err=nu / 2.0 - 1.0, l1=l1, linf=linf, it=it, conv=conv, rungs=rungs, b=b, flux=flux)
192 print(
"G1 Dirichlet sphere (steady), R/h in {8, 16, 32}, box 4R")
194 for Rh
in (8, 16, 32):
195 rows = [
g1_case(Rh, off)
for off
in OFFSETS]
197 idr = max(abs(r[
"b"][
"identity_error"]) / abs(r[
"b"][
"wall_in"])
for r
in rows)
198 dfr = max(abs(r[
"b"][
"defect"]) / abs(r[
"b"][
"wall_in"])
for r
in rows)
199 print(f
" R/h={Rh:3d} Nu/2-1 = {[format(r['err'], '+.3e') for r in rows]} L1 {rms([r['l1'] for r in rows]):.3e}"
200 f
" Linf {rms([r['linf'] for r in rows]):.3e} iters {[r['it'] for r in rows]}"
201 f
" identity/|wall| <= {idr:.1e} defect/|wall| <= {dfr:.1e}")
203 check(r[
"conv"], f
"R/h={Rh}: the solve converged ({r['it']} iterations)")
204 check(r[
"rungs"][1] + r[
"rungs"][2] + r[
"rungs"][3] == 0, f
"R/h={Rh}: R0 = 100 % ({r['rungs']})")
206 ident = abs(b[
"wall_in"] + b[
"boundary_in"] - b[
"defect"])
207 check(ident <= 1e-12 * abs(b[
"wall_in"]),
208 f
"R/h={Rh}: |wall - box - defect| = {ident:.2e} <= 1e-12 |wall| ({abs(b['wall_in']):.3e})")
209 check(abs(b[
"defect"]) <= 1e-6 * abs(b[
"wall_in"]),
210 f
"R/h={Rh}: |defect| = {abs(b['defect']):.2e} <= 1e-6 |wall|")
211 check(abs(b[
"identity_error"]) <= 1e-12 * abs(b[
"wall_in"]),
212 f
"R/h={Rh}: identity_error {b['identity_error']:.2e}")
213 e = {k:
rms([r[
"err"]
for r
in v])
for k, v
in res.items()}
214 l1 = {k:
rms([r[
"l1"]
for r
in v])
for k, v
in res.items()}
215 li = {k:
rms([r[
"linf"]
for r
in v])
for k, v
in res.items()}
216 for a, b
in ((8, 16), (16, 32)):
217 check(
order(e[a], e[b]) >= 1.7, f
"Nu order {a}->{b} {order(e[a], e[b]):.2f} >= 1.7 (rms {e[a]:.3e} -> {e[b]:.3e})")
218 check(
order(l1[a], l1[b]) >= 1.8, f
"field L1 order {a}->{b} {order(l1[a], l1[b]):.2f} >= 1.8 ({l1[a]:.3e} -> {l1[b]:.3e})")
219 check(
order(li[a], li[b]) >= 1.5, f
"field Linf order {a}->{b} {order(li[a], li[b]):.2f} >= 1.5 ({li[a]:.3e} -> {li[b]:.3e})")
220 check(e[32] <= 2e-3, f
"|Nu/2 - 1| {e[32]:.2e} <= 2e-3 at R/h = 32 (prov.)")
221 giter_check(
"G1", {k: [r[
"it"]
for r
in v]
for k, v
in res.items()})
222 print(
"G1 anisotropic h' = (1, 1, 2), R/h_min in {16, 32}")
225 rows = [
g1_case(Rh, off, aniso=
True)
for off
in OFFSETS]
226 ea[Rh] =
rms([r[
"err"]
for r
in rows])
227 print(f
" R/h={Rh:3d} Nu/2-1 = {[format(r['err'], '+.3e') for r in rows]} iters {[r['it'] for r in rows]}"
228 f
" rungs {[r['rungs'] for r in rows]}")
230 check(r[
"conv"], f
"aniso R/h={Rh}: the solve converged ({r['it']} iterations)")
232 check(r[
"rungs"][0] >= 0.999 * sum(r[
"rungs"])
and r[
"rungs"][3] == 0,
233 f
"aniso R/h={Rh}: R0 >= 99.9 %, no R2 ({r['rungs']})")
234 check(
order(ea[16], ea[32]) >= 1.7, f
"aniso Nu order {order(ea[16], ea[32]):.2f} >= 1.7 (rms {ea[16]:.3e} -> {ea[32]:.3e})")
239 """Instance 0: a sphere Ri. Instance 1: a huge box minus a sphere Ro (solid outside Ro)."""
240 ni = np.array([1, -1, -1, 3, -1, -1, 1, -1, -1, 34, 1, 2], dtype=np.int32)
241 nr = np.zeros(4 * 16)
243 nr[16 * k + 14] = 1.0
244 nr[16 * k + 15] = 1.0
246 nr[16 + 0] = nr[16 + 1] = nr[16 + 2] = 1e3
248 ii = np.array([0, -1, 3, -1], dtype=np.int32)
249 ir = np.zeros(2 * 18)
251 ir[18 * k:18 * k + 3] = c0
254 return ni, nr, ii, ir
258 """Ruling Q-C (WO-4): G-iter is gated on a multigrid-friendly box — n rounded UP to a multiple
259 of 2^(levels + 1) per axis, read as levels = the number of ladder rungs (3 -> 16)."""
261 return ((n + m - 1) // m) * m
265 Ri, D, q, co = 1.0, 0.8, 0.3, 0.0
268 n = int(math.ceil(2.0 * Ro / h)) + 6
272 s =
walled((n, n, n), (L, L, L))
273 c0 = np.array([0.5 * L, 0.5 * L, 0.5 * L]) + np.asarray(off) * h
275 s.set_solid_from_scene(cutcell_pressure=
False)
276 add_cc(s, D, box=
"neumann")
277 s.set_scalar_wall(
"c",
"neumann", q, instance=0)
278 s.set_scalar_wall(
"c",
"dirichlet", co, instance=1)
279 s.solve_scalar_steady(
"c")
280 fac = s.diagnostics.scalar_facets(
"c")
281 inner = fac[
"instance"] == 0
282 cg = float(np.sum(fac[
"area"][inner] * fac[
"wall_value"][inner]) / np.sum(fac[
"area"][inner]))
283 exact_g = co + (q * Ri / D) * (1.0 - Ri / Ro)
285 r = np.sqrt((X - c0[0]) ** 2 + (Y - c0[1]) ** 2 + (Z - c0[2]) ** 2)
286 l1, linf =
field_errors(s, co + (q * Ri * Ri / D) * (1.0 / r - 1.0 / Ro))
287 flux = s.scalar_wall_flux(
"c")
290 return dict(err=cg / exact_g - 1.0, l1=l1, linf=linf, it=it, conv=conv, rungs=rungs,
291 fin=float(flux[0]) / (q * float(np.sum(fac[
"area"][inner]))) - 1.0)
295 print(
"G2 concentric shells (steady), Neumann q inner, Dirichlet outer Ro = 2.5 Ri, Ri/h in {6, 12, 24}")
296 e, l1, its = {}, {}, {}
297 for Rih
in (6, 12, 24):
298 rows = [
g2_case(Rih, off)
for off
in OFFSETS]
299 e[Rih] =
rms([r[
"err"]
for r
in rows])
300 l1[Rih] =
rms([r[
"l1"]
for r
in rows])
301 its[Rih] = [r[
"it"]
for r
in rows]
302 print(f
" Ri/h={Rih:3d} c_Gamma rel err {[format(r['err'], '+.3e') for r in rows]} L1 {l1[Rih]:.3e}"
303 f
" inner flux/(q area)-1 {[format(r['fin'], '+.1e') for r in rows]} iters {[r['it'] for r in rows]}")
305 check(r[
"conv"], f
"Ri/h={Rih}: converged ({r['it']} iterations)")
306 check(r[
"rungs"][1] + r[
"rungs"][2] + r[
"rungs"][3] == 0, f
"Ri/h={Rih}: R0 = 100 % ({r['rungs']})")
307 check(abs(r[
"fin"]) <= 1e-12, f
"Ri/h={Rih}: inner flux = q x discrete area ({r['fin']:+.1e})")
308 for a, b
in ((6, 12), (12, 24)):
309 check(
order(e[a], e[b]) >= 1.7, f
"c_Gamma order {a}->{b} {order(e[a], e[b]):.2f} >= 1.7 (rms {e[a]:.3e} -> {e[b]:.3e})")
310 check(
order(l1[a], l1[b]) >= 1.8, f
"field L1 order {a}->{b} {order(l1[a], l1[b]):.2f} >= 1.8 ({l1[a]:.3e} -> {l1[b]:.3e})")
311 check(abs(e[24]) <= 2e-3, f
"|c_Gamma err| {e[24]:.2e} <= 2e-3 at Ri/h = 24 (prov.)")
312 print(
" G-iter on multigrid-friendly boxes (ruling Q-C): n rounded up to a multiple of 16")
314 for Rih
in (6, 12, 24):
315 rows = [
g2_case(Rih, off, mgbox=
True)
for off
in OFFSETS]
316 itm[Rih] = [r[
"it"]
for r
in rows]
317 print(f
" Ri/h={Rih:3d} n={mg_box(int(math.ceil(5.0 * Rih)) + 6)} c_Gamma rel err "
318 f
"{[format(r['err'], '+.3e') for r in rows]} iters {itm[Rih]}")
320 check(r[
"conv"], f
"Ri/h={Rih} (mg box): converged ({r['it']} iterations)")
321 print(f
" (native boxes, correctness only: iters {[max(its[k]) for k in sorted(its)]})")
330 n = int(round(L / h))
331 s =
walled((n, n, n), (L, L, L))
333 c0 = np.array([0.5 * L, 0.5 * L, 0.5 * L]) + np.asarray(off) * h
335 r = np.sqrt((X - c0[0]) ** 2 + (Y - c0[1]) ** 2 + (Z - c0[2]) ** 2)
336 s.set_solid(np.asfortranarray(r - R))
337 add_cc(s, D, box=
"neumann")
341 rf = np.sqrt((P[0] - c0[0]) ** 2 + (P[1] - c0[1]) ** 2 + (P[2] - c0[2]) ** 2)
342 s.set_scalar_bc(
"c", f,
"dirichlet", 1.0 - A * R / rf)
343 s.set_scalar_wall(
"c",
"robin", 0.0, coefficient=Da * D / R)
344 s.solve_scalar_steady(
"c")
345 sh = -float(s.scalar_wall_flux(
"c")[0]) / (2.0 * math.pi * R * D)
347 return dict(err=sh / (2.0 * A) - 1.0, it=it, conv=conv, rungs=rungs)
351 print(
"G3a Robin external sphere (steady), R/h in {8, 16, 32}")
352 for Da
in (0.1, 1.0, 10.0, 100.0):
354 for Rh
in (8, 16, 32):
355 rows = [
g3a_case(Rh, off, Da)
for off
in OFFSETS]
356 e[Rh] =
rms([r[
"err"]
for r
in rows])
357 its[Rh] = [r[
"it"]
for r
in rows]
358 print(f
" Da={Da:6.1f} R/h={Rh:3d} Sh rel err {[format(r['err'], '+.3e') for r in rows]} iters {[r['it'] for r in rows]}")
360 check(r[
"conv"], f
"Da={Da} R/h={Rh}: converged ({r['it']} iterations)")
361 check(r[
"rungs"][1] + r[
"rungs"][2] + r[
"rungs"][3] == 0, f
"Da={Da} R/h={Rh}: R0 = 100 %")
362 for a, b
in ((8, 16), (16, 32)):
363 check(
order(e[a], e[b]) >= 1.7, f
"Da={Da}: Sh order {a}->{b} {order(e[a], e[b]):.2f} >= 1.7 (rms {e[a]:.3e} -> {e[b]:.3e})")
364 check(e[32] <= 3e-3, f
"Da={Da}: |Sh err| {e[32]:.2e} <= 3e-3 at R/h = 32 (prov.)")
373 f =
lambda l: l * math.cos(l) - (1.0 - Bi) * math.sin(l)
374 a, b = 1e-9, math.pi - 1e-12
389 s =
walled((n, n, n), (L, L, L))
391 mu = D * lam * lam / (R * R)
394 c0 = np.array([0.5 * L, 0.5 * L, 0.5 * L]) + np.asarray(off) * h
396 r = np.sqrt((X - c0[0]) ** 2 + (Y - c0[1]) ** 2 + (Z - c0[2]) ** 2)
397 s.set_solid(np.asfortranarray(R - r))
398 add_cc(s, D, box=
"neumann")
400 s.set_scalar_wall(
"c",
"dirichlet", 0.0)
402 s.set_scalar_wall(
"c",
"robin", 0.0, coefficient=Bi * D / R)
404 s.set_field(
"c", np.asfortranarray(np.where(x > 1e-12, np.sin(x) / np.where(x > 1e-12, x, 1.0), 1.0)))
405 masses, idmax, its = [], 0.0, []
406 for k
in range(nsteps):
408 b = s.diagnostics.scalar_budget(
"c")
409 masses.append(b[
"mass"])
410 scale = max(abs(b[
"d_mass"]), abs(b[
"mass"]) * 1e-300)
411 idmax = max(idmax, abs(b[
"identity_error"]) / scale)
415 return dict(err=float(
"nan"), idrel=idmax, its=its, conv=
False, rungs=rungs)
416 mu_h = (masses[-2] / masses[-1] - 1.0) / dt
417 return dict(err=mu_h / mu - 1.0, idrel=idmax, its=its, conv=
True, rungs=rungs)
421 print(
"G3b Robin interior sphere (transient, BE late-time ratio, dt mu = 1, 30 steps), R/h in {8, 16, 32}")
422 for Bi
in (0.1, 1.0, 10.0, 100.0, math.inf):
424 for Rh
in (8, 16, 32):
426 rows = [
g3b_case(Rh, off, Bi)
for off
in OFFSETS]
427 e[Rh] =
rms([r[
"err"]
for r
in rows])
428 print(f
" Bi={Bi:6.1f} R/h={Rh:3d} mu rel err {[format(r['err'], '+.3e') for r in rows]}"
429 f
" identity/|dM| <= {max(r['idrel'] for r in rows):.1e}"
430 f
" iters/step {min(min(r['its']) for r in rows)}..{max(max(r['its']) for r in rows)}"
431 f
" ({time.time() - t0:.0f} s)")
433 check(r[
"conv"], f
"Bi={Bi} R/h={Rh}: every step converged")
434 check(r[
"idrel"] <= 1e-13, f
"Bi={Bi} R/h={Rh}: budget identity {r['idrel']:.1e} <= 1e-13 |d_mass|")
435 check(r[
"rungs"][1] + r[
"rungs"][2] + r[
"rungs"][3] == 0, f
"Bi={Bi} R/h={Rh}: R0 = 100 %")
436 o1, o2 =
order(e[8], e[16]),
order(e[16], e[32])
437 check(o1 >= 1.7
and o2 >= 1.7, f
"Bi={Bi}: orders {o1:.2f}, {o2:.2f} >= 1.7")
438 check(e[32] <= 2e-3, f
"Bi={Bi}: |err| {e[32]:.2e} <= 2e-3 at R/h = 32 (prov.)")
442J01_SQ = 5.783185962946784
452 s =
walled((n, n, 4), (L, L, 4 * h), periodic_z=
True)
453 c0 = np.array([0.5 * L, 0.5 * L]) + np.asarray(off[:2]) * h
455 rr = np.sqrt((X - c0[0]) ** 2 + (Y - c0[1]) ** 2)
456 s.set_solid(np.asfortranarray(R - rr))
457 add_cc(s, D, box=
"neumann", periodic_z=
True)
458 return s, X - c0[0], Y - c0[1], rr
463 t, s, k = 1.0, 1.0, 0
464 while abs(t) > 1e-17:
466 t *= -(x * x / 4.0) / (k * k)
474 while abs(t) > 1e-17:
476 t *= -(x * x / 4.0) / (k * (k + 1))
483 s, dx, dy, rr =
pipe(Rh, off, D)
484 eig = J11P_SQ
if neumann
else J01_SQ
488 s.set_scalar_wall(
"c",
"neumann" if neumann
else "dirichlet", 0.0)
489 geo = s.diagnostics.scalar_geometry(
"c")
490 kap = geo[
"kappa"] * (geo[
"unknown"] > 0.5)
492 jv = np.vectorize(j1)(math.sqrt(J11P_SQ) * rr)
493 c = jv * np.where(rr > 0, dx / np.where(rr > 0, rr, 1.0), 0.0)
494 c -= np.sum(kap * c) / np.sum(kap)
497 c = np.vectorize(j0)(math.sqrt(J01_SQ) * rr)
498 mom = np.ones_like(dx)
499 s.set_field(
"c", np.asfortranarray(c))
501 for k
in range(nsteps):
503 vals.append(float(np.sum(kap * mom * s.get_field(
"c"))))
506 mu_h = (vals[-2] / vals[-1] - 1.0) / dt
507 return dict(err=mu_h / mu - 1.0, its=its, conv=conv, rungs=rungs)
512 s, dx, dy, rr =
pipe(Rh, off, D)
513 s.set_scalar_wall(
"c",
"dirichlet", 0.0)
514 uz = np.maximum(2.0 * (1.0 - rr * rr), 0.0)
515 geo = s.diagnostics.scalar_geometry(
"c")
516 kap = geo[
"kappa"] * (geo[
"unknown"] > 0.5)
517 v = np.maximum(1.0 - rr * rr, 0.0)
519 for k
in range(iters):
520 s.set_scalar_source(
"c", np.asfortranarray(uz * v))
521 s.set_field(
"c", np.asfortranarray(v))
522 s.solve_scalar_steady(
"c")
526 bnew = float(np.sum(kap * uz * v * v) / np.sum(kap * uz * v * w))
527 nrm = math.sqrt(float(np.sum(kap * w * w)))
529 if k > 3
and abs(bnew - beta) <= 1e-12 * abs(bnew):
533 nu = beta * 1.0 * 1.0 / D
534 return dict(err=nu / GRAETZ - 1.0, its=its, conv=conv, rungs=rungs)
538 print(
"G7a pipe decay (BE ratio, dt mu = 1, 30 steps), R/h in {16, 32, 64}")
539 for neumann
in (
False,
True):
541 for Rh
in (16, 32, 64):
542 rows = [
g7a_case(Rh, off, neumann)
for off
in OFFSETS]
543 e[Rh] =
rms([r[
"err"]
for r
in rows])
544 print(f
" {'neumann j11p^2' if neumann else 'dirichlet j01^2'} R/h={Rh:3d} rel err "
545 f
"{[format(r['err'], '+.3e') for r in rows]} iters/step {min(min(r['its']) for r in rows)}..{max(max(r['its']) for r in rows)}")
547 check(r[
"conv"], f
"R/h={Rh}: converged")
548 check(r[
"rungs"][1] + r[
"rungs"][2] + r[
"rungs"][3] == 0, f
"R/h={Rh}: R0 = 100 %")
549 tag =
"neumann" if neumann
else "dirichlet"
550 for a, b
in ((16, 32), (32, 64)):
551 check(
order(e[a], e[b]) >= 1.8, f
"{tag}: order {a}->{b} {order(e[a], e[b]):.2f} >= 1.8 (rms {e[a]:.3e} -> {e[b]:.3e})")
552 check(e[32] <= 5e-4, f
"{tag}: |err| {e[32]:.2e} <= 5e-4 at R/h = 32")
553 print(
"G7b Graetz Nu_T (inverse iteration with solve_scalar_steady), R/h in {16, 32, 64}")
555 for Rh
in (16, 32, 64):
556 rows = [
g7b_case(Rh, off)
for off
in OFFSETS]
557 e[Rh] =
rms([r[
"err"]
for r
in rows])
558 print(f
" R/h={Rh:3d} Nu_T rel err {[format(r['err'], '+.3e') for r in rows]} iters/solve "
559 f
"{min(min(r['its']) for r in rows)}..{max(max(r['its']) for r in rows)}")
561 check(r[
"conv"], f
"R/h={Rh}: converged")
562 for a, b
in ((16, 32), (32, 64)):
563 check(
order(e[a], e[b]) >= 1.7, f
"Graetz order {a}->{b} {order(e[a], e[b]):.2f} >= 1.7 (rms {e[a]:.3e} -> {e[b]:.3e})")
564 check(e[32] <= 1e-3, f
"Graetz |err| {e[32]:.2e} <= 1e-3 at R/h = 32 (prov.)")
569 """G1's sphere, transient at dt D/h^2 = 1 from c = 0 (Dirichlet wall c = 1, box c = 0)."""
573 n = int(round(L / h))
574 s =
walled((n, n, n), (L, L, L))
576 c0 = np.array([0.5 * L, 0.5 * L, 0.5 * L]) + np.asarray(off) * h
578 r = np.sqrt((X - c0[0]) ** 2 + (Y - c0[1]) ** 2 + (Z - c0[2]) ** 2)
579 s.set_solid(np.asfortranarray(r - R))
580 add_cc(s, D, box=
"dirichlet")
581 s.set_scalar_wall(
"c",
"dirichlet", 1.0)
583 for k
in range(nsteps):
585 c = s.diagnostics.scalar_census(
"c")
586 its.append(c[
"krylov_iterations"])
587 lv.append(c[
"num_mg_levels"])
592 """G5b's geometry (periodic simple-cubic array, c = 0.3) on an n^3 grid, insulating walls with a
593 flux and a source, steady: the singular case of §5.1 (same surrogate as G5b's closure)."""
596 s =
pf.Solver((n, n, n), extent=(L, L, L))
597 s.set_advection(
False)
600 R = 0.5 * L * (0.3 * 6.0 / math.pi) ** (1.0 / 3.0)
601 c0 = np.array([0.5 * L, 0.5 * L, 0.5 * L]) + np.asarray(off) * h
603 r = np.sqrt((X - c0[0]) ** 2 + (Y - c0[1]) ** 2 + (Z - c0[2]) ** 2)
604 s.set_solid(np.asfortranarray(r - R))
605 s.add_scalar(
"c", diffusivity=0.6, cutcell=
True)
606 s.set_scalar_wall(
"c",
"neumann", 0.2)
607 s.set_scalar_source(
"c", -0.5)
608 s.solve_scalar_steady(
"c")
609 c = s.diagnostics.scalar_census(
"c")
610 return c[
"krylov_iterations"], c[
"krylov_converged"], c[
"num_mg_levels"], 2.0 * R / h
614 print(
"G-iter transient: G1's sphere at dt D/h^2 = 1, 6 steps from c = 0, R/h in {8, 16, 32}")
615 for Rh
in (8, 16, 32):
617 print(f
" R/h={Rh:3d} iterations/step {[its for its, _ in rows]} mg levels {rows[0][1][0]}")
619 cold = max(its[0]
for its, _
in rows)
620 warm = max(max(its[1:])
for its, _
in rows)
621 check(cold <= 12, f
"R/h={Rh}: <= 12 iterations on the cold first step ({cold})")
622 check(warm <= 10, f
"R/h={Rh}: <= 10 iterations per warm step ({warm})")
623 print(
"G-iter singular steady: G5b's geometry (periodic SC array, c = 0.3), n in {32, 48, 80}"
624 " (n = 20/40/80 rounded up to multiples of 16, ruling Q-C)")
628 mx.append(max(r[0]
for r
in rows))
629 print(f
" n={n:3d} (ND {rows[0][3]:.1f}) iterations {[r[0] for r in rows]} mg levels {rows[0][2]}")
631 check(r[1], f
"n={n}: converged ({r[0]} iterations)")
632 check(max(mx) <= 30, f
"singular: <= 30 iterations at every rung ({mx})")
633 gr = [b - a
for a, b
in zip(mx, mx[1:])]
634 check(all(g <= 5
for g
in gr), f
"singular: growth <= 5 per doubling ({gr})")
642 """Stream function of solid-body rotation (Omega = 1, u = d psi/dy, v = -d psi/dx), clamped to
643 its wall values inside the solids."""
644 r = np.clip(np.hypot(X, Y), R_I, R_O)
649 """Coaxial cylinders R_i = 0.4 < r < R_o = 1, an SDF along z, nz = 4, every face periodic."""
653 s =
pf.Solver((n, n, 4), extent=(L, L, 4 * h), origin=(-0.5 * L + off[0] * h,
654 -0.5 * L + off[1] * h, 0.0))
655 s.set_advection(
False)
660 s.set_solid(np.asfortranarray(np.minimum(r - R_I, R_O - r)), cutcell_pressure=
True)
661 s.add_scalar(
"c", diffusivity=0.0, scheme=scheme, cutcell=
True)
666 """Physical F/V through the low x and y faces of every cell: the differences of a NODE
667 potential (round 6's exact stream-function fluxes), so every cell's net flux telescopes to zero.
668 The potential is the clamped psi, set to its wall value on both nodes of every face the
669 projection closes (openness 0): the field is then discretely divergence-free in the openness
670 the predicate reads (the solver's gated cut-cell openness), as a projected field is."""
671 x, y, _ = s.cell_centers()
672 xl, yl = np.asarray(x) - 0.5 * h, np.asarray(y) - 0.5 * h
673 Xn, Yn = np.meshgrid(xl, yl, indexing=
"ij")
675 rn = np.hypot(Xn, Yn)
676 wall = np.where(rn < 0.5 * (R_I + R_O), -0.5 * R_I * R_I, -0.5 * R_O * R_O)
677 shut_x = s.get_ox_proj()[:, :, 0] <= 0.0
678 shut_y = s.get_oy_proj()[:, :, 0] <= 0.0
679 mark = shut_x | np.roll(shut_x, 1, axis=1) | shut_y | np.roll(shut_y, 1, axis=0)
680 P = np.where(mark, wall, P)
681 fx = (np.roll(P, -1, axis=1) - P) / (h * h)
682 fy = -(np.roll(P, -1, axis=0) - P) / (h * h)
683 return fx[:, :,
None] * np.ones(4), fy[:, :,
None] * np.ones(4)
687 """Face velocities (internal index velocity) with open * vel = F/V * tRef, the openness the
688 projection conserves; returns max |F| on faces whose openness is 0 (lost) over max |F|."""
689 tref = s.unit_scales[
"t_ref"]
690 ox, oy = s.get_ox_proj(), s.get_oy_proj()
691 vx = np.where(ox > 0.0, fx * tref / np.where(ox > 0.0, ox, 1.0), 0.0)
692 vy = np.where(oy > 0.0, fy * tref / np.where(oy > 0.0, oy, 1.0), 0.0)
693 s.set_field(
"u", np.asfortranarray(vx))
694 s.set_field(
"v", np.asfortranarray(vy))
695 s.set_field(
"w", np.asfortranarray(np.zeros_like(vx)))
696 lost = max(float(np.max(np.abs(np.where(ox > 0.0, 0.0, fx)))),
697 float(np.max(np.abs(np.where(oy > 0.0, 0.0, fy)))))
698 return lost / max(float(np.max(np.abs(fx))), float(np.max(np.abs(fy))))
701def g9_case(Rh, off, scheme, cr, rtol=None, nsteps=None):
703 geo = s.diagnostics.scalar_geometry(
"c")
704 unk = geo[
"unknown"] > 0.5
706 ax, ay, az = geo[
"aperture_x"], geo[
"aperture_y"], geo[
"aperture_z"]
707 full = unk & (kap >= 1.0)
708 for a, ap
in ((0, ax), (1, ay), (2, az)):
709 full &= (ap >= 1.0) & (np.roll(ap, -1, axis=a) >= 1.0)
711 out = (np.maximum(np.roll(fx, -1, axis=0), 0) + np.maximum(-fx, 0) +
712 np.maximum(np.roll(fy, -1, axis=1), 0) + np.maximum(-fy, 0))
714 nrev = int(math.ceil(T * float(np.max(out[full])) / cr))
719 c0 = np.where(unk, np.exp(-((X - 0.7) ** 2 + Y * Y) / (2 * 0.08**2)), 0.0)
720 s.set_field(
"c", np.asfortranarray(c0))
722 s.set_scalar_residual_tolerance(
"c", rtol)
723 m0 = float(np.sum(kap * c0) * h**3)
724 cmax0 = float(c0.max())
725 st = dict(min=0.0, max=cmax0, ident=0.0, defects=0.0, finite=
True, small=0, impl=0.0,
726 cb=0.0, its=0, lost=lost, minkap=float(kap[unk].min()), steps=0)
727 nst = nrev
if nsteps
is None else nsteps
730 b = s.diagnostics.scalar_budget(
"c")
731 st[
"ident"] = max(st[
"ident"], abs(b[
"identity_error"]) / m0)
732 st[
"defects"] += b[
"defect"]
733 c = s.get_field(
"c")[unk]
734 st[
"finite"] = st[
"finite"]
and bool(np.all(np.isfinite(c)))
735 st[
"min"] = min(st[
"min"], float(c.min()))
736 st[
"max"] = max(st[
"max"], float(c.max()))
737 cen = s.diagnostics.scalar_census(
"c")
738 st[
"small"] = max(st[
"small"], cen[
"num_small_cells"])
739 st[
"impl"] = max(st[
"impl"], cen[
"num_implicit_faces"] / max(1, cen[
"num_flux_faces"]))
740 st[
"cb"] = max(st[
"cb"], cen[
"bulk_courant"])
741 st[
"its"] = max(st[
"its"], cen[
"krylov_iterations"])
742 st[
"guarded"] = cen[
"num_guarded_flux_faces"]
745 m1 = float(np.sum(kap * c) * h**3)
746 st[
"m0"], st[
"m1"], st[
"cmax0"] = m0, m1, cmax0
747 st[
"cons"] = abs(m1 - m0 + st[
"defects"]) / m0
748 st[
"drift"] = abs(m1 - m0) / m0
749 err = np.where(unk, kap * np.abs(c - c0), 0.0)
750 st[
"L1"] = float(err.sum() / np.sum(kap * c0))
751 cut = unk & (kap < 1.0)
754 band |= np.roll(cut, 1, axis=a) | np.roll(cut, -1, axis=a)
756 st[
"cutshare"] = float(err[cut].sum() / err.sum())
757 st[
"bandshare"] = float(err[band].sum() / err.sum())
762 """Grid offsets from a fixed sequence whose geometry carries a sliver (min kappa < 1e-2, gate
763 (v)); the first `want` that do."""
764 rng = np.random.default_rng(9000 + Rh)
767 off = rng.uniform(-0.5, 0.5, size=2)
769 geo = s.diagnostics.scalar_geometry(
"c")
770 if float(geo[
"kappa"][geo[
"unknown"] > 0.5].min()) < 1e-2:
772 if len(found) == want:
778 """No solid: a periodic box, uniform translation (1, 0.5) for one x-period, Koren at bulk Courant
779 cr. Returns (min c, C_bulk) — the bulk scheme's own boundedness, for G9 (iii)'s reading."""
780 s =
pf.Solver((n, n, 4), extent=(1.0, 1.0, 4.0 / n))
781 s.set_advection(
False)
784 s.set_pressure_geometry(np.asfortranarray(np.ones((n, n, 4))))
785 s.add_scalar(
"c", diffusivity=0.0, scheme=
"koren", cutcell=
True)
786 h, U = 1.0 / n, (1.0, 0.5)
787 dt = cr * h / (U[0] + U[1])
789 tr = s.unit_scales[
"t_ref"]
790 s.set_field(
"u", np.asfortranarray(np.full((n, n, 4), U[0] * tr / h)))
791 s.set_field(
"v", np.asfortranarray(np.full((n, n, 4), U[1] * tr / h)))
793 s.set_field(
"c", np.asfortranarray(np.exp(-((X - 0.5) ** 2 + (Y - 0.5) ** 2) / (2 * 0.08**2))))
795 for _
in range(int(round(1.0 / (U[0] * dt)))):
797 mn = min(mn, float(s.get_field(
"c").min()))
798 return mn, s.diagnostics.scalar_census(
"c")[
"bulk_courant"]
802 print(
"G9: advection in an annulus (R_i 0.4, R_o 1, nz 4), solid-body rotation, a Gaussian blob "
803 "carried one revolution, D = 0 (round 6's set-up)")
804 for cr
in (0.5, 0.9):
806 print(f
" control, NO solid, uniform translation, koren at C_bulk {cb:.3f}: min c = {mn:.2e} "
808 for Rh
in (16, 32, 64):
810 check(len(off) == 1, f
"R_o/h={Rh}: an offset with a sliver (min kappa < 1e-2) exists")
812 for scheme
in (
"fou",
"koren"):
813 for cr
in (0.5, 0.9):
815 st =
g9_case(Rh, off, scheme, cr)
816 tag = f
"R_o/h={Rh} {scheme:5s} C={cr}"
817 print(f
" {tag}: {st['steps']} steps, C_bulk {st['cb']:.3f}, small cells <= {st['small']}, "
818 f
"implicit faces <= {100 * st['impl']:.2f} %, BiCGStab <= {st['its']}, min kappa "
819 f
"{st['minkap']:.1e}, lost flux {st['lost']:.1e}, guarded faces {st['guarded']}, "
820 f
"L1 {st['L1']:.3e} (cut cells {100 * st['cutshare']:.1f} %, cut band "
821 f
"{100 * st['bandshare']:.1f} %), min {st['min']:.2e}, max {st['max']:.6f} "
822 f
"[{time.time() - t0:.0f} s]")
823 check(st[
"ident"] <= 1e-13, f
"{tag}: (i) budget identity per step {st['ident']:.1e} M0 <= 1e-13")
824 check(st[
"cons"] <= 1e-12, f
"{tag}: (ii) |M_end - M0 + sum defect| = {st['cons']:.1e} M0 <= 1e-12")
826 check(st[
"min"] >= -1e-12 * st[
"cmax0"], f
"{tag}: (iii) min c {st['min']:.1e} >= -1e-12 max c0")
828 check(st[
"min"] >= -1e-3 * st[
"cmax0"]
and st[
"max"] <= (1 + 1e-3) * st[
"cmax0"],
829 f
"{tag}: (iii) min c {st['min']:.1e} >= -1e-3, max c {st['max']:.6f} <= 1.001 max c0")
833 print(f
" INFO {tag}: (iii) not gated above bulk Courant 1/2 (D-WO5-1): min c "
834 f
"{st['min']:.1e}, max c {st['max']:.6f} (max c0 {st['cmax0']:.6f})")
835 check(st[
"finite"], f
"{tag}: (iv) finite throughout")
836 check(st[
"minkap"] < 1e-2, f
"{tag}: (v) min kappa {st['minkap']:.1e} < 1e-2")
837 check(abs(st[
"cb"] - cr) <= 0.02 * cr, f
"{tag}: bulk Courant {st['cb']:.3f} ~ {cr}")
838 st =
g9_case(Rh, off,
"fou", 0.9, rtol=1e-13)
839 print(f
" R_o/h={Rh} fou C=0.9 rtol 1e-13: |dM|/M0 = {st['drift']:.1e}, "
840 f
"|dM + sum defect| = {st['cons']:.1e} M0")
841 check(st[
"drift"] <= 1e-8, f
"R_o/h={Rh}: (ii) sanity: raw drift {st['drift']:.1e} <= 1e-8 at rtol 1e-13")
846 cls =
pf.Solver if kind ==
"staggered" else pf.SolverColocated
847 s = cls((n, n, n), extent=(1.0, 1.0, 1.0))
848 s.set_advection(
False)
852 if scheme ==
"staggered-ghost":
853 s.diagnostics.set_ghost_projection(
True)
854 elif scheme
is not None:
855 s.set_collocated_scheme(scheme)
856 R = (0.3 * 3.0 / (4.0 * math.pi)) ** (1.0 / 3.0)
858 s.set_solid(np.asfortranarray(np.sqrt((X - 0.513) ** 2 + (Y - 0.479) ** 2 + (Z - 0.507) ** 2) - R),
859 cutcell_pressure=
True)
860 s.set_body_force((30.0, 9.0, 0.0))
861 s.add_scalar(
"c", diffusivity=0.0, cutcell=
True)
862 unk = s.diagnostics.scalar_geometry(
"c")[
"unknown"] > 0.5
863 s.set_field(
"c", np.asfortranarray(np.where(unk, 1.0, 0.0)))
865 for _
in range(nsteps):
867 dev = max(dev, float(np.max(np.abs(s.get_field(
"c")[unk] - 1.0))))
868 return dev, s.diagnostics.scalar_census(
"c")
872 print(
"G9b: constant preservation under flow's own projection (Stokes through an SC sphere "
873 "array, c = 1, 50 steps, D = 0)")
874 for kind, scheme
in ((
"staggered",
None), (
"collocated",
"gauge-exact"), (
"collocated",
"plain"),
875 (
"collocated",
"embed")):
877 tag = f
"{kind} {scheme or ''}".strip()
878 print(f
" {tag}: max|c - 1| = {dev:.2e}; C_bulk {cen['bulk_courant']:.3f}, flux faces "
879 f
"{cen['num_flux_faces']}, implicit {cen['num_implicit_faces']}, guarded "
880 f
"{cen['num_guarded_flux_faces']}")
881 check(dev <= 1e-6, f
"{tag}: max|c - 1| = {dev:.1e} <= 1e-6")
882 check(cen[
"bulk_courant"] > 0.3, f
"{tag}: the flow advects (C_bulk {cen['bulk_courant']:.3f})")
883 for kind, scheme
in ((
"collocated",
"ghost"), (
"staggered",
"staggered-ghost")):
884 raises(RuntimeError,
lambda k=kind, sc=scheme:
g9b_case(k, sc, nsteps=1),
885 f
"{kind} {scheme}: refused for a cut-cell scalar (Q13: no divergence-free face flux)")
889def channel_case(kind="staggered", n=24, dt=0.008, D=0.01, scheme="koren", out_bc="neumann",
890 c0=0.2, cin=1.0, cap=True):
891 """A 2 x 1 x 1 channel (2n x n x n cells): inflow U = 1 on -x, outflow on +x, no-slip walls on y
892 and z, mu 0.05; a solid sphere (R 0.23) off the axis and, with `cap`, a second one (R 0.2)
893 centred just outside the outlet, cutting the outflow face (slivers in the outlet column). The
894 cut-cell scalar: Dirichlet `cin` on the inflow face, `out_bc` on the outflow face (Dirichlet
895 0.5), Neumann on the walls and the solids; `c0` in the fluid."""
896 cls =
pf.Solver if kind ==
"staggered" else pf.SolverColocated
897 s = cls((2 * n, n, n), extent=(2.0, 1.0, 1.0))
898 s.set_advection(
False)
899 if kind !=
"staggered":
900 s.set_collocated_scheme(
"gauge-exact")
904 s.set_domain_bc(
"-x",
"inflow", velocity=(1.0, 0.0, 0.0))
905 s.set_domain_bc(
"+x",
"outflow")
907 s.set_domain_bc(f,
"wall")
909 sdf = np.sqrt((X - 0.71) ** 2 + (Y - 0.48) ** 2 + (Z - 0.53) ** 2) - 0.23
911 sdf = np.minimum(sdf, np.sqrt((X - 2.07) ** 2 + (Y - 0.31) ** 2 + (Z - 0.64) ** 2) - 0.2)
912 s.set_solid(np.asfortranarray(sdf), cutcell_pressure=
True)
913 s.add_scalar(
"c", diffusivity=D, scheme=scheme, cutcell=
True)
914 s.set_scalar_bc(
"c",
"-x",
"dirichlet", cin)
915 if out_bc ==
"dirichlet":
916 s.set_scalar_bc(
"c",
"+x",
"dirichlet", 0.5)
918 s.set_scalar_bc(
"c",
"+x",
"neumann")
920 s.set_scalar_bc(
"c", f,
"neumann")
921 geo = s.diagnostics.scalar_geometry(
"c")
922 unk = geo[
"unknown"] > 0.5
923 s.set_field(
"c", np.asfortranarray(np.where(unk, c0, 0.0)))
924 return s, unk, geo[
"kappa"], dt, (1.0 / n) ** 3
928 """Step the channel; per step the budget identity with the mass change summed exactly
929 (math.fsum of kappa V (c - c^n) over the unknowns: the budget's own d_mass differences two
930 O(M) reductions whose round-off, ~1e-14 M, is ~1e-12 of a step's change in a long channel),
931 and the run's conservation, bounds and census."""
933 cp = s.get_field(
"c")
934 m0 = V * math.fsum((kap * cp)[unk].ravel())
935 st = dict(ident=0.0, internal=0.0, flows=0.0, defects=0.0, min=float(cp[unk].min()),
936 max=float(cp[unk].max()), finite=
True, small=0, impl=0, cb=0.0, its=0, steps=0)
937 for _
in range(nsteps):
939 b = s.diagnostics.scalar_budget(
"c")
941 dm = V * math.fsum((kap * (c - cp))[unk].ravel())
942 flows = dt * (b[
"wall_in"] + b[
"boundary_in"] + b[
"source_in"])
944 st[
"ident"] = max(st[
"ident"], abs(dm - flows + b[
"defect"]) / abs(dm))
945 st[
"internal"] = max(st[
"internal"], abs(b[
"identity_error"]) / b[
"mass"])
947 st[
"defects"] += b[
"defect"]
949 st[
"finite"] = st[
"finite"]
and bool(np.all(np.isfinite(cu)))
950 st[
"min"] = min(st[
"min"], float(cu.min()))
951 st[
"max"] = max(st[
"max"], float(cu.max()))
952 cen = s.diagnostics.scalar_census(
"c")
953 st[
"small"] = max(st[
"small"], cen[
"num_small_cells"])
954 st[
"impl"] = max(st[
"impl"], cen[
"num_implicit_faces"])
955 st[
"cb"] = max(st[
"cb"], cen[
"bulk_courant"])
956 st[
"its"] = max(st[
"its"], cen[
"krylov_iterations"])
959 m1 = V * math.fsum((kap * cp)[unk].ravel())
960 st[
"cons"] = abs(m1 - m0 - st[
"flows"] + st[
"defects"]) / m0
962 st[
"outlet"] = float(np.sum((kap * cp)[-1][last]) / np.sum(kap[-1][last]))
968 print(
"G9c: open domain faces (WO-5b, D-WO5-3): a 2 x 1 x 1 channel, inflow U = 1 / no-slip walls "
969 "/ outflow, a sphere + a cap cutting the outlet, the scalar on flow's own projection")
971 rows = ((
"koren C<=1/2", dict(scheme=
"koren", dt=0.007), 286,
True,
False),
972 (
"fou C~0.9", dict(scheme=
"fou", dt=0.0135), 148,
True,
True),
973 (
"koren, Dirichlet outlet", dict(scheme=
"koren", dt=0.007, out_bc=
"dirichlet"), 40,
False,
975 for tag, kw, nsteps, bounded, small
in rows:
978 print(f
" {tag}: {st['steps']} steps, C_bulk <= {st['cb']:.3f}, small cells <= {st['small']}, "
979 f
"implicit faces <= {st['impl']}, BiCGStab <= {st['its']}; identity <= {st['ident']:.1e} "
980 f
"|dM| (internal identity_error <= {st['internal']:.1e} M), run conservation "
981 f
"{st['cons']:.1e} M0; c - [0.2, 1] in [{st['min'] - 0.2:.1e}, {st['max'] - 1.0:.1e}]; outlet mean "
982 f
"{st['outlet']:.3f} [{time.time() - t0:.0f} s]")
983 check(st[
"ident"] <= 1e-13, f
"{tag}: per-step budget identity {st['ident']:.1e} |dM| <= 1e-13")
984 check(st[
"internal"] <= 1e-12, f
"{tag}: identity_error {st['internal']:.1e} M <= 1e-12 (sanity)")
985 check(st[
"cons"] <= 1e-12, f
"{tag}: |M_end - M0 - sum dt flows + sum defects| {st['cons']:.1e} M0 <= 1e-12")
986 check(st[
"finite"], f
"{tag}: finite throughout")
988 check(st[
"small"] > 0
and st[
"impl"] > 0, f
"{tag}: small cells and implicit faces occur")
990 tol = 1e-10
if kw[
"scheme"] ==
"fou" else 1e-3
991 check(st[
"min"] >= 0.2 - tol
and st[
"max"] <= 1.0 + tol,
992 f
"{tag}: bounded by the data, c in [{st['min']:.6f}, {st['max']:.6f}] within {tol:.0e}")
993 check(st[
"outlet"] > 0.3, f
"{tag}: the front reached the outlet (mean {st['outlet']:.3f})")
994 if kw[
"scheme"] ==
"koren":
995 check(st[
"cb"] <= 0.5, f
"{tag}: bulk Courant {st['cb']:.3f} <= 1/2 (D-WO5-1)")
997 st =
g9c_run(20, scheme=
"koren", dt=0.008, c0=1.0, cin=1.0)
998 dev = max(abs(st[
"min"] - 1.0), abs(st[
"max"] - 1.0))
999 print(f
" constant c = 1 (inflow 1): max|c - 1| = {dev:.2e}")
1000 check(dev <= 1e-6, f
"constant preservation through the open faces: max|c - 1| = {dev:.1e} <= 1e-6")
1003 s.add_scalar(
"d", diffusivity=0.5, cutcell=
True)
1004 s.set_scalar_bc(
"d",
"-x",
"dirichlet", 1.0)
1006 s.set_scalar_bc(
"d", f,
"neumann")
1007 s.solve_scalar_steady(
"d")
1008 b = s.diagnostics.scalar_budget(
"d")
1009 cen = s.diagnostics.scalar_census(
"d")
1011 print(f
" steady, D = 0.5 (Pe_h {1.0 / 24 / 0.5:.3f}): {cen['krylov_iterations']} iterations, "
1012 f
"boundary_in {b['boundary_in']:.3e}, identity_error {b['identity_error']:.1e} (rate {rate})")
1013 check(cen[
"krylov_converged"],
"steady with open faces converges")
1014 check(abs(b[
"identity_error"]) <= 1e-12 * rate, f
"steady rate balance {abs(b['identity_error']):.1e} <= 1e-12 Q cin")
1017 "collocated: an open domain face is refused for a cut-cell scalar (open after WO-5b)")
1020 s.set_field(
"u", np.asfortranarray(np.full(unk.shape, 1.0)))
1021 raises(RuntimeError, s.advance_scalars,
"open faces, a moving fluid and no projection yet: refused")
1026 """Run fn() with the C-level stderr captured; returns (fn's result, the text)."""
1029 with tempfile.TemporaryFile(mode=
"w+b")
as tmp:
1032 os.dup2(tmp.fileno(), 2)
1039 return r, tmp.read().decode(errors=
"replace")
1043 """Review finding 2 (rulings D-WOR-2a/b/c): open faces but NO inflow face -- both x ends
1044 'outflow', the flow driven by a body force, so the whole -x face backflows; walls on y and z, a
1045 Neumann sphere. A steady scalar, insulating everywhere, no source, from a non-uniform start:
1046 the problem is not the uniform-mean singular case (no compatibility projection, no gauge), the
1047 solve converges -- to a constant, the null vector --, and the backflow rows are counted and
1048 warned about once. Returns the census."""
1049 s =
pf.Solver((2 * n, n, n), extent=(2.0, 1.0, 1.0))
1050 s.set_advection(
False)
1054 s.set_domain_bc(
"-x",
"outflow")
1055 s.set_domain_bc(
"+x",
"outflow")
1057 s.set_domain_bc(f,
"wall")
1059 s.set_solid(np.asfortranarray(np.sqrt((X - 0.97) ** 2 + (Y - 0.48) ** 2 + (Z - 0.53) ** 2) - 0.23),
1060 cutcell_pressure=
True)
1061 s.set_body_force((1.0, 0.0, 0.0))
1062 for _
in range(nsteps):
1064 s.add_scalar(
"b", diffusivity=0.05, cutcell=
True)
1066 s.set_scalar_bc(
"b", f,
"neumann")
1067 unk = s.diagnostics.scalar_geometry(
"b")[
"unknown"] > 0.5
1068 s.set_field(
"b", np.asfortranarray(np.where(unk, 0.5 + 0.3 * np.sin(3.0 * X) * np.cos(2.0 * Y), 0.0)))
1070 cen = s.diagnostics.scalar_census(
"b")
1071 c = s.get_field(
"b")[unk]
1072 spread = float(c.max() - c.min())
1073 print(f
" backflow (both x ends outflow, body force): {cen['num_backflow_faces']} backflow rows, "
1074 f
"{cen['krylov_iterations']} iterations, residual {cen['krylov_residual']:.1e}, "
1075 f
"incompatibility {cen['steady_incompatibility']:.1e}, max - min c = {spread:.1e}; "
1076 f
"stderr: {err.strip()!r}")
1077 check(cen[
"num_backflow_faces"] > 0, f
"backflow: census num_backflow_faces > 0 ({cen['num_backflow_faces']})")
1078 check(
"BACKFLOW" in err
and "num_backflow_faces" in err,
"backflow: the steady solve warns, naming the census key")
1079 check(cen[
"krylov_converged"], f
"backflow, no inflow face: the steady solve converges "
1080 f
"({cen['krylov_iterations']} iterations, D-WOR-2b)")
1081 check(cen[
"steady_incompatibility"] == 0.0,
"backflow: not treated as the uniform-mean singular case")
1082 check(spread <= 1e-6, f
"backflow: the converged field is the null vector, a constant (spread {spread:.1e})")
1084 check(
"BACKFLOW" not in err2,
"backflow: the warning is printed once per scalar")
1090 """The scalar's advective face flux per unit area through the LOW a-face of each cell
1091 (physical, c-free: open * u), from fields: the projection's openness (get_ox/oy/oz, the
1092 staggered non-ghost openness of §6.1) times the face velocity (get_field, internal, converted),
1093 zero unless both cells are fluid unknowns (the guard of §6.1). Periodic roll; a non-periodic
1094 axis' low boundary face is zeroed by the caller's mask."""
1095 geo = s.diagnostics.scalar_geometry(name)
1096 unk = geo[
"unknown"] > 0.5
1097 o = (s.get_ox, s.get_oy, s.get_oz)[a]()
1098 v = s.get_field(
"uvw"[a]) / s.unit_scales[
"velocity_to_internal"][a]
1099 return np.where(unk & np.roll(unk, 1, axis=a), o * v, 0.0)
1103 """U_i/V (§1.5) per cell, physical: sum_f F_out (x_f - x_i) / V = the mean of the cell's two
1104 a-face fluxes per area, per axis."""
1109 idx = [
slice(
None)] * 3
1112 U.append(0.5 * (f + np.roll(f, -1, axis=a)))
1117 """scalar_mean_flux recomputed from fields (§8.1): the diffusive face sum of -D a (c_j - c_i)/h
1118 (c = theta + G.x, the true displacement) over the coupled low faces, plus the advective
1119 sum (U_i/V - kappa_i Ubar) theta_i, both over the whole box's cell count. Returns
1120 (J (3,), the advective part (3,), Ubar (3,), phi = sum kappa / N)."""
1121 geo = s.diagnostics.scalar_geometry(name)
1122 unk = geo[
"unknown"] > 0.5
1123 kap = np.where(unk, geo[
"kappa"], 0.0)
1124 th = s.get_field(name)
1128 ksum = math.fsum(kap[unk].ravel())
1129 ub = [math.fsum(U[a][unk].ravel()) / ksum
for a
in range(3)]
1130 J, Ja = np.zeros(3), np.zeros(3)
1131 for a, ap
in enumerate((geo[
"aperture_x"], geo[
"aperture_y"], geo[
"aperture_z"])):
1132 cpl = unk & np.roll(unk, 1, axis=a)
1134 idx = [
slice(
None)] * 3
1136 cpl[tuple(idx)] =
False
1137 dc = th - np.roll(th, 1, axis=a) + G[a] * h[a]
1138 J[a] = math.fsum((-D * ap * dc / h[a])[cpl].ravel()) / N
1139 Ja[a] = math.fsum(((U[a] - kap * ub[a]) * th)[unk].ravel()) / N
1140 return J + Ja, Ja, ub, ksum / N
1144 """G8's velocity (ruling D-WO6-1): the Poiseuille flux through the open part of each z-face
1145 (m x m midpoint sub-samples of the face), divided by oz A, so that F = oz w A carries no
1146 point-sampling error."""
1147 x, y, _ = (np.asarray(v)
for v
in s.cell_centers())
1149 g = (np.arange(m) + 0.5) / m - 0.5
1150 GX, GY = np.meshgrid(g * h, g * h, indexing=
"ij")
1151 flux = np.zeros((x.size, y.size))
1152 for i
in range(x.size):
1153 px = x[i] + GX - c0[0]
1154 for j
in range(y.size):
1155 py = y[j] + GY - c0[1]
1156 r2 = (px * px + py * py) / (R * R)
1157 flux[i, j] = np.mean(np.where(r2 < 1.0, 2.0 * U * (1.0 - r2), 0.0))
1158 o = oz[:, :, :1][:, :, 0]
1159 w2 = np.where(o > 0, flux / np.where(o > 0, o, 1.0), 0.0)
1160 return np.repeat(w2[:, :,
None], oz.shape[2], axis=2)
1163def g8_case(Rh, off, U=1.0, Pe=10.0, nbox=None, nz=4, exact_flux=True):
1164 """G8: G7's pipe (R = 1, nz = 4 periodic), frozen Poiseuille z-face velocities (set_field;
1165 ruling D-WO6-1: the FACE-AVERAGED flux over the open part of each face; divergence-free
1166 because z-invariant), insulating walls, mean gradient e_z, steady. Returns the Taylor-Aris coefficient -<u'theta> (interstitial, from fields) over
1167 its exact value Pe^2 D/48, Pe = U R/D. `nbox`/`nz` give G-iter's multigrid-friendly box (ruling
1168 D-WO4-1; the problem is z-invariant, so nz changes nothing but the cell count);
1169 `exact_flux=False` the INFO variant: face-centre point samples, clipped >= 0."""
1173 n = nbox
or 2 * Rh + 6
1175 s =
walled((n, n, nz), (L, L, nz * h), periodic_z=
True)
1176 c0 = np.array([0.5 * L, 0.5 * L]) + np.asarray(off[:2]) * h
1178 rr = np.sqrt((X - c0[0]) ** 2 + (Y - c0[1]) ** 2)
1179 s.set_solid(np.asfortranarray(R - rr), cutcell_pressure=
True)
1183 w = np.maximum(2.0 * U * (1.0 - rr * rr / (R * R)), 0.0)
1184 s.set_field(
"w", np.asfortranarray(w * s.unit_scales[
"velocity_to_internal"][2]))
1185 add_cc(s, D, box=
"neumann", periodic_z=
True)
1186 s.set_scalar_mean_gradient(
"c", (0.0, 0.0, 1.0))
1187 s.solve_scalar_steady(
"c")
1188 per = (
False,
False,
True)
1190 Jc = np.asarray(s.scalar_mean_flux(
"c"))
1192 c = s.diagnostics.scalar_census(
"c")
1193 return dict(err=48.0 * val / (Pe * Pe * D) - 1.0, its=c[
"krylov_iterations"],
1194 conv=c[
"krylov_converged"], pe_h=c[
"max_cell_peclet"], ubar=ub[2],
1195 jdiff=float(np.max(np.abs(Jc - J)) / np.max(np.abs(Jc))), J=Jc, phi=phi,
1196 incompat=c[
"steady_incompatibility"], s=s)
1200 print(
"G8 Taylor-Aris: pipe R/h in {16, 32, 64}, face-averaged Poiseuille fluxes (D-WO6-1), insulating walls, "
1201 "mean gradient e_z, steady; -<u'theta> -> Pe^2 D/48 at Pe = UR/D = 10")
1203 for Rh
in (16, 32, 64):
1204 rows = [
g8_case(Rh, off)
for off
in OFFSETS]
1205 e[Rh] =
rms([r[
"err"]
for r
in rows])
1206 print(f
" R/h={Rh:3d} rel err {[format(r['err'], '+.3e') for r in rows]} iterations "
1207 f
"{[r['its'] for r in rows]} census Pe_h {rows[0]['pe_h']:.3f} Ubar/U - 1 "
1208 f
"{rows[0]['ubar'] - 1.0:+.2e} |J - J_fields| / |J| <= {max(r['jdiff'] for r in rows):.1e}"
1209 f
" incompatibility {max(r['incompat'] for r in rows):.1e}")
1211 check(r[
"conv"], f
"R/h={Rh}: converged ({r['its']} iterations; native box: correctness "
1212 f
"only, ruling D-WO4-1)")
1213 check(r[
"jdiff"] <= 1e-10, f
"R/h={Rh}: scalar_mean_flux = the field sums to "
1214 f
"{r['jdiff']:.1e} <= 1e-10")
1215 for a, b
in ((16, 32), (32, 64)):
1216 check(
order(e[a], e[b]) >= 1.8, f
"Taylor-Aris order {a}->{b} {order(e[a], e[b]):.2f} >= 1.8 "
1217 f
"(rms {e[a]:.3e} -> {e[b]:.3e})")
1218 check(e[32] <= 1e-3, f
"Taylor-Aris |err| {e[32]:.2e} <= 1e-3 at R/h = 32")
1219 ex = {Rh:
rms([
g8_case(Rh, off, exact_flux=
False)[
"err"]
for off
in OFFSETS])
for Rh
in (16, 32)}
1220 print(f
" INFO face-centre point samples (an O(h^2) flux-quadrature error): rms {ex[16]:.3e} -> "
1221 f
"{ex[32]:.3e}, order {order(ex[16], ex[32]):.2f}")
1222 print(
"G-iter singular steady on G8, multigrid-friendly boxes (ruling D-WO4-1): n = 48 / 80 / 144, "
1225 for Rh
in (16, 32, 64):
1227 its.append(max(r[
"its"]
for r
in rows))
1228 print(f
" R/h={Rh:3d} iterations {[r['its'] for r in rows]} rel err "
1229 f
"{[format(r['err'], '+.3e') for r in rows]}")
1231 check(r[
"conv"], f
"R/h={Rh} mg box: converged")
1232 check(max(its) <= 30, f
"G8 singular steady: <= 30 iterations at every rung ({its})")
1233 gr = [b - a
for a, b
in zip(its, its[1:])]
1234 check(all(g <= 5
for g
in gr), f
"G8 singular steady: growth <= 5 per doubling ({gr})")
1238 """G5b: the periodic simple-cubic array, solid fraction 0.3, on an n^3 grid of the unit
1239 period, insulating spheres, mean gradient e_x, steady (singular). k* = -J_x/(D G_x)."""
1242 s =
pf.Solver((n, n, n), extent=(L, L, L))
1243 s.set_advection(
False)
1246 R = 0.5 * L * (0.3 * 6.0 / math.pi) ** (1.0 / 3.0)
1247 c0 = np.array([0.5 * L, 0.5 * L, 0.5 * L]) + np.asarray(off) * h
1249 r = np.sqrt((X - c0[0]) ** 2 + (Y - c0[1]) ** 2 + (Z - c0[2]) ** 2)
1250 s.set_solid(np.asfortranarray(r - R))
1251 s.add_scalar(
"c", diffusivity=D, cutcell=
True)
1252 s.set_scalar_mean_gradient(
"c", (1.0, 0.0, 0.0))
1253 s.solve_scalar_steady(
"c")
1254 J = np.asarray(s.scalar_mean_flux(
"c"))
1255 c = s.diagnostics.scalar_census(
"c")
1256 Jf, _, _, _ =
mean_flux_fields(s,
"c", D, (1.0, 0.0, 0.0), (
True,
True,
True))
1257 return dict(k=-J[0] / D, its=c[
"krylov_iterations"], conv=c[
"krylov_converged"],
1258 lv=c[
"num_mg_levels"], nd=2.0 * R / h, jdiff=float(np.max(np.abs(J - Jf)) / abs(J[0])))
1262 """The no-solid identity: a box with no solid (SDF > 0 everywhere), mean gradient G, at rest
1263 or with a uniform velocity; the closure solution is theta = const and J = -D G exactly."""
1264 s =
pf.Solver((n, n, n), extent=(1.0, 1.0, 1.0))
1265 s.set_advection(
False)
1268 s.set_solid(np.asfortranarray(np.ones((n, n, n))), cutcell_pressure=vel
is not None)
1270 for a, nm
in enumerate(
"uvw"):
1271 s.set_field(nm, np.asfortranarray(np.full((n, n, n), vel[a] *
1272 s.unit_scales[
"velocity_to_internal"][a])))
1273 s.add_scalar(
"c", diffusivity=D, cutcell=
True)
1274 s.set_field(
"c", np.asfortranarray(np.random.default_rng(7).uniform(-1, 1, (n, n, n))))
1275 s.set_scalar_mean_gradient(
"c", G)
1276 s.solve_scalar_steady(
"c")
1277 J = np.asarray(s.scalar_mean_flux(
"c"))
1278 c = s.diagnostics.scalar_census(
"c")
1283 print(
"G5b insulating periodic SC array, c = 0.3, mean gradient e_x: k* = -J_x/(D G_x) via "
1284 "scalar_mean_flux; ND = 16.6 / 33.2 / 66.4 (n = 20 / 40 / 80, doublings)")
1285 hs = (1.0 - 0.3) / (1.0 + 0.15)
1287 for n
in (20, 40, 80):
1288 rows = [
g5b_case(n, off)
for off
in OFFSETS]
1289 k[n] = [r[
"k"]
for r
in rows]
1290 print(f
" n={n:3d} (ND {rows[0]['nd']:.1f}) k* {[f'{v:.7f}' for v in k[n]]} iterations "
1291 f
"{[r['its'] for r in rows]} mg levels {rows[0]['lv']} |J - J_fields|/|J_x| <= "
1292 f
"{max(r['jdiff'] for r in rows):.1e}")
1294 check(r[
"conv"], f
"n={n}: converged ({r['its']} iterations)")
1296 check(r[
"k"] <= hs, f
"n={n}: k* {r['k']:.6f} <= Hashin-Shtrikman {hs:.6f}")
1297 check(r[
"jdiff"] <= 1e-10, f
"n={n}: scalar_mean_flux = the field sums ({r['jdiff']:.1e})")
1298 d1 =
rms([a - b
for a, b
in zip(k[20], k[40])])
1299 d2 =
rms([a - b
for a, b
in zip(k[40], k[80])])
1301 check(p >= 1.7, f
"self-convergence order {p:.2f} >= 1.7 (rms |k_20 - k_40| {d1:.3e}, "
1302 f
"|k_40 - k_80| {d2:.3e})")
1303 kx = [c + (c - b) / (2.0 ** p - 1.0)
for b, c
in zip(k[40], k[80])]
1304 print(f
" Richardson-extrapolated k* {[f'{v:.6f}' for v in kx]}; ND 16.6 rung "
1305 f
"{max(k[20]) - hs:+.2e} against the bound (INFO: the bound is of the exact k*)")
1306 check(max(kx) <= hs, f
"extrapolated k* {max(kx):.6f} <= Hashin-Shtrikman {hs:.6f}")
1307 print(
"G-iter singular steady on the G5b closure, multigrid-friendly n = 32 / 48 / 80 (ruling Q-C)")
1310 rows = [
g5b_case(n, off)
for off
in OFFSETS]
1311 mx.append(max(r[
"its"]
for r
in rows))
1312 print(f
" n={n:3d} iterations {[r['its'] for r in rows]} k* {[format(r['k'], '.6f') for r in rows]}")
1314 check(r[
"conv"], f
"n={n}: converged")
1315 check(max(mx) <= 30, f
"G5b singular: <= 30 iterations at every rung ({mx})")
1316 gr = [b - a
for a, b
in zip(mx, mx[1:])]
1317 check(all(g <= 5
for g
in gr), f
"G5b singular: growth <= 5 per rung ({gr})")
1318 print(
"no-solid identity: k* = 1 to 1e-12")
1321 print(f
" at rest, G = e_x: k* - 1 = {ks - 1.0:+.1e}, J_y, J_z = {J[1]:+.1e}, {J[2]:+.1e}; "
1322 f
"{c['krylov_iterations']} iterations")
1323 check(abs(ks - 1.0) <= 1e-12
and abs(J[1]) <= 1e-12
and abs(J[2]) <= 1e-12,
1324 "no solid, at rest: k* = 1 to 1e-12, transverse flux 0")
1325 G = np.array([0.3, -0.5, 0.8])
1327 dev = float(np.max(np.abs(J + 0.6 * G)) / (0.6 * np.linalg.norm(G)))
1328 print(f
" uniform flow (0.2, 0.1, -0.3), G = (0.3, -0.5, 0.8): max|J + D G| / (D|G|) = {dev:.1e}; "
1329 f
"census Pe_h {c['max_cell_peclet']:.3g}, {c['krylov_iterations']} iterations")
1330 check(dev <= 1e-12,
"no solid, uniform flow (moving frame): J = -D G to 1e-12")
1335 """G-adv's parametrization (A2): one probe steady solve at the present face field, then u, v, w
1336 times target / (census max_cell_peclet), so the next solve's census reads `target`."""
1337 s.solve_scalar_steady(name)
1338 k = target / s.diagnostics.scalar_census(name)[
"max_cell_peclet"]
1339 for nm
in (
"u",
"v",
"w"):
1340 s.set_field(nm, np.asfortranarray(s.get_field(nm) * k))
1344 """(v), ruling D-WO5c-1: the steady rate balance relative to the GROSS budget — the sum of the
1345 terms' absolute values, the source taken gross (V sum |r| over the unknowns, r the per-cell
1346 source density of the right-hand side: kappa s for a per-cell source, the mean-gradient terms
1347 in closure mode; |source_in| for a uniform one) — bound 1e-11. Returns (that ratio, the ratio
1348 against the largest NET term: INFO, O(1) for the mean-free closure source of (b) / (b'))."""
1349 b = s.diagnostics.scalar_budget(name)
1350 net = max(abs(b[
"wall_in"]), abs(b[
"source_in"]), abs(b[
"boundary_in"]))
1351 src = abs(b[
"source_in"])
1352 if name
in GADV_SRC:
1353 geo = s.diagnostics.scalar_geometry(name)
1354 unk = geo[
"unknown"] > 0.5
1355 x, y, z = s.cell_centers()
1356 V = (x[1] - x[0]) * (y[1] - y[0]) * (z[1] - z[0])
1357 src = V * math.fsum(np.abs(GADV_SRC[name])[unk].ravel())
1358 gross = abs(b[
"wall_in"]) + src + abs(b[
"boundary_in"])
1359 ie = abs(b[
"identity_error"])
1360 return ie / gross, (ie / net
if net > 0.0
else None)
1364 """(a) WO-5's C3 problem: a periodic box 4R, a Dirichlet sphere (c = 1) R = 1 with a source,
1365 D = 0.7, the projected Stokes field of that geometry (20 steps under a body force, mu dt/h^2 =
1366 1), rescaled to census Pe_h = pe; steady."""
1371 s =
pf.Solver((n, n, n), extent=(L, L, L))
1372 s.set_advection(
False)
1377 c0 = np.array([0.5 * L + 0.37 * h, 0.5 * L - 0.22 * h, 0.5 * L + 0.11 * h])
1378 s.set_solid(np.asfortranarray(np.sqrt((X - c0[0]) ** 2 + (Y - c0[1]) ** 2 + (Z - c0[2]) ** 2) - R),
1379 cutcell_pressure=
True)
1380 s.set_body_force((1.0, 0.4, 0.2))
1383 s.add_scalar(
"c", diffusivity=D, cutcell=
True)
1384 s.set_scalar_wall(
"c",
"dirichlet", 1.0)
1385 s.set_scalar_source(
"c", -0.3)
1387 s.solve_scalar_steady(
"c")
1392 """G9b's geometry and flow: the periodic simple-cubic sphere array, solid fraction 0.3, one
1393 sphere per unit period on n^3 cells; Stokes through it from step() (G9b's body force, 50
1395 s =
pf.Solver((n, n, n), extent=(1.0, 1.0, 1.0))
1396 s.set_advection(
False)
1400 R = (0.3 * 3.0 / (4.0 * math.pi)) ** (1.0 / 3.0)
1402 s.set_solid(np.asfortranarray(np.sqrt((X - 0.513) ** 2 + (Y - 0.479) ** 2 + (Z - 0.507) ** 2) - R),
1403 cutcell_pressure=
True)
1404 s.set_body_force((30.0, 9.0, 0.0))
1411 """The B-field source for G = e_x (until WO-6's mean-gradient mode): s = u_x - <u_x> per
1412 unknown cell, u_x the cell average of its two x-face velocities (physical), <.> the kappa-
1413 weighted mean over the fluid unknowns; 0 elsewhere."""
1414 geo = s.diagnostics.scalar_geometry(name)
1415 unk = geo[
"unknown"] > 0.5
1418 ux = 0.5 * (u + np.roll(u, -1, axis=0))
1419 mean = float(np.sum((kap * ux)[unk]) / np.sum(kap[unk]))
1420 return np.asfortranarray(np.where(unk, ux - mean, 0.0))
1424 """The mean-gradient terms of the right-hand side per unit volume (§1.5), physical, per cell:
1425 the faces' D G_a (a_a^+ - a_a^-)/h_a over the coupled faces, minus G.(U_i/V - kappa_i Ubar);
1426 the gross scale of (v) in closure mode."""
1427 geo = s.diagnostics.scalar_geometry(name)
1428 unk = geo[
"unknown"] > 0.5
1429 kap = np.where(unk, geo[
"kappa"], 0.0)
1432 ksum = math.fsum(kap[unk].ravel())
1433 r = np.zeros(unk.shape)
1434 for a, ap
in enumerate((geo[
"aperture_x"], geo[
"aperture_y"], geo[
"aperture_z"])):
1435 lo = np.where(unk & np.roll(unk, 1, axis=a), ap, 0.0)
1436 hi = np.roll(lo, -1, axis=a)
1437 ub = math.fsum(U[a][unk].ravel()) / ksum
1438 r += D * G[a] * (hi - lo) / h[a] - G[a] * (U[a] - kap * ub)
1439 return np.where(unk, r, 0.0)
1443 """(b) the closure problem on the SC array (insulating spheres: steady, singular) in the
1444 mean-gradient mode of WO-6 (theta, G = e_x), or (b') the reactive bed (Dirichlet spheres,
1445 c = 0) with the per-cell source u_x - <u_x> (WO-5c's form), D = 0.05; census Pe_h = pe."""
1447 s.add_scalar(
"c", diffusivity=0.05, cutcell=
True)
1448 if wall ==
"neumann":
1449 s.set_scalar_wall(
"c",
"neumann", 0.0)
1450 s.set_scalar_mean_gradient(
"c", (1.0, 0.0, 0.0))
1453 s.solve_scalar_steady(
"c")
1455 s.set_scalar_wall(
"c",
"dirichlet", 0.0)
1459 s.set_scalar_source(
"c", src)
1460 geo = s.diagnostics.scalar_geometry(
"c")
1461 GADV_SRC[
"c"] = geo[
"kappa"] * src
1462 s.solve_scalar_steady(
"c")
1467 """(c) G9c's channel (inflow U = 1 / no-slip walls / outflow, a sphere + a cap cutting the
1468 outlet), the flow developed by 20 NS steps; a steady scalar, Dirichlet 1 at the inlet, Neumann
1469 elsewhere. The captured open-face flux cannot be rescaled through set_field, so the census
1470 Pe_h is set through D instead (Pe_h ~ 1/D: the same operator up to a factor)."""
1471 st =
g9c_run(20, scheme=
"koren", dt=0.008)
1474 s.add_scalar(
"p", diffusivity=D0, cutcell=
True)
1475 s.set_scalar_bc(
"p",
"-x",
"dirichlet", 1.0)
1477 s.set_scalar_bc(
"p", f,
"neumann")
1478 s.solve_scalar_steady(
"p")
1479 p0 = s.diagnostics.scalar_census(
"p")[
"max_cell_peclet"]
1480 s.add_scalar(
"d", diffusivity=D0 * p0 / pe, cutcell=
True)
1481 s.set_scalar_bc(
"d",
"-x",
"dirichlet", 1.0)
1483 s.set_scalar_bc(
"d", f,
"neumann")
1484 s.solve_scalar_steady(
"d")
1488GADV_PE = (0.1, 1.0, 10.0)
1493 """(i), (ii), (v) of one row; returns the iteration count."""
1494 c = s.diagnostics.scalar_census(name)
1495 its = c[
"krylov_iterations"]
1496 b = s.diagnostics.scalar_budget(name)
1499 ident = abs(b[
"identity_error"]) / rate
1502 extra = f
" (INFO: {netr:.1e} of the largest net term)" if netr
is not None else ""
1503 print(f
" {tag} Pe_h {c['max_cell_peclet']:.4g}: {its} iterations (<= {bound}), residual "
1504 f
"{c['krylov_residual']:.1e}, {c['num_mg_levels']} levels; budget identity {ident:.1e}{extra}")
1505 check(abs(c[
"max_cell_peclet"] / pe - 1.0) <= 1e-9, f
"{tag}: census Pe_h {c['max_cell_peclet']:.6g} = {pe}")
1506 check(c[
"krylov_converged"]
and c[
"krylov_residual"] <= 1e-10,
1507 f
"{tag} Pe_h {pe}: (i) converged to rtol 1e-10 within 200 ({its} iterations)")
1508 check(its <= bound, f
"{tag} Pe_h {pe}: (ii) {its} <= {bound} iterations (Q20, D-WOR-8)")
1509 check(ident <= 1e-11, f
"{tag} Pe_h {pe}: (v) steady budget identity {ident:.1e} <= 1e-11 of the gross budget")
1516 check(g <= 1.7, f
"{tag} Pe_h {pe}: (iii) growth per doubling {lo[pe]} -> {hi[pe]} = {g:.2f}x <= 1.7x")
1520 print(
"G-adv: steady advection on the advective surrogate (design Amendment A2), "
1521 "Pe_h = census max_cell_peclet")
1526 bounds = {16: (16, 25, 40), 32: (20, 34, 55)}
1530 for pe, bd
in zip(GADV_PE, bounds[Rh]):
1533 its[Rh][pe] =
gadv_row(f
"(a) R/h={Rh} ({4 * Rh}^3)", s,
"c", pe, bd)
1535 print(f
" [(a): {time.time() - t0:.0f} s]")
1536 bounds_b = {
"neumann": {32: (10, 16, 24), 64: (12, 20, 30)},
1537 "dirichlet": {32: (15, 20, 30), 64: (15, 20, 30)}}
1538 for wall, nm
in ((
"neumann",
"(b) closure, Neumann spheres, mean gradient e_x"),
1539 (
"dirichlet",
"(b') Dirichlet spheres")):
1544 for pe, bd
in zip(GADV_PE, bounds_b[wall][n]):
1546 if wall ==
"neumann":
1547 check(s.diagnostics.scalar_census(
"c")[
"steady_incompatibility"] >= 0.0
and
1548 s.diagnostics.scalar_census(
"c")[
"num_mg_levels"] > 1, f
"{nm} n={n}: full table")
1549 its[n][pe] =
gadv_row(f
"{nm} n={n}", s,
"c", pe, bd)
1551 print(f
" [{nm}: {time.time() - t0:.0f} s]")
1553 for pe, bd
in ((1.0, 16), (10.0, 18)):
1555 gadv_row(
"(c) G9c channel, open faces", s,
"d", pe, bd, rate=1.0)
1556 print(f
" [(c): {time.time() - t0:.0f} s]")
1561 """A list of numbers formatted with `spec` (no nested f-string quotes: Python 3.10)."""
1562 return "[" +
", ".join(format(x, spec)
for x
in v) +
"]"
1566 """A walled box of physical size L (no flow)."""
1567 return walled((n, n, n), (L, L, L))
1571 """Ruling D-WO7-1: the sealed solid volume (kappa_s > 0, conjugate, no open solid face and no
1572 conjugate facet: not a solid unknown) is <= 1e-6 of the conjugate solid volume (as D-WO2-1)."""
1573 r = cen[
"sealed_solid_volume"] / cen[
"solid_volume"]
if cen[
"solid_volume"] > 0
else 0.0
1574 check(r <= 1e-6, f
"{tag}: sealed solid volume {r:.1e} <= 1e-6 of the solid volume")
1579 """Solid unknowns that no solid face and no facet couple: kappa_s > 0, every solid aperture
1580 1 - a^snap = 0 (all six fluid apertures snapped to 1, hence no facet). Ruling D-WO7-1 makes
1581 them sealed (not unknowns): this count must be 0."""
1582 geo = s.diagnostics.scalar_geometry(name)
1583 us = geo[
"solid_unknown"] > 0.5
1584 ax, ay, az = geo[
"aperture_x"], geo[
"aperture_y"], geo[
"aperture_z"]
1585 allopen = np.ones(us.shape, dtype=bool)
1586 for a, ap
in ((0, ax), (1, ay), (2, az)):
1587 allopen &= (ap >= 1.0) & (np.roll(ap, -1, axis=a) >= 1.0)
1592 """Maxwell's conducting sphere in a uniform gradient G (psi form, Lam_f = 1, Lam_s = ratio):
1593 outside G.x' (1 + A R^3/r^3), inside B G.x', A = (1 - ratio)/(ratio + 2), B = 3/(ratio + 2),
1595 xs, ys, zs = X - c0[0], Y - c0[1], Z - c0[2]
1596 r = np.sqrt(xs * xs + ys * ys + zs * zs)
1597 gx = G[0] * xs + G[1] * ys + G[2] * zs
1598 A, B = (1.0 - ratio) / (ratio + 2.0), 3.0 / (ratio + 2.0)
1599 out = gx * (1.0 + A * R**3 / np.maximum(r, 1e-300) ** 3)
1600 return np.where(r >= R, out, B * gx), B * gx, out
1603def g4_case(Rh, off, ratio, K=1.0, rtol=None, G=(0.3, -0.5, 0.8)):
1604 """G4: a conjugate sphere R = 1 (Lam_s = ratio, C_s = 1, partition K) in a box 6R, Lam_f = D =
1605 1, the exact exterior field as the box Dirichlet profile, steady."""
1611 c0 = np.array([0.5 * L, 0.5 * L, 0.5 * L]) + np.asarray(off) * h
1613 r = np.sqrt((X - c0[0]) ** 2 + (Y - c0[1]) ** 2 + (Z - c0[2]) ** 2)
1614 s.set_solid(np.asfortranarray(r - R))
1615 add_cc(s, D, box=
"neumann")
1619 s.set_scalar_bc(
"c", f,
"dirichlet", out)
1620 s.set_scalar_solid(
"c", diffusivity=ratio * D / K, capacity=1.0, partition=K)
1621 if rtol
is not None:
1622 s.set_scalar_residual_tolerance(
"c", rtol)
1623 s.solve_scalar_steady(
"c")
1624 geo = s.diagnostics.scalar_geometry(
"c")
1625 cen = s.diagnostics.scalar_census(
"c")
1626 return s, X, Y, Z, c0, geo, cen
1630 """Least-squares fit psi = a + g.x over the masked cells; returns g."""
1631 A = np.stack([np.ones(mask.sum()), X[mask], Y[mask], Z[mask]], axis=1)
1632 sol, *_ = np.linalg.lstsq(A, psi[mask], rcond=
None)
1637 """The k_s = k_f checks (the brief's early unit test): with Lam_s = Lam_f, K = 1, R_c = 0 the
1638 composite must reproduce the homogeneous solution — a linear field to round-off (§1.6.3, G4(a))
1639 and, in the closure mode, k* = 1 (theta = const)."""
1640 print(
"conjugate unit: Lam_s = Lam_f, K = 1, R_c = 0 reproduces the homogeneous solution")
1641 G = (0.3, -0.5, 0.8)
1642 for K
in (1.0, 3.0):
1643 s, X, Y, Z, c0, geo, cen =
g4_case(6, OFFSETS[0], 1.0, K=K, rtol=1e-12, G=G)
1644 ex = G[0] * (X - c0[0]) + G[1] * (Y - c0[1]) + G[2] * (Z - c0[2])
1645 uf = geo[
"unknown"] > 0.5
1646 us = geo[
"solid_unknown"] > 0.5
1648 ef = float(np.max(np.abs(s.get_field(
"c") - ex)[uf]))
1649 cs = s.get_scalar_solid(
"c")
1650 es = float(np.max(np.abs(cs / K - ex)[us]))
1651 scale = float(np.linalg.norm(G)) * 6.0
1652 print(f
" K={K}: max|psi_f - G.x| {ef:.2e}, max|psi_s - G.x| {es:.2e} (every solid unknown); "
1653 f
"{int(us.sum())} solid unknowns, sealed solid volume {cen['sealed_solid_volume']:.1e} "
1654 f
"of {cen['solid_volume']:.3e}; {cen['krylov_iterations']} it, rungs {cen['probe_rungs']}")
1655 check(cen[
"krylov_converged"], f
"K={K}: converged")
1656 check(int(iso.sum()) == 0, f
"K={K}: no uncoupled solid unknown (D-WO7-1; {int(iso.sum())})")
1658 check(ef <= 1e-10 * scale
and es <= 1e-10 * scale,
1659 f
"K={K}: linear field reproduced to 1e-10 |G| L in both phases ({ef:.1e}, {es:.1e})")
1660 check(bool(np.all(np.isnan(cs[~us]))), f
"K={K}: get_scalar_solid NaN outside the solid unknowns")
1662 s =
pf.Solver((n, n, n), extent=(1.0, 1.0, 1.0))
1663 s.set_advection(
False)
1666 R = 0.5 * (0.3 * 6.0 / math.pi) ** (1.0 / 3.0)
1668 s.set_solid(np.asfortranarray(np.sqrt((X - 0.51) ** 2 + (Y - 0.49) ** 2 + (Z - 0.505) ** 2) - R))
1669 s.add_scalar(
"c", diffusivity=D, cutcell=
True)
1670 s.set_scalar_solid(
"c", diffusivity=D)
1671 s.set_scalar_mean_gradient(
"c", (1.0, 0.0, 0.0))
1672 s.solve_scalar_steady(
"c")
1673 J = np.asarray(s.scalar_mean_flux(
"c"))
1674 th = s.get_field(
"c")
1675 print(f
" closure, SC array c = 0.3: k* - 1 = {-J[0] / D - 1.0:+.2e}, J_y,z = {J[1]:+.1e}, {J[2]:+.1e},"
1676 f
" max|theta| {float(np.max(np.abs(th))):.1e}")
1677 check(abs(-J[0] / D - 1.0) <= 1e-12
and abs(J[1]) <= 1e-12
and abs(J[2]) <= 1e-12,
1678 "closure at Lam_s = Lam_f: k* = 1 to 1e-12 (the mean-gradient conjugate terms, §1.5)")
1682 print(
"G4 Maxwell conjugate sphere (steady), box 6R, R/h in {6, 12, 24}")
1683 G = (0.3, -0.5, 0.8)
1684 Gn = float(np.linalg.norm(G))
1686 for ratio
in (1e-2, 1.0, 10.0, 1e3):
1687 e[ratio], its[ratio] = {}, {}
1688 for Rh
in (6, 12, 24):
1691 s, X, Y, Z, c0, geo, cen =
g4_case(Rh, off, ratio, G=G)
1692 us = geo[
"solid_unknown"] > 0.5
1693 full = us & (geo[
"kappa_solid"] >= 1.0)
1695 Bg = 3.0 / (ratio + 2.0) * np.asarray(G)
1696 rows.append(dict(err=float(np.linalg.norm(gfit - Bg) / np.linalg.norm(Bg)),
1697 it=cen[
"krylov_iterations"], conv=cen[
"krylov_converged"],
1700 e[ratio][Rh] =
rms([r[
"err"]
for r
in rows])
1701 its[ratio][Rh] = [r[
"it"]
for r
in rows]
1702 print(f
" ratio={ratio:g} R/h={Rh:3d} interior gradient rel err {fmt([r['err'] for r in rows], '.3e')}"
1703 f
" iters {its[ratio][Rh]} rungs {rows[0]['rungs']} isolated solid {[r['iso'] for r in rows]}")
1705 check(r[
"conv"], f
"ratio={ratio} R/h={Rh}: converged ({r['it']} iterations)")
1706 check(r[
"it"] <= 30, f
"ratio={ratio} R/h={Rh}: G-iter conjugate <= 30 ({r['it']})")
1708 check(max(e[ratio].values()) <= 1e-9,
1709 f
"ratio=1: interior gradient exact to round-off ({max(e[ratio].values()):.1e} <= 1e-9)")
1711 o1, o2 =
order(e[ratio][6], e[ratio][12]),
order(e[ratio][12], e[ratio][24])
1712 check(o1 >= 1.7
and o2 >= 1.7, f
"ratio={ratio}: interior-gradient orders {o1:.2f}, {o2:.2f} >= 1.7")
1713 check(e[ratio][24] <= 5e-3, f
"ratio={ratio}: |err| {e[ratio][24]:.2e} <= 5e-3 at R/h = 24 (prov.)")
1714 for ratio
in (1e-2, 1e3):
1715 for Rh
in (6, 12, 24):
1716 b = 2 * max(its[1.0][Rh]) + 5
1717 check(max(its[ratio][Rh]) <= b,
1718 f
"(d) ratio={ratio} R/h={Rh}: iterations {max(its[ratio][Rh])} <= 2 x ratio-1 + 5 = {b}")
1719 print(
"G4(c) K = 3 with the same Lam_s: psi identical, c_s = 3 psi_s")
1720 for ratio
in (10.0,):
1721 s1, X, Y, Z, c0, geo, _ =
g4_case(12, OFFSETS[0], ratio, K=1.0, rtol=1e-13, G=G)
1722 s3, _, _, _, _, _, _ =
g4_case(12, OFFSETS[0], ratio, K=3.0, rtol=1e-13, G=G)
1723 us = geo[
"solid_unknown"] > 0.5
1725 p1, p3 = s1.get_field(
"c_solid"), s3.get_field(
"c_solid")
1726 d = float(np.max(np.abs(p1 - p3)[us & ~iso]) / np.max(np.abs(p1)[us]))
1727 df = float(np.max(np.abs(s1.get_field(
"c") - s3.get_field(
"c"))) / np.max(np.abs(s1.get_field(
"c"))))
1728 c3 = s3.get_scalar_solid(
"c")
1729 k3 = float(np.max(np.abs(c3[us] - 3.0 * p3[us])))
1730 print(f
" ratio={ratio}: max|psi_s(K=3) - psi_s(K=1)| {d:.1e}, fluid {df:.1e} (rel); "
1731 f
"max|c_s - 3 psi_s| {k3:.1e}")
1732 check(d <= 1e-9
and df <= 1e-9, f
"K = 3: psi identical to K = 1 within 1e-9 ({d:.1e}, {df:.1e})")
1733 check(k3 == 0.0,
"K = 3: get_scalar_solid = 3 psi_s exactly")
1737 """k* of perfectly conducting spheres on the simple-cubic lattice, Andrianov & Topol eq. 157
1739 a1, a2, a3, a4, a5, a6 = 1.305, 0.231, 0.405, 0.0723, 0.153, 0.0105
1740 den = (-1.0 + c + a1 * c ** (10 / 3) * (1.0 + a2 * c ** (11 / 3)) / (1.0 - a3 * c ** (7 / 3)) +
1741 a4 * c ** (14 / 3) + a5 * c**6 + a6 * c ** (22 / 3))
1742 return 1.0 - 3.0 * c / den
1748 s =
pf.Solver((n, n, n), extent=(L, L, L))
1749 s.set_advection(
False)
1752 R = 0.5 * L * (0.3 * 6.0 / math.pi) ** (1.0 / 3.0)
1753 c0 = np.array([0.5 * L, 0.5 * L, 0.5 * L]) + np.asarray(off) * h
1755 r = np.sqrt((X - c0[0]) ** 2 + (Y - c0[1]) ** 2 + (Z - c0[2]) ** 2)
1756 s.set_solid(np.asfortranarray(r - R))
1757 s.add_scalar(
"c", diffusivity=D, cutcell=
True)
1758 s.set_scalar_solid(
"c", diffusivity=ratio * D)
1759 s.set_scalar_mean_gradient(
"c", (1.0, 0.0, 0.0))
1760 s.solve_scalar_steady(
"c")
1761 J = np.asarray(s.scalar_mean_flux(
"c"))
1762 c = s.diagnostics.scalar_census(
"c")
1763 return dict(k=-J[0] / D, its=c[
"krylov_iterations"], conv=c[
"krylov_converged"], nd=2.0 * R / h,
1770 print(f
"G5a conducting periodic SC array, c = 0.3, Lam_s/Lam_f = 1e4, mean gradient e_x; "
1771 f
"reference k* (Andrianov-Topol eq. 157, perfect conductor) = {ref:.5f}")
1773 for n
in (20, 40, 80):
1774 rows = [
g5a_case(n, off)
for off
in OFFSETS]
1775 k[n] = float(np.mean([r[
"k"]
for r
in rows]))
1776 its[n] = [r[
"its"]
for r
in rows]
1777 print(f
" n={n} (ND {rows[0]['nd']:.1f}) k* {fmt([r['k'] for r in rows], '.6f')} "
1778 f
"rel err vs ref {k[n] / ref - 1.0:+.2e} iters {its[n]} residual {fmt([r['res'] for r in rows], '.1e')}"
1779 f
" isolated solid {[r['iso'] for r in rows]}")
1781 check(r[
"conv"], f
"n={n}: converged ({r['its']} iterations)")
1782 check(r[
"its"] <= 30, f
"n={n}: G-iter singular steady <= 30 ({r['its']})")
1789 p = math.log2(abs(k[20] - k[40]) / abs(k[40] - k[80]))
if k[40] != k[80]
else float(
"inf")
1790 check(p >= 1.7, f
"(i) self-convergence order {p:.2f} >= 1.7")
1791 kx = k[80] + (k[80] - k[40]) / (2.0**p - 1.0)
1792 check(abs(kx / ref - 1.0) <= 5e-4,
1793 f
"(ii) extrapolate {kx:.6f}: |k*/ref - 1| {abs(kx / ref - 1.0):.2e} <= 5e-4 (order-2 extrapolate "
1794 f
"{k[80] + (k[80] - k[40]) / 3.0:.6f}, INFO)")
1795 for n, b
in ((20, 6.64e-2), (40, 1.82e-2), (80, 4.86e-3)):
1796 check(abs(k[n] / ref - 1.0) <= b, f
"(iii) n={n}: |k*/ref - 1| {abs(k[n] / ref - 1.0):.2e} <= {b:.2e}")
1800 """The slowest decay rate mu and the mode (P, B, C) of the composite sphere in the psi form
1801 (Lam_f = C_f = 1): solid r < R, psi_s = P sin(k_s r)/r; fluid R < r < Ro, psi_f = (B sin(k_f r)
1802 + C cos(k_f r))/r; psi_f(Ro) = 0, Lam_s psi_s' = psi_f' and psi_s - psi_f + R_c Lam_s psi_s' = 0
1803 at R (the l = 0 analogue of conj.py's exact())."""
1805 ks, kf = math.sqrt(CK * mu / Ls), math.sqrt(mu)
1806 S =
lambda k, r: math.sin(k * r) / r
1807 C =
lambda k, r: math.cos(k * r) / r
1808 dS =
lambda k, r: (k * math.cos(k * r) * r - math.sin(k * r)) / (r * r)
1809 dC =
lambda k, r: (-k * math.sin(k * r) * r - math.cos(k * r)) / (r * r)
1810 return np.array([[0.0, S(kf, Ro), C(kf, Ro)],
1811 [Ls * dS(ks, R), -dS(kf, R), -dC(kf, R)],
1812 [S(ks, R) + Rc * Ls * dS(ks, R), -S(kf, R), -C(kf, R)]])
1813 det =
lambda m: float(np.linalg.det(mat(m)))
1814 mus = np.linspace(1e-4, 40.0, 40000)
1815 d = [det(m)
for m
in mus]
1816 for i
in range(len(mus) - 1):
1817 if d[i] * d[i + 1] < 0:
1818 a, b = mus[i], mus[i + 1]
1819 for _
in range(200):
1821 if det(a) * det(m) <= 0:
1826 _, _, vt = np.linalg.svd(mat(mu))
1827 return mu, vt[-1], math.sqrt(CK * mu / Ls), math.sqrt(mu)
1828 raise RuntimeError(
"no root")
1831G6_CASES = ((10.0, 1.0, 1.0, 0.0), (0.1, 1.0, 1.0, 0.0), (100.0, 0.5, 1.0, 0.0), (3.0, 3.0, 3.0, 0.0),
1832 (1.0, 1.0, 1.0, 0.2), (5.0, 1.0, 0.5, 0.5))
1836G6_BOUND = ({8: 1.48e-2, 16: 3.77e-3, 32: 9.56e-4}, {8: 3.37e-2, 16: 8.45e-3, 32: 2.14e-3},
1837 {8: 1.62e-2, 16: 4.16e-3, 32: 1.06e-3}, {8: 3.49e-3, 16: 9.12e-4, 32: 2.37e-4},
1838 {8: 7.55e-3, 16: 2.01e-3, 32: 5.16e-4}, {8: 7.41e-3, 16: 1.90e-3, 32: 4.82e-4})
1842 """G6: a conjugate core R = 1 (instance 0) inside an immersed Dirichlet sphere Ro = 2 (instance
1843 1, psi = 0); psi form (Lam_s, C_s K, K, R_c), Lam_f = C_f = 1; BE late-time ratio of the total
1844 mass (fluid + solid) with dt mu = 1, the exact mode as the initial condition."""
1845 Ls, CK, K, Rc = case
1848 n = int(math.ceil(2.0 * Ro / h)) + 6
1850 s =
walled((n, n, n), (L, L, L))
1851 c0 = np.array([0.5 * L, 0.5 * L, 0.5 * L]) + np.asarray(off) * h
1853 s.set_solid_from_scene(cutcell_pressure=
False)
1854 mu, (P, B, C), ks, kf =
g6_exact(Ls, CK, Rc)
1857 add_cc(s, 1.0, box=
"neumann")
1858 s.set_scalar_wall(
"c",
"dirichlet", 0.0, instance=1)
1859 s.set_scalar_solid(
"c", diffusivity=Ls / CK, capacity=CK / K, partition=K, contact_resistance=Rc,
1862 r = np.maximum(np.sqrt((X - c0[0]) ** 2 + (Y - c0[1]) ** 2 + (Z - c0[2]) ** 2), 1e-12)
1863 s.set_field(
"c", np.asfortranarray((B * np.sin(kf * r) + C * np.cos(kf * r)) / r))
1864 s.set_field(
"c_solid", np.asfortranarray(P * np.sin(ks * r) / r))
1865 masses, mfl, its, idmax = [], [], [], 0.0
1867 for _
in range(nsteps):
1869 b = s.diagnostics.scalar_budget(
"c")
1870 masses.append(b[
"mass"] + b[
"mass_solid"])
1871 mfl.append(b[
"mass"])
1872 idmax = max(idmax, abs(b[
"identity_error"]) / max(abs(b[
"d_mass"]), 1e-300))
1873 cen = s.diagnostics.scalar_census(
"c")
1874 its.append(cen[
"krylov_iterations"])
1875 if not cen[
"krylov_converged"]:
1876 return dict(err=float(
"nan"), its=its, conv=
False, idrel=idmax, rungs=cen[
"probe_rungs"])
1877 mu_h = (masses[-2] / masses[-1] - 1.0) / dt
1878 mu_f = (mfl[-2] / mfl[-1] - 1.0) / dt
1879 sealed_check(f
"G6 case {G6_CASES.index(case) + 1} R/h={Rh}", cen)
1880 return dict(err=mu_h / mu - 1.0, errf=mu_f / mu - 1.0, its=its, conv=
True, idrel=idmax,
1881 rungs=cen[
"probe_rungs"], nsolid=cen[
"num_solid_unknowns"], iso=iso)
1885 print(
"G6 transient composite sphere (conjugate core R, immersed Dirichlet sphere 2R), "
1886 "BE late-time ratio, dt mu = 1, 30 steps; R/h in {8, 16, 32}")
1887 for ci, case
in enumerate(G6_CASES):
1888 if cases
is not None and ci
not in cases:
1890 mu =
g6_exact(case[0], case[1], case[3])[0]
1892 for Rh
in (8, 16, 32):
1894 rows = [
g6_case(Rh, off, case)
for off
in OFFSETS]
1895 e[Rh] =
rms([r[
"err"]
for r
in rows])
1896 print(f
" case {ci + 1} (Lam_s, CK, K, Rc) = {case} mu = {mu:.6f} R/h={Rh:3d} "
1897 f
"mu rel err {fmt([r['err'] for r in rows], '+.3e')} (INFO fluid mass: "
1898 f
"{fmt([r.get('errf', float('nan')) for r in rows], '+.3e')}; isolated solid "
1899 f
"{[r.get('iso') for r in rows]}) identity/|dM| <= "
1900 f
"{max(r['idrel'] for r in rows):.1e} iters/step {min(min(r['its']) for r in rows)}.."
1901 f
"{max(max(r['its']) for r in rows)} rungs {rows[0]['rungs']} ({time.time() - t0:.0f} s)")
1903 check(r[
"conv"], f
"case {ci + 1} R/h={Rh}: every step converged")
1904 check(r[
"idrel"] <= 1e-13, f
"case {ci + 1} R/h={Rh}: budget identity {r['idrel']:.1e} <= 1e-13 |d_mass|")
1905 check(max(r[
"its"]) <= 30, f
"case {ci + 1} R/h={Rh}: G-iter conjugate <= 30 ({max(r['its'])})")
1906 o1, o2 =
order(e[8], e[16]),
order(e[16], e[32])
1907 check(o1 >= 1.7
and o2 >= 1.7, f
"case {ci + 1}: (i) orders {o1:.2f}, {o2:.2f} >= 1.7")
1910 for Rh
in (8, 16, 32):
1911 b = G6_BOUND[ci][Rh]
1912 check(e[Rh] <= b, f
"case {ci + 1}: (iii) |err| {e[Rh]:.3e} <= {b:.2e} at R/h = {Rh}")
1916 """WO-7's extra G-adv row (design A2): G-adv(b) with conducting spheres, Lam_s/Lam_f = 10, K = 1,
1917 at Pe_h 1 and 10 (the mean-gradient mode, G = e_x): converged, in <= 1.5x the insulating (b)
1918 count of the same field."""
1919 print(
"G-adv(b) conjugate: conducting spheres Lam_s/Lam_f = 10 vs insulating, Pe_h 1 and 10")
1921 for pe
in (1.0, 10.0):
1923 ci = si.diagnostics.scalar_census(
"c")
1925 s.add_scalar(
"c", diffusivity=0.05, cutcell=
True)
1926 s.set_scalar_solid(
"c", diffusivity=0.5)
1927 s.set_scalar_mean_gradient(
"c", (1.0, 0.0, 0.0))
1929 s.solve_scalar_steady(
"c")
1930 cc = s.diagnostics.scalar_census(
"c")
1931 b = s.diagnostics.scalar_budget(
"c")
1932 print(f
" n={n} Pe_h {cc['max_cell_peclet']:.3g}: conjugate {cc['krylov_iterations']} it "
1933 f
"(converged {cc['krylov_converged']}, residual {cc['krylov_residual']:.1e}), insulating "
1934 f
"{ci['krylov_iterations']} it; identity_error {b['identity_error']:.1e}")
1935 check(cc[
"krylov_converged"], f
"n={n} Pe_h={pe}: conjugate converged")
1936 check(cc[
"krylov_iterations"] <= 1.5 * ci[
"krylov_iterations"],
1937 f
"n={n} Pe_h={pe}: {cc['krylov_iterations']} <= 1.5 x {ci['krylov_iterations']}")
1947 except Exception
as e:
1948 check(
False, f
"{msg} (raised {type(e).__name__}: {e})")
1950 check(
False, msg +
" (did not raise)")
1954 """`raises`, and the message names every one of `needles` (the remedy)."""
1958 missing = [w
for w
in needles
if w
not in str(e)]
1959 check(
not missing, f
"{msg}" + (f
" (message lacks {missing}: {e})" if missing
else ""))
1961 except Exception
as e:
1962 check(
False, f
"{msg} (raised {type(e).__name__}: {e})")
1964 check(
False, msg +
" (did not raise)")
1968 print(
"API: the opt-in, the refusals (§8.1) and the name checks (ruling D-WO3-2)")
1970 s =
pf.Solver((n, n, n), extent=(1.0, 1.0, 1.0))
1971 s.set_advection(
False)
1976 s.set_solid(np.asfortranarray(np.sqrt((X - 0.5) ** 2 + (Y - 0.5) ** 2 + (Z - 0.5) ** 2) - 0.2))
1977 raises(ValueError,
lambda: s.add_scalar(
"bad", 1.0, cutcell=
True, iters=5),
1978 "add_scalar(cutcell=True, iters=5) is a ValueError")
1979 s.add_scalar(
"legacy", 1.0)
1980 s.add_scalar(
"c", 1.0, cutcell=
True)
1981 for nm, fn
in ((
"scalar_geometry",
lambda: s.diagnostics.scalar_geometry(
"legacy")),
1982 (
"scalar_census",
lambda: s.diagnostics.scalar_census(
"legacy")),
1983 (
"scalar_budget",
lambda: s.diagnostics.scalar_budget(
"legacy")),
1984 (
"set_scalar_wall",
lambda: s.set_scalar_wall(
"legacy",
"dirichlet", 1.0)),
1985 (
"set_scalar_source",
lambda: s.set_scalar_source(
"legacy", 1.0)),
1986 (
"solve_scalar_steady",
lambda: s.solve_scalar_steady(
"legacy"))):
1987 raises(ValueError, fn, f
"{nm} on a legacy scalar is a ValueError")
1988 raises(ValueError,
lambda: s.set_scalar_wall(
"c",
"dirichlet", 1.0, instance=0),
1989 "set_scalar_wall(instance=0) without a scene is a ValueError")
1990 raises(ValueError,
lambda: s.set_scalar_wall(
"c",
"robin", 0.0, coefficient=-1.0),
1991 "a negative robin coefficient is a ValueError")
1992 raises(ValueError,
lambda: s.set_scalar_residual_tolerance(
"c", 0.0),
"rtol = 0 is a ValueError")
1993 raises(ValueError,
lambda: s.set_scalar_bc(
"c",
"-x",
"dirichlet", np.zeros((n, n + 1))),
1994 "a profile of the wrong shape is a ValueError")
1995 s.set_scalar_wall(
"c",
"dirichlet", 1.0)
1997 c = s.diagnostics.scalar_census(
"c")
1999 check(c[
"krylov_converged"]
and c[
"num_mg_levels"] == 3,
2000 f
"one step converged ({c['krylov_iterations']} iterations, {c['num_mg_levels']} MG levels)")
2001 s.set_scalar_bc(
"c",
"-x",
"dirichlet", 0.5)
2002 raises(RuntimeError, s.advance_scalars,
"a scalar Dirichlet face against a periodic flow face is refused")
2003 s.set_scalar_bc(
"c",
"-x",
"periodic")
2004 raises(ValueError,
lambda: s.set_scalar_mean_gradient(
"c", (float(
"nan"), 0.0, 0.0)),
2005 "a non-finite mean gradient is a ValueError")
2006 raises(ValueError,
lambda: s.set_scalar_mean_gradient(
"legacy", (1.0, 0.0, 0.0)),
2007 "set_scalar_mean_gradient on a legacy scalar is a ValueError")
2008 s.set_scalar_mean_gradient(
"c", (1.0, 0.0, 0.0))
2010 sw =
pf.Solver((n, n, n), extent=(1.0, 1.0, 1.0))
2011 sw.set_advection(
False)
2014 sw.set_domain_bc(
"-y",
"wall")
2015 sw.set_domain_bc(
"+y",
"wall")
2016 sw.set_solid(np.asfortranarray(np.sqrt((X - 0.5) ** 2 + (Y - 0.5) ** 2 + (Z - 0.5) ** 2) - 0.2))
2017 sw.add_scalar(
"c", 1.0, cutcell=
True)
2018 sw.set_scalar_bc(
"c",
"-y",
"neumann")
2019 sw.set_scalar_bc(
"c",
"+y",
"neumann")
2020 sw.set_scalar_mean_gradient(
"c", (1.0, 0.0, 0.5))
2021 sw.solve_scalar_steady(
"c")
2022 sw.set_scalar_mean_gradient(
"c", (0.0, 1.0, 0.0))
2023 raises_naming(RuntimeError,
lambda: sw.solve_scalar_steady(
"c"), (
"along y",
"-y"),
2024 "a mean gradient along a non-periodic axis is refused, naming the axis and face")
2025 s.set_scalar_mean_gradient(
"c", (0.0, 0.0, 0.0))
2026 s.set_porous_continuity(
True)
2027 raises(RuntimeError, s.advance_scalars,
"porous continuity is refused")
2030 s =
pf.Solver((n, n, n), extent=(1.0, 1.0, 1.0))
2031 s.set_advection(
False)
2036 s.set_solid(np.asfortranarray(np.sqrt((X - 0.5) ** 2 + (Y - 0.5) ** 2 + (Z - 0.5) ** 2) - 0.2))
2037 s.add_scalar(
"c", 1.0, cutcell=
True)
2038 s.set_field(
"u", np.asfortranarray(np.full((n, n, n), 0.5)))
2039 raises_naming(RuntimeError, s.advance_scalars, (
"cutcell_pressure=True",
"set_pressure_geometry"),
2040 "a moving fluid without cutcell_pressure is refused, naming the remedy (D-WO5-2)")
2042 s = pf.SolverColocated((n, n, n), extent=(1.0, 1.0, 1.0))
2043 s.set_advection(
False)
2047 s.set_collocated_scheme(
"ghost")
2048 s.set_solid(np.asfortranarray(np.sqrt((X - 0.5) ** 2 + (Y - 0.5) ** 2 + (Z - 0.5) ** 2) - 0.2),
2049 cutcell_pressure=
True)
2050 s.add_scalar(
"c", 1.0, cutcell=
True)
2052 (
"'gauge-exact'",
"'plain'",
"'embed'",
"staggered Solver"),
2053 "the 'ghost' scheme is refused, listing gauge-exact, plain, embed and the staggered "
2059 for seed
in (
"set_field",
"set_velocity"):
2060 s = pf.SolverColocated((n, n, n), extent=(1.0, 1.0, 1.0))
2061 s.set_advection(
False)
2065 s.set_collocated_scheme(
"gauge-exact")
2066 s.set_solid(np.asfortranarray(np.sqrt((X - 0.5) ** 2 + (Y - 0.5) ** 2 + (Z - 0.5) ** 2) - 0.2),
2067 cutcell_pressure=
True)
2068 s.add_scalar(
"c", 1.0, cutcell=
True)
2069 s.set_scalar_wall(
"c",
"dirichlet", 1.0)
2070 if seed ==
"set_field":
2071 s.set_field(
"u", np.asfortranarray(np.full((n, n, n), 0.5)))
2072 for fn, nm
in ((
lambda: s.solve_scalar_steady(
"c"),
"solve_scalar_steady"),
2073 (s.advance_scalars,
"advance_scalars")):
2074 raises_naming(RuntimeError, fn, (
"FACE field",
"set_velocity",
"step()"),
2075 f
"collocated {nm} with an unbuilt face field and a moving fluid is "
2076 "refused, naming the remedy (D-WOR-1)")
2078 s.set_velocity(0, np.asfortranarray(np.full((n, n, n), 0.5)))
2079 s.solve_scalar_steady(
"c")
2080 cen = s.diagnostics.scalar_census(
"c")
2081 check(cen[
"max_cell_peclet"] > 0.0
and cen[
"num_flux_faces"] > 0,
2082 f
"collocated, seeded by set_velocity: the steady solve advects (Pe_h "
2083 f
"{cen['max_cell_peclet']:.3g}, {cen['num_flux_faces']} flux faces)")
2086 for m, want
in ((15,
True), (16,
False)):
2087 s =
pf.Solver((m, m, m), extent=(1.0, 1.0, 1.0))
2088 s.set_advection(
False)
2089 Xm, Ym, Zm =
grid(s)
2090 s.set_solid(np.asfortranarray(np.sqrt((Xm - 0.5) ** 2 + (Ym - 0.5) ** 2 + (Zm - 0.5) ** 2) - 0.2))
2091 s.add_scalar(
"c", 1.0, cutcell=
True)
2092 s.set_scalar_wall(
"c",
"dirichlet", 1.0)
2095 got =
"ScalarMG level table stops" in err
2096 check(got == want
and "ScalarMG" not in err2,
2097 f
"{m}^3 steady: the shallow-bottom warning is {'printed once' if want else 'absent'} "
2098 f
"(D-WOR-4; {err.strip()[:90]!r})")
2101 for scheme
in (
"koren",
"fou"):
2102 s =
pf.Solver((n, n, n), extent=(1.0, 1.0, 1.0))
2103 s.set_advection(
False)
2105 s.set_solid(np.asfortranarray(np.sqrt((X - 0.5) ** 2 + (Y - 0.5) ** 2 + (Z - 0.5) ** 2) - 0.2),
2106 cutcell_pressure=
True)
2107 s.add_scalar(
"c", 0.01, scheme=scheme, cutcell=
True)
2108 s.set_field(
"u", np.asfortranarray(np.full((n, n, n), 0.75)))
2111 cb = s.diagnostics.scalar_census(
"c")[
"bulk_courant"]
2112 want = scheme ==
"koren"
2113 check(cb > 0.5
and (
"'koren' at bulk Courant" in err) == want
and "Courant" not in err2,
2114 f
"{scheme} at bulk Courant {cb:.3f}: the koren warning is "
2115 f
"{'printed once' if want else 'absent'} (D-WOR-7)")
2117 plate = np.asfortranarray(np.abs(X - (n // 2 + 0.55) * h) - 0.2 * h)
2118 s =
pf.Solver((n, n, n), extent=(1.0, 1.0, 1.0))
2119 s.set_advection(
False)
2121 s.add_scalar(
"c", 1.0, cutcell=
True)
2123 errs.append(
capture_stderr(
lambda: s.solve_scalar_steady(
"c"))[1])
2125 errs.append(
capture_stderr(
lambda: s.solve_scalar_steady(
"c"))[1])
2126 check([
"thin-solid" in e
for e
in errs] == [
True,
False,
True],
2127 f
"the thin-solid warning: once per geometry, again after set_solid (D-WOR-7; "
2128 f
"{['thin-solid' in e for e in errs]})")
2130 s =
pf.Solver((n, n, n), extent=(1.0, 1.0, 1.0))
2131 s.set_advection(
False)
2136 s.set_solid(np.asfortranarray(np.sqrt((X - 0.5) ** 2 + (Y - 0.5) ** 2 + (Z - 0.5) ** 2) - 0.2))
2137 s.add_scalar(
"legacy", 1.0)
2138 s.add_scalar(
"c", 1.0, cutcell=
True)
2139 raises(ValueError,
lambda: s.set_scalar_solid(
"legacy", 1.0),
"set_scalar_solid on a legacy scalar")
2140 for kw, nm
in (({
"diffusivity": -1.0},
"diffusivity < 0"), ({
"capacity": 0.0},
"capacity = 0"),
2141 ({
"partition": 0.0},
"partition = 0"), ({
"contact_resistance": -1.0},
"R_c < 0"),
2142 ({
"instance": 0},
"instance= without a scene")):
2143 args = {
"diffusivity": 1.0}
2145 raises(ValueError,
lambda a=args: s.set_scalar_solid(
"c", **a), f
"set_scalar_solid: {nm} is a ValueError")
2146 check(
"c_solid" not in s.field_names(),
"no solid field before set_scalar_solid")
2147 s.set_scalar_solid(
"c", 2.0, capacity=0.5, partition=3.0)
2148 check(
"c_solid" in s.field_names(),
"set_scalar_solid registers 'c_solid'")
2149 check(bool(np.all(np.isnan(s.get_scalar_solid(
"c")))),
"get_scalar_solid before a solve: all NaN")
2150 s.set_field(
"c", np.asfortranarray(np.ones((n, n, n))))
2151 s.set_field(
"c_solid", np.asfortranarray(np.ones((n, n, n))))
2153 c = s.diagnostics.scalar_census(
"c")
2154 cs = s.get_scalar_solid(
"c")
2155 geo = s.diagnostics.scalar_geometry(
"c")
2156 us = geo[
"solid_unknown"] > 0.5
2157 check(c[
"krylov_converged"]
and c[
"num_solid_unknowns"] == int(us.sum()) > 0,
2158 f
"a conjugate step converged ({c['krylov_iterations']} it, {c['num_solid_unknowns']} solid unknowns)")
2159 check(float(np.max(np.abs(cs[us] - 3.0))) <= 1e-9
and float(np.max(np.abs(s.get_field(
"c")[geo[
"unknown"] > 0.5] - 1.0))) <= 1e-9,
2160 "psi = 1 in both phases is an equilibrium: c = 1, c_s = K = 3")
2161 s.set_scalar_wall(
"c",
"neumann", 0.0)
2163 check(s.diagnostics.scalar_census(
"c")[
"num_solid_unknowns"] == 0,
"set_scalar_wall(instance=None) ends the conjugate path")
2167G13_CASES = (
"gap",
"contact",
"conj")
2171 """Two sphere instances (body ids 0 and 1) of radius R centred at c1, c2."""
2172 ni = np.array([1, -1, -1], dtype=np.int32)
2175 nr[14] = nr[15] = 1.0
2176 ii = np.array([0, -1, 0, -1], dtype=np.int32)
2177 ir = np.zeros(2 * 18)
2178 for k, c
in enumerate((c1, c2)):
2179 ir[18 * k:18 * k + 3] = c
2180 ir[18 * k + 6] = 1.0
2181 ir[18 * k + 7] = 1.0
2182 return ni, nr, ii, ir
2186 """§11 G13: two spheres R = 1 along x in a box (6R, 4R, 4R) with Dirichlet box faces, steady.
2187 'gap' / 'contact': Dirichlet spheres c = 1 at a surface gap R/32 / an overlap R/64, far field 0;
2188 the functional is the total wall flux into the fluid. 'conj': the contacting pair conjugate at
2189 Lam_s/Lam_f = 100 (K = 1), the box faces at the far-field profile c = x - x_c (the pair alone at
2190 rest would carry no flux); the functional is the heat entering through the -x box face,
2191 Q = sum 2 D (g - c_0) h over its face cells (the operator's own boundary row; no solid touches
2195 cells = (6 * Rh, 4 * Rh, 4 * Rh)
2196 L = (6.0 * R, 4.0 * R, 4.0 * R)
2198 xc = np.array([0.5 * L[0], 0.5 * L[1], 0.5 * L[2]]) + np.asarray(off) * h
2199 d = 2.0 * R + (R / 32.0
if case ==
"gap" else -R / 64.0)
2200 c1, c2 = xc - [0.5 * d, 0.0, 0.0], xc + [0.5 * d, 0.0, 0.0]
2202 s.set_solid_from_scene(cutcell_pressure=
False)
2204 add_cc(s, D, box=
"neumann")
2207 s.set_scalar_bc(
"c", f,
"dirichlet", P[0] - xc[0])
2208 s.set_scalar_solid(
"c", diffusivity=100.0 * D)
2210 add_cc(s, D, box=
"dirichlet")
2211 s.set_scalar_wall(
"c",
"dirichlet", 1.0)
2212 s.solve_scalar_steady(
"c")
2213 cen = s.diagnostics.scalar_census(
"c")
2216 c = s.get_field(
"c")
2217 F = float(np.sum(2.0 * D * ((P[0] - xc[0]) - c[0, :, :]) * h))
2219 F = float(np.sum(s.scalar_wall_flux(
"c")))
2220 b = s.diagnostics.scalar_budget(
"c")
2221 return dict(F=F, it=cen[
"krylov_iterations"], conv=cen[
"krylov_converged"], cen=cen, b=b,
2222 finite=bool(np.all(np.isfinite(s.get_field(
"c")[s.diagnostics.scalar_geometry(
"c")[
"unknown"] > 0.5]))))
2226 """(R2 fraction, rungs) over both phases' probes (the solid tuple on a conjugate scalar)."""
2227 pr = cen[
"probe_rungs"]
2228 tot = sum(pr[
"fluid"]) + (sum(pr[
"solid"])
if "solid" in pr
else 0)
2229 r2 = pr[
"fluid"][3] + (pr[
"solid"][3]
if "solid" in pr
else 0)
2230 return (r2 / tot
if tot
else 0.0), pr
2234 """§11 G13 thin plate: a solid slab 0.4 h thick across the box, its mid-plane 0.05 h off a
2235 cell-centre plane (a slab between two centre planes leaves every PL sample positive); the census
2236 counts thin-solid cells and the §9 warning is printed (stderr, captured at the fd)."""
2241 s =
walled((n, n, n), (L, L, L))
2243 x0 = (n // 2 + 0.5) * h + 0.05 * h
2244 s.set_solid(np.asfortranarray(np.abs(X - x0) - 0.2 * h))
2245 add_cc(s, 0.7, box=
"dirichlet")
2246 s.set_scalar_wall(
"c",
"dirichlet", 1.0)
2247 with tempfile.TemporaryFile(mode=
"w+b")
as tmp:
2250 os.dup2(tmp.fileno(), 2)
2252 s.solve_scalar_steady(
"c")
2257 err = tmp.read().decode(errors=
"replace")
2258 cen = s.diagnostics.scalar_census(
"c")
2263 print(
"G13 contacts: two spheres R = 1 in a box (6R, 4R, 4R), R/h in {8, 16, 32}, steady")
2267 info = case ==
"conj"
2269 print(
" OPEN: contact model pending (§13 Q4, Frank) -- the conjugate contact row is INFO")
2271 def check(cond, msg, _info=info):
2273 print((
" info ok " if cond
else " info MISS ") + msg)
2275 globals()[
"check"](cond, msg)
2278 rows = [
g13_case(Rh, off, case)
for off
in OFFSETS]
2279 F[Rh] = float(np.mean([r[
"F"]
for r
in rows]))
2280 its[Rh] = [r[
"it"]
for r
in rows]
2281 fr = [
g13_rungs(r[
"cen"])
for r
in rows]
2282 print(f
" {case:7s} R/h={Rh:3d} F = {[format(r['F'], '.6e') for r in rows]} (mean {F[Rh]:.6e}) iters {its[Rh]}"
2283 f
" two-sided {[r['cen']['num_two_sided'] for r in rows]} thin {[r['cen']['num_thin_solid'] for r in rows]}"
2284 f
" rungs {[p for _, p in fr]}")
2285 for r, (r2, _)
in zip(rows, fr):
2286 check(r[
"conv"]
and r[
"finite"], f
"{case} R/h={Rh}: converged and finite ({r['it']} iterations)")
2287 check(r[
"it"] <= 50, f
"{case} R/h={Rh}: <= 50 iterations ({r['it']})")
2288 if case ==
"gap" and Rh >= 32:
2289 print(f
" info gap R/h={Rh}: two-sided {r['cen']['num_two_sided']} (the gap is >= h)")
2291 check(r[
"cen"][
"num_two_sided"] > 0, f
"{case} R/h={Rh}: census two-sided > 0 ({r['cen']['num_two_sided']})")
2292 check(r2 <= 0.01, f
"{case} R/h={Rh}: R2 <= 1 % of the probes ({100 * r2:.2f} %)")
2294 a, b, c = (F[k]
for k
in rungs)
2295 p =
order(abs(a - b), abs(b - c))
2296 check(p >= 1.0, f
"{case}: total-flux self-convergence order {p:.2f} >= 1.0 "
2297 f
"(|F8 - F16| {abs(a - b):.3e}, |F16 - F32| {abs(b - c):.3e})")
2299 print(f
" thin plate 0.4h: num_thin_solid {cen['num_thin_solid']}, two-sided {cen['num_two_sided']}, "
2300 f
"rungs {cen['probe_rungs']}; stderr: {err.strip()!r}")
2301 check(cen[
"num_thin_solid"] > 0, f
"thin plate: num_thin_solid > 0 ({cen['num_thin_solid']})")
2302 check(
"thin" in err,
"thin plate: the §9 thin-solid warning is printed")
2305GATES = {
"api": gate_api,
"g1": gate_g1,
"g2": gate_g2,
"g3a": gate_g3a,
"g3b": gate_g3b,
"g7": gate_g7,
2306 "giter": gate_giter,
"g9": gate_g9,
"g9b": gate_g9b,
"g9c": gate_g9c,
"gadv": gate_gadv,
2307 "g8": gate_g8,
"g5b": gate_g5b,
"conj_unit": gate_conj_unit,
"g4": gate_g4,
"g5a": gate_g5a,
2308 "g6": gate_g6,
"gadv_conj": gate_gadv_conj,
"g13": gate_g13}
2309for _ci
in range(len(G6_CASES)):
2310 GATES[f
"g6_{_ci + 1}"] = (
lambda c=_ci:
gate_g6(cases=(c,)))
2312if __name__ ==
"__main__":
2313 names = sys.argv[1:]
or list(GATES)
2317 print(f
"[{nm}: {time.time() - t0:.0f} s]")
2319 print(f
"{len(failures)} FAILED")
low_face_flux(s, name, a)
channel_case(kind="staggered", n=24, dt=0.008, D=0.01, scheme="koren", out_bc="neumann", c0=0.2, cin=1.0, cap=True)
gadv_row(tag, s, name, pe, bound, rate=None)
solid_isolated(s, name="c")
g8_case(Rh, off, U=1.0, Pe=10.0, nbox=None, nz=4, exact_flux=True)
maxwell_fields(X, Y, Z, c0, R, G, ratio)
g4_case(Rh, off, ratio, K=1.0, rtol=None, G=(0.3, -0.5, 0.8))
g2_case(Rih, off, mgbox=False)
two_body_scene(c0, Ri, Ro)
raises_naming(exc, fn, needles, msg)
interior_gradient(X, Y, Z, psi, mask)
rescale_peclet(s, name, target)
add_cc(s, D, box="neumann", periodic_z=False)
cell_velocity(s, name, periodic=(True, True, True))
g6_case(Rh, off, case, nsteps=30)
g6_exact(Ls, CK, Rc, R=1.0, Ro=2.0)
gate_g13(cases=G13_CASES, rungs=(8, 16, 32))
sphere_pair_scene(c1, c2, R)
g1_case(Rh, off, aniso=False)
g7a_case(Rh, off, neumann, nsteps=30)
g9b_case(kind, scheme, n=32, nsteps=50)
g9_case(Rh, off, scheme, cr, rtol=None, nsteps=None)
no_solid_case(G, vel=None, D=0.6, n=16)
g5b_geometry_case(n, off)
g3b_case(Rh, off, Bi, nsteps=30)
g5a_case(n, off, D=0.6, ratio=1e4)
g7b_case(Rh, off, iters=25)
giter_transient_case(Rh, off, nsteps=6)
annulus_case(Rh, off, scheme="koren")
poiseuille_face_average(s, c0, R, U, oz, m=24)
walled(cells, extent, origin=(0.0, 0.0, 0.0), periodic_z=False)
backflow_steady_row(n=12, nsteps=10)
set_annulus_velocity(s, fx, fy)
mean_flux_fields(s, name, D, G, periodic)
closure_rhs_density(s, name, D, G)
koren_bulk_control(cr, n=32)
static std::vector< double > slice(const std::vector< double > &g, int ox, int oy, int oz, int lnx, int lny, int lnz)