26#include <nanobind/nanobind.h>
27#include <nanobind/ndarray.h>
28#include <nanobind/stl/array.h>
29#include <nanobind/stl/function.h>
30#include <nanobind/stl/optional.h>
31#include <nanobind/stl/string.h>
32#include <nanobind/stl/tuple.h>
33#include <nanobind/stl/variant.h>
34#include <nanobind/stl/vector.h>
39#include <Kokkos_Core.hpp>
45#include "amr_bindings_checks.hpp"
58#include "peclet/core/common/types.hpp"
59#include "peclet/core/geom/scene_query.hpp"
60#include "peclet/core/geom/sdf.hpp"
61#include "peclet/core/python/kokkos_teardown.hpp"
62#include "peclet/core/python/ndarray_interop.hpp"
64namespace nb = nanobind;
65using namespace peclet::core;
77using DArray = nb::ndarray<double, nb::c_contig>;
82nb::ndarray<nb::numpy, T>
vec1(std::vector<T> v) {
83 const std::size_t n = v.size();
84 return peclet::core::python::vector_to_ndarray<T>(std::move(v), {n}, {1});
87nb::ndarray<nb::numpy, T>
vec2(std::vector<T> v, std::size_t cols) {
88 const std::size_t n = v.size() / cols;
89 return peclet::core::python::vector_to_ndarray<T>(std::move(v), {n, cols},
90 {
static_cast<std::int64_t
>(cols), 1});
96 std::vector<double> d(
static_cast<std::size_t
>(n) * 3);
97 for (Index i = 0; i < n; ++i) {
109 if (axis < 0 || axis > 2)
110 throw std::runtime_error(
"sizes(axis): axis must be 0, 1 or 2");
112 std::vector<double> d(
static_cast<std::size_t
>(n));
113 for (Index i = 0; i < n; ++i)
121 std::vector<std::int32_t> d(
static_cast<std::size_t
>(n));
122 for (Index i = 0; i < n; ++i)
123 d[i] =
static_cast<std::int32_t
>(t.
level(i));
130 std::vector<std::uint64_t> d(
static_cast<std::size_t
>(n));
131 for (Index i = 0; i < n; ++i)
132 d[i] =
static_cast<std::uint64_t
>(t.
code(i));
137nb::ndarray<nb::numpy, double>
vecToArray(std::vector<double> v) {
143 if (
static_cast<Index
>(field.shape(0)) != t.
numLeaves())
144 throw std::runtime_error(std::string(who) +
": field length != num_leaves");
145 const double* f = field.data();
146 return std::vector<double>(f, f +
static_cast<std::size_t
>(t.
numLeaves()));
155using peclet::core::python::Releasable;
169 const std::array<long, 3>& cells) {
170 std::array<double, 3> h{};
171 for (
int d = 0; d < 3; ++d) {
172 if (!(extent[d] > 0.0))
173 throw std::runtime_error(
"extent: every component must be > 0");
175 throw std::runtime_error(
"extent: every finest-cell count must be > 0");
176 h[d] = extent[d] / (double)cells[d];
185 const std::array<long, 3>& cells) {
187 for (
int d = 1; d < 3; ++d)
188 if (std::fabs(h[d] - h[0]) > 1e-12 * std::fabs(h[0])) {
190 std::snprintf(msg,
sizeof msg,
191 "spacing_from_extent returns ONE number, but extent/cells gives "
192 "dx=%.17g dy=%.17g dz=%.17g — the octree's cells are CUBES here. Use "
193 "spacings_from_extent (or pass `extent` to the constructor) for a box mesh.",
195 throw std::runtime_error(msg);
201using SpacingArg = std::variant<double, std::array<double, 3>>;
203 if (
const double* d = std::get_if<double>(&sp))
205 return std::get<std::array<double, 3>>(sp);
210inline std::array<long, 3>
rootCellsOf(
const std::array<long, 3>& cells,
unsigned lmax,
212 const long f = (long)1 << lmax;
213 std::array<long, 3> root{};
214 for (
int d = 0; d < 3; ++d) {
215 if (cells[d] <= 0 || cells[d] % f != 0) {
217 std::snprintf(msg,
sizeof msg,
218 "%s: cells=(%ld, %ld, %ld) must be positive multiples of 2**lmax = %ld "
219 "(`cells` is the FINEST grid; the root brick is cells / 2**lmax)",
220 who, cells[0], cells[1], cells[2], f);
221 throw std::runtime_error(msg);
223 root[d] = cells[d] / f;
229inline std::array<double, 3>
resolveSpacing(
const std::optional<SpacingArg>& spacing,
230 const std::optional<std::array<double, 3>>& extent,
231 const std::array<long, 3>& cells,
const char* who) {
232 if (spacing && extent)
233 throw std::runtime_error(std::string(who) +
234 ": pass EITHER spacing= (the finest cell size) OR extent= (the box "
235 "side lengths; spacing = extent / cells), not both");
240 return {1.0, 1.0, 1.0};
250 std::array<double, 3>
spacing) {
251 t_.init(IVec<3>{root[0], root[1], root[2]},
lmax);
259 unsigned lmax()
const {
return t_.lmax(); }
260 std::array<double, 3>
origin()
const {
return {geo_.origin[0], geo_.origin[1], geo_.origin[2]}; }
263 const auto b = t_.brick();
264 const long f = (long)1 << t_.lmax();
265 return {(long)b[0] * f, (
long)b[1] * f, (long)b[2] * f};
269 const auto c =
cells();
270 return {(double)c[0] * geo_.h0[0], (
double)c[1] * geo_.h0[1], (double)c[2] * geo_.h0[2]};
272 std::array<double, 3>
spacing()
const {
return {geo_.h0[0], geo_.h0[1], geo_.h0[2]}; }
276 nb::ndarray<nb::numpy, double>
sizes(
int axis)
const {
return leafSizes(t_, geo_, axis); }
282 Index
find(std::array<double, 3> x)
const {
283 std::array<Coord, 3> fine{};
284 for (
int d = 0; d < 3; ++d) {
285 double f = (x[d] - geo_.origin[d]) / geo_.h0[d];
288 fine[d] =
static_cast<Coord>(f);
290 return t_.find(fine);
297 chk::sphereArgs(center, radius, target_level, band, t_.lmax());
298 geom::Sphere s{{center[0], center[1], center[2]}, radius};
300 t_, geo_, [&](
const Vec<3>& p) {
return s.eval(p); }, target_level, band,
balance);
305 Index
refine_to_sdf(std::function<
double(
double,
double,
double)> sdf,
unsigned target_level,
308 t_, geo_, [&](
const Vec<3>& p) {
return sdf(p[0], p[1], p[2]); }, target_level, band,
315 std::function<
unsigned(
double,
double,
double)> target_level,
318 t_, geo_, [&](
const Vec<3>& p) {
return sdf(p[0], p[1], p[2]); },
319 [&](
const Vec<3>& p) {
return target_level(p[0], p[1], p[2]); }, band,
balance);
325 std::function<
double(
double,
double,
double)> gap,
326 unsigned coarsest_level,
double n,
double band,
bool balance) {
327 chk::gapFloorArgs(coarsest_level, t_.lmax(), n, band);
329 geo_.hMax(), coarsest_level, n);
331 t_, geo_, [&](
const Vec<3>& p) {
return sdf(p[0], p[1], p[2]); }, tgt, band,
balance);
356 nb::ndarray<nb::numpy, double>
adapt(
DArray field,
double refine_thresh,
double coarsen_thresh,
357 unsigned finest_level,
double eps,
bool linear) {
358 chk::adaptArgs(refine_thresh, coarsen_thresh, finest_level, t_.lmax(), eps);
359 auto fv =
asField(t_, field,
"adapt");
360 auto r =
amr::adapt(t_, fv, refine_thresh, coarsen_thresh, finest_level, eps, linear);
361 t_ = std::move(r.octree);
388 Poisson(
const Octree& oct,
bool periodic) : n_(oct.octreeRef().numLeaves()) {
390 mg_.setPeriodic(periodic);
399 std::vector<double> out;
400 mg_.op(0).applyLaplacian(toVec(u,
"apply"), out);
406 std::vector<double> res;
407 return mg_.op(0).residual(toVec(u,
"residual"), toVec(rhs,
"residual"), res);
413 nb::tuple
solve(
DArray rhs, std::optional<DArray> x0,
int cycles,
int pre,
int post,
double tol) {
414 chk::solveArgs(cycles, pre, post, tol);
415 std::vector<double> rv = toVec(rhs,
"solve");
416 std::vector<double> u(
static_cast<std::size_t
>(n_), 0.0);
418 u = toVec(*x0,
"solve");
419 std::vector<double> res;
420 double r = mg_.op(0).residual(u, rv, res);
422 for (
int k = 0; k < cycles; ++k) {
423 mg_.vcycle(0, u, rv, pre, post);
424 r = mg_.op(0).residual(u, rv, res);
426 if (tol > 0.0 && r <= tol)
429 return nb::make_tuple(
vec1<double>(std::move(u)), r, done);
433 std::vector<double> toVec(
const DArray& a,
const char* who)
const {
434 if (
static_cast<Index
>(a.shape(0)) != n_)
435 throw std::runtime_error(std::string(who) +
": length != num_leaves");
436 const double* p = a.data();
437 return std::vector<double>(p, p +
static_cast<std::size_t
>(n_));
459class DistributedOctree;
461class Flow :
public Releasable {
463 Flow(
const Octree& oct,
double rho,
double mu,
double dt) : n_(oct.octreeRef().numLeaves()) {
465 flow_.setDensity(rho);
466 flow_.setViscosity(mu);
469 for (
int d = 0; d < 3; ++d) {
470 extent_[d] =
static_cast<double>(t.brick()[d]) *
static_cast<double>(Index(1) << t.lmax()) *
482 nb::gil_scoped_release nogil;
483 flow_.rebalanceMpi([&](
const Vec<3>& p) {
return sdf(p[0], p[1], p[2]); });
484 n_ = flow_.numLeaves();
489 void set_body_force(
double fx,
double fy,
double fz) { flow_.setBodyForce(fx, fy, fz); }
492 flow_.setGhostProjection(on, matrix_order, rhs_order);
495 flow_.setGhostSampled(on, rho, max_samples);
503 flow_.setPressure(std::vector<double>(h.data(), h.data() + h.shape(0)));
505 void set_dt(
double dt) { flow_.setDt(dt); }
507 nb::gil_scoped_release nogil;
508 flow_.finishAdapt([&](
const Vec<3>& p) {
return sdf(p[0], p[1], p[2]); });
509 n_ = flow_.numLeaves();
517 void set_solid(std::function<
double(
double,
double,
double)> sdf) {
525 nb::gil_scoped_release nogil;
526 flow_.setSolid([&](
const Vec<3>& p) {
return sdf(p[0], p[1], p[2]); });
536 nb::ndarray<const double, nb::c_contig> radii,
bool periodic) {
537 if (centers.ndim() != 2 || centers.shape(1) != 3)
538 throw std::runtime_error(
"set_solid_spheres: centers must be (M, 3)");
539 const std::size_t m = centers.shape(0);
540 if (radii.ndim() != 1 || (radii.shape(0) != m && radii.shape(0) != 1))
541 throw std::runtime_error(
"set_solid_spheres: radii must be (M,) or (1,)");
542 std::vector<double> cx(m), cy(m), cz(m), rr(m);
543 const double* cp = centers.data();
544 const double* rp = radii.data();
545 const bool oneR = radii.shape(0) == 1;
546 for (std::size_t i = 0; i < m; ++i) {
548 cy[i] = cp[3 * i + 1];
549 cz[i] = cp[3 * i + 2];
550 rr[i] = oneR ? rp[0] : rp[i];
557 geom::SphereBedQuery q(std::move(cx), std::move(cy), std::move(cz), std::move(rr),
558 Vec<3>{origin_[0], origin_[1], origin_[2]},
559 Vec<3>{extent_[0], extent_[1], extent_[2]}, periodic);
575 flow_.setPressureBottomExtent(
static_cast<Index
>(cells));
580 void step(
int mom_iters,
int pres_iters) { flow_.step(mom_iters, pres_iters); }
583 nb::ndarray<nb::numpy, double>
velocity(
int c)
const {
585 throw std::runtime_error(
"velocity: component must be 0..2");
586 const auto& v = flow_.velocity(c);
587 return vec1<double>(std::vector<double>(v.begin(), v.end()));
596 auto* buf =
new std::vector<std::uint8_t>(
static_cast<std::size_t
>(n_));
597 for (Index i = 0; i < n_; ++i)
598 (*buf)[
static_cast<std::size_t
>(i)] = flow_.isFluid(i) ? 1 : 0;
599 nb::capsule owner(buf,
600 [](
void* p)
noexcept {
delete static_cast<std::vector<std::uint8_t>*
>(p); });
601 return nb::ndarray<nb::numpy, bool>(
reinterpret_cast<bool*
>(buf->data()),
602 {static_cast<std::size_t>(n_)}, owner, {1});
615 flow_.setVelocity(c, std::vector<double>(h.data(), h.data() + h.shape(0)));
618 void project(
int pres_iters) { flow_.project(pres_iters); }
625 std::array<double, 3> extent_{0.0, 0.0, 0.0};
626 std::array<double, 3> origin_{0.0, 0.0, 0.0};
640 std::array<double, 3>
spacing, std::array<bool, 3> periodic) {
644 d_.init(IVec<3>{global_root[0], global_root[1], global_root[2]},
lmax, g,
645 {periodic[0], periodic[1], periodic[2]}, MPI_COMM_WORLD);
650 int rank()
const {
return d_.rank(); }
651 int size()
const {
return d_.size(); }
653 unsigned lmax()
const {
return d_.lmax(); }
655 const auto& hv = d_.h0();
656 return {hv[0], hv[1], hv[2]};
660 const auto& c = d_.globalFineSize();
661 return {(long)c[0], (
long)c[1], (long)c[2]};
665 const auto c =
cells();
666 const auto& hv = d_.h0();
667 return {(double)c[0] * hv[0], (
double)c[1] * hv[1], (double)c[2] * hv[2]};
671 const auto& o = d_.globalGeometry().origin;
672 return {o[0], o[1], o[2]};
675 const auto& b = d_.blockOriginRoot();
676 return {b[0], b[1], b[2]};
679 const auto& b = d_.blockBrick();
680 return {b[0], b[1], b[2]};
683 const auto& b = d_.globalRootSize();
684 return {b[0], b[1], b[2]};
688 nb::ndarray<nb::numpy, double>
centers()
const {
689 return leafCenters(d_.local(), d_.localGeometry());
691 nb::ndarray<nb::numpy, double>
sizes(
int axis)
const {
692 return leafSizes(d_.local(), d_.localGeometry(), axis);
695 nb::ndarray<nb::numpy, std::uint64_t>
codes()
const {
return leafCodes(d_.local()); }
702 chk::sphereArgs(center, radius, target_level, band, d_.lmax());
703 geom::Sphere s{{center[0], center[1], center[2]}, radius};
704 auto lgeo = d_.localGeometry();
706 d_.local(), lgeo, [&](
const Vec<3>& p) { return s.eval(p); }, target_level, band,
717 Index
refine_to_sdf(std::function<
double(
double,
double,
double)> sdf,
unsigned target_level,
719 auto lgeo = d_.localGeometry();
721 d_.local(), lgeo, [&](
const Vec<3>& p) { return sdf(p[0], p[1], p[2]); }, target_level,
737 const Index n = d_.local().numLeaves();
738 if (
static_cast<Index
>(fields.shape(0)) != n)
739 throw std::runtime_error(
"rebalance: fields.shape[0] != num_leaves");
740 const int K =
static_cast<int>(fields.shape(1));
741 const double* in = fields.data();
742 std::vector<std::vector<double>> cols(
static_cast<std::size_t
>(K),
743 std::vector<double>(
static_cast<std::size_t
>(n)));
744 for (Index i = 0; i < n; ++i)
745 for (
int c = 0; c < K; ++c)
746 cols[
static_cast<std::size_t
>(c)][
static_cast<std::size_t
>(i)] = in[i * K + c];
750 const Index m = d_.local().numLeaves();
751 std::vector<double> out(
static_cast<std::size_t
>(m) *
static_cast<std::size_t
>(K));
752 for (Index i = 0; i < m; ++i)
753 for (
int c = 0; c < K; ++c)
754 out[i * K + c] = cols[
static_cast<std::size_t
>(c)][
static_cast<std::size_t
>(i)];
755 return vec2<double>(std::move(out),
static_cast<std::size_t
>(K));
763 std::vector<double> f =
asField(d_.local(), field,
"face_neighbor_gather");
764 std::vector<double> g = d_.faceNeighborGather(f, sentinel);
773 auto fv =
asField(d_.local(), field,
"lohner_indicator");
781 nb::ndarray<nb::numpy, double>
adapt(
DArray field,
double refine_thresh,
double coarsen_thresh,
782 unsigned finest_level,
double eps,
bool linear) {
783 chk::adaptArgs(refine_thresh, coarsen_thresh, finest_level, d_.lmax(), eps);
784 auto fv =
asField(d_.local(), field,
"adapt");
793 asField(d_.local(), field,
"write_vtu"));
805 : n_(d.ref().local().numLeaves()) {
806 flow_.initMpi(d.
ref());
807 flow_.setDensity(rho);
808 flow_.setViscosity(mu);
835 const auto t = f_.engine().faceTopology();
837 d[
"start"] =
vec1<std::int64_t>(std::vector<std::int64_t>(t.start.begin(), t.start.end()));
839 d[
"axis"] =
vec1<std::int32_t>(std::vector<std::int32_t>(t.axis.begin(), t.axis.end()));
841 d[
"upup_i"] =
vec1<std::int64_t>(std::vector<std::int64_t>(t.upupI.begin(), t.upupI.end()));
842 d[
"upup_j"] =
vec1<std::int64_t>(std::vector<std::int64_t>(t.upupJ.begin(), t.upupJ.end()));
847 auto i64 = [](
const std::vector<peclet::core::Index>& v) {
850 d[
"seam"] = i64(t.seam);
851 d[
"samp_i"] = i64(t.sampI);
852 d[
"samp_j"] = i64(t.sampJ);
853 d[
"uu_rec_i"] = i64(t.uuRecI);
854 d[
"uu_rec_j"] = i64(t.uuRecJ);
857 d[
"rec_start"] = i64(t.recStart);
859 d[
"rec_cell"] = i64(t.recCell);
861 d[
"cell_center"] =
vec2<double>(std::vector<double>(t.center), 3);
868 return f_.engine().pressureMgLevels();
897 c.def_prop_ro(
"cells", &T::cells,
898 "Finest-level cell counts per axis (root*2**lmax; the GLOBAL grid on a "
899 "DistributedOctree).")
900 .def_prop_ro(
"extent", &T::extent,
"Box side lengths in world units (cells*spacing).")
902 "spacing", &T::spacing,
903 "Finest cell size (dx, dy, dz), per axis, in length units. Equal on a cubic octree.")
904 .def_prop_ro(
"num_leaves", &T::num_leaves,
905 "Number of leaves (Z-order slots; this rank's on a DistributedOctree).")
906 .def_prop_ro(
"lmax", &T::lmax,
"Root-cell level (max refinement depth).")
907 .def_prop_ro(
"origin", &T::origin,
"Lower corner in world coordinates (length units).")
908 .def(
"centers", &T::centers,
909 "Leaf world centres, (num_leaves, 3) float64 (global coordinates, length units).")
910 .def(
"sizes", &T::sizes, nb::arg(
"axis") = 0,
911 "Leaf world widths along `axis`: spacing[axis]*2**level, (num_leaves,) float64. A leaf "
912 "is a BOX, so `axis` selects which of the three widths (0 by default, which is THE "
913 "width on a cubic octree).")
914 .def(
"levels", &T::levels,
"Leaf refinement levels, (num_leaves,) int32 (0 = finest).")
915 .def(
"codes", &T::codes,
"Leaf block-local Morton origin codes, (num_leaves,) uint64.")
916 .def(
"refine_to_sphere", &T::refine_to_sphere, nb::arg(
"center"), nb::arg(
"radius"),
917 nb::arg(
"target_level") = 0u, nb::arg(
"band") = 1.0, nb::arg(
"balance") =
true,
918 "Refine leaves the sphere surface (`center`, `radius` in length units) passes through "
920 "`band` cells) down to "
921 "target_level; optionally restore 2:1 balance (cross-block, collective, on a "
922 "DistributedOctree). Returns the (local) number of refinements performed.")
924 "refine_to_sdf", &chk::refineToSdf<T>, nb::arg(
"sdf"), nb::arg(
"target_level") = 0u,
925 nb::arg(
"band") = 1.0, nb::arg(
"balance") =
true,
926 "Refine toward an arbitrary signed-distance field given as a callable f(x,y,z)->distance "
927 "(suite sign: <0 inside solid), down to target_level — rings / packed beds / any "
928 "non-sphere geometry. Collective when balance=True on a DistributedOctree. Returns "
929 "refinements performed.")
930 .def(
"balance", &T::balance,
931 "Enforce 2:1 graded balance to a fixpoint (cross-block and collective on a "
932 "DistributedOctree); returns (this rank's) refinements performed.")
934 "lohner_indicator", &chk::lohnerIndicator<T>, nb::arg(
"field"), nb::arg(
"eps") = 0.01,
935 "Löhner normalized-second-difference feature indicator E in [0,1] per leaf from a scalar "
936 "field (num_leaves,); large E = steep feature (refine), small = smooth (coarsen). On a "
937 "DistributedOctree it is evaluated across the owner-based halo (collective).")
938 .def(
"adapt", &T::adapt, nb::arg(
"field"), nb::arg(
"refine_thresh"),
939 nb::arg(
"coarsen_thresh"), nb::arg(
"finest_level") = 0u, nb::arg(
"eps") = 0.01,
940 nb::arg(
"linear") =
true,
941 "Solution-adaptive step (Löhner-driven): refine where the indicator > refine_thresh (to "
942 "finest_level), coarsen sibling groups all < coarsen_thresh, 2:1-balance, and "
943 "conservatively remap `field`. MUTATES the octree in place; returns the remapped field "
944 "(M,). `linear` uses minmod-limited prolongation (else piecewise-constant). On a "
945 "DistributedOctree: per block, cross-block balance, ORB ownership kept, bit-identical "
946 "across rank counts (collective).")
947 .def(
"write_vtu", &T::write_vtu, nb::arg(
"path"), nb::arg(
"name"), nb::arg(
"field"),
948 "Write the octree (this rank's block on a DistributedOctree — one file per rank, "
949 "combine in ParaView) + a per-leaf scalar field (num_leaves,) as a VTK UnstructuredGrid "
950 "(.vtu, ASCII, one cell per leaf).");
961 peclet::core::python::install(m);
962 m.attr(
"build_toolchain") = PECLET_AMR_BUILD_TOOLCHAIN;
964 "peclet.amr — adaptive mesh refinement: per-block Octree (serial) and DistributedOctree "
965 "(MPI ORB) for the mesh, the geometric-multigrid Poisson solver, and the device (Kokkos) "
966 "Flow cut-cell Stokes/Navier-Stokes solver. Build a graded octree, refine to an SDF "
967 "surface, read leaf geometry + per-leaf fields as numpy, load-rebalance, gather face "
968 "neighbours, export VTU, and run the flow step on device.";
972 [](std::array<long, 3> cells,
unsigned lmax,
int num_ranks,
long bottom_extent) {
973 chk::ladder(
"predict_hierarchy", lmax);
974 const auto root =
rootCellsOf(cells, lmax,
"predict_hierarchy");
976 throw std::runtime_error(
"predict_hierarchy: num_ranks must be >= 1");
977 if (bottom_extent < 1)
978 throw std::runtime_error(
"predict_hierarchy: bottom_extent must be >= 1");
979 const peclet::core::IVec<3> G{root[0], root[1], root[2]};
981 nb::list cellsL, kindL, extentL;
982 for (
const auto& lv : p.levels) {
983 cellsL.append(lv.cells);
985 extentL.append(nb::make_tuple(lv.extent[0], lv.extent[1], lv.extent[2]));
989 d[
"extent"] = extentL;
991 d[
"num_levels"] = (long)p.levels.size();
992 d[
"num_in_place"] = (long)p.numInPlace();
995 for (
auto k : p.stages)
997 d[
"stages"] = stagesL;
998 d[
"bottom"] = p.bottomName();
1001 nb::arg(
"cells"), nb::arg(
"lmax") = 0u, nb::arg(
"num_ranks") = 1,
1002 nb::arg(
"bottom_extent") = 4,
1003 "The pressure-multigrid ladder a Flow builds on `cells` FINEST cells per axis at tree depth "
1004 "`lmax` over `num_ranks` ranks (docs/amr_mg_depth.md §6.2, §6.7) — a pre-flight tool. A "
1005 "pure function: it builds no mesh and needs no MPI; it re-runs the ladder rule on the ORB "
1006 "a freshly constructed DistributedOctree would produce (not a partition after "
1007 "`DistributedOctree.rebalance` / `Flow.rebalance_mpi`). Below the root brick the ladder "
1008 "halves the grid while every rank's block stays even; where it stops above "
1009 "`bottom_extent` cells per axis on more than one rank the level MOVES (a stage): onto fewer "
1010 "ranks by a sibling merge or a repartition when the Flow's stage policy is on "
1011 "(docs/amr_mg_depth.md WO4b), where the ladder lifts again, else gathered onto every rank "
1012 "(the replicated tail) and continued there; the coarsest level is then solved "
1013 "by damped-Jacobi sweeps if it has at most `bottom_extent` cells per axis, else by the "
1014 "agglomerated GraphAMG-PCG bottom. The prediction is that of the default "
1015 "`Flow.set_pressure_bottom('auto')`.\n\n"
1016 "Returns a dict, levels finest first: `extent` the level's global grid in CELLS per axis "
1017 "(a count, not a length), `cells` its total cell count as if the mesh were uniform (so it "
1018 "equals `Flow.diagnostics.pressure_mg_levels` leaf for leaf only for a uniform mesh at "
1019 "num_ranks=1), `kind` ('octree' at or above the root brick, 'lifted' below it in place, "
1020 "'tail' / 'sibling' / 'repartition' on a stage's continued ladder -- a stage's first level "
1021 "is the SAME grid as the level above it, moved rather than coarsened, exactly as "
1022 "`pressure_mg_levels` lists it), `num_levels`, `num_in_place` (levels above the first "
1023 "stage), `stages` (the stage kinds, outermost first), `tail` (bool: a replicated tail "
1024 "engages) and `bottom` ('jacobi' or 'amg', suffixed '+tail' / '+sibling' / '+repartition' "
1025 "per stage, innermost first) — the spelling `Flow.diagnostics.pressure_mg_bottom` "
1027 "`lmax` is the number of octree coarsenings THE MESH supports, i.e. the tree's lmax for a "
1028 "mesh refined to level 0 somewhere. An UNREFINED Octree(cells, lmax=k>0) is the same mesh "
1029 "as Octree(cells/2**k, lmax=0) — all its leaves are root cells — and must be predicted that "
1030 "way. In general pass depth = tree.lmax - levels().min() and cells = root * 2**depth. "
1031 "`bottom_extent` (default 4, the solver's default; a count in cells per axis, dimensionless) "
1033 "`Flow.pressure_bottom_extent` the run will use; pass the same value.");
1036 "spacing_from_extent",
1037 [](std::array<double, 3> extent, std::array<long, 3> root_cells,
unsigned lmax) {
1038 chk::extentLadder(
"spacing_from_extent", extent, lmax);
1039 const long f = (long)1 << lmax;
1040 return spacingFromExtent(extent, {root_cells[0] * f, root_cells[1] * f, root_cells[2] * f});
1042 nb::arg(
"extent"), nb::arg(
"root_cells"), nb::arg(
"lmax"),
1043 "The finest cell width h0 = extent / (root_cells * 2**lmax) of a PHYSICAL domain (`extent` "
1044 "and h0 in the caller's length units) — the "
1045 "one place an AMR spacing is computed, so no caller writes one (see "
1046 "suite/docs/PHYSICAL_UNITS_PLAN.md). Returns ONE number, so it raises when the extent does "
1047 "not give cubic cells — use `spacings_from_extent` for a box mesh.");
1050 "spacings_from_extent",
1051 [](std::array<double, 3> extent, std::array<long, 3> root_cells,
unsigned lmax) {
1052 chk::extentLadder(
"spacings_from_extent", extent, lmax);
1053 const long f = (long)1 << lmax;
1055 {root_cells[0] * f, root_cells[1] * f, root_cells[2] * f});
1057 nb::arg(
"extent"), nb::arg(
"root_cells"), nb::arg(
"lmax"),
1058 "The finest cell size (dx, dy, dz) = extent / (root_cells * 2**lmax), PER AXIS, in the "
1059 "caller's length units (those of `extent`). The "
1060 "anisotropic form of `spacing_from_extent`: it accepts any positive extent, because the "
1061 "octree's cells are boxes (core/docs/amr_anisotropic.md).");
1063 nb::class_<Octree> octree(
1065 "Serial single-block adaptive octree with a world placement (origin + finest "
1066 "spacing per axis). Leaves are addressed in Z-order slot order; every per-leaf "
1067 "array is indexed by that slot. Lengths (origin, spacing, extent, centres, sizes, sphere "
1068 "centres and radii) are in the caller's consistent length units; amr assumes no unit "
1073 [](
Octree* self, std::array<long, 3> cells,
unsigned lmax, std::array<double, 3> origin,
1074 std::optional<SpacingArg> spacing, std::optional<std::array<double, 3>> extent) {
1075 chk::octree(cells, lmax, origin, spacing, extent);
1076 const auto root =
rootCellsOf(cells, lmax,
"Octree");
1079 nb::arg(
"cells"), nb::kw_only(), nb::arg(
"lmax") = 0u,
1080 nb::arg(
"origin") = std::array<double, 3>{0, 0, 0}, nb::arg(
"spacing") = nb::none(),
1081 nb::arg(
"extent") = nb::none(),
1082 "Build a uniform octree resolving `cells` FINEST cells per axis, refinable `lmax` levels "
1083 "(the root brick is cells/2**lmax root cells, which must divide exactly; lmax=0 is a "
1084 "uniform grid). `origin` is the block's lower corner. Every argument after `cells` is "
1086 "State the domain PHYSICALLY with `extent` = the box side lengths: the cell size is "
1087 "then extent/cells PER AXIS and the caller never writes a spacing. Alternatively give "
1088 "`spacing` (one number for cubic cells, or (dx, dy, dz)); default 1. Passing both "
1090 "The cells are BOXES (core/docs/amr_anisotropic.md): any positive extent is accepted, "
1091 "the octree refines by 2 on every axis, and every level inherits the root aspect "
1092 "ratio. Read the three numbers back from `.spacing`.")
1094 "True iff every face-adjacent leaf pair differs by at most one level (2:1).")
1095 .def(
"find", &chk::find<Octree>, nb::arg(
"x"),
1096 "Index of the leaf containing world point x=(x,y,z), or -1 if outside the block.")
1097 .def(
"refine_to_sdf_graded", &chk::refineToSdfGraded<Octree>, nb::arg(
"sdf"),
1098 nb::arg(
"target_level"), nb::arg(
"band") = 2.0, nb::arg(
"balance") =
true,
1099 "GRADED surface refinement (the mixed-level cut band, "
1100 "docs/amr_mixed_level_cut_band_plan.md §7): `target_level` is a callable "
1101 "f(x,y,z)->level giving the COARSEST acceptable level at a world point (0 = finest), "
1102 "so cut cells end up at SEVERAL levels — fine in throats/contacts, coarse on smooth "
1103 "caps. The band margin is measured in cells of the level being created (not in the "
1104 "finest spacing as in refine_to_sdf). Requires Flow.set_ghost_sampled(True) — the "
1105 "classic overlay contracts a uniform finest band and raises on these level jumps. "
1106 "Returns refinements performed.")
1108 nb::arg(
"coarsest_level"), nb::arg(
"n") = 4.0, nb::arg(
"band") = 2.0,
1109 nb::arg(
"balance") =
true,
1110 "refine_to_sdf_graded driven by the plan's GAP-WIDTH FLOOR (§7 criterion 1): the "
1111 "target level at a point is the coarsest L with n*h_L <= gap(x), clamped to "
1112 "[0, coarsest_level]. `gap` is the local fluid-gap proxy f(x,y,z)->width — for a "
1113 "sphere packing the two-closest-surfaces sum d1+d2; a medial-axis or peclet.pnm "
1114 "throat-radius field substitutes verbatim. n=4 per the M1/M2 measurements. This is "
1115 "the AMReX multi-valued-cell rule inverted: coarsening never merges or disconnects "
1117 .def(
"refine_leaf", &chk::refineLeaf<Octree>, nb::arg(
"i"),
1118 "Split leaf `i` into its 8 children; returns True if it was split (level>0).");
1121 nb::class_<Poisson>(
1123 "Cell-centered finite-volume Poisson solver (L u = rhs) on an Octree, by a "
1124 "geometric-multigrid V-cycle. L is the conservative two-point FV Laplacian (suite sign). "
1125 "The hierarchy snapshots the octree at construction; per-leaf arrays are (num_leaves,) "
1126 "float64 in Z-order slots.")
1128 nb::init<const Octree&, bool>(), nb::arg(
"octree"), nb::arg(
"periodic") =
true,
1129 "Build the multigrid hierarchy from `octree`. periodic=True solves the singular periodic "
1130 "problem (constant null space removed each cycle).")
1134 "Number of multigrid levels: the octree's own coarsenings down to the root brick, then "
1135 "levels BELOW it (the root lifted, docs/amr_mg_depth.md §6.1-§6.2) for as long as some "
1136 "axis has more than 4 cells and every axis stays even with at least 2 cells after "
1137 "halving. So a uniform lmax=0 mesh has a real hierarchy (64^3: 5 levels).")
1139 "L applied to u (the FV Laplacian); use b = apply(u_exact) to manufacture a RHS. "
1140 "(num_leaves,) -> (num_leaves,).")
1142 "Volume-weighted L2 residual norm sqrt(sum V*(rhs - L u)^2).")
1144 "solve", &
Poisson::solve, nb::arg(
"rhs"), nb::arg(
"x0") = std::nullopt,
1145 nb::arg(
"cycles") = 20, nb::arg(
"pre") = 2, nb::arg(
"post") = 2, nb::arg(
"tol") = 0.0,
1146 "Solve L u = rhs with up to `cycles` V-cycles (pre/post Gauss-Seidel sweeps), from x0 or "
1147 "0, stopping once residual <= tol (tol<=0 disables). Returns (u (num_leaves,), "
1148 "final_residual, cycles_done).");
1152 "Collocated incompressible Stokes/Navier-Stokes step on an Octree with a cut-cell immersed "
1153 "boundary (no-slip on an SDF solid). step() = implicit viscous momentum predictor + "
1154 "Almgren-Bell-Colella rotational projection, whose pressure Poisson equation is solved by "
1155 "multigrid-preconditioned CG (the hierarchy continues below the octree's root brick; "
1156 "`diagnostics.pressure_mg_levels`). The box is TRIPLY PERIODIC and the only driving is a "
1157 "uniform body force (set_body_force); a wall is an immersed solid. Any consistent unit "
1158 "system: density [mass/length^3], dynamic viscosity [mass/(length*time)], dt [time], "
1159 "lengths those of the Octree's extent. Iterate step() to a steady state or march in time; "
1160 "velocities and pressure are per-leaf (num_leaves,) arrays in Z-order slots.")
1161 .def(
"__init__", &chk::initFlow<Flow, const Octree>, nb::arg(
"octree"),
1162 nb::arg(
"density") = 1.0, nb::arg(
"viscosity") = 1.0, nb::arg(
"dt") = 1e6,
1165 "Create a flow on `octree` with the given density, dynamic viscosity and time step "
1166 "(defaults 1, 1 and 1e6). A large dt drives straight to the steady (Stokes) solution. "
1167 "The octree is borrowed by reference and must outlive the Flow's use of it.")
1168 .def(
"__init__", &chk::initFlow<Flow, DistributedOctree>, nb::arg(
"octree"),
1169 nb::arg(
"density") = 1.0, nb::arg(
"viscosity") = 1.0, nb::arg(
"dt") = 1e6,
1170 nb::keep_alive<1, 2>(),
1171 "DISTRIBUTED (mpi4py, collective): run this solver on one ORB block of a "
1172 "DistributedOctree — the whole step (momentum, pressure, overlays, adaptivity) then "
1173 "executes multi-rank through the ±2 leaf ghost registry. Per-leaf arrays are this "
1174 "rank's LOCAL leaves. setSolid/step/project/begin_adapt/finish_adapt/rebalance_mpi "
1175 "are collective. np=1 is bit-identical to the single-rank constructor.")
1177 "DISTRIBUTED: weighted-ORB load rebalance — migrates the leaves WITH the state (u, p) "
1178 "to the new owners and rebuilds every solver structure (collective). num_leaves is "
1182 "Build the cut-cell operators from a signed-distance callable f(x,y,z) (>0 fluid, <0 "
1183 "solid) and zero the fields. Call before stepping; re-call to change the geometry.")
1184 .def(
"set_solid_spheres", &chk::setSolidSpheres<Flow>, nb::arg(
"centers"), nb::arg(
"radii"),
1185 nb::arg(
"periodic") =
true,
1186 "set_solid for a UNION OF SPHERES, evaluated natively instead of through a Python "
1187 "callback — the porous-media geometry. `centers` is (M,3), `radii` is (M,) or (1,), "
1190 "`periodic` uses the minimum-image convention over the octree's own box extent. "
1191 "Prefer this to set_solid at bed scale: set_solid samples the SDF tens of times per "
1192 "leaf (operator build, overlay classification at virtual positions, the openness "
1193 "probe), so a Python callback dominates everything else — measured >1h43m of pure "
1194 "numpy on an 11.35M-leaf 180-sphere bed before the GPU ran a single kernel.")
1195 .def(
"set_body_force", &chk::setBodyForce<Flow>, nb::arg(
"fx"), nb::arg(
"fy"), nb::arg(
"fz"),
1196 "Set the body force per unit volume [force/length^3] driving the flow, e.g. a mean "
1197 "pressure gradient -dp/dx along x. It is the only driving the periodic box has. "
1198 "Default (0, 0, 0).")
1200 "Enable/disable momentum advection (high-order scheme SOU by default; implicit FOU + "
1201 "deferred correction). ON by default since 2026-10-24; False => Stokes (no inertia), "
1202 "which a creeping-flow script must now ask for.")
1203 .def(
"set_ghost_projection", &chk::setGhostProjection<Flow>, nb::arg(
"on"),
1204 nb::arg(
"matrix_order") = 2, nb::arg(
"rhs_order") = 2,
1205 "DEFAULT since 2026-08-25 (AUTO: ghost, with an aperture fallback + stderr notice when "
1206 "the finest band is too thin): the fluid-only constraint scheme — family-free, "
1207 "unconditionally stable, protocol-independent (flow's attractor-campaign verdicts; == "
1208 "flow's set_collocated_scheme('ghost')). FULL directional ghost-cell projection (the "
1209 "AMR port): binary-openness pressure operator + wall-anchored closure overlay on the "
1210 "finest-band rows, MG-preconditioned BiCGStab, ghost-closed divergence constraint; "
1211 "implies set_ghost_gradient. (matrix_order, rhs_order) closure orders: (2, 2) default "
1212 "and the only pair cleared for production — the (1, 2) mixed form is march-UNSTABLE "
1213 "above ~2000 spheres (flow hardening Phase A), kept callable for parity records only. "
1214 "Raises if the finest band is too thin (a closure would cross a 2:1 boundary). Call "
1215 "before set_solid.")
1216 .def(
"set_ghost_sampled", &chk::setGhostSampled<Flow>, nb::arg(
"on"), nb::arg(
"rho") = 2.2,
1217 nb::arg(
"max_samples") = 0L,
1218 "MIXED-LEVEL CUT BAND (docs/amr_mixed_level_cut_band_plan.md): allow cut cells at "
1219 "MULTIPLE octree levels — the finest-band contract is dropped. Chain entries that "
1220 "cross a 2:1 boundary become degree-2 LS virtual samples at the uniform closure "
1221 "positions (identity weights at same level, so a uniform finest band is BIT-IDENTICAL "
1222 "to set_ghost_sampled(False)); face classification uses the level-aware canonical "
1223 "openness; the momentum xi-row seam correction and the wall-aware C/F tangential "
1224 "fallback ride along. Implies the ghost projection (engages when the resolved scheme "
1225 "is ghost — the AUTO default or an explicit set_ghost_projection(True)). Distributed "
1226 "since 2026-08-30 (the clouds are a deterministic probe set through the leaf halo). "
1227 "`rho` is the least-squares cloud radius factor, dimensionless (rho = factor * max(h, "
1229 "shipped behaviour) and `max_samples` the nearest-N candidate cap (0 = uncapped) — the "
1230 "M2a cloud-economy knobs, inert at their defaults; do not change them in production "
1231 "without the M2a table. Call before set_solid.")
1232 .def(
"set_pressure", &chk::setPressure<Flow>, nb::arg(
"values"),
1233 "Write the accumulated rotational pressure (pressure units, force/length^2) from a "
1234 "(num_leaves,) array — restart, or "
1235 "re-accumulation policies after finish_adapt (at steady-state dt the transferred p is "
1236 "the load-bearing state; zeroing it after a coarsening adapt lets it re-accumulate "
1238 .def(
"set_dt", &chk::setDt<Flow>, nb::arg(
"dt"),
1239 "Change the time step dt (time units). dt is BAKED INTO the momentum operator at build "
1241 "(idiag = rho/dt), so a set_dt must be followed by set_solid or the operator stays "
1242 "stale. set_solid reallocates and zeroes u and p, so a dt SWITCH mid-march is: read "
1243 "velocity()/pressure() -> set_dt -> set_solid -> set_velocity()/set_pressure(). That "
1244 "sequence is the dt-cycling protocol of the attractor-family batteries.")
1246 "Snapshot the octree topology + (u, p) ahead of an external mesh mutation (adapt / "
1247 "refine_to_sphere / refine_to_sdf / balance on the SAME Octree object). Pair with "
1250 "Rebuild the solver on the mutated octree and conservatively transfer the snapshotted "
1251 "u and p onto it (minmod-limited linear remap). `sdf` is re-sampled on the new leaves "
1252 "(pass the same geometry callable as set_solid); keep the cut band at the finest "
1253 "level on the new mesh (re-run refine_to_sdf on the geometry band after a "
1254 "solution-driven adapt). The advecting face field restarts from the cell average for "
1256 .def(
"set_cf_scheme", &chk::setCfScheme<Flow>, nb::arg(
"scheme"),
1257 "Coarse/fine (2:1) interface scheme. 1 = Martin-Cartwright tangential quadratic, THE "
1258 "DEFAULT since 2026-09-21: second order, applied to the momentum diffusion, the "
1259 "divergence constraint and the pressure gradients (the pressure matrix/MG stays "
1260 "standard, which does not move the steady solution). 0 = the standard two-point flux, "
1261 "first-order at level boundaries, kept only to reproduce pre-2026-09-21 graded results. "
1262 "The default is INERT BY GEOMETRY on a uniform or finest-band mesh -- no C/F faces, no "
1263 "delta -- and matters where a 2:1 interface sees tangential variation, which on a "
1264 "self-similar graded ladder is the difference between order 1.60 and 0.41. Works with "
1265 "both the aperture and the ghost projection. The seam reconstruction of the advected "
1267 "(diagnostics.set_seam_reconstruction) rides on the quadratic scheme: with 0 no seam "
1268 "tables are built. Call before set_solid.")
1269 .def(
"set_advection_scheme", &chk::setAdvectionScheme<Flow>, nb::arg(
"scheme"),
1270 "High-order advection flux: 0 = second-order upwind (default), 1 = Koren TVD.")
1273 "Implicit first-order-upwind deferred-correction advection (default on): unconditionally "
1274 "stable. Off = fully explicit high-order advection.")
1275 .def(
"set_outer_iterations", &chk::setOuterIterations<Flow>, nb::arg(
"n"),
1276 nb::arg(
"tol") = 1e-6,
1277 "Picard outer iterations over the lagged advection per step (default 1).")
1278 .def(
"set_pressure_tolerance", &chk::setPressureTolerance<Flow>, nb::arg(
"rtol"),
1279 "Relative tolerance of the PRESSURE solve, for both drivers -- the MG-PCG default and "
1280 "the ghost projection's BiCGStab (flow shares its set_pressure_pcg tolerance with its "
1281 "ghost BiCGStab the same way). Default 1e-10, the value that was hard-coded until "
1282 "2026-09-21, so leaving it alone reproduces every earlier result. The iteration CAP is "
1283 "step()'s `pres_iters`; this is the accuracy it works to, and loosening it is the "
1284 "cheapest cost knob in the step.")
1286 "The pressure-solve DRIVER of the aperture projection. on=True (THE DEFAULT) is "
1287 "MG-preconditioned conjugate gradients: one V-cycle of the pressure multigrid "
1288 "preconditions CG, the fluid-mean component of the residual is removed every iteration "
1289 "(an aperture cut-cell right-hand side is incompatible by exactly that component), and "
1290 "the solve stops at set_pressure_tolerance or at step()'s / project()'s `pres_iters`. "
1291 "on=False is the bounded stationary V-cycle: exactly `pres_iters` V-cycles, with no "
1292 "tolerance test and no mean removal, so on cut-cell geometry its residual STALLS at "
1293 "the incompatible component instead of converging. Both solve the same pressure "
1294 "equation, so where both converge they give the same projected velocity to the solve "
1295 "tolerance; the choice moves cost and robustness, not the answer. Leave it on: "
1296 "on=False exists to A/B the driver on a compatible problem. It has NO effect under the "
1297 "ghost projection -- the default scheme -- whose nonsymmetric operator is always "
1298 "solved by MG-preconditioned BiCGStab; it acts with set_ghost_projection(False) or "
1299 "where the default fell back to the aperture projection. flow's "
1300 "`Solver.set_pressure_pcg` is the same selector, but flow has no stationary driver "
1301 "(on=False raises there) and takes the cap and tolerance as its max_iter / rtol "
1302 "arguments. Takes effect at the next step()/project(); on a DISTRIBUTED Flow pass "
1303 "the same value on every rank.")
1304 .def(
"set_momentum_tolerance", &chk::setMomentumTolerance<Flow>, nb::arg(
"rtol"),
1305 "Relative tolerance of the per-component MOMENTUM solve (BiCGStab, MG-preconditioned "
1306 "by default). Default 1e-8. At the large dt used for steady drag the momentum operator "
1307 "degrades toward a bare elliptic Laplacian and the solve gets expensive; this bounds "
1308 "the over-solve. The cap is step()'s `mom_iters`. (flow spells the same concept "
1309 "set_velocity_residual_tolerance -- the momentum/velocity divergence between the two "
1310 "codes is a ../docs/NAMING.md item, not settled here.)")
1312 "What solves the coarsest level of the pressure multigrid (docs/amr_mg_depth.md "
1313 "§6.6). A V-cycle converges at a mesh-independent rate only if its coarsest level is "
1314 "effectively solved, and 60 damped-Jacobi sweeps solve a level only up to ~4 cells per "
1315 "axis (8e-9 at 4, 8e-3 at 8, 0.6 at 25). 'auto' (THE DEFAULT) engages the agglomerated "
1316 "GraphAMG-PCG bottom iff the coarsest level still has more than "
1317 "`pressure_bottom_extent` cells on some axis -- i.e. where the ladder ran out on an odd "
1318 "or badly factored grid -- and keeps the sweeps otherwise; 'smoother' always sweeps; "
1319 "'agglomerated' always solves exactly. The choice changes the preconditioner, not the "
1320 "converged pressure (to the solve tolerance), and at the default extent it does not "
1321 "change the iteration count either (§11.4(a): identical counts in all nine measured "
1322 "'smoother'/'agglomerated' pairs); leave it at 'auto' unless you are comparing bottom "
1323 "solves. The same three strings and default as flow's `Solver.set_pressure_bottom`. "
1324 "Takes effect at once on the hierarchy already built and is kept for later set_solid "
1325 "calls. On a DISTRIBUTED Flow call it on every rank: the exact bottom lives in the "
1326 "replicated stage's continued ladder, which the call may build. Raises on any other "
1329 "Where the pressure ladder stops coarsening below the root brick and hands over to the "
1330 "bottom solve, in CELLS PER AXIS of the coarsest level -- a count, not a length: the "
1331 "limit is the bottom smoother's, which solves a level only up to ~4 cells per axis "
1332 "whatever the physical domain (../docs/NAMING.md §1.8; docs/amr_mg_depth.md "
1333 "§6.2/§11.4). The ladder stops once no axis has more than `cells` cells, and "
1334 "set_pressure_bottom('auto') engages the exact bottom where it stopped above it. "
1335 "Default 4, the value at which the 60 bottom sweeps are exact; it is measured rather "
1336 "than preferred (§11.4: 8 moves the iteration count by ~1 on one case in three; "
1337 "tests/study/amr_pressure_depth.py --sweep), so there is rarely a reason to change it. "
1338 "Changes the preconditioner, not the converged pressure (to the solve tolerance). "
1339 "Takes effect at the NEXT set_solid, where the ladder is built. Raises if cells < 1.")
1341 "The bottom extent, in cells per axis (a count, not a length), that "
1342 "set_pressure_bottom_extent last stored (default 4) -- the one the next "
1343 "set_solid builds the ladder with (docs/amr_mg_depth.md §6.8).")
1344 .def(
"step", &chk::step<Flow>, nb::arg(
"mom_iters") = 100, nb::arg(
"pres_iters") = 60,
1345 "Advance one collocated projection step of length dt on device. `mom_iters` caps the "
1346 "momentum solve (BiCGStab, MG-preconditioned) and `pres_iters` the pressure solve "
1347 "(MG-PCG, or BiCGStab under the ghost projection); each stops earlier at its "
1348 "set_momentum_tolerance / set_pressure_tolerance. Collective on a distributed Flow.")
1350 "Per-leaf velocity component (0=x,1=y,2=z), (num_leaves,) float64, in velocity units "
1353 "All three velocity components, (num_leaves, 3) float64, in velocity units "
1356 "Per-leaf fluid mask (False in the solid), (num_leaves,) bool.")
1358 "Volume-weighted L2 norm of the residual cell divergence (projection-quality "
1361 "Per-leaf pressure (incremental-rotational p), (num_leaves,) float64, in pressure units "
1362 "(force/length^2).")
1364 "ABC divergence-free FACE velocity, one value per CSR (sub)face (conservative flux / "
1365 "streamline post-processing).")
1366 .def(
"set_velocity", &chk::setVelocity<Flow>, nb::arg(
"component"), nb::arg(
"values"),
1367 "Write velocity component c (0=x,1=y,2=z) from a (num_leaves,) array in velocity units "
1368 "(length/time) — initial "
1369 "conditions, restart, or warm-start. Call before step()/project().")
1370 .def(
"project", &chk::project<Flow>, nb::arg(
"pres_iters") = 60,
1371 "Pressure projection only (no momentum solve) — project an externally-set velocity "
1372 "field to divergence-free. Returns nothing; read the result via "
1373 "velocity()/velocities().")
1376 "The developer tier (FlowDiagnostics, a view onto this Flow): iteration counts of the "
1377 "last step, the face-field divergence and topology, the C/F and seam-reconstruction "
1378 "censuses, the pressure-multigrid ladder and its bottom solver, and the "
1379 "solver-internals / ablation switches. Nothing here is needed to set up, run or read "
1380 "out a simulation; everything here has a production default.");
1382 nb::class_<FlowDiagnostics>(
1383 m,
"FlowDiagnostics",
1384 "Developer instruments and ablation switches of a Flow, reached as `flow.diagnostics` "
1385 "(suite/docs/QUALITY_PLAN.md D2: the public Flow surface is what a user needs to set up, "
1386 "run and read out a simulation; this is what a developer uses to inspect or ablate it).")
1388 "Total momentum BiCGStab iterations (summed over the 3 components) of the last step.")
1390 "Pressure PCG iterations of the last step.")
1392 "Picard outer iterations actually run in the last step (1 unless "
1393 "set_outer_iterations(>1)).")
1395 "L2 norm of the APERTURE-weighted divergence of the ABC face field. MEANINGFUL ON THE "
1396 "APERTURE PATH ONLY (set_ghost_projection(False)), where it is the pressure-solve "
1397 "residual, far below divergence_norm — including across 2:1 interfaces. Under the "
1398 "GHOST projection (the DEFAULT) the solved constraint is this divergence PLUS an "
1399 "overlay delta that is a functional of the CELL velocities, not of the face field, so "
1400 "this norm omits it and reads O(1) on a perfectly healthy solve (34 at N=32, 184 at "
1401 "N=64 on the Z&H sphere, with the velocities matching peclet.flow to 1e-6). There, "
1402 "divergence_norm() is the residual you want. Unnormalized either way: it grows with "
1403 "resolution and velocity magnitude, so read it as a trend, never as an absolute.")
1405 "How many 2:1 C/F sub-face slots of THIS RANK carry the standard two-point "
1406 "face value because the quadratic one is withheld: both incident cells must be "
1407 "REGULAR fluid (fluid and not cut) for the quadratic C/F scheme "
1408 "(set_cf_scheme(1), the default) to apply there, so this counts the sub-faces "
1409 "where a level boundary meets the wall (docs/amr_cf_flux_gate.md §6.5). 0 "
1410 "on every uniform or finest-band mesh; on a graded mesh it measures the size "
1411 "of the set that runs at the standard scheme's local order. Each sub-face "
1412 "contributes two slots (one per incident cell) and the sum over ranks equals "
1413 "the single-rank count.")
1415 "The face CSR topology face_field() is indexed by, as a dict of arrays: 'start' "
1416 "(num_leaves+1 row offsets, int64), 'nbr' (neighbour leaf per (sub)face, int64), "
1417 "'axis' (0/1/2, int32), 'dir' (+1/-1 from the owning cell toward the neighbour, "
1418 "int32), 'raw_area' (world area the ADVECTIVE flux uses -- the FINE area at a 2:1 "
1419 "sub-face, so a coarse face's four sub-faces sum to the coarse area), 'dist' (world "
1420 "centre distance, 1.5*h_fine at a 2:1 sub-face), 'alpha' (face openness in [0, 1]) and "
1421 "'upup_i' / 'upup_j' (the second upwind probes the SOU/Koren reconstruction samples, "
1422 "-1 where none). A 2:1 sub-face is a slot whose two incident leaves have different "
1423 "Octree.levels(); its centroid is the FINER leaf's face centre. Host-copied on every "
1424 "call -- a diagnostic, not a step-loop read-out. Under MPI a neighbour index >= "
1425 "num_leaves is a ghost slot of this rank's registry, whose world centre (like every "
1426 "slot's) is row `slot` of 'cell_center', an (num_leaves + num_ghost_cells, 3) array. "
1427 "The SEAM RECONSTRUCTION tables of docs/amr_cf_convective.md come with it: 'seam' (one "
1428 "descriptor id per face slot, -1 = a plain slot that takes the ordinary SOU/Koren "
1429 "line), the per-descriptor 'samp_i' / 'samp_j' (the tangential-sample record when i / "
1430 "j is the COARSE cell of a 2:1 sub-face, else -1), 'uu_rec_i' / 'uu_rec_j' (the "
1431 "upstream probe's record when the second upwind cell of i / j crosses a level, else "
1432 "-1) and 'd1_i' / 'd1_j' (world half width along the face axis), and the record CSR "
1433 "'rec_start', 'rec_cell', 'rec_w', 'rec_dist' (the world probe distance, used only "
1434 "where a record is an UPSTREAM probe). All empty with set_cf_scheme(0 = standard), "
1435 "which builds no tables. Rank-local under MPI.")
1437 "Leaf count of every pressure-multigrid level, finest first "
1438 "(docs/amr_mg_depth.md §6.7), as a list of int; empty before set_solid, which "
1439 "is where the hierarchy is built. Levels below the root brick are LIFTED levels "
1440 "— the same octree with its root halved — so a uniform mesh has a real "
1441 "hierarchy rather than a single level. Under MPI the in-place levels are THIS "
1442 "RANK's counts, the levels of a replicated tail (appended last) are GLOBAL "
1443 "counts, identical on every rank, and the levels of a sibling-merge or "
1444 "repartition stage are this rank's counts on its target block (0 on a rank "
1445 "that owns none). Check it against "
1446 "`peclet.amr.predict_hierarchy` (level count, and leaf for leaf on a "
1447 "uniform mesh at np=1), never against a literal.")
1449 "What solves the coarsest pressure level of the hierarchy AS BUILT: 'jacobi' "
1450 "(60 damped-Jacobi sweeps, effectively exact at <= 4 cells per axis: the "
1451 "slowest mode falls by 8e-9) or 'amg' (the agglomerated GraphAMG-PCG solve), "
1452 "with the suffix '+tail' when the coarsest level was gathered onto every rank "
1453 "by the replicated stage, '+sibling' / '+repartition' when a level moved onto "
1454 "fewer ranks (one suffix per stage, innermost first; docs/amr_mg_depth.md "
1455 "§6.5-§6.7, WO4b). Which one runs "
1456 "follows `Flow.set_pressure_bottom` (default 'auto': the exact bottom engages "
1457 "only where the ladder ran out above `Flow.pressure_bottom_extent` cells per "
1458 "axis). 'jacobi' before set_solid.")
1460 "How many tangential-sample records the seam reconstruction built on THIS RANK "
1461 "-- one per 2:1 sub-face pair that passes the C/F face gate (both cells regular "
1462 "fluid). 0 on a uniform mesh and with the standard C/F scheme.")
1464 "How many face-layer records the seam reconstruction built on THIS RANK -- one "
1465 "per (coarse cell, face) whose far side is refined and whose four fine cells "
1466 "are fluid (the case-3 upstream probe).")
1468 "Use the Galerkin velocity multigrid as the momentum solve preconditioner (default on; "
1469 "makes the momentum solve scale with resolution). Call before set_solid.")
1471 "Use the symmetric multicolour Gauss-Seidel smoother in the momentum multigrid (default "
1472 "off = weighted Jacobi). Call before set_solid.")
1474 "Use the rediscretised staircase velocity-MG instead of Galerkin (default off).")
1476 "Solve the momentum predictor with the velocity-MG as the solver (no Krylov), mirroring "
1477 "flow's velocity solve (default off = BiCgStab with the MG as preconditioner).")
1479 "Directional ghost cell-gradient on cut cells for the pressure predictor and the "
1480 "projection's cell correction (2nd-order one-sided, never reads decoupled solid "
1481 "pressure — removes the gauge-dependent O(1/h) cut-cell gradient error of the plain "
1482 "ABC gradient). The ghost projection (the default) implies it; this switch matters for "
1483 "the aperture fallback only. Call before set_solid.")
1485 "Aperture estimator for the (fallback) aperture projection: 2 = analytic "
1486 "marching-squares (DEFAULT since 2026-08-26), 1 = legacy one-sample model. "
1487 "Call before set_solid.")
1489 "ABLATION. The advecting velocity of the momentum advection: the projected, "
1490 "divergence-free face field uf (ON, the shipped Almgren-Bell-Colella scheme) or, with "
1491 "on=False, the un-projected 1/2(u_i+u_j) cell->face average that the first step uses "
1492 "before any projection has run. It is the ONE discretization difference between this "
1493 "solver and peclet.flow's SolverColocated on a uniform grid; turning it off makes the "
1494 "two agree to solver tolerance (docs/amr_flow_uniform_parity.md).")
1496 "ABLATION. Reconstruct the ADVECTED value with level-aware probes at every face whose "
1497 "upwind-side stencil crosses a 2:1 coarse/fine seam (default ON, "
1498 "docs/amr_cf_convective.md): the coarse upwind cell is tangentially sampled at the "
1499 "sub-face's own column, and an upstream probe at another octree level is taken at its "
1500 "TRUE distance (a coarser one as the same tangential sample, a finer one as the mean of "
1501 "the four face-layer children). Without it the sub-face value carries the coarse "
1502 "column's tangential offset -- an O(h) face error, so an O(1) local truncation on the "
1503 "fine side of the seam. on=False restores that, bit for bit, and may be flipped between "
1504 "steps; the tables are built in set_solid either way. Inert with advection off, with "
1505 "set_cf_scheme(0 = standard), and on any mesh with no 2:1 face. Leave it on in "
1506 "production: the switch exists for the A/B of docs/amr_cf_convective.md §12, where it "
1507 "cuts the one-step seam truncation 7.9e-3 -> 2.0e-3 at no measurable cost.");
1509 nb::class_<DistributedOctree> distributed(
1510 m,
"DistributedOctree",
1511 "MPI octree: an ORB block decomposition of a global root grid (one BlockOctree per rank, "
1512 "over MPI_COMM_WORLD). Construct it collectively; "
1513 "refine/balance/rebalance/face_neighbor_gather are collective. Per-leaf arrays describe "
1514 "THIS rank's local block in global world coordinates. Lengths (origin, spacing, extent, "
1515 "centres, sizes) are in the caller's consistent length units.");
1520 std::array<double, 3> origin, std::optional<SpacingArg> spacing,
1521 std::array<bool, 3> periodic, std::optional<std::array<double, 3>> extent) {
1522 chk::placement(
"DistributedOctree", lmax, origin, spacing, extent);
1523 const auto root =
rootCellsOf(cells, lmax,
"DistributedOctree");
1525 root, lmax, origin,
resolveSpacing(spacing, extent, cells,
"DistributedOctree"),
1528 nb::arg(
"cells"), nb::kw_only(), nb::arg(
"lmax") = 0u,
1529 nb::arg(
"origin") = std::array<double, 3>{0, 0, 0}, nb::arg(
"spacing") = nb::none(),
1530 nb::arg(
"periodic") = std::array<bool, 3>{
true,
true,
true},
1531 nb::arg(
"extent") = nb::none(),
1532 "Decompose a global grid of `cells` FINEST cells per axis (root cells = cells/2**lmax, "
1533 "each `lmax` levels deep) across the ranks of MPI_COMM_WORLD via ORB. `origin` places "
1534 "the global grid; `periodic` per axis. Every argument after `cells` is keyword-only.\n\n"
1535 "State the domain PHYSICALLY with `extent` = the global box side lengths; the cell size "
1536 "is then extent/cells PER AXIS. Alternatively give `spacing` (one number or (dx, dy, "
1537 "dz)); default 1. Passing both raises. Read the three numbers back from `.spacing`.")
1541 "This rank's block lower corner, in global root-cell coordinates.")
1543 "This rank's block size in root cells per axis.")
1545 "Global grid size in root cells per axis.")
1546 .def(
"rebalance", &chk::rebalance<DistributedOctree>, nb::arg(
"fields"),
1547 "Re-decompose by leaf count (weighted ORB) and migrate leaves + their fields. `fields` "
1548 "is (num_leaves, K) float64; returns this rank's (M, K) columns after migration. Pure "
1549 "redistribution; the partition is updated in place (collective).")
1551 nb::arg(
"sentinel") = 0.0,
1552 "For each local leaf, the field value across each of its 6 faces, gathered over the "
1553 "owner-based halo. `field` is (num_leaves,); returns (num_leaves, 6) laid out "
1554 "[+x,-x,+y,-y,+z,-z]; domain boundaries carry `sentinel` (collective).");
Geometric multigrid for AmrPoisson over a uniformly-coarsened octree hierarchy.
Per-block adaptive octree over block-local Morton codes.
unsigned level(Index i) const
std::array< std::array< Coord, Dim >, 2 > bounds(Index i) const
Inclusive integer bounds [lo, hi] of leaf i in fine units.
typename M::coord_type Coord
typename M::code_type Code
std::array< long, 3 > global_root_size() const
std::array< long, 3 > block_origin_root() const
std::array< long, 3 > block_brick() const
DO & ref()
The wrapped core octree (the distributed Flow constructor hooks into it).
void write_vtu(const std::string &path, const std::string &name, DArray field)
nb::ndarray< nb::numpy, std::int32_t > levels() const
std::array< double, 3 > spacing() const
nb::ndarray< nb::numpy, double > rebalance(DArray fields)
nb::ndarray< nb::numpy, double > lohner_indicator(DArray field, double eps)
DistributedOctree(std::array< long, 3 > global_root, unsigned lmax, std::array< double, 3 > origin, std::array< double, 3 > spacing, std::array< bool, 3 > periodic)
Index refine_to_sphere(std::array< double, 3 > center, double radius, unsigned target_level, double band, bool balance)
std::array< long, 3 > cells() const
The GLOBAL finest grid: global root cells * 2**lmax per axis (what the constructor took).
std::array< double, 3 > origin() const
The global lower corner.
Index refine_to_sdf(std::function< double(double, double, double)> sdf, unsigned target_level, double band, bool balance)
nb::ndarray< nb::numpy, double > centers() const
nb::ndarray< nb::numpy, double > face_neighbor_gather(DArray field, double sentinel)
nb::ndarray< nb::numpy, double > sizes(int axis) const
nb::ndarray< nb::numpy, double > adapt(DArray field, double refine_thresh, double coarsen_thresh, unsigned finest_level, double eps, bool linear)
nb::ndarray< nb::numpy, std::uint64_t > codes() const
std::array< double, 3 > extent() const
The global box side lengths, cells * spacing.
void release() noexcept override
void set_momentum_mg(bool on)
void set_seam_reconstruction(bool on)
int last_outer_iters() const
int last_pres_iters() const
void set_ghost_gradient(bool on)
void set_momentum_gs(bool on)
void set_uf_advection(bool on)
peclet::core::Index num_seam_sample_records() const
double divergence_norm_face()
void set_velocity_mg_staircase(bool on)
void set_aperture_order(int order)
std::string pressure_mg_bottom() const
std::vector< peclet::core::Index > pressure_mg_levels() const
nb::dict face_topology() const
peclet::core::Index num_cf_cut_faces() const
peclet::core::Index num_seam_layer_records() const
int last_mom_iters() const
void set_momentum_mg_solver(bool on)
void set_pressure_tolerance(double rtol)
void set_solid(std::function< double(double, double, double)> sdf)
void set_implicit_advection(bool on)
void set_pressure_bottom(const std::string &mode)
void set_ghost_sampled(bool on, double rho, long max_samples)
void set_advection(bool on)
nb::ndarray< nb::numpy, double > pressure() const
void set_solid_spheres(nb::ndarray< const double, nb::c_contig > centers, nb::ndarray< const double, nb::c_contig > radii, bool periodic)
nb::ndarray< nb::numpy, double > face_field() const
void set_body_force(double fx, double fy, double fz)
nb::ndarray< nb::numpy, bool > is_fluid() const
void set_velocity(int c, nb::ndarray< double, nb::c_contig > h)
void set_momentum_tolerance(double rtol)
void project(int pres_iters)
long pressure_bottom_extent() const
nb::ndarray< nb::numpy, double > velocity(int c) const
nb::ndarray< nb::numpy, double > velocities() const
void set_pressure_pcg(bool on)
void set_outer_iterations(int n, double tol)
void rebalance_mpi(std::function< double(double, double, double)> sdf)
void set_advection_scheme(int s)
void release() noexcept override
void step(int mom_iters, int pres_iters)
void set_pressure_bottom_extent(long cells)
Flow(const Octree &oct, double rho, double mu, double dt)
void set_ghost_projection(bool on, int matrix_order, int rhs_order)
void set_cf_scheme(int scheme)
amr::AmrFlow & engine()
The developer tier (QUALITY_PLAN D2): FlowDiagnostics reaches the solver through this.
void finish_adapt(std::function< double(double, double, double)> sdf)
void set_pressure(nb::ndarray< double, nb::c_contig > h)
std::array< double, 3 > spacing() const
Index refine_to_sphere(std::array< double, 3 > center, double radius, unsigned target_level, double band, bool balance)
Index refine_to_gap_floor(std::function< double(double, double, double)> sdf, std::function< double(double, double, double)> gap, unsigned coarsest_level, double n, double band, bool balance)
nb::ndarray< nb::numpy, std::uint64_t > codes() const
nb::ndarray< nb::numpy, std::int32_t > levels() const
Index find(std::array< double, 3 > x) const
nb::ndarray< nb::numpy, double > centers() const
const BO & octreeRef() const
Index refine_to_sdf_graded(std::function< double(double, double, double)> sdf, std::function< unsigned(double, double, double)> target_level, double band, bool balance)
nb::ndarray< nb::numpy, double > lohner_indicator(DArray field, double eps)
bool refine_leaf(Index i)
void release() noexcept override
void write_vtu(const std::string &path, const std::string &name, DArray field)
std::array< long, 3 > cells() const
The FINEST-level cell counts the block resolves: root cells * 2**lmax per axis.
std::array< double, 3 > origin() const
Octree(std::array< long, 3 > root, unsigned lmax, std::array< double, 3 > origin, std::array< double, 3 > spacing)
Index refine_to_sdf(std::function< double(double, double, double)> sdf, unsigned target_level, double band, bool balance)
std::array< double, 3 > extent() const
The block's physical side lengths, cells * spacing.
nb::ndarray< nb::numpy, double > sizes(int axis) const
const amr::AmrGeometry< 3 > & geoRef() const
nb::ndarray< nb::numpy, double > adapt(DArray field, double refine_thresh, double coarsen_thresh, unsigned finest_level, double eps, bool linear)
nb::tuple solve(DArray rhs, std::optional< DArray > x0, int cycles, int pre, int post, double tol)
void release() noexcept override
std::size_t num_levels() const
Poisson(const Octree &oct, bool periodic)
double residual(DArray u, DArray rhs)
nb::ndarray< nb::numpy, double > apply(DArray u)
nb::ndarray< nb::numpy, double > leafCenters(const BO &t, const amr::AmrGeometry< 3 > &geo)
nb::ndarray< nb::numpy, std::uint64_t > leafCodes(const BO &t)
std::array< double, 3 > spacingOf(const SpacingArg &sp)
nb::ndarray< double, nb::c_contig > DArray
nb::ndarray< nb::numpy, double > vecToArray(std::vector< double > v)
double spacingFromExtent(const std::array< double, 3 > &extent, const std::array< long, 3 > &cells)
std::array< double, 3 > resolveSpacing(const std::optional< SpacingArg > &spacing, const std::optional< std::array< double, 3 > > &extent, const std::array< long, 3 > &cells, const char *who)
std::array< double, 3 > spacingsFromExtent(const std::array< double, 3 > &extent, const std::array< long, 3 > &cells)
std::array< long, 3 > rootCellsOf(const std::array< long, 3 > &cells, unsigned lmax, const char *who)
void bindOctreeCommon(nb::class_< T > &c)
nb::ndarray< nb::numpy, T > vec2(std::vector< T > v, std::size_t cols)
nb::ndarray< nb::numpy, double > leafSizes(const BO &t, const amr::AmrGeometry< 3 > &geo, int axis)
nb::ndarray< nb::numpy, std::int32_t > leafLevels(const BO &t)
nb::ndarray< nb::numpy, T > vec1(std::vector< T > v)
std::vector< double > asField(const BO &t, const DArray &field, const char *who)
amr::DistributedOctree< 3 > DO
std::variant< double, std::array< double, 3 > > SpacingArg
const char * toString(MgLevelKind k)
Index refineToSdf(BlockOctree< Dim, Bits > &t, const AmrGeometry< Dim > &geo, SdfFn &&sdf, unsigned targetLevel, Real band=1.0, bool balance=true)
Refine leaves near an SDF interface down to targetLevel.
std::vector< double > lohnerIndicator(const BlockOctree< Dim, Bits > &t, const std::vector< double > &u, double eps=0.01)
Löhner normalized second-difference indicator E_i ∈ [0,1], per leaf, for scalar u (indexed by leaf sl...
std::vector< double > distributedAdapt(DistributedOctree< Dim, Bits > &d, const std::vector< double > &f, double refineThresh, double coarsenThresh, unsigned finestLevel=0, double eps=0.01, bool linear=true)
One distributed solution-adaptive step.
@ Octree
a coarsening of the octree itself (at or above the root brick)
Index refineToSdfGraded(BlockOctree< Dim, Bits > &t, const AmrGeometry< Dim > &geo, SdfFn &&sdf, TargetFn &&targetFn, Real band=2.0, bool balance=true)
Graded variant of refineToSdf: a per-point TARGET LEVEL function instead of one global targetLevel — ...
AdaptResult< Dim, Bits > adapt(const BlockOctree< Dim, Bits > &t, const std::vector< double > &f, double refineThresh, double coarsenThresh, unsigned finestLevel=0, double eps=0.01, bool linear=true)
All-in-one solution-adaptive step: Löhner indicator → flags → adaptField.
void writeVtu(const std::string &path, const BlockOctree< Dim, Bits > &t, const AmrGeometry< Dim > &geo, const std::string &name, const std::vector< double > &cellData)
Write a BlockOctree (+ world geometry + a per-leaf scalar) as a VTK UnstructuredGrid (....
auto gapFloorTarget(GapFn &&gapFn, Real h0, unsigned coarsestLevel, Real n=4.0)
The plan's §7 criterion 1 as a ready-made targetFn for refineToSdfGraded: the GAP-WIDTH FLOOR.
MgLadderPrediction< Dim > predictPressureLadder(IVec< Dim > G, unsigned lmax, int numRanks, Index bottomExtent=4, const PressureStagePolicy &policy={})
Predict the pressure-multigrid ladder for a global ROOT grid G (in root cells, i.e.
std::vector< double > lohnerIndicatorDistributed(const DistributedOctree< Dim, Bits > &d, const std::vector< double > &u, double eps=0.01)
Löhner indicator per local leaf, using the owner-based face-neighbour halo so cross-block neighbours ...
World-space placement of a block-local octree: fine coordinate (0,..,0) sits at origin,...
Vec< Dim > center(const std::array< std::array< Coord, Dim >, 2 > &b) const
World coordinate of a leaf centre, from its integer bounds [lo,hi] (inclusive, fine units).
Real leafSize(unsigned level, int d) const
World width of a leaf at level on axis d (it covers 2^level fine cells).