23#include <nanobind/nanobind.h>
24#include <nanobind/ndarray.h>
25#include <nanobind/stl/array.h>
26#include <nanobind/stl/optional.h>
27#include <nanobind/stl/pair.h>
28#include <nanobind/stl/string.h>
29#include <nanobind/stl/tuple.h>
30#include <nanobind/stl/vector.h>
34#include <Kokkos_Core.hpp>
42#include "peclet/core/common/types.hpp"
43#include "peclet/core/decomp/block_decomposer.hpp"
59#include "peclet/core/python/kokkos_teardown.hpp"
60#include "peclet/core/python/ndarray_interop.hpp"
62namespace nb = nanobind;
67using peclet::flow::bindings::ensure_mpi_init;
81 "Anderson accelerator of a steady march (doc/steady_acceleration.md): type-II Anderson on "
82 "the march state (velocity + P, plus the collocated face field under projected-face "
83 "advection), velocity-only metric. Created by s.diagnostics.anderson_accelerator(); the "
84 "public driver is peclet.flow.march_to_steady. step(accelerate) is ONE call of the solver's "
85 "step() (preceded by the lazy mix when accelerate and a mix is pending); between calls the "
86 "solver always holds a genuine step output.")
87 .def(
"step", &A::step, nb::arg(
"accelerate") =
true,
88 "One map evaluation: when accelerate and a mix is pending, the solver's state is "
89 "replaced by the Anderson mix first; then one solver.step(). accelerate=False is a "
90 "plain step that still records history. Raises if the configuration became "
91 "unsupported (the same refusals as the constructor).")
92 .def_prop_ro(
"residual", &A::residual,
93 "Relative velocity residual ||g_u - x_u|| / ||g_u|| of the last evaluation "
94 "(inf before the first).")
96 "status", [](
const A& a) {
return std::string(a.statusName()); },
97 "'active' or 'disabled' (acceleration stopped; steps are plain).")
98 .def_prop_ro(
"reason", &A::reason,
"Why the status is not 'active' ('' while active).")
99 .def_prop_ro(
"num_restarts", &A::numRestarts,
"History restarts so far.")
100 .def_prop_ro(
"num_resets", &A::numResets,
101 "History resets because the state or the parameters (dt, rho, mu, body force, "
102 "advection on / scheme / implicit) "
103 "were changed from outside.")
104 .def_prop_ro(
"num_columns", &A::numColumns,
"Window columns in use.")
105 .def_prop_ro(
"window", &A::window,
"The window m.")
106 .def_prop_ro(
"mixing", &A::mixing,
"The mixing beta.")
107 .def_prop_ro(
"memory_bytes", &A::memoryBytes,
108 "Bytes of the history: (2m+3) * n_fields * 8 * n_padded (this rank).")
109 .def_prop_ro(
"seconds", &A::seconds,
110 "Cumulative wall time spent in the accelerator, solver.step() excluded "
111 "(device-fenced), seconds, this rank.")
112 .def(
"reset", &A::reset,
"Clear the history (the next call starts a new window).")
113 .def(
"disable", &A::disable,
"Stop accelerating for good; step() is then a plain step.");
124 "Developer tier of a Solver, reached as `s.diagnostics`: instruments (censuses, timers, "
125 "budgets, ledgers), solver TUNING beyond the public driver selection, ablation switches "
126 "and the raw zero-copy / MPI internals. Nothing here is needed to set up, run or read out "
127 "a simulation. It holds a reference to the solver and no state of its own; the setters "
128 "that CHANGE RESULTS say so in their docstring.");
146static void bind_solver(nb::module_& m,
const char* name,
const char* diag_name) {
151 "One incompressible Navier-Stokes solver on a block of the grid (staggered MAC, the "
152 "reference) -- or, for SolverColocated, the same API with cell-centered velocities and "
153 "the ABC approximate projection. Construct on a (physical) domain; set_rho / set_mu / "
154 "set_dt and the domain BCs; give it a geometry (set_solid, set_pressure_geometry or a "
155 "scene); step(); read out with the get_* arrays. Developer instruments and tuning live "
156 "on `.diagnostics`.");
172 "flow — Kokkos cut-cell IBM incompressible Navier-Stokes solver for porous media.\n\n"
173 "Two solver classes share an identical API (only the velocity-unknown placement differs):\n"
174 " Solver — staggered MAC grid (THE flow solver; permeability/drag accuracy "
176 " SolverColocated — collocated / cell-centered velocities (ABC approximate projection)\n\n"
177 "Conventions: physical units throughout (density rho, viscosity mu, physical pressure p); "
179 "are negative inside the solid; fields are Fortran-order (nx,ny,nz) float64 (x-fastest). "
181 "the single-rank module — the multi-rank MPI path is exercised by the tests/kokkos_mpi "
183 "Kokkos is initialized at import and finalized via a Python atexit hook that first releases "
184 "every live Solver and zero-copy field view (flow.finalize() does the same on demand); "
185 "nothing needs to be released before interpreter exit. execution_space names the active "
186 "Kokkos backend (\"OpenMP\", \"Cuda\", \"HIP\"), chosen by the build's install prefix.";
189 peclet::core::python::install(m);
197#ifdef PECLET_FLOW_MPI
205 [](
int gnx,
int gny,
int gnz,
int levels,
double max_imbalance) {
207 int rank = 0, size = 1;
208 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
209 MPI_Comm_size(MPI_COMM_WORLD, &size);
212 auto dec = peclet::flow::CutcellMG::decomposition(
static_cast<std::size_t
>(size), gnx, gny,
213 gnz, levels, max_imbalance);
214 auto blk = dec.block(
static_cast<std::size_t
>(rank));
215 std::vector<int> origin{(int)blk.origin[0], (
int)blk.origin[1], (int)blk.origin[2]};
216 std::vector<int> bsize{(int)blk.size[0], (
int)blk.size[1], (int)blk.size[2]};
217 return std::make_pair(origin, bsize);
219 nb::arg(
"gnx"), nb::arg(
"gny"), nb::arg(
"gnz"), nb::arg(
"levels") = 0,
220 nb::arg(
"max_imbalance") = 1.05,
221 "Return this MPI rank's ORB block of the global (gnx,gny,gnz) grid as (origin, size), each a "
222 "length-3 list [x,y,z]. Use it to slice the global SDF into this rank's local block for a "
223 "distributed Solver, in this order: Solver(*size), init_mpi(gnx, gny, gnz), then the "
224 "geometry (init_mpi raises after set_solid / set_pressure_geometry). MPI_Init is called if "
226 "levels / max_imbalance choose how the partition is built and MUST match the values given "
227 "to Solver.set_decomposition() -- both derive the same partition and have to agree. "
228 "levels=0 (DEFAULT) = AUTO: the aligned ORB (split positions on the FINE grid snapped to a "
229 "power of two, capped at 16, i.e. 5 nested multigrid levels) whenever it is exactly "
230 "balanced; otherwise the coarse-first partition at depth 5, then 4, with a balance-aware "
231 "split axis, the first within max_imbalance (default 1.05) that nests at least as many "
232 "levels in place as the aligned ORB (every block even and at least 4 cells wide at each); "
233 "otherwise the balance-aware aligned ORB if it has a smaller largest block and nests at "
234 "least min(3, the aligned ORB's) levels; otherwise the aligned ORB. AUTO never cuts an "
235 "axis the aligned ORB "
236 "leaves whole, and changes its set of cut axes only when the aligned ORB's largest block "
237 "is at least 5/4 of the mean. levels=1 = the aligned ORB as is (the default before 2026-10: "
239 "an older np > 1 partition). levels >= 2 = COARSE-FIRST: build the ORB on the grid "
240 "coarsened levels-1 times and refine the partition upward, so every block is a multiple of "
241 "the coarsening factor BY CONSTRUCTION and the hierarchy nests for the full requested "
242 "depth. Coarse-first also balances better: the aligned ORB picks a split and then rounds "
243 "it (a balanced 96|96 can round to 128|64), whereas on the coarse grid one cell IS the "
244 "quantum. Each depth from `levels` down to 2 is BUILT and measured, and the deepest one "
245 "whose max-block/min-block ratio stays within max_imbalance is taken, else the aligned "
248#ifdef PECLET_FLOW_MPI
251 [](
int gnx,
int gny,
int gnz,
int np,
int levels,
bool telescope,
int min_extent,
252 int decomposition_levels,
double max_imbalance,
253 const std::optional<std::vector<double>>&
weights) -> nb::object {
254 std::vector<std::tuple<std::tuple<int, int, int>, int, std::tuple<int, int, int>,
255 std::tuple<int, int, int>,
bool>>
258 for (
const auto& r : peclet::flow::CutcellMG::predict(
259 gnx, gny, gnz, np, levels, telescope, min_extent, decomposition_levels,
261 out.emplace_back(std::make_tuple(r.global.x, r.global.y, r.global.z), r.ranks,
262 std::make_tuple(r.block.x, r.block.y, r.block.z),
263 std::make_tuple(r.ratio.x, r.ratio.y, r.ratio.z), r.tele);
266 return nb::cast(out);
267 return nb::make_tuple(nb::cast(out), align);
269 nb::arg(
"gnx"), nb::arg(
"gny"), nb::arg(
"gnz"), nb::arg(
"np"), nb::arg(
"levels"),
270 nb::arg(
"telescope") =
true, nb::arg(
"min_extent") = 4, nb::arg(
"decomposition_levels") = 0,
271 nb::arg(
"max_imbalance") = 1.05, nb::arg(
"weights") = nb::none(),
272 "The pressure-multigrid hierarchy init_mpi WOULD build for this grid / rank count / level "
273 "request, for the level-0 decomposition that decomposition_levels / max_imbalance describe "
274 "(pass what you will pass to Solver.set_decomposition) and with or "
275 "without coarse-level telescoping -- a pure function, no MPI, no allocation, any rank "
276 "count. Returns one row per level: (global dims, ranks holding the level, block-0 dims, "
277 "ratio to the next level, telescopes-out). Pre-flight any job with it. telescope defaults to "
278 "True, the Solver's own default (set_pressure_telescope), so the forecast is the hierarchy "
279 "the solver builds; telescope=False forecasts the in-place-only hierarchy, which at np > 1 "
280 "can stop coarsening early. levels=0 forecasts "
281 "the automatic depth (doc/mg_depth_policy.md) for the singular operator (periodic / "
282 "all-Neumann / immersed solid; no outflow face), at the default bottom extent 4.\n\n"
283 "weights: per-cell weights, exactly what diagnostics.rebalance_by_weights takes (global "
284 "x-fastest, gnx*gny*gnz values). Given, the forecast is the hierarchy AFTER that rebalance: "
285 "level 0 is its aligned weighted ORB (split planes on multiples of 2^a, a the largest "
286 "alignment whose weight imbalance stays within 1.05; decomposition_levels / max_imbalance "
287 "are then ignored, as the rebalance ignores set_decomposition), and a stage may be a "
288 "repartition onto fewer ranks (reported as telescopes-out). The return is then the pair "
289 "(rows, align), align = 2^a -- the value rebalance_by_weights returns and a co-decomposing "
290 "dem takes as migrate_to_weights(weights, align=...). None (default): the rows alone, "
291 "unchanged. min_extent is in cells (a count, not a length).");
292 m.attr(
"has_mpi") =
true;
294 m.attr(
"has_mpi") =
false;
flow — the Anderson accelerator of a steady march: core's AndersonCore wrapped around one Solver<Grid...
static void bind_solver(nb::module_ &m, const char *name, const char *diag_name)
static void bind_diagnostics(nb::module_ &m, const char *name)
static void bind_accelerator(nb::module_ &m, const char *name)
Input validation of the peclet.flow Python binding (src/flow_bindings.cpp only).
Shared helpers of the peclet.flow Python binding: array conversion, the string-enum tables,...
Python binding of peclet.flow: construction and domain read-outs, solver controls,...
Python binding of peclet.flow: domain boundary conditions, scenes, solids, moving instances and hydro...
Python binding of peclet.flow: phase change (mass flux, energy, divergence source).
Python binding of peclet.flow: scalar transport.
Python binding of peclet.flow: the sharp viscous interface stress of the VoF momentum (setter,...
Python binding of peclet.flow: the developer tier's solver tuning, ablation switches and pressure / m...
Python binding of peclet.flow: the VoF colour field, its advection, contact angle and wetting.
Python binding of peclet.flow: the VoF block container, open boundaries, curvature and surface tensio...
Python binding of peclet.flow: the VoF momentum coupling, interface forces and property closures.
flow — host-facing Kokkos IBM Navier-Stokes solver (drop-in flow-style API).
void bindDiagnosticsSharpViscous(C &cls)
SolverDiagnostics (and its collocated twin): sharp viscous interface census and fit.
void bindDiagnosticsPhaseChange(C &cls)
SolverDiagnostics (and its collocated twin): phase-change options, ledgers and budgets.
void bindSolverSharpViscous(C &cls)
Solver (and its collocated twin): sharp viscous interface setter and read-out.
void bindDiagnosticsVofMomentum(C &cls)
SolverDiagnostics (and its collocated twin): VoF momentum options and read-outs, property and density...
void bindSolverPhaseChange(C &cls)
Solver (and its collocated twin): phase change.
void bindSolverVofMomentum(C &cls)
Solver (and its collocated twin): VoF momentum and property closures, cell force and drag.
void bindSolverControls(C &cls)
Solver (and its collocated twin): time step, body force, advection, decomposition and the pressure / ...
void bindDiagnosticsScalar(C &cls)
SolverDiagnostics (and its collocated twin): scalar geometry, census, budget and facets.
void bindSolverGeometry(C &cls)
Solver (and its collocated twin): domain BCs, pressure geometry, scenes, instances,...
void bindDiagnosticsSolverOptions(C &cls)
SolverDiagnostics (and its collocated twin): face interpolation, pressure projection and advection sw...
void bindSolverState(C &cls)
Solver (and its collocated twin): state, stepping, velocity and field read-outs.
void bindDiagnosticsVofForces(C &cls)
SolverDiagnostics (and its collocated twin): CSF mode, interface width, curvature clips,...
void bindSolverVof(C &cls)
Solver (and its collocated twin): VoF colour field, advection, contact angle and wall slip.
void bindDiagnosticsGeometry(C &cls)
SolverDiagnostics (and its collocated twin): cut-cell and moving-instance instruments,...
void bindDiagnosticsVof(C &cls)
SolverDiagnostics (and its collocated twin): VoF step controls, geometry, contact angle,...
void bindDiagnosticsPressure(C &cls)
SolverDiagnostics (and its collocated twin): momentum and pressure-solver options,...
void bindDiagnosticsPorousMpi(C &cls)
SolverDiagnostics (and its collocated twin): pressure under-relaxation, porous options,...
void bindSolverSetup(C &cls)
Solver (and its collocated twin): the diagnostics tier, constructors, domain read-outs,...
void bindSolverScalar(C &cls)
Solver (and its collocated twin): scalar transport.
void bindSolverPorousMpi(C &cls)
Solver (and its collocated twin): ghost width, porous continuity, divergence read-outs and MPI.
void bindDiagnosticsVofBlocks(C &cls)
SolverDiagnostics (and its collocated twin): VoF census, block container, outflow density correction,...
void bindSolverVofBlocks(C &cls)
Solver (and its collocated twin): VoF blocks, open boundaries, curvature and surface tension.
The developer tier: a view onto one Solver<Grid> (no state of its own).
static std::vector< peclet::core::Real > weights(int kind, Grid3 g)