flow 1.4.0
Kokkos cut-cell IBM incompressible Navier-Stokes solver + pnm pore extraction
Loading...
Searching...
No Matches
flow_bindings_geometry.hpp
Go to the documentation of this file.
1
9#pragma once
10
12
13namespace peclet::flow::bindings {
14
17template <class Grid, class C>
18inline void bindSolverGeometry(C& cls) {
19 using S = BoundSolver<Grid>;
20 cls.def(
21 "set_domain_bc",
22 [](S& s, const std::string& face, const std::string& type, std::array<double, 3> velocity) {
23 chk::finiteEach("set_domain_bc", "velocity", velocity, "length/time");
24 s.setDomainBc(face_index(face, "set_domain_bc"),
25 enum_index(type, kBcTypes, "set_domain_bc", "type"), velocity[0], velocity[1],
26 velocity[2]);
27 },
28 nb::arg("face"), nb::arg("type"), nb::arg("velocity") = std::array<double, 3>{0.0, 0.0, 0.0},
29 "Set a per-face domain BC. `face` is one of '-x', '+x', '-y', '+y', '-z', '+z'; `type` "
30 "is 'periodic' (the default on every face), 'wall' (no-slip), 'inflow' (Dirichlet "
31 "`velocity` -- an inlet, or a lid with a tangential velocity), 'outflow' "
32 "(zero-gradient velocity, p = 0) or 'slip' (free-slip / symmetry plane: zero normal "
33 "velocity, zero normal derivative of the tangential components, pressure Neumann like a "
34 "wall; `velocity` is ignored). The TYPE must be set BEFORE the geometry (set_solid / "
35 "set_pressure_geometry / set_solid_from_scene): it is folded into the operators when "
36 "the geometry is built, and a call that would CHANGE it raises afterwards. A VALUE "
37 "update on a face whose type is unchanged (ramping an inflow jet, a lid's tangential "
38 "speed) is allowed at any time and takes effect the next step. A half-domain closed by "
39 "a 'slip' face reproduces the full symmetric domain pointwise "
40 "(tests/kokkos/test_freeslip). Both grids (Solver and SolverColocated). "
41 "`velocity` is in the caller's units (length/time).");
42 cls.def(
43 "set_domain_bc_profile",
44 [](S& s, const std::string& face, nb::ndarray<double, nb::c_contig> prof) {
45 if (prof.ndim() != 3 || prof.shape(2) != 3)
46 throw std::runtime_error("profile must be (Nb,Nc,3)");
47 const int nb_ = (int)prof.shape(0), nc = (int)prof.shape(1);
48 s.setDomainBcProfile(face_index(face, "set_domain_bc_profile"),
49 peclet::core::python::ndarray_to_vector<double>(nb::ndarray<>(prof)),
50 nb_, nc);
51 },
52 nb::arg("face"), nb::arg("profile"),
53 "Prescribe a per-position inlet velocity profile (Nb,Nc,3) over a face (one of '-x', "
54 "'+x', '-y', '+y', '-z', '+z'; sets it to 'inflow'). Like set_domain_bc, the TYPE (making "
55 "a face inflow for the first time) must be set BEFORE the geometry; updating the "
56 "profile on a face that is ALREADY inflow is allowed after the geometry.");
57 cls.def(
58 "set_pressure_geometry",
59 [](S& s, nb::ndarray<double, nb::f_contig> sdf) { s.setPressureGeometry(grid_in(sdf)); },
60 nb::arg("sdf"),
61 "Set an all-fluid SDF for the cut-cell pressure operator without an immersed solid (the "
62 "channel/BFS domain-BC path). For a no-slip immersed BODY in an inflow/outflow domain, "
63 "call "
64 "set_solid(sdf, cutcell_pressure=True) instead -- do NOT also call this (a second "
65 "geometry "
66 "setter overwrites the SDF and wipes the solid).");
67 cls.def(
68 "set_scene",
69 [](S& s, nb::ndarray<int, nb::c_contig> ni, nb::ndarray<double, nb::c_contig> nr,
70 nb::ndarray<int, nb::c_contig> ii, nb::ndarray<double, nb::c_contig> ir, bool periodic) {
71 s.setScene(std::vector<int>(ni.data(), ni.data() + ni.size()),
72 std::vector<double>(nr.data(), nr.data() + nr.size()),
73 std::vector<int>(ii.data(), ii.data() + ii.size()),
74 std::vector<double>(ir.data(), ir.data() + ir.size()), periodic);
75 },
76 nb::arg("node_ints"), nb::arg("node_reals"), nb::arg("instance_ints"),
77 nb::arg("instance_reals"), nb::arg("periodic") = false,
78 "Install an analytic geometry scene from core's flat encoding (3 ints + 16 reals per "
79 "node, 2 ints + 18 reals per instance -- reals[17] is the centre-pinned flag; legacy 17-real "
80 "records are accepted, reading an all-zero centre as 'follows the body'). Coordinates are "
81 "the caller's own PHYSICAL ones when the solver was given an extent -- so ONE scene "
82 "serves flow, dem and voro unchanged -- and CELL UNITS on the global inner grid "
83 "otherwise (cell (i,j,k)'s centre at (i,j,k) -- half a cell from cell_centers(), which "
84 "returns i + 1/2 in cell units). The scene is replicated on every rank, so scene-derived "
85 "geometry needs no "
86 "communication and -- unlike diagnostics.set_exact_crossings -- is NOT single-rank only. "
87 "periodic=True treats the scene as min-image periodic over the global grid (one "
88 "instance per body, no images); periodic=False leaves images to the caller.");
89 cls.def("set_solid_from_scene", &S::setSolidFromScene, nb::arg("cutcell_pressure") = true,
90 "Sample the installed scene onto this rank's inner grid and install it as the solid, "
91 "entirely on device (no nx*ny*nz float64 host round trip). "
92 "The scene's coordinates are physical (the caller's length units) under an extent.");
93 cls.def("has_scene", &S::hasScene,
94 "True once set_scene has installed an analytic CSG scene on this solver. False for "
95 "geometry set any other way (set_solid with a sampled SDF, set_pressure_geometry), and "
96 "false again if no scene has been given yet. set_solid_from_scene and the "
97 "scene-derived per-body hydrodynamic force/motion bookkeeping all require this to be "
98 "True first.");
99 cls.def(
100 "set_instance_motion",
101 [](S& s, int i, std::array<double, 3> lin, std::array<double, 3> ang,
102 std::optional<std::array<double, 3>> center) {
103 chk::instanceMotion(lin, ang, center);
104 s.setInstanceMotion(i, lin, ang, center ? center->data() : nullptr);
105 },
106 nb::arg("instance"), nb::arg("lin_vel") = std::array<double, 3>{0.0, 0.0, 0.0},
107 nb::arg("ang_vel") = std::array<double, 3>{0.0, 0.0, 0.0}, nb::arg("center") = nb::none(),
108 "Rigid-body motion of one scene instance, in the scene's own coordinates per time (the "
109 "caller's physical length with an extent, CELLS without one; the angular velocity is "
110 "1/time either way). Any nonzero component switches the solver onto the moving-geometry "
111 "path: the momentum operator's no-slip datum becomes the local wall velocity and the "
112 "cut-cell projection gains the wall's own volume flux. All-zero keeps the static path, "
113 "bit for bit. Staggered grid only in v1 (no ghost projection / porous / variable rho).");
114 cls.def("has_moving_instance", &S::hasMovingInstance,
115 "True when at least one scene instance carries a nonzero velocity.");
116 cls.def("num_scene_instances", &S::sceneInstanceCount,
117 "Number of instances in the scene set by set_scene (0 before it). Instance indices "
118 "run 0..num_scene_instances()-1 in set_instance_transform / set_instance_motion, "
119 "scene_owner() and the hydrodynamic force/torque accessors.");
120 cls.def(
121 "set_instance_transform",
122 [](S& s, int i, std::array<double, 3> t, std::array<double, 4> q) {
123 chk::instanceTransform(t, q);
124 s.setInstanceTransform(i, t, q);
125 },
126 nb::arg("instance"), nb::arg("translation"),
127 nb::arg("quat") = std::array<double, 4>{0.0, 0.0, 0.0, 1.0},
128 "Move one scene instance (quat as (x,y,z,w)). Takes effect at the next "
129 "rebuild_geometry(): the SDF, the cut-cell overlay, the apertures and the pressure "
130 "operator are all derived from the transforms, so moving one without rebuilding would "
131 "run the solver on stale geometry.");
132 cls.def("refresh_wall_velocity", &S::refreshWallVelocity,
133 "Re-derive ONLY the wall-velocity fields and the momentum operator that folds them in, "
134 "for a driver that changes an instance's VELOCITY every step while its transform stays "
135 "put -- the linearised oscillating body, a shear cell driven by counter-moving plates. "
136 "set_instance_motion alone does not reach those fields (they are built in "
137 "set_solid_from_scene), so the alternative is a full rebuild_geometry() per step to "
138 "update a boundary condition. Refuses if a transform has changed since the last "
139 "geometry build, because it does NOT re-sample the SDF, the apertures, the ownership "
140 "field or the pressure operator. Velocity and pressure are untouched. "
141 "Velocities stay in the caller's units (set_instance_motion).");
142 cls.def("rebuild_geometry", &S::rebuildGeometry,
143 "Re-derive all geometry from the current instance transforms. Velocity and pressure are "
144 "PRESERVED across the rebuild (set_solid zeroes them by design). Full rebuild: the "
145 "measured cost is ~65% momentum/IBM stencils, ~35% pressure/MG, scene sampling in the "
146 "noise. Cells uncovered by the motion inherit zero, not an extrapolated fluid value.");
147 cls.def(
148 "hydro_force_torque_reaction",
149 [](S& s) {
150 std::vector<double> v = s.hydroForceTorqueReaction();
151 const std::size_t n = v.size() / 6;
152 return peclet::core::python::vector_to_ndarray(std::move(v), {2, n, 3},
153 {static_cast<std::int64_t>(3 * n), 3, 1});
154 },
155 "THE hydrodynamic force and torque on each scene instance: the DISCRETE REACTION -- "
156 "the momentum the fluid actually lost to each body, assembled from the composed step's "
157 "budget (time term, body force, and the viscous fluxes at u*; the pressure telescopes "
158 "inside each owner region and needs no field). Shape (2, n_instances, 3): [0] force, "
159 "[1] torque about the instance centre. The force is exactly conservative (sum = f * "
160 "V_fluid at steady state, to the solver residual) and as accurate as the flow solution "
161 "it sustains: Zick & Homsy's drag within 0.7 % at N = 24 (tests/python/"
162 "test_hydro_force_units.py). The torque carries the closed-form transposed-stress wall "
163 "term; measured 2026-09-30 on a steadily spinning sphere it reads 1.019-1.027 of "
164 "8 pi mu a^3 Omega / (1 - phi) at R/h 6-12 (over-reads ~2 %, falling with "
165 "resolution), and on a translating sphere whose true torque is zero it is zero to "
166 "1e-15 on a symmetric placement and |T| / (|F| R) = 5e-5 to 1e-3 off it. "
167 "diagnostics.hydro_force_torque_traction() is the surface-traction estimate: ~30 % "
168 "low, but it carries the pressure/viscous split. Staggered only; EXPLICIT advection "
169 "is carried (the stashed advective RHS term is subtracted); implicit advection / "
170 "porous / variable properties / domain BCs are refused loudly (v2); call after "
171 "step(). Atomics: tolerance-reproducible, not bitwise.");
172 cls.def(
173 "hydro_force_torque",
174 [](S& s) {
175 // Warns from the first release that carries the canonical names, not one release
176 // later as docs/NAMING.md section 0 has it for a respelling: the old spelling here
177 // is not harmless, it hands out a force ~30 % low under the natural name.
178 if (PyErr_WarnEx(PyExc_DeprecationWarning,
179 "hydro_force_torque() is deprecated: it returns the traction "
180 "integral, which under-reads the drag by ~30 % at any resolution. "
181 "For the force and torque on the bodies call "
182 "hydro_force_torque_reaction(); for the traction and its "
183 "pressure/viscous split, diagnostics.hydro_force_torque_traction().",
184 1) < 0)
185 throw nb::python_error();
187 },
188 "DEPRECATED (warns) -- the canonical names are hydro_force_torque_reaction() for the "
189 "force and "
190 "torque on the bodies, and diagnostics.hydro_force_torque_traction() for what this "
191 "returns. It is NOT the force on the bodies: it is the reconstructed surface-traction "
192 "integral, which under-reads the drag by ~30 % at any resolution (the viscous part; "
193 "traction / reaction 0.685-0.730 over phi 0.008-0.45, N 24-128). Returns exactly what "
194 "diagnostics.hydro_force_torque_traction() returns (shape (4, n_instances, 3): force, "
195 "torque, pressure part, viscous part); see that method for the details. Where the "
196 "reaction refuses (SolverColocated, porous, variable properties, domain BCs, implicit "
197 "advection) the traction is the only estimate there is -- call it by its diagnostic "
198 "name and allow for the under-read. Kept working under the suite's rule for a shipped "
199 "name (docs/NAMING.md section 0); removal needs a major release. "
200 "Force and torque come back in the caller's (physical) units.");
201 cls.def("instance_center", &S::instanceCenter, nb::arg("i"),
202 "The resolved centre of rotation of instance i (world coordinates). "
203 "In the caller's length units.");
204 cls.def(
205 "set_solid",
206 [](S& s, nb::ndarray<double, nb::f_contig> sdf, bool cutcell_pressure) {
207 s.setSolid(grid_in(sdf), cutcell_pressure);
208 },
209 nb::arg("sdf"), nb::arg("cutcell_pressure") = false,
210 "Set the solid SDF as a Fortran-order (nx,ny,nz) float64 array sampled at cell_centers() "
211 "(negative inside the solid, positive in fluid, in the solver's length unit). "
212 "cutcell_pressure=True enables the open-face-weighted cut-cell pressure operator "
213 "(proper no-slip); it composes with domain BCs, so this is the single call for a "
214 "no-slip immersed body in an inflow/outflow domain. The multigrid coarse operators are "
215 "always the rediscretized per-level cut-cell operators (the former `pressure_coarse=` "
216 "mode selector is gone).");
217}
218
221template <class Grid, class C>
222inline void bindDiagnosticsGeometry(C& cls) {
223 using D = Diagnostics<Grid>;
224 cls.def(
225 "set_exact_crossings_from_scene",
226 [](D& diag) { return diag.s->setExactCrossingsFromScene(); },
227 "Compute EXACT wall crossings from the installed scene, on device, on every rank -- the "
228 "in-solver replacement for set_exact_crossings + scripts/exact_apertures_spheres.py. "
229 "Bisection, not Newton: only SIGN correctness is guaranteed for bound-only leaves.");
230 cls.def(
231 "set_wall_flux_divergence",
232 [](D& diag, bool on) { return diag.s->setWallFluxDivergence(on); }, nb::arg("on"),
233 "Rung 3 on/off (default on = correct physics). Off leaves the moving wall's no-slip "
234 "datum in the momentum operator but drops the wall's own volume flux from the cut-cell "
235 "projection -- the configuration the Galilean gate uses to exhibit the failure the term "
236 "fixes.");
237 cls.def(
238 "set_fresh_cell_seed", [](D& diag, bool on) { return diag.s->setFreshCellSeed(on); },
239 nb::arg("on"),
240 "Fresh-cell policy for MOVING geometry. A point a body has just uncovered inherits "
241 "whatever the solid held there -- zero, or a stale masked value -- which is one of the "
242 "two textbook mechanisms behind spurious force oscillations in a moving-boundary IBM. "
243 "True seeds it with the LOCAL WALL VELOCITY instead, so it starts moving with the "
244 "surface that released it. Bounded (no extrapolation), no new field, and exactly the "
245 "old behaviour when nothing moves. DEFAULT TRUE since 2026-08-30: measured on an "
246 "oscillating sphere translating through the grid, it removes a resolution-INDEPENDENT "
247 "+2.6..2.9% drag bias, cuts the spurious force oscillation 20-50x to within 17% of the "
248 "non-moving floor, and improves the resolved CFD-DEM loop's total-momentum "
249 "conservation 95x. Pass False for the pre-2026-08-30 behaviour.");
250 cls.def(
251 "fluid_momentum_cells",
252 [](D& diag) {
253 const auto n = diag.s->fluidMomentumCells();
254 return std::array<long, 3>{n[0], n[1], n[2]};
255 },
256 "Unmasked (fluid) staggered momentum cells per component -- the exact discrete datum of "
257 "the reaction identity: at steady state, sum over bodies of F_c = f_c * N_c.");
258 cls.def(
259 "reaction_budget_terms",
260 [](D& diag) {
261 std::vector<double> v = diag.s->reactionBudgetTerms();
262 return peclet::core::python::vector_to_ndarray(std::move(v), {2, std::size_t(3)}, {3, 1});
263 },
264 "Diagnostic decomposition of the reaction identity, shape (2, 3): [0] the unsteady sum "
265 "sum_i (rho/dt)(u_i - u^n_i) and [1] the advective sum sum_i A_i, both over the FLUID "
266 "momentum cells of each component. The full discrete identity is sum_bodies F_c = "
267 "f_c*N_c + sum fb + [1]_c - [0]_c; the Stokes form drops both because they vanish at "
268 "steady state with advection off. sum_i A_i is the advection operator's net momentum "
269 "flux through the cut walls -- an O(h) property of that operator, not of the budget.");
270 cls.def(
271 "moving_instance_cut_cells",
272 [](D& diag) {
273 std::vector<long> v = diag.s->movingInstanceCutCells();
274 std::vector<double> d(v.begin(), v.end());
275 return peclet::core::python::vector_to_ndarray(std::move(d), {v.size()}, {1});
276 },
277 "Per instance: inner cells on this rank it owns that touch a fractional face aperture, "
278 "recounted whenever any instance moves. ZERO for a moving instance means its surface "
279 "sits on grid planes (or is sub-cell) and its wall velocity is silently inert "
280 "(set_solid_from_scene warns). Empty when no instance moves.");
281 cls.def(
282 "moving_instance_degenerate_points",
283 [](D& diag) {
284 std::vector<long> v = diag.s->movingInstanceDegeneratePoints();
285 std::vector<double> d(v.begin(), v.end());
286 return peclet::core::python::vector_to_ndarray(std::move(d), {v.size()}, {1});
287 },
288 "Per instance: staggered velocity points where the sampled SDF is EXACTLY zero -- a face "
289 "on a lattice plane. Those points are fluid to the mask and not ghosts to the cut-cell "
290 "fold, so a moving body's datum never enters there (set_solid_from_scene warns). Empty "
291 "when no instance moves.");
292 cls.def(
293 "instance_center_pinned", [](D& diag, int i) { return diag.s->instanceCenterPinned(i); },
294 nb::arg("i"),
295 "True if instance i's centre of rotation is PINNED (an explicit finite centre in the "
296 "encoding, or set_instance_motion(center=...)); False if it follows the body's "
297 "translation (NaN in the encoding, the builder's default; legacy all-zero raw arrays).");
298 cls.def(
299 "periodic_image_overlap_cells", [](D& diag) { return diag.s->periodicImageOverlapCells(); },
300 "Cells on this rank whose solid/fluid sign was decided by a periodic IMAGE of an "
301 "instance wider than the box (set_solid_from_scene warns when nonzero): the scene "
302 "evaluates the UNION of images, so a slab wider than the box refills any cavity carved "
303 "from it. 0 when no instance is that wide or the images agree.");
304 cls.def(
305 "hydro_force_torque_traction",
306 [](D& diag) { return traction_force_torque_array<Grid>(*diag.s); },
307 "DIAGNOSTIC -- not the force on the bodies; that is "
308 "Solver.hydro_force_torque_reaction(). The reconstructed surface-TRACTION loads, shape "
309 "(4, n_instances, 3): [0] force, [1] torque about the instance centre, [2] the pressure "
310 "part, [3] the viscous part ([0] == [2] + [3]). The cut-cell surface integral of "
311 "(-p I + mu(grad u + grad u^T)) against the exact aperture wall-area vector, with a "
312 "central-difference velocity gradient that spans the wall. It UNDER-READS THE VISCOUS "
313 "PART: traction / reaction drag = 0.685-0.730 over phi 0.008-0.45 and N 24-128 "
314 "(measured 2026-09-30), i.e. ~30 % low at ANY resolution -- refinement does not fix "
315 "it. The torque is low by the same mechanism: a steadily spinning sphere reads "
316 "0.59-0.72 of 8 pi mu a^3 Omega / (1 - phi) at R/h 6-12 (the reaction: 1.019-1.027). "
317 "What it offers that the reaction does not: the pressure/viscous split, and it runs "
318 "where the reaction refuses (the collocated solver, porous, variable properties, domain "
319 "BCs, implicit advection). A consistent traction (from the momentum operator's "
320 "small-cell-robust wall reconstruction) is planned. Was Solver.hydro_force_torque() "
321 "(deprecated). Atomics: tolerance-reproducible, not bitwise.");
322 cls.def(
323 "wall_area_probe", [](D& diag) { return diag.s->wallAreaProbe(); },
324 "Diagnostic: [sum_c x_c*A_wall_x, sum_c y_c*A_wall_y, sum_c z_c*A_wall_z] over all cut "
325 "cells. Must equal -V_solid componentwise if the aperture wall-area vectors are right, "
326 "so it separates a force-integral error in the GEOMETRY from one in the traction.");
327 cls.def(
328 "wall_flux_imbalance", [](D& diag) { return diag.s->wallFluxImbalance(); },
329 "Sum over cells of u_wall . A_wall -- the compatibility datum of the singular pressure "
330 "problem. Exactly zero for a translating body in a periodic box; small but nonzero for "
331 "rotation. Reported, not corrected.");
332 cls.def(
333 "get_cut_owner",
334 [](D& diag) {
335 std::vector<int> v = diag.s->getCutOwner();
336 const auto nx = static_cast<std::size_t>(diag.s->nx());
337 const auto ny = static_cast<std::size_t>(diag.s->ny());
338 const auto nz = static_cast<std::size_t>(diag.s->nz());
339 return peclet::core::python::vector_to_ndarray(
340 std::move(v), {nx, ny, nz},
341 {1, static_cast<std::int64_t>(nx), static_cast<std::int64_t>(nx * ny)});
342 },
343 "Per-inner-cell owning scene instance (the argmin behind the sampled SDF), (nx,ny,nz) "
344 "int32; -1 before set_solid_from_scene. Moving geometry reads its wall velocity off the "
345 "owner and resolved CFD-DEM posts the hydrodynamic force back to it.");
346 cls.def(
347 "field_view",
348 [](D& diag, const std::string& name) {
349 return field3d_out(*diag.s, diag.s->fieldView(name));
350 },
351 nb::arg("name"),
352 "Zero-copy view of a registered field's full padded buffer as a Fortran-order "
353 "(nx+2g, ny+2g, nz+2g) array (g = ghost_width); host → NumPy, device → DLPack (CuPy). "
354 "step() does not device-synchronize at entry: a driver that writes a view from its own "
355 "non-blocking stream (cupy/torch) must synchronize that stream before calling step() "
356 "(null-stream writers stay ordered).");
357 cls.def(
358 "exchange_field", [](D& diag, const std::string& name) { diag.s->exchangeField(name); },
359 nb::arg("name"),
360 "Fill a registered field's ghost cells (cross-rank + periodic under MPI; periodic "
361 "single-rank).");
362 cls.def(
363 "exchange_field_add",
364 [](D& diag, const std::string& name) { diag.s->exchangeFieldAdd(name); }, nb::arg("name"),
365 "Add-reduce halo: fold ghost-layer deposits back onto their owner (cross-rank + "
366 "periodic). "
367 "The particle->grid deposition primitive for MPI CFD-DEM; single-rank non-periodic "
368 "no-op.");
369}
370
371} // namespace peclet::flow::bindings
Shared helpers of the peclet.flow Python binding: array conversion, the string-enum tables,...
int face_index(const std::string &f, const char *who)
int enum_index(const std::string &v, const std::vector< std::string > &names, const char *who, const char *what)
const std::vector< std::string > kBcTypes
auto field3d_out(S &s, peclet::flow::CCField f)
void bindSolverGeometry(C &cls)
Solver (and its collocated twin): domain BCs, pressure geometry, scenes, instances,...
std::vector< double > grid_in(nb::ndarray< double, nb::f_contig > a)
void bindDiagnosticsGeometry(C &cls)
SolverDiagnostics (and its collocated twin): cut-cell and moving-instance instruments,...
auto traction_force_torque_array(peclet::flow::Solver< Grid > &s)
The reconstructed-traction loads as the (4, n_instances, 3) array that both of its Python names retur...
Definition prof.py:1
The developer tier: a view onto one Solver<Grid> (no state of its own).