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>
39#include <Kokkos_Core.hpp>
51#include "peclet/core/python/kokkos_teardown.hpp"
52#include "peclet/core/python/ndarray_interop.hpp"
55namespace nb = nanobind;
61using namespace peclet::dem::binding_checks;
63peclet::dem::F3 f3(
const F3Arg& a) {
64 return peclet::dem::F3{a[0], a[1], a[2]};
70using Grid3 = nb::ndarray<float, nb::ndim<3>, nb::f_contig>;
74std::vector<float> to_vec(nb::ndarray<float, nb::c_contig> a) {
75 return peclet::core::python::ndarray_to_vector<float>(nb::ndarray<>(a));
77std::vector<float> grid_to_vec(Grid3 g) {
78 return peclet::core::python::ndarray_to_vector<float>(nb::ndarray<>(g));
84std::vector<float> rows_of(nb::ndarray<float, nb::c_contig> a,
int cols,
const Simulation& s,
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) +
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)");
95std::vector<float> flat_of(nb::ndarray<float, nb::c_contig> a,
const Simulation& s,
98 throw std::invalid_argument(std::string(who) +
": expected an (N,) array");
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)");
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});
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});
119int shape_kind(
const std::string& name,
const char* who) {
120 if (name ==
"sphere")
122 if (name ==
"hollow_cylinder")
126 throw std::invalid_argument(
127 std::string(who) +
": expected 'sphere', 'hollow_cylinder' or 'box', got '" + name +
"'");
139 m.attr(
"__doc__") =
"peclet.dem (Kokkos + ArborX): performance-portable XPBD granular dynamics";
145 peclet::core::python::install(m);
147 nb::class_<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.")
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).")
161 "set_velocity_solver",
162 [](Diagnostics& d,
const std::string& name) {
163 if (name ==
"gauss_seidel")
165 else if (name ==
"jacobi")
168 throw std::invalid_argument(
169 "set_velocity_solver: expected 'gauss_seidel' or 'jacobi', got '" + 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.")
179 return std::string(d.s->
velocityUseGS() ?
"gauss_seidel" :
"jacobi");
181 "'gauss_seidel' or 'jacobi'.")
183 "set_cuda_graphs", [](Diagnostics& d,
bool on) { d.s->
setCudaGraphs(on); },
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.")
189 "cuda_graphs", [](Diagnostics& d) {
return d.s->
cudaGraphs(); },
190 "Whether CUDA-graph replay of the solver loops is enabled.")
193 [](Diagnostics& d,
const std::string& mode) { d.s->
setFusedSweeps(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.")
200 "fused_sweeps", [](Diagnostics& d) {
return d.s->
fusedSweeps(); },
201 "Fused-sweep policy: 'auto', 'on' or 'off'.")
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.")
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.")
212 "multilevel_coloring_conflicts",
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).")
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;
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).")
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).")
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).")
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)));
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.")
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).")
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.")
281 "mpi_gathers", [](Diagnostics& d) {
return d.s->mpiGathers(); },
282 "Cumulative ghost gather() count across distributed steps.")
286 nb::class_<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.")
296 count(
"Simulation",
"capacity", capacity, 0);
300 "Allocate for up to `capacity` particles (owned + periodic ghost slots); set_positions "
304 "diagnostics", [](
Simulation& s) {
return Diagnostics{&s}; }, nb::keep_alive<0, 1>(),
305 "The developer tier (Diagnostics) of this simulation.")
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);
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.")
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);
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.")
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);
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.")
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);
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).")
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);
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.")
396 [](
Simulation& s, nb::ndarray<int, nb::c_contig> ids) {
397 s.
setShapeIds(std::vector<int>(ids.data(), ids.data() + ids.size()));
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).")
414 nb::arg(
"min"), nb::arg(
"max"),
415 "Set the domain by (min, max) corner tuples (arbitrary origin; length units); keeps "
416 "current periodicity.")
425 finiteEach(
"set_domain",
"origin", origin,
"length");
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. "
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).")
436 "Set periodic boundaries per axis (x, y, z); read back with the `periodic` property "
437 "(suite/docs/NAMING.md 1.4).")
439 "The domain's lower corner (x, y, z), in length units — read-only; set it with "
442 "The domain's SIZE (Lx, Ly, Lz), in length units — read-only, and note it is a "
444 "far corner, which is `origin + extent` (suite/docs/NAMING.md 1.1).")
446 "Per-axis periodicity (x, y, z) — read-only; set it with `set_periodic`.")
451 finiteEach(
"set_gravity",
"gravity", g,
"length/time^2");
455 "Set the gravitational acceleration (gx, gy, gz), in length/time^2 units -- any "
456 "sequence of three floats. The default is ZERO.")
458 "The gravitational acceleration (gx, gy, gz), in length/time^2 units.")
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");
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 "
473 "set_solver_iterations",
475 count(
"set_solver_iterations",
"pos", pos, 0);
476 count(
"set_solver_iterations",
"vel", vel, 0);
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).")
483 "set_hertz_material",
484 [](
Simulation& s,
int mat,
float youngs,
float poisson) {
485 positive(
"set_hertz_material",
"youngs", youngs,
"force/area");
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).")
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)");
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 "
510 "The stabilization mode: 'off', 'onesided', 'multilevel' (or a diagnostics "
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 "
525 positive(
"set_global_scale",
"scale", scale,
"dimensionless");
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.")
536 positive(
"set_dt",
"dt", dt,
"time");
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.")
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,
549 nonneg(
"set_material_params",
"friction", friction,
"dimensionless");
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.")
563 [](
Simulation& s,
const std::vector<int>& 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.")
572 [](
Simulation& s,
int a,
int b,
float e,
float mu) {
574 nonneg(
"set_pair_material",
"friction", mu,
"dimensionless");
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.")
581 "set_wall_material_id",
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.")
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,
599 nonneg(
"add_analytic_wall",
"friction", friction,
"dimensionless");
601 std::vector<int>(node_ints.data(), node_ints.data() + node_ints.size()),
602 to_vec(node_reals), root, invert, restitution, friction);
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 "
616 s.
addPlane(p[0], p[1], p[2], n[0], n[1], n[2]);
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 "
627 finiteEach(
"add_sdf_wall",
"origin", origin,
"length");
628 positiveEach(
"add_sdf_wall",
"spacing", spacing,
"length");
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,
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] "
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.")
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");
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 "
661 "by grains in contact even though the geometry is static). Cheap; call every step for a "
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]);
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.")
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);
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);
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];
699 const float w = buf[k * i + 3];
700 im[i] = (w == 0.0f) ? 1.0f : w;
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.")
716 [](
Simulation& s, nb::ndarray<float, nb::c_contig> a) {
719 nb::arg(
"velocities"),
720 "Set particle velocities (length/time units) from an (N, 3) array.")
722 "set_external_forces",
723 [](
Simulation& s, nb::ndarray<float, nb::c_contig> a) {
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.")
731 "Zero all per-particle external forces (force units).")
733 "set_external_torques",
734 [](
Simulation& s, nb::ndarray<float, nb::c_contig> a) {
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.")
746 "Zero all per-particle external torques (and re-enable island sleeping).")
749 [](
Simulation& s, nb::ndarray<float, nb::c_contig> a) {
752 nb::arg(
"quaternions"),
753 "Set particle orientation quaternions (x, y, z, w) from an (N, 4) array.")
755 "set_angular_velocities",
756 [](
Simulation& s, nb::ndarray<float, nb::c_contig> a) {
759 nb::arg(
"angular_velocities"),
760 "Set particle angular velocities (body frame; 1/time units, radians per time) from an "
764 [](
Simulation& s, nb::ndarray<float, nb::c_contig> a) {
767 nb::arg(
"inv_inertia"),
768 "Set the per-particle principal-frame diagonal inverse inertia from an (N, 3) array.")
771 [](
Simulation& s, nb::ndarray<float, nb::c_contig> a) {
774 nb::arg(
"inv_mass"),
"Set per-particle inverse mass, an (N,) array (0 = fixed body).")
776 "set_scales_uniform",
778 positive(
"set_scales_uniform",
"scale", scale,
"dimensionless");
781 nb::arg(
"scale"),
"Set a single uniform scale for all particles.")
784 [](
Simulation& s, nb::ndarray<float, nb::c_contig> a) {
785 s.
setScales(flat_of(a, s,
"set_scales"));
787 nb::arg(
"scales"),
"Set per-particle scales from an (N,) array (the growth target).")
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");
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 "
800 "The current particle growth factor (-1 = growth inactive).")
804 "Return per-particle masses (1 / inverse mass; 0 for fixed bodies) as an (N,) array.")
807 "Return particle positions (length units) as an (N, 3) numpy array.")
810 "Return particle velocities (length/time units) as an (N, 3) numpy array.")
812 "get_angular_velocities",
814 "Return particle angular velocities (body frame; 1/time units) as an (N, 3) numpy "
818 "Return the per-particle principal-frame diagonal inverse inertia as an (N, 3) array.")
821 "Return particle orientation quaternions (x, y, z, w) as an (N, 4) numpy array.")
824 "Return per-particle scales as an (N,) numpy array.")
830 "get_positions_view",
832 return peclet::core::python::view_to_ndarray(Kokkos::subview(
835 "Zero-copy (N,3) device array of positions (NumPy view on host, DLPack/CuPy on GPU).")
837 "get_velocities_view",
839 return peclet::core::python::view_to_ndarray(Kokkos::subview(
842 "Zero-copy (N,3) device array of velocities (NumPy view on host, DLPack/CuPy on GPU).")
844 "get_external_forces_view",
846 return peclet::core::python::view_to_ndarray(Kokkos::subview(
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.")
854 return peclet::core::python::view_to_ndarray(
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.")
861 "Advance `n` XPBD substeps of the time step set by set_dt (raises if set_dt was never "
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).")
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.")
878 "Broad-phase candidate pairs found in the last step (ArborX BVH query).")
881 "Narrow-phase contact manifolds (touching pairs) resolved in the last step.")
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 "
889 "Measure and return the maximum pair interpenetration of the current committed state.")
892 [](
Simulation& s, std::tuple<int, int, int> res) {
893 auto [rx, ry, rz] = res;
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});
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].")
906 [](
Simulation& s,
const std::string& filename, std::tuple<int, int, int> res) {
907 auto [rx, ry, rz] = res;
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.")
914 "Write particle state to a VTP file (ParaView/Ovito).")
916 "Export particle state to a LAMMPS dump file.")
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,
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.")
940 "Number of currently-sleeping real bodies.")
944 nonneg(
"set_verlet_skin",
"skin_frac", skin_frac,
"dimensionless; 0 disables");
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).")
952 "Broadphase-skin fraction of the max grain radius (0 = rebuild every step).")
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.")
959 "Whether incremental (warm-started) coloring is enabled.")
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.")
973 "The narrow-phase shell detection: 'one_way' or 'two_way'.")
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) {
982 mpiBox(origin, extent, cells);
984 MPI_Initialized(&inited);
987 char** argv =
nullptr;
990 s.initMpi(origin, extent, cells, periodic, MPI_COMM_WORLD);
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).")
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);
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 "
1030 .def(
"rebalance", &Simulation::rebalance,
1031 "Re-decompose by particle count and migrate ownership now; returns this rank's new "
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.")
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;
1061 to_vec(radii), pmn, pmx, periodic);
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.");
bool incrementalColoring() const
void relax(int n=1)
n dynamics-free RELAXATION substeps (overlap removal only, no gravity / velocity update): the growth-...
void enablePeriodicity(bool x, bool y, bool z)
void stepHertz(int substeps, float skin_frac)
Advance substeps explicit soft-sphere Hertz-Mindlin steps of the stored dt (device-side loop; the (e,...
std::tuple< float, float, float > domainExtent() const
std::tuple< float, float, float > domainOrigin() const
std::string stabilizationMode() const
bool sleeping() const
True while island sleeping is enabled.
std::string restitutionModel() const
std::tuple< float, float, float > gravity() const
void writeVtp(const std::string &filename) const
std::tuple< bool, bool, bool > domainPeriodic() const
float growthFactor() const
std::string shellDetection() const
void setIncrementalColoring(bool enabled)
Incremental (warm-started) graph colouring of the contact manifolds (default ON): reuse last substep'...
void setShellDetection(const std::string &mode)
Narrow-phase shell detection of the XPBD engine (step / step_mpi / relax / compute_overlaps; the Hert...
float globalScale() const
void clearExternalForces()
void clearExternalTorques()
void exportLammps(const std::string &filename, int step) const
float getGrowthRate() const
void setRestitutionModel(const std::string &model)
Restitution model of the PGS velocity solve: "newton" (default; per-substep restitution with Moreau's...
void step(int n=1)
Advance n XPBD substeps of the stored dt (set_dt first; suite/docs/NAMING.md 1.5).
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).
void setQuaternions(const std::vector< float > &q)
void setFusedSweeps(const std::string &mode)
Fused colour sweeps (CUDA): run a whole sweep — and where eligible the whole adaptive iteration loop ...
std::vector< float > getMasses() const
void setThermostat(float temperature, float tau, float kB)
void setWallTransform(int wallIndex, F3 translation, float qx, float qy, float qz, float qw)
std::vector< float > getInvInertia() const
std::pair< int, int > debugColoringConflicts()
bool velocityUseGS() const
int numAsleep()
Number of currently-sleeping real bodies (diagnostics / tests).
std::vector< float > getVelocities() const
void setPairMaterial(int a, int b, float restitution, float friction)
Set the symmetric pair material (restitution, friction) for material ids (a, b).
std::vector< float > getScales() const
std::pair< int, int > debugColoringLeftovers()
std::tuple< double, float, int > restOrphanStats()
Orphan-account diagnostics: (sum, max, count>0) of the per-body orphaned budget.
peclet::dem::SplitStats debugSplitStats() const
void setVelocityUseGS(bool useGS)
std::vector< float > getQuaternions() const
void setWallVelocity(int wallIndex, F3 linVel, F3 angVel, F3 center)
void exportSdf(const std::string &filename, int rx, int ry, int rz)
void setVerletSkin(float skin_frac)
Verlet-cached impulse broadphase (single-GPU, non-periodic; default OFF).
void setGlobalScale(float s)
void addPlane(float px, float py, float pz, float nx, float ny, float nz)
void setVelocities(const std::vector< float > &v)
int addSdfWall(const std::vector< float > &grid, int nx, int ny, int nz, F3 origin, F3 spacing, float restitution, float friction)
void setPositions(const std::vector< float > &xyz)
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).
void setInvInertia(const std::vector< float > &ii)
const Vf & invMassView() const
void setDt(float dt)
The time step every stepper uses (suite/docs/NAMING.md 1.5).
void setAngularVelocities(const std::vector< float > &w)
const V3 & externalForcesView() const
void setDomainCanonical(F3 extent, F3 origin, bool px, bool py, bool pz)
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...
std::vector< float > getAngularVelocities() const
void setScalesUniform(float s)
std::vector< float > getSdfGrid(int rx, int ry, int rz)
void setCudaGraphs(bool enabled)
CUDA-graph replay of the solver's iteration loops (single-rank CUDA; default ON).
void setExternalTorques(const std::vector< float > &t)
int debugMultilevelColoringConflicts()
void setSolverIterations(int pos, int vel)
const V3 & velocitiesView() const
void setExternalForces(const std::vector< float > &f)
std::vector< float > getPositions() const
std::tuple< double, float, int > restBankStats()
Poisson-restitution diagnostics: (sum, max, count>0) of the committed per-pair owed separation impuls...
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).
void setMaterialParams(float restitution_normal, float restitution_tangent, float friction)
std::string fusedSweeps() const
void setDomainMinMax(F3 mn, F3 mx)
void setMaterialIds(const std::vector< int > &ids)
Per-particle material ids (0..kMaxMaterials-1); pair (e, mu) values come from setPairMaterial.
const V3 & positionsView() const
void setInvMass(const std::vector< float > &im)
void setScales(const std::vector< float > &s)
void setGrowthParams(float rate, float new_factor)
void setGravity(float gx, float gy, float gz)
void setWallMaterialId(int wid, int mat)
Give an SDF wall a material id so particle-wall (e, mu) also resolves via the pair table.
std::vector< float > wallSdfAt(int wallIndex, const std::vector< float > &pts) const
void setStabilizationMode(const std::string &mode)
Select the stabilization pass of the staged velocity solve: "off" (pure symmetric PGS),...
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)
C int MPI_Init(int *a, char ***b)
dem — the Simulation facade: the host-facing, binding-agnostic std::vector API the nanobind module (d...