flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
flow_bindings.cpp
Go to the documentation of this file.
1
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>
31
32#include <array>
33#include <cstdint>
34#include <Kokkos_Core.hpp>
35#include <limits>
36#include <string>
37#include <vector>
38
39#ifdef PECLET_FLOW_MPI
40#include <mpi.h>
41
42#include "peclet/core/common/types.hpp"
43#include "peclet/core/decomp/block_decomposer.hpp"
44#endif
45
55#include "flow_bindings_vof.hpp"
58#include "flow_ibm.hpp"
59#include "peclet/core/python/kokkos_teardown.hpp"
60#include "peclet/core/python/ndarray_interop.hpp"
61
62namespace nb = nanobind;
63// The topic binders (flow_bindings_<topic>.hpp).
64namespace fb = peclet::flow::bindings;
65// The shared binding helpers (flow_bindings_common.hpp).
66#ifdef PECLET_FLOW_MPI
67using peclet::flow::bindings::ensure_mpi_init;
68#endif
72
73// The developer-tier Anderson accelerator of a steady march, bound as a PRIVATE class
74// (`_AndersonAccelerator` / `_AndersonAcceleratorColocated`) and created only through
75// `s.diagnostics.anderson_accelerator(...)`. The public entry is peclet.flow.march_to_steady.
76template <class Grid>
77static void bind_accelerator(nb::module_& m, const char* name) {
78 using A = BoundAccelerator<Grid>;
79 nb::class_<A>(
80 m, name,
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).")
95 .def_prop_ro(
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.");
114}
115
116// The developer tier of Solver<Grid>: every member that inspects, profiles, ablates or tunes
117// the solver beyond what a user of the method needs (suite/docs/QUALITY_PLAN.md D2). Bound
118// once per grid as `<name>Diagnostics`, reached only through `Solver.diagnostics`.
119template <class Grid>
120static void bind_diagnostics(nb::module_& m, const char* name) {
121 using D = Diagnostics<Grid>;
122 nb::class_<D> cls(
123 m, name,
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.");
140}
141
142// Register a solver class for the given GridLayout policy (Staggered -> "Solver", Colocated ->
143// "SolverColocated") and its developer tier. The Python API is identical across grids; only
144// the velocity-unknown placement and the advection control volume differ inside Solver<Grid>.
145template <class Grid>
146static void bind_solver(nb::module_& m, const char* name, const char* diag_name) {
147 using S = BoundSolver<Grid>;
148 bind_diagnostics<Grid>(m, diag_name);
149 nb::class_<S> cls(
150 m, 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`.");
168}
169
170NB_MODULE(_flow, m) {
171 m.attr("__doc__") =
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 "
175 "default)\n"
176 " SolverColocated — collocated / cell-centered velocities (ABC approximate projection)\n\n"
177 "Conventions: physical units throughout (density rho, viscosity mu, physical pressure p); "
178 "SDFs\n"
179 "are negative inside the solid; fields are Fortran-order (nx,ny,nz) float64 (x-fastest). "
180 "This is\n"
181 "the single-rank module — the multi-rank MPI path is exercised by the tests/kokkos_mpi "
182 "suite.\n\n"
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.";
187 // Kokkos init + the release-then-finalize atexit hook + finalize() + execution_space: the
188 // suite-wide pattern (see the file comment and peclet/core/python/kokkos_teardown.hpp).
189 peclet::core::python::install(m);
190
191 // Staggered MAC grid (THE flow solver) + the collocated/cell-centered variant. Same Python API.
192 bind_solver<peclet::flow::Staggered>(m, "Solver", "SolverDiagnostics");
193 bind_solver<peclet::flow::Colocated>(m, "SolverColocated", "SolverColocatedDiagnostics");
194 bind_accelerator<peclet::flow::Staggered>(m, "_AndersonAccelerator");
195 bind_accelerator<peclet::flow::Colocated>(m, "_AndersonAcceleratorColocated");
196
197#ifdef PECLET_FLOW_MPI
198 // Module-level: this rank's ORB block of the global (gnx,gny,gnz) grid, matching the
199 // deterministic BlockDecomposer the Solver's initMpi re-derives internally (and the C++
200 // tests/kokkos_mpi template). Returns (origin=[ox,oy,oz], size=[lnx,lny,lnz]); slice the global
201 // SDF with these to build the local block, then Solver(*size) + init_mpi(gnx,gny,gnz). MPI_Init
202 // is called if needed.
203 m.def(
204 "mpi_block",
205 [](int gnx, int gny, int gnz, int levels, double max_imbalance) {
206 ensure_mpi_init();
207 int rank = 0, size = 1;
208 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
209 MPI_Comm_size(MPI_COMM_WORLD, &size);
210 // Derive it through the SAME factory Solver::initMpi uses, so this local block size matches
211 // the solver's dec_ under either decomposition mode (see Solver.set_decomposition).
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);
218 },
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 "
225 "needed.\n\n"
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: "
238 "reproduces "
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 "
246 "ORB.");
247
248#ifdef PECLET_FLOW_MPI
249 m.def(
250 "predict_hierarchy",
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>>
256 out;
257 int align = 1;
258 for (const auto& r : peclet::flow::CutcellMG::predict(
259 gnx, gny, gnz, np, levels, telescope, min_extent, decomposition_levels,
260 max_imbalance, weights ? &*weights : nullptr, &align))
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);
264#endif
265 if (!weights)
266 return nb::cast(out);
267 return nb::make_tuple(nb::cast(out), align);
268 },
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;
293#else
294 m.attr("has_mpi") = false;
295#endif
296}
flow — the Anderson accelerator of a steady march: core's AndersonCore wrapped around one Solver<Grid...
NB_MODULE(_flow, m)
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)