flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
test_mirror_symmetry.py
Go to the documentation of this file.
1#!/usr/bin/env python
2"""Wall-normal mirror symmetry of the MAC step, and the placement of the variable viscosity.
3
4A bubble column between two walls (y = 0 and y = NY, x/z periodic) collected its bubbles at the
5LOW wall -- and so did the same column with every bubble mirrored to the other side. The cause
6was the variable-viscosity momentum operator: it averaged mu across the faces of CELL i, but the
7staggered unknown u_c(i) lives on the -c face of cell i, so every component saw mu shifted half a
8cell towards +c -- first-order accurate, and in a walled direction a mirror asymmetry (VarFaceProps,
9src/face_props.hpp). Two checks:
10
11 1. mirror pair -- solver A and its y-mirror B (cell fields reflected, v negated onto the mirrored
12 face), same fixed dt, A(y) against mirror(B)(y) after a few steps. Round-off only (~1e-14;
13 the velocity gate is 1e-12 in every row);
14 the shifted viscosity gave 1e-3..1e-2. Variants: single phase with a transported scalar
15 driving rho, the body force and (or not) mu, arithmetic and harmonic viscosity means; the
16 structured VoF with CSF; the block container with its per-marker CSF. The blob touches the
17 LOW wall (the mirror touches the high one) and straddles the periodic x seam.
18 The three variable-mu variants run with set_viscous_stress('laplacian') and again with 'full'
19 (WO-2 of doc/full_viscous_stress.md: the transpose term keeps the mirror symmetry to the same
20 bound). The placement gate (2.) pins 'laplacian': its forcing is the Laplacian form.
21 2. placement -- steady variable-viscosity Stokes, u = A (sin kx cos ky, -cos kx sin ky, 0),
22 mu = 1 + sin(kx + 0.3) cos(ky + 0.7) / 2, forced by -div(mu grad u_c): second order in h
23 (the shifted viscosity was first order: 1.39 then 1.05).
24
25Run: OMP_NUM_THREADS=4 PYTHONPATH=<build> python tests/python/test_mirror_symmetry.py
26Exit 0 pass, 1 fail, 77 skipped (no module).
27"""
28import sys
29
30import numpy as np
31
32try:
33 import peclet.flow as pf
34except ImportError:
35 print("SKIP: peclet.flow not importable")
36 sys.exit(77)
37
38NX, NY, NZ = 24, 20, 12
39DT, NSTEPS = 0.05, 3
40R = 3.6
41
42
43def mir_c(f):
44 """Mirror of a cell-centred (and x/z-face) field: row j <-> NY-1-j."""
45 return np.asfortranarray(f[:, ::-1, :])
46
47
48def mir_v(v):
49 """Mirror of the y-face field: get_v's index j is the face j - 1/2 (index 0 the low wall face),
50 so the face j maps to NY - j and changes sign."""
51 out = np.zeros_like(v)
52 out[:, 1:, :] = -v[:, :0:-1, :]
53 return np.asfortranarray(out)
54
55
56def sphere(c, r, sub=6):
57 g = (np.arange(sub) + 0.5) / sub
58 frac = np.zeros((NX, NY, NZ))
59 for gx in g:
60 for gy in g:
61 for gz in g:
62 X, Y, Z = np.meshgrid(np.arange(NX) + gx, np.arange(NY) + gy, np.arange(NZ) + gz,
63 indexing="ij")
64 dx = X - c[0]
65 dx -= NX * np.round(dx / NX) # periodic in x: the blob straddles the seam
66 frac += (dx * dx + (Y - c[1]) ** 2 + (Z - c[2]) ** 2) < r * r
67 return np.asfortranarray(frac / sub ** 3)
68
69
70def build(mode, mirror, variable_mu=True, harmonic=False, full=False):
71 cy = 2.0 if mode == "scalar" else 3.0 # scalar: straddles the wall; markers: 0.6 cell inside
72 c = (0.4, NY - cy if mirror else cy, 6.1)
73 s = pf.Solver(NX, NY, NZ)
74 s.set_advection(False)
75 s.set_rho(1.0)
76 s.set_mu(0.05)
77 s.set_domain_bc("-y", "wall", (0, 0, 0))
78 s.set_domain_bc("+y", "wall", (0, 0, 0))
79 s.set_pressure_geometry(np.full((NX, NY, NZ), 10.0, order="F"))
80 if mode == "scalar":
81 s.add_scalar("T", 0.0, "koren")
82 s.set_field("T", sphere(c, R))
83 s.set_property_model("rho", "linear", "T", [1.0, -0.5])
84 if variable_mu:
85 s.set_property_model("mu", "linear", "T", [0.05, -0.04])
86 s.set_property_model("force_x", "linear", "T", [0.0, -0.02])
87 else:
88 s.enable_vof()
89 s.set_vof(sphere(c, R) if mode == "vof" else np.zeros((NX, NY, NZ), order="F"))
90 s.set_property_model("rho", "linear", "C", [1.0, -0.9])
91 s.set_property_model("mu", "linear", "C", [0.05, -0.04])
92 s.set_surface_tension(0.02)
93 if mode == "blocks":
94 s.enable_vof_blocks([(c[0], c[1], c[2], R)])
95 s.enable_vof_block_csf()
96 s.set_property_model("force_x", "linear", "C", [0.0, -0.02])
97 if harmonic:
98 s.diagnostics.set_property_mode("variable", True)
99 # The viscous stress form, explicit both ways: the plain variants keep the Laplacian form they
100 # were written for (the default is AUTO = full since WO-7); the full-stress variants
101 # (doc/full_viscous_stress.md WO-2) must hold the same tolerance.
102 s.set_viscous_stress("full" if full else "laplacian")
103 s.set_pressure_pcg(True, 800, 1e-12)
104 s.set_superficial_velocity(True, "x", 0.0)
105 rng = np.random.default_rng(1)
106 u, v, w = (np.asfortranarray(0.05 * rng.standard_normal((NX, NY, NZ))) for _ in range(3))
107 v[:, 0, :] = 0.0 # the low wall face
108 if mirror:
109 u, v, w = mir_c(u), mir_v(v), mir_c(w)
110 for k, a in enumerate((u, v, w)):
111 s.set_velocity(k, a)
112 return s
113
114
115# The sharp viscous interface's edge-owner ties of run A after the first step (flow
116# doc/vof_sharp_viscous_stress.md ยง5.8, WO-9.1): the blob's y-symmetry plane lies on a grid face,
117# so mirror-image cells tie at its edges. All n_E = 2; the owner-set mean makes the step
118# mirror-equivariant to round-off (single-owner tie-breaks left 3e-5 / 8e-5).
119TIED_EDGES = {"vof": 78, "blocks": 92}
120
121
122def mirror_asymmetry(mode, **kw):
123 A, B = build(mode, False, **kw), build(mode, True, **kw)
124 ties = None
125 for n in range(NSTEPS):
126 for s in (A, B):
127 s.set_dt(DT)
128 s.step()
129 if n == 0 and kw.get("full") and mode in TIED_EDGES:
130 c = A.diagnostics.vof_viscous_interface_census()
131 ties = (c["tied_edges"], c["max_tie_spread"])
132
133 def rel(a, b):
134 return float(np.abs(a - b).max() / np.abs(a).max())
135
136 vel = max(rel(A.get_u(), mir_c(B.get_u())), rel(A.get_v(), mir_v(B.get_v())),
137 rel(A.get_w(), mir_c(B.get_w())))
138 return vel, rel(A.get_p(), mir_c(B.get_p())), ties
139
140
141def steady_varmu_error(N, A=1e-3, nz=4):
142 k = 2.0 * np.pi / N
143 xc = np.arange(N) + 0.5
144 X, Y = np.meshgrid(xc, xc, indexing="ij")
145 mu = 1 + 0.5 * np.sin(k * X + 0.3) * np.cos(k * Y + 0.7)
146 mux = 0.5 * k * np.cos(k * X + 0.3) * np.cos(k * Y + 0.7)
147 muy = -0.5 * k * np.sin(k * X + 0.3) * np.sin(k * Y + 0.7)
148 ux, uy = A * np.sin(k * X) * np.cos(k * Y), -A * np.cos(k * X) * np.sin(k * Y)
149 fx = -(-2 * k * k * mu * ux + A * k * (mux * np.cos(k * X) * np.cos(k * Y)
150 - muy * np.sin(k * X) * np.sin(k * Y)))
151 fy = -(-2 * k * k * mu * uy + A * k * (mux * np.sin(k * X) * np.sin(k * Y)
152 - muy * np.cos(k * X) * np.cos(k * Y)))
153 rep = lambda a: np.asfortranarray(np.repeat(a[:, :, None], nz, axis=2)) # noqa: E731
154 s = pf.Solver(N, N, nz)
155 s.set_rho(1.0)
156 s.set_mu(1.0)
157 s.set_dt(2.0)
158 s.set_advection(False)
159 s.set_pressure_pcg(True, 400, 1e-13)
160 s.diagnostics.set_velocity_solver_params(400, 1e-12, 2)
161 s.set_pressure_geometry(np.asfortranarray(np.full((N, N, nz), 10.0)))
162 s.enable_cell_force()
163 s.diagnostics.set_property_mode("variable", False)
164 # The forcing above is -div(mu grad u): this gate is the placement of the Laplacian bands, so
165 # it pins that form (the default is AUTO = full since WO-7; the full stress's own smooth-mu
166 # order is gated by ctest full_stress_operator, G1(e)).
167 s.set_viscous_stress("laplacian")
168 # plain incremental pressure: its fixed point is the steady Stokes solution exactly (the
169 # rotational correction with a variable mu is not -- see set_variable_rotational)
170 s.diagnostics.set_variable_rotational("off", 1.0)
171 s.set_field("mu", rep(mu))
172 for nm, a in (("force_x", rep(fx)), ("force_y", rep(fy)), ("force_z", rep(0 * fx))):
173 s.set_field(nm, a)
174 s.diagnostics.exchange_field(nm)
175 prev = None
176 for _ in range(20000):
177 s.step()
178 u = np.array(s.get_u())
179 if prev is not None and np.max(np.abs(u - prev)) <= 1e-13 * np.max(np.abs(u)):
180 break
181 prev = u
182 u, v = np.array(s.get_u())[:, :, 0], np.array(s.get_v())[:, :, 0]
183 i = np.arange(N, dtype=np.float64)
184 xu, yc = np.meshgrid(i, i + 0.5, indexing="ij") # u on the -x face: (x_i, y_c)
185 xc2, yv = np.meshgrid(i + 0.5, i, indexing="ij") # v on the -y face: (x_c, y_j)
186 ue = A * np.sin(k * xu) * np.cos(k * yc)
187 ve = -A * np.cos(k * xc2) * np.sin(k * yv)
188 return max(np.abs(u - ue).max(), np.abs(v - ve).max()) / A
189
190
191def main():
192 ok = True
193 cases = [("scalar, constant mu", "scalar", dict(variable_mu=False)),
194 ("scalar, mu(T) arithmetic", "scalar", {}),
195 ("scalar, mu(T) harmonic", "scalar", dict(harmonic=True)),
196 ("structured VoF + CSF", "vof", {}),
197 ("block VoF + block CSF", "blocks", {}),
198 ("scalar, mu(T) full stress", "scalar", {"full": True}),
199 ("structured VoF + CSF, full stress", "vof", {"full": True}),
200 ("block VoF + CSF, full stress", "blocks", {"full": True})]
201 for name, mode, kw in cases:
202 vel, p, ties = mirror_asymmetry(mode, **kw)
203 good = vel <= 1e-12 and p < 1e-8 # p carries the 1e-12 PCG tolerance, not round-off
204 extra = ""
205 if ties is not None: # the sharp rows: the owner ties are pinned (G-SV12)
206 good &= ties[0] == TIED_EDGES[mode] and ties[1] <= 1e-9
207 extra = f" tied edges {ties[0]} (want {TIED_EDGES[mode]}), spread {ties[1]:.1e}"
208 ok &= good
209 print(f"mirror {name:28s} velocity {vel:.2e} pressure {p:.2e}{extra} "
210 f"{'ok' if good else 'FAIL'}")
211 e16, e32 = steady_varmu_error(16), steady_varmu_error(32)
212 order = np.log2(e16 / e32)
213 good = order > 1.8
214 ok &= good
215 print(f"placement variable-mu steady Stokes error N=16 {e16:.3e} N=32 {e32:.3e} "
216 f"order {order:.2f} (> 1.8) {'ok' if good else 'FAIL'}")
217 print("PASS" if ok else "FAIL")
218 return 0 if ok else 1
219
220
221if __name__ == "__main__":
222 sys.exit(main())
steady_varmu_error(N, A=1e-3, nz=4)
build(mode, mirror, variable_mu=True, harmonic=False, full=False)