20#ifndef PECLET_AMR_FLOW_HPP
21#define PECLET_AMR_FLOW_HPP
54#include "peclet/core/common/host_parallel.hpp"
55#include "peclet/core/common/types.hpp"
56#include "peclet/core/common/view.hpp"
63 const char* v = std::getenv(name);
64 return v && v[0] && !(v[0] ==
'0' && v[1] ==
'\0');
71template <
int Dim,
unsigned Bits,
class Flu
idFn>
74 std::vector<Index> start(
static_cast<std::size_t
>(n) + 1, 0);
75 for (Index i = 0; i < n; ++i) {
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;
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;
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");
128 View<const double> u2, View<double> div) {
136 Kokkos::parallel_for(
137 "amr::flow_div", g.
n, KOKKOS_LAMBDA(
const Index i) {
143 for (Index k = st(i); k < st(i + 1); ++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);
161 View<const double> u2, View<const double> phi, View<double> uf) {
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) {
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;
189 Kokkos::parallel_reduce(
190 "amr::flow_divface", g.
n,
191 KOKKOS_LAMBDA(
const Index i,
double& acc) {
195 for (Index k = st(i); k < st(i + 1); ++k)
196 d += aA(k) * dr(k) * uf(k);
207inline void grad3(
const FaceGeom& g, View<const double> f, View<double> gx, View<double> gy,
216 Kokkos::parallel_for(
217 "amr::flow_grad3", g.
n, KOKKOS_LAMBDA(
const Index i) {
219 gx(i) = gy(i) = gz(i) = 0.0;
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) {
229 const double gg = (dr(k) > 0) ? (f(nb(k)) - fi) / di(k) : (fi - f(nb(k))) / di(k);
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);
265 View<double> gy, View<double> gz) {
271 Kokkos::parallel_for(
272 "amr::flow_ghostgrad", ov.
n, KOKKOS_LAMBDA(
const Index s) {
273 const Index i = cell(s);
275 for (
int a = 0; a < 3; ++a) {
277 for (
int k = 0; k < 3; ++k)
278 acc += w(s * 9 + a * 3 + k) * f(idx(s * 9 + a * 3 + k));
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;
309 View<const double> u2,
double rho, View<const double> rscale,
310 View<double> advDiag, View<double> advCoef, View<const double> uf,
319 Kokkos::parallel_for(
320 "amr::flow_buildfou", g.
n, KOKKOS_LAMBDA(
const Index i) {
323 for (Index k = st(i); k < st(i + 1); ++k)
327 const double rs = rscale(i);
329 for (Index k = st(i); k < st(i + 1); ++k) {
330 const Index j = nb(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);
365template <
class FldFn>
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);
371 return hoFaceValue(phiUpUp, phiUp, phiDown, advScheme);
372 const Index rs = upIsI ? sv.
sampI(s) : sv.
sampJ(s);
374 const Index rd = upIsI ? sv.
sampJ(s) : sv.
sampI(s);
375 const double d1 = upIsI ? sv.
d1I(s) : sv.
d1J(s);
376 const double upStar = (rs >= 0) ? sv.
gather(rs, fld) : phiUp;
379 double uu = phiUpUp, dUU = 2.0 * d1;
384 const double downStar = (advScheme != 0 && rd >= 0) ? sv.
gather(rd, fld) : phiDown;
385 return hoFaceValueSeam(uu, phiUp, upStar, downStar, d1, dUU, distK, advScheme);
396 View<const double> u2,
int comp,
double rho,
int advScheme,
397 View<double> defc, View<const double> uf,
bool useFace,
bool seamOn) {
409 Kokkos::parallel_for(
410 "amr::flow_defsou", g.
n, KOKKOS_LAMBDA(
const Index i) {
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);
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),
434 sou += ra(k) * velOut * phiFace;
435 fou += ra(k) * velOut * fld(up);
437 defc(i) = rho * iv(i) * (sou - fou);
444 View<const double> u2,
int comp,
double rho,
int advScheme,
445 View<double> defc, View<const double> uf,
bool useFace,
bool seamOn) {
457 Kokkos::parallel_for(
458 "amr::flow_advexpl", g.
n, KOKKOS_LAMBDA(
const Index i) {
463 auto fld = [&](Index c) {
return (comp == 0) ? u0(c) : (comp == 1) ? u1(c) : u2(c); };
465 for (Index k = st(i); k < st(i + 1); ++k) {
466 const Index j = nb(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),
482 sou += ra(k) * velOut * phiFace;
484 defc(i) = rho * sou * iv(i);
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) {
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) {
503 p(i) += rho_dt * phi(i) - mu * div(i);
510template <
unsigned Bits = 21u>
516 void init(
const Octree& t, Real h0, Vec<3> origin = Vec<3>{}) {
519 void init(
const Octree& t,
const Vec<3>& h0, Vec<3> origin = Vec<3>{}) {
543 for (
int d = 0; d < 3; ++d)
544 b[d] = mu_ / (h0_[d] * h0_[d]);
550 void setBodyForce(
double fx,
double fy,
double fz) { f_ = {fx, fy, fz}; }
599 ghostProjReq_ = on ? 1 : 0;
600 gpMatrixOrder_ = matrixOrder;
601 gpRhsOrder_ = rhsOrder;
615 ghostSampledReq_ = on ? 1 : 0;
617 gpsMaxN_ = maxSamples;
725 outerIters_ = (n < 1) ? 1 : n;
731 template <
class SdfFn>
733 const Index n = t_->numLeaves();
734 SetupProfiler prof(n);
735 buildHostOperators(sdfFn, prof);
738 buildProjectionOverlay(sdfFn, hov, hovS, prof);
739 buildPressureHierarchy(sdfFn, prof);
753 assembleMomentumOperator(n, ov, prof);
755 prof.phase(
"velocity MG build");
756 buildFaceGeometry(n, ov, prof);
758 prof.phase(
"cf overlays");
760 uploadGhostOverlays(sdfFn, n, hov, hovS);
761 allocateStepState(n);
764 prof.phase(
"overlays upload + state alloc");
772 struct SetupProfiler {
775 std::chrono::steady_clock::time_point t0;
776 explicit SetupProfiler(Index nLeaves)
778 const char* e = std::getenv(
"PECLET_AMR_PROFILE_SETUP");
779 return e && e[0] ==
'1';
782 , t0(std::chrono::steady_clock::now()) {}
783 void phase(
const char* name) {
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();
796 template <
class SdfFn>
797 void buildHostOperators(SdfFn& sdfFn, SetupProfiler& prof) {
798 const Index n = t_->numLeaves();
800 mom_.init(*t_, h0_, origin_);
801 pres_.init(*t_, h0_);
802 pres_.setOrigin(origin_);
803 prof.phase(
"mom.init + pres.init");
811 const bool wantGhost = (ghostProjReq_ != 0);
812 ghostProj_ = wantGhost;
813 ghostSampled_ = (ghostSampledReq_ == 1) && wantGhost;
828 momSolver_.setDistributed({}, {}, 0);
829 pcg_.setDistributed({}, {}, 0);
832 prof.phase(
"mom.build (SDF+cut stencils)");
836 template <
class SdfFn>
837 void buildProjectionOverlay(SdfFn& sdfFn, GhostOverlay& hov, GhostOverlaySampled& hovS,
838 SetupProfiler& prof) {
842 &gfine, shiftD_,
false, gpsRho_, gpsMaxN_);
843 prof.phase(
"buildGhostOverlaySampled");
844 }
else if (ghostProj_) {
847 hov =
buildGhostOverlay(*t_, pres_, mom_.sdfCRaw(), gpMatrixOrder_, gpRhsOrder_, &viol);
851 int lv = viol ? 1 : 0, gv = 0;
852 MPI_Allreduce(&lv, &gv, 1, MPI_INT, MPI_LOR, dist_->comm());
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");
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");
871 template <
class SdfFn>
872 void buildPressureHierarchy(SdfFn& sdfFn, SetupProfiler& prof) {
880 *t_, pres_, [&sdfFn](
const Vec<3>& p) {
return sdfFn(p); }, h0_, origin_, shiftD_);
881 pres_.buildOpenness(binFn);
882 prof.phase(
"buildOpenness (mixed)");
887 presMGD_.build(*dist_, h0_, binFn, &dhalo_,
true, presBottomExtent_);
889 presMG_.build(*t_, h0_, binFn,
true,
false,
890 true, presBottomExtent_);
891 prof.phase(
"presMG.build");
893 auto binFn =
makeBinaryOpenFn([&sdfFn](
const Vec<3>& p) {
return sdfFn(p); }, h0_);
894 pres_.buildOpenness(binFn);
896 presMGD_.build(*dist_, h0_, binFn, &dhalo_,
true, presBottomExtent_);
898 presMG_.build(*t_, h0_, binFn,
true,
false,
899 true, presBottomExtent_);
907 gpPocket_ = dist_ ? std::vector<char>{} :
findPocketCells(*t_, pres_, mom_.sdfCRaw());
908 prof.phase(
"findPocketCells");
911 auto openFn = [&](
const Vec<3>& fc,
int axis) {
return faceFrac(sdfFn, fc, axis); };
912 pres_.buildOpenness(openFn);
914 presMGD_.build(*dist_, h0_, openFn, &dhalo_,
true, presBottomExtent_);
916 presMG_.build(*t_, h0_, openFn,
true,
false,
917 true, presBottomExtent_);
922 presMGD_.setBottom(presBottom_);
924 presMG_.setBottom(presBottom_);
927 presMGD_.setRemoveMean(
true);
928 pcg_.setDistributed([
this](View<double> v) { presMGD_.sync(0, v); }, allred_,
929 presMGD_.extendedSize(0));
931 presMG_.setRemoveMean(
true);
933 prof.phase(
"nullspace setup");
937 void assembleMomentumOperator(Index n,
const BlockOctreeView<3, Bits>& ov, SetupProfiler& prof) {
939 auto A = mom_.assembleOperator();
940 momOp_ = MomentumOp{};
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");
948 prof.phase(
"assembleMomentum (device)");
953 void buildVelocityMG(Index n) {
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) {
979 lnbr.push_back(A.nbr[
static_cast<std::size_t
>(k)]);
980 lcoef.push_back(A.coef[
static_cast<std::size_t
>(k)]);
982 lstart.push_back(
static_cast<Index
>(lnbr.size()));
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;
995 velMG_.build(*t_, h0_, rho_ / dt_, mu_, momOp_, kap, fl, cu, mgMinCoarse_);
996 velMG_.setGaussSeidel(momGS_);
1000 auto A = mom_.assembleOperator();
1001 momMG_.build(*t_, A.diag, A.start, A.nbr, A.coef);
1002 momMG_.setGaussSeidel(momGS_);
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;
1016 geom_ =
buildFaceGeom(pres_, [&](Index i) {
return mom_.isFluid(i); });
1017 geom_.
fluid = toDevice(mom_.fluidRaw(),
"fg_fluid_ext");
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();
1030 gc_ = GhostGradOverlay{};
1035 void buildCfOverlays(Index n) {
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;
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");
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;
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;
1064 cfCutFaces_ =
countCfCutFaces(pres_, *t_, regularOk, [&](Index s) {
return mom_.isFluid(s); });
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_);
1083 auto divD =
buildCfDivDelta(pres_, *t_, regularOk, fluidOk, cfScheme_);
1085 auto ufd =
buildCfUfDelta(pres_, *t_, regularOk, fluidOk, cfScheme_);
1090 auto countGhost = [&](
const std::vector<Index>& col) {
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);
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");
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{};
1133 template <
class SdfFn>
1134 void uploadGhostOverlays(SdfFn& sdfFn, Index n,
const GhostOverlay& hov,
1135 const GhostOverlaySampled& hovS) {
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)]))
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");
1156 if (ghostSampled_) {
1157 CfCsr msd =
buildMomSeamDelta(hovS, *t_, pres_, mom_, sdfFn, origin_, rho_ / dt_, mu_,
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;
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)]);
1171 buildSampledGradCsr(hovS, *t_, pres_, [&](Index i) {
return mom_.isCut(i); }, classicOk));
1173 gpsMomDelta_ = CfCsrDev{};
1174 gcS_ = GhostGradCsrDev{};
1177 auto mk = [&](
const char* l) {
return View<double>(l,
static_cast<std::size_t
>(nExt_)); };
1179 gprh_ = mk(
"gp_rhat");
1181 gpph_ = mk(
"gp_phat");
1184 gpsh_ = mk(
"gp_shat");
1189 void allocateStepState(Index n) {
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);
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));
1204 faceFieldBuilt_ =
false;
1205 bmom_ = View<double>(
"df_bmom",
static_cast<std::size_t
>(n));
1206 Kokkos::deep_copy(p_, 0.0);
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);
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_));
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;
1231 momSolver_.setJacobi(2, 0.7);
1235 if (momMGon_ && !(dist_ && useStaircaseMG_)) {
1236 if (useStaircaseMG_)
1237 momSolver_.setPreconditioner(
1238 [
this](View<const double> r, View<double> z) {
runMgVcycle(velMG_, r, z); });
1240 momSolver_.setPreconditioner(
1241 [
this](View<const double> r, View<double> z) {
runMgVcycle(momMG_, r, z); });
1243 pcg_.setVcycle(2, 2, 60, 0.8);
1244 pcg_.setSingular(
true);
1280 return SpClock::time_point{};
1282 return SpClock::now();
1284 void spAdd(
int ph, SpClock::time_point t0) {
1288 spAcc_[ph] += std::chrono::duration<double, std::milli>(SpClock::now() - t0).count();
1295 spMom_ += lastMomIters_;
1296 spPres_ += lastPresIters_;
1297 spOuter_ += lastOuterIters_;
1301 std::fprintf(stderr,
"[step-prof] leaves %lld | pressure MG levels %zu:", (
long long)n_,
1304 std::fprintf(stderr,
" %lld", (
long long)n);
1308 if (spSteps_ < spWindow_)
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_);
1318 for (
int k = 0; k <
SP_N; ++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) {
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)" :
"");
1331 for (
int k = 0; k <
SP_N; ++k)
1334 spMom_ = spPres_ = spOuter_ = 0.0;
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, "
1348 void step(
int momIters = 100,
int presIters = 60) {
1351 const double idiag = rho_ / dt_;
1353 lastOuterIters_ = 1;
1354 const auto spT0 =
spMark();
1358 for (
int c = 0; c < 3; ++c)
1359 Kokkos::deep_copy(u0_[c], View<const double>(u_[c]));
1365 grad3(geom_, View<const double>(p_), gx_[0], gx_[1], gx_[2]);
1368 for (
int a = 0; a < 3; ++a)
1369 cfApply(cfGrad_[
static_cast<std::size_t
>(a)], View<const double>(p_), gx_[a]);
1372 applyGhostGrad(gc_, View<const double>(p_), gx_[0], gx_[1], gx_[2]);
1378 for (
int outer = 0; outer < outerIters_; ++outer) {
1386 momOp_.hasAdv = implicitFou_;
1392 const View<const double> ufv(uf_);
1393 const bool useUf = faceFieldBuilt_ && ufAdvect_;
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_,
1398 for (
int c = 0; c < 3; ++c) {
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,
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,
1410 if (momMGon_ && useStaircaseMG_)
1411 velMG_.setFineOp(momOp_);
1425 for (
int c = 0; c < 3; ++c) {
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);
1433 cfApply(cfMom_, View<const double>(u_[c]), bmom_);
1435 cfApply(gpsMomDelta_, View<const double>(u_[c]), bmom_);
1443 (momMGSolver_ ? momSolver_.solveDefectCorrection(
1444 momOp_, u_[c], View<const double>(bmom_), momIters, momTol_)
1445 : momSolver_.solveBiCGStab(momOp_, u_[c], View<const double>(bmom_),
1453 if (outerIters_ > 1) {
1454 lastOuterIters_ = outer + 1;
1457 for (
int c = 0; c < 3; ++c)
1459 dmax,
maxAbsDiff(View<const double>(u_[c]), View<const double>(uprev_[c]), n));
1460 if (dmax < outerTol_)
1463 for (
int c = 0; c < 3; ++c)
1464 Kokkos::deep_copy(uprev_[c], View<const double>(u_[c]));
1477 divergence(geom_, View<const double>(u_[0]), View<const double>(u_[1]),
1478 View<const double>(u_[2]), div_);
1481 cfApplyComp(cfDiv_, View<const double>(u_[0]), View<const double>(u_[1]),
1482 View<const double>(u_[2]), div_);
1486 ghostDivergDelta(gpOv_, View<const double>(u_[0]), View<const double>(u_[1]),
1487 View<const double>(u_[2]), div_);
1489 View<const double>(u_[2]), div_);
1492 Kokkos::deep_copy(phi_, 0.0);
1495 lastPresIters_ =
solveGhostBiCGStab(phi_, View<const double>(div_), presIters, presTol_);
1517 const bool dbg =
amrEnvFlag(
"PECLET_AMR_PRES_DEBUG");
1518 if (dbg && !dist_) {
1521 const FvOp& op0 = presMG_.op(0);
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) {
1532 for (Index k = st(i); k < st(i + 1); ++k)
1534 const double m = (d > 1e-30) ? 1.0 : 0.0;
1535 a += m * dv(i) / iv(i);
1537 c += m * dv(i) * dv(i) / iv(i);
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_) {
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);
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) {
1559 Kokkos::parallel_reduce(
1561 KOKKOS_LAMBDA(
const Index i,
double& acc) { acc += a(i) * b(i) / iv(i); }, s);
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);
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;
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);
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;
1591 Kokkos::deep_copy(presMG_.b(0), div_);
1592 Kokkos::deep_copy(presMG_.x(0), 0.0);
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);
1599 residualFv(presMG_.op(0), View<const double>(presMG_.x(0)),
1600 View<const double>(presMG_.b(0)), rdbg);
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);
1606 Kokkos::deep_copy(phi_, presMG_.x(0));
1607 lastPresIters_ = presIters;
1621 buildFaceField(geom_, View<const double>(u_[0]), View<const double>(u_[1]),
1622 View<const double>(u_[2]), View<const double>(phi_), uf_);
1627 cfApplyComp(cfUfVel_, View<const double>(u_[0]), View<const double>(u_[1]),
1628 View<const double>(u_[2]), uf_);
1650 faceFieldBuilt_ =
true;
1651 grad3(geom_, View<const double>(phi_), gx_[0], gx_[1], gx_[2]);
1652 for (
int a = 0; a < 3; ++a)
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]);
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);
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);
1688 for (
int c = 0; c < 3; ++c)
1689 adaptGradU_[
static_cast<std::size_t
>(c)] =
1696 template <
class SdfFn>
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_,
true,
1704 dist_ ? &adaptGradU_[
static_cast<std::size_t
>(c)] :
nullptr);
1705 std::vector<double> np =
1706 transferField(*adaptOldT_, adaptP_, *t_,
true, dist_ ? &adaptGradP_ :
nullptr);
1708 for (
int c = 0; c < 3; ++c) {
1715 for (
int c = 0; c < 3; ++c)
1716 adaptU_[
static_cast<std::size_t
>(c)].clear();
1726 template <
class SdfFn>
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);
1734 dist_->rebalance(cols);
1736 for (
int c = 0; c < 3; ++c) {
1737 setVelocity(c, cols[
static_cast<std::size_t
>(c)]);
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);
1755 Kokkos::parallel_for(
1756 "amr::flow_zerosolid", n_, KOKKOS_LAMBDA(
const Index i) {
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_),
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);
1785 const Index nl = mg.numLeaves(0);
1788 Kokkos::parallel_for(
"amr::mgv_b", nl, KOKKOS_LAMBDA(
const Index i) { b0(i) = r(i); });
1790 Kokkos::deep_copy(mg.x(0), 0.0);
1791 mg.vcycle(mgVcPre_, mgVcPre_, mgVcBottom_, 0.7);
1794 Kokkos::parallel_for(
"amr::mgv_z", nl, KOKKOS_LAMBDA(
const Index i) { z(i) = x0(i); });
1798 static double maxAbsDiff(View<const double> a, View<const double> b, Index n) {
1800 Kokkos::parallel_reduce(
1801 "amr::flow_maxdiff", n,
1802 KOKKOS_LAMBDA(
const Index i,
double& lm) {
1803 double d = a(i) - b(i);
1809 Kokkos::Max<double>(m));
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);
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);
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);
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) {
1854 Kokkos::parallel_for(
1855 "amr::pack_vel", n_, KOKKOS_LAMBDA(
const Index i) { p(i * 3 +
cc) = uc(i); });
1857 return peclet::core::toVector(packed);
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_);
1868 ghostDivergDelta(gpOv_, View<const double>(u_[0]), View<const double>(u_[1]),
1869 View<const double>(u_[2]), div_);
1871 View<const double>(u_[2]), div_);
1873 return std::sqrt(
allSum(dotPlain(View<const double>(div_), View<const double>(div_), n_)));
1891 const double l =
divFaceNorm(geom_, View<const double>(uf_));
1892 return std::sqrt(
allSum(l * l));
1901 std::vector<Index> out;
1903 for (std::size_t L = 0; L < presMG_.numLevels(); ++L)
1904 out.push_back(presMG_.numLeaves(L));
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));
1919 return dist_ ? presMGD_.bottomName() : presMG_.bottomName();
1937 presBottom_ = B::Auto;
1938 else if (kind ==
"smoother")
1939 presBottom_ = B::Smoother;
1940 else if (kind ==
"agglomerated")
1941 presBottom_ = B::Agglomerated;
1943 throw std::runtime_error(
1944 "amr::AmrFlow::setPressureBottom: expected 'auto', 'smoother' or 'agglomerated'");
1946 presMGD_.setBottom(presBottom_);
1948 presMG_.setBottom(presBottom_);
1962 throw std::runtime_error(
"amr::AmrFlow::setPressureBottomExtent: must be >= 1");
1963 presBottomExtent_ = e;
1970 std::vector<double>
faceField()
const {
return peclet::core::toVector(uf_); }
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);
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);
2058 bool isFluid(Index i)
const {
return mom_.isFluid(i); }
2071 dhex_.exchange3(u_[0], u_[1], u_[2]);
2083 MPI_Allreduce(&s, &g, 1, MPI_DOUBLE, MPI_SUM, dist_->comm());
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]);
2098 const FvOp&
gpOp0() {
return dist_ ? presMGD_.op(0) : presMG_.op(0); }
2103 template <
class 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)
2112 return hp->resolveGlobal(g);
2114 mom_.setFrameShift(shiftD_);
2115 mom_.setResolver(resv);
2116 pres_.setFrameShift(shiftD_);
2117 pres_.setResolver(resv);
2118 const Index n = t_->numLeaves();
2121 const bool profSetup =
amrEnvFlag(
"PECLET_AMR_PROFILE_SETUP");
2124 const auto rT0 = std::chrono::steady_clock::now();
2131 mom_.build(sdfFn, rho_ / dt_, beta);
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);
2139 (void)pres_.periodicNeighbor(j, ax, dr);
2144 if (ghostSampled_) {
2155 &gfine, shiftD_,
true, gpsRho_, gpsMaxN_);
2157 *t_, pres_, [&sdfFn](
const Vec<3>& p) {
return sdfFn(p); }, h0_, origin_, shiftD_);
2158 pres_.buildOpenness(binFn);
2159 }
else if (ghostProj_ || ghostGrad_) {
2161 (void)
buildGhostOverlay(*t_, pres_, mom_.sdfCRaw(), gpMatrixOrder_, gpRhsOrder_, &viol);
2167 const double rBuildMs =
2168 std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - rT0).count();
2169 const long pend = dhalo_.resolveMisses();
2171 std::fprintf(stderr,
"[setSolid] round %d: build %.1f ms, %lld ghosts, %ld pending\n",
2172 rounds, rBuildMs, (
long long)dhalo_.numGhosts(), pend);
2181 std::fprintf(stderr,
"[setSolid] distributed discovery fixpoint: %d rounds (%lld ghosts)\n",
2182 rounds, (
long long)dhalo_.numGhosts());
2185 mom_.build(sdfFn, rho_ / dt_, beta);
2187 nExt_ = dhalo_.extendedSize();
2189 allred_ = [
this](
double s) {
return allSum(s); };
2190 momSolver_.setDistributed([
this](View<double> v) { dhex_.exchange(v); }, allred_, nExt_);
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);
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) {
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)
2249 (void)pres_.probeSlot(q);
2272 const Index n = t_->numLeaves();
2273 hostParFor(n, [&](Index i) {
2274 pres_.forEachFaceFull(i, [&](Index j,
int axis,
int dir,
double,
double,
double) {
2277 const unsigned Lj = pres_.levelOf(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)
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;
2288 for (
int t = 0; t < 3; ++t) {
2291 q[t] = lo[t] + (((k >> bit) & 1) ? sh : 0L);
2294 (void)pres_.probeSlot(q);
2297 const Index uJ = pres_.periodicNeighbor(j, axis, dir);
2298 if (uJ >= 0 && pres_.levelOf(uJ) > Lj)
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));
2315 mom_.setGhosts(glo, glv);
2316 pres_.setGhosts(std::move(glo), std::move(glv));
2343 const auto spT =
spMark();
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));
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));
2374 Kokkos::parallel_for(
"amr::gp_r0", n, KOKKOS_LAMBDA(
const Index i) { r(i) = bb(i) - r(i); });
2377 Kokkos::deep_copy(gprh_, gpr_);
2379 std::sqrt(
allSum(dotPlain(View<const double>(gpr_), View<const double>(gpr_), n)));
2382 double rho = 1, alpha = 1, omega = 1, best = res0;
2384 Kokkos::deep_copy(gpv_, 0.0);
2385 Kokkos::deep_copy(gpp_, 0.0);
2387 for (; it < maxIters; ++it) {
2388 const double rhoNew =
2389 allSum(dotPlain(View<const double>(gprh_), View<const double>(gpr_), n));
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_);
2397 const double rhatV =
allSum(dotPlain(View<const double>(gprh_), View<const double>(gpv_), n));
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);
2410 ghostPrec(View<const double>(gps_), gpsh_);
2413 const double tt =
allSum(dotPlain(View<const double>(gpt_), View<const double>(gpt_), n));
2415 ?
allSum(dotPlain(View<const double>(gpt_), View<const double>(gps_), n)) / tt
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) {
2427 if (rnorm < 0.999 * best) {
2430 }
else if (++noImprove >= 6) {
2445 geom_.
seam = toDevice(h.
seam,
"seam_desc");
2446 geom_.
sampI = toDevice(h.
sampI,
"seam_sampi");
2447 geom_.
sampJ = toDevice(h.
sampJ,
"seam_sampj");
2450 geom_.
d1I = toDevice(h.
d1I,
"seam_d1i");
2451 geom_.
d1J = toDevice(h.
d1J,
"seam_d1j");
2455 geom_.
recW = toDevice(h.
recW,
"seam_recw");
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;
2481 void buildGhostGradOverlay() {
2482 const Index n = t_->numLeaves();
2483 std::vector<Index> cells;
2484 for (Index i = 0; i < n; ++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);
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)]);
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;
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);
2513 w[o + 1] = -0.5 / h;
2515 const Index jpp = pres_.periodicNeighbor(jp, a, +1);
2522 w[o + 2] = -0.5 / h;
2527 w[o + 1] = -1.0 / h;
2530 const Index jmm = pres_.periodicNeighbor(jm, a, -1);
2535 w[o + 1] = -2.0 / h;
2542 w[o + 1] = -1.0 / h;
2548 gc_.cell = toDevice(cells,
"gc_cell");
2549 gc_.idx = toDevice(idx,
"gc_idx");
2550 gc_.w = toDevice(w,
"gc_w");
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);
2582 const double den = (x - y) * (x - z);
2583 return den > 1e-300 ? (x * x) / den : 1.0;
2598 const double den = (x - y) * (x - z);
2599 return 1.0 - (den > 1e-300 ? (x * x) / den : 1.0);
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)
2606 const int t1 = (axis + 1) % 3, t2 = (axis + 2) % 3;
2608 const double e1 = 0.5 * h0_[t1], e2 = 0.5 * h0_[t2];
2609 auto at = [&](
double d1,
double d2) {
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);
2621 double sd = sdfFn(fc);
2625 for (
int d = 0; d < 3; ++d) {
2626 Vec<3> pp = fc, pm = fc;
2629 g[d] = (sdfFn(pp) - sdfFn(pm)) / (2.0 * h0_[d]);
2631 double gmag = std::sqrt(g[0] * g[0] + g[1] * g[1] + g[2] * g[2]);
2634 int t1 = (axis + 1) % 3, t2 = (axis + 2) % 3;
2636 double denom = (std::fabs(g[t1]) * h0_[t1] + std::fabs(g[t2]) * h0_[t2]) / gmag;
2639 double frac = 0.5 + sd / denom;
2640 return frac < 0.0 ? 0.0 : (frac > 1.0 ? 1.0 : frac);
2643 const Octree* t_ =
nullptr;
2646 double rho_ = 1.0, mu_ = 1.0, dt_ = 1e6;
2648 bool presPCG_ =
true;
2649 bool presDbgSpdDone_ =
false;
2650 bool momMGon_ =
true;
2651 bool useStaircaseMG_ =
false;
2652 int mgVcPre_ = 2, mgVcBottom_ = 30;
2653 Index mgMinCoarse_ = 256;
2654 bool momGS_ =
false;
2657 bool ghostGrad_ =
true;
2660 bool ghostProj_ =
false;
2661 int8_t ghostProjReq_ = -1;
2663 int apertureOrder_ = 2;
2664 int gpMatrixOrder_ = 2, gpRhsOrder_ = 2;
2680 int outerIters_ = 1;
2681 double outerTol_ = 1e-6;
2682 double momTol_ = 1e-8;
2683 double presTol_ = 1e-10;
2684 bool advect_ =
true;
2685 bool implicitFou_ =
true;
2688 bool ready_ =
false;
2689 int lastMomIters_ = 0, lastPresIters_ = 0, lastOuterIters_ = 1;
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;
2699 double spAcc_[
SP_N] = {};
2700 double spMom_ = 0.0, spPres_ = 0.0, spOuter_ = 0.0;
2702 AmrCutCell<Bits> mom_;
2703 AmrPoisson<3, Bits> pres_;
2704 Multigrid<3, Bits> presMG_;
2708 Index presBottomExtent_ = 4;
2709 MomentumMG<Bits> momMG_;
2710 VelocityMG<Bits> velMG_;
2714 std::array<View<double>, 3> defc_;
2715 View<double> advDiag_, advCoef_;
2717 GhostGradOverlay gc_;
2718 GhostOverlayDev gpOv_;
2719 bool ghostSampled_ =
false;
2720 int8_t ghostSampledReq_ = 0;
2721 double gpsRho_ = 2.2;
2723 GhostOverlaySampledDev gpOvS_;
2724 GhostGradCsrDev gcS_;
2725 CfCsrDev gpsMomDelta_;
2726 std::vector<char> gpPocket_;
2728 CfCompCsrDev cfDiv_;
2729 std::array<CfCsrDev, 3> cfGrad_;
2730 CfCompCsrDev cfUfVel_;
2731 Index cfGhostCols_ = 0;
2732 Index cfCutFaces_ = 0;
2733 bool seamRecon_ =
true;
2734 Index seamSampleRecords_ = 0;
2735 Index seamLayerRecords_ = 0;
2736 View<double> maskC_;
2737 View<double> gpr_, gprh_, gpp_, gpph_, gpv_, gps_, gpsh_, gpt_;
2738 View<double> rscale_;
2740 std::array<View<double>, 3> u_, gx_;
2741 std::array<View<double>, 3> u0_,
2743 View<double> p_, phi_, div_, bmom_;
2745 bool faceFieldBuilt_ =
2747 bool ufAdvect_ =
true;
2749 std::unique_ptr<Octree> adaptOldT_;
2750 std::array<std::vector<double>, 3> adaptU_;
2751 std::vector<double> adaptP_;
2752 std::array<std::vector<std::array<double, 3>>, 3> adaptGradU_;
2753 std::vector<std::array<double, 3>> adaptGradP_;
2756 DistributedOctree<3, Bits>* dist_ =
nullptr;
2757 LeafHalo<3, Bits> dhalo_;
2758 LeafHaloExchange dhex_;
2759 DistributedFlowMultigrid<3, Bits> presMGD_;
2760 std::array<long, 3> shiftD_{};
2762 std::function<double(
double)> allred_;
void setImplicitAdvection(bool on)
Implicit-FOU deferred correction (default ON).
Index numSeamSampleRecords() const
Seam-reconstruction census (docs/amr_cf_convective.md §5.2): how many sample records (one per 2:1 sub...
void setApertureOrder(int order)
FULL directional ghost-cell projection (the AMR port of flow's collocated set_ghost_projection): the ...
void setMomentumMG(bool on)
Use the Galerkin velocity multigrid (MomentumMG) as the momentum BiCGStab preconditioner.
std::vector< double > velocity(int c) const
Copy a velocity component back to host (single D2H, no host loop — S2a).
void finishAdapt(SdfFn &&sdfFn)
Rebuild on the mutated octree and transfer the snapshotted fields onto it.
void setGhostGradient(bool on)
Directional ghost cell-gradient for the −∇pⁿ predictor and the projection's cell correction (the AMR ...
void ghostPrec(View< const double > r, View< double > z)
void step(int momIters=100, int presIters=60)
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...
void gpProject(View< double > v)
void prepareDistributed(SdfFn &&sdfFn)
Install the resolver seams, run every prober to the miss-collect fixpoint, freeze the ±2 halo,...
void setBodyForce(double fx, double fy, double fz)
void setPressurePCG(bool on)
Use MG-preconditioned CG for the pressure solve (default) vs plain V-cycles.
void syncVel()
Refresh the ghost tails of the three velocity components (one batched message round).
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...
std::vector< double > pressure() const
Copy the pressure field back to host (single D2H), (num_leaves,) — the incremental-rotational p.
void setPressureTol(double tol)
Relative tolerance of the PRESSURE solve, for both drivers: the MG-PCG (the default) and the ghost pr...
void setVelocityMGMinCoarse(Index m)
Pore-scale cap for the staircase velocity-MG: the coarsest level keeps ≥ this many cells,...
void setVelocity(int c, const std::vector< double > &h)
Set a velocity component from host (testing / initial conditions).
bool isFluid(Index i) const
Per-leaf fluid mask (false inside the solid) — for host-side post-processing / bindings.
double divNormL2()
L2 norm of the (openness-weighted) divergence of the current velocity — the ghost-closed divergence w...
std::array< long, 3 > globalFineExtent() const
The DOMAIN's fine extent (D1): the block's own single-rank, where block == domain.
void copyToHost(const View< double > &d, std::vector< double > &h) const
Copy a device View into a host vector (sized n_).
void setAdvectionScheme(int s)
High-order advection scheme: 0 = second-order upwind (SOU, default), 1 = Koren TVD.
int solveGhostBiCGStab(View< double > x, View< const double > b, int maxIters, double tol=1e-10)
void init(const Octree &t, const Vec< 3 > &h0, Vec< 3 > origin=Vec< 3 >{})
void installGhostMeta()
Mirror the halo registry's ghost metadata (block-local lo + level) into mom_ and pres_.
std::vector< double > debugSou(int comp)
DEBUG: the raw high-order advection ∇·(u u_comp) per cell from the current velocity (== host oracle::...
void setViscosity(double mu)
Index numGhostCells() const
Distributed: number of ghost slots in the ±2 registry (0 single-rank).
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.
Index numCfGhostColumns() const
Developer diagnostic: entries of the four C/F-scheme overlays that read a GHOST slot (0 single-rank,...
void finishProjection(Index n)
Shared projection tail: build the div-free face field from u* + φ, correct the cell velocities (ABC /...
void setGhostProjection(bool on, int matrixOrder=2, int rhsOrder=2)
void probeCfScheme()
Discovery arm for the C/F quadratic scheme (cf_scheme.hpp), run inside prepareDistributed's miss-coll...
Index pressureBottomExtent() const
The bottom extent the next setSolid builds the ladder with (default 4).
Index numSeamLayerRecords() const
The face-layer half of the census: one record per (regular coarse cell, face) whose far side is refin...
int lastOuterIters() const
Picard outer iterations actually run in the last step (1 unless setOuterIterations(>1)).
void setDensity(double rho)
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...
double divNormFace()
L2 norm of the APERTURE-weighted divergence of the ABC face field uf_ (built each project()).
void ghostMatvec(View< const double > x, View< double > y)
void spAdd(int ph, SpClock::time_point t0)
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 ...
std::string pressureMgBottom() const
What actually solves the coarsest pressure level (docs/amr_mg_depth.md §6.6/§6.7): "jacobi" (60 dampe...
void project(int presIters=60)
Pressure projection of the current velocity in place.
void syncScalar(View< double > v)
Refresh the ghost tail of one cell scalar (p, φ, Krylov scratch).
std::vector< double > faceField() const
Copy the divergence-free face field to host (one value per CSR (sub)face, forEachFaceFull order).
void setMomentumTol(double tol)
Relative tolerance for the per-step momentum BiCGStab solve (default 1e-8).
void setSeamReconstruction(bool on)
ABLATION (docs/amr_cf_convective.md §5.5, Q-C).
void setPressureBottomExtent(Index e)
Where the pressure ladder stops lifting the root and hands over to the bottom (docs/amr_mg_depth....
void setUfAdvection(bool on)
ABLATION (developer tier).
void setPressure(const std::vector< double > &h)
Write the accumulated rotational pressure from host (restart / finishAdapt).
std::vector< double > localVector(const View< double > &v) const
Host copy of the LOCAL rows of a (possibly ghost-extended) per-cell field.
const FvOp & gpOp0()
The pressure operator the ghost solver runs on (distributed MG level 0 or presMG_'s).
std::chrono::steady_clock SpClock
void probeCfTangential(Index coarse, int axis)
Every coordinate cfAppendStencil can probe from the coarse cell of one C/F face: the tangential ± nei...
void setVelocityMGStaircase(bool on)
Choose the momentum-MG coarse-operator strategy: false (default) = Galerkin (MomentumMG,...
BlockOctree< 3, Bits > Octree
void zeroSolid(View< double > v)
Zero a per-leaf field on non-fluid cells (the transferred fields' solid cleanup).
void spEndStep()
Close a profiled step; print + reset when the window fills.
int lastPresIters() const
Pressure PCG iterations of the last step.
void requireOperator(const char *what) const
Every solve entry point needs the cut-cell operators that setSolid builds; without them the state vie...
void rebalanceMpi(SdfFn &&sdfFn)
Distributed load rebalance (docs/amr_distributed_flow.md, rung 6): re-decompose the octree by leaf co...
void probeSeamLayer()
Discovery arm for the SEAM builder (seam_recon.hpp), run beside probeCfScheme() inside prepareDistrib...
StepPhase
One incompressible step on device (Stokes, or Navier–Stokes with setAdvection).
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).
std::vector< Index > pressureMgLevels() const
The pressure multigrid's ladder as BUILT on this rank: per-level leaf counts, level 0 first (docs/amr...
int lastMomIters() const
Total momentum BiCGStab iterations (summed over the 3 components) of the last step.
void beginAdapt()
Snapshot the octree topology + (u, p) ahead of an external mesh mutation.
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....
Vec< 3 > betaPerAxis() const
The viscous coefficient of each derivative axis, mu/h0_a^2 — the octree twin of the structured solver...
void setMomentumGS(bool on)
Opt-in: use the multicolour Gauss–Seidel smoother in the momentum MG (Galerkin or staircase) instead ...
void setMomentumMGSolver(bool on)
Opt-in (P4): solve the momentum predictor with the velocity multigrid used as the solver — MG-precond...
std::vector< double > slotCenters() const
World centre of every slot of the extended (local + ghost) leaf array, row-major (nExt,...
double allSum(double s) const
Global sum (identity single-rank).
void setAdvection(bool on)
Momentum advection ∇·(u u), ON by default (user directive 2026-10-23, amr 2026-10-24; setAdvection(fa...
void setCfScheme(int scheme)
Coarse/fine (2:1) interface scheme (cf_scheme.hpp): 1 = Martin–Cartwright tangential quadratic,...
void setSolid(SdfFn &&sdfFn)
Build the cut-cell operators (host) + upload all device structures.
void setOuterIterations(int n, double tol=1e-6)
Optional Picard outer loop over the lagged advection (mirror of flow's outerIters_): each outer itera...
FaceTopologyHost faceTopology() const
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).
SpClock::time_point spMark() const
Cell-centered FV Poisson operator on one (periodic) block octree.
void forEachFaceFull(Index i, Fn &&fn) const
Like forEachFaceNeighbor but exposes geometry for a consistent FV divergence/gradient: fn(neighbour,...
Index periodicNeighbor(Index i, int axis, int dir) const
Periodic face neighbour leaf (covering the cell just across the face).
const Octree & octree() const
Real cellVolume(Index i) const
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.
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),...
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).
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...
Index countCfCutFaces(const AmrPoisson< 3, Bits > &ap, const BlockOctree< 3, Bits > &t, RegularFn &®ularOk, 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.
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 ?
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.
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 &®ularOk, 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...
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 ...
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,...
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 &®ularOk, 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.
SeamReconHost buildSeamRecon(const AmrPoisson< 3, Bits > &ap, RegularFn &®ularOk, 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).
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.
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 ...
bool amrEnvFlag(const char *name)
Truthy environment flag (unset / "" / "0" ⇒ false).
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...
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).
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).
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...
std::array< CfCsr, 3 > buildCfGradDelta(const AmrPoisson< 3, Bits > &ap, const BlockOctree< 3, Bits > &t, RegularFn &®ularOk, 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.
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.
@ standard
raw coarse value (two-point flux; 1st-order at 2:1 faces)
@ quadratic
Martin–Cartwright tangential quadratic (2nd-order at 2:1 faces).
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...
std::vector< double > d1J
std::vector< double > center
World centre of EVERY slot (local leaves then ghosts, size nExt): the only way a caller can say what ...
std::vector< Index > seam
std::vector< Index > upupI
std::vector< Index > recStart
std::vector< Index > recCell
std::vector< double > recDist
std::vector< Index > uuRecJ
std::vector< Index > sampI
std::vector< Index > uuRecI
std::vector< double > alpha
std::vector< double > recW
std::vector< double > d1I
std::vector< Index > upupJ
std::vector< double > rawArea
std::vector< double > dist
std::vector< Index > sampJ
std::vector< Index > start
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
View< double > recDist
per record: dUU for UPSTREAM use (unused as a φ_U* sample)
View< Index > uuRecI
per descriptor: upstream-probe record for up == i, else −1
View< Index > recCell
record entries: cell slot
View< double > alphaArea
α·area (physical) per face, size nFaces
View< int > dir
face direction +1/-1, size nFaces
View< double > recW
record entries: weight
View< double > invVol
1/V_i per cell, size n
View< double > rawArea
raw face area (physical, no openness) per face — advection flux
View< int > axis
face axis 0/1/2, size nFaces
View< Index > upupJ
upstream-of-j probe (periodicNeighbor(j,axis,+dir)) — SOU, size nFaces
View< Index > nbr
neighbour leaf per face, size nFaces
View< double > alpha
openness per face (gradient gate), size nFaces
View< double > dist
face-normal distance (physical) per face, size nFaces
View< Index > start
CSR row offsets, size n+1.
View< Index > sampI
per descriptor: sample record when i is the COARSE cell, else −1
View< Index > seam
descriptor id per face slot, −1 = plain slot; size nFaces
View< Index > upupI
upstream-of-i probe (periodicNeighbor(i,axis,−dir)) — SOU, size nFaces
View< Index > recStart
record CSR offsets, size nRec+1
View< char > fluid
per-cell fluid flag, size n
View< double > d1J
per descriptor: half width of j along the face axis (physical)
View< double > d1I
per descriptor: half width of i along the face axis (physical)
View< Index > sampJ
per descriptor: sample record when j is the COARSE cell, else −1
View< Index > faceStart
CSR row offsets, size n+1.
View< double > bcDiag
Dirichlet boundary diagonal per cell (0 if periodic), size n.
View< double > invVol
1/V_i, size n
View< double > faceW
w_f = openness·A_f/d_f per face, size nFaces
Ghost-gradient overlay (setGhostGradient): per cut cell, a precomputed 3-point directional FD stencil...
View< double > w
[n*9] stencil weight (0 = unused)
Index n
number of overlay (cut) cells
View< Index > idx
[n*9] stencil cell, slot s*9 + axis*3 + k
View< Index > cell
[n] leaf index
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...
View< const Index > sampI
View< const Index > sampJ
View< const Index > uuRecJ
View< const double > recDist
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...
View< const Index > uuRecI