flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
mac2d.py
Go to the documentation of this file.
1"""A-priori operator test for a sharp viscous stress on a 2-D MAC grid (architect, 2026-10-31).
2
3Steady two-phase Stokes div(2 mu D(u)) - grad p + f = 0, div u = 0 on [0,1]^2 with a planar interface
4phi = n.(x - c) - s (side A: phi < 0). Dirichlet data = exact FACE-AVERAGED velocities on every node outside
5the unknown set (boundary faces and one ghost row). The MAC unknown is the face-averaged velocity, so the
6error is measured against exact face averages. Direct sparse solve: this is the steady state of flow's
7predictor + projection with any lagging of explicit terms.
8
9Schemes (sample stress on cell centres = normal, on nodes = shear):
10 arith : beta_cell = mu(C), beta_node = mean of 4 cells (flow default)
11 harm4 : beta_node = harmonic of 4 cells (register Q4 option)
12 facef : exact PLIC face fraction per row, arithmetic ("sub-cell mu from PLIC")
13 linkh : each link difference divided by its own resistance (GFM / Liu-Fedkiw-Kang)
14 sharp : beta m + sum_l T_l(tau)(1 - beta Rbar_l), tau = interface traction
15 tau: 'oracle' (exact) or 'fit' (kinked LS fit on the low-mu side gradient, 3x3 block)
16"""
17import numpy as np
18import scipy.sparse as sp
19import scipy.sparse.linalg as spla
20
21GL_X, GL_W = np.polynomial.legendre.leggauss(5)
22
23
24def cdf_box(s, h):
25 return np.clip((s + 0.5 * h) / h, 0.0, 1.0)
26
27
28def cdf_hat(s, h):
29 s = np.clip(s, -h, h)
30 return np.where(s <= 0, (s + h) ** 2 / (2 * h * h), 1.0 - (h - s) ** 2 / (2 * h * h))
31
32
33class Case:
34 def __init__(self, N, alpha_deg, off_cells, muA, muB, kind, eps=1.0, tau0=1.0):
35 self.N, self.h = N, 1.0 / N
36 a = np.deg2rad(alpha_deg)
37 self.n = np.array([np.cos(a), np.sin(a)])
38 self.t = np.array([-np.sin(a), np.cos(a)])
39 self.c = np.array([0.5, 0.5])
40 self.s = off_cells * self.h
41 self.muA, self.muB, self.kind, self.eps, self.tau0 = muA, muB, kind, eps, tau0
42
43 def phi(self, x, y):
44 return self.n[0] * (x - self.c[0]) + self.n[1] * (y - self.c[1]) - self.s
45
46 def frac_line(self, x0, y0, e, kern):
47 """side-A fraction of a segment through (x0,y0) along unit e, kernel 'box' (h) or 'hat' (2h)."""
48 p0 = self.phi(x0, y0)
49 g = self.n[0] * e[0] + self.n[1] * e[1]
50 cdf = cdf_box if kern == "box" else cdf_hat
51 if abs(g) < 1e-14:
52 return 1.0 if p0 < 0 else 0.0
53 ss = -p0 / g
54 F = float(cdf(ss, self.h))
55 return F if g > 0 else 1.0 - F
56
57 def frac_cell(self, x0, y0):
58 h = self.h
59 poly = [(x0, y0), (x0 + h, y0), (x0 + h, y0 + h), (x0, y0 + h)]
60 out = []
61 for k in range(4):
62 P, Q = poly[k], poly[(k + 1) % 4]
63 fp, fq = self.phi(*P), self.phi(*Q)
64 if fp < 0:
65 out.append(P)
66 if (fp < 0) != (fq < 0):
67 w = fp / (fp - fq)
68 out.append((P[0] + w * (Q[0] - P[0]), P[1] + w * (Q[1] - P[1])))
69 if len(out) < 3:
70 return 0.0
71 A = 0.0
72 for k in range(len(out)):
73 A += out[k][0] * out[(k + 1) % len(out)][1] - out[(k + 1) % len(out)][0] * out[k][1]
74 return abs(A) / 2 / (h * h)
75
76 # exact solution -------------------------------------------------------------------------------------
77 def vel(self, x, y):
78 xi = self.phi(x, y)
79 eta = self.t[0] * (x - self.c[0]) + self.t[1] * (y - self.c[1])
80 mu = np.where(xi < 0, self.muA, self.muB)
81 U = np.zeros_like(xi)
82 ux = np.zeros_like(xi)
83 uy = np.zeros_like(xi)
84 if self.kind in ("couette",):
85 U = self.tau0 * xi / mu
86 if self.kind in ("poiseuille", "general"):
87 U = (self.tau0 * xi - 0.5 * xi * xi) / mu
88 ux = ux + U * self.t[0]
89 uy = uy + U * self.t[1]
90 if self.kind in ("extension", "general"):
91 ux = ux + self.eps * (xi * self.n[0] - eta * self.t[0])
92 uy = uy + self.eps * (xi * self.n[1] - eta * self.t[1])
93 return ux, uy
94
95 def force(self):
96 if self.kind in ("poiseuille", "general"):
97 return self.t.copy()
98 return np.zeros(2)
99
100 def tau_exact(self):
101 return 0.0 if self.kind == "extension" else self.tau0
102
103 def face_avg(self, comp, x0, y0, e):
104 """average of velocity component over the face segment centred (x0,y0) along e (length h)."""
105 h = self.h
106 p0 = self.phi(x0, y0)
107 g = self.n[0] * e[0] + self.n[1] * e[1]
108 cuts = [-0.5 * h, 0.5 * h]
109 if abs(g) > 1e-14:
110 ss = -p0 / g
111 if -0.5 * h < ss < 0.5 * h:
112 cuts = [-0.5 * h, ss, 0.5 * h]
113 tot = 0.0
114 for k in range(len(cuts) - 1):
115 a, b = cuts[k], cuts[k + 1]
116 sq = 0.5 * (a + b) + 0.5 * (b - a) * GL_X
117 xs, ys = x0 + sq * e[0], y0 + sq * e[1]
118 v = self.vel(xs, ys)[comp]
119 tot += 0.5 * (b - a) * np.dot(GL_W, v)
120 return tot / h
121
122
123class Mac:
124 """index maps; u[i,j]: x=i h, y=(j+1/2)h, i=0..N, j=-1..N; v[i,j]: x=(i+1/2)h, y=j h, i=-1..N, j=0..N."""
125
126 def __init__(self, N):
127 self.N = N
128 self.nu = (N + 1) * (N + 2)
129 self.nv = (N + 2) * (N + 1)
130
131 def iu(self, i, j):
132 return i * (self.N + 2) + (j + 1)
133
134 def iv(self, i, j):
135 return self.nu + (i + 1) * (self.N + 1) + j
136
137 def unknown_u(self, i, j):
138 return 1 <= i <= self.N - 1 and 0 <= j <= self.N - 1
139
140 def unknown_v(self, i, j):
141 return 0 <= i <= self.N - 1 and 1 <= j <= self.N - 1
142
143
144FCORR = None
145OWN_ONLY = None
146DNN_W = "all"
147CELL_VOL = False
148TAU_RULE = "band-avg"
149DNN_EPS = 1e-3
150
151
152def build(case, scheme, tau_mode="fit"):
153 N, h = case.N, case.h
154 m = Mac(N)
155 muA, muB = case.muA, case.muB
156 ex, ey = np.array([1.0, 0.0]), np.array([0.0, 1.0])
157 n, t = case.n, case.t
158 # cell fractions incl. one ring of outside cells (index -1..N)
159 C = np.zeros((N + 2, N + 2))
160 for i in range(-1, N + 1):
161 for j in range(-1, N + 1):
162 x0, y0 = i * h, j * h
163 ph = [case.phi(x0, y0), case.phi(x0 + h, y0), case.phi(x0, y0 + h), case.phi(x0 + h, y0 + h)]
164 if max(ph) < 0:
165 C[i + 1, j + 1] = 1.0
166 elif min(ph) >= 0:
167 C[i + 1, j + 1] = 0.0
168 else:
169 C[i + 1, j + 1] = case.frac_cell(x0, y0)
170 Cc = lambda i, j: C[i + 1, j + 1]
171 mu_of = lambda f: f * muA + (1 - f) * muB
172 R_of = lambda f: f / muA + (1 - f) / muB
173 lowA = muA < muB
174 mulo, muhi = (muA, muB) if lowA else (muB, muA)
175 rr = mulo / muhi
176
177 # links: (name, a, c, nodes(+,-), thetaA) link difference m = (u+ - u-)/h
178 def cell_links(i, j):
179 f = Cc(i, j)
180 return [("xx", 0, 0, (m.iu(i + 1, j), m.iu(i, j)), f), ("yy", 1, 1, (m.iv(i, j + 1), m.iv(i, j)), f)]
181
182 def node_links(i, j):
183 thy = case.frac_line(i * h, j * h, ey, "hat")
184 thx = case.frac_line(i * h, j * h, ex, "hat")
185 return [("yu", 1, 0, (m.iu(i, j), m.iu(i, j - 1)), thy), ("xv", 0, 1, (m.iv(i, j), m.iv(i - 1, j)), thx)]
186
187 # tau fit per band cell ----------------------------------------------------------------------------------
188 mixed = np.zeros((N + 2, N + 2), bool)
189 for i in range(-1, N + 1):
190 for j in range(-1, N + 1):
191 mixed[i + 1, j + 1] = 0.0 < Cc(i, j) < 1.0
192 band = mixed.copy()
193 for di in (-1, 0, 1):
194 for dj in (-1, 0, 1):
195 band[1:-1, 1:-1] |= mixed[1 + di:N + 1 + di, 1 + dj:N + 1 + dj]
196 tauexpr = {}
197 dnnexpr = {}
198
199 def tau_fit(i, j):
200 """tau_hat = mu_lo t.S_lo n with L_lo from an LS fit of all links in the 3x3 block (kinked model)."""
201 if (i, j) in tauexpr:
202 return tauexpr[(i, j)]
203 rows, rhs = [], []
204 for di in (-1, 0, 1):
205 for dj in (-1, 0, 1):
206 ci, cj = i + di, j + dj
207 if not (0 <= ci <= N - 1 and 0 <= cj <= N - 1):
208 continue
209 for L in cell_links(ci, cj):
210 rows.append(L); rhs.append(None)
211 for ni in range(i - 1, i + 3):
212 for nj in range(j - 1, j + 3):
213 if not (0 <= ni <= N and 0 <= nj <= N):
214 continue
215 for L in node_links(ni, nj):
216 rows.append(L); rhs.append(None)
217 A = np.zeros((len(rows), 4))
218 for r, (_, a, c, _, thA) in enumerate(rows):
219 thlo = thA if lowA else 1 - thA
220 A[r, 2 * a + c] += 1.0
221 # (1-thlo) n_a t_c (rr-1) (t.S n), t.S n = sum_pq (t_p n_q + t_q n_p) L_pq
222 k = (1 - thlo) * n[a] * t[c] * (rr - 1)
223 for p in range(2):
224 for q in range(2):
225 A[r, 2 * p + q] += k * (t[p] * n[q] + t[q] * n[p])
226 G = np.linalg.pinv(A) # 4 x nl
227 wv = np.array([[t[p] * n[q] + t[q] * n[p] for q in range(2)] for p in range(2)]).ravel()
228 coef = mulo * (wv @ G) # tau = coef . m
229 nn = np.array([[n[p] * n[q] for q in range(2)] for p in range(2)]).ravel()
230 if DNN_W == "hi": # weight each link by its high-mu content: D_nn from the stiff side
231 wl = np.array([(1 - thA) if lowA else thA for (_, _, _, _, thA) in rows]) + DNN_EPS
232 cdn = nn @ (np.linalg.pinv(A * wl[:, None]) * wl[None, :])
233 else:
234 cdn = nn @ G # D_nn = n.L n (continuous)
235 expr, dexpr = {}, {}
236 for r, (_, a, c, (ip, im), _) in enumerate(rows):
237 expr[ip] = expr.get(ip, 0.0) + coef[r] / h
238 expr[im] = expr.get(im, 0.0) - coef[r] / h
239 dexpr[ip] = dexpr.get(ip, 0.0) + cdn[r] / h
240 dexpr[im] = dexpr.get(im, 0.0) - cdn[r] / h
241 tauexpr[(i, j)] = expr
242 dnnexpr[(i, j)] = dexpr
243 return expr
244
245 def tau_at(cells):
246 if TAU_RULE == "owner":
247 cand = [(ci, cj) for (ci, cj) in cells if 0 <= ci <= N - 1 and 0 <= cj <= N - 1 and mixed[ci + 1, cj + 1]]
248 if not cand:
249 cand = [(ci, cj) for (ci, cj) in cells if 0 <= ci <= N - 1 and 0 <= cj <= N - 1]
250 own = min(cand, key=lambda q: (abs(case.phi((q[0] + 0.5) * h, (q[1] + 0.5) * h)), q))
251 return tau_fit(*own)
252 if TAU_RULE == "mixed-avg": # note section 5.7 Q-A: mean over the interfacial cells among the four
253 cs = [(ci, cj) for (ci, cj) in cells if 0 <= ci <= N - 1 and 0 <= cj <= N - 1 and mixed[ci + 1, cj + 1]]
254 if cs:
255 e = {}
256 for cc in cs:
257 for k, v in tau_fit(*cc).items():
258 e[k] = e.get(k, 0.0) + v / len(cs)
259 return e
260 cs = [(ci, cj) for (ci, cj) in cells if 0 <= ci <= N - 1 and 0 <= cj <= N - 1 and band[ci + 1, cj + 1]]
261 if not cs:
262 cs = [(ci, cj) for (ci, cj) in cells if 0 <= ci <= N - 1 and 0 <= cj <= N - 1]
263 e = {}
264 for cc in cs:
265 for k, v in tau_fit(*cc).items():
266 e[k] = e.get(k, 0.0) + v / len(cs)
267 return e
268
269 # sample stresses ---------------------------------------------------------------------------------------
270 def stress(links, beta, factor, cells_adj):
271 """sigma = factor*[ beta*sum m + sum_l T_l (1 - beta Rbar_l) ] as (dict, const)."""
272 e, const = {}, 0.0
273 for (nm, a, c, (ip, im), thA) in links:
274 if OWN_ONLY is not None and nm not in OWN_ONLY:
275 continue
276 e[ip] = e.get(ip, 0.0) + factor * beta / h
277 e[im] = e.get(im, 0.0) - factor * beta / h
278 if scheme == "sharp":
279 for (_, a, c, (ip, im), thA) in links:
280 k = factor * n[a] * t[c] * (1.0 - beta * R_of(thA))
281 if abs(k) < 1e-300 or thA in (0.0, 1.0) and abs(1.0 - beta * R_of(thA)) < 1e-12:
282 continue
283 if tau_mode == "oracle":
284 const += k * case.tau_exact()
285 else:
286 for kk, v in tau_at(cells_adj).items():
287 e[kk] = e.get(kk, 0.0) + k * v
288 return e, const
289
290 def stress_linkh(links, factor):
291 e = {}
292 for (_, a, c, (ip, im), thA) in links:
293 b = 1.0 / R_of(thA)
294 e[ip] = e.get(ip, 0.0) + factor * b / h
295 e[im] = e.get(im, 0.0) - factor * b / h
296 return e, 0.0
297
298 def side_mu(x, y):
299 return muA if case.phi(x, y) < 0 else muB
300
301 def beta_cell(i, j, row, side=None):
302 if side is not None:
303 return side
304 if CELL_VOL:
305 return mu_of(Cc(i, j))
306 if scheme == "facef" or (scheme == "sharp" and SHARP_BASE == "facef"):
307 xc, yc = (i + 0.5) * h, (j + 0.5) * h
308 return mu_of(case.frac_line(xc, yc, ey if row == "u" else ex, "box"))
309 return mu_of(Cc(i, j))
310
311 def beta_node(i, j, row, side=None):
312 if side is not None:
313 return side
314 cells = [Cc(i - 1, j - 1), Cc(i, j - 1), Cc(i - 1, j), Cc(i, j)]
315 mus = [mu_of(f) for f in cells]
316 if scheme == "harm4":
317 return 4.0 / sum(1.0 / x for x in mus)
318 if scheme == "facef" or (scheme == "sharp" and SHARP_BASE == "facef"):
319 return mu_of(case.frac_line(i * h, j * h, ex if row == "u" else ey, "box"))
320 return 0.25 * sum(mus)
321
322 cache = {}
323 GFM = scheme == "sharp" and SHARP_BASE == "gfm"
324
325 def sig_cell(i, j, comp, side=None):
326 key = ("c", i, j, comp, side)
327 if key not in cache:
328 L = cell_links(i, j)[comp]
329 if scheme == "linkh":
330 cache[key] = stress_linkh([L], 2.0)
331 else:
332 cache[key] = stress([L], beta_cell(i, j, "u" if comp == 0 else "v", side), 2.0, [(i, j)])
333 return cache[key]
334
335 def sig_node(i, j, row, side=None):
336 key = ("n", i, j, row, side)
337 if key not in cache:
338 L = node_links(i, j)
339 if OWN_ONLY is not None:
340 L = [x for x in L if x[0] == ("yu" if row == "u" else "xv")]
341 if scheme == "linkh":
342 cache[key] = stress_linkh(L, 1.0)
343 else:
344 cache[key] = stress(L, beta_node(i, j, row, side), 1.0, [(i - 1, j - 1), (i, j - 1), (i - 1, j), (i, j)])
345 return cache[key]
346
347 # assemble -----------------------------------------------------------------------------------------------
348 uidx = {}
349 for i in range(N + 1):
350 for j in range(-1, N + 1):
351 if m.unknown_u(i, j):
352 uidx[m.iu(i, j)] = len(uidx)
353 for i in range(-1, N + 1):
354 for j in range(N + 1):
355 if m.unknown_v(i, j):
356 uidx[m.iv(i, j)] = len(uidx)
357 nvel = len(uidx)
358 npr = N * N
359 ntot = nvel + npr + 1
360 pid = lambda i, j: nvel + i * N + j
361 # exact face averages for all nodes
362 xall = np.zeros(m.nu + m.nv)
363 for i in range(N + 1):
364 for j in range(-1, N + 1):
365 xall[m.iu(i, j)] = case.face_avg(0, i * h, (j + 0.5) * h, ey)
366 for i in range(-1, N + 1):
367 for j in range(N + 1):
368 xall[m.iv(i, j)] = case.face_avg(1, (i + 0.5) * h, j * h, ex)
369 f = case.force()
370 R, Cl, V = [], [], []
371
372 def add_J(row, ci, cj, w):
373 """row += w * J(cell), J = 2 (muB - muA) D_nn."""
374 if FCORR == "oracle":
375 dnn = case.eps if case.kind in ("extension", "general") else 0.0
376 b[row] -= w * 2 * (muB - muA) * dnn
377 else:
378 tau_fit(ci, cj)
379 add(row, {k: w * 2 * (muB - muA) * v for k, v in dnnexpr[(ci, cj)].items()}, 0.0, 1.0)
380 b = np.zeros(ntot)
381
382 def add(row, expr, const, sgn):
383 nonlocal b
384 for k, v in expr.items():
385 if k in uidx:
386 R.append(row); Cl.append(uidx[k]); V.append(sgn * v)
387 else:
388 b[row] -= sgn * v * xall[k]
389 b[row] -= sgn * const
390
391 for i in range(N + 1):
392 for j in range(N):
393 if not m.unknown_u(i, j):
394 continue
395 r = uidx[m.iu(i, j)]
396 sd = side_mu(i * h, (j + 0.5) * h) if GFM else None
397 e, c0 = sig_cell(i, j, 0, sd); add(r, e, c0, 1.0 / h)
398 e, c0 = sig_cell(i - 1, j, 0, sd); add(r, e, c0, -1.0 / h)
399 e, c0 = sig_node(i, j + 1, "u", sd); add(r, e, c0, 1.0 / h)
400 e, c0 = sig_node(i, j, "u", sd); add(r, e, c0, -1.0 / h)
401 R += [r, r]; Cl += [pid(i, j), pid(i - 1, j)]; V += [-1.0 / h, 1.0 / h]
402 b[r] -= f[0]
403 if FCORR:
404 for (ci, sg) in ((i, 1.0), (i - 1, -1.0)):
405 xc, yc = (ci + 0.5) * h, (j + 0.5) * h
406 dq = case.frac_line(xc, yc, ey, "box") - Cc(ci, j)
407 if abs(dq) > 1e-15:
408 add_J(r, ci, j, sg * dq / h)
409 for i in range(N):
410 for j in range(N + 1):
411 if not m.unknown_v(i, j):
412 continue
413 r = uidx[m.iv(i, j)]
414 sd = side_mu((i + 0.5) * h, j * h) if GFM else None
415 e, c0 = sig_node(i + 1, j, "v", sd); add(r, e, c0, 1.0 / h)
416 e, c0 = sig_node(i, j, "v", sd); add(r, e, c0, -1.0 / h)
417 e, c0 = sig_cell(i, j, 1, sd); add(r, e, c0, 1.0 / h)
418 e, c0 = sig_cell(i, j - 1, 1, sd); add(r, e, c0, -1.0 / h)
419 R += [r, r]; Cl += [pid(i, j), pid(i, j - 1)]; V += [-1.0 / h, 1.0 / h]
420 b[r] -= f[1]
421 if FCORR:
422 for (cj, sg) in ((j, 1.0), (j - 1, -1.0)):
423 xc, yc = (i + 0.5) * h, (cj + 0.5) * h
424 dq = case.frac_line(xc, yc, ex, "box") - Cc(i, cj)
425 if abs(dq) > 1e-15:
426 add_J(r, i, cj, sg * dq / h)
427 for i in range(N):
428 for j in range(N):
429 r = pid(i, j)
430 div = {m.iu(i + 1, j): 1.0 / h, m.iu(i, j): -1.0 / h, m.iv(i, j + 1): 1.0 / h, m.iv(i, j): -1.0 / h}
431 add(r, div, 0.0, 1.0)
432 R.append(r); Cl.append(ntot - 1); V.append(1.0)
433 R.append(ntot - 1); Cl.append(r); V.append(1.0)
434 A = sp.csr_matrix((V, (R, Cl)), shape=(ntot, ntot))
435 # The fit internals of this build, for the WO-2 reference dump (wo2_reference.py); no effect on A, b.
436 build.last = dict(C=C, mixed=mixed, tauexpr=tauexpr, dnnexpr=dnnexpr, xall=xall, mac=m)
437 return A, b, uidx, xall, m
438
439
440SHARP_BASE = "arith"
441
442
443def solve_err(case, scheme, tau_mode="fit"):
444 A, b, uidx, xall, m = build(case, scheme, tau_mode)
445 x = spla.spsolve(A.tocsc(), b)
446 ex = np.array([xall[k] for k in uidx])
447 uh = x[: len(uidx)]
448 err = np.abs(uh - ex)
449 scale = np.max(np.abs(ex))
450 return err.max() / scale, err.mean() / scale
force(self)
Definition mac2d.py:95
frac_line(self, x0, y0, e, kern)
Definition mac2d.py:46
float h
Definition mac2d.py:35
face_avg(self, comp, x0, y0, e)
Definition mac2d.py:103
phi(self, x, y)
Definition mac2d.py:43
tau_exact(self)
Definition mac2d.py:100
float s
Definition mac2d.py:40
frac_cell(self, x0, y0)
Definition mac2d.py:57
__init__(self, N, alpha_deg, off_cells, muA, muB, kind, eps=1.0, tau0=1.0)
Definition mac2d.py:34
str kind
Definition mac2d.py:41
vel(self, x, y)
Definition mac2d.py:77
unknown_v(self, i, j)
Definition mac2d.py:140
tuple nu
Definition mac2d.py:128
iv(self, i, j)
Definition mac2d.py:134
tuple nv
Definition mac2d.py:129
unknown_u(self, i, j)
Definition mac2d.py:137
iu(self, i, j)
Definition mac2d.py:131
__init__(self, N)
Definition mac2d.py:126
solve_err(case, scheme, tau_mode="fit")
Definition mac2d.py:443
cdf_box(s, h)
Definition mac2d.py:24
build(case, scheme, tau_mode="fit")
Definition mac2d.py:152
cdf_hat(s, h)
Definition mac2d.py:28