peclet-dem 1.1.0
Performance-portable XPBD Discrete Element Method (Kokkos + ArborX)
Loading...
Searching...
No Matches
solve_driver_force.hpp
Go to the documentation of this file.
1
34#ifndef DEM_SOLVE_DRIVER_FORCE_HPP
35#define DEM_SOLVE_DRIVER_FORCE_HPP
36
37#include <cstdio>
38#include <cstdlib>
39#include <Kokkos_Core.hpp>
40#include <Kokkos_Sort.hpp>
41#include <stdexcept>
42
43#include "particles.hpp"
44#include "solve_driver.hpp" // findCollisionsGrow, maxOwnedRadius, readInt/readFloat
45#include "solver_hertz.hpp"
46
47namespace peclet::dem {
48
53inline void hertzRebuildPairs(Particles& P, float skin) {
54 CpExec space;
55 Kokkos::deep_copy(space, P.posPred, P.pos); // broadphase reads posPred
56 const int np = findCollisionsGrow(P, skin);
57 const size_t need = P.pairs.extent(0);
58 if (P.hertzXi.extent(0) < need) {
59 P.hertzXi = Kokkos::View<float* [3], CpMem>("hertzXi", need);
60 P.hertzSnPair = Kokkos::View<float*, CpMem>("hertzSnPair", need);
61 P.hertzKeys = Kokkos::View<unsigned long long*, CpMem>("hertzKeys", need);
62 P.hertzPrevKeys = Kokkos::View<unsigned long long*, CpMem>("hertzPrevKeys", need);
63 P.hertzPrevXi = Kokkos::View<float* [3], CpMem>("hertzPrevXi", need);
64 }
65 // keys for the new list + history carry from the previous sorted list
66 {
67 auto pairs = P.pairs;
68 auto keys = P.hertzKeys;
69 auto xi = P.hertzXi;
70 auto pk = P.hertzPrevKeys;
71 auto px = P.hertzPrevXi;
72 auto gid = P.gid;
73 const int pc = P.hertzPrevCount;
74 Kokkos::parallel_for(
75 "peclet::dem::hertz_carry", Kokkos::RangePolicy<CpExec>(space, 0, np),
76 KOKKOS_LAMBDA(int idx) {
77 // Canonical orientation: the lower-gid body first. The Mindlin spring xi is the
78 // tangential displacement of pairs(idx, 0) relative to pairs(idx, 1), so it flips sign
79 // with the order; the two owners of a cross-rank pair (owned slots precede ghosts) and
80 // a rank that received the pair by migration would otherwise hold it in different
81 // orientations, and a gid-keyed carry would hand one of them the wrong sign
82 // (docs/contact_solve_framework.md §12 S21; measured: dP 9e-4 in hertz_shear at the
83 // first drift migration). At np 1 gid == slot and the broad phase already emits
84 // (lower, higher): unchanged.
85 const int a0 = pairs(idx, 0), b0 = pairs(idx, 1);
86 if (gid(a0) > gid(b0)) {
87 pairs(idx, 0) = b0;
88 pairs(idx, 1) = a0;
89 }
90 const unsigned long long k =
91 pairKeyFromGids((unsigned)gid(pairs(idx, 0)), (unsigned)gid(pairs(idx, 1)));
92 keys(idx) = k;
93 const int l = lowerBoundKey(pk, pc, k);
94 const bool hit = (l < pc && pk(l) == k);
95 xi(idx, 0) = hit ? px(l, 0) : 0.0f;
96 xi(idx, 1) = hit ? px(l, 1) : 0.0f;
97 xi(idx, 2) = hit ? px(l, 2) : 0.0f;
98 });
99 }
100 P.hertzNumPairs = np;
101 { // lagged patch-stiffness store: reset at rebuild (one mis-damped step, harmless)
102 auto sn = Kokkos::subview(P.hertzSnPair, Kokkos::pair<int, int>(0, np));
103 Kokkos::deep_copy(space, sn, 0.0f);
104 }
105 Kokkos::deep_copy(space, P.hertzRefPos, P.pos);
106 Kokkos::deep_copy(space, P.hertzDispMax, 0.0f);
107 space.fence();
108}
109
112 const int n = P.hertzNumPairs;
113 if (n < 0)
114 return; // no valid LIVE list (fresh sim, or just after an ownership migration): the prev
115 // store may hold carried history for the coming rebuild — do not wipe it.
116 if (n == 0) {
117 P.hertzPrevCount = 0;
118 return;
119 }
120 CpExec space;
121 const auto rng = Kokkos::pair<int, int>(0, n);
122 auto kd = Kokkos::subview(P.hertzPrevKeys, rng);
123 Kokkos::deep_copy(space, kd, Kokkos::subview(P.hertzKeys, rng));
124 Kokkos::View<int*, CpMem> perm(
125 Kokkos::view_alloc(space, "peclet::dem::hertz_perm", Kokkos::WithoutInitializing), n);
126 Kokkos::parallel_for(
127 "peclet::dem::hertz_iota", Kokkos::RangePolicy<CpExec>(space, 0, n),
128 KOKKOS_LAMBDA(int i) { perm(i) = i; });
129 Kokkos::Experimental::sort_by_key(space, kd, perm);
130 auto xi = P.hertzXi;
131 auto px = P.hertzPrevXi;
132 Kokkos::parallel_for(
133 "peclet::dem::hertz_gather", Kokkos::RangePolicy<CpExec>(space, 0, n), KOKKOS_LAMBDA(int i) {
134 const int j = perm(i);
135 px(i, 0) = xi(j, 0);
136 px(i, 1) = xi(j, 1);
137 px(i, 2) = xi(j, 2);
138 });
139 P.hertzPrevCount = n;
140 space.fence();
141}
142
149 static HertzBodies bodies(const Particles& P) {
150 return HertzBodies{
151 .pos = P.pos, .vel = P.vel, .angVel = P.angVel, .rad = P.rad, .invMass = P.invMass};
152 }
153
154 static HertzShapes shapes(const Particles& P, bool hasShapes) {
155 return HertzShapes{.quat = Kokkos::View<const float* [4], CpMem>(P.quat),
156 .scale = Kokkos::View<const float*, CpMem>(P.scale),
157 .shapeId = P.shapeId,
158 .shapes = P.shapes,
159 .shell = P.shell,
160 .globalScale = P.globalScale,
161 .contactRadiusFrac = P.hertzContactRadiusFrac,
162 .hasShapes = hasShapes};
163 }
165 void rebuild(Particles& P, float skin) const {
166 hertzRebuildPairs(P, skin);
167 if (P.numWalls > 0)
171 }
172 void pairForces(Particles& P, float dt, bool hasShapes) const {
177 P.hertzE,
178 P.hertzNu};
179 if (hasShapes)
180 hertzShapePairForces(P.pairs, P.hertzNumPairs, bodies(P), shapes(P, hasShapes), P.sdfGrid,
181 mat, dt, P.hertzXi, P.hertzSnPair, P.deltaVel, P.deltaAngVel);
182 else
184 P.deltaAngVel, shapes(P, hasShapes));
185 }
186 void wallForces(Particles& P, float dt, bool hasShapes) const {
187 if (P.numWalls > 0 && P.hertzNumWallCand > 0) {
192 P.hertzE,
193 P.hertzNu};
194 const HertzWallState wall{.walls = P.walls,
195 .wallGrid = P.wallGrid,
196 .xiWall = P.hertzXiWall,
197 .maxWalls = Particles::kHertzMaxWalls,
198 .snWall = P.hertzSnWall};
199 hertzWallForces(Kokkos::View<const int*, CpMem>(P.hertzWallCand), P.hertzNumWallCand, wall,
200 bodies(P), mat, dt, P.deltaVel, P.deltaAngVel, shapes(P, hasShapes));
201 }
202 }
203
204 void validate(const Particles& P) const {
206 throw std::runtime_error("step_hertz: periodic domains not supported");
207 if (P.numPlanes > 0)
208 throw std::runtime_error("step_hertz: analytic planes not supported (use an SDF wall)");
210 throw std::runtime_error("step_hertz: too many SDF walls");
211 }
212};
213
217inline void zeroForceScratch(V3 dv, V3 dw, int lo, int hi) {
218 if (hi <= lo)
219 return;
220 CpExec space;
221 Kokkos::parallel_for(
222 "peclet::dem::force_zero_ghost", Kokkos::RangePolicy<CpExec>(space, lo, hi),
223 KOKKOS_LAMBDA(int i) {
224 for (int c = 0; c < 3; ++c) {
225 dv(i, c) = 0.0f;
226 dw(i, c) = 0.0f;
227 }
228 });
229 space.fence();
230}
231
234 static constexpr bool distributed = false;
235 float allMax(float v) const { return v; }
236 float allMin(float v) const { return v; }
237 void gatherGhosts(Particles&) const {}
238 void refreshGhostState(Particles&, bool) const {}
240};
241
244template <class Law, class Hooks>
245inline void demStepForce(Particles& P, float dt, int nsteps, float skinFrac, const Law& law,
246 const Hooks& hooks) {
247 law.validate(P);
248 // world radii of the owned span (a halo gather re-fills owned + ghosts)
250 float minRad = 0.0f;
251 {
252 CpExec space;
253 auto rad = P.rad;
254 float m = 3.4e38f;
255 Kokkos::parallel_reduce(
256 "peclet::dem::hertz_minrad", Kokkos::RangePolicy<CpExec>(space, 0, P.numReal),
257 KOKKOS_LAMBDA(int i, float& acc) {
258 if (rad(i) < acc)
259 acc = rad(i);
260 },
261 Kokkos::Min<float>(m));
262 space.fence();
263 minRad = m;
264 }
265 // Skin off the SMALLEST radius (globally under MPI: every rank must use the same skin, so the
266 // rebuild threshold — and thus the collective gather schedule — is identical): a max-radius skin
267 // inflates every small-grain pair cutoff by the big body's margin (measured ~15x more cached
268 // pairs in the ball-impact case).
269 const float skin = skinFrac * hooks.allMin(minRad);
270 const float rebuildAt = 0.25f * skin * skin; // (skin/2)^2 on |dx|^2
271 const F3 g = P.gravity;
272 // Cache-validity must be a COLLECTIVE decision too: after a migration every rank invalidates,
273 // but a single desynchronised flag would desynchronise the gather below.
274 bool rebuild = hooks.allMax(P.hertzNumPairs < 0 ? 1.0f : 0.0f) > 0.0f;
275 // Non-spherical dispatch: any shape with a point shell routes pairs through the per-point
276 // Hertz kernel and enables orientation integration.
277 bool hasShapes = false;
278 {
279 auto hs = Kokkos::create_mirror_view(P.shapes);
280 Kokkos::deep_copy(hs, P.shapes);
281 for (size_t si = 0; si < hs.extent(0); ++si)
282 if (hs(si).numPoints > 0)
283 hasShapes = true;
284 }
285 static const bool profile = std::getenv("PECLET_DEM_HERTZ_PROFILE") != nullptr;
286 double tPair = 0, tWall = 0, tInt = 0, tRebuild = 0, tCheck = 0;
287 int nRebuilds = 0;
288 Kokkos::Timer timer;
289 for (int k = 0; k < nsteps; ++k) {
290 if (rebuild) {
291 law.commitHistory(P);
292 // Distributed: re-gather the ghost band (pair cutoff + skin) with a fresh topology, THEN
293 // build the rank-local pair list over owned + ghosts. Between rebuilds the Verlet argument
294 // covers the ghosts too: nothing outside the band can reach a cached pair before the next
295 // displacement-triggered rebuild.
296 hooks.gatherGhosts(P);
297 law.rebuild(P, skin);
298 rebuild = false;
299 ++nRebuilds;
300 if (profile) {
301 tRebuild += timer.seconds();
302 timer.reset();
303 }
304 } else {
305 // Ghosts must track their owners every step (positions/velocities changed by integrate).
306 hooks.refreshGhostState(P, hasShapes);
307 }
308 hooks.clearGhostScratch(P); // ghost force/torque slots: accumulated but never consumed
309 law.pairForces(P, dt, hasShapes);
310 if (profile) {
311 tPair += timer.seconds();
312 timer.reset();
313 }
314 law.wallForces(P, dt, hasShapes);
315 if (profile) {
316 tWall += timer.seconds();
317 timer.reset();
318 }
319 hertzIntegrate(P.numReal, P.deltaVel, P.deltaAngVel, P.bodyState(), g, dt, hasShapes);
320 if (profile) {
321 tInt += timer.seconds();
322 timer.reset();
323 }
324 if ((k & 15) == 15 || k == nsteps - 1) {
325 if (hooks.allMax(hertzMaxDisp2(P.numReal, P.pos, P.hertzRefPos)) > rebuildAt)
326 rebuild = true;
327 if (profile) {
328 tCheck += timer.seconds();
329 timer.reset();
330 }
331 }
332 }
333 if (profile)
334 std::printf(
335 "[hertz profile] steps=%d pairs=%d wallcand=%d rebuilds=%d | pair %.3fs wall %.3fs "
336 "integrate %.3fs check %.3fs rebuild %.3fs\n",
337 nsteps, P.hertzNumPairs, P.hertzNumWallCand, nRebuilds, tPair, tWall, tInt, tCheck,
338 tRebuild);
339 CpExec space;
340 Kokkos::deep_copy(space, P.posPred, P.pos); // keep the impulse-path views coherent
341 Kokkos::deep_copy(space, P.velPred, P.vel);
342 space.fence();
343}
344
347inline void demStepHertz(Particles& P, float dt, int nsteps, float skinFrac) {
348 demStepForce(P, dt, nsteps, skinFrac, HertzMindlinLaw{}, SoloForceHooks{});
349}
350
351} // namespace peclet::dem
352
353#endif // DEM_SOLVE_DRIVER_FORCE_HPP
void hertzWallForces(Kokkos::View< const int *, CpMem > candSlots, int numCand, const HertzWallState &wall, const HertzBodies &bodies, const HertzMaterials &mat, float dt, Kokkos::View< float *[3], CpMem > force, Kokkos::View< float *[3], CpMem > torque, const HertzShapes &shp={})
SDF-wall forces (per particle x wall).
int hertzBuildWallCandidates(int numReal, int numWalls, Kokkos::View< const WallSdf *, CpMem > walls, GridView wallGrid, Kokkos::View< const float *[3], CpMem > pos, Kokkos::View< const float *, CpMem > rad, float skin, Kokkos::View< int *, CpMem > outSlots, Kokkos::View< int, CpMem > outCount)
Build the wall candidate list: particles within (radius + skin) of any wall's zero level.
void hertzIntegrate(int numReal, Kokkos::View< float *[3], CpMem > force, Kokkos::View< float *[3], CpMem > torque, const BodyState &bodies, F3 gravity, float dt, bool integrateOrientation=false)
Symplectic-Euler kick-drift (MUSEN-style) + displacement tracking for the Verlet rebuild.
void hertzCommitHistory(Particles &P)
Save the current list (sorted by key) so the NEXT rebuild can carry the history.
void demStepForce(Particles &P, float dt, int nsteps, float skinFrac, const Law &law, const Hooks &hooks)
nsteps explicit force-based DEM steps of size dt with force law Law (see file comment).
Kokkos::View< const float *, CpMem > PairTableView
unsigned long long pairKeyFromGids(unsigned a, unsigned b)
The one 64-bit pair identity every gid-keyed ledger uses (the XPBD persistent-contact and warm-start ...
Kokkos::DefaultExecutionSpace CpExec
void hertzPairForces(Kokkos::View< const int *[2], CpMem > pairs, int numPairs, const HertzBodies &bodies, const HertzMaterials &mat, float dt, Kokkos::View< float *[3], CpMem > xi, Kokkos::View< float *[3], CpMem > force, Kokkos::View< float *[3], CpMem > torque, const HertzShapes &shp={})
Cached-pair forces: overlap from current positions; history resets when a cached pair is currently se...
Kokkos::View< float *[3], CpMem > V3
int findCollisionsGrow(Particles &P, float margin)
Broad phase with an automatically-grown pair buffer.
void hertzRebuildPairs(Particles &P, float skin)
Rebuild the Hertz cached pair list with margin skin, carrying the Mindlin shear history across by pai...
void zeroForceScratch(V3 dv, V3 dw, int lo, int hi)
Zero the force/torque accumulator rows [lo, hi) — under MPI the pair kernels atomically accumulate on...
void hertzShapePairForces(Kokkos::View< const int *[2], CpMem > pairs, int numPairs, const HertzBodies &bodies, const HertzShapes &shp, GridView sdfGrid, const HertzMaterials &mat, float dt, Kokkos::View< float *[3], CpMem > xi, Kokkos::View< float *, CpMem > snPrev, Kokkos::View< float *[3], CpMem > force, Kokkos::View< float *[3], CpMem > torque)
Non-spherical pairs: per-point Hertz springs over A's point shell against B's SDF (the same one-sided...
void demStepHertz(Particles &P, float dt, int nsteps, float skinFrac)
nsteps of the soft-sphere Hertz-Mindlin engine — the single-GPU instantiation of the force-based driv...
void fillWorldRadii(Vf scale, Vf rad, float gs, float bR, int n)
World radii rad(i) = scale(i) * globalScale * baseRadius over [0, n): the owned span before a step,...
float hertzMaxDisp2(int numReal, Kokkos::View< const float *[3], CpMem > pos, Kokkos::View< const float *[3], CpMem > refPos)
Max squared displacement since the last pair build (called only at rebuild checks – keeping this out ...
Kokkos::View< const unsigned char *, CpMem > MatIdView
int lowerBoundKey(const KeysView &keys, int count, unsigned long long key)
lower_bound over a ledger's sorted keys: the first index whose key is >= key (count when none).
dem — portable (Kokkos) particle SoA container: the storage the dem flip pivots on.
dem — the shared contact-solve driver: the full modern velocity + position solve sequence (warm-start...
Soft-sphere Hertz–Mindlin DEM (reference force model) for SPHERES.
The body state a Hertz force launcher reads.
The Hertz–Mindlin contact materials: each body's material id, the optional pair table of (e,...
Hertz–Mindlin force-law policy (the first force law; see file comment).
static HertzShapes shapes(const Particles &P, bool hasShapes)
The shape data a Hertz contact reads (hasShapes false: a sphere-only run).
void wallForces(Particles &P, float dt, bool hasShapes) const
void rebuild(Particles &P, float skin) const
static HertzBodies bodies(const Particles &P)
The body state a Hertz contact reads.
void commitHistory(Particles &P) const
void validate(const Particles &P) const
Engine-support restrictions of this law (probed once per call).
void pairForces(Particles &P, float dt, bool hasShapes) const
What a non-spherical Hertz contact reads: orientation, scale, shape id, the shape registry and its sh...
The SDF walls and their per-(particle, wall) contact history at slot i * maxWalls + wall: the Mindlin...
Kokkos::View< WallSdf *, CpMem > walls
Kokkos::View< float *, CpMem > hertzE
Kokkos::View< float *[3], CpMem > hertzXi
Kokkos::View< unsigned char *, CpMem > materialId
Kokkos::View< int, CpMem > hertzWallCandCount
Kokkos::View< int *[2], CpMem > pairs
Kokkos::View< int *, CpMem > hertzWallCand
Kokkos::View< float, CpMem > hertzDispMax
static constexpr int kHertzMaxWalls
Kokkos::View< float *, CpMem > pairMaterials
Kokkos::View< ShapeDesc *, CpMem > shapes
Kokkos::View< unsigned long long *, CpMem > hertzPrevKeys
Kokkos::View< float *, CpMem > hertzNu
Kokkos::View< unsigned long long *, CpMem > hertzKeys
BodyState bodyState() const
Kokkos::View< float *, CpMem > hertzSnWall
Kokkos::View< float *[3], CpMem > hertzRefPos
Kokkos::View< float *, CpMem > sdfGrid
Kokkos::View< float *, CpMem > hertzSnPair
Kokkos::View< float *, CpMem > wallGrid
Kokkos::View< float *[3], CpMem > shell
Kokkos::View< float *[3], CpMem > hertzXiWall
Kokkos::View< float *[3], CpMem > hertzPrevXi
Single-GPU hooks: no ghosts, reductions are already global. Everything inlines away.
static constexpr bool distributed
void clearGhostScratch(Particles &) const
void gatherGhosts(Particles &) const
void refreshGhostState(Particles &, bool) const