flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
mac_velocity_mg.hpp
Go to the documentation of this file.
1
18#ifndef PECLET_FLOW_MAC_VELOCITY_MG_HPP
19#define PECLET_FLOW_MAC_VELOCITY_MG_HPP
20
21#include <functional>
22#include <Kokkos_Core.hpp>
23#include <string>
24#include <vector>
25
26#include "mac_cheb_momentum.hpp" // ibmStencilJacobiBounds, ibmChebUpdate, ChebCoeffs
27#include "mac_cutcell_mg.hpp" // restrictAvg, prolongAdd, FPV/FPC
28#include "mac_ibm.hpp" // ibmRbgsStencilColor (pin smoother), MConst
29#include "policy.hpp"
30#include "staggered_advection.hpp" // fou_operator_aniso (upwind-convective coarse op)
31
32namespace peclet::flow {
33
34// pin-aware variable-coefficient residual (mg_residual_var_k): r = 0 at pinned (classified-solid)
35// cells, else b - A x with the float operator accumulated in double.
36inline void residualVarPin(CCField r, CCConst x, CCConst b, FPC AC, FPC AW, FPC AE, FPC AS, FPC AN,
37 FPC AB, FPC AT, CCConst pin, C3 e, int g) {
38 const bool hasPin = (pin.extent(0) != 0);
39 ccFor3( // rule H (doc/vof_step_performance_design.md §4.5): host pencil, device MDRange
40 "peclet::flow::vmg_resid", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
41 KOKKOS_LAMBDA(int lx, int ly, int lz) {
42 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
43 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
44 if (hasPin && pin(i) > 0.5) {
45 r(i) = 0.0;
46 return;
47 }
48 const double Ax = (double)AC(i) * x(i) + (double)AE(i) * x(i + sx) +
49 (double)AW(i) * x(i - sx) + (double)AN(i) * x(i + sy) +
50 (double)AS(i) * x(i - sy) + (double)AT(i) * x(i + sz) +
51 (double)AB(i) * x(i - sz);
52 r(i) = b(i) - Ax;
53 });
54}
55
56// F-1 (doc/vof_projection_cost_design.md §7, applied where the stop residual actually lives:
57// Solver::velSweepLoop's stencil functor): max|r| and max|b - r| over the inner cells with
58// residualVarPin's VERBATIM cell body, r taken as 0 on the held normal-Dirichlet plane (index
59// `holdIdx` along `holdAxis`, exactly the inner cells zeroPlane zeroes; holdAxis < 0 = none). No
60// write of r. Max is order-free: bitwise to residualVarPin + zeroPlane + maxAbsDiffInner(b, r) +
61// maxAbsInner(r) on every backend; `bmax` = max|b| (maxAbsInner(b), the stop scale's |b|).
62inline void residualVarPinMax(CCConst x, CCConst b, FPC AC, FPC AW, FPC AE, FPC AS, FPC AN, FPC AB,
63 FPC AT, CCConst pin, C3 e, int g, int holdAxis, int holdIdx,
64 double& rmax, double& bdmax, double& bmax) {
65 const bool hasPin = (pin.extent(0) != 0);
67 "peclet::flow::vmg_resid_max", C3{g, g, g}, C3{e.x - g, e.y - g, e.z - g},
68 KOKKOS_LAMBDA(int lx, int ly, int lz, double& m, double& d, double& bm) {
69 const long sx = 1, sy = e.x, sz = (long)e.x * e.y;
70 const long i = (long)lx + (long)ly * sy + (long)lz * sz;
71 double r;
72 if (hasPin && pin(i) > 0.5) {
73 r = 0.0;
74 } else {
75 const double Ax = (double)AC(i) * x(i) + (double)AE(i) * x(i + sx) +
76 (double)AW(i) * x(i - sx) + (double)AN(i) * x(i + sy) +
77 (double)AS(i) * x(i - sy) + (double)AT(i) * x(i + sz) +
78 (double)AB(i) * x(i - sz);
79 r = b(i) - Ax;
80 }
81 if (holdAxis >= 0 && (holdAxis == 0 ? lx : (holdAxis == 1 ? ly : lz)) == holdIdx)
82 r = 0.0;
83 const double ar = Kokkos::fabs(r);
84 if (ar > m)
85 m = ar;
86 const double ad = Kokkos::fabs(b(i) - r);
87 if (ad > d)
88 d = ad;
89 const double ab = Kokkos::fabs(b(i));
90 if (ab > bm)
91 bm = ab;
92 },
93 Kokkos::Max<double>(rmax), Kokkos::Max<double>(bdmax), Kokkos::Max<double>(bmax));
94}
95
96// masked trilinear prolongation (mg_prolong_masked_k): like prolongAdd but does NOT add the coarse
97// correction into a fine cell whose mask < eps (the clean-fluid exclude mask is 0 at IBM cut+solid
98// cells).
99inline void prolongMasked(CCField fine, CCConst coarse, CCConst mask, C3 fext, C3 cext, int g,
100 C3 finner, C3 ratio, double eps) {
101 CCExec space;
102 using MD = MDRange3<CCExec>;
103 Kokkos::parallel_for(
104 "peclet::flow::vmg_prolong_masked", MD(space, {0, 0, 0}, {finner.x, finner.y, finner.z}),
105 KOKKOS_LAMBDA(int ifx, int ify, int ifz) {
106 const long fi =
107 (long)(ifx + g) + (long)(ify + g) * fext.x + (long)(ifz + g) * (long)fext.x * fext.y;
108 if (mask(fi) < eps)
109 return; // no correction into a cut/solid fine cell
110 const double cx = (ratio.x == 2) ? 0.5 * ifx - 0.25 + g : ifx + g;
111 const double cy = (ratio.y == 2) ? 0.5 * ify - 0.25 + g : ify + g;
112 const double cz = (ratio.z == 2) ? 0.5 * ifz - 0.25 + g : ifz + g;
113 const double fxw = Kokkos::floor(cx), fyw = Kokkos::floor(cy), fzw = Kokkos::floor(cz);
114 const double wx = cx - fxw, wy = cy - fyw, wz = cz - fzw;
115 const int x0 = (int)fxw, y0 = (int)fyw, z0 = (int)fzw;
116 const long sy = cext.x, sz = (long)cext.x * cext.y;
117 auto C = [&](int xx, int yy, int zz) {
118 return coarse((long)xx + (long)yy * sy + (long)zz * sz);
119 };
120 const double c00 = C(x0, y0, z0) * (1 - wx) + C(x0 + 1, y0, z0) * wx;
121 const double c10 = C(x0, y0 + 1, z0) * (1 - wx) + C(x0 + 1, y0 + 1, z0) * wx;
122 const double c01 = C(x0, y0, z0 + 1) * (1 - wx) + C(x0 + 1, y0, z0 + 1) * wx;
123 const double c11 = C(x0, y0 + 1, z0 + 1) * (1 - wx) + C(x0 + 1, y0 + 1, z0 + 1) * wx;
124 const double c0 = c00 * (1 - wy) + c10 * wy, c1 = c01 * (1 - wy) + c11 * wy;
125 fine(fi) += c0 * (1 - wz) + c1 * wz;
126 });
127}
128
129// STAIRCASE coarse operator (mg_build_velocity_op_staircase_k): theta<thresh -> identity (pinned)
130// row; else a plain const-coeff Helmholtz (idiag + 2*(bx+by+bz) diagonal, per-axis -b
131// off-diagonals).
132inline void buildVelocityStaircase(FPV AC, FPV AW, FPV AE, FPV AS, FPV AN, FPV AB, FPV AT,
133 CCConst theta, C3 e, int g, double bx, double by, double bz,
134 double thresh, double idiag) {
135 CCExec space;
136 using MD = MDRange3<CCExec>;
137 Kokkos::parallel_for(
138 "peclet::flow::vmg_staircase", MD(space, {g, g, g}, {e.x - g, e.y - g, e.z - g}),
139 KOKKOS_LAMBDA(int lx, int ly, int lz) {
140 const long i = (long)lx + (long)ly * e.x + (long)lz * (long)e.x * e.y;
141 if (theta(i) <
142 thresh) { // classified solid -> identity row (smoother/residual pin it to 0)
143 AC(i) = (MReal)1.0;
144 AW(i) = AE(i) = AS(i) = AN(i) = AB(i) = AT(i) = (MReal)0.0;
145 return;
146 }
147 AC(i) = (MReal)(idiag + 2.0 * (bx + by + bz));
148 AW(i) = (MReal)(-bx);
149 AE(i) = (MReal)(-bx);
150 AS(i) = (MReal)(-by);
151 AN(i) = (MReal)(-by);
152 AB(i) = (MReal)(-bz);
153 AT(i) = (MReal)(-bz);
154 });
155}
156
157// classified-solid rows (theta < thresh) -> identity, over the inner cells (the staircase pin
158// applied after an operator builder that wrote every row).
159inline void pinSolidRows(FPV AC, FPV AW, FPV AE, FPV AS, FPV AN, FPV AB, FPV AT, CCConst theta,
160 C3 e, int g, double thresh) {
161 CCExec space;
162 using MD = MDRange3<CCExec>;
163 Kokkos::parallel_for(
164 "peclet::flow::vmg_pin_rows", MD(space, {g, g, g}, {e.x - g, e.y - g, e.z - g}),
165 KOKKOS_LAMBDA(int lx, int ly, int lz) {
166 const long i = (long)lx + (long)ly * e.x + (long)lz * (long)e.x * e.y;
167 if (theta(i) < thresh) {
168 AC(i) = (MReal)1.0;
169 AW(i) = AE(i) = AS(i) = AN(i) = AB(i) = AT(i) = (MReal)0.0;
170 }
171 });
172}
173
174// UPWIND-CONVECTIVE coarse operator (build_adv_coarse_stencil_k): anisotropic const-coeff
175// backward-Euler diffusion (per-axis beta bx/by/bz) PLUS first-order-upwind advection from the
176// restricted coarse advecting velocity (scaled by s_a=1/cfac_a per face axis). M-matrix on every
177// level -> stable in the advection- dominated rows. The fine residual + smoother give the exact
178// sharp-IBM answer; this only sets the rate.
179inline void buildAdvCoarse(FPV AC, FPV AW, FPV AE, FPV AS, FPV AN, FPV AB, FPV AT, CCConst U,
180 CCConst V, CCConst W, int comp, C3 e, int g, double bx, double by,
181 double bz, double fouw, double sx, double sy, double sz, double idiag) {
182 CCExec space;
183 using MD = MDRange3<CCExec>;
184 Kokkos::parallel_for(
185 "peclet::flow::vmg_adv_coarse", MD(space, {g, g, g}, {e.x - g, e.y - g, e.z - g}),
186 KOKKOS_LAMBDA(int x, int y, int z) {
187 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
188 double cC = idiag + 2.0 * (bx + by + bz), cxm = -bx, cxp = -bx, cym = -by, cyp = -by,
189 czm = -bz, czp = -bz;
190 sadv::ViewAcc Ua{U, e.x, e.y}, Va{V, e.x, e.y}, Wa{W, e.x, e.y};
191 sadv::fou_operator_aniso(comp, x, y, z, Ua, Va, Wa, fouw, sx, sy, sz, cC, cxm, cxp, cym,
192 cyp, czm, czp);
193 AC(i) = (MReal)cC;
194 AW(i) = (MReal)cxm;
195 AE(i) = (MReal)cxp;
196 AS(i) = (MReal)cym;
197 AN(i) = (MReal)cyp;
198 AB(i) = (MReal)czm;
199 AT(i) = (MReal)czp;
200 });
201}
202
203// CONST-COEFF anisotropic Helmholtz A = idiag*I - nu_dt*Lap (mg_const_diffusion_op_aniso_k), over
204// the WHOLE extended block (the domain-BC velocity op; coarse spacing via per-axis beta). For
205// cavity/BFS where the fine op is also const-coeff (no IBM stencil).
206inline void buildConstAniso(FPV AC, FPV AW, FPV AE, FPV AS, FPV AN, FPV AB, FPV AT, C3 e, double bx,
207 double by, double bz, double idiag) {
208 CCExec space;
209 const std::size_t n = (std::size_t)e.x * e.y * e.z;
210 const MReal c = (MReal)(idiag + 2.0 * (bx + by + bz)), nx = (MReal)(-bx), ny = (MReal)(-by),
211 nz = (MReal)(-bz);
212 Kokkos::parallel_for(
213 "peclet::flow::vmg_const_aniso", Kokkos::RangePolicy<CCExec>(space, 0, n),
214 KOKKOS_LAMBDA(std::size_t i) {
215 AC(i) = c;
216 AW(i) = nx;
217 AE(i) = nx;
218 AS(i) = ny;
219 AN(i) = ny;
220 AB(i) = nz;
221 AT(i) = nz;
222 });
223}
224
225// No-slip face-fold for the const-coeff MG operator (mg_diffusion_bc_fold_k): at a Dirichlet wall
226// the tangential ghost is 2*u_wall - u_inner -> +beta moves onto the boundary-adjacent inner cell's
227// diagonal (AC += beta); the dropped off-diagonal multiplies a held-0 ghost. Over the perp plane of
228// face (a,s).
229inline void boundaryFold(FPV AC, C3 e, int g, int a, int s, double beta) {
230 CCExec space;
231 int dims[3] = {e.x, e.y, e.z};
232 long st[3] = {1, e.x, (long)e.x * e.y};
233 const int b = (a + 1) % 3, c = (a + 2) % 3;
234 const long sa = st[a], sb = st[b], sc = st[c];
235 const int bic = (s == 0) ? g : (dims[a] - g - 1); // boundary-adjacent inner cell along a
236 Kokkos::parallel_for(
237 "peclet::flow::vmg_bc_fold", MDRange2<CCExec>(space, {0, 0}, {dims[b], dims[c]}),
238 KOKKOS_LAMBDA(int p0, int p1) {
239 const long i = (long)p0 * sb + (long)p1 * sc + (long)bic * sa;
240 AC(i) = (MReal)((double)AC(i) + beta);
241 });
242}
243
244// Fill a non-periodic boundary ghost of a coarse correction before trilinear prolongation
245// (mg_fill_bc_ghost_k): Dirichlet (outflow) -> ghost 0; Neumann (wall/inflow) -> ghost = nearest
246// inner (zero-gradient). Plane (a,s).
247inline void fillBcGhost(CCField x, C3 e, int g, int a, int s, int dirichlet) {
248 CCExec space;
249 int dims[3] = {e.x, e.y, e.z};
250 long st[3] = {1, e.x, (long)e.x * e.y};
251 const int b = (a + 1) % 3, c = (a + 2) % 3;
252 const long sa = st[a], sb = st[b], sc = st[c];
253 const int na = dims[a];
254 Kokkos::parallel_for(
255 "peclet::flow::vmg_fill_bc_ghost", MDRange2<CCExec>(space, {0, 0}, {dims[b], dims[c]}),
256 KOKKOS_LAMBDA(int p0, int p1) {
257 const long base = (long)p0 * sb + (long)p1 * sc;
258 if (s == 0) {
259 const double v = dirichlet ? 0.0 : x(base + (long)g * sa);
260 for (int ia = 0; ia < g; ++ia)
261 x(base + (long)ia * sa) = v;
262 } else {
263 const double v = dirichlet ? 0.0 : x(base + (long)(na - g - 1) * sa);
264 for (int ia = na - g; ia < na; ++ia)
265 x(base + (long)ia * sa) = v;
266 }
267 });
268}
269
270// zero a field on the plane at index `idx` along `axis` (held-Dirichlet boundary-face residual
271// exclude).
272inline void zeroPlane(CCField m, C3 e, int axis, int idx) {
273 CCExec space;
274 int dims[3] = {e.x, e.y, e.z};
275 long st[3] = {1, e.x, (long)e.x * e.y};
276 const int b = (axis + 1) % 3, c = (axis + 2) % 3;
277 const long sa = st[axis], sb = st[b], sc = st[c];
278 Kokkos::parallel_for(
279 "peclet::flow::vmg_zero_plane", MDRange2<CCExec>(space, {0, 0}, {dims[b], dims[c]}),
280 KOKKOS_LAMBDA(int p0, int p1) { m((long)p0 * sb + (long)p1 * sc + (long)idx * sa) = 0.0; });
281}
282
283inline void thresholdMask(CCField m, CCConst theta,
284 double thresh) { // m = 1 where theta < thresh (solid)
285 CCExec space;
286 std::size_t n = m.extent(0);
287 CCField mm = m;
288 CCConst th = theta;
289 Kokkos::parallel_for(
290 "peclet::flow::vmg_threshold", Kokkos::RangePolicy<CCExec>(space, 0, n),
291 KOKKOS_LAMBDA(std::size_t i) { mm(i) = (th(i) < thresh) ? 1.0 : 0.0; });
292}
293// max |a| over the inner cells of a G-ghosted block.
294inline double maxAbsInner(CCConst a, C3 e, int g) {
295 CCExec space;
296 using MD = MDRange3<CCExec>;
297 double m = 0.0;
298 Kokkos::parallel_reduce(
299 "peclet::flow::vmg_maxabs", MD(space, {g, g, g}, {e.x - g, e.y - g, e.z - g}),
300 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
301 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
302 const double d = Kokkos::fabs(a(i));
303 if (d > acc)
304 acc = d;
305 },
306 Kokkos::Max<double>(m));
307 return m;
308}
309// max |a - b| over the inner cells of a G-ghosted block (the V-cycle update norm).
310inline double maxAbsDiffInner(CCConst a, CCConst b, C3 e, int g) {
311 CCExec space;
312 using MD = MDRange3<CCExec>;
313 double m = 0.0;
314 Kokkos::parallel_reduce(
315 "peclet::flow::vmg_maxabsdiff", MD(space, {g, g, g}, {e.x - g, e.y - g, e.z - g}),
316 KOKKOS_LAMBDA(int x, int y, int z, double& acc) {
317 const long i = (long)x + (long)y * e.x + (long)z * (long)e.x * e.y;
318 const double d = Kokkos::fabs(a(i) - b(i));
319 if (d > acc)
320 acc = d;
321 },
322 Kokkos::Max<double>(m));
323 return m;
324}
325inline void mulMask(CCField r, CCConst m) { // r *= m (clean-fluid residual filter)
326 CCExec space;
327 std::size_t n = r.extent(0);
328 CCField rr = r;
329 CCConst mm = m;
330 Kokkos::parallel_for(
331 "peclet::flow::vmg_mulmask", Kokkos::RangePolicy<CCExec>(space, 0, n),
332 KOKKOS_LAMBDA(std::size_t i) { rr(i) *= mm(i); });
333}
334
335// Velocity (momentum) geometric multigrid with the staircase coarse operator. All levels ghost
336// width G=2.
338 public:
339 static constexpr int G = 2;
340#ifdef PECLET_FLOW_MPI
341 using Comm = MPI_Comm;
342 static MPI_Comm nullComm() { return MPI_COMM_NULL; }
343#else
344 using Comm = void*; // non-MPI build: solve()'s communicator argument is inert
345 static void* nullComm() { return nullptr; }
346#endif
347 struct Level {
348 C3 ext, inner, ratio{2, 2, 2}, cfac{1, 1, 1};
349 C3 og{0, 0, 0}; // block inner origin (global red-black parity); {0,0,0} single-rank
350 C3 gdim{0, 0, 0}; // GLOBAL dims of this level (og + inner == gdim -> owns the +face)
351 std::size_t n = 0;
353 CCField cd; // Chebyshev search direction (chebSmooth_; allocated on first use)
354 double chebHi = -1.0; // Gershgorin lambda_max of diag(AC)^-1 A, GLOBAL; set per solve()
355 CCField advU, advV, advW; // restricted advecting velocity (upwind-convective coarse op; L>=1)
356 FPV AC, AW, AE, AS, AN, AB, AT;
357#ifdef PECLET_FLOW_MPI
358 std::shared_ptr<GridHaloTopology<3>> halo; // per-level topology (decomposed)
359 std::shared_ptr<GridHalo<double>> dev; // per-level ghost exchange (ghost width G=2)
360#endif
361 };
362
369 void setMetric(const double w[3], const double hp[3]) {
370 for (int a = 0; a < 3; ++a) {
371 w_[a] = w[a];
372 hp_[a] = hp[a];
373 }
374 aniso_ = !(hp_[0] == 1.0 && hp_[1] == 1.0 && hp_[2] == 1.0);
375 }
376
378 std::vector<C3> levelRatios() const {
379 std::vector<C3> r;
380 r.reserve(lv_.size());
381 for (const auto& v : lv_)
382 r.push_back(v.ratio);
383 return r;
384 }
385
386 // periodic uniform hierarchy (halve each axis while even and >=2, capped at nLevels).
387 void init(int nx, int ny, int nz, int nLevels) {
388 lv_.clear();
389 C3 inner{nx, ny, nz}, cf{1, 1, 1};
390 for (int L = 0; L < nLevels; ++L) {
391 Level v;
392 v.inner = inner;
393 v.gdim = inner;
394 v.ext = C3{inner.x + 2 * G, inner.y + 2 * G, inner.z + 2 * G};
395 v.cfac = cf;
396 v.n = (std::size_t)v.ext.x * v.ext.y * v.ext.z;
397 auto can = [&](int d) { return (d % 2 == 0) && (d / 2 >= 2); };
398 C3 next = inner;
399 C3 ratio{1, 1, 1};
400 if (L + 1 < nLevels) {
401 // The SHARED aspect-ratio rule (doc/anisotropic_metric.md §5.3): the same helper, the same
402 // hp, so this hierarchy's level table is the pressure hierarchy's on the same grid.
403 const bool canA[3] = {can(inner.x), can(inner.y), can(inner.z)};
404 const double H[3] = {hp_[0] * (double)cf.x, hp_[1] * (double)cf.y, hp_[2] * (double)cf.z};
405 ratio = CutcellMG::mgChooseRatio(H, canA, aniso_, aspectTheta_);
406 if (ratio.x == 2)
407 next.x = inner.x / 2;
408 if (ratio.y == 2)
409 next.y = inner.y / 2;
410 if (ratio.z == 2)
411 next.z = inner.z / 2;
412 }
413 v.ratio = ratio;
414 v.x = CCField("vmg_x", v.n);
415 v.rhs = CCField("vmg_rhs", v.n);
416 v.res = CCField("vmg_res", v.n);
417 v.theta = CCField("vmg_th", v.n);
418 v.pin = CCField("vmg_pin", v.n);
419 if (L > 0) { // coarse advecting velocity for the upwind-convective coarse op
420 v.advU = CCField("vmg_au", v.n);
421 v.advV = CCField("vmg_av", v.n);
422 v.advW = CCField("vmg_aw", v.n);
423 }
424 for (FPV* p : {&v.AC, &v.AW, &v.AE, &v.AS, &v.AN, &v.AB, &v.AT})
425 *p = FPV("vmg_A", v.n);
426 lv_.push_back(v);
427 if (next.x == inner.x && next.y == inner.y && next.z == inner.z)
428 break;
429 inner = next;
430 cf = C3{cf.x * ratio.x, cf.y * ratio.y, cf.z * ratio.z};
431 }
432 lv_[0].resMask =
433 CCField("vmg_resmask0", lv_[0].n); // level 0 only (clean-fluid exclude, staircase path)
434 }
435#ifdef PECLET_FLOW_MPI
436 // Multi-rank velocity-MG: coarsen the GLOBAL grid 2:1 per level; each level gets its own G=2 core
437 // halo. No global reductions here (the velocity op is non-singular -> no mean removal, no
438 // Krylov), so the fold is just fill()->exchange + the block-origin red-black parity. Single-rank
439 // (size 1) == init().
440 void initMpi(int gnx, int gny, int gnz, int nLevels, MPI_Comm comm) {
441 int size = 1;
442 MPI_Comm_size(comm, &size);
443 initMpi(peclet::core::decomp::BlockDecomposer<3>(static_cast<std::size_t>(size),
444 peclet::core::IVec<3>{gnx, gny, gnz}),
445 nLevels, comm, /*inPlace=*/false);
446 }
447 // The solver's hierarchy: level 0 on the caller's decomposition (the velocity block IbmSolver
448 // already exchanges on), coarse levels = that decomposition coarsened IN PLACE, so an axis
449 // coarsens only while every rank's block origin and size are even on it (the same gate as
450 // CutcellMG without telescoping; with inPlace=false a fresh plain ORB is built per level, which
451 // only the standalone ctest wants). Every rank sees the same replicated decomposition, so the
452 // level count agrees globally with no communication.
453 void initMpi(const peclet::core::decomp::BlockDecomposer<3>& dec0, int nLevels, MPI_Comm comm,
454 bool inPlace = true) {
455 lv_.clear();
456 distributed_ = true;
457 int rank = 0, size = 1;
458 MPI_Comm_rank(comm, &rank);
459 MPI_Comm_size(comm, &size);
460 std::array<bool, 3> per{true, true, true};
461 const auto& g0 = dec0.globalSize();
462 C3 gs{(int)g0[0], (int)g0[1], (int)g0[2]}, cf{1, 1, 1};
463 auto can = [&](int d) { return (d % 2 == 0) && (d / 2 >= 2); };
464 auto evenOn = [](const peclet::core::decomp::BlockDecomposer<3>& d, int ax) {
465 for (std::size_t b = 0; b < d.numBlocks(); ++b) {
466 const auto blk = d.block(b);
467 if (blk.origin[ax] % 2 != 0 || blk.size[ax] % 2 != 0)
468 return false;
469 }
470 return true;
471 };
472 peclet::core::decomp::BlockDecomposer<3> dec = dec0;
473 for (int L = 0; L < nLevels; ++L) {
474 Level v;
475 v.halo = std::make_shared<GridHaloTopology<3>>();
476 if (!inPlace && L > 0)
477 dec = peclet::core::decomp::BlockDecomposer<3>(static_cast<std::size_t>(size),
478 peclet::core::IVec<3>{gs.x, gs.y, gs.z});
479 v.halo->buildTopology(dec, rank, G, per, comm);
480 v.dev = std::make_shared<GridHalo<double>>();
481 v.dev->init(*v.halo);
482 v.dev->setLabel("vmg L" + std::to_string(L));
483 const auto& idx = v.halo->indexer();
484 const auto eg = idx.sizeInclGhost(), ino = idx.sizeInner(), oig = idx.originInclGhost();
485 v.ext = {(int)eg[0], (int)eg[1], (int)eg[2]};
486 v.inner = {(int)ino[0], (int)ino[1], (int)ino[2]};
487 v.og = {(int)oig[0] + G, (int)oig[1] + G, (int)oig[2] + G};
488 v.gdim = gs;
489 v.cfac = cf;
490 v.n = idx.numCellsInclGhost();
491 C3 next = gs, ratio{1, 1, 1};
492 if (L + 1 < nLevels) {
493 // §5.3, distributed: today's candidate set (global can() + the even-block gate), then the
494 // aspect rule. A pure function of replicated data on every rank, like CutcellMG's.
495 const bool canA[3] = {can(gs.x) && (!inPlace || evenOn(dec, 0)),
496 can(gs.y) && (!inPlace || evenOn(dec, 1)),
497 can(gs.z) && (!inPlace || evenOn(dec, 2))};
498 const double H[3] = {hp_[0] * (double)cf.x, hp_[1] * (double)cf.y, hp_[2] * (double)cf.z};
499 ratio = CutcellMG::mgChooseRatio(H, canA, aniso_, aspectTheta_);
500 if (ratio.x == 2)
501 next.x = gs.x / 2;
502 if (ratio.y == 2)
503 next.y = gs.y / 2;
504 if (ratio.z == 2)
505 next.z = gs.z / 2;
506 }
507 v.ratio = ratio;
508 v.x = CCField("vmg_x", v.n);
509 v.rhs = CCField("vmg_rhs", v.n);
510 v.res = CCField("vmg_res", v.n);
511 v.theta = CCField("vmg_th", v.n);
512 v.pin = CCField("vmg_pin", v.n);
513 if (L > 0) {
514 v.advU = CCField("vmg_au", v.n);
515 v.advV = CCField("vmg_av", v.n);
516 v.advW = CCField("vmg_aw", v.n);
517 }
518 for (FPV* p : {&v.AC, &v.AW, &v.AE, &v.AS, &v.AN, &v.AB, &v.AT})
519 *p = FPV("vmg_A", v.n);
520 lv_.push_back(v);
521 if (next.x == gs.x && next.y == gs.y && next.z == gs.z)
522 break;
523 gs = next;
524 cf = C3{cf.x * ratio.x, cf.y * ratio.y, cf.z * ratio.z};
525 if (inPlace)
526 dec = dec.coarsened(peclet::core::IVec<3>{ratio.x, ratio.y, ratio.z});
527 }
528 lv_[0].resMask = CCField("vmg_resmask0", lv_[0].n);
529 }
530#endif
531 // Does this rank's block on level `lv` touch global face f (0=-x,1=+x,2=-y,3=+y,4=-z,5=+z)?
532 // Single-rank: always. The domain-BC fold, the held-face residual exclude, the correction
533 // ghosts and the prolongation ghosts are all applied only by the owning rank (WO-F rule).
534 bool touches(const Level& lv, int f) const {
535 const int a = f / 2;
536 const int o = (a == 0) ? lv.og.x : (a == 1) ? lv.og.y : lv.og.z;
537 const int n = (a == 0) ? lv.inner.x : (a == 1) ? lv.inner.y : lv.inner.z;
538 const int gn = (a == 0) ? lv.gdim.x : (a == 1) ? lv.gdim.y : lv.gdim.z;
539 return (f % 2 == 0) ? (o == 0) : (o + n == gn);
540 }
541 int nLevels() const { return (int)lv_.size(); }
542 Level& level(int L) { return lv_[L]; }
543 // Levels built; 0 means the hierarchy has never been initialised. Dereferencing level 0 in
544 // that state is a segfault, so callers that can reach solve() without init() must ask.
545 int levels() const { return (int)lv_.size(); }
546
547 // level-0 fine operator = the external IBM stencil (7 float arrays on the same G=2 block).
548 void setFineStencil(FPC AC, FPC AW, FPC AE, FPC AS, FPC AN, FPC AB, FPC AT) {
549 Level& f = lv_[0];
550 Kokkos::deep_copy(f.AC, AC);
551 Kokkos::deep_copy(f.AW, AW);
552 Kokkos::deep_copy(f.AE, AE);
553 Kokkos::deep_copy(f.AS, AS);
554 Kokkos::deep_copy(f.AN, AN);
555 Kokkos::deep_copy(f.AB, AB);
556 Kokkos::deep_copy(f.AT, AT);
557 }
558
559 // staircase coarse op: level-0 pin = fine solid mask, resMask = clean-fluid mask; coarse levels
560 // classify by restricted theta and build a const-coeff Helmholtz. nu_dt = mu, idiag = rho/dt, h0
561 // = 1.
562 void setStaircase(CCConst theta0, CCConst solid0, CCConst resmask0, double nu_dt, double idiag,
563 double thresh) {
564 usePin_ = true;
565 useResMask_ = true; // staircase: pin classified-solid cells + exclude the IBM band
566 Level& f = lv_[0];
567 Kokkos::deep_copy(f.theta, theta0);
568 Kokkos::deep_copy(f.pin, solid0);
569 Kokkos::deep_copy(f.resMask, resmask0);
570 for (int L = 1; L < (int)lv_.size(); ++L) {
571 Level& c = lv_[L];
572 Level& fin = lv_[L - 1];
573 restrictAvg(c.theta, CCConst(fin.theta), c.ext, fin.ext, G, G, c.inner,
574 fin.ratio); // coarse theta = avg
575 thresholdMask(c.pin, CCConst(c.theta), thresh);
576 const double bx = nu_dt * w_[0] / (double)(c.cfac.x * c.cfac.x),
577 by = nu_dt * w_[1] / (double)(c.cfac.y * c.cfac.y),
578 bz = nu_dt * w_[2] / (double)(c.cfac.z * c.cfac.z);
579 buildVelocityStaircase(c.AC, c.AW, c.AE, c.AS, c.AN, c.AB, c.AT, CCConst(c.theta), c.ext, G,
580 bx, by, bz, thresh, idiag);
581 }
582 }
583
584 // MIXED operator: an immersed solid AND domain BCs (the packed-bed-with-inlet case). Level 0 =
585 // the external cut-cell stencil (setFineStencil) with the solid pin and the clean-fluid exclude,
586 // PLUS the held normal-Dirichlet boundary face excluded from coarsening (as setDomainBcOp does);
587 // coarse levels = the staircase Helmholtz (classified solid pinned) PLUS the domain-face folds
588 // (tangential wall/inflow +beta, outflow -beta) on the owning rank. The non-periodic correction
589 // ghosts are zero (fill() / the smoother keep them so), which is the Dirichlet-0 the fold
590 // assumes. Needs setBC() first. comp = velocity component (the fold is component-dependent).
591 // upwind: the fine stencil carries implicit first-order-upwind advection, so the coarse
592 // operator adds the FOU part from the restricted advecting velocity (restrictAdvVelocities must
593 // have run this step) on the fluid rows, the classified-solid rows staying pinned.
594 void setStaircaseBc(int comp, CCConst theta0, CCConst solid0, CCConst resmask0, double nu_dt,
595 double idiag, double thresh, bool upwind = false, double fouw = 0.0) {
596 heldComp_ = comp;
597 setStaircase(theta0, solid0, resmask0, nu_dt, idiag, thresh);
598 if (upwind)
599 for (int L = 1; L < (int)lv_.size(); ++L) {
600 Level& c = lv_[L];
601 const double bx = nu_dt * w_[0] / (double)(c.cfac.x * c.cfac.x),
602 by = nu_dt * w_[1] / (double)(c.cfac.y * c.cfac.y),
603 bz = nu_dt * w_[2] / (double)(c.cfac.z * c.cfac.z);
604 buildAdvCoarse(c.AC, c.AW, c.AE, c.AS, c.AN, c.AB, c.AT, CCConst(c.advU), CCConst(c.advV),
605 CCConst(c.advW), comp, c.ext, G, bx, by, bz, fouw, 1.0 / c.cfac.x,
606 1.0 / c.cfac.y, 1.0 / c.cfac.z, idiag);
607 pinSolidRows(c.AC, c.AW, c.AE, c.AS, c.AN, c.AB, c.AT, CCConst(c.theta), c.ext, G, thresh);
608 }
609 Level& f = lv_[0];
610 {
611 const int t = bc_[2 * comp]; // the -side face of the normal component lands at index G
612 if ((t == 1 || t == 2 || t == 4) && touches(f, 2 * comp))
613 zeroPlane(f.resMask, f.ext, comp, G);
614 }
615 for (int L = 1; L < (int)lv_.size(); ++L) {
616 Level& c = lv_[L];
617 const double bx = nu_dt * w_[0] / (double)(c.cfac.x * c.cfac.x),
618 by = nu_dt * w_[1] / (double)(c.cfac.y * c.cfac.y),
619 bz = nu_dt * w_[2] / (double)(c.cfac.z * c.cfac.z);
620 for (int ff = 0; ff < 6; ++ff) {
621 const int a = ff / 2, sd = ff % 2;
622 const double ba = (a == 0) ? bx : (a == 1) ? by : bz;
623 double dval;
624 if (bc_[ff] == 3)
625 dval = -ba;
626 else if ((bc_[ff] == 1 || bc_[ff] == 2) && a != comp)
627 dval = ba;
628 else
629 continue; // periodic, the normal comp at a wall / free-slip face, or a FREE-SLIP
630 // tangential face -- see the note in setDomainBcOp: the coarse levels keep
631 // the Dirichlet-at-ghost surrogate there, deliberately
632 if (touches(c, ff))
633 boundaryFold(c.AC, c.ext, G, a, sd, dval);
634 }
635 }
636 }
637
638 // UPWIND-CONVECTIVE coarse op (implicit-FOU): restrict the advecting velocity u/v/w (level-0
639 // block) to every coarse level (8:1 average; numerical diffusion is welcome -> keeps the
640 // M-matrix). Call ONCE per Picard iteration, before buildUpwindCoarse for the 3 components (the
641 // velocity is shared/frozen at u^k).
643 for (int L = 1; L < (int)lv_.size(); ++L) {
644 Level& cs = lv_[L];
645 Level& fin = lv_[L - 1];
646 CCConst fu = (L == 1) ? u0 : CCConst(fin.advU), fv = (L == 1) ? v0 : CCConst(fin.advV),
647 fw = (L == 1) ? w0 : CCConst(fin.advW);
648 restrictAvg(cs.advU, fu, cs.ext, fin.ext, G, G, cs.inner, fin.ratio);
649 fill(cs, cs.advU);
650 restrictAvg(cs.advV, fv, cs.ext, fin.ext, G, G, cs.inner, fin.ratio);
651 fill(cs, cs.advV);
652 restrictAvg(cs.advW, fw, cs.ext, fin.ext, G, G, cs.inner, fin.ratio);
653 fill(cs, cs.advW);
654 }
655 }
656 // Build the coarse operators for component comp = aniso const-coeff diffusion + dt*FOU from the
657 // restricted advecting velocity (level 0 stays the fine As_[comp] set by setFineStencil). No pin
658 // / no exclude mask -- the upwind M-matrix is stable; the fine residual gives the exact sharp
659 // answer. Per Picard iter, per comp.
660 void buildUpwindCoarse(int comp, double nu_dt, double idiag, double fouw) {
661 usePin_ = false;
662 useResMask_ = false; // upwind path: pure variable-coeff MG (no pin/exclude)
663 for (int L = 1; L < (int)lv_.size(); ++L) {
664 Level& c = lv_[L];
665 const double bx = nu_dt * w_[0] / (double)(c.cfac.x * c.cfac.x),
666 by = nu_dt * w_[1] / (double)(c.cfac.y * c.cfac.y),
667 bz = nu_dt * w_[2] / (double)(c.cfac.z * c.cfac.z);
668 const double sx = 1.0 / (double)c.cfac.x, sy = 1.0 / (double)c.cfac.y,
669 sz = 1.0 / (double)c.cfac.z;
670 buildAdvCoarse(c.AC, c.AW, c.AE, c.AS, c.AN, c.AB, c.AT, CCConst(c.advU), CCConst(c.advV),
671 CCConst(c.advW), comp, c.ext, G, bx, by, bz, fouw, sx, sy, sz, idiag);
672 }
673 }
674
675 // DOMAIN-BC const-coeff path (cavity/BFS): per-face BC types {-x,+x,-y,+y,-z,+z}
676 // (0=periodic,1=wall, 2=inflow,3=outflow,4=free-slip). Enables the non-periodic fill (periodic
677 // axes wrap; non-periodic ghosts left as the caller / correction set them) + the
678 // Dirichlet/Neumann prolongation ghosts.
679 void setBC(const int bc[6]) {
680 bcMode_ = false;
681 for (int i = 0; i < 6; ++i) {
682 bc_[i] = bc[i];
683 if (bc[i])
684 bcMode_ = true;
685 }
686 }
687 // Re-impose the full velocity BC on the level-0 iterate before each smoother colour + the
688 // residual (exactly as the RB-GS path does via fillVelGhosts(c,1)): the const-coeff smoother
689 // updates the held Dirichlet faces, so without this the boundary corners drift (~2% vs RB-GS, as
690 // the CUDA vmg also does). With it the vel-MG converges to the RB-GS fixed point. IbmSolver
691 // supplies this per component before the solve.
692 void setBcApplyL0(std::function<void(CCField)> fn) { bcApplyL0_ = std::move(fn); }
693
694 // Use a Chebyshev polynomial smoother instead of red-black Gauss-Seidel on every level.
695 // `degree` is taken from the caller's sweep counts (pre/post/bottom), so a 2/2 V-cycle becomes a
696 // degree-2 polynomial and the two are compared at equal nominal work. The interval is
697 // [hi/eigRatio, hi] with hi the level's Gershgorin lambda_max: a SMOOTHER wants the top of the
698 // spectrum (the coarse grid owns the rest), which is why this is not the solver's true lower
699 // bound. eigRatio is the usual MG knob -- PETSc defaults near 10, MueLu near 20.
700 void setChebyshevSmoother(bool on, int degree = 0, double eigRatio = 10.0) {
701 chebSmooth_ = on;
702 chebDegree_ = degree; // 0 = follow pre_/post_/bottom_
703 chebEigRatio_ = eigRatio > 1.0 ? eigRatio : 10.0;
704 }
705 bool chebyshevSmoother() const { return chebSmooth_; }
707 void setAspectThreshold(double theta) { aspectTheta_ = theta; }
708 // const-coeff aniso operator + no-slip/inflow/outflow boundary fold for component comp, on EVERY
709 // level. nu_dt = mu, idiag = rho/dt, h0 = 1. Rebuilt per component (the fold is
710 // component-dependent). No pin. useResMask_: exclude the HELD normal-Dirichlet boundary face
711 // (a==comp, -side, wall/inflow) from coarsening -- that cell's value is pinned by the BC
712 // re-imposition, so its (nonzero) residual would drive a spurious coarse correction into the
713 // boundary (the ~2% drift CUDA's domain-BC vmg leaves). Excluding it makes the V-cycle converge
714 // to the RB-GS fixed point (analogue of the IBM clean-fluid exclude).
715 void setDomainBcOp(int comp, double nu_dt, double idiag) {
716 heldComp_ = comp;
717 usePin_ = false;
718 Level& f = lv_[0];
719 Kokkos::deep_copy(f.resMask, 1.0);
720 useResMask_ = false;
721 for (int s = 0; s < 1;
722 ++s) { // only the -side face index G lands inside the smoother range [G, ext-G)
723 const int t = bc_[2 * comp + s];
724 if (t == 1 || t == 2 || t == 4) {
725 if (touches(f, 2 * comp + s))
726 zeroPlane(f.resMask, f.ext, comp, G);
727 useResMask_ = true; // rank-uniform (the masked transfers must agree across ranks)
728 }
729 }
730 for (int L = 0; L < (int)lv_.size(); ++L) {
731 Level& c = lv_[L];
732 const double bx = nu_dt * w_[0] / (double)(c.cfac.x * c.cfac.x),
733 by = nu_dt * w_[1] / (double)(c.cfac.y * c.cfac.y),
734 bz = nu_dt * w_[2] / (double)(c.cfac.z * c.cfac.z);
735 buildConstAniso(c.AC, c.AW, c.AE, c.AS, c.AN, c.AB, c.AT, c.ext, bx, by, bz, idiag);
736 for (int f = 0; f < 6; ++f) {
737 const int a = f / 2, s = f % 2;
738 const double ba = (a == 0) ? bx : (a == 1) ? by : bz;
739 double dval;
740 if (bc_[f] == 3)
741 dval = -ba; // outflow zero-gradient: every component
742 else if ((bc_[f] == 1 || bc_[f] == 2) && a != comp)
743 dval = ba; // wall/inflow: tangential fold
744 else if (bc_[f] == 4 && a != comp && L == 0)
745 dval = -ba; // free-slip: zero-gradient tangential fold -- LEVEL 0 ONLY. On the
746 // coarse levels the exact Neumann row (-ba, ghost 0) is what the fine
747 // operator has, but with rho/dt -> 0 it leaves the coarse tangential
748 // operator nearly singular (slip on two opposite faces removes its
749 // Dirichlet anchor in that direction), and the V-cycle's few-sweep
750 // coarse solves then return noise instead of a correction. Measured,
751 // sphere in an inflow/outflow channel at nu dt/h^2 = 1e3, residual
752 // after 32 V-cycles: -ba on every level 1.2e-3 (+-z slip) and a
753 // stagnation at 0.89 (all four faces slip); coarse fold dropped 2.5e-7
754 // and 3.3e-4 (walls: 7.5e-8). The coarse levels therefore keep the
755 // Dirichlet-at-ghost-centre surrogate, which is exactly what the
756 // normal component at any Dirichlet face already uses; the fixed point
757 // is set by level 0 alone.
758 else
759 continue; // periodic, the normal comp at a wall / free-slip face, or a coarse slip face
760 if (touches(c, f))
761 boundaryFold(c.AC, c.ext, G, a, s, dval);
762 }
763 }
764 }
765
766 // solve()'s global max over its communicator (distributed); the local value otherwise.
767 double solveMax(double v, [[maybe_unused]] Comm comm) const {
768#ifdef PECLET_FLOW_MPI
769 if (distributed_ && comm != MPI_COMM_NULL) {
770 double g = 0.0;
771 MPI_Allreduce(&v, &g, 1, MPI_DOUBLE, MPI_MAX, comm);
772 return g;
773 }
774#endif
775 return v;
776 }
777 // Chebyshev needs an interval that CONTAINS each level's spectrum, and every rank must use
778 // the SAME polynomial or the iterates drift apart. The operator is fixed for the whole solve,
779 // so the Gershgorin reduction runs once per level in solve() -- not inside smooth(), which would
780 // put an all-reduce on every level of every V-cycle and hand back the latency the smoother saves.
782 for (Level& lv : lv_) {
783 double lo = 0.0, hi = 0.0;
784 ibmStencilJacobiBounds(FPC(lv.AC), FPC(lv.AW), FPC(lv.AE), FPC(lv.AS), FPC(lv.AN), FPC(lv.AB),
785 FPC(lv.AT), usePin_ ? CCConst(lv.pin) : empty_, lv.ext, G, lo, hi);
786 lv.chebHi = solveMax(hi, comm);
787 }
788 }
789 // solve()'s level-0 residual res = b - A x (BC hook first) and its global max|res| over the
790 // inner cells.
791 double level0Residual(Comm comm) {
792 Level& l0 = lv_[0];
793 fill(l0, l0.x);
794 if (bcApplyL0_)
795 bcApplyL0_(l0.x);
796 residualVarPin(l0.res, CCConst(l0.x), CCConst(l0.rhs), FPC(l0.AC), FPC(l0.AW), FPC(l0.AE),
797 FPC(l0.AS), FPC(l0.AN), FPC(l0.AB), FPC(l0.AT),
798 usePin_ ? CCConst(l0.pin) : empty_, l0.ext, G);
799 // the held normal-Dirichlet face (wall / inflow, -side) is imposed, not solved: not part
800 // of the convergence measure
801 if (bcMode_ && heldComp_ >= 0) {
802 const int t = bc_[2 * heldComp_];
803 if ((t == 1 || t == 2 || t == 4) && touches(l0, 2 * heldComp_))
804 zeroPlane(l0.res, l0.ext, heldComp_, G);
805 }
806 return solveMax(maxAbsInner(CCConst(l0.res), l0.ext, G), comm);
807 }
808 // solve A x = b (b,x on the level-0 G=2 block): up to nvc V-cycles. Solution left in x.
809 // Two optional stops (global max under MPI):
810 // tol > 0: max|x_{k+1} - x_k| over the inner cells <= tol * (first cycle's) -- the update
811 // criterion IbmSolver's RB-GS sweep loop uses, so cycles and sweeps compare;
812 // resTol > 0: max|b - A x| <= resTol * max|b| (the level-0 fine operator, pinned rows 0) --
813 // the criterion that measures convergence itself; a warm start that already
814 // solves the equation stops at once. resTol takes precedence when both are set.
815 // Returns the cycles run; lastResidualRatio() is max|r|/max|b| at exit (resTol mode only).
816 int solve(CCConst b, CCField x, int nvc, int pre, int post, int bottom, double tol = 0.0,
817 Comm comm = nullComm(), double resTol = 0.0) {
818 pre_ = pre;
819 post_ = post;
820 bottom_ = bottom;
821 Level& l0 = lv_[0];
822 // H-2d (doc/vof_projection_cost_design.md §8, perf A5's pattern): on a single rank the solve
823 // runs on the caller's Views -- level 0's rhs and x are rebound to b and x and restored at
824 // exit -- instead of staging copies in and out. No pass writes level 0's rhs (the V-cycle
825 // writes rhs on the coarse levels only, by restriction), so the const b is only read.
826 struct Restore {
827 Level& l;
828 CCField rhs, x;
829 bool on;
830 ~Restore() {
831 if (on) {
832 l.rhs = rhs;
833 l.x = x;
834 }
835 }
836 } restore{l0, l0.rhs, l0.x, false};
837 if (!distributed_ && b.extent(0) == l0.n && x.extent(0) == l0.n) {
838 restore.on = true;
839 l0.rhs = CCField(const_cast<double*>(b.data()), l0.n); // unmanaged alias, read only
840 l0.x = x;
841 } else {
842 Kokkos::deep_copy(l0.rhs, b);
843 Kokkos::deep_copy(l0.x, x);
844 }
845 if (chebSmooth_)
846 chebLevelBounds(comm);
847 // The forcing may enter through a Dirichlet ghost (an inflow) rather than through b, so the
848 // convergence scale is max(max|b|, max|A x|) with max|A x| = max|b - r| from the initial
849 // residual -- max|b| alone is ~0 on the first step from rest and the stop never triggers.
850 const bool useRes = resTol > 0.0;
851 const bool useDu = !useRes && tol > 0.0;
852 if (useDu && prev_.extent(0) != l0.n)
853 prev_ = CCField("vmg_prev", l0.n);
854 double du0 = 0.0, bnorm = 0.0;
855 int used = nvc;
856 lastResRatio_ = -1.0;
857 if (useRes) { // scale only; at least one cycle always runs (see IbmSolver::velSweepLoop)
858 const double r0 = level0Residual(comm);
859 bnorm =
860 std::max(solveMax(maxAbsInner(CCConst(l0.rhs), l0.ext, G), comm),
861 solveMax(maxAbsDiffInner(CCConst(l0.rhs), CCConst(l0.res), l0.ext, G), comm));
862 lastResRatio_ = bnorm > 0.0 ? r0 / bnorm : 0.0;
863 }
864 double rPrev = -1.0;
865 for (int v = 0; v < nvc; ++v) {
866 if (useDu)
867 Kokkos::deep_copy(prev_, l0.x);
868 vcycle(0);
869 if (useRes) {
870 const double r = level0Residual(comm);
871 lastResRatio_ = bnorm > 0.0 ? r / bnorm : 0.0;
872 // round-off floor / stagnation guard (see IbmSolver::velSweepLoop)
873 const bool floor = r <= 1e-14 * bnorm || (rPrev >= 0.0 && r >= rPrev);
874 rPrev = r;
875 if (r <= resTol * bnorm || floor) {
876 used = v + 1;
877 break;
878 }
879 } else if (useDu) {
880 const double du = solveMax(maxAbsDiffInner(CCConst(l0.x), CCConst(prev_), l0.ext, G), comm);
881 if (v == 0)
882 du0 = du;
883 if (du <= tol * du0) {
884 used = v + 1;
885 break;
886 }
887 }
888 }
889 if (!restore.on)
890 Kokkos::deep_copy(x, l0.x);
891 return used;
892 }
893 double lastResidualRatio() const { return lastResRatio_; }
894
895 public: // (public for nvcc extended-lambda)
896 void vcycle(int L) {
897 Level& lv = lv_[L];
898 const bool l0 = (L == 0);
899 if (L + 1 == (int)lv_.size()) {
900 smooth(lv, bottom_, l0);
901 return;
902 } // velocity op non-singular -> no mean removal
903 smooth(lv, pre_, l0);
904 fill(lv, lv.x);
905 if (l0 && bcApplyL0_)
906 bcApplyL0_(lv.x); // domain-BC: re-impose the velocity BC before the level-0 residual
907 residualVarPin(lv.res, CCConst(lv.x), CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AW), FPC(lv.AE),
908 FPC(lv.AS), FPC(lv.AN), FPC(lv.AB), FPC(lv.AT),
909 usePin_ ? CCConst(lv.pin) : empty_, lv.ext, G);
910 const bool masked =
911 useResMask_ && (lv.resMask.extent(0) == lv.n); // level 0: exclude the IBM cut-cell band
912 if (masked)
913 mulMask(lv.res, CCConst(lv.resMask));
914 Level& cs = lv_[L + 1];
915 restrictAvg(cs.rhs, CCConst(lv.res), cs.ext, lv.ext, G, G, cs.inner, lv.ratio);
916 Kokkos::deep_copy(cs.x, 0.0);
917 vcycle(L + 1);
918 fill(cs, cs.x);
920 cs); // non-periodic boundary ghosts the trilinear prolong samples (domain-BC mode)
921 if (masked)
922 prolongMasked(lv.x, CCConst(cs.x), CCConst(lv.resMask), lv.ext, cs.ext, G, lv.inner, lv.ratio,
923 0.5);
924 else
925 prolongAdd(lv.x, CCConst(cs.x), lv.ext, cs.ext, G, G, lv.inner, lv.ratio);
926 smooth(lv, post_, l0);
927 }
928 void smooth(Level& lv, int sweeps, bool isL0) {
929 const C3 og = lv.og; // global red-black parity (block inner origin); {0,0,0} single-rank
930 CCConst pin = usePin_ ? CCConst(lv.pin) : empty_;
931 if (chebSmooth_ && lv.chebHi > 0.0) {
932 chebSmooth(lv, chebDegree_ > 0 ? chebDegree_ : sweeps, isL0, pin);
933 return;
934 }
935 for (int k = 0; k < sweeps; ++k)
936 for (int color = 0; color < 2; ++color) {
937#ifdef PECLET_FLOW_MPI
938 if (distributed_ && !bcMode_) {
939 // Overlap the per-colour halo with the interior sweep (see CutcellMG::smooth) — only on
940 // the periodic/IBM path: the per-colour BC hook re-imposes ghost/held cells AFTER the
941 // fill in the blocking order, which the split would reorder.
942 const C3 lo{G + 1, G + 1, G + 1};
943 const C3 hi{lv.ext.x - G - 1, lv.ext.y - G - 1, lv.ext.z - G - 1};
944 lv.dev->exchangeBegin(lv.x);
945 ibmRbgsStencilColorBox(lv.x, CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AW), FPC(lv.AE),
946 FPC(lv.AS), FPC(lv.AN), FPC(lv.AB), FPC(lv.AT), pin, lv.ext, og,
947 color, lo, hi, C3{0, 0, 0}, C3{0, 0, 0});
948 lv.dev->exchangeEnd(lv.x);
949 ibmRbgsStencilColorBox(lv.x, CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AW), FPC(lv.AE),
950 FPC(lv.AS), FPC(lv.AN), FPC(lv.AB), FPC(lv.AT), pin, lv.ext, og,
951 color, C3{G, G, G}, C3{lv.ext.x - G, lv.ext.y - G, lv.ext.z - G},
952 lo, hi);
953 continue;
954 }
955#endif
956 fill(lv, lv.x);
957 if (isL0 && bcApplyL0_)
958 bcApplyL0_(lv.x); // re-impose the velocity BC (held Dirichlet faces) per colour
959 ibmRbgsStencilColor(lv.x, CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AW), FPC(lv.AE), FPC(lv.AS),
960 FPC(lv.AN), FPC(lv.AB), FPC(lv.AT), pin, lv.ext, og, G, color);
961 }
962 }
963
964 // Degree-`degree` Chebyshev polynomial smoother on diag(AC)^-1 A over [hi/eigRatio, hi]. One
965 // residual and ONE halo exchange per degree, against red-black's two colour passes and two
966 // exchanges per sweep -- the reason to want it here at all. The direction restarts at zero on
967 // every call: each smooth is an independent polynomial application, not a continued iteration.
968 // lv.res is scratch here; vcycle recomputes it after smoothing, so overwriting it is safe.
969 void chebSmooth(Level& lv, int degree, bool isL0, CCConst pin) {
970 if (degree < 1)
971 return;
972 if (lv.cd.extent(0) != lv.n)
973 lv.cd = CCField("vmg_cd", lv.n);
974 Kokkos::deep_copy(lv.cd, 0.0);
975 ChebCoeffs cb(lv.chebHi / chebEigRatio_, lv.chebHi);
976 for (int k = 0; k < degree; ++k) {
977 fill(lv, lv.x);
978 if (isL0 && bcApplyL0_)
979 bcApplyL0_(lv.x);
980 residualVarPin(lv.res, CCConst(lv.x), CCConst(lv.rhs), FPC(lv.AC), FPC(lv.AW), FPC(lv.AE),
981 FPC(lv.AS), FPC(lv.AN), FPC(lv.AB), FPC(lv.AT), pin, lv.ext, G);
982 double alpha = 0.0, beta = 0.0;
983 cb.next(k, alpha, beta);
984 ibmChebUpdate(lv.x, lv.cd, CCConst(lv.res), FPC(lv.AC), pin, lv.ext, G, alpha, beta);
985 }
986 }
987 // periodic ghost fill; in domain-BC mode only the periodic axes wrap (non-periodic boundary
988 // ghosts are left as the caller / correction set them -- the boundary fold + held ghost represent
989 // the wall). Distributed (periodic IBM path): the per-level core halo (cross-rank + periodic in
990 // one call).
991 void fill(Level& lv, CCField f) {
992#ifdef PECLET_FLOW_MPI
993 if (distributed_) {
994 lv.dev->exchange(f); // cross-rank + periodic on all three axes
995 if (bcMode_)
996 zeroBcGhosts(lv, f);
997 return;
998 }
999#endif
1000 for (int a = 0; a < 3; ++a)
1001 if (!bcMode_ || (bc_[2 * a] == 0 && bc_[2 * a + 1] == 0))
1002 fillAxis(lv, f, a);
1003 }
1004 // Non-periodic global-face ghosts of `f` -> 0 on the owning rank (the halo exchange is built
1005 // periodic on every axis, so it has just wrapped the opposite side of the domain into them). A
1006 // coarse correction wants exactly 0 there; level 0 gets the real BC from the hook afterwards.
1008 for (int a = 0; a < 3; ++a)
1009 for (int s = 0; s < 2; ++s)
1010 if (bc_[2 * a + s] != 0 && touches(lv, 2 * a + s))
1011 fillBcGhost(f, lv.ext, G, a, s, /*dirichlet=*/1);
1012 }
1013 // non-periodic boundary ghosts of a coarse correction before trilinear prolong (Dirichlet outflow
1014 // -> 0, Neumann wall/inflow -> zero-gradient).
1016 if (!bcMode_)
1017 return;
1018 for (int a = 0; a < 3; ++a)
1019 for (int s = 0; s < 2; ++s) {
1020 const int t = bc_[2 * a + s];
1021 if (t == 0 || !touches(lv, 2 * a + s))
1022 continue;
1023 fillBcGhost(lv.x, lv.ext, G, a, s, t == 3 ? 1 : 0);
1024 }
1025 }
1026 void fillAxis(Level& lv, CCField f, int axis) {
1027 CCExec space;
1028 C3 e = lv.ext;
1029 int N3[3] = {lv.inner.x, lv.inner.y, lv.inner.z};
1030 int dims[3] = {e.x, e.y, e.z};
1031 long st[3] = {1, e.x, (long)e.x * e.y};
1032 const int a = axis, b = (axis + 1) % 3, c = (axis + 2) % 3;
1033 const long sa = st[a], sb = st[b], sc = st[c];
1034 const int N = N3[a];
1035 CCField ff = f;
1036 Kokkos::parallel_for(
1037 "peclet::flow::vmg_pfill", MDRange2<CCExec>(space, {0, 0}, {dims[b], dims[c]}),
1038 KOKKOS_LAMBDA(int p0, int p1) {
1039 const long base = (long)p0 * sb + (long)p1 * sc;
1040 for (int gl = 0; gl < G; ++gl) {
1041 ff(base + (long)gl * sa) = ff(base + (long)(gl + N) * sa);
1042 ff(base + (long)(G + N + gl) * sa) = ff(base + (long)(G + gl) * sa);
1043 }
1044 });
1045 }
1046
1047 private:
1048 std::vector<Level> lv_;
1049 double w_[3] = {1.0, 1.0, 1.0}; // per-axis metric weight (setMetric); 1.0 = isotropic lattice
1050 double hp_[3] = {1.0, 1.0, 1.0}; // per-axis spacing h_a' (setMetric); the §5 coarsening rule
1051 bool aniso_ = false; // engages that rule; false => today's level table verbatim
1052 double aspectTheta_ = 2.0; // anisotropic-coarsening threshold (setAspectThreshold)
1053 int pre_ = 2, post_ = 2, bottom_ = 8;
1054 bool chebSmooth_ = false; // Chebyshev polynomial smoother instead of red-black GS
1055 int chebDegree_ = 0; // 0 = follow pre_/post_/bottom_
1056 double chebEigRatio_ = 10.0; // interval is [chebHi/chebEigRatio_, chebHi]
1057 bool usePin_ = true,
1058 useResMask_ = true; // staircase: pin + clean-fluid exclude; upwind/domain-BC: neither
1059 bool bcMode_ = false;
1060 int bc_[6] = {0, 0, 0, 0, 0, 0}; // domain-BC (non-periodic) mode
1061 std::function<void(CCField)> bcApplyL0_; // re-impose the velocity BC on level 0 (domain-BC mode)
1062 CCConst empty_; // zero-extent View -> "no pin / no mask" to the kernels
1063 bool distributed_ = false; // multi-rank (initMpi); fill() exchanges on every level
1064 CCField prev_; // previous iterate for the update-tolerance stop (solve tol > 0)
1065 double lastResRatio_ = -1.0; // max|r|/max|b| at exit of the last resTol-mode solve
1066 int heldComp_ = -1; // component of the last domain-BC operator build (held-face exclude)
1067};
1068
1069} // namespace peclet::flow
1070
1071#endif // PECLET_FLOW_MAC_VELOCITY_MG_HPP
static C3 mgChooseRatio(const double H[3], const bool canA[3], bool aniso, double theta)
void setFineStencil(FPC AC, FPC AW, FPC AE, FPC AS, FPC AN, FPC AB, FPC AT)
void fillProlongBcGhosts(Level &lv)
void buildUpwindCoarse(int comp, double nu_dt, double idiag, double fouw)
void zeroBcGhosts(Level &lv, CCField f)
void setChebyshevSmoother(bool on, int degree=0, double eigRatio=10.0)
bool touches(const Level &lv, int f) const
double solveMax(double v, Comm comm) const
void setStaircaseBc(int comp, CCConst theta0, CCConst solid0, CCConst resmask0, double nu_dt, double idiag, double thresh, bool upwind=false, double fouw=0.0)
int solve(CCConst b, CCField x, int nvc, int pre, int post, int bottom, double tol=0.0, Comm comm=nullComm(), double resTol=0.0)
void fillAxis(Level &lv, CCField f, int axis)
double level0Residual(Comm comm)
void setBcApplyL0(std::function< void(CCField)> fn)
void setDomainBcOp(int comp, double nu_dt, double idiag)
void smooth(Level &lv, int sweeps, bool isL0)
void chebSmooth(Level &lv, int degree, bool isL0, CCConst pin)
void restrictAdvVelocities(CCConst u0, CCConst v0, CCConst w0)
void fill(Level &lv, CCField f)
void setAspectThreshold(double theta)
Anisotropic-coarsening aspect threshold theta (doc/anisotropic_metric.md §5.1).
void setStaircase(CCConst theta0, CCConst solid0, CCConst resmask0, double nu_dt, double idiag, double thresh)
void setBC(const int bc[6])
void init(int nx, int ny, int nz, int nLevels)
std::vector< C3 > levelRatios() const
The per-level coarsening ratio actually chosen (the level table of §5; the two hierarchies share one ...
void setMetric(const double w[3], const double hp[3])
Per-axis metric of the physical domain (doc/anisotropic_metric.md §1.1): the weights w_a = 1/h_a'^2,...
flow — Chebyshev semi-iteration as a standalone momentum (implicit-diffusion) solver,...
flow — portable (Kokkos) geometric multigrid for the cut-cell (variable-openness) pressure Poisson.
flow — portable (Kokkos) IBM geometric fields + variable-coefficient RB-GS smoother.
void zeroPlane(CCField m, C3 e, int axis, int idx)
Kokkos::DefaultExecutionSpace CCExec
void residualVarPinMax(CCConst x, CCConst b, FPC AC, FPC AW, FPC AE, FPC AS, FPC AN, FPC AB, FPC AT, CCConst pin, C3 e, int g, int holdAxis, int holdIdx, double &rmax, double &bdmax, double &bmax)
void buildConstAniso(FPV AC, FPV AW, FPV AE, FPV AS, FPV AN, FPV AB, FPV AT, C3 e, double bx, double by, double bz, double idiag)
Kokkos::MDRangePolicy< Exec, Kokkos::Rank< 3, Kokkos::Iterate::Left, Kokkos::Iterate::Left > > MDRange3
3-D range, x (the first index) fastest (both the tile order and the order within a tile).
Definition policy.hpp:36
void buildVelocityStaircase(FPV AC, FPV AW, FPV AE, FPV AS, FPV AN, FPV AB, FPV AT, CCConst theta, C3 e, int g, double bx, double by, double bz, double thresh, double idiag)
void thresholdMask(CCField m, CCConst theta, double thresh)
void ibmChebUpdate(CCField x, CCField d, CCConst r, FPC AC, CCConst solidmask, C3 e, int g, double alpha, double beta)
One Chebyshev update on the Jacobi-preconditioned system: d <- beta*d + alpha*r/AC ; x += d.
void prolongAdd(CCField fine, CCConst coarse, C3 fext, C3 cext, int gf, int gc, C3 finner, C3 ratio)
Kokkos::View< const double *, CCMem > CCConst
void ibmStencilJacobiBounds(MC AC, MC AW, MC AE, MC AS, MC AN, MC AB, MC AT, CCConst solidmask, C3 e, int g, double &lo, double &hi)
Gershgorin bounds [lo, hi] on the spectrum of the Jacobi-preconditioned cut-cell Helmholtz diag(AC)^-...
void ccReduce3(const char *name, C3 lo, C3 hi, F f, R &&... reducers)
void residualVarPin(CCField r, CCConst x, CCConst b, FPC AC, FPC AW, FPC AE, FPC AS, FPC AN, FPC AB, FPC AT, CCConst pin, C3 e, int g)
void boundaryFold(FPV AC, C3 e, int g, int a, int s, double beta)
Kokkos::View< const MReal *, CCMem > FPC
void fillBcGhost(CCField x, C3 e, int g, int a, int s, int dirichlet)
double maxAbsInner(CCConst a, C3 e, int g)
Kokkos::View< double *, CCMem > CCField
void ccFor3(const char *name, C3 lo, C3 hi, F f)
Kokkos::View< MReal *, CCMem > FPV
void restrictAvg(CCField coarse, CCConst fine, C3 cext, C3 fext, int gc, int gf, C3 cinner, C3 ratio)
double maxAbsDiffInner(CCConst a, CCConst b, C3 e, int g)
void ibmRbgsStencilColorBox(CCField x, CCConst b, MC AC, MC AW, MC AE, MC AS, MC AN, MC AB, MC AT, CCConst solidmask, C3 ext, C3 og, int color, C3 rlo, C3 rhi, C3 slo, C3 shi)
Definition mac_ibm.hpp:410
void mulMask(CCField r, CCConst m)
void pinSolidRows(FPV AC, FPV AW, FPV AE, FPV AS, FPV AN, FPV AB, FPV AT, CCConst theta, C3 e, int g, double thresh)
void prolongMasked(CCField fine, CCConst coarse, CCConst mask, C3 fext, C3 cext, int g, C3 finner, C3 ratio, double eps)
void ibmRbgsStencilColor(CCField x, CCConst b, MC AC, MC AW, MC AE, MC AS, MC AN, MC AB, MC AT, CCConst solidmask, C3 ext, C3 og, int g, int color)
Definition mac_ibm.hpp:287
void buildAdvCoarse(FPV AC, FPV AW, FPV AE, FPV AS, FPV AN, FPV AB, FPV AT, CCConst U, CCConst V, CCConst W, int comp, C3 e, int g, double bx, double by, double bz, double fouw, double sx, double sy, double sz, double idiag)
Kokkos::MDRangePolicy< Exec, Kokkos::Rank< 2, Kokkos::Iterate::Left, Kokkos::Iterate::Left > > MDRange2
2-D range, first index fastest (both the tile order and the order within a tile).
Definition policy.hpp:31
Definition post.py:1
void fou_operator_aniso(int comp, int x, int y, int z, A U, A V, A W, double dt, double sx, double sy, double sz, double &cC, double &cxm, double &cxp, double &cym, double &cyp, double &czm, double &czp)
flow — the multidimensional iteration policies: iteration order follows storage.
flow — portable (Kokkos) staggered MAC momentum advection (Koren TVD + FOU).
int y
int x
int z
The Chebyshev coefficient recurrence (Golub-Varga; the form multigrid Chebyshev smoothers use).
void next(int it, double &alpha, double &beta)
Coefficients for iteration it (0-based). Advances the recurrence.
static constexpr int N
static constexpr double AC
static constexpr double U