peclet-amr 0.2.0
Block-local-Morton AMR octree + collocated cut-cell Navier–Stokes solver (header-only C++20, Kokkos + MPI)
Loading...
Searching...
No Matches
flow.hpp
Go to the documentation of this file.
1// core — device (Kokkos) collocated incompressible Stokes step on a BlockOctree.
2//
3// The device counterpart of oracle::AmrFlow (flow.hpp): the whole cut-cell IBM projection step
4// runs in Kokkos kernels instead of the host-serial gaussSeidel + host projection the drag
5// study found to be the bottleneck. It reuses the host AmrCutCell / AmrPoisson to *build*
6// the operators (geometry, openness, cut stencils — done once), then drives the time step
7// entirely on the device:
8// * momentum predictor — MomentumOp (assembled cut-cell operator) solved with the
9// parallel BiCGStab of momentum.hpp;
10// * pressure projection — the openness Poisson on Multigrid / PCG;
11// * divergence, ABC gradient correction, rotational pressure update — face-CSR kernels
12// (FaceGeom) that mirror AmrPoisson::forEachFaceFull (same 2:1 sub-faces +
13// openness), so D / G / L stay consistent exactly as in the host collocated coupling.
14//
15// Navier–Stokes (setAdvection, ON by default since 2026-10-24) and Stokes (setAdvection(false)):
16// implicit-FOU + explicit SOU/Koren deferred correction, advected by the divergence-free face
17// field uf (built each projection; falls back to ½(u_i+u_j) until the first projection) —
18// conservative (∇·uf = 0).
19//
20#ifndef PECLET_AMR_FLOW_HPP
21#define PECLET_AMR_FLOW_HPP
22
23#include <array>
24#include <chrono>
25#include <cmath>
26#include <cstdio>
27#include <cstdlib>
28#include <memory>
29#include <stdexcept>
30#include <string>
31#include <vector>
32
33#include "peclet/amr/adapt.hpp" // transferField (conservative remap for finishAdapt)
34#include "peclet/amr/advect_recon.hpp" // shared high-order face reconstruction (host+device)
36#include "peclet/amr/cf_scheme.hpp" // pluggable 2:1 C/F schemes (setCfScheme)
37#include "peclet/amr/common.hpp"
39#include "peclet/amr/distributed_adapt.hpp" // transferGradients (distributed finishAdapt)
40#include "peclet/amr/distributed_flow_mg.hpp" // distributed pressure MG (initMpi mode)
42#include "peclet/amr/face_geom.hpp" // FaceGeom (shared with the device assembler)
43#include "peclet/amr/facegeom_assembly.hpp" // assembleFaceGeom (D4/D6)
44#include "peclet/amr/ghost_projection.hpp" // directional ghost overlay (setGhostProjection)
45#include "peclet/amr/ghost_projection_sampled.hpp" // mixed-level sampled overlay (setGhostSampled)
48#include "peclet/amr/momentum_assembly.hpp" // assembleMomentum (D3/D6)
50#include "peclet/amr/pcg.hpp"
52#include "peclet/amr/seam_recon.hpp" // seam-reconstruction tables (docs/amr_cf_convective.md)
54#include "peclet/core/common/host_parallel.hpp"
55#include "peclet/core/common/types.hpp"
56#include "peclet/core/common/view.hpp"
57
58namespace peclet::amr {
59
62inline bool amrEnvFlag(const char* name) {
63 const char* v = std::getenv(name);
64 return v && v[0] && !(v[0] == '0' && v[1] == '\0');
65}
66
67// FaceGeom (the collocated projection's static face-geometry CSR) now lives in face_geom.hpp so the
68// device assembler and this driver share the type without a circular include.
69
71template <int Dim, unsigned Bits, class FluidFn>
72FaceGeom buildFaceGeom(const AmrPoisson<Dim, Bits>& ap, FluidFn&& isFluid) {
73 const Index n = ap.octree().numLeaves();
74 std::vector<Index> start(static_cast<std::size_t>(n) + 1, 0);
75 for (Index i = 0; i < n; ++i) {
76 Index cnt = 0;
77 ap.forEachFaceFull(i, [&](Index, int, int, double, double, double) { ++cnt; });
78 start[static_cast<std::size_t>(i) + 1] = start[static_cast<std::size_t>(i)] + cnt;
79 }
80 const Index nf = start[static_cast<std::size_t>(n)];
81 std::vector<Index> nbr(static_cast<std::size_t>(nf));
82 std::vector<int> axis(static_cast<std::size_t>(nf)), dir(static_cast<std::size_t>(nf));
83 std::vector<double> aArea(static_cast<std::size_t>(nf)), rArea(static_cast<std::size_t>(nf)),
84 dist(static_cast<std::size_t>(nf)), alpha(static_cast<std::size_t>(nf));
85 std::vector<Index> upupI(static_cast<std::size_t>(nf)), upupJ(static_cast<std::size_t>(nf));
86 std::vector<double> invVol(static_cast<std::size_t>(n));
87 std::vector<char> fluid(static_cast<std::size_t>(n));
88 for (Index i = 0; i < n; ++i) {
89 invVol[static_cast<std::size_t>(i)] = 1.0 / ap.cellVolume(i);
90 fluid[static_cast<std::size_t>(i)] = isFluid(i) ? 1 : 0;
91 Index k = start[static_cast<std::size_t>(i)];
92 ap.forEachFaceFull(i, [&](Index j, int ax, int dr, double area, double d, double al) {
93 nbr[static_cast<std::size_t>(k)] = j;
94 axis[static_cast<std::size_t>(k)] = ax;
95 dir[static_cast<std::size_t>(k)] = dr;
96 aArea[static_cast<std::size_t>(k)] = al * area;
97 rArea[static_cast<std::size_t>(k)] = area;
98 dist[static_cast<std::size_t>(k)] = d;
99 alpha[static_cast<std::size_t>(k)] = al;
100 // SOU upstream-of-upwind probes (point neighbour one cell further upstream): if i is the
101 // upwind cell the upstream is across i's −dir face; if j is upwind, across j's +dir face.
102 upupI[static_cast<std::size_t>(k)] = ap.periodicNeighbor(i, ax, -dr);
103 upupJ[static_cast<std::size_t>(k)] = ap.periodicNeighbor(j, ax, dr);
104 ++k;
105 });
106 }
107 FaceGeom g;
108 g.n = n;
109 g.start = toDevice(start, "fg_start");
110 g.nbr = toDevice(nbr, "fg_nbr");
111 g.axis = toDevice(axis, "fg_axis");
112 g.dir = toDevice(dir, "fg_dir");
113 g.alphaArea = toDevice(aArea, "fg_aarea");
114 g.rawArea = toDevice(rArea, "fg_rarea");
115 g.dist = toDevice(dist, "fg_dist");
116 g.alpha = toDevice(alpha, "fg_alpha");
117 g.upupI = toDevice(upupI, "fg_upupi");
118 g.upupJ = toDevice(upupJ, "fg_upupj");
119 g.invVol = toDevice(invVol, "fg_invvol");
120 g.fluid = toDevice(fluid, "fg_fluid");
121 return g;
122}
123
127inline void divergence(const FaceGeom& g, View<const double> u0, View<const double> u1,
128 View<const double> u2, View<double> div) {
129 auto st = g.start;
130 auto nb = g.nbr;
131 auto ax = g.axis;
132 auto dr = g.dir;
133 auto aA = g.alphaArea;
134 auto iv = g.invVol;
135 auto fl = g.fluid;
136 Kokkos::parallel_for(
137 "amr::flow_div", g.n, KOKKOS_LAMBDA(const Index i) {
138 if (!fl(i)) {
139 div(i) = 0.0;
140 return;
141 }
142 double d = 0.0;
143 for (Index k = st(i); k < st(i + 1); ++k) {
144 const int a = ax(k);
145 const double ui = (a == 0) ? u0(i) : (a == 1) ? u1(i) : u2(i);
146 const Index j = nb(k);
147 const double uj = (a == 0) ? u0(j) : (a == 1) ? u1(j) : u2(j);
148 d += aA(k) * dr(k) * 0.5 * (ui + uj);
149 }
150 div(i) = d * iv(i);
151 });
152}
153
160inline void buildFaceField(const FaceGeom& g, View<const double> u0, View<const double> u1,
161 View<const double> u2, View<const double> phi, View<double> uf) {
162 auto st = g.start;
163 auto nb = g.nbr;
164 auto ax = g.axis;
165 auto dr = g.dir;
166 auto di = g.dist;
167 Kokkos::parallel_for(
168 "amr::flow_buildface", g.n, KOKKOS_LAMBDA(const Index i) {
169 for (Index k = st(i); k < st(i + 1); ++k) {
170 const int a = ax(k);
171 const Index j = nb(k);
172 const double ui = (a == 0) ? u0(i) : (a == 1) ? u1(i) : u2(i);
173 const double uj = (a == 0) ? u0(j) : (a == 1) ? u1(j) : u2(j);
174 const double gphi = (dr(k) > 0) ? (phi(j) - phi(i)) / di(k) : (phi(i) - phi(j)) / di(k);
175 uf(k) = 0.5 * (ui + uj) - gphi;
176 }
177 });
178}
179
182inline double divFaceNorm(const FaceGeom& g, View<const double> uf) {
183 auto st = g.start;
184 auto dr = g.dir;
185 auto aA = g.alphaArea;
186 auto iv = g.invVol;
187 auto fl = g.fluid;
188 double s = 0.0;
189 Kokkos::parallel_reduce(
190 "amr::flow_divface", g.n,
191 KOKKOS_LAMBDA(const Index i, double& acc) {
192 if (!fl(i))
193 return;
194 double d = 0.0;
195 for (Index k = st(i); k < st(i + 1); ++k)
196 d += aA(k) * dr(k) * uf(k);
197 d *= iv(i);
198 acc += d * d;
199 },
200 s);
201 return std::sqrt(s);
202}
203
207inline void grad3(const FaceGeom& g, View<const double> f, View<double> gx, View<double> gy,
208 View<double> gz) {
209 auto st = g.start;
210 auto nb = g.nbr;
211 auto ax = g.axis;
212 auto dr = g.dir;
213 auto di = g.dist;
214 auto al = g.alpha;
215 auto fl = g.fluid;
216 Kokkos::parallel_for(
217 "amr::flow_grad3", g.n, KOKKOS_LAMBDA(const Index i) {
218 if (!fl(i)) {
219 gx(i) = gy(i) = gz(i) = 0.0;
220 return;
221 }
222 const double fi = f(i);
223 double gp[3] = {0, 0, 0}, gm[3] = {0, 0, 0};
224 int np[3] = {0, 0, 0}, nm[3] = {0, 0, 0};
225 for (Index k = st(i); k < st(i + 1); ++k) {
226 if (al(k) <= 1e-12)
227 continue;
228 const int a = ax(k);
229 const double gg = (dr(k) > 0) ? (f(nb(k)) - fi) / di(k) : (fi - f(nb(k))) / di(k);
230 if (dr(k) > 0) {
231 gp[a] += gg;
232 ++np[a];
233 } else {
234 gm[a] += gg;
235 ++nm[a];
236 }
237 }
238 double out[3];
239 for (int a = 0; a < 3; ++a) {
240 const double a1 = np[a] ? gp[a] / np[a] : 0.0;
241 const double a2 = nm[a] ? gm[a] / nm[a] : 0.0;
242 out[a] = 0.5 * (a1 + a2);
243 }
244 gx(i) = out[0];
245 gy(i) = out[1];
246 gz(i) = out[2];
247 });
248}
249
257 Index n = 0;
258 View<Index> cell;
259 View<Index> idx;
260 View<double> w;
261};
262
264inline void applyGhostGrad(const GhostGradOverlay& ov, View<const double> f, View<double> gx,
265 View<double> gy, View<double> gz) {
266 if (ov.n == 0)
267 return;
268 auto cell = ov.cell;
269 auto idx = ov.idx;
270 auto w = ov.w;
271 Kokkos::parallel_for(
272 "amr::flow_ghostgrad", ov.n, KOKKOS_LAMBDA(const Index s) {
273 const Index i = cell(s);
274 double g[3];
275 for (int a = 0; a < 3; ++a) {
276 double acc = 0.0;
277 for (int k = 0; k < 3; ++k)
278 acc += w(s * 9 + a * 3 + k) * f(idx(s * 9 + a * 3 + k));
279 g[a] = acc;
280 }
281 gx(i) = g[0];
282 gy(i) = g[1];
283 gz(i) = g[2];
284 });
285}
286
291inline void momRhs(View<const double> uc, View<const double> gradP, View<const double> adv,
292 View<const double> rscale, View<const char> fluid, double idiag, double fc,
293 View<double> b, Index n) {
294 Kokkos::parallel_for(
295 "amr::flow_momrhs", n, KOKKOS_LAMBDA(const Index i) {
296 b(i) = fluid(i) ? (idiag * uc(i) + fc - gradP(i) - adv(i)) * rscale(i) : 0.0;
297 });
298}
299
308inline void buildFou(const FaceGeom& g, View<const double> u0, View<const double> u1,
309 View<const double> u2, double rho, View<const double> rscale,
310 View<double> advDiag, View<double> advCoef, View<const double> uf,
311 bool useFace) {
312 auto st = g.start;
313 auto nb = g.nbr;
314 auto ax = g.axis;
315 auto dr = g.dir;
316 auto ra = g.rawArea;
317 auto iv = g.invVol;
318 auto fl = g.fluid;
319 Kokkos::parallel_for(
320 "amr::flow_buildfou", g.n, KOKKOS_LAMBDA(const Index i) {
321 if (!fl(i)) {
322 advDiag(i) = 0.0;
323 for (Index k = st(i); k < st(i + 1); ++k)
324 advCoef(k) = 0.0;
325 return;
326 }
327 const double rs = rscale(i);
328 double dsum = 0.0;
329 for (Index k = st(i); k < st(i + 1); ++k) {
330 const Index j = nb(k);
331 if (!fl(j)) {
332 advCoef(k) = 0.0;
333 continue;
334 }
335 const int a = ax(k);
336 const double ui = (a == 0) ? u0(i) : (a == 1) ? u1(i) : u2(i);
337 const double uj = (a == 0) ? u0(j) : (a == 1) ? u1(j) : u2(j);
338 const double velOut = useFace ? dr(k) * uf(k) : dr(k) * 0.5 * (ui + uj);
339 const double w = rs * rho * ra(k) * velOut * iv(i);
340 if (velOut < 0.0) {
341 advCoef(k) = w; // inflow → off-diagonal toward upstream neighbour j
342 } else {
343 advCoef(k) = 0.0;
344 dsum += w; // outflow → diagonal
345 }
346 }
347 advDiag(i) = dsum;
348 });
349}
350
365template <class FldFn>
366KOKKOS_INLINE_FUNCTION double advectedFaceValue(const SeamView& sv, Index k, bool upIsI,
367 double phiUpUp, double phiUp, double phiDown,
368 double distK, int advScheme, const FldFn& fld) {
369 const Index s = sv.on ? sv.seam(k) : Index(-1);
370 if (s < 0)
371 return hoFaceValue(phiUpUp, phiUp, phiDown, advScheme); // today's reconstruction, bit for bit
372 const Index rs = upIsI ? sv.sampI(s) : sv.sampJ(s); // φ_U* (case 1)
373 const Index ru = upIsI ? sv.uuRecI(s) : sv.uuRecJ(s); // φ_UU* (cases 2/3)
374 const Index rd = upIsI ? sv.sampJ(s) : sv.sampI(s); // φ_D*, Koren only
375 const double d1 = upIsI ? sv.d1I(s) : sv.d1J(s);
376 const double upStar = (rs >= 0) ? sv.gather(rs, fld) : phiUp;
377 // No upstream record: the probe is at the upwind cell's own level (or was withheld by a gate),
378 // which is the equal-spacing `dUU = 2·d1` today's formula already assumes.
379 double uu = phiUpUp, dUU = 2.0 * d1;
380 if (ru >= 0) {
381 uu = sv.gather(ru, fld);
382 dUU = sv.recDist(ru);
383 }
384 const double downStar = (advScheme != 0 && rd >= 0) ? sv.gather(rd, fld) : phiDown;
385 return hoFaceValueSeam(uu, phiUp, upStar, downStar, d1, dUU, distK, advScheme);
386}
387
395inline void deferredSou(const FaceGeom& g, View<const double> u0, View<const double> u1,
396 View<const double> u2, int comp, double rho, int advScheme,
397 View<double> defc, View<const double> uf, bool useFace, bool seamOn) {
398 auto st = g.start;
399 auto nb = g.nbr;
400 auto ax = g.axis;
401 auto dr = g.dir;
402 auto ra = g.rawArea;
403 auto ds = g.dist;
404 auto iv = g.invVol;
405 auto fl = g.fluid;
406 auto uiP = g.upupI;
407 auto ujP = g.upupJ;
408 const SeamView sv = makeSeamView(g, seamOn);
409 Kokkos::parallel_for(
410 "amr::flow_defsou", g.n, KOKKOS_LAMBDA(const Index i) {
411 if (!fl(i)) {
412 defc(i) = 0.0;
413 return;
414 }
415 auto fld = [&](Index c) { return (comp == 0) ? u0(c) : (comp == 1) ? u1(c) : u2(c); };
416 double sou = 0.0, fou = 0.0;
417 for (Index k = st(i); k < st(i + 1); ++k) {
418 const Index j = nb(k);
419 if (!fl(j))
420 continue;
421 const int a = ax(k);
422 const double uai = (a == 0) ? u0(i) : (a == 1) ? u1(i) : u2(i);
423 const double uaj = (a == 0) ? u0(j) : (a == 1) ? u1(j) : u2(j);
424 const double velOut = useFace ? dr(k) * uf(k) : dr(k) * 0.5 * (uai + uaj);
425 const bool upIsI = velOut > 0.0;
426 const Index up = upIsI ? i : j;
427 const Index down = upIsI ? j : i;
428 const Index upup = upIsI ? uiP(k) : ujP(k);
429 const double phiUp = fld(up);
430 const double phiUpUp = (upup >= 0 && fl(upup)) ? fld(upup) : phiUp;
431 const double phiDown = fld(down);
432 const double phiFace = advectedFaceValue(sv, k, upIsI, phiUpUp, phiUp, phiDown, ds(k),
433 advScheme, fld); // shared recon
434 sou += ra(k) * velOut * phiFace;
435 fou += ra(k) * velOut * fld(up); // FOU flux = velOut · upwind value
436 }
437 defc(i) = rho * iv(i) * (sou - fou); // ρ·(SOU − FOU), unscaled
438 });
439}
440
443inline void advectExplicit(const FaceGeom& g, View<const double> u0, View<const double> u1,
444 View<const double> u2, int comp, double rho, int advScheme,
445 View<double> defc, View<const double> uf, bool useFace, bool seamOn) {
446 auto st = g.start;
447 auto nb = g.nbr;
448 auto ax = g.axis;
449 auto dr = g.dir;
450 auto ra = g.rawArea;
451 auto ds = g.dist;
452 auto iv = g.invVol;
453 auto fl = g.fluid;
454 auto uiP = g.upupI;
455 auto ujP = g.upupJ;
456 const SeamView sv = makeSeamView(g, seamOn);
457 Kokkos::parallel_for(
458 "amr::flow_advexpl", g.n, KOKKOS_LAMBDA(const Index i) {
459 if (!fl(i)) {
460 defc(i) = 0.0;
461 return;
462 }
463 auto fld = [&](Index c) { return (comp == 0) ? u0(c) : (comp == 1) ? u1(c) : u2(c); };
464 double sou = 0.0;
465 for (Index k = st(i); k < st(i + 1); ++k) {
466 const Index j = nb(k);
467 if (!fl(j))
468 continue;
469 const int a = ax(k);
470 const double uai = (a == 0) ? u0(i) : (a == 1) ? u1(i) : u2(i);
471 const double uaj = (a == 0) ? u0(j) : (a == 1) ? u1(j) : u2(j);
472 const double velOut = useFace ? dr(k) * uf(k) : dr(k) * 0.5 * (uai + uaj);
473 const bool upIsI = velOut > 0.0;
474 const Index up = upIsI ? i : j;
475 const Index down = upIsI ? j : i;
476 const Index upup = upIsI ? uiP(k) : ujP(k);
477 const double phiUp = fld(up);
478 const double phiUpUp = (upup >= 0 && fl(upup)) ? fld(upup) : phiUp;
479 const double phiDown = fld(down);
480 const double phiFace = advectedFaceValue(sv, k, upIsI, phiUpUp, phiUp, phiDown, ds(k),
481 advScheme, fld); // shared recon
482 sou += ra(k) * velOut * phiFace;
483 }
484 defc(i) = rho * sou * iv(i); // ρ·SOU (fully explicit)
485 });
486}
487
489inline void correct(View<double> uc, View<const double> gphi, View<const char> fluid, Index n) {
490 Kokkos::parallel_for(
491 "amr::flow_correct", n, KOKKOS_LAMBDA(const Index i) {
492 if (fluid(i))
493 uc(i) -= gphi(i);
494 });
495}
496
498inline void presUpdate(View<double> p, View<const double> phi, View<const double> div,
499 View<const char> fluid, double rho_dt, double mu, Index n) {
500 Kokkos::parallel_for(
501 "amr::flow_presupd", n, KOKKOS_LAMBDA(const Index i) {
502 if (fluid(i))
503 p(i) += rho_dt * phi(i) - mu * div(i);
504 });
505}
506
507// ===========================================================================
508// AmrFlow — collocated Stokes projection step, fully on device.
509// ===========================================================================
510template <unsigned Bits = 21u>
511class AmrFlow {
512 public:
514
516 void init(const Octree& t, Real h0, Vec<3> origin = Vec<3>{}) {
517 init(t, detail::filledVec<3>(h0), origin);
518 }
519 void init(const Octree& t, const Vec<3>& h0, Vec<3> origin = Vec<3>{}) {
520 t_ = &t;
521 h0_ = h0;
522 origin_ = origin;
523 dist_ = nullptr; // single-rank unless initMpi is used
524 }
525
535 init(d.local(), d.h0(), d.globalGeometry().origin);
536 dist_ = &d;
537 }
538
541 Vec<3> betaPerAxis() const {
542 Vec<3> b{};
543 for (int d = 0; d < 3; ++d)
544 b[d] = mu_ / (h0_[d] * h0_[d]);
545 return b;
546 }
547 void setDensity(double rho) { rho_ = rho; }
548 void setViscosity(double mu) { mu_ = mu; }
549 void setDt(double dt) { dt_ = dt; }
550 void setBodyForce(double fx, double fy, double fz) { f_ = {fx, fy, fz}; }
552 void setPressurePCG(bool on) { presPCG_ = on; }
567 void setGhostGradient(bool on) { ghostGrad_ = on; }
597 void setApertureOrder(int order) { apertureOrder_ = order; }
598 void setGhostProjection(bool on, int matrixOrder = 2, int rhsOrder = 2) {
599 ghostProjReq_ = on ? 1 : 0; // explicit selection disables the AUTO default
600 gpMatrixOrder_ = matrixOrder;
601 gpRhsOrder_ = rhsOrder;
602 }
603
614 void setGhostSampled(bool on, double rho = 2.2, long maxSamples = 0) {
615 ghostSampledReq_ = on ? 1 : 0;
616 gpsRho_ = rho;
617 gpsMaxN_ = maxSamples;
618 }
619
632 void setCfScheme(int scheme) { cfScheme_ = static_cast<CfScheme>(scheme); }
640 void setAdvection(bool on) { advect_ = on; }
643 void setImplicitAdvection(bool on) { implicitFou_ = on; }
645 void setAdvectionScheme(int s) { advScheme_ = s; }
655 void setMomentumTol(double tol) { momTol_ = tol; }
662 void setPressureTol(double tol) { presTol_ = tol; }
671 void setUfAdvection(bool on) { ufAdvect_ = on; }
680 void setSeamReconstruction(bool on) { seamRecon_ = on; }
688 void setMomentumMG(bool on) { momMGon_ = on; }
689
694 void setVelocityMGStaircase(bool on) { useStaircaseMG_ = on; }
699 void setVelocityMGMinCoarse(Index m) { mgMinCoarse_ = m; }
703 void setMomentumGS(bool on) { momGS_ = on; }
704
717 void setMomentumMGSolver(bool on) { momMGSolver_ = on; }
718
724 void setOuterIterations(int n, double tol = 1e-6) {
725 outerIters_ = (n < 1) ? 1 : n;
726 outerTol_ = tol;
727 }
728
731 template <class SdfFn>
732 void setSolid(SdfFn&& sdfFn) {
733 const Index n = t_->numLeaves();
734 SetupProfiler prof(n);
735 buildHostOperators(sdfFn, prof);
736 GhostOverlay hov;
738 buildProjectionOverlay(sdfFn, hov, hovS, prof);
739 buildPressureHierarchy(sdfFn, prof);
740
741 // Device assembly (D6): the static cut-cell momentum operator CSR and the collocated face
742 // geometry are assembled ON THE DEVICE (assembleMomentum / assembleFaceGeom), and the
743 // pressure MG operators are device-assembled per level (Multigrid D5) — so no host CSR walk and
744 // no operator round-trip. Each is bit-for-bit identical to the host assembler on OpenMP (locked
745 // in test_amr_momentum / test_amr_facegeom), so the flow result is unchanged. A shared device
746 // octree view backs both assemblers.
747 // DISTRIBUTED: assemble on the HOST through the resolver seam instead (the device walkers
748 // cannot resolve cross-block probes) and upload — same parity-locked builders, ghost
749 // columns included.
751 if (!dist_)
752 ov.upload(*t_);
753 assembleMomentumOperator(n, ov, prof);
754 buildVelocityMG(n);
755 prof.phase("velocity MG build");
756 buildFaceGeometry(n, ov, prof);
757 buildCfOverlays(n);
758 prof.phase("cf overlays");
759 if (ghostProj_)
760 uploadGhostOverlays(sdfFn, n, hov, hovS);
761 allocateStepState(n);
762 n_ = n;
763 ready_ = true;
764 prof.phase("overlays upload + state alloc");
765 }
766
767 private:
768 // ---- setSolid phases (in call order) ---------------------------------------------------------
769 // Phase profiler (PECLET_AMR_PROFILE_SETUP=1): setSolid is the whole setup cost at bed
770 // scale (measured 127 us/leaf single-threaded, [[performance-sota-yardstick]]) — the
771 // per-phase breakdown is what any optimization must start from.
772 struct SetupProfiler {
773 bool on;
774 Index n;
775 std::chrono::steady_clock::time_point t0;
776 explicit SetupProfiler(Index nLeaves)
777 : on([] {
778 const char* e = std::getenv("PECLET_AMR_PROFILE_SETUP");
779 return e && e[0] == '1';
780 }())
781 , n(nLeaves)
782 , t0(std::chrono::steady_clock::now()) {}
783 void phase(const char* name) {
784 if (!on)
785 return;
786 Kokkos::fence();
787 auto now = std::chrono::steady_clock::now();
788 double ms = std::chrono::duration<double, std::milli>(now - t0).count();
789 std::fprintf(stderr, "[setSolid] %-28s %9.1f ms (%6.1f us/leaf)\n", name, ms,
790 1e3 * ms / static_cast<double>(n));
791 t0 = std::chrono::steady_clock::now();
792 }
793 };
794
796 template <class SdfFn>
797 void buildHostOperators(SdfFn& sdfFn, SetupProfiler& prof) {
798 const Index n = t_->numLeaves();
799 // Host operator build (geometry, openness, cut stencils) — same as oracle::AmrFlow::setSolid.
800 mom_.init(*t_, h0_, origin_);
801 pres_.init(*t_, h0_);
802 pres_.setOrigin(origin_);
803 prof.phase("mom.init + pres.init");
804 // Resolve the projection mode. DEFAULT SWITCH (2026-08-25, user decision): AUTO = the
805 // GHOST (fluid-only) projection — family-free/stable/unique (see the setter doc) — falling
806 // back to the aperture projection with a stderr notice when the finest band is too thin for
807 // the overlay (probed below; the July AUTO arm restored, now unconditional). Explicit
808 // setGhostProjection(true/false) pins the scheme (band violations then THROW as before).
809 // The overlay is built below (it needs only mom_'s sdf samples + pres_'s topology walk,
810 // no openness).
811 const bool wantGhost = (ghostProjReq_ != 0); // explicit on (1) or AUTO (-1)
812 ghostProj_ = wantGhost; // provisional; AUTO may fall back below
813 ghostSampled_ = (ghostSampledReq_ == 1) && wantGhost;
814 // D1/D2 (docs/amr_march_perf_and_distributed_plan.md): the mixed-level cut band is
815 // DISTRIBUTED. The sampled builders probe through the LeafHalo seam inside
816 // prepareDistributed's fixpoint (D1) and their least-squares clouds read ghost slots like any
817 // other CSR the step consumes (D2), so there is no single-rank guard left. Acceptance:
818 // np=1 bitwise, np=2,4 within the established decomposition-independence class
819 // (tests/test_amr_distributed_seam_mpi.cpp).
820 if (dist_) {
821 // Distributed: install the resolver seams and run every prober to the miss-collect
822 // fixpoint (docs/amr_distributed_flow.md). Freezes the ±2 halo, leaves mom_ FULLY built
823 // (its final round ran with every ghost resolved) and the solver hooks installed.
824 prepareDistributed(sdfFn);
825 } else {
826 nExt_ = n;
827 allred_ = {};
828 momSolver_.setDistributed({}, {}, 0);
829 pcg_.setDistributed({}, {}, 0);
830 mom_.build(sdfFn, /*idiag=*/rho_ / dt_, /*beta=*/betaPerAxis());
831 }
832 prof.phase("mom.build (SDF+cut stencils)");
833 }
834
836 template <class SdfFn>
837 void buildProjectionOverlay(SdfFn& sdfFn, GhostOverlay& hov, GhostOverlaySampled& hovS,
838 SetupProfiler& prof) {
839 if (ghostSampled_) { // mixed-level cut band: sample-slot overlay, no band-margin probe
840 const auto gfine = globalFineExtent();
841 hovS = buildGhostOverlaySampled(*t_, pres_, sdfFn, gpMatrixOrder_, gpRhsOrder_, origin_,
842 &gfine, shiftD_, /*discovery=*/false, gpsRho_, gpsMaxN_);
843 prof.phase("buildGhostOverlaySampled");
844 } else if (ghostProj_) { // probe the band margin; explicit request throws on violation, AUTO
845 // falls
846 bool viol = false;
847 hov = buildGhostOverlay(*t_, pres_, mom_.sdfCRaw(), gpMatrixOrder_, gpRhsOrder_, &viol);
848 if (dist_) {
849 // COLLECTIVE band-margin decision: the flag is agreed across ranks before anyone
850 // commits (one rank throwing/falling back alone would deadlock the MG collectives).
851 int lv = viol ? 1 : 0, gv = 0;
852 MPI_Allreduce(&lv, &gv, 1, MPI_INT, MPI_LOR, dist_->comm());
853 viol = gv != 0;
854 }
855 if (viol) {
856 if (ghostProjReq_ == 1)
857 throw std::runtime_error(
858 "amr ghost projection: an overlay row's ±2 closure reach crosses a 2:1 level "
859 "boundary — widen the refineToSdf band margin");
860 ghostProj_ = false; // AUTO: fall back to the aperture projection
861 fprintf(stderr,
862 "peclet::core AmrFlow: AUTO scheme fell back to the aperture projection (the "
863 "finest band is too thin for the ghost overlay). Select explicitly with "
864 "setGhostProjection to silence this notice.\n");
865 }
866 }
867 }
868
871 template <class SdfFn>
872 void buildPressureHierarchy(SdfFn& sdfFn, SetupProfiler& prof) {
873 if (ghostProj_) {
874 // Ghost projection: the pressure geometry is the BINARY openness on the unchanged MG
875 // rails; the closure physics lives in the overlay (built above). Sampled mode: the
876 // level-aware canonical rule (the sampled overlay's face states are FORCED to it — the
877 // overlay-closed <=> binary-closed invariant).
878 if (ghostSampled_) {
879 auto binFn = makeBinaryOpenFnMixed(
880 *t_, pres_, [&sdfFn](const Vec<3>& p) { return sdfFn(p); }, h0_, origin_, shiftD_);
881 pres_.buildOpenness(binFn);
882 prof.phase("buildOpenness (mixed)");
883 // D1: the pressure hierarchy has to be the DISTRIBUTED one when a seam is installed —
884 // gpOp0() reads presMGD_ whenever dist_ is set, so building presMG_ here left the ghost
885 // solver pointing at an empty operator.
886 if (dist_)
887 presMGD_.build(*dist_, h0_, binFn, &dhalo_, /*liftRoot=*/true, presBottomExtent_);
888 else
889 presMG_.build(*t_, h0_, binFn, /*periodic=*/true, /*immersedWall=*/false,
890 /*liftRoot=*/true, presBottomExtent_);
891 prof.phase("presMG.build");
892 } else {
893 auto binFn = makeBinaryOpenFn([&sdfFn](const Vec<3>& p) { return sdfFn(p); }, h0_);
894 pres_.buildOpenness(binFn);
895 if (dist_)
896 presMGD_.build(*dist_, h0_, binFn, &dhalo_, /*liftRoot=*/true, presBottomExtent_);
897 else
898 presMG_.build(*t_, h0_, binFn, /*periodic=*/true, /*immersedWall=*/false,
899 /*liftRoot=*/true, presBottomExtent_);
900 }
901 ghostGrad_ = true; // the directional gradient is part of the scheme
902 // Fragmentation guard: pockets outside the main binary component are decoupled (see
903 // findPocketCells) — folded into maskC_ below and hidden from the directional gradients.
904 // Single-rank host BFS only: the DISTRIBUTED label-propagation guard is a rung-6 item
905 // (a rank-local BFS would mislabel components that span ranks), so multi-rank runs are
906 // unprotected on fragmenting geometries until it lands.
907 gpPocket_ = dist_ ? std::vector<char>{} : findPocketCells(*t_, pres_, mom_.sdfCRaw());
908 prof.phase("findPocketCells");
909 } else {
910 gpPocket_.clear();
911 auto openFn = [&](const Vec<3>& fc, int axis) { return faceFrac(sdfFn, fc, axis); };
912 pres_.buildOpenness(openFn);
913 if (dist_)
914 presMGD_.build(*dist_, h0_, openFn, &dhalo_, /*liftRoot=*/true, presBottomExtent_);
915 else
916 presMG_.build(*t_, h0_, openFn, /*periodic=*/true, /*immersedWall=*/false,
917 /*liftRoot=*/true, presBottomExtent_);
918 }
919 // What solves the coarsest level (docs/amr_mg_depth.md §6.6): `auto` engages the agglomerated
920 // GraphAMG-PCG bottom only where the ladder ran out above `presBottomExtent_`.
921 if (dist_)
922 presMGD_.setBottom(presBottom_);
923 else
924 presMG_.setBottom(presBottom_);
925 // Singular periodic pressure: per-level nullspace projection.
926 if (dist_) {
927 presMGD_.setRemoveMean(true);
928 pcg_.setDistributed([this](View<double> v) { presMGD_.sync(0, v); }, allred_,
929 presMGD_.extendedSize(0));
930 } else {
931 presMG_.setRemoveMean(true);
932 }
933 prof.phase("nullspace setup");
934 }
935
937 void assembleMomentumOperator(Index n, const BlockOctreeView<3, Bits>& ov, SetupProfiler& prof) {
938 if (dist_) {
939 auto A = mom_.assembleOperator();
940 momOp_ = MomentumOp{};
941 momOp_.n = n;
942 momOp_.diag = toDevice(A.diag, "mo_diag");
943 momOp_.faceStart = toDevice(A.start, "mo_start");
944 momOp_.faceNbr = toDevice(A.nbr, "mo_nbr");
945 momOp_.faceCoef = toDevice(A.coef, "mo_coef");
946 } else {
947 momOp_ = assembleMomentum<Bits>(mom_, ov); // static Stokes operator (hasAdv stays false)
948 prof.phase("assembleMomentum (device)");
949 }
950 }
951
953 void buildVelocityMG(Index n) {
954 // Velocity multigrid (momentum preconditioner): the Galerkin hierarchy A_c = R·A·P built
955 // directly from the exact assembled momentum CSR. Consistent with the fine cut-cell
956 // operator by construction (inherits the ξ-overlay + D_rescale row scaling; a coarse cell
957 // of all-solid children stays an identity row). It only changes the preconditioner (the
958 // BiCGStab matvec is the exact operator) ⇒ same converged solution, but the iteration
959 // count stays ~flat with N instead of growing like the Jacobi-preconditioned BiCGStab.
960 // Build the chosen momentum-MG: Galerkin (MomentumMG) by default, or the rediscretized
961 // staircase (VelocityMG) — both from the static Stokes operator, once.
962 // DISTRIBUTED: the Galerkin MG becomes RANK-LOCAL (additive-Schwarz preconditioner): the
963 // local rows of the exact operator with the ghost COLUMNS dropped. At np=1 nothing is
964 // dropped, so the preconditioner — and hence the whole step — stays bit-identical to the
965 // single-rank path; at np>1 it is a block preconditioner (iterations may grow with np,
966 // the converged step is unchanged — the preconditioner never moves the solution). The
967 // EXACT cross-rank Galerkin RAP is the documented follow-up
968 // (docs/amr_distributed_flow.md §4c); the staircase variant is single-rank-only for now
969 // (distributed falls back to Jacobi-with-halo preconditioning).
970 if (momMGon_ && dist_ && !useStaircaseMG_) {
971 auto A = mom_.assembleOperator();
972 std::vector<Index> lstart(1, 0);
973 std::vector<Index> lnbr;
974 std::vector<double> lcoef;
975 for (Index i = 0; i < n; ++i) {
976 for (Index k = A.start[static_cast<std::size_t>(i)];
977 k < A.start[static_cast<std::size_t>(i) + 1]; ++k)
978 if (A.nbr[static_cast<std::size_t>(k)] < n) { // drop ghost columns (Schwarz cut)
979 lnbr.push_back(A.nbr[static_cast<std::size_t>(k)]);
980 lcoef.push_back(A.coef[static_cast<std::size_t>(k)]);
981 }
982 lstart.push_back(static_cast<Index>(lnbr.size()));
983 }
984 momMG_.build(*t_, A.diag, lstart, lnbr, lcoef);
985 momMG_.setGaussSeidel(momGS_);
986 } else if (momMGon_ && !dist_) {
987 if (useStaircaseMG_) {
988 std::vector<double> kap(static_cast<std::size_t>(n));
989 std::vector<char> fl(static_cast<std::size_t>(n)), cu(static_cast<std::size_t>(n));
990 for (Index i = 0; i < n; ++i) {
991 kap[static_cast<std::size_t>(i)] = mom_.kappa(i);
992 fl[static_cast<std::size_t>(i)] = mom_.isFluid(i) ? 1 : 0;
993 cu[static_cast<std::size_t>(i)] = mom_.isCut(i) ? 1 : 0;
994 }
995 velMG_.build(*t_, h0_, rho_ / dt_, mu_, momOp_, kap, fl, cu, mgMinCoarse_);
996 velMG_.setGaussSeidel(momGS_);
997 } else {
998 // The Galerkin RAP hierarchy is a host triple-product over the fine CSR, so it needs the
999 // operator on the host; assemble it there for the MG build only (bit-identical to momOp_).
1000 auto A = mom_.assembleOperator();
1001 momMG_.build(*t_, A.diag, A.start, A.nbr, A.coef);
1002 momMG_.setGaussSeidel(momGS_);
1003 }
1004 }
1005 }
1006
1008 void buildFaceGeometry(Index n, const BlockOctreeView<3, Bits>& ov, SetupProfiler& prof) {
1009 std::vector<char> fluidVec(static_cast<std::size_t>(n));
1010 for (Index i = 0; i < n; ++i)
1011 fluidVec[static_cast<std::size_t>(i)] = mom_.isFluid(i) ? 1 : 0;
1012 if (dist_) {
1013 // Host walker through the resolver seam (nbr/upup may be ghost slots), then EXTEND the
1014 // fluid flags over the ghost tail — the advection kernels read fl(j)/fl(upup) at ghost
1015 // slots (mom_.fluidRaw() carries the ghost metadata filled from the world SdfFn).
1016 geom_ = buildFaceGeom(pres_, [&](Index i) { return mom_.isFluid(i); });
1017 geom_.fluid = toDevice(mom_.fluidRaw(), "fg_fluid_ext");
1018 } else {
1019 geom_ = assembleFaceGeom<Bits>(pres_, fluidVec, ov);
1020 }
1021 prof.phase("assembleFaceGeom");
1022 std::vector<double> rs(static_cast<std::size_t>(n));
1023 for (Index i = 0; i < n; ++i)
1024 rs[static_cast<std::size_t>(i)] = mom_.rhsScale(i);
1025 rscale_ = toDevice(rs, "df_rscale");
1026 fluid_ = geom_.fluid;
1027 if (ghostGrad_ && !ghostSampled_)
1028 buildGhostGradOverlay();
1029 else
1030 gc_ = GhostGradOverlay{}; // sampled mode: the CSR overlay gcS_ owns all cut cells
1031 // C/F interface scheme overlays (cf_scheme.hpp): the same host builders the oracle uses
1032 }
1033
1035 void buildCfOverlays(Index n) {
1036 // (parity by construction), uploaded once. Momentum delta = ×μ on the α=1 velocity geometry.
1037 // The per-FACE C/F gate (docs/amr_cf_flux_gate.md §6.1, §6.4) needs `regular = fluid && !cut`
1038 // at GHOST slots too: the gate is a property of the FACE, and a 2:1 sub-face at a block seam
1039 // has one of its two cells on another rank. `cut(g)` cannot be recomputed here — it is the SDF
1040 // sign at g's SIX face-neighbour centres, and the discovery fixpoint registers the C/F
1041 // tangential reach and the face sweep's ±2 upstream reach, not those six — so the OWNER's flag
1042 // is exchanged instead. One `syncScalar` on an nExt-sized View, exact by definition, and
1043 // decomposition-independent because the owner's own SDF samples are.
1044 std::vector<char> cfRegular(static_cast<std::size_t>(nExt_), 0);
1045 for (Index i = 0; i < n; ++i)
1046 cfRegular[static_cast<std::size_t>(i)] = (mom_.isFluid(i) && !mom_.isCut(i)) ? 1 : 0;
1047 if (dist_) {
1048 std::vector<double> rx(static_cast<std::size_t>(nExt_), 0.0);
1049 for (Index i = 0; i < n; ++i)
1050 rx[static_cast<std::size_t>(i)] = cfRegular[static_cast<std::size_t>(i)] ? 1.0 : 0.0;
1051 View<double> rv = toDevice(rx, "cf_regular");
1052 syncScalar(rv);
1053 const std::vector<double> rh = toVector(rv);
1054 for (Index s = n; s < nExt_; ++s)
1055 cfRegular[static_cast<std::size_t>(s)] = (rh[static_cast<std::size_t>(s)] > 0.5) ? 1 : 0;
1056 }
1057 // Programming-error guard (§6.4): a builder that asks for a slot the flag was never filled for
1058 // is a bug in the discovery, not a configuration the solver should tolerate silently.
1059 auto regularOk = [&](Index s) {
1060 if (s < 0 || s >= static_cast<Index>(cfRegular.size()))
1061 throw std::logic_error("peclet::amr: C/F regular flag queried outside [0, nExt)");
1062 return cfRegular[static_cast<std::size_t>(s)] != 0;
1063 };
1064 cfCutFaces_ = countCfCutFaces(pres_, *t_, regularOk, [&](Index s) { return mom_.isFluid(s); });
1065 if (cfScheme_ != CfScheme::standard) {
1066 auto fluidOk = [&](Index i) { return mom_.isFluid(i); };
1067 auto rowRegular = [&](Index i) { return mom_.isFluid(i) && !mom_.isCut(i); };
1068 auto lapD = buildCfLapDelta(mom_.lap(), *t_, mu_, rowRegular, fluidOk, cfScheme_);
1069 // The projection family (D, the ABC gradient substitution, and the advecting face field)
1070 // is gated PER FACE, never per row: `cfFace(i, j) = level mismatch && regular(i) &&
1071 // regular(j)`, one predicate through one emitter (docs/amr_cf_flux_gate.md). A face flux is
1072 // ONE number shared by two cells, so a gate that is a property of a cell cannot be
1073 // conservative — under the old row gate the regular cell booked the C/F correction in its
1074 // constraint, the cut cell did not, and uf carried it for both: a permanent mass source at
1075 // the cut cell, ‖D(Δvel) − Δ_cfDiv‖ = 2.018e-01 against ‖div(uf)‖ = 2.016e-01 on a mesh
1076 // whose cut band meets the level boundary. Cut rows still receive no delta (the 2026-08-27
1077 // stability fix — 2 of 12 throat-graded meshes marched to k~1e12 with cut rows in cfDiv —
1078 // is retained in full by the same predicate, since a cut row has no passing face); what
1079 // changed is that the REGULAR row across a cut-adjacent 2:1 face no longer receives it
1080 // either, and that face reverts to the standard two-point value. Inert by geometry on any
1081 // uniform or finest-band mesh (cut cells there have no C/F face); `numCfCutFaces()` counts
1082 // the sub-faces where it is not.
1083 auto divD = buildCfDivDelta(pres_, *t_, regularOk, fluidOk, cfScheme_);
1084 auto gd = buildCfGradDelta(pres_, *t_, regularOk, fluidOk, cfScheme_);
1085 auto ufd = buildCfUfDelta(pres_, *t_, regularOk, fluidOk, cfScheme_);
1086 // Distributed diagnostic (numCfGhostColumns): how many overlay entries read a GHOST slot.
1087 // It is the observable that says the seam is actually exercised — a build that silently
1088 // fell back to the raw coarse value at every block boundary reports zero.
1089 cfGhostCols_ = 0;
1090 auto countGhost = [&](const std::vector<Index>& col) {
1091 for (Index c : col)
1092 if (c >= n)
1093 ++cfGhostCols_;
1094 };
1095 countGhost(lapD.slot);
1096 countGhost(divD.slot);
1097 for (int a = 0; a < 3; ++a)
1098 countGhost(gd[static_cast<std::size_t>(a)].slot);
1099 countGhost(ufd.vel.slot);
1100 cfMom_ = uploadCfCsr(lapD, "cf_mom");
1101 cfDiv_ = uploadCfCompCsr(divD, "cf_div");
1102 for (int a = 0; a < 3; ++a)
1103 cfGrad_[static_cast<std::size_t>(a)] =
1104 uploadCfCsr(gd[static_cast<std::size_t>(a)], "cf_grad");
1105 cfUfVel_ = uploadCfCompCsr(ufd.vel, "cf_ufvel");
1106 // The convective flux at a 2:1 seam (ROADMAP B5, docs/amr_cf_convective.md §5.2): the
1107 // descriptors + records the two advective kernels reconstruct the ADVECTED value from.
1108 // It reuses the SAME per-face gate (`regularOk`) and the SAME tangential sample operator
1109 // (`cfAppendStencil`, quadratic — §5.1 Q-A: one such operator suite-wide) as the four
1110 // overlays above, which is why it is built here rather than beside the FaceGeom.
1111 //
1112 // It RIDES THE C/F SCHEME (the design note pins the stencil — "cfAppendStencil ...
1113 // scheme = quadratic" §5.1 — but not this gating): with CfScheme::standard the whole
1114 // projection family takes the raw coarse value at a 2:1 face, and a quadratic tangential
1115 // sample in the advection alone would be a closure the rest of the operator does not
1116 // share. It is also what keeps the distributed probe story exact — probeCfScheme() and
1117 // probeSeamLayer() run under the same condition, so every coordinate this builder asks
1118 // for is already in the halo registry.
1119 uploadSeamRecon(buildSeamRecon(pres_, regularOk, fluidOk, CfScheme::quadratic));
1120 } else {
1121 cfGhostCols_ = 0;
1122 cfMom_ = CfCsrDev{};
1123 cfDiv_ = CfCompCsrDev{};
1124 for (int a = 0; a < 3; ++a)
1125 cfGrad_[static_cast<std::size_t>(a)] = CfCsrDev{};
1126 cfUfVel_ = CfCompCsrDev{};
1127 clearSeamRecon();
1128 }
1129 }
1130
1133 template <class SdfFn>
1134 void uploadGhostOverlays(SdfFn& sdfFn, Index n, const GhostOverlay& hov,
1135 const GhostOverlaySampled& hovS) {
1136 // Closure overlay (pre-built in the mode-resolve step above) + the coupled-subspace mask
1137 // for the BiCGStab projection. Sampled mode uploads the sample-slot overlay instead (the
1138 // classic gpOv_ stays empty — every delta site calls both, empties no-op).
1139 gpOv_ = ghostSampled_ ? GhostOverlayDev{} : uploadGhostOverlay(hov);
1140 gpOvS_ = ghostSampled_ ? uploadGhostOverlaySampled(hovS) : GhostOverlaySampledDev{};
1141 const GhostOverlay& rows = ghostSampled_ ? hovS.base : hov;
1142 std::vector<double> mc(static_cast<std::size_t>(n), 0.0);
1143 for (Index i = 0; i < n; ++i)
1144 mc[static_cast<std::size_t>(i)] =
1145 (mom_.isFluid(i) && !(!gpPocket_.empty() && gpPocket_[static_cast<std::size_t>(i)]))
1146 ? 1.0
1147 : 0.0;
1148 for (Index r = 0; r < rows.n; ++r)
1149 if (!rows.coupled[static_cast<std::size_t>(r)])
1150 mc[static_cast<std::size_t>(rows.cell[static_cast<std::size_t>(r)])] = 0.0;
1151 maskC_ = toDevice(mc, "gp_maskc");
1152 // Sampled mode: momentum ξ-row seam correction (host CSR folds 1/rscale for the oracle's
1153 // pre-rscale source; the device adds POST-rscale via cfApply, so re-fold rscale per row)
1154 // + the CSR directional-gradient overlay (cascade over sample functionals; classic
1155 // same-level fallback on cut cells without a row — the oracle's gradP split).
1156 if (ghostSampled_) {
1157 CfCsr msd = buildMomSeamDelta(hovS, *t_, pres_, mom_, sdfFn, origin_, rho_ / dt_, mu_,
1158 /*nSkipped=*/nullptr, shiftD_);
1159 for (Index i = 0; i < n; ++i) {
1160 const double rs = mom_.rhsScale(i);
1161 for (Index k = msd.start[static_cast<std::size_t>(i)];
1162 k < msd.start[static_cast<std::size_t>(i) + 1]; ++k)
1163 msd.coef[static_cast<std::size_t>(k)] *= rs;
1164 }
1165 gpsMomDelta_ = uploadCfCsr(msd, "gps_momdelta");
1166 auto classicOk = [&](Index j, Index i) {
1167 return j >= 0 && mom_.isFluid(j) && pres_.levelOf(j) == pres_.levelOf(i) &&
1168 !(!gpPocket_.empty() && j < n && gpPocket_[static_cast<std::size_t>(j)]);
1169 };
1170 gcS_ = uploadGhostGradCsr(
1171 buildSampledGradCsr(hovS, *t_, pres_, [&](Index i) { return mom_.isCut(i); }, classicOk));
1172 } else {
1173 gpsMomDelta_ = CfCsrDev{};
1174 gcS_ = GhostGradCsrDev{};
1175 }
1176 // Krylov scratch carries the ghost tail (matvec inputs) in distributed mode.
1177 auto mk = [&](const char* l) { return View<double>(l, static_cast<std::size_t>(nExt_)); };
1178 gpr_ = mk("gp_r");
1179 gprh_ = mk("gp_rhat");
1180 gpp_ = mk("gp_p");
1181 gpph_ = mk("gp_phat");
1182 gpv_ = mk("gp_v");
1183 gps_ = mk("gp_s");
1184 gpsh_ = mk("gp_shat");
1185 gpt_ = mk("gp_t");
1186 }
1187
1189 void allocateStepState(Index n) {
1190 // Device state. Fields whose ghost entries are READ through the CSRs / overlays (u, p, φ)
1191 // — plus div (its View is deep_copied into the nExt-sized distributed MG rhs) and the u
1192 // snapshots (full-extent deep_copies of u) — carry the ghost tail [n, nExt); nExt == n
1193 // single-rank, so those allocations are unchanged there.
1194 for (int c = 0; c < 3; ++c) {
1195 u_[c] = View<double>("df_u", static_cast<std::size_t>(nExt_));
1196 gx_[c] = View<double>("df_g", static_cast<std::size_t>(n));
1197 Kokkos::deep_copy(u_[c], 0.0);
1198 }
1199 p_ = View<double>("df_p", static_cast<std::size_t>(nExt_));
1200 phi_ = View<double>("df_phi", static_cast<std::size_t>(nExt_));
1201 div_ = View<double>("df_div", static_cast<std::size_t>(nExt_));
1202 uf_ = View<double>("df_uf",
1203 geom_.nbr.extent(0)); // ABC divergence-free face field (per CSR face)
1204 faceFieldBuilt_ = false;
1205 bmom_ = View<double>("df_bmom", static_cast<std::size_t>(n));
1206 Kokkos::deep_copy(p_, 0.0);
1207 // Implicit-FOU advection state. The momentum operator + its velocity-MG are rebuilt each
1208 // step from the *full* operator (viscous + FOU) so the MG is advection-aware (the viscous-
1209 // only MG diverges on the advection operator at cut cells); the FOU is baked into the CSR
1210 // (momOp_.hasAdv stays false). defc holds the device-computed explicit ρ(SOU−FOU)
1211 // deferred correction. uadvHost_ caches u^n on the host for the per-step operator rebuild.
1212 for (int c = 0; c < 3; ++c) {
1213 defc_[c] = View<double>("df_defc", static_cast<std::size_t>(n));
1214 Kokkos::deep_copy(defc_[c], 0.0);
1215 // uⁿ snapshot for the backward-Euler mass term (frozen across Picard outer iters) + the
1216 // previous outer iterate for the outer-loop convergence test.
1217 u0_[c] = View<double>("df_u0", static_cast<std::size_t>(nExt_));
1218 uprev_[c] = View<double>("df_uprev", static_cast<std::size_t>(nExt_));
1219 }
1220 // Device-resident implicit-FOU advection: the FOU operator (advDiag + per-face advCoef over the
1221 // face-geometry CSR) is rebuilt on device each step from uⁿ and added to the static Stokes
1222 // operator in the matvec (no host round-trip). The static operator + Galerkin velocity-MG are
1223 // built once (above); the advection is a perturbation the static MG still preconditions.
1224 advDiag_ = View<double>("df_advdiag", static_cast<std::size_t>(n));
1225 advCoef_ = View<double>("df_advcoef", geom_.nbr.extent(0));
1226 momOp_.advStart = geom_.start;
1227 momOp_.advNbr = geom_.nbr;
1228 momOp_.advDiag = advDiag_;
1229 momOp_.advCoef = advCoef_;
1230 momOp_.hasAdv = false; // set per-step when advection is on
1231 momSolver_.setJacobi(2, 0.7);
1232 // Generic MG preconditioner: dispatch the chosen hierarchy's V-cycle (z = M⁻¹ r), decoupling
1233 // the solver from the MG type so Galerkin and staircase are interchangeable. Distributed:
1234 // the rank-local Galerkin hierarchy built above (staircase unsupported there ⇒ Jacobi).
1235 if (momMGon_ && !(dist_ && useStaircaseMG_)) {
1236 if (useStaircaseMG_)
1237 momSolver_.setPreconditioner(
1238 [this](View<const double> r, View<double> z) { runMgVcycle(velMG_, r, z); });
1239 else
1240 momSolver_.setPreconditioner(
1241 [this](View<const double> r, View<double> z) { runMgVcycle(momMG_, r, z); });
1242 }
1243 pcg_.setVcycle(2, 2, 60, 0.8);
1244 pcg_.setSingular(true);
1245 }
1246
1247 public:
1251 // ---- M0 (docs/amr_march_perf_and_distributed_plan.md): the per-phase STEP profiler -----------
1252 // `PECLET_AMR_PROFILE_STEP=1` accumulates FENCED per-phase timings over a window of steps
1253 // (`PECLET_AMR_PROFILE_STEP_WINDOW`, default 50) and prints ms/step and µs/leaf per phase next
1254 // to the iteration counters — the instrument Phase M's attribution matrix reads. The four
1255 // pressure-solve rows are NESTED inside `pressure solve` (the residual is Krylov vector work and
1256 // the reductions), so they are printed indented and must not be added to the total.
1257 //
1258 // OFF (the default) every hook is one bool test: no fence, no clock, no change to the kernel
1259 // sequence — so a profiler-off march is bitwise what it was before the profiler existed.
1277 using SpClock = std::chrono::steady_clock;
1278 SpClock::time_point spMark() const {
1279 if (!stepProf_)
1280 return SpClock::time_point{};
1281 Kokkos::fence();
1282 return SpClock::now();
1283 }
1284 void spAdd(int ph, SpClock::time_point t0) {
1285 if (!stepProf_)
1286 return;
1287 Kokkos::fence();
1288 spAcc_[ph] += std::chrono::duration<double, std::milli>(SpClock::now() - t0).count();
1289 }
1290
1291 void spEndStep() {
1292 if (!stepProf_)
1293 return;
1294 ++spSteps_;
1295 spMom_ += lastMomIters_;
1296 spPres_ += lastPresIters_;
1297 spOuter_ += lastOuterIters_;
1298 if (!spHeader_) { // the static hierarchy shape, on the first profiled step (H-mg's
1299 // denominator, and the one line a contention-exposed box can still trust)
1300 const std::vector<Index> lad = pressureMgLevels();
1301 std::fprintf(stderr, "[step-prof] leaves %lld | pressure MG levels %zu:", (long long)n_,
1302 lad.size());
1303 for (Index n : lad)
1304 std::fprintf(stderr, " %lld", (long long)n);
1305 std::fprintf(stderr, " | bottom %s\n", pressureMgBottom().c_str());
1306 spHeader_ = true;
1307 }
1308 if (spSteps_ < spWindow_)
1309 return;
1310 static const char* kName[SP_N] = {
1311 "glue (copies + syncs)", "grad3 (binary)", "cf delta kernels", "overlay delta kernels",
1312 "advection build", "momentum rhs", "momentum solve", "divergence",
1313 "pressure solve", " . binary matvec", " . overlay matvec", " . projection",
1314 " . MG preconditioner", "finish projection"};
1315 const double w = static_cast<double>(spSteps_);
1316 const double leaves = static_cast<double>(n_);
1317 double tot = 0.0;
1318 for (int k = 0; k < SP_N; ++k)
1319 if (k < SP_PRES_MV || k > SP_PRES_PC)
1320 tot += spAcc_[k];
1321 std::fprintf(stderr,
1322 "[step-prof] %d steps | %.3f ms/step (%.3f us/leaf) | mom %.1f it, "
1323 "pres %.1f it, outer %.2f\n",
1324 spSteps_, tot / w, 1e3 * tot / w / leaves, spMom_ / w, spPres_ / w, spOuter_ / w);
1325 for (int k = 0; k < SP_N; ++k) {
1326 const bool nested = (k >= SP_PRES_MV && k <= SP_PRES_PC);
1327 std::fprintf(stderr, "[step-prof] %-22s %8.3f ms/step %8.4f us/leaf %5.1f%%%s\n",
1328 kName[k], spAcc_[k] / w, 1e3 * spAcc_[k] / w / leaves,
1329 100.0 * spAcc_[k] / (tot > 0 ? tot : 1.0), nested ? " (nested)" : "");
1330 }
1331 for (int k = 0; k < SP_N; ++k)
1332 spAcc_[k] = 0.0;
1333 spSteps_ = 0;
1334 spMom_ = spPres_ = spOuter_ = 0.0;
1335 }
1336
1340 void requireOperator(const char* what) const {
1341 if (!ready_)
1342 throw std::runtime_error(std::string("amr::AmrFlow::") + what +
1343 ": no cut-cell operator -- call setSolid() first (Python: "
1344 "Flow.set_solid / set_solid_spheres; after begin_adapt, "
1345 "finish_adapt)");
1346 }
1347
1348 void step(int momIters = 100, int presIters = 60) {
1349 requireOperator("step");
1350 const Index n = n_;
1351 const double idiag = rho_ / dt_;
1352 lastMomIters_ = 0;
1353 lastOuterIters_ = 1;
1354 const auto spT0 = spMark();
1355 // Freeze the time-level uⁿ for the backward-Euler mass term + warm start; it stays anchored
1356 // across the Picard outer iterations (only the advecting velocity re-lags). For outerIters_==1
1357 // this is just a copy of uⁿ ⇒ bit-identical to the single lagged step.
1358 for (int c = 0; c < 3; ++c)
1359 Kokkos::deep_copy(u0_[c], View<const double>(u_[c]));
1360 // −∇p^n is constant across the outer iterations (pressure is projected once, after the loop,
1361 // like flow's single per-step projection) ⇒ hoist it out.
1362 syncScalar(p_); // ghost tail of pⁿ before the gradient reads (no-op single-rank)
1363 spAdd(SP_GLUE, spT0);
1364 auto spT = spMark();
1365 grad3(geom_, View<const double>(p_), gx_[0], gx_[1], gx_[2]);
1366 spAdd(SP_GRAD, spT);
1367 spT = spMark();
1368 for (int a = 0; a < 3; ++a) // 2nd-order C/F face gradients (level-boundary rows)
1369 cfApply(cfGrad_[static_cast<std::size_t>(a)], View<const double>(p_), gx_[a]);
1370 spAdd(SP_CF, spT);
1371 spT = spMark();
1372 applyGhostGrad(gc_, View<const double>(p_), gx_[0], gx_[1], gx_[2]);
1373 applyGhostGradCsr(gcS_, View<const double>(p_), gx_[0], gx_[1], gx_[2]);
1374 spAdd(SP_OVERLAY, spT);
1375 // Picard outer loop over the lagged advection only (the momentum nonlinearity); for
1376 // outerIters_==1 this is the single lagged predictor, then one projection — bit-identical to
1377 // before.
1378 for (int outer = 0; outer < outerIters_; ++outer) {
1379 // --- advection lagged to the *current* predictor iterate (uⁿ on the first pass):
1380 // implicit-FOU operator + explicit ρ(SOU−FOU) deferred correction. The matvec stays linear
1381 // during each solve (the advecting velocity is frozen in advDiag_/advCoef_). With advection
1382 // OFF the operator and RHS are identical every pass, so a second pass reproduces the first ⇒
1383 // instant early-stop. ---
1384 spT = spMark();
1385 if (advect_) {
1386 momOp_.hasAdv = implicitFou_;
1387 syncVel(); // ghost tails of the (lagged) advecting velocity for buildFou/deferredSou
1388 // Advect with the divergence-free face field uf (from the previous projection); fall back
1389 // to ½(u_i+u_j) before the first projection has built it. The implicit FOU and the explicit
1390 // SOU/FOU deferred correction use the SAME velocity ⇒ the FOU cancels at steady state
1391 // (host-parity).
1392 const View<const double> ufv(uf_);
1393 const bool useUf = faceFieldBuilt_ && ufAdvect_;
1394 if (implicitFou_)
1395 buildFou(geom_, View<const double>(u_[0]), View<const double>(u_[1]),
1396 View<const double>(u_[2]), rho_, View<const double>(rscale_), advDiag_, advCoef_,
1397 ufv, useUf);
1398 for (int c = 0; c < 3; ++c) {
1399 if (implicitFou_)
1400 deferredSou(geom_, View<const double>(u_[0]), View<const double>(u_[1]),
1401 View<const double>(u_[2]), c, rho_, advScheme_, defc_[c], ufv, useUf,
1402 seamRecon_);
1403 else
1404 advectExplicit(geom_, View<const double>(u_[0]), View<const double>(u_[1]),
1405 View<const double>(u_[2]), c, rho_, advScheme_, defc_[c], ufv, useUf,
1406 seamRecon_);
1407 }
1408 // The staircase MG's fine level mirrors the sharp operator; refresh it so it picks up the
1409 // current advection state (hasAdv). (The Galerkin MG is the static viscous operator.)
1410 if (momMGon_ && useStaircaseMG_)
1411 velMG_.setFineOp(momOp_);
1412 }
1413 spAdd(SP_ADV, spT);
1414 // --- predictor: incremental BE viscous (+ implicit-FOU) solve per component, RHS carries
1415 // −∇p^n and −ρ(SOU−FOU); the mass term is anchored at uⁿ (u0_), the solve warm-starts at the
1416 // current iterate. ---
1417 // D2: the momentum ξ-seam delta is a CSR over the overlay's SAMPLE functionals, so on a
1418 // mixed-level band it reads ghost slots — and with advection off nothing else has refreshed
1419 // uⁿ's ghost tail since the previous step's projection. The C/F momentum delta (cfMom_) is
1420 // in exactly the same position: it reads u at the coarse cell's tangential neighbours,
1421 // which are ghost slots at a block seam. (Zero ghosts single-rank / np=1, so this is a
1422 // no-op exchange there and the path stays bit-identical.)
1423 if (dist_ && (ghostSampled_ || cfScheme_ != CfScheme::standard))
1424 syncVel();
1425 for (int c = 0; c < 3; ++c) {
1426 spT = spMark();
1427 momRhs(View<const double>(u0_[c]), View<const double>(gx_[c]), View<const double>(defc_[c]),
1428 View<const double>(rscale_), View<const char>(fluid_), idiag, f_[c], bmom_, n);
1429 spAdd(SP_MOMRHS, spT);
1430 spT = spMark();
1431 // C/F-scheme deferred correction on the velocity diffusion: b += μ(∇²_scheme − ∇²_std)
1432 // of the lagged component (regular rows only, rscale = 1 there).
1433 cfApply(cfMom_, View<const double>(u_[c]), bmom_);
1434 // Momentum ξ-row seam correction (sampled mode; rscale re-folded at upload).
1435 cfApply(gpsMomDelta_, View<const double>(u_[c]), bmom_);
1436 spAdd(SP_CF, spT);
1437 spT = spMark();
1438 // P4 (opt-in): the velocity-MG used as the *solver* — MG-preconditioned defect correction,
1439 // no Krylov (the flow RB-GS/velocity-MG mirror; cannot break down on the non-symmetric
1440 // operator) — vs the default MG-preconditioned BiCGStab. Both reach the same solution (the
1441 // matvec is the exact operator); the choice only trades robustness for convergence rate.
1442 lastMomIters_ +=
1443 (momMGSolver_ ? momSolver_.solveDefectCorrection(
1444 momOp_, u_[c], View<const double>(bmom_), momIters, momTol_)
1445 : momSolver_.solveBiCGStab(momOp_, u_[c], View<const double>(bmom_),
1446 momIters, momTol_))
1447 .iters;
1448 spAdd(SP_MOMSOLVE, spT);
1449 }
1450 // Outer-loop convergence on the predictor velocity (skipped for the default outerIters_==1,
1451 // so that path is untouched). With advection off the second iterate equals the first ⇒ stops
1452 // at 2.
1453 if (outerIters_ > 1) {
1454 lastOuterIters_ = outer + 1;
1455 if (outer > 0) {
1456 double dmax = 0.0;
1457 for (int c = 0; c < 3; ++c)
1458 dmax = std::max(
1459 dmax, maxAbsDiff(View<const double>(u_[c]), View<const double>(uprev_[c]), n));
1460 if (dmax < outerTol_)
1461 break;
1462 }
1463 for (int c = 0; c < 3; ++c)
1464 Kokkos::deep_copy(uprev_[c], View<const double>(u_[c]));
1465 }
1466 }
1467 project(presIters); // single pressure projection per step (flow structure)
1468 spEndStep();
1469 }
1470
1472 void project(int presIters = 60) {
1473 requireOperator("project");
1474 const Index n = n_;
1475 auto spT = spMark();
1476 syncVel(); // ghost tails of u* for the divergence (+ the ghost-closed overlay delta)
1477 divergence(geom_, View<const double>(u_[0]), View<const double>(u_[1]),
1478 View<const double>(u_[2]), div_);
1479 spAdd(SP_DIV, spT);
1480 spT = spMark();
1481 cfApplyComp(cfDiv_, View<const double>(u_[0]), View<const double>(u_[1]),
1482 View<const double>(u_[2]), div_); // 2nd-order C/F face averages (setCfScheme)
1483 spAdd(SP_CF, spT);
1484 spT = spMark();
1485 if (ghostProj_) { // ghost-closed constraint: binary div (geom_ carries binary α) + overlay
1486 ghostDivergDelta(gpOv_, View<const double>(u_[0]), View<const double>(u_[1]),
1487 View<const double>(u_[2]), div_);
1488 ghostDivergDeltaSampled(gpOvS_, View<const double>(u_[0]), View<const double>(u_[1]),
1489 View<const double>(u_[2]), div_);
1490 }
1491 spAdd(SP_OVERLAY, spT);
1492 Kokkos::deep_copy(phi_, 0.0);
1493 if (ghostProj_) {
1494 spT = spMark();
1495 lastPresIters_ = solveGhostBiCGStab(phi_, View<const double>(div_), presIters, presTol_);
1496 spAdd(SP_PRES, spT);
1497 spT = spMark();
1499 spAdd(SP_FINISH, spT);
1500 return;
1501 }
1502 // Two selectable pressure drivers, like flow's CutcellMG: MG-PCG (default, presPCG_) and the
1503 // bounded stationary V-cycle (setPressurePCG(false)). MG-PCG covers ADVECTION too — the
1504 // historic exclusion ("transient near-nullspace issue") was characterised 2026-08-19 and was
1505 // NOT a property of the operator (which is geometry-only, advection-independent, SPD in the
1506 // volume-weighted inner product): the aperture RHS is INCOMPATIBLE by a fluid-mean component
1507 // (div_ is zeroed at solid-centered cells whose faces are partially open, breaking the
1508 // telescoping that would make Σ V·div = 0 over the operator's DOF set; the defect grows with
1509 // the developed flow, ~3e-3 relative at steady state on the Z&H sphere). The un-deflated
1510 // V-cycle's residual therefore STALLS at exactly |mean|·sqrt(V_fluid) — the old "60 bounded
1511 // cycles" was a stagnation cap, not a convergence count. The PCG's per-iteration fluid-range
1512 // projection (maskSolid + volume-weighted fluid-mean removal) deflates exactly that component,
1513 // so CG is valid and healthy: measured flat 15–17 iters/step (tol 1e-10) across the whole
1514 // impulsive N=32 transient, steady K identical to the V-cycle path to 4+ digits.
1515 // Debug knob (env, default-off): PECLET_AMR_PRES_DEBUG=1 — per-cycle/-solve residual +
1516 // RHS-compatibility trace to stderr (the characterisation instrumentation, kept).
1517 const bool dbg = amrEnvFlag("PECLET_AMR_PRES_DEBUG");
1518 if (dbg && !dist_) {
1519 // RHS compatibility: the operator's left null vector is the constant over fluid cells in the
1520 // volume-weighted inner product, so a solvable RHS needs Σ V_i·div_i ≈ 0 over fluid cells.
1521 const FvOp& op0 = presMG_.op(0);
1522 auto st = op0.faceStart;
1523 auto w = op0.faceW;
1524 auto bcD = op0.bcDiag;
1525 auto iv = op0.invVol;
1526 auto dv = div_;
1527 double su = 0.0, sv = 0.0, sn = 0.0;
1528 Kokkos::parallel_reduce(
1529 "amr::dbg_compat", n,
1530 KOKKOS_LAMBDA(const Index i, double& a, double& b, double& c) {
1531 double d = bcD(i);
1532 for (Index k = st(i); k < st(i + 1); ++k)
1533 d += w(k);
1534 const double m = (d > 1e-30) ? 1.0 : 0.0;
1535 a += m * dv(i) / iv(i);
1536 b += m / iv(i);
1537 c += m * dv(i) * dv(i) / iv(i);
1538 },
1539 su, sv, sn);
1540 std::fprintf(stderr, "[amr pres] rhs fluid-mean=%.3e |rhs|_D=%.3e (rel mean %.3e)\n", su / sv,
1541 std::sqrt(sn), (su / sv) / (std::sqrt(sn) + 1e-300));
1542 if (!presDbgSpdDone_) {
1543 // One-shot direct SPD probe of the assembled pressure operator (advection cannot enter
1544 // the assembly — this measures it): symmetry <y,Lx>_D vs <x,Ly>_D on deterministic
1545 // pseudo-random vectors, and the Rayleigh quotient sign (L negative-semidefinite).
1546 presDbgSpdDone_ = true;
1547 View<double> xr("dbg_x", static_cast<std::size_t>(n)),
1548 yr("dbg_y", static_cast<std::size_t>(n)), Ax("dbg_Ax", static_cast<std::size_t>(n)),
1549 Ay("dbg_Ay", static_cast<std::size_t>(n));
1550 Kokkos::parallel_for(
1551 "amr::dbg_fill", n, KOKKOS_LAMBDA(const Index i) {
1552 xr(i) = std::sin(0.7 * static_cast<double>(i) + 0.3);
1553 yr(i) = std::cos(1.3 * static_cast<double>(i) + 1.1);
1554 });
1555 applyFv(op0, View<const double>(xr), Ax);
1556 applyFv(op0, View<const double>(yr), Ay);
1557 auto dotD = [&](View<const double> a, View<const double> b) {
1558 double s = 0.0;
1559 Kokkos::parallel_reduce(
1560 "amr::dbg_dot", n,
1561 KOKKOS_LAMBDA(const Index i, double& acc) { acc += a(i) * b(i) / iv(i); }, s);
1562 return s;
1563 };
1564 const double yLx = dotD(View<const double>(yr), View<const double>(Ax));
1565 const double xLy = dotD(View<const double>(xr), View<const double>(Ay));
1566 const double xLx = dotD(View<const double>(xr), View<const double>(Ax));
1567 const double yLy = dotD(View<const double>(yr), View<const double>(Ay));
1568 std::fprintf(stderr,
1569 "[amr pres] SPD probe: <y,Lx>_D=%.15e <x,Ly>_D=%.15e rel asym=%.2e; "
1570 "Rayleigh <x,Lx>_D=%.3e <y,Ly>_D=%.3e (must be <=0)\n",
1571 yLx, xLy, std::fabs(yLx - xLy) / (std::fabs(yLx) + 1e-300), xLx, yLy);
1572 }
1573 }
1574 spT = spMark();
1575 if (presPCG_) {
1576 const auto R = dist_
1577 ? pcg_.solve(presMGD_, phi_, View<const double>(div_), presIters, presTol_)
1578 : pcg_.solve(presMG_, phi_, View<const double>(div_), presIters, presTol_);
1579 lastPresIters_ = R.iters;
1580 if (dbg)
1581 std::fprintf(stderr, "[amr pres] pcg iters=%d res0=%.3e res=%.3e rel=%.3e\n", R.iters,
1582 R.res0, R.res, R.res0 > 0 ? R.res / R.res0 : 0.0);
1583 } else if (dist_) {
1584 Kokkos::deep_copy(presMGD_.b(0), div_);
1585 Kokkos::deep_copy(presMGD_.x(0), 0.0);
1586 for (int it = 0; it < presIters; ++it)
1587 presMGD_.vcycle(2, 2, 60, 0.8);
1588 Kokkos::deep_copy(phi_, presMGD_.x(0));
1589 lastPresIters_ = presIters;
1590 } else {
1591 Kokkos::deep_copy(presMG_.b(0), div_);
1592 Kokkos::deep_copy(presMG_.x(0), 0.0);
1593 View<double> rdbg;
1594 if (dbg)
1595 rdbg = View<double>("pres_dbg_res", static_cast<std::size_t>(n));
1596 for (int it = 0; it < presIters; ++it) {
1597 presMG_.vcycle(2, 2, 60, 0.8);
1598 if (dbg) {
1599 residualFv(presMG_.op(0), View<const double>(presMG_.x(0)),
1600 View<const double>(presMG_.b(0)), rdbg);
1601 const double rn =
1602 std::sqrt(dotPlain(View<const double>(rdbg), View<const double>(rdbg), n));
1603 std::fprintf(stderr, "[amr pres] vcycle %2d |r|=%.6e\n", it + 1, rn);
1604 }
1605 }
1606 Kokkos::deep_copy(phi_, presMG_.x(0));
1607 lastPresIters_ = presIters;
1608 }
1609 spAdd(SP_PRES, spT);
1610 spT = spMark();
1612 spAdd(SP_FINISH, spT);
1613 }
1614
1618 void finishProjection(Index n) {
1619 // u*'s ghost tail is current (project() synced it and u is untouched since); φ's is not.
1620 syncScalar(phi_);
1621 buildFaceField(geom_, View<const double>(u_[0]), View<const double>(u_[1]),
1622 View<const double>(u_[2]), View<const double>(phi_), uf_);
1623 // 2nd-order C/F face values (setCfScheme), VELOCITY part only: the distance-weighted
1624 // {u_fine, coarse*} interpolation on the 2:1 sub-faces. Its divergence IS the constraint's
1625 // Δ_cfDiv — measured identical to 8.7e-17 — so the projection has already balanced it and uf
1626 // stays divergence-free with it in.
1627 cfApplyComp(cfUfVel_, View<const double>(u_[0]), View<const double>(u_[1]),
1628 View<const double>(u_[2]), uf_);
1629 // The φ part is NOT applied, and must not be. It substitutes the quadratic coarse* into uf's
1630 // FACE GRADIENT, but the pressure matrix is L = D_std·G_std (a recorded decision: at the fixed
1631 // point φ→0, so the matrix's C/F order cannot move the steady solution). A gradient the solve
1632 // never inverted cannot be balanced by it, so adding it breaks exactly the property uf exists
1633 // to have: Σ_faces α·A·dir·uf = 0, i.e. that advecting a scalar with uf conserves it and
1634 // leaves a uniform field uniform.
1635 //
1636 // Measured on a graded sphere at cf=1 (N=32, lmax=2, band=3, 25 steps), decomposing
1637 // d = (rhs − Lφ) − Δ_cfDiv + D(Δvel) + D(Δφ) [identity holds to 2.3e-15]
1638 // solve residual ‖rhs − Lφ‖ 1.34e-12
1639 // ‖D(Δvel) − Δ_cfDiv‖ 8.71e-17 ← velocity part: balanced, keep it
1640 // ‖D(Δφ)‖ 6.675e-03 ← THE ENTIRE flux imbalance
1641 // It is proportional to φ (0.240 at step 1, 6.7e-3 at step 25, 3.1e-4 at step 60) so it
1642 // vanishes at steady state and never showed up in a steady drag gate — but with advection on
1643 // it sat at 4.0e-2, the same order as the cell field's O(h²) divergence, i.e. uf had stopped
1644 // being a conservative flux for the whole of the transient.
1645 //
1646 // If a quadratic face gradient in uf is wanted, the pressure matrix has to invert the same
1647 // operator (L = D·G_quad). Mixing them is what this removes. The φ CSR is no longer built at
1648 // all (docs/amr_cf_flux_gate.md §6.7) — a CSR that must never be applied is a trap; §6.8
1649 // records the deferred-correction path that would buy a quadratic uf face gradient legally.
1650 faceFieldBuilt_ = true;
1651 grad3(geom_, View<const double>(phi_), gx_[0], gx_[1], gx_[2]);
1652 for (int a = 0; a < 3; ++a) // 2nd-order C/F face gradients (level-boundary rows)
1653 cfApply(cfGrad_[static_cast<std::size_t>(a)], View<const double>(phi_), gx_[a]);
1654 applyGhostGrad(gc_, View<const double>(phi_), gx_[0], gx_[1], gx_[2]);
1655 applyGhostGradCsr(gcS_, View<const double>(phi_), gx_[0], gx_[1], gx_[2]);
1656 for (int c = 0; c < 3; ++c)
1657 correct(u_[c], View<const double>(gx_[c]), View<const char>(fluid_), n);
1658 presUpdate(p_, View<const double>(phi_), View<const double>(div_), View<const char>(fluid_),
1659 rho_ / dt_, mu_, n);
1660 }
1661
1662 // ---- adaptivity during a run (ladder step 5) -------------------------------------------------
1663 // The octree is borrowed by pointer and mutated EXTERNALLY (refine/coarsen/balance/adapt on the
1664 // same object). beginAdapt snapshots the current topology + fields; after the mutation,
1665 // finishAdapt conservatively remaps u and the accumulated rotational p onto the new mesh
1666 // (minmod-limited linear transferField) and rebuilds every solver structure via setSolid. The
1667 // caller must keep the cut band at the finest level on the new mesh (refineToSdf the geometry
1668 // band again after a solution-driven adapt): the ghost overlay build throws / auto-falls-back
1669 // exactly as in setSolid. uf restarts from the ½-average fallback for one step.
1670
1677 void beginAdapt() {
1678 requireOperator("beginAdapt");
1679 ready_ = false; // no operator until finishAdapt rebuilds it on the new topology
1680 adaptOldT_ = std::make_unique<Octree>(*t_);
1681 for (int c = 0; c < 3; ++c)
1682 adaptU_[static_cast<std::size_t>(c)] = velocity(c);
1683 adaptP_ = pressure();
1684 if (dist_) {
1685 // Halo-completed prolongation gradients on the OLD mesh (while dist_ still holds it):
1686 // the block-local transfer stencil zeroes gradients at interior block boundaries,
1687 // which would make the remap np-dependent there (measured ~5% field divergence).
1688 for (int c = 0; c < 3; ++c)
1689 adaptGradU_[static_cast<std::size_t>(c)] =
1690 transferGradients(*dist_, adaptU_[static_cast<std::size_t>(c)]);
1691 adaptGradP_ = transferGradients(*dist_, adaptP_);
1692 }
1693 }
1694
1696 template <class SdfFn>
1697 void finishAdapt(SdfFn&& sdfFn) {
1698 if (!adaptOldT_)
1699 throw std::runtime_error("amr::AmrFlow::finishAdapt called without beginAdapt");
1700 std::array<std::vector<double>, 3> nu;
1701 for (int c = 0; c < 3; ++c)
1702 nu[static_cast<std::size_t>(c)] =
1703 transferField(*adaptOldT_, adaptU_[static_cast<std::size_t>(c)], *t_, /*linear=*/true,
1704 dist_ ? &adaptGradU_[static_cast<std::size_t>(c)] : nullptr);
1705 std::vector<double> np =
1706 transferField(*adaptOldT_, adaptP_, *t_, /*linear=*/true, dist_ ? &adaptGradP_ : nullptr);
1707 setSolid(sdfFn); // full operator/overlay rebuild on the new topology (zeroes the fields)
1708 for (int c = 0; c < 3; ++c) {
1709 setVelocity(c, nu[static_cast<std::size_t>(c)]);
1710 zeroSolid(u_[c]); // cells that became solid on the new mesh hold 0 (no-slip state)
1711 }
1712 setPressure(np);
1713 zeroSolid(p_); // solid p is pinned/decoupled
1714 adaptOldT_.reset();
1715 for (int c = 0; c < 3; ++c)
1716 adaptU_[static_cast<std::size_t>(c)].clear();
1717 adaptP_.clear();
1718 }
1719
1726 template <class SdfFn>
1727 void rebalanceMpi(SdfFn&& sdfFn) {
1728 if (!dist_)
1729 throw std::runtime_error("amr::AmrFlow::rebalanceMpi requires initMpi");
1730 std::vector<std::vector<double>> cols(4);
1731 for (int c = 0; c < 3; ++c)
1732 cols[static_cast<std::size_t>(c)] = velocity(c);
1733 cols[3] = pressure();
1734 dist_->rebalance(cols); // t_ still points at dist_->local(), now the new block's octree
1735 setSolid(sdfFn); // full rebuild (registry, halos, operators) on the new block
1736 for (int c = 0; c < 3; ++c) {
1737 setVelocity(c, cols[static_cast<std::size_t>(c)]);
1738 zeroSolid(u_[c]);
1739 }
1740 setPressure(cols[3]);
1741 zeroSolid(p_);
1742 }
1743
1745 void setPressure(const std::vector<double>& h) {
1746 auto m = Kokkos::create_mirror_view(p_);
1747 for (Index i = 0; i < n_; ++i)
1748 m(i) = h[static_cast<std::size_t>(i)];
1749 Kokkos::deep_copy(p_, m);
1750 }
1751
1753 void zeroSolid(View<double> v) {
1754 auto fl = fluid_;
1755 Kokkos::parallel_for(
1756 "amr::flow_zerosolid", n_, KOKKOS_LAMBDA(const Index i) {
1757 if (!fl(i))
1758 v(i) = 0.0;
1759 });
1760 }
1761
1764 std::vector<double> debugSou(int comp) {
1765 syncVel();
1766 View<double> s("dbg_sou", static_cast<std::size_t>(n_));
1767 advectExplicit(geom_, View<const double>(u_[0]), View<const double>(u_[1]),
1768 View<const double>(u_[2]), comp, 1.0, advScheme_, s, View<const double>(uf_),
1769 false, seamRecon_);
1770 std::vector<double> h(static_cast<std::size_t>(n_));
1771 auto m = Kokkos::create_mirror_view(s);
1772 Kokkos::deep_copy(m, s);
1773 for (Index i = 0; i < n_; ++i)
1774 h[static_cast<std::size_t>(i)] = m(i);
1775 return h;
1776 }
1777
1780 template <class MG>
1781 void runMgVcycle(MG& mg, View<const double> r, View<double> z) {
1782 // Element copies over the LOCAL rows (not deep_copy): in distributed mode the Krylov
1783 // scratch carries a ghost tail while the (rank-local) MG levels are local-sized; the
1784 // solver refreshes z's ghost tail before the next matvec. Same values single-rank.
1785 const Index nl = mg.numLeaves(0);
1786 {
1787 auto b0 = mg.b(0);
1788 Kokkos::parallel_for("amr::mgv_b", nl, KOKKOS_LAMBDA(const Index i) { b0(i) = r(i); });
1789 }
1790 Kokkos::deep_copy(mg.x(0), 0.0);
1791 mg.vcycle(mgVcPre_, mgVcPre_, mgVcBottom_, 0.7);
1792 {
1793 auto x0 = mg.x(0);
1794 Kokkos::parallel_for("amr::mgv_z", nl, KOKKOS_LAMBDA(const Index i) { z(i) = x0(i); });
1795 }
1796 }
1797
1798 static double maxAbsDiff(View<const double> a, View<const double> b, Index n) {
1799 double m = 0.0;
1800 Kokkos::parallel_reduce(
1801 "amr::flow_maxdiff", n,
1802 KOKKOS_LAMBDA(const Index i, double& lm) {
1803 double d = a(i) - b(i);
1804 if (d < 0.0)
1805 d = -d;
1806 if (d > lm)
1807 lm = d;
1808 },
1809 Kokkos::Max<double>(m));
1810 return m;
1811 }
1812
1813 void copyToHost(const View<double>& d, std::vector<double>& h) const {
1814 auto m = Kokkos::create_mirror_view(d);
1815 Kokkos::deep_copy(m, d);
1816 for (Index i = 0; i < n_; ++i)
1817 h[static_cast<std::size_t>(i)] = m(i);
1818 }
1819
1820 void setVelocity(int c, const std::vector<double>& h) {
1821 auto m = Kokkos::create_mirror_view(u_[c]);
1822 for (Index i = 0; i < n_; ++i)
1823 m(i) = h[static_cast<std::size_t>(i)];
1824 Kokkos::deep_copy(u_[c], m);
1825 }
1826
1828 std::vector<double> velocity(int c) const { return localVector(u_[c]); }
1831 std::vector<double> pressure() const { return localVector(p_); }
1832
1834 std::vector<double> localVector(const View<double>& v) const {
1835 if (v.extent(0) == static_cast<std::size_t>(n_))
1836 return peclet::core::toVector(v);
1837 View<double> packed(Kokkos::view_alloc("amr::local_packed", Kokkos::WithoutInitializing),
1838 static_cast<std::size_t>(n_));
1839 Kokkos::parallel_for("amr::pack_local", n_, KOKKOS_LAMBDA(const Index i) { packed(i) = v(i); });
1840 return peclet::core::toVector(packed);
1841 }
1842
1847 std::vector<double> velocities() const {
1848 View<double> packed(Kokkos::view_alloc("amr::vel_packed", Kokkos::WithoutInitializing),
1849 static_cast<std::size_t>(n_) * 3);
1850 for (int c = 0; c < 3; ++c) {
1851 auto uc = u_[c];
1852 auto p = packed;
1853 const int cc = c;
1854 Kokkos::parallel_for(
1855 "amr::pack_vel", n_, KOKKOS_LAMBDA(const Index i) { p(i * 3 + cc) = uc(i); });
1856 }
1857 return peclet::core::toVector(packed);
1858 }
1859
1861 double divNormL2() {
1862 syncVel();
1863 divergence(geom_, View<const double>(u_[0]), View<const double>(u_[1]),
1864 View<const double>(u_[2]), div_);
1865 cfApplyComp(cfDiv_, View<const double>(u_[0]), View<const double>(u_[1]),
1866 View<const double>(u_[2]), div_);
1867 if (ghostProj_) {
1868 ghostDivergDelta(gpOv_, View<const double>(u_[0]), View<const double>(u_[1]),
1869 View<const double>(u_[2]), div_);
1870 ghostDivergDeltaSampled(gpOvS_, View<const double>(u_[0]), View<const double>(u_[1]),
1871 View<const double>(u_[2]), div_);
1872 }
1873 return std::sqrt(allSum(dotPlain(View<const double>(div_), View<const double>(div_), n_)));
1874 }
1875
1890 double divNormFace() {
1891 const double l = divFaceNorm(geom_, View<const double>(uf_));
1892 return std::sqrt(allSum(l * l));
1893 }
1894
1900 std::vector<Index> pressureMgLevels() const {
1901 std::vector<Index> out;
1902 if (!dist_) {
1903 for (std::size_t L = 0; L < presMG_.numLevels(); ++L)
1904 out.push_back(presMG_.numLeaves(L));
1905 return out;
1906 }
1907 for (std::size_t L = 0; L < presMGD_.numLevels(); ++L)
1908 out.push_back(presMGD_.numLeaves(L));
1909 for (std::size_t L = 0; L < presMGD_.numStageLevels(); ++L)
1910 out.push_back(presMGD_.stageLeaves(L)); // §6.5: the stage's level 0 IS the moved level
1911 return out;
1912 }
1913
1918 std::string pressureMgBottom() const {
1919 return dist_ ? presMGD_.bottomName() : presMG_.bottomName();
1920 }
1921
1934 void setPressureBottom(const std::string& kind) {
1935 using B = typename Multigrid<3, Bits>::Bottom;
1936 if (kind == "auto")
1937 presBottom_ = B::Auto;
1938 else if (kind == "smoother")
1939 presBottom_ = B::Smoother;
1940 else if (kind == "agglomerated")
1941 presBottom_ = B::Agglomerated;
1942 else
1943 throw std::runtime_error(
1944 "amr::AmrFlow::setPressureBottom: expected 'auto', 'smoother' or 'agglomerated'");
1945 if (dist_)
1946 presMGD_.setBottom(presBottom_);
1947 else
1948 presMG_.setBottom(presBottom_);
1949 }
1950
1961 if (e < 1)
1962 throw std::runtime_error("amr::AmrFlow::setPressureBottomExtent: must be >= 1");
1963 presBottomExtent_ = e;
1964 }
1965
1966 Index pressureBottomExtent() const { return presBottomExtent_; }
1967
1970 std::vector<double> faceField() const { return peclet::core::toVector(uf_); }
1981 std::vector<Index> start, nbr, upupI, upupJ;
1982 std::vector<int> axis, dir;
1983 std::vector<double> rawArea, dist, alpha;
1988 std::vector<Index> seam, sampI, sampJ, uuRecI, uuRecJ, recStart, recCell;
1989 std::vector<double> d1I, d1J, recDist, recW;
1994 std::vector<double> center;
1995 };
1998 t.start = peclet::core::toVector(geom_.start);
1999 t.nbr = peclet::core::toVector(geom_.nbr);
2000 t.upupI = peclet::core::toVector(geom_.upupI);
2001 t.upupJ = peclet::core::toVector(geom_.upupJ);
2002 t.axis = peclet::core::toVector(geom_.axis);
2003 t.dir = peclet::core::toVector(geom_.dir);
2004 t.rawArea = peclet::core::toVector(geom_.rawArea);
2005 t.dist = peclet::core::toVector(geom_.dist);
2006 t.alpha = peclet::core::toVector(geom_.alpha);
2007 t.seam = peclet::core::toVector(geom_.seam);
2008 t.sampI = peclet::core::toVector(geom_.sampI);
2009 t.sampJ = peclet::core::toVector(geom_.sampJ);
2010 t.uuRecI = peclet::core::toVector(geom_.uuRecI);
2011 t.uuRecJ = peclet::core::toVector(geom_.uuRecJ);
2012 t.recStart = peclet::core::toVector(geom_.recStart);
2013 t.recCell = peclet::core::toVector(geom_.recCell);
2014 t.d1I = peclet::core::toVector(geom_.d1I);
2015 t.d1J = peclet::core::toVector(geom_.d1J);
2016 t.recDist = peclet::core::toVector(geom_.recDist);
2017 t.recW = peclet::core::toVector(geom_.recW);
2018 t.center = slotCenters();
2019 return t;
2020 }
2021
2025 std::vector<double> slotCenters() const {
2026 std::vector<double> c(static_cast<std::size_t>(nExt_) * 3, 0.0);
2027 for (Index s = 0; s < nExt_; ++s) {
2028 const std::array<long, 3> lo = pres_.loOf(s);
2029 const double w = static_cast<double>(1L << pres_.levelOf(s));
2030 for (int a = 0; a < 3; ++a)
2031 c[static_cast<std::size_t>(s) * 3 + static_cast<std::size_t>(a)] =
2032 origin_[a] + h0_[a] * (static_cast<double>(lo[a] + shiftD_[a]) + 0.5 * w);
2033 }
2034 return c;
2035 }
2036
2039 Index numSeamSampleRecords() const { return seamSampleRecords_; }
2042 Index numSeamLayerRecords() const { return seamLayerRecords_; }
2043 Index numLeaves() const { return n_; }
2045 Index numGhostCells() const { return nExt_ - n_; }
2049 Index numCfGhostColumns() const { return cfGhostCols_; }
2056 Index numCfCutFaces() const { return cfCutFaces_; }
2058 bool isFluid(Index i) const { return mom_.isFluid(i); }
2060 int lastMomIters() const { return lastMomIters_; }
2062 int lastPresIters() const { return lastPresIters_; }
2064 int lastOuterIters() const { return lastOuterIters_; }
2065
2066 // ---- distributed plumbing (docs/amr_distributed_flow.md, rung 4) ----------------------------
2067
2069 void syncVel() {
2070 if (dist_)
2071 dhex_.exchange3(u_[0], u_[1], u_[2]);
2072 }
2073
2074 void syncScalar(View<double> v) {
2075 if (dist_)
2076 dhex_.exchange(v);
2077 }
2078
2079 double allSum(double s) const {
2080 if (!dist_)
2081 return s;
2082 double g = 0.0;
2083 MPI_Allreduce(&s, &g, 1, MPI_DOUBLE, MPI_SUM, dist_->comm());
2084 return g;
2085 }
2086
2089 std::array<long, 3> globalFineExtent() const {
2090 std::array<long, 3> g{};
2091 for (int a = 0; a < 3; ++a)
2092 g[a] = dist_ ? static_cast<long>(dist_->globalFineSize()[a])
2093 : static_cast<long>(pres_.fineExt()[a]);
2094 return g;
2095 }
2096
2098 const FvOp& gpOp0() { return dist_ ? presMGD_.op(0) : presMG_.op(0); }
2099
2103 template <class SdfFn>
2104 void prepareDistributed(SdfFn&& sdfFn) {
2105 dhalo_.init(*dist_);
2106 for (int a = 0; a < 3; ++a)
2107 shiftD_[a] = dist_->blockFineOrigin()[a];
2108 auto resv = [hp = &dhalo_, sh = shiftD_](const std::array<long, 3>& p) -> Index {
2109 std::array<long, 3> g = p;
2110 for (int a = 0; a < 3; ++a)
2111 g[a] += sh[a];
2112 return hp->resolveGlobal(g);
2113 };
2114 mom_.setFrameShift(shiftD_);
2115 mom_.setResolver(resv);
2116 pres_.setFrameShift(shiftD_);
2117 pres_.setResolver(resv);
2118 const Index n = t_->numLeaves();
2119 const Vec<3> beta = betaPerAxis();
2120 int rounds = 0;
2121 const bool profSetup = amrEnvFlag("PECLET_AMR_PROFILE_SETUP");
2122 for (;;) {
2123 ++rounds;
2124 const auto rT0 = std::chrono::steady_clock::now();
2125 installGhostMeta(); // metadata for every ghost known so far (same-round hits read it)
2126 // Classic path: mom_.build stays in the loop because its sdfC feeds the classic overlay
2127 // prober below. Sampled path (D3 setup-cost fix): its ±1 probes are a subset of the face
2128 // sweep's explicit periodicNeighbor probes, so the full build runs ONCE after the fixpoint
2129 // instead of once per round.
2130 if (!ghostSampled_)
2131 mom_.build(sdfFn, rho_ / dt_, beta); // ±1 probes (also fills the extended sdfC/fluid)
2132 // FaceGeom probes: the full face enumeration + the SOU upstream-of-upwind ±2 reach.
2133 // Host-parallel since the F1 resolution (miss registration is mutex-guarded and the miss
2134 // SET is order-canonical — see LeafHalo::resolve); pure discovery, results discarded.
2135 hostParFor(n, [&](Index i) {
2136 pres_.forEachFaceFull(i, [&](Index j, int ax, int dr, double, double, double) {
2137 (void)pres_.periodicNeighbor(i, ax, -dr);
2138 if (j >= 0)
2139 (void)pres_.periodicNeighbor(j, ax, dr);
2140 });
2141 });
2142 // Overlay / directional-gradient ±2 chains (every cut cell is a non-clean overlay row,
2143 // so this covers buildGhostGradOverlay's probes too). Discovery only — result discarded.
2144 if (ghostSampled_) {
2145 // D1 (DD2): the SAMPLED builders are probers too, and they reach further than the classic
2146 // ±2 chain — an LS cloud descends a whole box of radius 2.2·max(h,H) around each virtual
2147 // position, and the mixed openness rule probes ±¼h0 off every face centroid. The overlay
2148 // runs in PROBE-ONLY discovery mode (D3 setup-cost fix): identical control flow and probe
2149 // pattern, pending regions blind-descended at 4-cell granularity so their misses register
2150 // in one collective round instead of one octree level per round, and none of the
2151 // least-squares work a discovery round would discard is done. The REAL build (setSolid,
2152 // after this fixpoint) runs with every ghost resolved and never sets the flag.
2153 const auto gfine = globalFineExtent();
2154 (void)buildGhostOverlaySampled(*t_, pres_, sdfFn, gpMatrixOrder_, gpRhsOrder_, origin_,
2155 &gfine, shiftD_, /*discovery=*/true, gpsRho_, gpsMaxN_);
2156 auto binFn = makeBinaryOpenFnMixed(
2157 *t_, pres_, [&sdfFn](const Vec<3>& p) { return sdfFn(p); }, h0_, origin_, shiftD_);
2158 pres_.buildOpenness(binFn); // discovery only; setSolid rebuilds it after the fixpoint
2159 } else if (ghostProj_ || ghostGrad_) {
2160 bool viol = false;
2161 (void)buildGhostOverlay(*t_, pres_, mom_.sdfCRaw(), gpMatrixOrder_, gpRhsOrder_, &viol);
2162 }
2163 if (cfScheme_ != CfScheme::standard) {
2164 probeCfScheme(); // the four buildCf*Delta builders' tangential reach
2165 probeSeamLayer(); // the seam builder's far-side reach across a GHOST neighbour
2166 }
2167 const double rBuildMs =
2168 std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - rT0).count();
2169 const long pend = dhalo_.resolveMisses();
2170 if (profSetup)
2171 std::fprintf(stderr, "[setSolid] round %d: build %.1f ms, %lld ghosts, %ld pending\n",
2172 rounds, rBuildMs, (long long)dhalo_.numGhosts(), pend);
2173 if (pend == 0)
2174 break;
2175 }
2176 if (profSetup)
2177 // The discovery fixpoint's round count. The classic +-2 chain converges in <=3; the SAMPLED
2178 // builders reach a whole LS box, and D0's descent deliberately learns one octree level per
2179 // round rather than registering a miss per fine cell, so the sampled path needs more (it
2180 // grows with the level span the clouds cover). Each round is a full rebuild + a collective.
2181 std::fprintf(stderr, "[setSolid] distributed discovery fixpoint: %d rounds (%lld ghosts)\n",
2182 rounds, (long long)dhalo_.numGhosts());
2184 if (ghostSampled_)
2185 mom_.build(sdfFn, rho_ / dt_, beta); // once, every coord it probes already resolved
2186 dhalo_.finalize();
2187 nExt_ = dhalo_.extendedSize();
2188 dhex_.init(dhalo_);
2189 allred_ = [this](double s) { return allSum(s); };
2190 momSolver_.setDistributed([this](View<double> v) { dhex_.exchange(v); }, allred_, nExt_);
2191 }
2192
2218 const Index n = t_->numLeaves();
2219 hostParFor(n, [&](Index i) {
2220 const unsigned Li = pres_.levelOf(i);
2221 pres_.forEachFaceFull(i, [&](Index j, int axis, int, double, double, double) {
2222 const unsigned Lj = pres_.levelOf(j);
2223 if (Lj == Li)
2224 return;
2225 probeCfTangential((Lj > Li) ? j : i, axis);
2226 });
2227 });
2228 }
2229
2233 void probeCfTangential(Index coarse, int axis) {
2234 const unsigned Lc = pres_.levelOf(coarse);
2235 const std::array<long, 3> bc = pres_.loOf(coarse);
2236 const long sc = 1L << Lc, sh = sc >> 1;
2237 for (int tt = 0; tt < 3; ++tt) {
2238 if (tt == axis)
2239 continue;
2240 for (int dir = -1; dir <= 1; dir += 2) {
2241 (void)pres_.periodicNeighbor(coarse, tt, dir);
2242 std::array<long, 3> lo = bc;
2243 lo[tt] += (dir > 0) ? sc : -sc;
2244 for (int oct = 0; oct < (1 << 3); ++oct) {
2245 std::array<long, 3> q = lo;
2246 for (int d = 0; d < 3; ++d)
2247 if ((oct >> d) & 1)
2248 q[d] += sh;
2249 (void)pres_.probeSlot(q);
2250 }
2251 }
2252 }
2253 }
2254
2272 const Index n = t_->numLeaves();
2273 hostParFor(n, [&](Index i) {
2274 pres_.forEachFaceFull(i, [&](Index j, int axis, int dir, double, double, double) {
2275 if (j < 0)
2276 return;
2277 const unsigned Lj = pres_.levelOf(j);
2278 if (Lj > 0) { // the four face-layer corners beyond j (a layer record with C == j)
2279 const std::array<long, 3> lo = pres_.loOf(j);
2280 const long sj = 1L << Lj, sh = sj >> 1;
2281 std::array<long, 3> p{};
2282 for (int d = 0; d < 3; ++d)
2283 p[d] = lo[d];
2284 p[axis] = (dir > 0) ? lo[axis] + sj : lo[axis] - 1;
2285 for (int k = 0; k < 4; ++k) {
2286 std::array<long, 3> q = p;
2287 int bit = 0;
2288 for (int t = 0; t < 3; ++t) {
2289 if (t == axis)
2290 continue;
2291 q[t] = lo[t] + (((k >> bit) & 1) ? sh : 0L);
2292 ++bit;
2293 }
2294 (void)pres_.probeSlot(q);
2295 }
2296 }
2297 const Index uJ = pres_.periodicNeighbor(j, axis, dir);
2298 if (uJ >= 0 && pres_.levelOf(uJ) > Lj)
2299 probeCfTangential(uJ, axis); // a sample record with C == uJ, F == j (case 2)
2300 });
2301 });
2302 }
2303
2306 const Index ng = dhalo_.numGhosts();
2307 std::vector<std::array<long, 3>> glo(static_cast<std::size_t>(ng));
2308 std::vector<unsigned> glv(static_cast<std::size_t>(ng));
2309 for (Index g = 0; g < ng; ++g) {
2310 for (int a = 0; a < 3; ++a)
2311 glo[static_cast<std::size_t>(g)][a] =
2312 static_cast<long>(dhalo_.ghostCoord(g)[a]) - shiftD_[a];
2313 glv[static_cast<std::size_t>(g)] = static_cast<unsigned>(dhalo_.level(dhalo_.numLocal() + g));
2314 }
2315 mom_.setGhosts(glo, glv); // copies — pres_ takes the originals
2316 pres_.setGhosts(std::move(glo), std::move(glv));
2317 }
2318
2319 // (public like runMgVcycle: nvcc rejects extended device lambdas in private member functions)
2320 // Project onto the coupled subspace: pin decoupled rows (solid-centered + no-phi-coupling
2321 // overlay rows) to 0 and remove the volume-weighted mean over the coupled cells (the constant
2322 // null mode of the connected fluid region) — removeMeanVol with the coupled mask (the mean
2323 // reduced globally in distributed mode; allred_ is empty single-rank ⇒ bit-identical).
2324 void gpProject(View<double> v) { removeMeanVolReduced(v, gpOp0().invVol, maskC_, n_, allred_); }
2325
2326 // Nonsymmetric ghost pressure matvec: y = P[rho·(L_bin x + Delta x)]. The caller keeps x's
2327 // ghost tail current (syncScalar before every call in distributed mode).
2328 void ghostMatvec(View<const double> x, View<double> y) {
2329 auto spT = spMark();
2330 applyFv(gpOp0(), x, y);
2331 spAdd(SP_PRES_MV, spT);
2332 spT = spMark();
2333 ghostApplyDelta(gpOv_, x, y);
2334 ghostApplyDeltaSampled(gpOvS_, x, y);
2335 spAdd(SP_PRES_MVOV, spT);
2336 spT = spMark();
2337 gpProject(y);
2338 spAdd(SP_PRES_PROJ, spT);
2339 }
2340
2341 // Preconditioner: two binary-openness V-cycles (the unchanged MG hierarchy) + projection.
2342 void ghostPrec(View<const double> r, View<double> z) {
2343 const auto spT = spMark();
2344 if (dist_) {
2345 Kokkos::deep_copy(presMGD_.b(0), r);
2346 Kokkos::deep_copy(presMGD_.x(0), 0.0);
2347 presMGD_.vcycle(2, 2, 60, 0.8);
2348 presMGD_.vcycle(2, 2, 60, 0.8);
2349 Kokkos::deep_copy(z, presMGD_.x(0));
2350 } else {
2351 Kokkos::deep_copy(presMG_.b(0), r);
2352 Kokkos::deep_copy(presMG_.x(0), 0.0);
2353 presMG_.vcycle(2, 2, 60, 0.8);
2354 presMG_.vcycle(2, 2, 60, 0.8);
2355 Kokkos::deep_copy(z, presMG_.x(0));
2356 }
2357 gpProject(z);
2358 spAdd(SP_PRES_PC, spT);
2359 }
2360
2361 // MG-preconditioned BiCGStab on the ghost pressure operator (device mirror of the oracle's
2362 // solveGhostBiCGStab: same projection, same stagnation guard against the small
2363 // attainable-residual floor of the slightly incompatible ghost system). Returns iterations.
2364 int solveGhostBiCGStab(View<double> x, View<const double> b, int maxIters, double tol = 1e-10) {
2365 const Index n = n_;
2366 // Dots are locally summed then globally reduced (allSum = identity single-rank); every
2367 // matvec input's ghost tail is refreshed first. Stagnation/early-break branches depend on
2368 // reduced scalars only ⇒ every rank takes the same branch.
2369 syncScalar(x);
2370 ghostMatvec(View<const double>(x), gpr_);
2371 {
2372 auto r = gpr_;
2373 auto bb = b;
2374 Kokkos::parallel_for("amr::gp_r0", n, KOKKOS_LAMBDA(const Index i) { r(i) = bb(i) - r(i); });
2375 }
2376 gpProject(gpr_);
2377 Kokkos::deep_copy(gprh_, gpr_);
2378 const double res0 =
2379 std::sqrt(allSum(dotPlain(View<const double>(gpr_), View<const double>(gpr_), n)));
2380 if (res0 == 0.0)
2381 return 0;
2382 double rho = 1, alpha = 1, omega = 1, best = res0;
2383 int noImprove = 0;
2384 Kokkos::deep_copy(gpv_, 0.0);
2385 Kokkos::deep_copy(gpp_, 0.0);
2386 int it = 0;
2387 for (; it < maxIters; ++it) {
2388 const double rhoNew =
2389 allSum(dotPlain(View<const double>(gprh_), View<const double>(gpr_), n));
2390 if (rhoNew == 0.0)
2391 break;
2392 const double beta = (rhoNew / rho) * (alpha / omega);
2393 bicgPUpdate(gpp_, View<const double>(gpr_), View<const double>(gpv_), beta, omega, n);
2394 ghostPrec(View<const double>(gpp_), gpph_);
2395 syncScalar(gpph_);
2396 ghostMatvec(View<const double>(gpph_), gpv_);
2397 const double rhatV = allSum(dotPlain(View<const double>(gprh_), View<const double>(gpv_), n));
2398 if (rhatV == 0.0)
2399 break;
2400 alpha = rhoNew / rhatV;
2401 Kokkos::deep_copy(gps_, gpr_);
2402 axpy(gps_, -alpha, View<const double>(gpv_), n);
2403 const double snorm =
2404 std::sqrt(allSum(dotPlain(View<const double>(gps_), View<const double>(gps_), n)));
2405 if (snorm <= tol * res0) {
2406 axpy(x, alpha, View<const double>(gpph_), n);
2407 ++it;
2408 break;
2409 }
2410 ghostPrec(View<const double>(gps_), gpsh_);
2411 syncScalar(gpsh_);
2412 ghostMatvec(View<const double>(gpsh_), gpt_);
2413 const double tt = allSum(dotPlain(View<const double>(gpt_), View<const double>(gpt_), n));
2414 omega = (tt != 0.0)
2415 ? allSum(dotPlain(View<const double>(gpt_), View<const double>(gps_), n)) / tt
2416 : 0.0;
2417 axpy(x, alpha, View<const double>(gpph_), n);
2418 axpy(x, omega, View<const double>(gpsh_), n);
2419 Kokkos::deep_copy(gpr_, gps_);
2420 axpy(gpr_, -omega, View<const double>(gpt_), n);
2421 const double rnorm =
2422 std::sqrt(allSum(dotPlain(View<const double>(gpr_), View<const double>(gpr_), n)));
2423 if (rnorm <= tol * res0) {
2424 ++it;
2425 break;
2426 }
2427 if (rnorm < 0.999 * best) {
2428 best = rnorm;
2429 noImprove = 0;
2430 } else if (++noImprove >= 6) {
2431 ++it;
2432 break; // attainable-residual floor (compatibility gap) — stagnation guard
2433 }
2434 rho = rhoNew;
2435 if (omega == 0.0)
2436 break;
2437 }
2438 gpProject(x);
2439 return it;
2440 }
2441
2442 private:
2444 void uploadSeamRecon(const SeamReconHost& h) {
2445 geom_.seam = toDevice(h.seam, "seam_desc");
2446 geom_.sampI = toDevice(h.sampI, "seam_sampi");
2447 geom_.sampJ = toDevice(h.sampJ, "seam_sampj");
2448 geom_.uuRecI = toDevice(h.uuRecI, "seam_uureci");
2449 geom_.uuRecJ = toDevice(h.uuRecJ, "seam_uurecj");
2450 geom_.d1I = toDevice(h.d1I, "seam_d1i");
2451 geom_.d1J = toDevice(h.d1J, "seam_d1j");
2452 geom_.recStart = toDevice(h.recStart, "seam_recstart");
2453 geom_.recDist = toDevice(h.recDist, "seam_recdist");
2454 geom_.recCell = toDevice(h.recCell, "seam_reccell");
2455 geom_.recW = toDevice(h.recW, "seam_recw");
2456 seamSampleRecords_ = h.numSampleRecords;
2457 seamLayerRecords_ = h.numLayerRecords;
2458 }
2460 void clearSeamRecon() {
2461 geom_.seam = View<Index>{};
2462 geom_.sampI = View<Index>{};
2463 geom_.sampJ = View<Index>{};
2464 geom_.uuRecI = View<Index>{};
2465 geom_.uuRecJ = View<Index>{};
2466 geom_.d1I = View<double>{};
2467 geom_.d1J = View<double>{};
2468 geom_.recStart = View<Index>{};
2469 geom_.recDist = View<double>{};
2470 geom_.recCell = View<Index>{};
2471 geom_.recW = View<double>{};
2472 seamSampleRecords_ = 0;
2473 seamLayerRecords_ = 0;
2474 }
2475
2476 // Host build of the ghost-gradient overlay (setGhostGradient): one row per cut cell (fluid
2477 // with a solid face neighbour — the cells where the ABC grad3 is gauge-dependent O(1/h)),
2478 // holding a 3-point directional FD stencil per axis. Mirrors oracle::AmrFlow::gradOfDir: cut
2479 // cells have same-level face neighbours by the finest-band contract; the ±2 probe falls back
2480 // to the 2-point one-sided closure when that cell is solid or not same-level.
2481 void buildGhostGradOverlay() {
2482 const Index n = t_->numLeaves();
2483 std::vector<Index> cells;
2484 for (Index i = 0; i < n; ++i)
2485 if (mom_.isCut(i))
2486 cells.push_back(i);
2487 const Index m = static_cast<Index>(cells.size());
2488 std::vector<Index> idx(static_cast<std::size_t>(m) * 9, 0);
2489 std::vector<double> w(static_cast<std::size_t>(m) * 9, 0.0);
2490 // Pocket cells (fragmentation guard) count as solid for the directional gradient: their φ is
2491 // pinned/decoupled, and reading the pinned 0 is the gauge-dependent defect the ghost
2492 // gradient exists to avoid. Levels via pres_.levelOf: ghost-slot-safe in distributed
2493 // builds (identical to t_->level for local leaves; the pocket guard is single-rank-only —
2494 // gpPocket_ stays empty distributed until the label-propagation guard lands).
2495 auto ok = [&](Index j, Index i) {
2496 return j >= 0 && mom_.isFluid(j) && pres_.levelOf(j) == pres_.levelOf(i) &&
2497 !(!gpPocket_.empty() && j < n && gpPocket_[static_cast<std::size_t>(j)]);
2498 };
2499 for (Index s = 0; s < m; ++s) {
2500 const Index i = cells[static_cast<std::size_t>(s)];
2501 const double h = pres_.cellWidth(i);
2502 for (int a = 0; a < 3; ++a) {
2503 const std::size_t o = static_cast<std::size_t>(s) * 9 + static_cast<std::size_t>(a) * 3;
2504 for (int k = 0; k < 3; ++k)
2505 idx[o + static_cast<std::size_t>(k)] = i; // safe defaults (w = 0)
2506 const Index jp = pres_.periodicNeighbor(i, a, +1);
2507 const Index jm = pres_.periodicNeighbor(i, a, -1);
2508 const bool ap = ok(jp, i), am = ok(jm, i);
2509 if (am && ap) {
2510 idx[o] = jp;
2511 w[o] = 0.5 / h;
2512 idx[o + 1] = jm;
2513 w[o + 1] = -0.5 / h;
2514 } else if (ap) {
2515 const Index jpp = pres_.periodicNeighbor(jp, a, +1);
2516 if (ok(jpp, i)) {
2517 idx[o] = i;
2518 w[o] = -1.5 / h;
2519 idx[o + 1] = jp;
2520 w[o + 1] = 2.0 / h;
2521 idx[o + 2] = jpp;
2522 w[o + 2] = -0.5 / h;
2523 } else {
2524 idx[o] = jp;
2525 w[o] = 1.0 / h;
2526 idx[o + 1] = i;
2527 w[o + 1] = -1.0 / h;
2528 }
2529 } else if (am) {
2530 const Index jmm = pres_.periodicNeighbor(jm, a, -1);
2531 if (ok(jmm, i)) {
2532 idx[o] = i;
2533 w[o] = 1.5 / h;
2534 idx[o + 1] = jm;
2535 w[o + 1] = -2.0 / h;
2536 idx[o + 2] = jmm;
2537 w[o + 2] = 0.5 / h;
2538 } else {
2539 idx[o] = i;
2540 w[o] = 1.0 / h;
2541 idx[o + 1] = jm;
2542 w[o + 1] = -1.0 / h;
2543 }
2544 } // sandwiched: all weights stay 0
2545 }
2546 }
2547 gc_.n = m;
2548 gc_.cell = toDevice(cells, "gc_cell");
2549 gc_.idx = toDevice(idx, "gc_idx");
2550 gc_.w = toDevice(w, "gc_w");
2551 }
2552
2553 // Fluid area fraction of a face. DEFAULT (order 2, 2026-08-26 user decision): triangle-fan
2554 // marching squares on FIVE ANALYTIC samples (4 corners + centre) -- exact linear fraction per
2555 // triangle, O(h^2), no saddle ambiguity, and the sub-resolution floor 1e-6 (alpha ~ 1e-12 rows
2556 // destroy the pressure conditioning -- flow tracker rows 51/52). Because the AMR solver holds
2557 // the analytic sdfFn, this samples the TRUE geometry (no trilinear ceiling). order 1 = the
2558 // legacy one-sample gradient-normalised linear model (kept for A/B), which carries a SIGNED
2559 // convexity bias measured at +0.59%/+0.27% bed permeability at R=8/12 (decay ~h^2).
2560 static double triFrac(double a, double b, double c) {
2561 const bool pa = a >= 0.0, pb = b >= 0.0, pc = c >= 0.0;
2562 const int np = (pa ? 1 : 0) + (pb ? 1 : 0) + (pc ? 1 : 0);
2563 if (np == 3)
2564 return 1.0;
2565 if (np == 0)
2566 return 0.0;
2567 double x, y, z;
2568 if (np == 1) {
2569 if (pa) {
2570 x = a;
2571 y = b;
2572 z = c;
2573 } else if (pb) {
2574 x = b;
2575 y = c;
2576 z = a;
2577 } else {
2578 x = c;
2579 y = a;
2580 z = b;
2581 }
2582 const double den = (x - y) * (x - z);
2583 return den > 1e-300 ? (x * x) / den : 1.0;
2584 }
2585 if (!pa) {
2586 x = a;
2587 y = b;
2588 z = c;
2589 } else if (!pb) {
2590 x = b;
2591 y = c;
2592 z = a;
2593 } else {
2594 x = c;
2595 y = a;
2596 z = b;
2597 }
2598 const double den = (x - y) * (x - z);
2599 return 1.0 - (den > 1e-300 ? (x * x) / den : 1.0);
2600 }
2601 template <class SdfFn>
2602 double faceFrac(SdfFn&& sdfFn, const Vec<3>& fc, int axis) const {
2603 if (apertureOrder_ >= 2) {
2604 if (sdfFn(fc) <= 0.0)
2605 return 0.0; // center gate (kept from order 1; see flow ccFaceOpenMS)
2606 const int t1 = (axis + 1) % 3, t2 = (axis + 2) % 3;
2607 // Phase 3: the four corner probes sit half a cell out on EACH tangential axis.
2608 const double e1 = 0.5 * h0_[t1], e2 = 0.5 * h0_[t2];
2609 auto at = [&](double d1, double d2) {
2610 Vec<3> p = fc;
2611 p[t1] += d1;
2612 p[t2] += d2;
2613 return sdfFn(p);
2614 };
2615 const double c00 = at(-e1, -e2), c10 = at(e1, -e2), c11 = at(e1, e2), c01 = at(-e1, e2);
2616 const double cc = sdfFn(fc);
2617 const double frac = 0.25 * (triFrac(c00, c10, cc) + triFrac(c10, c11, cc) +
2618 triFrac(c11, c01, cc) + triFrac(c01, c00, cc));
2619 return frac < 1e-3 ? 0.0 : (frac > 1.0 - 1e-12 ? 1.0 : frac); // floor: see flow ccFaceOpenMS
2620 }
2621 double sd = sdfFn(fc);
2622 if (sd <= 0.0)
2623 return 0.0;
2624 Vec<3> g{};
2625 for (int d = 0; d < 3; ++d) {
2626 Vec<3> pp = fc, pm = fc;
2627 pp[d] += h0_[d];
2628 pm[d] -= h0_[d];
2629 g[d] = (sdfFn(pp) - sdfFn(pm)) / (2.0 * h0_[d]);
2630 }
2631 double gmag = std::sqrt(g[0] * g[0] + g[1] * g[1] + g[2] * g[2]);
2632 if (gmag < 1e-6)
2633 gmag = 1e-6;
2634 int t1 = (axis + 1) % 3, t2 = (axis + 2) % 3;
2635 // Phase 3: the projected in-plane extent of the face, per tangential axis.
2636 double denom = (std::fabs(g[t1]) * h0_[t1] + std::fabs(g[t2]) * h0_[t2]) / gmag;
2637 if (denom < 1e-9)
2638 denom = 1e-9;
2639 double frac = 0.5 + sd / denom;
2640 return frac < 0.0 ? 0.0 : (frac > 1.0 ? 1.0 : frac);
2641 }
2642
2643 const Octree* t_ = nullptr;
2644 Vec<3> h0_ = detail::filledVec<3>(1.0);
2645 Vec<3> origin_{};
2646 double rho_ = 1.0, mu_ = 1.0, dt_ = 1e6;
2647 Vec<3> f_{};
2648 bool presPCG_ = true;
2649 bool presDbgSpdDone_ = false; // one-shot debug SPD probe (PECLET_AMR_PRES_DEBUG)
2650 bool momMGon_ = true; // velocity-MG momentum preconditioner (scalable; see setMomentumMG)
2651 bool useStaircaseMG_ = false; // false = Galerkin (MomentumMG), true = staircase (VelocityMG)
2652 int mgVcPre_ = 2, mgVcBottom_ = 30; // momentum-MG V-cycle pre/post sweeps + bottom sweeps
2653 Index mgMinCoarse_ = 256; // staircase velocity-MG pore-scale cap (coarsest cell count)
2654 bool momGS_ = false; // opt-in: multicolour Gauss–Seidel smoother in the momentum MG
2655 bool momMGSolver_ =
2656 false; // opt-in (P4): velocity-MG as the solver (defect correction), not BiCGStab
2657 bool ghostGrad_ = true; // gauge-exact directional cell gradient (setGhostGradient) — the
2658 // DEFAULT since 2026-08-18, mirroring flow's collocated
2659 // set_collocated_scheme("gauge-exact")
2660 bool ghostProj_ = false; // RESOLVED projection mode (set by setSolid from the request)
2661 int8_t ghostProjReq_ = -1; // -1 = AUTO (DEFAULT since 2026-08-25: ghost, aperture fallback
2662 // on thin band), 0 = explicit aperture, 1 = explicit ghost
2663 int apertureOrder_ = 2; // aperture estimator order (setApertureOrder; default 2)
2664 int gpMatrixOrder_ = 2, gpRhsOrder_ = 2; // closure orders (2,2 = the production pair; the
2665 // (1,2) mixed form is march-unstable at scale)
2666 // DEFAULT since 2026-09-21 (user decision): the Martin-Cartwright tangential quadratic, NOT the
2667 // standard two-point flux. The register had already settled that "cf=1 is not optional on graded
2668 // meshes" and rejected cf=0 there, but the shipped default stayed standard, so a user who built a
2669 // graded mesh silently got the configuration the project had decided against. Measured on a
2670 // self-similar ladder (docs/amr_graded_convergence.md §3), as orders:
2671 //
2672 // standard quadratic
2673 // interface NORMAL to the variation 2.00 2.00 (inert: no tangential variation to
2674 // interface TANGENTIAL 0.41 1.60 correct, so the delta is empty)
2675 //
2676 // with the absolute gap on the tangential arm widening 3.8x at n=32 to 8.8x at n=64. INERT BY
2677 // GEOMETRY on any uniform or finest-band mesh: no C/F faces means an empty delta CSR and the
2678 // identical code path, so only graded runs move.
2679 CfScheme cfScheme_ = CfScheme::quadratic; // 2:1 C/F interface scheme (setCfScheme)
2680 int outerIters_ = 1; // Picard outer iterations over the lagged advection (default 1)
2681 double outerTol_ = 1e-6; // outer-loop early-stop tolerance on max|Δu|
2682 double momTol_ = 1e-8; // per-step momentum BiCGStab relative tolerance (Phase-0 knob)
2683 double presTol_ = 1e-10; // pressure solve relative tolerance (MG-PCG and ghost BiCGStab)
2684 bool advect_ = true; // momentum advection ∇·(u u), ON by default (off ⇒ Stokes)
2685 bool implicitFou_ = true; // implicit-FOU deferred-correction (stable) vs fully-explicit
2686 int advScheme_ = 0; // high-order flux: 0 = SOU (default), 1 = Koren TVD
2687 Index n_ = 0;
2688 bool ready_ = false; // an operator exists (setSolid ran; cleared by beginAdapt)
2689 int lastMomIters_ = 0, lastPresIters_ = 0, lastOuterIters_ = 1;
2690 // M0 step profiler (PECLET_AMR_PROFILE_STEP): all inert unless stepProf_.
2691 bool stepProf_ = amrEnvFlag("PECLET_AMR_PROFILE_STEP");
2692 bool spHeader_ = false;
2693 int spWindow_ = [] {
2694 const char* e = std::getenv("PECLET_AMR_PROFILE_STEP_WINDOW");
2695 const int v = e ? std::atoi(e) : 0;
2696 return v > 0 ? v : 50;
2697 }();
2698 int spSteps_ = 0;
2699 double spAcc_[SP_N] = {};
2700 double spMom_ = 0.0, spPres_ = 0.0, spOuter_ = 0.0;
2701
2702 AmrCutCell<Bits> mom_;
2703 AmrPoisson<3, Bits> pres_;
2704 Multigrid<3, Bits> presMG_;
2708 Index presBottomExtent_ = 4;
2709 MomentumMG<Bits> momMG_; // Galerkin velocity multigrid (momentum preconditioner)
2710 VelocityMG<Bits> velMG_; // rediscretized staircase velocity multigrid (alternative)
2711 MomentumOp momOp_;
2712 MomentumSolver<Bits> momSolver_;
2713 PCG<3, Bits> pcg_;
2714 std::array<View<double>, 3> defc_; // explicit ρ(SOU−FOU) deferred correction per component
2715 View<double> advDiag_, advCoef_; // device-resident implicit-FOU operator (rebuilt each step)
2716 FaceGeom geom_;
2717 GhostGradOverlay gc_; // directional ghost-gradient overlay (empty unless setGhostGradient)
2718 GhostOverlayDev gpOv_; // closure overlay (empty unless setGhostProjection)
2719 bool ghostSampled_ = false; // RESOLVED sampled mode (set by setSolid)
2720 int8_t ghostSampledReq_ = 0; // setGhostSampled request (mixed-level cut band)
2721 double gpsRho_ = 2.2; // sampled band: LS cloud radius factor (setGhostSampled)
2722 long gpsMaxN_ = 0; // sampled band: nearest-N candidate cap, 0 = uncapped
2723 GhostOverlaySampledDev gpOvS_; // sample-slot overlay (empty unless sampled)
2724 GhostGradCsrDev gcS_; // sampled CSR directional-gradient overlay
2725 CfCsrDev gpsMomDelta_; // momentum ξ-row seam correction (rscale-folded)
2726 std::vector<char> gpPocket_; // fragmentation guard: 1 = decoupled pocket cell (ghost mode)
2727 CfCsrDev cfMom_; // +μ(∇²_scheme − ∇²_std) momentum RHS overlay
2728 CfCompCsrDev cfDiv_; // (D_scheme − D_std) divergence overlay
2729 std::array<CfCsrDev, 3> cfGrad_; // (G_scheme − G_std) per gradient axis
2730 CfCompCsrDev cfUfVel_; // (uf_scheme − uf_std) face-field overlay: velocity part
2731 Index cfGhostCols_ = 0; // overlay entries reading a ghost slot (diagnostic)
2732 Index cfCutFaces_ = 0; // C/F slots where the face gate withholds the quadratic
2733 bool seamRecon_ = true; // seam reconstruction of the advected value (§5.5, default on)
2734 Index seamSampleRecords_ = 0; // seam tables: sample records built (docs/amr_cf_convective.md)
2735 Index seamLayerRecords_ = 0; // seam tables: face-layer records built
2736 View<double> maskC_; // 1 = coupled row (Krylov subspace), 0 = pinned
2737 View<double> gpr_, gprh_, gpp_, gpph_, gpv_, gps_, gpsh_, gpt_; // ghost BiCGStab scratch
2738 View<double> rscale_;
2739 View<char> fluid_;
2740 std::array<View<double>, 3> u_, gx_;
2741 std::array<View<double>, 3> u0_,
2742 uprev_; // frozen uⁿ (BE mass term) + previous Picard outer iterate
2743 View<double> p_, phi_, div_, bmom_;
2744 View<double> uf_; // ABC/Basilisk divergence-free face field (one per CSR (sub)face)
2745 bool faceFieldBuilt_ =
2746 false; // uf_ populated by a projection (else advection falls back to ½(u_i+u_j))
2747 bool ufAdvect_ = true; // ABLATION (diagnostics): advect with uf_ (ON, the shipped scheme) or
2748 // with the un-projected ½(u_i+u_j) — see setUfAdvection
2749 std::unique_ptr<Octree> adaptOldT_; // beginAdapt topology snapshot
2750 std::array<std::vector<double>, 3> adaptU_; // beginAdapt field snapshots
2751 std::vector<double> adaptP_;
2752 std::array<std::vector<std::array<double, 3>>, 3> adaptGradU_; // distributed transfer grads
2753 std::vector<std::array<double, 3>> adaptGradP_;
2754
2755 // ---- distributed context (initMpi; all null/empty single-rank) -----------------------------
2756 DistributedOctree<3, Bits>* dist_ = nullptr; // the ORB block + communicator
2757 LeafHalo<3, Bits> dhalo_; // the flow's ±2 ghost registry (frozen in setSolid)
2758 LeafHaloExchange dhex_; // device value refresh over dhalo_
2759 DistributedFlowMultigrid<3, Bits> presMGD_; // distributed pressure MG (level 0 on dhalo_)
2760 std::array<long, 3> shiftD_{}; // block global fine origin
2761 Index nExt_ = 0; // n_ + ghosts (== n_ single-rank)
2762 std::function<double(double)> allred_; // Allreduce hook (empty single-rank)
2763};
2764
2765} // namespace peclet::amr
2766
2767#endif // PECLET_AMR_FLOW_HPP
void setImplicitAdvection(bool on)
Implicit-FOU deferred correction (default ON).
Definition flow.hpp:643
Index numSeamSampleRecords() const
Seam-reconstruction census (docs/amr_cf_convective.md §5.2): how many sample records (one per 2:1 sub...
Definition flow.hpp:2039
void setApertureOrder(int order)
FULL directional ghost-cell projection (the AMR port of flow's collocated set_ghost_projection): the ...
Definition flow.hpp:597
void setMomentumMG(bool on)
Use the Galerkin velocity multigrid (MomentumMG) as the momentum BiCGStab preconditioner.
Definition flow.hpp:688
std::vector< double > velocity(int c) const
Copy a velocity component back to host (single D2H, no host loop — S2a).
Definition flow.hpp:1828
void finishAdapt(SdfFn &&sdfFn)
Rebuild on the mutated octree and transfer the snapshotted fields onto it.
Definition flow.hpp:1697
void setGhostGradient(bool on)
Directional ghost cell-gradient for the −∇pⁿ predictor and the projection's cell correction (the AMR ...
Definition flow.hpp:567
void ghostPrec(View< const double > r, View< double > z)
Definition flow.hpp:2342
void step(int momIters=100, int presIters=60)
Definition flow.hpp:1348
void initMpi(DistributedOctree< 3, Bits > &d)
Distributed mode (docs/amr_distributed_flow.md, rung 4): run this solver on one ORB block of a Distri...
Definition flow.hpp:534
void gpProject(View< double > v)
Definition flow.hpp:2324
void prepareDistributed(SdfFn &&sdfFn)
Install the resolver seams, run every prober to the miss-collect fixpoint, freeze the ±2 halo,...
Definition flow.hpp:2104
void setBodyForce(double fx, double fy, double fz)
Definition flow.hpp:550
void setPressurePCG(bool on)
Use MG-preconditioned CG for the pressure solve (default) vs plain V-cycles.
Definition flow.hpp:552
void syncVel()
Refresh the ghost tails of the three velocity components (one batched message round).
Definition flow.hpp:2069
std::vector< double > velocities() const
All three velocity components interleaved as a flat (n,3) row-major host buffer (out[i*3+c]) with a s...
Definition flow.hpp:1847
std::vector< double > pressure() const
Copy the pressure field back to host (single D2H), (num_leaves,) — the incremental-rotational p.
Definition flow.hpp:1831
void setPressureTol(double tol)
Relative tolerance of the PRESSURE solve, for both drivers: the MG-PCG (the default) and the ghost pr...
Definition flow.hpp:662
void setVelocityMGMinCoarse(Index m)
Pore-scale cap for the staircase velocity-MG: the coarsest level keeps ≥ this many cells,...
Definition flow.hpp:699
void setVelocity(int c, const std::vector< double > &h)
Set a velocity component from host (testing / initial conditions).
Definition flow.hpp:1820
void setDt(double dt)
Definition flow.hpp:549
bool isFluid(Index i) const
Per-leaf fluid mask (false inside the solid) — for host-side post-processing / bindings.
Definition flow.hpp:2058
double divNormL2()
L2 norm of the (openness-weighted) divergence of the current velocity — the ghost-closed divergence w...
Definition flow.hpp:1861
std::array< long, 3 > globalFineExtent() const
The DOMAIN's fine extent (D1): the block's own single-rank, where block == domain.
Definition flow.hpp:2089
void copyToHost(const View< double > &d, std::vector< double > &h) const
Copy a device View into a host vector (sized n_).
Definition flow.hpp:1813
void setAdvectionScheme(int s)
High-order advection scheme: 0 = second-order upwind (SOU, default), 1 = Koren TVD.
Definition flow.hpp:645
int solveGhostBiCGStab(View< double > x, View< const double > b, int maxIters, double tol=1e-10)
Definition flow.hpp:2364
void init(const Octree &t, const Vec< 3 > &h0, Vec< 3 > origin=Vec< 3 >{})
Definition flow.hpp:519
void installGhostMeta()
Mirror the halo registry's ghost metadata (block-local lo + level) into mom_ and pres_.
Definition flow.hpp:2305
std::vector< double > debugSou(int comp)
DEBUG: the raw high-order advection ∇·(u u_comp) per cell from the current velocity (== host oracle::...
Definition flow.hpp:1764
void setViscosity(double mu)
Definition flow.hpp:548
Index numGhostCells() const
Distributed: number of ghost slots in the ±2 registry (0 single-rank).
Definition flow.hpp:2045
void runMgVcycle(MG &mg, View< const double > r, View< double > z)
Run one V-cycle of a momentum MG as a preconditioner: z = M⁻¹ r.
Definition flow.hpp:1781
Index numCfGhostColumns() const
Developer diagnostic: entries of the four C/F-scheme overlays that read a GHOST slot (0 single-rank,...
Definition flow.hpp:2049
void finishProjection(Index n)
Shared projection tail: build the div-free face field from u* + φ, correct the cell velocities (ABC /...
Definition flow.hpp:1618
void setGhostProjection(bool on, int matrixOrder=2, int rhsOrder=2)
Definition flow.hpp:598
void probeCfScheme()
Discovery arm for the C/F quadratic scheme (cf_scheme.hpp), run inside prepareDistributed's miss-coll...
Definition flow.hpp:2217
Index pressureBottomExtent() const
The bottom extent the next setSolid builds the ladder with (default 4).
Definition flow.hpp:1966
Index numSeamLayerRecords() const
The face-layer half of the census: one record per (regular coarse cell, face) whose far side is refin...
Definition flow.hpp:2042
int lastOuterIters() const
Picard outer iterations actually run in the last step (1 unless setOuterIterations(>1)).
Definition flow.hpp:2064
void setDensity(double rho)
Definition flow.hpp:547
Index numCfCutFaces() const
The C/F census (docs/amr_cf_flux_gate.md §6.5): owned forEachFaceFull slots on a 2:1 sub-face between...
Definition flow.hpp:2056
double divNormFace()
L2 norm of the APERTURE-weighted divergence of the ABC face field uf_ (built each project()).
Definition flow.hpp:1890
void ghostMatvec(View< const double > x, View< double > y)
Definition flow.hpp:2328
void spAdd(int ph, SpClock::time_point t0)
Definition flow.hpp:1284
void setPressureBottom(const std::string &kind)
What solves the coarsest pressure level (docs/amr_mg_depth.md §6.6/§11.6): "auto" (the default — the ...
Definition flow.hpp:1934
std::string pressureMgBottom() const
What actually solves the coarsest pressure level (docs/amr_mg_depth.md §6.6/§6.7): "jacobi" (60 dampe...
Definition flow.hpp:1918
void project(int presIters=60)
Pressure projection of the current velocity in place.
Definition flow.hpp:1472
void syncScalar(View< double > v)
Refresh the ghost tail of one cell scalar (p, φ, Krylov scratch).
Definition flow.hpp:2074
std::vector< double > faceField() const
Copy the divergence-free face field to host (one value per CSR (sub)face, forEachFaceFull order).
Definition flow.hpp:1970
void setMomentumTol(double tol)
Relative tolerance for the per-step momentum BiCGStab solve (default 1e-8).
Definition flow.hpp:655
void setSeamReconstruction(bool on)
ABLATION (docs/amr_cf_convective.md §5.5, Q-C).
Definition flow.hpp:680
void setPressureBottomExtent(Index e)
Where the pressure ladder stops lifting the root and hands over to the bottom (docs/amr_mg_depth....
Definition flow.hpp:1960
Index numLeaves() const
Definition flow.hpp:2043
void setUfAdvection(bool on)
ABLATION (developer tier).
Definition flow.hpp:671
void setPressure(const std::vector< double > &h)
Write the accumulated rotational pressure from host (restart / finishAdapt).
Definition flow.hpp:1745
std::vector< double > localVector(const View< double > &v) const
Host copy of the LOCAL rows of a (possibly ghost-extended) per-cell field.
Definition flow.hpp:1834
const FvOp & gpOp0()
The pressure operator the ghost solver runs on (distributed MG level 0 or presMG_'s).
Definition flow.hpp:2098
std::chrono::steady_clock SpClock
Definition flow.hpp:1277
void probeCfTangential(Index coarse, int axis)
Every coordinate cfAppendStencil can probe from the coarse cell of one C/F face: the tangential ± nei...
Definition flow.hpp:2233
void setVelocityMGStaircase(bool on)
Choose the momentum-MG coarse-operator strategy: false (default) = Galerkin (MomentumMG,...
Definition flow.hpp:694
BlockOctree< 3, Bits > Octree
Definition flow.hpp:513
void zeroSolid(View< double > v)
Zero a per-leaf field on non-fluid cells (the transferred fields' solid cleanup).
Definition flow.hpp:1753
void spEndStep()
Close a profiled step; print + reset when the window fills.
Definition flow.hpp:1291
int lastPresIters() const
Pressure PCG iterations of the last step.
Definition flow.hpp:2062
void requireOperator(const char *what) const
Every solve entry point needs the cut-cell operators that setSolid builds; without them the state vie...
Definition flow.hpp:1340
void rebalanceMpi(SdfFn &&sdfFn)
Distributed load rebalance (docs/amr_distributed_flow.md, rung 6): re-decompose the octree by leaf co...
Definition flow.hpp:1727
void probeSeamLayer()
Discovery arm for the SEAM builder (seam_recon.hpp), run beside probeCfScheme() inside prepareDistrib...
Definition flow.hpp:2271
StepPhase
One incompressible step on device (Stokes, or Navier–Stokes with setAdvection).
Definition flow.hpp:1260
static double maxAbsDiff(View< const double > a, View< const double > b, Index n)
Max |a − b| over all cells (the Picard outer-loop convergence measure).
Definition flow.hpp:1798
std::vector< Index > pressureMgLevels() const
The pressure multigrid's ladder as BUILT on this rank: per-level leaf counts, level 0 first (docs/amr...
Definition flow.hpp:1900
int lastMomIters() const
Total momentum BiCGStab iterations (summed over the 3 components) of the last step.
Definition flow.hpp:2060
void beginAdapt()
Snapshot the octree topology + (u, p) ahead of an external mesh mutation.
Definition flow.hpp:1677
void setGhostSampled(bool on, double rho=2.2, long maxSamples=0)
SAMPLED ghost projection: the mixed-level cut-band mode (docs/amr_mixed_level_cut_band_plan....
Definition flow.hpp:614
Vec< 3 > betaPerAxis() const
The viscous coefficient of each derivative axis, mu/h0_a^2 — the octree twin of the structured solver...
Definition flow.hpp:541
void setMomentumGS(bool on)
Opt-in: use the multicolour Gauss–Seidel smoother in the momentum MG (Galerkin or staircase) instead ...
Definition flow.hpp:703
void setMomentumMGSolver(bool on)
Opt-in (P4): solve the momentum predictor with the velocity multigrid used as the solver — MG-precond...
Definition flow.hpp:717
std::vector< double > slotCenters() const
World centre of every slot of the extended (local + ghost) leaf array, row-major (nExt,...
Definition flow.hpp:2025
double allSum(double s) const
Global sum (identity single-rank).
Definition flow.hpp:2079
void setAdvection(bool on)
Momentum advection ∇·(u u), ON by default (user directive 2026-10-23, amr 2026-10-24; setAdvection(fa...
Definition flow.hpp:640
void setCfScheme(int scheme)
Coarse/fine (2:1) interface scheme (cf_scheme.hpp): 1 = Martin–Cartwright tangential quadratic,...
Definition flow.hpp:632
void setSolid(SdfFn &&sdfFn)
Build the cut-cell operators (host) + upload all device structures.
Definition flow.hpp:732
void setOuterIterations(int n, double tol=1e-6)
Optional Picard outer loop over the lagged advection (mirror of flow's outerIters_): each outer itera...
Definition flow.hpp:724
FaceTopologyHost faceTopology() const
Definition flow.hpp:1996
void init(const Octree &t, Real h0, Vec< 3 > origin=Vec< 3 >{})
Cubic-cell overload — the pre-Phase-3 spelling (docs/amr_anisotropic.md §2).
Definition flow.hpp:516
SpClock::time_point spMark() const
Definition flow.hpp:1278
Cell-centered FV Poisson operator on one (periodic) block octree.
Definition poisson.hpp:43
void forEachFaceFull(Index i, Fn &&fn) const
Like forEachFaceNeighbor but exposes geometry for a consistent FV divergence/gradient: fn(neighbour,...
Definition poisson.hpp:329
Index periodicNeighbor(Index i, int axis, int dir) const
Periodic face neighbour leaf (covering the cell just across the face).
Definition poisson.hpp:375
const Octree & octree() const
Definition poisson.hpp:586
Real cellVolume(Index i) const
Definition poisson.hpp:262
Per-block adaptive octree over block-local Morton codes.
const Vec< Dim > & h0() const
Phase 3: the FINEST spacing per axis (docs/amr_anisotropic.md §2).
const AmrGeometry< Dim > & globalGeometry() const
Bottom
What solves the coarsest level (docs/amr_mg_depth.md §6.6).
Vec< Dim > filledVec(Real v)
Vec<Dim> with every component set to v (C++ has no aggregate-fill initializer).
FaceGeom buildFaceGeom(const AmrPoisson< Dim, Bits > &ap, FluidFn &&isFluid)
Build FaceGeom from a built AmrPoisson (openness set) + a fluid predicate.
Definition flow.hpp:72
void divergence(const FaceGeom &g, View< const double > u0, View< const double > u1, View< const double > u2, View< double > div)
Openness-weighted FV divergence: div_i = invVol_i Σ_faces α·area·dir·½(u^axis_i+u^axis_j),...
Definition flow.hpp:127
void correct(View< double > uc, View< const double > gphi, View< const char > fluid, Index n)
u_c -= gradPhi_c on fluid cells (the projection velocity correction).
Definition flow.hpp:489
void removeMeanVolReduced(View< double > u, View< const double > invVol, View< const double > mask, Index n, const std::function< double(double)> &reduce)
Project u onto the FLUID range: zero solid cells, then subtract the volume-weighted mean over the flu...
Definition pcg.hpp:80
Index countCfCutFaces(const AmrPoisson< 3, Bits > &ap, const BlockOctree< 3, Bits > &t, RegularFn &&regularOk, FluidFn &&fluidOk)
The C/F CENSUS (docs/amr_cf_flux_gate.md §6.5): how many OWNED forEachFaceFull slots (i,...
auto makeBinaryOpenFnMixed(const BlockOctree< 3, Bits > &t, const AmrPoisson< 3, Bits > &pres, SdfFn sdfFn, const Vec< 3 > &h0, Vec< 3 > origin, std::array< long, 3 > frameShift={})
The canonical (sub)face openness for mixed-level cut bands: open iff both adjacent ACTUAL leaf center...
CfCsrDev uploadCfCsr(const CfCsr &h, const char *name)
solver::MomentumSolver MomentumSolver
The BiCGStab solver never touched the octree: its Bits parameter was vestigial and is gone in core.
Definition momentum.hpp:45
GhostOverlaySampled buildGhostOverlaySampled(const BlockOctree< 3, Bits > &t, const AmrPoisson< 3, Bits > &pres, SdfFn &&sdf, int matrixOrder, int rhsOrder, Vec< 3 > origin=Vec< 3 >{}, const std::array< long, 3 > *globalFine=nullptr, std::array< long, 3 > frameShift={}, bool discovery=false, double rhoFactor=2.2, long maxSamples=0)
Build the sampled overlay.
void momRhs(View< const double > uc, View< const double > gradP, View< const double > adv, View< const double > rscale, View< const char > fluid, double idiag, double fc, View< double > b, Index n)
Momentum RHS for one component: b_i = fluid ?
Definition flow.hpp:291
void applyGhostGrad(const GhostGradOverlay &ov, View< const double > f, View< double > gx, View< double > gy, View< double > gz)
Overwrite gx/gy/gz on the overlay cells with the directional stencil applied to f.
Definition flow.hpp:264
MomentumOp assembleMomentum(const AmrCutCell< Bits > &ccop, const BlockOctreeView< 3, Bits > &ov, bool scaleAdvByRscale=false)
Assemble the MomentumOp entirely on the device from a built host AmrCutCell + a device octree view.
CfCompCsr buildCfDivDelta(const AmrPoisson< 3, Bits > &ap, const BlockOctree< 3, Bits > &t, RegularFn &&regularOk, FluidFn &&fluidOk, CfScheme scheme)
(D_scheme − D_std) for the face-average divergence div_i = invV·Σ α·A·dir·(face value).
void advectExplicit(const FaceGeom &g, View< const double > u0, View< const double > u1, View< const double > u2, int comp, double rho, int advScheme, View< double > defc, View< const double > uf, bool useFace, bool seamOn)
Fully-explicit high-order advection for component comp: defc = ρ·SOU (no implicit FOU; the setImplici...
Definition flow.hpp:443
void deferredSou(const FaceGeom &g, View< const double > u0, View< const double > u1, View< const double > u2, int comp, double rho, int advScheme, View< double > defc, View< const double > uf, bool useFace, bool seamOn)
Deferred-correction advection term for component comp: defc = ρ·SOU − ρ·FOU (UNSCALED; the predictor ...
Definition flow.hpp:395
void cfApply(const CfCsrDev &c, View< const double > f, View< double > out)
out(i) += Σ coef·f(slot).
double hoFaceValue(double upup, double up, double down, int scheme)
High-order advected face value from the two upwind cells (upup, up) and the downwind cell (down).
void buildFou(const FaceGeom &g, View< const double > u0, View< const double > u1, View< const double > u2, double rho, View< const double > rscale, View< double > advDiag, View< double > advCoef, View< const double > uf, bool useFace)
Build the implicit-FOU advection operator from the lagged velocity u0..2 (uⁿ) entirely on device,...
Definition flow.hpp:308
GhostOverlaySampledDev uploadGhostOverlaySampled(const GhostOverlaySampled &h)
CfCompCsrDev uploadCfCompCsr(const CfCompCsr &h, const char *name)
CfUfDelta buildCfUfDelta(const AmrPoisson< 3, Bits > &ap, const BlockOctree< 3, Bits > &t, RegularFn &&regularOk, FluidFn &&fluidOk, CfScheme scheme)
void presUpdate(View< double > p, View< const double > phi, View< const double > div, View< const char > fluid, double rho_dt, double mu, Index n)
Rotational incremental pressure update: p += (ρ/dt)φ − μ·div, on fluid cells.
Definition flow.hpp:498
SeamReconHost buildSeamRecon(const AmrPoisson< 3, Bits > &ap, RegularFn &&regularOk, FluidFn &&fluidOk, CfScheme scheme)
Build the seam-reconstruction tables over the LOCAL rows of ap (docs/amr_cf_convective....
double hoFaceValueSeam(double upup, double up, double upStar, double downStar, double d1, double dUU, double dD, int scheme)
The same reconstruction with every distance and every sample made explicit — the rule of docs/amr_cf_...
void ghostApplyDelta(const GhostOverlayDev &ov, View< const double > x, View< double > y)
Device matrix overlay (== ghostApplyDeltaHost). Distinct rows per thread: no atomics.
std::vector< std::array< double, Dim > > transferGradients(const DistributedOctree< Dim, Bits > &d, const std::vector< double > &f)
transferField's minmod prolongation gradients on a DistributedOctree: bit-identical to the block-loca...
std::vector< char > findPocketCells(const BlockOctree< 3, Bits > &t, const AmrPoisson< 3, Bits > &pres, const std::vector< double > &sdfC)
Fragmentation guard (the AMR port of flow's host-BFS pocket guard): the BINARY coupled-face graph (a ...
std::vector< double > transferField(const BlockOctree< Dim, Bits > &oldT, const std::vector< double > &oldF, const BlockOctree< Dim, Bits > &newT, bool linear=true, const std::type_identity_t< std::vector< std::array< double, Dim > > > *gradIn=nullptr)
Conservative remap of a leaf field from oldT to newT (same domain).
Definition adapt.hpp:91
GhostGradCsrHost buildSampledGradCsr(const GhostOverlaySampled &ov, const BlockOctree< 3, Bits > &t, const AmrPoisson< 3, Bits > &pres, IsCutFn &&isCut, OkFn &&classicOk)
void ghostApplyDeltaSampled(const GhostOverlaySampledDev &ov, View< const double > x, View< double > y)
Device matrix overlay (== ghostApplyDeltaSampledHost). Distinct rows per thread: no atomics.
void residualFv(const FvOp &op, View< const double > u, View< const double > rhs, View< double > res)
res = rhs − H u.
Definition fv_op.hpp:119
void grad3(const FaceGeom &g, View< const double > f, View< double > gx, View< double > gy, View< double > gz)
ABC cell-gradient of a scalar field f: gx/gy/gz = ½(g⁻+g⁺) of the adjacent face gradients along each ...
Definition flow.hpp:207
bool amrEnvFlag(const char *name)
Truthy environment flag (unset / "" / "0" ⇒ false).
Definition flow.hpp:62
void buildFaceField(const FaceGeom &g, View< const double > u0, View< const double > u1, View< const double > u2, View< const double > phi, View< double > uf)
Build the ABC/Basilisk divergence-free FACE field: uf(k) = ½(u^axis_i+u^axis_j) − (φ₊−φ₋)/dist for fa...
Definition flow.hpp:160
double divFaceNorm(const FaceGeom &g, View< const double > uf)
L2 norm of the divergence of the FACE field uf (the div-free flux diagnostic / host-parity check).
Definition flow.hpp:182
auto makeBinaryOpenFn(SdfFn sdfFn, const Vec< 3 > &h0)
Binary openness callable factory for the MG surrogate: a face is open iff both adjacent centers (prob...
FaceGeom assembleFaceGeom(const AmrPoisson< 3, Bits > &ap, const std::vector< char > &fluidHost, const BlockOctreeView< 3, Bits > &ov)
Assemble the collocated FaceGeom entirely on device from a built AmrPoisson (openness set) + a per-ce...
void applyGhostGradCsr(const GhostGradCsrDev &ov, View< const double > f, View< double > gx, View< double > gy, View< double > gz)
CfCsr buildCfLapDelta(const AmrPoisson< 3, Bits > &ap, const BlockOctree< 3, Bits > &t, double factor, RowFn &&rowOk, FluidFn &&fluidOk, CfScheme scheme)
(∇²_scheme − ∇²_std) as a scalar CSR, ×factor (pass μ for the momentum deferred-correction RHS,...
void ghostDivergDeltaSampled(const GhostOverlaySampledDev &ov, View< const double > u0, View< const double > u1, View< const double > u2, View< double > d)
Device divergence overlay (== ghostDivergDeltaSampledHost).
void applyFv(const FvOp &op, View< const double > u, View< double > Lu)
Hu = (c0·I + cD·L) u (consistent conservative FV Laplacian, c0=0/cD=1 ⇒ pure L).
Definition fv_op.hpp:112
GhostGradCsrDev uploadGhostGradCsr(const GhostGradCsrHost &h)
GhostOverlayDev uploadGhostOverlay(const GhostOverlay &h)
double advectedFaceValue(const SeamView &sv, Index k, bool upIsI, double phiUpUp, double phiUp, double phiDown, double distK, int advScheme, const FldFn &fld)
THE advected face value at one (sub)face slot — written once so deferredSou and advectExplicit cannot...
Definition flow.hpp:366
std::array< CfCsr, 3 > buildCfGradDelta(const AmrPoisson< 3, Bits > &ap, const BlockOctree< 3, Bits > &t, RegularFn &&regularOk, FluidFn &&fluidOk, CfScheme scheme)
(G_scheme − G_std) for the ABC cell gradient gradOf/grad3.
SeamView makeSeamView(const FaceGeom &g, bool on)
Bundle a FaceGeom's seam tables for the kernels.
Definition face_geom.hpp:76
void ghostDivergDelta(const GhostOverlayDev &ov, View< const double > u0, View< const double > u1, View< const double > u2, View< double > d)
Device divergence overlay (== ghostDivergDeltaHost).
CfCsr buildMomSeamDelta(const GhostOverlaySampled &ov, const BlockOctree< 3, Bits > &t, const AmrPoisson< 3, Bits > &pres, const Mom &mom, SdfFn &&sdf, Vec< 3 > origin, double idiag, double mu, long *nSkipped=nullptr, std::array< long, 3 > frameShift={})
Momentum ξ-overlay seam correction (plan §6.2, rung 1): at overlay rows with a different-level ±1 nei...
void cfApplyComp(const CfCompCsrDev &c, View< const double > u0, View< const double > u1, View< const double > u2, View< double > out)
out(i) += Σ coef·u[comp](slot).
CfScheme
Coarse/fine interface scheme for the collocated flow operators.
Definition cf_scheme.hpp:73
@ standard
raw coarse value (two-point flux; 1st-order at 2:1 faces)
Definition cf_scheme.hpp:74
@ quadratic
Martin–Cartwright tangential quadratic (2nd-order at 2:1 faces).
Definition cf_scheme.hpp:75
GhostOverlay buildGhostOverlay(const BlockOctree< 3, Bits > &t, const AmrPoisson< 3, Bits > &pres, const std::vector< double > &sdfC, int matrixOrder, int rhsOrder, bool *bandViolation=nullptr)
Build the overlay from the octree + the cell-centered SDF samples (AmrCutCell::sdfCRaw — EXTENDED ove...
The face CSR topology faceField() is indexed by, copied to host: start the per-cell row offsets (size...
Definition flow.hpp:1980
std::vector< double > center
World centre of EVERY slot (local leaves then ghosts, size nExt): the only way a caller can say what ...
Definition flow.hpp:1994
std::vector< double > recDist
Definition flow.hpp:1989
std::vector< double > rawArea
Definition flow.hpp:1983
Device mirror of a BlockOctree's leaf arrays + device-callable queries.
void upload(const Host &t)
(Re)upload the host octree's current leaf set to the device.
View< Index > uuRecJ
per descriptor: upstream-probe record for up == j, else −1
Definition face_geom.hpp:45
View< double > recDist
per record: dUU for UPSTREAM use (unused as a φ_U* sample)
Definition face_geom.hpp:49
View< Index > uuRecI
per descriptor: upstream-probe record for up == i, else −1
Definition face_geom.hpp:44
View< Index > recCell
record entries: cell slot
Definition face_geom.hpp:50
View< double > alphaArea
α·area (physical) per face, size nFaces
Definition face_geom.hpp:28
View< int > dir
face direction +1/-1, size nFaces
Definition face_geom.hpp:27
View< double > recW
record entries: weight
Definition face_geom.hpp:51
View< double > invVol
1/V_i per cell, size n
Definition face_geom.hpp:34
View< double > rawArea
raw face area (physical, no openness) per face — advection flux
Definition face_geom.hpp:29
View< int > axis
face axis 0/1/2, size nFaces
Definition face_geom.hpp:26
View< Index > upupJ
upstream-of-j probe (periodicNeighbor(j,axis,+dir)) — SOU, size nFaces
Definition face_geom.hpp:33
View< Index > nbr
neighbour leaf per face, size nFaces
Definition face_geom.hpp:25
View< double > alpha
openness per face (gradient gate), size nFaces
Definition face_geom.hpp:31
View< double > dist
face-normal distance (physical) per face, size nFaces
Definition face_geom.hpp:30
View< Index > start
CSR row offsets, size n+1.
Definition face_geom.hpp:24
View< Index > sampI
per descriptor: sample record when i is the COARSE cell, else −1
Definition face_geom.hpp:42
View< Index > seam
descriptor id per face slot, −1 = plain slot; size nFaces
Definition face_geom.hpp:41
View< Index > upupI
upstream-of-i probe (periodicNeighbor(i,axis,−dir)) — SOU, size nFaces
Definition face_geom.hpp:32
View< Index > recStart
record CSR offsets, size nRec+1
Definition face_geom.hpp:48
View< char > fluid
per-cell fluid flag, size n
Definition face_geom.hpp:35
View< double > d1J
per descriptor: half width of j along the face axis (physical)
Definition face_geom.hpp:47
View< double > d1I
per descriptor: half width of i along the face axis (physical)
Definition face_geom.hpp:46
View< Index > sampJ
per descriptor: sample record when j is the COARSE cell, else −1
Definition face_geom.hpp:43
View< Index > faceStart
CSR row offsets, size n+1.
Definition fv_op.hpp:80
View< double > bcDiag
Dirichlet boundary diagonal per cell (0 if periodic), size n.
Definition fv_op.hpp:83
View< double > invVol
1/V_i, size n
Definition fv_op.hpp:79
View< double > faceW
w_f = openness·A_f/d_f per face, size nFaces
Definition fv_op.hpp:82
Ghost-gradient overlay (setGhostGradient): per cut cell, a precomputed 3-point directional FD stencil...
Definition flow.hpp:256
View< double > w
[n*9] stencil weight (0 = unused)
Definition flow.hpp:260
Index n
number of overlay (cut) cells
Definition flow.hpp:257
View< Index > idx
[n*9] stencil cell, slot s*9 + axis*3 + k
Definition flow.hpp:259
View< Index > cell
[n] leaf index
Definition flow.hpp:258
Sampled overlay: the classic per-row fields (weights, states, rescale — base; base....
Host ghost-projection overlay: one row per non-clean fluid leaf (== cut cell: some ±1 center sample s...
Host-side seam-reconstruction tables (docs/amr_cf_convective.md §5.2), built once per AmrFlow::setSol...
std::vector< Index > recStart
record CSR offsets, size nRec+1
std::vector< double > recW
record entries: weight
Index numSampleRecords
diagnostics: how many of the records are sample records
Index numLayerRecords
diagnostics: how many are layer records
std::vector< double > d1J
per descriptor: half width of j along the face axis (physical)
std::vector< Index > seam
per face slot: descriptor id, −1 = plain slot
std::vector< double > recDist
per record: dUU for UPSTREAM use (unused as a φ_U* sample)
std::vector< Index > sampI
per descriptor: sample record when i is the COARSE cell, else −1
std::vector< double > d1I
per descriptor: half width of i along the face axis (physical)
std::vector< Index > uuRecJ
per descriptor: upstream-probe record for up == j, else −1
std::vector< Index > sampJ
per descriptor: sample record when j is the COARSE cell, else −1
std::vector< Index > recCell
record entries: cell slot
std::vector< Index > uuRecI
per descriptor: upstream-probe record for up == i, else −1
The seam tables as the advective kernels capture them: const Views plus the ablation flag (AmrFlow::s...
Definition face_geom.hpp:58
View< const Index > sampI
Definition face_geom.hpp:59
View< const Index > seam
Definition face_geom.hpp:59
View< const double > d1J
Definition face_geom.hpp:60
View< const Index > sampJ
Definition face_geom.hpp:59
View< const double > d1I
Definition face_geom.hpp:60
View< const Index > uuRecJ
Definition face_geom.hpp:59
View< const double > recDist
Definition face_geom.hpp:60
double gather(Index r, const FldFn &fld) const
Σ over the record's entries IN RECORD ORDER, never reordered — that is what keeps np = 1 bitwise agai...
Definition face_geom.hpp:66
View< const Index > uuRecI
Definition face_geom.hpp:59