peclet-dem 1.1.0
Performance-portable XPBD Discrete Element Method (Kokkos + ArborX)
Loading...
Searching...
No Matches
dem_bindings.cpp
Go to the documentation of this file.
1
26#include <nanobind/nanobind.h>
27#include <nanobind/ndarray.h>
28#include <nanobind/stl/array.h>
29#include <nanobind/stl/optional.h>
30#include <nanobind/stl/pair.h>
31#include <nanobind/stl/string.h>
32#include <nanobind/stl/tuple.h>
33#include <nanobind/stl/vector.h>
34
35#include <array>
36#include <cmath>
37#include <cstdint>
38#include <cstdio>
39#include <Kokkos_Core.hpp>
40#include <optional>
41#include <stdexcept>
42#include <string>
43#include <tuple>
44#include <vector>
45
46#ifdef PECLET_DEM_MPI
47#include <mpi.h>
48#endif
49
51#include "peclet/core/python/kokkos_teardown.hpp"
52#include "peclet/core/python/ndarray_interop.hpp"
53#include "sim.hpp"
54
55namespace nb = nanobind;
57
58namespace {
59
60// Input validation: peclet::dem::binding_checks (dem_bindings_checks.hpp).
61using namespace peclet::dem::binding_checks;
62
63peclet::dem::F3 f3(const F3Arg& a) {
64 return peclet::dem::F3{a[0], a[1], a[2]};
65}
66
70using Grid3 = nb::ndarray<float, nb::ndim<3>, nb::f_contig>;
71
72// A contiguous numpy array -> flat C-order host vector (the bridge handles host copy / device
73// wrap).
74std::vector<float> to_vec(nb::ndarray<float, nb::c_contig> a) {
75 return peclet::core::python::ndarray_to_vector<float>(nb::ndarray<>(a));
76}
77std::vector<float> grid_to_vec(Grid3 g) {
78 return peclet::core::python::ndarray_to_vector<float>(nb::ndarray<>(g));
79}
80
84std::vector<float> rows_of(nb::ndarray<float, nb::c_contig> a, int cols, const Simulation& s,
85 const char* who) {
86 if (a.ndim() != 2 || static_cast<int>(a.shape(1)) != cols)
87 throw std::invalid_argument(std::string(who) + ": expected an (N, " + std::to_string(cols) +
88 ") array");
89 if (static_cast<int>(a.shape(0)) != s.numParticles())
90 throw std::invalid_argument(std::string(who) + ": " + std::to_string(a.shape(0)) +
91 " rows but num_particles = " + std::to_string(s.numParticles()) +
92 " (set_positions sizes the particle set; call it first)");
93 return to_vec(a);
94}
95std::vector<float> flat_of(nb::ndarray<float, nb::c_contig> a, const Simulation& s,
96 const char* who) {
97 if (a.ndim() != 1)
98 throw std::invalid_argument(std::string(who) + ": expected an (N,) array");
99 if (static_cast<int>(a.shape(0)) != s.numParticles())
100 throw std::invalid_argument(std::string(who) + ": " + std::to_string(a.shape(0)) +
101 " entries but num_particles = " + std::to_string(s.numParticles()) +
102 " (set_positions sizes the particle set; call it first)");
103 return to_vec(a);
104}
105
106// A flat C-order vector -> (N,cols) numpy array, moved into the array's backing store (no extra
107// copy).
108nb::ndarray<nb::numpy, float> rows(std::vector<float>&& v, int cols) {
109 const std::size_t n = v.size() / static_cast<std::size_t>(cols);
110 return peclet::core::python::vector_to_ndarray(std::move(v), {n, (std::size_t)cols},
111 {(std::int64_t)cols, 1});
112}
113nb::ndarray<nb::numpy, float> flat(std::vector<float>&& v) {
114 const std::size_t n = v.size();
115 return peclet::core::python::vector_to_ndarray(std::move(v), {n}, {1});
116}
117
119int shape_kind(const std::string& name, const char* who) {
120 if (name == "sphere")
121 return peclet::dem::SPHERE;
122 if (name == "hollow_cylinder")
124 if (name == "box")
125 return peclet::dem::BOX;
126 throw std::invalid_argument(
127 std::string(who) + ": expected 'sphere', 'hollow_cylinder' or 'box', got '" + name + "'");
128}
129
132struct Diagnostics {
133 Simulation* s;
134};
135
136} // namespace
137
138NB_MODULE(_dem, m) {
139 m.attr("__doc__") = "peclet.dem (Kokkos + ArborX): performance-portable XPBD granular dynamics";
140
141 // Kokkos init + the release-then-finalize atexit hook + finalize() + execution_space: the
142 // suite-wide pattern (file comment; peclet/core/python/kokkos_teardown.hpp). Simulation's own
143 // registry (sim.hpp) is released through a hook; the get_*_view capsules register themselves.
144 peclet::core::python::add_release_hook(&Simulation::releaseAll);
145 peclet::core::python::install(m);
146
147 nb::class_<Diagnostics>(
148 m, "Diagnostics",
149 "Developer tier of a Simulation, reached as `sim.diagnostics`: instruments, ablations and "
150 "execution-policy switches. Nothing here is needed to set up, run or read out a "
151 "simulation; the setters that CHANGE RESULTS say so in their docstring.")
152 .def(
153 "set_stabilization",
154 [](Diagnostics& d, const std::string& mode) { d.s->setStabilizationMode(mode); },
155 nb::arg("mode"),
156 "The full stabilization mode set: the three production modes of "
157 "Simulation.set_stabilization plus the two measurement modes -- 'escalate' (extra "
158 "symmetric sweeps up to 256; diagnostic/fallback) and 'ordered' (level-ordered symmetric "
159 "sweeps; known insufficient for deep columns).")
160 .def(
161 "set_velocity_solver",
162 [](Diagnostics& d, const std::string& name) {
163 if (name == "gauss_seidel")
164 d.s->setVelocityUseGS(true);
165 else if (name == "jacobi")
166 d.s->setVelocityUseGS(false);
167 else
168 throw std::invalid_argument(
169 "set_velocity_solver: expected 'gauss_seidel' or 'jacobi', got '" + name + "'");
170 },
171 nb::arg("name"),
172 "A/B switch of the collision solves: 'gauss_seidel' (default; colored Gauss-Seidel, "
173 "correct multi-contact dissipation) or 'jacobi' (mass-split Jacobi: every contact is "
174 "its own copy, solved against masses m/count, true-mass deltas summed -- conservative, "
175 "and at a fixed iteration budget more dissipative than Gauss-Seidel). CHANGES RESULTS.")
176 .def_prop_ro(
177 "velocity_solver",
178 [](Diagnostics& d) {
179 return std::string(d.s->velocityUseGS() ? "gauss_seidel" : "jacobi");
180 },
181 "'gauss_seidel' or 'jacobi'.")
182 .def(
183 "set_cuda_graphs", [](Diagnostics& d, bool on) { d.s->setCudaGraphs(on); },
184 nb::arg("enabled"),
185 "CUDA-graph replay of the solver's iteration loops (default True): capture collapses "
186 "each iteration's launch storm into one replay. Results are bit-identical either way; "
187 "inert on non-CUDA backends and on the distributed step.")
188 .def_prop_ro(
189 "cuda_graphs", [](Diagnostics& d) { return d.s->cudaGraphs(); },
190 "Whether CUDA-graph replay of the solver loops is enabled.")
191 .def(
192 "set_fused_sweeps",
193 [](Diagnostics& d, const std::string& mode) { d.s->setFusedSweeps(mode); },
194 nb::arg("mode"),
195 "Fused color sweeps (CUDA): a whole sweep -- and where eligible the whole adaptive "
196 "iteration loop -- as ONE kernel behind software grid barriers. 'auto' (default) uses "
197 "them exactly where graph replay is unavailable (the distributed step, or "
198 "set_cuda_graphs(False)); 'on'/'off' force. Bit-identical results either way.")
199 .def_prop_ro(
200 "fused_sweeps", [](Diagnostics& d) { return d.s->fusedSweeps(); },
201 "Fused-sweep policy: 'auto', 'on' or 'off'.")
202 .def(
203 "coloring_conflicts", [](Diagnostics& d) { return d.s->debugColoringConflicts(); },
204 "(velocity, position) graph-coloring-invariant violations in the last substep; a valid "
205 "coloring returns (0, 0). Test hook for the incremental warm-start path.")
206 .def(
207 "coloring_leftovers", [](Diagnostics& d) { return d.s->debugColoringLeftovers(); },
208 "(velocity, position) edges -- manifolds, position units -- the last substep's "
209 "colourings left uncoloured (single-rank). Non-zero means a colouring exhausted its "
210 "arbitration rounds or palette.")
211 .def(
212 "multilevel_coloring_conflicts",
213 [](Diagnostics& d) { return d.s->debugMultilevelColoringConflicts(); },
214 "Same-colour pairs at an aggregate of the last multilevel hierarchy, summed over its "
215 "levels; a valid coarse colouring returns 0 (0 also when no hierarchy was built).")
216 .def(
217 "split_stats",
218 [](Diagnostics& d) {
219 const auto st = d.s->debugSplitStats();
220 nb::dict r;
221 r["vel_hub_copies"] = st.velHubCopies;
222 r["pos_hub_copies"] = st.posHubCopies;
223 r["light_hubs"] = st.lightHubs;
224 r["split_bodies_vel"] = st.splitBodiesVel;
225 r["split_bodies_pos"] = st.splitBodiesPos;
226 r["unfired_split_contacts"] = st.unfiredSplitContacts;
227 r["drift_migrations"] = st.driftMigrations;
228 r["ml_hub_aggregated"] = st.mlHubAggregated;
229 r["vel_iters_used"] = st.velItersUsed;
230 r["pos_iters_used"] = st.posItersUsed;
231 r["orphan_clamps"] = st.orphanClamps;
232 return r;
233 },
234 "Dict of the last substep's body copies (docs/contact_solve_framework.md §4.4): hub "
235 "copy slots per phase, light hubs (hub mass < 10x its partners' mean), bodies solved "
236 "through more than one slot per phase (hubs; periodic images in the single-rank "
237 "position phase), and (0 until implemented) unfired split contacts and drift "
238 "migrations; ml_hub_aggregated: split velocity vertices in a multi-member level-1 "
239 "multilevel group (max over the last step call's substeps); vel_iters_used / "
240 "pos_iters_used: iterations of the last substep's main velocity and position loops "
241 "(-1: a device-side loop, whose count is read back only with the C++ diagnostics "
242 "switch debugIterationCounters); orphan_clamps: clamp hits of the distributed Poisson "
243 "orphan balance over the last step_mpi call (must stay 0).")
244 .def(
245 "rest_orphan_stats", [](Diagnostics& d) { return d.s->restOrphanStats(); },
246 "Poisson-restitution instrument: (sum, max, n_bodies>0) of the per-body orphaned event "
247 "budget (physical impulse units).")
248 .def(
249 "rest_bank_stats", [](Diagnostics& d) { return d.s->restBankStats(); },
250 "Poisson-restitution instrument: (sum, max, n_pairs>0) of the per-pair owed separation "
251 "impulse committed last substep (physical impulse units).")
252 .def(
253 "wall_sdf_at",
254 [](Diagnostics& d, int wall_index, nb::ndarray<float, nb::c_contig> pts) {
255 if (pts.ndim() != 2 || pts.shape(1) != 3)
256 throw std::invalid_argument("wall_sdf_at: points must be an (M, 3) array");
257 return flat(d.s->wallSdfAt(wall_index, to_vec(pts)));
258 },
259 nb::arg("wall_index"), nb::arg("points"),
260 "The wall's signed distance at world points: (M,3) in -> (M,) out, POSITIVE in the void "
261 "where the grains live -- exactly what the narrow phase reads, so it is the honest check "
262 "of a set_wall_transform placement and the way to draw a stirrer.")
263 .def(
264 "profiling_info",
265 [](Diagnostics& d) {
266 nb::dict r;
267 r["num_particles"] = d.s->numParticles();
268 r["num_contacts"] = d.s->numContacts();
269 r["num_manifolds"] = d.s->numManifolds();
270 r["max_overlap"] = d.s->maxOverlap();
271 return r;
272 },
273 "Dict of the particle / broad-phase pair / manifold counts and the last-step max "
274 "overlap (the same four values the Simulation properties carry).")
275#ifdef PECLET_DEM_MPI
276 .def_prop_ro(
277 "mpi_rebuilds", [](Diagnostics& d) { return d.s->mpiRebuilds(); },
278 "Cumulative halo topology-rebuild count (Verlet-skin path); with mpi_gathers this is "
279 "the ghost-reuse ratio.")
280 .def_prop_ro(
281 "mpi_gathers", [](Diagnostics& d) { return d.s->mpiGathers(); },
282 "Cumulative ghost gather() count across distributed steps.")
283#endif
284 ;
285
286 nb::class_<Simulation>(
287 m, "Simulation",
288 "One granular-dynamics simulation (XPBD impulse engine + explicit Hertz-Mindlin engine, "
289 "the same particle set). Set up shapes -> domain -> positions -> materials, `set_dt`, then "
290 "`step(n)`; read out with the `get_*` arrays. Developer instruments live on "
291 "`.diagnostics`. Units: any consistent set chosen by the caller (SI or not); each "
292 "docstring states the dimension of its quantities.")
293 .def(
294 "__init__",
295 [](Simulation* self, int capacity) {
296 count("Simulation", "capacity", capacity, 0);
297 new (self) Simulation(capacity);
298 },
299 nb::arg("capacity"),
300 "Allocate for up to `capacity` particles (owned + periodic ghost slots); set_positions "
301 "refuses more.")
302 .def_prop_ro("capacity", &Simulation::capacity, "The particle capacity this was built with.")
303 .def_prop_ro(
304 "diagnostics", [](Simulation& s) { return Diagnostics{&s}; }, nb::keep_alive<0, 1>(),
305 "The developer tier (Diagnostics) of this simulation.")
306 // ---- shapes -------------------------------------------------------------------------
307 .def(
308 "initialize_shape",
309 [](Simulation& s, const std::string& shape, float radius, float height, float thickness) {
310 positive("initialize_shape", "radius", radius, "length");
311 nonneg("initialize_shape", "height", height, "length");
312 nonneg("initialize_shape", "thickness", thickness, "length");
313 s.initializeShape(shape_kind(shape, "initialize_shape"), radius, height, thickness);
314 },
315 nb::arg("shape"), nb::arg("radius"), nb::arg("height") = 0.0f,
316 nb::arg("thickness") = 0.0f,
317 "Select the single particle shape and its dimensions: 'sphere' (radius), "
318 "'hollow_cylinder' (radius, height, thickness) or 'box' (half-extent = radius), all in "
319 "length units. RESETS "
320 "the shape registry to this one shape (use add_shape for a mixture) and records the "
321 "unit-mass inverse inertia that set_positions applies to every particle -- so call it "
322 "BEFORE set_positions.")
323 .def(
324 "set_sdf_shape",
325 [](Simulation& s, Grid3 grid, F3Arg origin, F3Arg spacing,
326 nb::ndarray<float, nb::c_contig> shell, F3Arg inv_inertia, float bounding_radius) {
327 sdfShapeArgs("set_sdf_shape", origin, spacing, inv_inertia, bounding_radius);
328 const int nx = (int)grid.shape(0), ny = (int)grid.shape(1), nz = (int)grid.shape(2);
329 s.setSdfShape(grid_to_vec(grid), nx, ny, nz, f3(origin), f3(spacing), to_vec(shell),
330 f3(inv_inertia), bounding_radius);
331 },
332 nb::arg("grid"), nb::arg("origin"), nb::arg("spacing"), nb::arg("shell"),
333 nb::arg("inv_inertia"), nb::arg("bounding_radius"),
334 "Import a general particle: `grid` is the body-frame signed distance on an (nx, ny, nz) "
335 "array indexed [x, y, z] (negative inside), sampled at nodes origin + (x, y, z) * "
336 "spacing; `shell` the (M,3) surface point shell (EMPTY = sample the field's own zero "
337 "level set); `inv_inertia` the unit-mass principal diagonal inverse inertia; "
338 "`bounding_radius` the canonical enclosing radius. `origin`, `spacing`, `grid` and "
339 "`bounding_radius` are in length units, `inv_inertia` in 1/length^2. RESETS the "
340 "registry to this one "
341 "shape. See peclet.dem.build_particle for the SDF -> (grid, shell, inertia) helper.")
342 .def(
343 "add_shape",
344 [](Simulation& s, const std::string& shape, float radius, float height, float thickness) {
345 positive("add_shape", "radius", radius, "length");
346 nonneg("add_shape", "height", height, "length");
347 nonneg("add_shape", "thickness", thickness, "length");
348 return s.addShape(shape_kind(shape, "add_shape"), radius, height, thickness);
349 },
350 nb::arg("shape"), nb::arg("radius"), nb::arg("height") = 0.0f,
351 nb::arg("thickness") = 0.0f,
352 "Append an analytic shape ('sphere' | 'hollow_cylinder' | 'box', dimensions -- radius, "
353 "height, thickness in length units -- as initialize_shape) to the registry and return "
354 "its index, for a simulation with a "
355 "MIXTURE of shapes. initialize_shape stays the single-shape entry point (it RESETS the "
356 "registry). Assign the returned index with set_shape_ids.")
357 .def(
358 "add_sdf_shape",
359 [](Simulation& s, Grid3 grid, F3Arg origin, F3Arg spacing,
360 nb::ndarray<float, nb::c_contig> shell, F3Arg inv_inertia, float bounding_radius) {
361 sdfShapeArgs("add_sdf_shape", origin, spacing, inv_inertia, bounding_radius);
362 const int nx = (int)grid.shape(0), ny = (int)grid.shape(1), nz = (int)grid.shape(2);
363 return s.addSdfShape(grid_to_vec(grid), nx, ny, nz, f3(origin), f3(spacing),
364 to_vec(shell), f3(inv_inertia), bounding_radius);
365 },
366 nb::arg("grid"), nb::arg("origin"), nb::arg("spacing"), nb::arg("shell"),
367 nb::arg("inv_inertia"), nb::arg("bounding_radius"),
368 "Append a grid-SDF shape (arguments as set_sdf_shape: origin, spacing, grid and "
369 "bounding_radius in length units, inv_inertia in 1/length^2) and return its index. "
370 "set_sdf_shape stays the single-shape entry point (it RESETS the registry).")
371 .def(
372 "add_scene_shape",
373 [](Simulation& s, nb::ndarray<int, nb::c_contig> ni, nb::ndarray<float, nb::c_contig> nr,
374 int root, nb::ndarray<float, nb::c_contig> shell, F3Arg inv_inertia,
375 float bounding_radius) {
376 nonnegEach("add_scene_shape", "inv_inertia", inv_inertia, "1/length^2");
377 positive("add_scene_shape", "bounding_radius", bounding_radius, "length");
378 return s.addSceneShape(std::vector<int>(ni.data(), ni.data() + ni.size()),
379 std::vector<float>(nr.data(), nr.data() + nr.size()), root,
380 std::vector<float>(shell.data(), shell.data() + shell.size()),
381 f3(inv_inertia), bounding_radius);
382 },
383 nb::arg("node_ints"), nb::arg("node_reals"), nb::arg("root"), nb::arg("shell"),
384 nb::arg("inv_inertia"), nb::arg("bounding_radius"),
385 "Register a COMPOSED analytic particle shape from core's flat node encoding (the arrays "
386 "peclet.geom.SceneBuilder.encode() returns; CSG of the full leaf vocabulary): the "
387 "collision field is the exact tree, evaluated in canonical body space. shell: (M,3) "
388 "surface probe points (bake the tree and run the shell path -- the point-shell model "
389 "still needs probes). inv_inertia: unit-mass principal diagonal inverse inertia; "
390 "bounding_radius: canonical enclosing radius. THE CANONICAL FRAME MUST BE THE PRINCIPAL "
391 "INERTIA FRAME (SceneBuilder.principal_frame emits exactly that); a non-principal tree "
392 "runs the diagonal-inertia rotational update on the wrong frame, silently. Returns the "
393 "shape id for set_shape_ids.")
394 .def(
395 "set_shape_ids",
396 [](Simulation& s, nb::ndarray<int, nb::c_contig> ids) {
397 s.setShapeIds(std::vector<int>(ids.data(), ids.data() + ids.size()));
398 },
399 nb::arg("ids"),
400 "Per-particle shape index (one int per particle, each < num_shapes). Refreshes each "
401 "particle's inverse inertia from its new shape. Call it AFTER set_positions: "
402 "set_positions resets every particle to shape 0 (and sizes the particle set this call "
403 "is checked against).")
404 .def_prop_ro("num_shapes", &Simulation::numShapes, "Number of registered shapes.")
405 // ---- domain ---------------------------------------------------------------------------
406 // Corner overload: set_domain(min, max) 3-tuples (arbitrary origin); keeps the current
407 // periodicity.
408 .def(
409 "set_domain",
410 [](Simulation& s, F3Arg mn, F3Arg mx) {
411 domainCorners(mn, mx);
412 s.setDomainMinMax(f3(mn), f3(mx));
413 },
414 nb::arg("min"), nb::arg("max"),
415 "Set the domain by (min, max) corner tuples (arbitrary origin; length units); keeps "
416 "current periodicity.")
417 // The suite-canonical form (suite/docs/NAMING.md 1.1): keyword `extent` / `origin` /
418 // `periodic`, the same three names flow.Solver, peclet.voro and the AMR octree take. Bound
419 // AFTER the corner overload, so a two-positional call still resolves to (min, max);
420 // `extent=` selects this one.
421 .def(
422 "set_domain",
423 [](Simulation& s, F3Arg extent, F3Arg origin, std::array<bool, 3> periodic) {
424 positiveEach("set_domain", "extent", extent, "length");
425 finiteEach("set_domain", "origin", origin, "length");
426 s.setDomainCanonical(f3(extent), f3(origin), periodic[0], periodic[1], periodic[2]);
427 },
428 nb::arg("extent"), nb::arg("origin") = F3Arg{0, 0, 0},
429 nb::arg("periodic") = std::array<bool, 3>{true, true, false},
430 "Set the domain the suite-canonical way: `extent` is the box SIZE (not the far corner), "
431 "`origin` the lower corner (both in length units), `periodic` the per-axis flags. "
432 "Equivalent to "
433 "`set_domain(min=origin, max=origin+extent)` plus `set_periodic(*periodic)`. Either "
434 "form resets the broad-phase skin to 0.1 x the global scale (as set_global_scale does).")
435 .def("set_periodic", &Simulation::enablePeriodicity, nb::arg("x"), nb::arg("y"), nb::arg("z"),
436 "Set periodic boundaries per axis (x, y, z); read back with the `periodic` property "
437 "(suite/docs/NAMING.md 1.4).")
438 .def_prop_ro("origin", &Simulation::domainOrigin,
439 "The domain's lower corner (x, y, z), in length units — read-only; set it with "
440 "`set_domain`.")
441 .def_prop_ro("extent", &Simulation::domainExtent,
442 "The domain's SIZE (Lx, Ly, Lz), in length units — read-only, and note it is a "
443 "size and not the "
444 "far corner, which is `origin + extent` (suite/docs/NAMING.md 1.1).")
445 .def_prop_ro("periodic", &Simulation::domainPeriodic,
446 "Per-axis periodicity (x, y, z) — read-only; set it with `set_periodic`.")
447 // ---- physics settings ---------------------------------------------------------------
448 .def(
449 "set_gravity",
450 [](Simulation& s, F3Arg g) {
451 finiteEach("set_gravity", "gravity", g, "length/time^2");
452 s.setGravity(g[0], g[1], g[2]);
453 },
454 nb::arg("gravity"),
455 "Set the gravitational acceleration (gx, gy, gz), in length/time^2 units -- any "
456 "sequence of three floats. The default is ZERO.")
457 .def_prop_ro("gravity", &Simulation::gravity,
458 "The gravitational acceleration (gx, gy, gz), in length/time^2 units.")
459 .def(
460 "set_thermostat",
461 [](Simulation& s, float temperature, float tau, float kB) {
462 nonneg("set_thermostat", "temperature", temperature, "temperature");
463 nonneg("set_thermostat", "tau", tau, "time; 0 disables");
464 positive("set_thermostat", "kB", kB, "energy/temperature");
465 s.setThermostat(temperature, tau, kB);
466 },
467 nb::arg("temperature"), nb::arg("tau"), nb::arg("kB") = 1.0f,
468 "Enable a Berendsen-style velocity thermostat: target `temperature` (temperature units, "
469 ">= 0), coupling time `tau` (time units; tau = 0 disables) and Boltzmann constant `kB` "
470 "(energy/temperature units; the measured temperature is 2 x kinetic energy / (3N x "
471 "kB)).")
472 .def(
473 "set_solver_iterations",
474 [](Simulation& s, int pos, int vel) {
475 count("set_solver_iterations", "pos", pos, 0);
476 count("set_solver_iterations", "vel", vel, 0);
477 s.setSolverIterations(pos, vel);
478 },
479 nb::arg("pos"), nb::arg("vel"),
480 "Set the XPBD position- and velocity-solve iteration counts. `vel` defaults to 0 (no "
481 "velocity solve, hence no restitution).")
482 .def(
483 "set_hertz_material",
484 [](Simulation& s, int mat, float youngs, float poisson) {
485 positive("set_hertz_material", "youngs", youngs, "force/area");
486 poissonRatio("set_hertz_material", "poisson", poisson);
487 s.setHertzMaterial(mat, youngs, poisson);
488 },
489 nb::arg("mat"), nb::arg("youngs"), nb::arg("poisson"),
490 "Per-material Young's modulus and Poisson ratio for the soft-sphere Hertz-Mindlin "
491 "engine (material ids as in set_material_ids).")
492 .def(
493 "set_stabilization",
494 [](Simulation& s, const std::string& mode) {
495 if (mode != "off" && mode != "onesided" && mode != "multilevel")
496 throw std::invalid_argument(
497 "set_stabilization: expected 'off', 'onesided' or 'multilevel', got '" + mode +
498 "' ('escalate' / 'ordered' are measurement modes: "
499 "diagnostics.set_stabilization)");
500 s.setStabilizationMode(mode);
501 },
502 nb::arg("mode"),
503 "Stabilization pass of the staged velocity solve: 'off' (pure symmetric PGS -- exact "
504 "ballistic response, but a deep static column mid-collapse cannot be arrested within the "
505 "iteration budget), 'onesided' (default: held-lower-side grounded impulses -- arrests "
506 "any collapse but is a momentum sink), 'multilevel' (GraphMG contact-graph aggregation: "
507 "coarse inelastic solves at super-body masses -- momentum-conserving transport "
508 "acceleration).")
509 .def_prop_ro("stabilization", &Simulation::stabilizationMode,
510 "The stabilization mode: 'off', 'onesided', 'multilevel' (or a diagnostics "
511 "mode).")
512 .def("set_restitution_model", &Simulation::setRestitutionModel, nb::arg("model"),
513 "Restitution model of the PGS velocity solve: 'newton' (default; per-substep "
514 "restitution with Moreau's target, -e x the pre-solve normal velocity on every closed "
515 "contact above the resting threshold, which cannot create kinetic energy for a uniform "
516 "e) or 'poisson' (event-level: each pair banks its kinetic compression impulse and "
517 "releases e x the bank as a budget-capped separation-velocity target during unloading "
518 "-- restores the multi-substep-impact rebound per-substep restitution cannot return; "
519 "it keeps Newton's per-substep targets, -e x the approach on approaching contacts "
520 "only).")
521 .def_prop_ro("restitution_model", &Simulation::restitutionModel, "'newton' or 'poisson'.")
522 .def(
523 "set_global_scale",
524 [](Simulation& s, float scale) {
525 positive("set_global_scale", "scale", scale, "dimensionless");
526 s.setGlobalScale(scale);
527 },
528 nb::arg("scale"),
529 "Set a global length scale applied to all particles (effective radius = scale x "
530 "global_scale x base radius). Resets the broad-phase skin, as set_domain does -- call "
531 "it BEFORE set_domain if you rely on the skin.")
532 .def_prop_ro("global_scale", &Simulation::globalScale, "The global length scale.")
533 .def(
534 "set_dt",
535 [](Simulation& s, float dt) {
536 positive("set_dt", "dt", dt, "time");
537 s.setDt(dt);
538 },
539 nb::arg("dt"),
540 "Set the time step (> 0, time units) every stepper uses: step, step_hertz, step_mpi, "
541 "step_hertz_mpi. There is no default -- a step before set_dt raises.")
542 .def_prop_ro("dt", &Simulation::dt, "The time step set by set_dt, in time units.")
543 .def(
544 "set_material_params",
545 [](Simulation& s, float restitution_normal, float restitution_tangent, float friction) {
546 restitutionCoef("set_material_params", "restitution_normal", restitution_normal);
547 finite("set_material_params", "restitution_tangent", restitution_tangent,
548 "dimensionless");
549 nonneg("set_material_params", "friction", friction, "dimensionless");
550 s.setMaterialParams(restitution_normal, restitution_tangent, friction);
551 },
552 nb::arg("restitution_normal"), nb::arg("restitution_tangent") = 0.0f,
553 nb::arg("friction") = 0.0f,
554 "Set the BODY-BODY normal/tangential restitution and Coulomb friction coefficient. The "
555 "default friction is ZERO, and add_analytic_wall / add_sdf_wall set the particle-WALL "
556 "material only -- so a bed more than a few layers deep run with the defaults behaves "
557 "like a liquid: it transmits full hydrostatic pressure to the container and the "
558 "position solve squeezes grains through the boundary. That failure is silent and looks "
559 "like a solver-convergence bug (raising the position iterations and halving dt do not "
560 "move it). Set a non-zero friction for any deep bed.")
561 .def(
562 "set_material_ids",
563 [](Simulation& s, const std::vector<int>& ids) {
564 materialIds(ids);
565 s.setMaterialIds(ids);
566 },
567 nb::arg("ids"),
568 "Per-particle material ids (0..7). Pair (e, mu) values come from set_pair_material; "
569 "without any set_pair_material call the global material applies everywhere.")
570 .def(
571 "set_pair_material",
572 [](Simulation& s, int a, int b, float e, float mu) {
573 restitutionCoef("set_pair_material", "restitution", e);
574 nonneg("set_pair_material", "friction", mu, "dimensionless");
575 s.setPairMaterial(a, b, e, mu);
576 },
577 nb::arg("a"), nb::arg("b"), nb::arg("restitution"), nb::arg("friction"),
578 "Symmetric pair material (restitution, friction) for material ids (a, b). The first "
579 "call seeds every pair from the current global material.")
580 .def(
581 "set_wall_material_id",
582 [](Simulation& s, int wid, int mat) {
583 // A negative id is the wall's default (-1: its binary material); only the upper bound
584 // is checked.
585 require(mat <= kMaxMaterialId, "set_wall_material_id", "mat",
586 "an integer <= " + std::to_string(kMaxMaterialId), mat);
587 s.setWallMaterialId(wid, mat);
588 },
589 nb::arg("wid"), nb::arg("mat"),
590 "Give an SDF wall a material id so particle-wall (e, mu) resolves via the pair table "
591 "instead of the wall's binary material.")
592 // ---- walls ----------------------------------------------------------------------------
593 .def(
594 "add_analytic_wall",
595 [](Simulation& s, nb::ndarray<int, nb::c_contig> node_ints,
596 nb::ndarray<float, nb::c_contig> node_reals, int root, bool invert, float restitution,
597 float friction) {
598 restitutionCoef("add_analytic_wall", "restitution", restitution);
599 nonneg("add_analytic_wall", "friction", friction, "dimensionless");
600 return s.addAnalyticWall(
601 std::vector<int>(node_ints.data(), node_ints.data() + node_ints.size()),
602 to_vec(node_reals), root, invert, restitution, friction);
603 },
604 nb::arg("node_ints"), nb::arg("node_reals"), nb::arg("root"), nb::arg("invert"),
605 nb::arg("restitution") = 0.0f, nb::arg("friction") = 0.0f,
606 "Add an ANALYTIC wall from a core shape tree in the flat node encoding (3 ints + 16 "
607 "reals per node). Exact at every scale, with no voxel grid to replicate per rank. "
608 "invert=False for a stirrer/obstacle (grains outside the solid); invert=True for a "
609 "container, built from a SOLID body (a solid cylinder for a drum). The wall is "
610 "positioned by the node TRANSFORM -- an identity transform sits at the origin. Returns "
611 "the wall index.")
612 .def(
613 "add_plane",
614 [](Simulation& s, F3Arg p, F3Arg n) {
615 plane(p, n);
616 s.addPlane(p[0], p[1], p[2], n[0], n[1], n[2]);
617 },
618 nb::arg("point"), nb::arg("normal"),
619 "Add an infinite boundary wall plane through `point` (length units), with `normal` "
620 "(dimensionless direction) pointing into the half-space the grains occupy (both "
621 "3-sequences). XPBD engine only; the Hertz engine "
622 "takes SDF walls.")
623 .def(
624 "add_sdf_wall",
625 [](Simulation& s, Grid3 grid, F3Arg origin, F3Arg spacing, float restitution,
626 float friction) {
627 finiteEach("add_sdf_wall", "origin", origin, "length");
628 positiveEach("add_sdf_wall", "spacing", spacing, "length");
629 restitutionCoef("add_sdf_wall", "restitution", restitution);
630 nonneg("add_sdf_wall", "friction", friction, "dimensionless");
631 const int nx = (int)grid.shape(0), ny = (int)grid.shape(1), nz = (int)grid.shape(2);
632 return s.addSdfWall(grid_to_vec(grid), nx, ny, nz, f3(origin), f3(spacing), restitution,
633 friction);
634 },
635 nb::arg("grid"), nb::arg("origin"), nb::arg("spacing"), nb::arg("restitution") = 0.0f,
636 nb::arg("friction") = 0.0f,
637 "Add a static world-space SDF wall/container (drum barrel, hopper, vibrating tray): "
638 "`grid` is the signed distance (length units) on an (nx, ny, nz) array indexed [x, y, z] "
639 "at world nodes "
640 "origin + (x, y, z) * spacing -- POSITIVE in the void where grains live, NEGATIVE in the "
641 "solid wall; `origin` and `spacing` are in length units; restitution / friction are the "
642 "binary particle-wall material (dimensionless). Returns the "
643 "wall index (for set_wall_velocity). See peclet.dem.build_wall_sdf for the SDF -> "
644 "(grid, origin, spacing) helper.")
645 // Rigid-body surface-velocity field of a wall: v(x) = linVel + angVel × (x − center).
646 // Rotating drum: set angVel about the axis point `center`. Vibrating wall: drive linVel each
647 // step.
648 .def(
649 "set_wall_velocity",
650 [](Simulation& s, int wall_index, F3Arg lin, F3Arg ang, F3Arg center) {
651 finiteEach("set_wall_velocity", "lin_vel", lin, "length/time");
652 finiteEach("set_wall_velocity", "ang_vel", ang, "1/time");
653 finiteEach("set_wall_velocity", "center", center, "length");
654 s.setWallVelocity(wall_index, f3(lin), f3(ang), f3(center));
655 },
656 nb::arg("wall_index"), nb::arg("lin_vel") = F3Arg{0, 0, 0},
657 nb::arg("ang_vel") = F3Arg{0, 0, 0}, nb::arg("center") = F3Arg{0, 0, 0},
658 "Set a wall's rigid-body surface velocity v(x) = lin_vel + ang_vel × (x − center): "
659 "lin_vel in length/time units, ang_vel in 1/time (radians per time), center in length "
660 "units (felt "
661 "by grains in contact even though the geometry is static). Cheap; call every step for a "
662 "vibrating wall.")
663 .def(
664 "set_wall_transform",
665 [](Simulation& s, int wall_index, F3Arg translation, std::array<float, 4> quat) {
666 finiteEach("set_wall_transform", "translation", translation, "length");
667 finiteEach("set_wall_transform", "quat", quat, "dimensionless");
668 s.setWallTransform(wall_index, f3(translation), quat[0], quat[1], quat[2], quat[3]);
669 },
670 nb::arg("wall_index"), nb::arg("translation") = F3Arg{0, 0, 0},
671 nb::arg("quat") = std::array<float, 4>{0, 0, 0, 1},
672 "Place an ANALYTIC wall (add_analytic_wall) rigidly in the world: quat (x,y,z,w) then "
673 "translation, composed onto the AUTHORED root transform, so calls are absolute and never "
674 "compound. This moves the GEOMETRY -- a stirrer blade sweeps -- where set_wall_velocity "
675 "only gives the static surface a velocity field (enough for an axisymmetric drum). Drive "
676 "both together each step: integrate ang_vel into the quaternion here and pass the same "
677 "ang_vel to set_wall_velocity. Grid-SDF walls have no tree and are refused.")
678 // ---- particle state -------------------------------------------------------------------
679 .def(
680 "set_positions",
681 [](Simulation& s, nb::ndarray<float, nb::c_contig> a) {
682 if (a.ndim() != 2 || (a.shape(1) != 3 && a.shape(1) != 4))
683 throw std::invalid_argument("set_positions: expected an (N, 3) or (N, 4) array");
684 const int n = (int)a.shape(0), k = (int)a.shape(1);
685 if (n > s.capacity())
686 throw std::invalid_argument(
687 "set_positions: " + std::to_string(n) +
688 " particles exceed Simulation(capacity=" + std::to_string(s.capacity()) + ")");
689 const std::vector<float> buf = to_vec(a);
690 std::vector<float> xyz((size_t)n * 3), im;
691 const bool hasMass = (k == 4);
692 if (hasMass)
693 im.resize(n);
694 for (int i = 0; i < n; ++i) {
695 xyz[3 * i] = buf[k * i];
696 xyz[3 * i + 1] = buf[k * i + 1];
697 xyz[3 * i + 2] = buf[k * i + 2];
698 if (hasMass) {
699 const float w = buf[k * i + 3];
700 im[i] = (w == 0.0f) ? 1.0f : w;
701 }
702 }
703 s.setPositions(xyz);
704 if (hasMass)
705 s.setInvMass(im);
706 },
707 nb::arg("positions"),
708 "Set particle positions (length units) from an (N, 3) array, or (N, 4) whose column 3 "
709 "is the INVERSE mass (1/mass units) (0 is remapped to 1; use set_inv_mass for a fixed "
710 "body). N may not exceed "
711 "`capacity`. This (re)sizes the particle set and RESETS every particle's quaternion, "
712 "scale, inverse mass, shape id (to 0), velocities and gid -- so every other per-particle "
713 "setter goes AFTER it.")
714 .def(
715 "set_velocities",
716 [](Simulation& s, nb::ndarray<float, nb::c_contig> a) {
717 s.setVelocities(rows_of(a, 3, s, "set_velocities"));
718 },
719 nb::arg("velocities"),
720 "Set particle velocities (length/time units) from an (N, 3) array.")
721 .def(
722 "set_external_forces",
723 [](Simulation& s, nb::ndarray<float, nb::c_contig> a) {
724 s.setExternalForces(rows_of(a, 3, s, "set_external_forces"));
725 },
726 nb::arg("forces"),
727 "Set the per-particle external FORCE (e.g. fluid drag; force units, mass x "
728 "length/time^2) from an (N, 3) array. Applied "
729 "each step as dv = F*invMass*dt; persists until re-set or cleared.")
730 .def("clear_external_forces", &Simulation::clearExternalForces,
731 "Zero all per-particle external forces (force units).")
732 .def(
733 "set_external_torques",
734 [](Simulation& s, nb::ndarray<float, nb::c_contig> a) {
735 s.setExternalTorques(rows_of(a, 3, s, "set_external_torques"));
736 },
737 nb::arg("torques"),
738 "Set the per-particle external TORQUE in the WORLD frame from an (N, 3) array (the "
739 "resolved-CFD-DEM hydrodynamic torque, a magnetic couple, ...). Applied each step in the "
740 "angular predictor as Euler's equation in the body frame, dw = invI*(tau_body - w x I "
741 "w)*dt, alongside the gyroscopic term that is already there; persists until re-set or "
742 "cleared. Only bodies with a finite inertia respond -- a torque on a body whose "
743 "invInertia is zero is inert, exactly as the gyroscopic term is. Sleeping is disabled "
744 "while a torque is set, as it is for external forces.")
745 .def("clear_external_torques", &Simulation::clearExternalTorques,
746 "Zero all per-particle external torques (and re-enable island sleeping).")
747 .def(
748 "set_quaternions",
749 [](Simulation& s, nb::ndarray<float, nb::c_contig> a) {
750 s.setQuaternions(rows_of(a, 4, s, "set_quaternions"));
751 },
752 nb::arg("quaternions"),
753 "Set particle orientation quaternions (x, y, z, w) from an (N, 4) array.")
754 .def(
755 "set_angular_velocities",
756 [](Simulation& s, nb::ndarray<float, nb::c_contig> a) {
757 s.setAngularVelocities(rows_of(a, 3, s, "set_angular_velocities"));
758 },
759 nb::arg("angular_velocities"),
760 "Set particle angular velocities (body frame; 1/time units, radians per time) from an "
761 "(N, 3) array.")
762 .def(
763 "set_inv_inertia",
764 [](Simulation& s, nb::ndarray<float, nb::c_contig> a) {
765 s.setInvInertia(rows_of(a, 3, s, "set_inv_inertia"));
766 },
767 nb::arg("inv_inertia"),
768 "Set the per-particle principal-frame diagonal inverse inertia from an (N, 3) array.")
769 .def(
770 "set_inv_mass",
771 [](Simulation& s, nb::ndarray<float, nb::c_contig> a) {
772 s.setInvMass(flat_of(a, s, "set_inv_mass"));
773 },
774 nb::arg("inv_mass"), "Set per-particle inverse mass, an (N,) array (0 = fixed body).")
775 .def(
776 "set_scales_uniform",
777 [](Simulation& s, float scale) {
778 positive("set_scales_uniform", "scale", scale, "dimensionless");
779 s.setScalesUniform(scale);
780 },
781 nb::arg("scale"), "Set a single uniform scale for all particles.")
782 .def(
783 "set_scales",
784 [](Simulation& s, nb::ndarray<float, nb::c_contig> a) {
785 s.setScales(flat_of(a, s, "set_scales"));
786 },
787 nb::arg("scales"), "Set per-particle scales from an (N,) array (the growth target).")
788 .def(
789 "set_growth_params",
790 [](Simulation& s, float rate, float new_factor) {
791 finite("set_growth_params", "rate", rate, "1/time");
792 finite("set_growth_params", "new_factor", new_factor, "dimensionless");
793 s.setGrowthParams(rate, new_factor);
794 },
795 nb::arg("rate"), nb::arg("new_factor") = -1.0f,
796 "Set the particle growth rate (factor *= exp(rate*dt) per step, capped at 1) and, if "
797 "new_factor > 0, the current growth factor (a negative value keeps it; 0.01 if growth "
798 "was inactive).")
799 .def_prop_ro("growth_factor", &Simulation::growthFactor,
800 "The current particle growth factor (-1 = growth inactive).")
801 .def_prop_ro("growth_rate", &Simulation::getGrowthRate, "The particle growth rate.")
802 .def(
803 "get_masses", [](const Simulation& s) { return flat(s.getMasses()); },
804 "Return per-particle masses (1 / inverse mass; 0 for fixed bodies) as an (N,) array.")
805 .def(
806 "get_positions", [](const Simulation& s) { return rows(s.getPositions(), 3); },
807 "Return particle positions (length units) as an (N, 3) numpy array.")
808 .def(
809 "get_velocities", [](const Simulation& s) { return rows(s.getVelocities(), 3); },
810 "Return particle velocities (length/time units) as an (N, 3) numpy array.")
811 .def(
812 "get_angular_velocities",
813 [](const Simulation& s) { return rows(s.getAngularVelocities(), 3); },
814 "Return particle angular velocities (body frame; 1/time units) as an (N, 3) numpy "
815 "array.")
816 .def(
817 "get_inv_inertia", [](const Simulation& s) { return rows(s.getInvInertia(), 3); },
818 "Return the per-particle principal-frame diagonal inverse inertia as an (N, 3) array.")
819 .def(
820 "get_quaternions", [](const Simulation& s) { return rows(s.getQuaternions(), 4); },
821 "Return particle orientation quaternions (x, y, z, w) as an (N, 4) numpy array.")
822 .def(
823 "get_scales", [](const Simulation& s) { return flat(s.getScales()); },
824 "Return per-particle scales as an (N,) numpy array.")
825 // Zero-copy device export (H2): the returned (N,3) array REFERENCES the device particle Views
826 // — a NumPy view on a host backend, a DLPack/__cuda_array_interface__ array (consume with
827 // cupy.from_dlpack / torch.from_dlpack) on CUDA/HIP — so a GPU-resident analysis chain never
828 // pays the device->host copy. The array keeps the (ref-counted) View alive.
829 .def(
830 "get_positions_view",
831 [](const Simulation& s) {
832 return peclet::core::python::view_to_ndarray(Kokkos::subview(
833 s.positionsView(), Kokkos::make_pair(0, s.numParticles()), Kokkos::ALL));
834 },
835 "Zero-copy (N,3) device array of positions (NumPy view on host, DLPack/CuPy on GPU).")
836 .def(
837 "get_velocities_view",
838 [](const Simulation& s) {
839 return peclet::core::python::view_to_ndarray(Kokkos::subview(
840 s.velocitiesView(), Kokkos::make_pair(0, s.numParticles()), Kokkos::ALL));
841 },
842 "Zero-copy (N,3) device array of velocities (NumPy view on host, DLPack/CuPy on GPU).")
843 .def(
844 "get_external_forces_view",
845 [](const Simulation& s) {
846 return peclet::core::python::view_to_ndarray(Kokkos::subview(
847 s.externalForcesView(), Kokkos::make_pair(0, s.numParticles()), Kokkos::ALL));
848 },
849 "Zero-copy (N,3) device array of the per-particle external force (NumPy view on host, "
850 "DLPack/CuPy on GPU) — write fluid drag here directly to avoid a host round-trip.")
851 .def(
852 "get_inv_mass_view",
853 [](const Simulation& s) {
854 return peclet::core::python::view_to_ndarray(
855 Kokkos::subview(s.invMassView(), Kokkos::make_pair(0, s.numParticles())));
856 },
857 "Zero-copy (N,) device array of per-particle inverse mass (NumPy view on host, "
858 "DLPack/CuPy on GPU) — read-only use; needed for stiff-safe drag integration.")
859 // ---- stepping -------------------------------------------------------------------------
860 .def("step", &Simulation::step, nb::arg("n") = 1,
861 "Advance `n` XPBD substeps of the time step set by set_dt (raises if set_dt was never "
862 "called).")
863 .def("relax", &Simulation::relax, nb::arg("n") = 1,
864 "Run `n` dynamics-free RELAXATION substeps: overlap removal only, no gravity and no "
865 "velocity update -- the growth-packing protocol's settle move (dt = 0 inside; the "
866 "stored dt is untouched and set_dt is not required).")
867 .def("step_hertz", &Simulation::stepHertz, nb::arg("substeps") = 1,
868 nb::arg("skin_frac") = 0.3f,
869 "Advance `substeps` explicit soft-sphere Hertz-Mindlin steps of the time step set by "
870 "set_dt (spheres, SDF walls, non-periodic): viscoelastic Hertz normal force + Mindlin "
871 "shear-history spring, Coulomb-clamped; (e, mu) from the pair-material tables, "
872 "stiffness from set_hertz_material. skin_frac is the Verlet pair-list skin as a "
873 "fraction of the radius.")
874 // ---- read-out -------------------------------------------------------------------------
875 .def_prop_ro("num_particles", &Simulation::numParticles, "The number of particles.")
876 .def_prop_ro(
877 "num_contacts", [](Simulation& s) { return s.numContacts(); },
878 "Broad-phase candidate pairs found in the last step (ArborX BVH query).")
879 .def_prop_ro(
880 "num_manifolds", [](Simulation& s) { return s.numManifolds(); },
881 "Narrow-phase contact manifolds (touching pairs) resolved in the last step.")
882 .def_prop_ro(
883 "max_overlap", [](Simulation& s) { return s.maxOverlap(); },
884 "Maximum pair interpenetration recorded by the position solver in the last step (its "
885 "last-iteration residual, so it under-reports the committed overlap -- see "
886 "docs/archive/packing_investigation.md). compute_overlaps() measures the committed "
887 "state.")
888 .def("compute_overlaps", &Simulation::computeOverlaps,
889 "Measure and return the maximum pair interpenetration of the current committed state.")
890 .def(
891 "get_sdf_grid",
892 [](Simulation& s, std::tuple<int, int, int> res) {
893 auto [rx, ry, rz] = res;
894 sampleCounts("get_sdf_grid", rx, ry, rz);
895 // x-fastest samples -> an (rx, ry, rz) array indexed [x, y, z] (Fortran order), the
896 // suite's grid layout and what set_sdf_shape / add_sdf_wall take back.
897 return peclet::core::python::vector_to_ndarray(
898 s.getSdfGrid(rx, ry, rz), {(std::size_t)rx, (std::size_t)ry, (std::size_t)rz},
899 {1, (std::int64_t)rx, (std::int64_t)rx * ry});
900 },
901 nb::arg("resolution"),
902 "Reconstruct the packed-bed SDF (negative inside solid) over the domain on an (rx, ry, "
903 "rz) grid; returns an (rx, ry, rz) array indexed [x, y, z].")
904 .def(
905 "export_sdf",
906 [](Simulation& s, const std::string& filename, std::tuple<int, int, int> res) {
907 auto [rx, ry, rz] = res;
908 sampleCounts("export_sdf", rx, ry, rz);
909 s.exportSdf(filename, rx, ry, rz);
910 },
911 nb::arg("filename"), nb::arg("resolution"),
912 "Reconstruct and write the packed-bed SDF on an (rx, ry, rz) grid to a VTI file.")
913 .def("write_vtp", &Simulation::writeVtp, nb::arg("filename"),
914 "Write particle state to a VTP file (ParaView/Ovito).")
915 .def("export_lammps", &Simulation::exportLammps, nb::arg("filename"), nb::arg("step"),
916 "Export particle state to a LAMMPS dump file.")
917 // ---- execution policy -----------------------------------------------------------------
918 .def(
919 "set_sleeping",
920 [](Simulation& s, bool enabled, float threshold_scale, int consecutive, float wake_scale,
921 bool wake_on_lost_contact, float immovable_frac) {
922 finite("set_sleeping", "threshold_scale", threshold_scale, "dimensionless");
923 finite("set_sleeping", "wake_scale", wake_scale, "dimensionless");
924 finite("set_sleeping", "immovable_frac", immovable_frac, "dimensionless");
925 s.setSleeping(enabled, threshold_scale, consecutive, wake_scale, wake_on_lost_contact,
926 immovable_frac);
927 },
928 nb::arg("enabled"), nb::arg("threshold_scale") = 2.0f, nb::arg("consecutive") = 64,
929 nb::arg("wake_scale") = 40.0f, nb::arg("wake_on_lost_contact") = false,
930 nb::arg("immovable_frac") = 0.01f,
931 "Island sleeping (single-GPU statics, default ON): freeze grounded bodies whose motion "
932 "stays below threshold_scale x the resting floor for `consecutive` substeps; wake only "
933 "above wake_scale x that floor (hysteresis vs residual jitter). wake_on_lost_contact "
934 "additionally wakes a sleeper whose support disappeared; immovable_frac is a sleeper's "
935 "effective inverse-mass fraction in the solve (0 = exactly immovable). Requires gravity "
936 "and no external force; inert under MPI.")
937 .def_prop_ro("sleeping", &Simulation::sleeping, "Whether island sleeping is enabled.")
938 .def_prop_ro(
939 "num_asleep", [](Simulation& s) { return s.numAsleep(); },
940 "Number of currently-sleeping real bodies.")
941 .def(
942 "set_verlet_skin",
943 [](Simulation& s, float skin_frac) {
944 nonneg("set_verlet_skin", "skin_frac", skin_frac, "dimensionless; 0 disables");
945 s.setVerletSkin(skin_frac);
946 },
947 nb::arg("skin_frac"),
948 "Enable the Verlet-cached impulse broadphase (single-GPU, non-periodic, default OFF, "
949 "i.e. skin_frac = 0): skip the ArborX rebuild while nothing moved more than skin/2 "
950 "(skin = skin_frac x max grain radius).")
951 .def_prop_ro("verlet_skin", &Simulation::verletSkin,
952 "Broadphase-skin fraction of the max grain radius (0 = rebuild every step).")
953 .def("set_incremental_coloring", &Simulation::setIncrementalColoring, nb::arg("enabled"),
954 "Incremental (warm-started) graph coloring of the contact manifolds (default True): "
955 "reuse last substep's colors and repair only the conflicts. This CHANGES RESULTS -- "
956 "the coloring fixes the Gauss-Seidel sweep order -- so False reproduces the "
957 "pre-incremental behaviour rather than merely running slower.")
958 .def_prop_ro("incremental_coloring", &Simulation::incrementalColoring,
959 "Whether incremental (warm-started) coloring is enabled.")
960 .def("set_shell_detection", &Simulation::setShellDetection, nb::arg("mode"),
961 "Narrow-phase shell detection of the XPBD engine (step, step_mpi, relax, "
962 "compute_overlaps; step_hertz is unaffected). 'one_way' (default): only the "
963 "lower-index body's shell points are tested against the other body's SDF, so a thin "
964 "rim, wall or edge pressed into a flat face between those points can go unseen. "
965 "'two_way': shell pairs are also probed the other way round, and a sphere-shell pair "
966 "always uses the exact sphere probe. Enable it for thin-walled or non-convex shells "
967 "(tubes, rings), sharp edges and corners against faces, and large size ratios where "
968 "the smaller body's features are finer than the larger body's shell spacing; not "
969 "needed for spheres or smooth convex bodies of similar size with dense shells. Costs "
970 "up to 2x the narrow phase and the contacts of shell pairs (docs/solver_details.md). "
971 "CHANGES RESULTS for non-sphere bodies.")
972 .def_prop_ro("shell_detection", &Simulation::shellDetection,
973 "The narrow-phase shell detection: 'one_way' or 'two_way'.")
974#ifdef PECLET_DEM_MPI
975 // ---- distributed step; built only with -DPECLET_DEM_MPI=ON ---------------------------
976 .def(
977 "init_mpi",
978 [](Simulation& s, std::tuple<double, double, double> origin,
979 std::tuple<double, double, double> extent, std::tuple<long, long, long> cells,
980 std::tuple<bool, bool, bool> periodic) {
981 // Checked before MPI_Init, so a refused call leaves MPI untouched.
982 mpiBox(origin, extent, cells);
983 int inited = 0;
984 MPI_Initialized(&inited);
985 if (!inited) {
986 int argc = 0;
987 char** argv = nullptr;
988 MPI_Init(&argc, &argv);
989 }
990 s.initMpi(origin, extent, cells, periodic, MPI_COMM_WORLD);
991 },
992 nb::arg("origin"), nb::arg("extent"), nb::arg("cells"), nb::arg("periodic"),
993 "Set up the ORB block decomposition + core particle halo for the distributed step on "
994 "the global domain (`origin` lower corner and `extent` SIZE in length units, `cells` "
995 "per axis for the ORB "
996 "grid, `periodic` per axis -- the suite's domain quartet).")
997 .def(
998 "enable_mpi_step",
999 [](Simulation& s, double rcut, int sync_every, bool forward_rotation, int rebalance_every,
1000 double verlet_skin) {
1001 nonneg("enable_mpi_step", "rcut", rcut, "length");
1002 nonneg("enable_mpi_step", "verlet_skin", verlet_skin, "length; 0 disables");
1003 s.enableMpiStep(rcut, sync_every, forward_rotation, rebalance_every, verlet_skin);
1004 },
1005 nb::arg("rcut") = 0.0, nb::arg("sync_every") = 1, nb::arg("forward_rotation") = true,
1006 nb::arg("rebalance_every") = 0, nb::arg("verlet_skin") = 0.0,
1007 "Enable the distributed step: ghost-band width rcut (a lower bound -- step_mpi widens "
1008 "it to the contact reach plus a drift slack and the prediction allowance, "
1009 "max(rcut, 2.1 x the global maximum radius + 0.25 x it + P), so the default 0 means "
1010 "exactly that), sync_every (the owner/ghost reconciliation interval; conservation is "
1011 "exact at any value -- a body updated from several places is solved through copies, "
1012 "mass-split for the projection-form phases and exclusively held by one rank per sync "
1013 "interval for the g = 0 one-shot restitution sweep -- larger sync_every means more lag, "
1014 "fewer messages), rotation forwarding, the load-rebalance interval in steps (0 = fixed "
1015 "decomposition; every step also votes, in the same reduction as the band, whether any "
1016 "body has drifted more than the slack outside its owner's block, and migrates it if so "
1017 "-- ownership is therefore not fixed across a run, and ghost selection uses the "
1018 "domain-clamped position on non-periodic axes), and the Verlet ghost-reuse skin (0 = "
1019 "rebuild the halo topology every substep; >0 = reuse it until a particle moves > skin, "
1020 "and P above is the skin instead of the predicted displacement).")
1021 .def("step_mpi", &Simulation::stepMpi, nb::arg("n") = 1,
1022 "Advance the distributed (MPI) simulation by `n` steps of the time step set by set_dt, "
1023 "with halo exchange.")
1024 .def("step_hertz_mpi", &Simulation::stepHertzMpi, nb::arg("substeps") = 1,
1025 nb::arg("skin_frac") = 0.3f,
1026 "Advance `substeps` distributed explicit Hertz-Mindlin (force-based) steps of the time "
1027 "step set by set_dt — the MPI counterpart of step_hertz on the init_mpi/enable_mpi_step "
1028 "decomposition. rebalance_every counts CALLS of this method; migration carries the "
1029 "Mindlin history.")
1030 .def("rebalance", &Simulation::rebalance,
1031 "Re-decompose by particle count and migrate ownership now; returns this rank's new "
1032 "owned count.")
1033 .def("migrate_to_weights", &Simulation::migrateToWeights, nb::arg("weights"),
1034 nb::arg("align") = 1,
1035 "Co-rebalance: migrate particle ownership onto the weighted ORB of per-cell weights "
1036 "(global x-fastest over the init_mpi cell grid), so each rank owns the particles in a "
1037 "block of near-equal total weight -- the SAME partition the coupled flow solver "
1038 "redistributes onto from the same weight field. `align` (a power of two, default 1) "
1039 "puts every block boundary on a multiple of `align` cells; 1 is the plain weighted "
1040 "ORB. A coupled run passes the alignment flow's rebalance_by_weights returned, "
1041 "which it chose for its pressure multigrid; dem alone has no reason to align. Raises "
1042 "ValueError when `align` is not a power of two, does not divide the cell grid, or "
1043 "`weights` does not cover it. Returns this rank's new owned count.")
1044 .def_prop_ro("rank", &Simulation::rank, "This rank's MPI index.")
1045 .def_prop_ro("num_ghost", &Simulation::numGhost,
1046 "The number of ghost particles on this rank.")
1047#endif
1048 ;
1049
1050 // Module-level LAMMPS dump writer from raw arrays: export_lammps(filename, step, pos, vel,
1051 // quats, radii, box_min, box_max, periodic).
1052 m.def(
1053 "export_lammps",
1054 [](const std::string& filename, int step, nb::ndarray<float, nb::c_contig> pos,
1055 nb::ndarray<float, nb::c_contig> vel, nb::ndarray<float, nb::c_contig> quats,
1056 nb::ndarray<float, nb::c_contig> radii, std::optional<F3Arg> box_min,
1057 std::optional<F3Arg> box_max, bool periodic) {
1058 const float* pmn = box_min ? box_min->data() : nullptr;
1059 const float* pmx = box_max ? box_max->data() : nullptr;
1060 peclet::dem::writeLammpsDump(filename, step, to_vec(pos), to_vec(vel), to_vec(quats),
1061 to_vec(radii), pmn, pmx, periodic);
1062 },
1063 nb::arg("filename"), nb::arg("step"), nb::arg("pos"), nb::arg("vel"), nb::arg("quats"),
1064 nb::arg("radii"), nb::arg("box_min") = std::nullopt, nb::arg("box_max") = std::nullopt,
1065 nb::arg("periodic") = false,
1066 "Module-level LAMMPS dump writer from raw arrays (filename, step, pos, vel, quats, radii, "
1067 "box corners, periodic flag), written as given: pos, radii and the box corners in length "
1068 "units, vel in length/time units, quats dimensionless.");
1069}
float computeOverlaps()
Definition sim.hpp:793
bool incrementalColoring() const
Definition sim.hpp:329
void relax(int n=1)
n dynamics-free RELAXATION substeps (overlap removal only, no gravity / velocity update): the growth-...
Definition sim.hpp:783
int capacity() const
Definition sim.hpp:389
static void releaseAll()
Definition sim.hpp:81
void enablePeriodicity(bool x, bool y, bool z)
Definition sim.hpp:178
void stepHertz(int substeps, float skin_frac)
Advance substeps explicit soft-sphere Hertz-Mindlin steps of the stored dt (device-side loop; the (e,...
Definition sim.hpp:371
std::tuple< float, float, float > domainExtent() const
Definition sim.hpp:195
std::tuple< float, float, float > domainOrigin() const
Definition sim.hpp:192
std::string stabilizationMode() const
Definition sim.hpp:240
bool sleeping() const
True while island sleeping is enabled.
Definition sim.hpp:290
std::string restitutionModel() const
Definition sim.hpp:259
std::tuple< float, float, float > gravity() const
Definition sim.hpp:202
void writeVtp(const std::string &filename) const
Definition sim.hpp:1142
int numParticles() const
Definition sim.hpp:958
std::tuple< bool, bool, bool > domainPeriodic() const
Definition sim.hpp:198
float growthFactor() const
Definition sim.hpp:744
std::string shellDetection() const
Definition sim.hpp:345
void setIncrementalColoring(bool enabled)
Incremental (warm-started) graph colouring of the contact manifolds (default ON): reuse last substep'...
Definition sim.hpp:328
void setShellDetection(const std::string &mode)
Narrow-phase shell detection of the XPBD engine (step / step_mpi / relax / compute_overlaps; the Hert...
Definition sim.hpp:336
float globalScale() const
Definition sim.hpp:379
void clearExternalForces()
Definition sim.hpp:666
void clearExternalTorques()
Definition sim.hpp:682
void exportLammps(const std::string &filename, int step) const
Definition sim.hpp:797
float getGrowthRate() const
Definition sim.hpp:745
float verletSkin() const
Definition sim.hpp:300
void setRestitutionModel(const std::string &model)
Restitution model of the PGS velocity solve: "newton" (default; per-substep restitution with Moreau's...
Definition sim.hpp:251
float dt() const
Definition sim.hpp:388
void step(int n=1)
Advance n XPBD substeps of the stored dt (set_dt first; suite/docs/NAMING.md 1.5).
Definition sim.hpp:774
int addSdfShape(const std::vector< float > &grid, int nx, int ny, int nz, F3 origin, F3 spacing, const std::vector< float > &shellFlat, F3 invInertia, float boundingRadius)
Append a grid-SDF shape (the general non-spherical particle) to the mixture and return its index.
int addShape(int shape_type, float radius, float height, float thickness)
Append an analytic shape and return its index, for simulations with a MIXTURE of shapes.
int addSceneShape(const std::vector< int > &nodeInts, const std::vector< float > &nodeReals, int root, const std::vector< float > &shellFlat, F3 invInertia, float boundingRadius)
void setSdfShape(const std::vector< float > &grid, int nx, int ny, int nz, F3 origin, F3 spacing, const std::vector< float > &shellFlat, F3 invInertia, float boundingRadius)
void initializeShape(int shape_type, float radius, float height, float thickness)
void setShapeIds(const std::vector< int > &ids)
Per-particle shape assignment.
Host-facing facade with std::vector setters/getters (binding-agnostic).
Definition sim.hpp:56
void setQuaternions(const std::vector< float > &q)
Definition sim.hpp:691
void setFusedSweeps(const std::string &mode)
Fused colour sweeps (CUDA): run a whole sweep — and where eligible the whole adaptive iteration loop ...
Definition sim.hpp:311
std::vector< float > getMasses() const
Definition sim.hpp:748
void setThermostat(float temperature, float tau, float kB)
Definition sim.hpp:205
bool cudaGraphs() const
Definition sim.hpp:306
void setWallTransform(int wallIndex, F3 translation, float qx, float qy, float qz, float qw)
Definition sim.hpp:525
std::vector< float > getInvInertia() const
Definition sim.hpp:729
std::pair< int, int > debugColoringConflicts()
Definition sim.hpp:970
bool velocityUseGS() const
Definition sim.hpp:217
int numAsleep()
Number of currently-sleeping real bodies (diagnostics / tests).
Definition sim.hpp:347
int capacity() const
Definition sim.hpp:389
std::vector< float > getVelocities() const
Definition sim.hpp:761
void setPairMaterial(int a, int b, float restitution, float friction)
Set the symmetric pair material (restitution, friction) for material ids (a, b).
Definition sim.hpp:417
std::vector< float > getScales() const
Definition sim.hpp:769
std::pair< int, int > debugColoringLeftovers()
Definition sim.hpp:1043
std::tuple< double, float, int > restOrphanStats()
Orphan-account diagnostics: (sum, max, count>0) of the per-body orphaned budget.
Definition sim.hpp:1136
peclet::dem::SplitStats debugSplitStats() const
Definition sim.hpp:1119
void setVelocityUseGS(bool useGS)
Definition sim.hpp:216
std::vector< float > getQuaternions() const
Definition sim.hpp:765
void setWallVelocity(int wallIndex, F3 linVel, F3 angVel, F3 center)
Definition sim.hpp:505
void exportSdf(const std::string &filename, int rx, int ry, int rz)
Definition sim.hpp:809
void setVerletSkin(float skin_frac)
Verlet-cached impulse broadphase (single-GPU, non-periodic; default OFF).
Definition sim.hpp:296
int numParticles() const
Definition sim.hpp:958
void setGlobalScale(float s)
Definition sim.hpp:375
void addPlane(float px, float py, float pz, float nx, float ny, float nz)
Definition sim.hpp:447
void setVelocities(const std::vector< float > &v)
Definition sim.hpp:646
int addSdfWall(const std::vector< float > &grid, int nx, int ny, int nz, F3 origin, F3 spacing, float restitution, float friction)
Definition sim.hpp:464
void setPositions(const std::vector< float > &xyz)
Definition sim.hpp:578
void setSleeping(bool enabled, float threshold_scale=2.0f, int consecutive=64, float wake_scale=40.0f, bool wake_on_lost_contact=false, float immovable_frac=0.01f)
Island sleeping / freezing (single-GPU statics, default ON; enabled=False disables).
Definition sim.hpp:275
void setInvInertia(const std::vector< float > &ii)
Definition sim.hpp:710
const Vf & invMassView() const
Definition sim.hpp:688
void setDt(float dt)
The time step every stepper uses (suite/docs/NAMING.md 1.5).
Definition sim.hpp:382
void setAngularVelocities(const std::vector< float > &w)
Definition sim.hpp:701
const V3 & externalForcesView() const
Definition sim.hpp:687
void setDomainCanonical(F3 extent, F3 origin, bool px, bool py, bool pz)
Definition sim.hpp:186
void setHertzMaterial(int mat, float youngs, float poisson)
Per-material Young's modulus + Poisson ratio for the Hertz-Mindlin engine (material ids as in setMate...
Definition sim.hpp:357
std::vector< float > getAngularVelocities() const
Definition sim.hpp:725
void setScalesUniform(float s)
Definition sim.hpp:630
std::vector< float > getSdfGrid(int rx, int ry, int rz)
Definition sim.hpp:951
void setCudaGraphs(bool enabled)
CUDA-graph replay of the solver's iteration loops (single-rank CUDA; default ON).
Definition sim.hpp:305
void setExternalTorques(const std::vector< float > &t)
Definition sim.hpp:672
int debugMultilevelColoringConflicts()
Definition sim.hpp:1071
void setSolverIterations(int pos, int vel)
Definition sim.hpp:210
const V3 & velocitiesView() const
Definition sim.hpp:963
void setExternalForces(const std::vector< float > &f)
Definition sim.hpp:657
std::vector< float > getPositions() const
Definition sim.hpp:757
std::tuple< double, float, int > restBankStats()
Poisson-restitution diagnostics: (sum, max, count>0) of the committed per-pair owed separation impuls...
Definition sim.hpp:1132
int addAnalyticWall(const std::vector< int > &nodeInts, const std::vector< float > &nodeReals, int root, bool invert, float restitution, float friction)
Add an ANALYTIC wall from a core shape tree in the flat encoding (Layer 1).
Definition sim.hpp:115
void setMaterialParams(float restitution_normal, float restitution_tangent, float friction)
Definition sim.hpp:400
std::string fusedSweeps() const
Definition sim.hpp:321
void setDomainMinMax(F3 mn, F3 mx)
Definition sim.hpp:169
void setMaterialIds(const std::vector< int > &ids)
Per-particle material ids (0..kMaxMaterials-1); pair (e, mu) values come from setPairMaterial.
Definition sim.hpp:408
const V3 & positionsView() const
Definition sim.hpp:962
void setInvMass(const std::vector< float > &im)
Definition sim.hpp:719
void setScales(const std::vector< float > &s)
Definition sim.hpp:639
void setGrowthParams(float rate, float new_factor)
Definition sim.hpp:735
void setGravity(float gx, float gy, float gz)
Definition sim.hpp:201
void setWallMaterialId(int wid, int mat)
Give an SDF wall a material id so particle-wall (e, mu) also resolves via the pair table.
Definition sim.hpp:439
std::vector< float > wallSdfAt(int wallIndex, const std::vector< float > &pts) const
Definition sim.hpp:552
void setStabilizationMode(const std::string &mode)
Select the stabilization pass of the staged velocity solve: "off" (pure symmetric PGS),...
Definition sim.hpp:224
NB_MODULE(_dem, m)
Input validation of the peclet.dem Python binding (src/dem_bindings.cpp only).
void mpiBox(const std::tuple< double, double, double > &origin, const std::tuple< double, double, double > &extent, const std::tuple< long, long, long > &cells)
init_mpi's global box: finite origin, positive extent, at least one ORB cell per axis.
void materialIds(const std::vector< int > &ids)
void nonnegEach(const char *who, const char *name, const std::array< T, N > &a, const char *dim)
void sampleCounts(const char *who, int rx, int ry, int rz)
A reconstruction grid's samples per axis (get_sdf_grid / export_sdf): each >= 1.
void finiteEach(const char *who, const char *name, const std::array< T, N > &a, const char *dim)
void restitutionCoef(const char *who, const char *name, double v)
A restitution coefficient: [0, 1], dimensionless.
void positive(const char *who, const std::string &name, double v, const char *dim)
void require(bool ok, const char *who, const std::string &name, const std::string &rule, double v)
void positiveEach(const char *who, const char *name, const std::array< T, N > &a, const char *dim)
void poissonRatio(const char *who, const char *name, double v)
An isotropic solid's Poisson ratio: (-1, 0.5], dimensionless.
void finite(const char *who, const std::string &name, double v, const char *dim)
void nonneg(const char *who, const std::string &name, double v, const char *dim)
std::array< float, 3 > F3Arg
A triple: any sequence of three floats (tuple, list, (3,) array).
void domainCorners(const F3Arg &mn, const F3Arg &mx)
set_domain(min, max): finite corners, max > min on every axis.
void plane(const F3Arg &p, const F3Arg &n)
add_plane: a finite point and a finite, non-zero normal.
constexpr int kMaxMaterialId
Material ids index the 8-entry pair tables (narrowphase.hpp kMaxMaterials).
void count(const char *who, const std::string &name, std::int64_t v, std::int64_t lo)
A count (capacity, iterations, samples per axis): an integer >= lo.
void sdfShapeArgs(const char *who, const F3Arg &origin, const F3Arg &spacing, const F3Arg &inv_inertia, float bounding_radius)
The shared arguments of set_sdf_shape / add_sdf_shape.
void writeLammpsDump(const std::string &filename, int step, const std::vector< float > &pos, const std::vector< float > &vel, const std::vector< float > &quat, const std::vector< float > &radii, const float *boxMin, const float *boxMax, bool pbcEnabled)
Definition io.hpp:23
C int MPI_Init(int *a, char ***b)
Definition pmpi.cpp:28
dem — the Simulation facade: the host-facing, binding-agnostic std::vector API the nanobind module (d...