peclet-dem 1.1.0
Performance-portable XPBD Discrete Element Method (Kokkos + ArborX)
Loading...
Searching...
No Matches
solver_multilevel.hpp
Go to the documentation of this file.
1
33#ifndef DEM_SOLVER_MULTILEVEL_HPP
34#define DEM_SOLVER_MULTILEVEL_HPP
35
36#include <Kokkos_Core.hpp>
37#include <stdexcept>
38#include <utility>
39#include <vector>
40
41#include "contact_preprocessing.hpp" // ManifoldC, colorKey, CpExec/CpMem
42#include "solver_fused.hpp" // demGridBarrier / FusedSweepCtx (fused coarse cycle)
43#include "solver_velocity.hpp" // PGSManifoldSweep
44
45namespace peclet::dem {
46
49inline constexpr int kMlMaxLevels = 10;
50inline constexpr int kMlSlotSkip = 63;
56inline constexpr long long kMlPendingSkipBit = 1ll << 62;
57
60 int numLevels = 0; // coarse levels built (0 = aggregation found nothing)
61 std::vector<int> groupOff; // per level: offset of its group arrays in the group pools
62 std::vector<int> numGroups; // per level: group count
63 std::vector<int> parentOff; // per level: offset of its parent map (from level l-1 ids)
64 std::vector<int> numColors; // per level: colours used by the crossing-manifold coloring
65};
66
68struct MlScratch {
69 Kokkos::View<long long*, CpMem> colorPacked; // per manifold: 6-bit colour slot per level
70 Kokkos::View<int*, CpMem> parent; // packed parent maps (pool, 5*cap)
71 Kokkos::View<float*, CpMem> invMassG; // packed per-group inverse mass (pool, 4*cap)
72 Kokkos::View<float* [3], CpMem> velG; // packed per-group velocity (pool, 4*cap)
73 Kokkos::View<float* [3], CpMem> velG0; // restriction snapshot (pool, 4*cap)
74 Kokkos::View<float*, CpMem> massG; // packed per-group mass accumulator (pool, 4*cap)
75 Kokkos::View<int*, CpMem> grp; // composed REAL-body -> current-level group map
76 Kokkos::View<int*, CpMem> mate; // matching scratch (per group of the finer level)
77 // Rigid 6-DOF aggregates (docs/contact_physics_followups.md §2.3), allocated lazily on the first
78 // multilevel pass with the group pools' extent: per group the origin O_g, the centre offset c_g
79 // (the centre of mass is O_g + c_g), the angular velocity Omega_g and its restriction snapshot,
80 // and the inverse inertia (xx, yy, zz, xy, xz, yz). accD: the build's per-group DOUBLE
81 // accumulators of one level (sum mu, then sum mu x / sum mu e / the six inertia components).
82 // Empty views: the build skips the geometry (no rigid cycle can run on them).
83 Kokkos::View<float* [3], CpMem> originG;
84 Kokkos::View<float* [3], CpMem> comOffG;
85 Kokkos::View<float* [3], CpMem> angG;
86 Kokkos::View<float* [3], CpMem> angG0;
87 Kokkos::View<float* [6], CpMem> invIG;
88 Kokkos::View<double* [7], CpMem> accD;
89};
90
95 Kokkos::View<const float* [3], CpMem> posPred;
96 Kokkos::View<float* [3], CpMem> angVelPred;
97 Kokkos::View<const float* [4], CpMem> quat;
98 Kokkos::View<const float* [3], CpMem> invIc;
99};
100
104 Kokkos::View<const ManifoldC*, CpMem> manifolds;
105 Kokkos::View<const int*, CpMem> realIdx;
106 Kokkos::View<float*, CpMem> lambdaAcc;
107 Kokkos::View<float, CpMem> maxApproach;
108 Kokkos::View<const float*, CpMem> restRel = {};
109};
110
111namespace mldetail {
114KOKKOS_INLINE_FUNCTION float effMass(float invMass) {
115 return 1.0f / Kokkos::fmax(invMass, 1e-30f);
116}
117
127inline constexpr int kGatePersistent = 1;
128inline constexpr int kGateCone = 2;
129inline constexpr int kGateSlip = 4;
130
134KOKKOS_INLINE_FUNCTION bool eligible(const ManifoldC& m, int idx,
135 Kokkos::View<const int*, CpMem> mColor,
136 Kokkos::View<const float*, CpMem> vn0,
137 Kokkos::View<const float* [3], CpMem> vt0,
138 Kokkos::View<const unsigned char*, CpMem> persistent,
139 Kokkos::View<const float* [3], CpMem> posPred, F3 gHat,
140 float qsThr, int gateMask) {
141 if (m.num_points <= 0 || mColor(idx) < 0)
142 return false;
143 if ((gateMask & kGatePersistent) && persistent(idx) == 0)
144 return false;
145 if (Kokkos::fabs(vn0(idx)) > qsThr)
146 return false; // ballistic pair: never aggregated (rebound stays fine + symmetric)
147 if (gateMask & kGateSlip) {
148 // Slip threshold = qsThr. Measured trade-off: a pour-settling bed's load-bearing contacts
149 // slip at 2-8 g dt (a tighter floor excludes them and the bed crushes), while silo bulk
150 // creep slips at <= 8 g dt (so some of it stays in and costs ~7% discharge vs the one-sided
151 // default). The two distributions overlap in g dt units -- no absolute threshold separates
152 // them; a slip-persistence (time-integrated) gate is the identified next refinement.
153 const F3 vt{vt0(idx, 0), vt0(idx, 1), vt0(idx, 2)};
154 if (dot3(vt, vt) > qsThr * qsThr)
155 return false;
156 }
157 if (m.bodyB < 0)
158 return true;
159 if (gateMask & kGateCone) {
160 const F3 dx = sub3(ldF3(posPred, m.bodyA), ldF3(posPred, m.bodyB));
161 const float up = -(dx.x * gHat.x + dx.y * gHat.y + dx.z * gHat.z);
162 return Kokkos::fabs(up) > 0.3f * Kokkos::sqrt(dot3(dx, dx));
163 }
164 return true;
165}
166
168KOKKOS_INLINE_FUNCTION bool canonical(const Kokkos::View<const float* [3], CpMem>& posPred,
169 const Kokkos::View<const int*, CpMem>& realIdx, int slot) {
170 const int r = realIdx(slot);
171 return posPred(slot, 0) == posPred(r, 0) && posPred(slot, 1) == posPred(r, 1) &&
172 posPred(slot, 2) == posPred(r, 2);
173}
174
178template <class VX>
179KOKKOS_INLINE_FUNCTION F3 memberOffset(const VX& posPred, int i,
180 const Kokkos::View<const float* [3], CpMem>& originG,
181 const Kokkos::View<const float* [3], CpMem>& comOffG,
182 int gi) {
183 const F3 e{posPred(i, 0) - originG(gi, 0), posPred(i, 1) - originG(gi, 1),
184 posPred(i, 2) - originG(gi, 2)};
185 return F3{e.x - comOffG(gi, 0), e.y - comOffG(gi, 1), e.z - comOffG(gi, 2)};
186}
187
190KOKKOS_INLINE_FUNCTION F3 spinInertiaTimes(F4 q, F3 invIc, F3 w) {
191 const float ix = 1.0f / Kokkos::fmax(invIc.x, 1e-30f);
192 if (invIc.x == invIc.y && invIc.y == invIc.z)
193 return scale3(w, ix);
194 const float iy = 1.0f / Kokkos::fmax(invIc.y, 1e-30f);
195 const float iz = 1.0f / Kokkos::fmax(invIc.z, 1e-30f);
196 const F3 wl = invRotateVector(q, w);
197 return rotateVector(q, F3{wl.x * ix, wl.y * iy, wl.z * iz});
198}
199
201template <class V6>
202KOKKOS_INLINE_FUNCTION F3 symMul(const V6& S, int g, F3 v) {
203 return F3{S(g, 0) * v.x + S(g, 3) * v.y + S(g, 4) * v.z,
204 S(g, 3) * v.x + S(g, 1) * v.y + S(g, 5) * v.z,
205 S(g, 4) * v.x + S(g, 5) * v.y + S(g, 2) * v.z};
206}
207
209struct D3 {
210 double x, y, z;
211};
212KOKKOS_INLINE_FUNCTION D3 crossD(D3 a, D3 b) {
213 return D3{a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x};
214}
215KOKKOS_INLINE_FUNCTION D3 rotateD(double qx, double qy, double qz, double qw, D3 v) {
216 const D3 qv{qx, qy, qz};
217 const D3 c = crossD(qv, v);
218 const D3 t{2.0 * c.x, 2.0 * c.y, 2.0 * c.z};
219 const D3 c2 = crossD(qv, t);
220 return D3{v.x + t.x * qw + c2.x, v.y + t.y * qw + c2.y, v.z + t.z * qw + c2.z};
221}
222} // namespace mldetail
223
233inline int buildMlLevelGeometry(const MlScratch& S, int off, int ng, int numReal,
234 Kokkos::View<const float* [3], CpMem> posPred,
235 Kokkos::View<const float*, CpMem> invMass,
236 Kokkos::View<const float* [4], CpMem> quat,
237 Kokkos::View<const float* [3], CpMem> invIc) {
238 CpExec space;
239 auto grp = S.grp;
240 auto acc = S.accD;
241 auto O = S.originG;
242 auto C = S.comOffG;
243 auto invIG = S.invIG;
244 const Kokkos::View<const float* [3], CpMem> Oc(S.originG), Cc(S.comOffG);
245 Kokkos::parallel_for(
246 "peclet::dem::ml_geo_reset", Kokkos::RangePolicy<CpExec>(space, 0, ng), KOKKOS_LAMBDA(int g) {
247 for (int c = 0; c < 7; ++c)
248 acc(g, c) = 0.0;
249 });
250 Kokkos::parallel_for(
251 "peclet::dem::ml_geo_origin_accum", Kokkos::RangePolicy<CpExec>(space, 0, numReal),
252 KOKKOS_LAMBDA(int i) {
253 const double mu = static_cast<double>(mldetail::effMass(invMass(i)));
254 const int g = grp(i);
255 Kokkos::atomic_add(&acc(g, 0), mu);
256 for (int c = 0; c < 3; ++c)
257 Kokkos::atomic_add(&acc(g, 1 + c), mu * static_cast<double>(posPred(i, c)));
258 });
259 Kokkos::parallel_for(
260 "peclet::dem::ml_geo_origin", Kokkos::RangePolicy<CpExec>(space, 0, ng),
261 KOKKOS_LAMBDA(int g) {
262 for (int c = 0; c < 3; ++c) {
263 O(off + g, c) = static_cast<float>(acc(g, 1 + c) / acc(g, 0));
264 acc(g, 1 + c) = 0.0;
265 }
266 });
267 Kokkos::parallel_for(
268 "peclet::dem::ml_geo_com_accum", Kokkos::RangePolicy<CpExec>(space, 0, numReal),
269 KOKKOS_LAMBDA(int i) {
270 const double mu = static_cast<double>(mldetail::effMass(invMass(i)));
271 const int g = grp(i);
272 for (int c = 0; c < 3; ++c) {
273 const float e = posPred(i, c) - Oc(off + g, c);
274 Kokkos::atomic_add(&acc(g, 1 + c), mu * static_cast<double>(e));
275 }
276 });
277 Kokkos::parallel_for(
278 "peclet::dem::ml_geo_com", Kokkos::RangePolicy<CpExec>(space, 0, ng), KOKKOS_LAMBDA(int g) {
279 for (int c = 0; c < 3; ++c)
280 C(off + g, c) = static_cast<float>(acc(g, 1 + c) / acc(g, 0));
281 for (int c = 1; c < 7; ++c)
282 acc(g, c) = 0.0;
283 });
284 Kokkos::parallel_for(
285 "peclet::dem::ml_geo_inertia_accum", Kokkos::RangePolicy<CpExec>(space, 0, numReal),
286 KOKKOS_LAMBDA(int i) {
287 const double mu = static_cast<double>(mldetail::effMass(invMass(i)));
288 const int g = grp(i);
289 const F3 df = mldetail::memberOffset(posPred, i, Oc, Cc, off + g);
290 const double dx = df.x, dy = df.y, dz = df.z;
291 const double d2 = dx * dx + dy * dy + dz * dz;
292 double J[6];
293 const double ix = 1.0 / Kokkos::fmax(static_cast<double>(invIc(i, 0)), 1e-30);
294 if (invIc(i, 0) == invIc(i, 1) && invIc(i, 1) == invIc(i, 2)) {
295 J[0] = J[1] = J[2] = ix;
296 J[3] = J[4] = J[5] = 0.0;
297 } else {
298 const double iy = 1.0 / Kokkos::fmax(static_cast<double>(invIc(i, 1)), 1e-30);
299 const double iz = 1.0 / Kokkos::fmax(static_cast<double>(invIc(i, 2)), 1e-30);
300 const double qx = quat(i, 0), qy = quat(i, 1), qz = quat(i, 2), qw = quat(i, 3);
301 // columns J e_k = R diag R^T e_k (R^T = rotation by the conjugate)
302 mldetail::D3 col[3];
303 for (int k = 0; k < 3; ++k) {
304 const mldetail::D3 ek{k == 0 ? 1.0 : 0.0, k == 1 ? 1.0 : 0.0, k == 2 ? 1.0 : 0.0};
305 const mldetail::D3 l = mldetail::rotateD(-qx, -qy, -qz, qw, ek);
306 col[k] = mldetail::rotateD(qx, qy, qz, qw, mldetail::D3{l.x * ix, l.y * iy, l.z * iz});
307 }
308 J[0] = col[0].x;
309 J[1] = col[1].y;
310 J[2] = col[2].z;
311 J[3] = 0.5 * (col[1].x + col[0].y);
312 J[4] = 0.5 * (col[2].x + col[0].z);
313 J[5] = 0.5 * (col[2].y + col[1].z);
314 }
315 Kokkos::atomic_add(&acc(g, 1), J[0] + mu * (d2 - dx * dx));
316 Kokkos::atomic_add(&acc(g, 2), J[1] + mu * (d2 - dy * dy));
317 Kokkos::atomic_add(&acc(g, 3), J[2] + mu * (d2 - dz * dz));
318 Kokkos::atomic_add(&acc(g, 4), J[3] - mu * dx * dy);
319 Kokkos::atomic_add(&acc(g, 5), J[4] - mu * dx * dz);
320 Kokkos::atomic_add(&acc(g, 6), J[5] - mu * dy * dz);
321 });
322 int bad = 0;
323 Kokkos::parallel_reduce(
324 "peclet::dem::ml_geo_invert", Kokkos::RangePolicy<CpExec>(space, 0, ng),
325 KOKKOS_LAMBDA(int g, int& nb) {
326 const double xx = acc(g, 1), yy = acc(g, 2), zz = acc(g, 3);
327 const double xy = acc(g, 4), xz = acc(g, 5), yz = acc(g, 6);
328 const double c00 = yy * zz - yz * yz, c01 = xz * yz - xy * zz, c02 = xy * yz - xz * yy;
329 const double c11 = xx * zz - xz * xz, c12 = xy * xz - xx * yz, c22 = xx * yy - xy * xy;
330 const double det = xx * c00 + xy * c01 + xz * c02;
331 if (!(det > 0.0) || !Kokkos::isfinite(det)) {
332 for (int c = 0; c < 6; ++c)
333 invIG(off + g, c) = 0.0f;
334 ++nb;
335 return;
336 }
337 const double inv = 1.0 / det;
338 invIG(off + g, 0) = static_cast<float>(c00 * inv);
339 invIG(off + g, 1) = static_cast<float>(c11 * inv);
340 invIG(off + g, 2) = static_cast<float>(c22 * inv);
341 invIG(off + g, 3) = static_cast<float>(c01 * inv);
342 invIG(off + g, 4) = static_cast<float>(c02 * inv);
343 invIG(off + g, 5) = static_cast<float>(c12 * inv);
344 },
345 bad);
346#ifndef NDEBUG
347 if (bad > 0)
348 throw std::logic_error("multilevel: a rigid aggregate's inertia is singular (§2.3 step 5)");
349#endif
350 return bad;
351}
352
356 Kokkos::View<const ManifoldC*, CpMem> manifolds;
358 Kokkos::View<const int*, CpMem> mColor;
359 Kokkos::View<const float*, CpMem> vn0;
360 Kokkos::View<const float* [3], CpMem> vt0;
361 Kokkos::View<const unsigned char*, CpMem> persistent;
362 Kokkos::View<const float* [3], CpMem> posPred;
364 float qsThr = 0.0f;
365 int gateMask = 0;
366};
367
374 Kokkos::View<const int*, CpMem> realIdx;
375 Kokkos::View<const float*, CpMem> invMass;
376 Kokkos::View<const unsigned char*, CpMem> asleep;
377 Kokkos::View<int*, CpMem> grp;
378 bool excludeImmovable = false;
379 bool haveAsleep = false;
380
381 KOKKOS_INLINE_FUNCTION bool operator()(int idx, int& gA, int& gB) const {
382 const ManifoldC m = elig.manifolds(idx);
383 if (m.bodyB < 0 || !mldetail::eligible(m, idx, elig.mColor, elig.vn0, elig.vt0, elig.persistent,
384 elig.posPred, elig.gHat, elig.qsThr, elig.gateMask))
385 return false;
386 // Never aggregate an immovable (sleeping / pinned) body: a group carrying its huge
387 // effMass wrecks the coarse-solve conditioning and pins the awake partner. (Gated so
388 // the sleeping-off path is bit-identical.)
389 if (excludeImmovable &&
390 (invMass(realIdx(m.bodyA)) == 0.0f || invMass(realIdx(m.bodyB)) == 0.0f ||
391 (haveAsleep && (asleep(realIdx(m.bodyA)) != 0 || asleep(realIdx(m.bodyB)) != 0))))
392 return false;
393 // Aggregation never crosses a periodic wrap (§2.3): an image slot's position is
394 // shifted, and an aggregate holding it would have no consistent geometry.
395 if (!mldetail::canonical(elig.posPred, realIdx, m.bodyA) ||
397 return false;
398 gA = grp(realIdx(m.bodyA));
399 gB = grp(realIdx(m.bodyB));
400 return gA != gB;
401 }
402};
403
408inline void matchMlLevelGroups(CpExec& space, const MlEligibility& elig,
409 Kokkos::View<const int*, CpMem> realIdx,
410 Kokkos::View<const float*, CpMem> invMass, bool excludeImmovable,
411 Kokkos::View<const unsigned char*, CpMem> asleep, bool haveAsleep,
412 const MlScratch& S, Kokkos::View<long long*, CpMem> winner,
413 int ngPrev) {
414 const MlMatchFilter pairOf{elig, realIdx, invMass, asleep, S.grp, excludeImmovable, haveAsleep};
415 Kokkos::parallel_for(
416 "peclet::dem::ml_match_reset", Kokkos::RangePolicy<CpExec>(space, 0, ngPrev),
417 KOKKOS_LAMBDA(int g) { winner(g) = -1; });
418 Kokkos::parallel_for(
419 "peclet::dem::ml_match_contend", Kokkos::RangePolicy<CpExec>(space, 0, elig.numManifolds),
420 KOKKOS_LAMBDA(int idx) {
421 int gA = 0, gB = 0;
422 if (!pairOf(idx, gA, gB))
423 return;
424 const long long key = colorKey(idx);
425 Kokkos::atomic_max(&winner(gA), key);
426 Kokkos::atomic_max(&winner(gB), key);
427 });
428 auto mate = S.mate;
429 Kokkos::parallel_for(
430 "peclet::dem::ml_mate_init", Kokkos::RangePolicy<CpExec>(space, 0, ngPrev),
431 KOKKOS_LAMBDA(int g) { mate(g) = g; });
432 Kokkos::parallel_for(
433 "peclet::dem::ml_match_commit", Kokkos::RangePolicy<CpExec>(space, 0, elig.numManifolds),
434 KOKKOS_LAMBDA(int idx) {
435 int gA = 0, gB = 0;
436 if (!pairOf(idx, gA, gB))
437 return;
438 const long long key = colorKey(idx);
439 if (winner(gA) == key && winner(gB) == key) { // sole winner of both endpoints
440 mate(gA) = gB;
441 mate(gB) = gA;
442 }
443 });
444}
445
451inline void colorMlLevelManifolds(CpExec& space, const MlEligibility& elig,
452 Kokkos::View<const int*, CpMem> realIdx, const MlScratch& S,
453 const ColorScratch& scratch, int ngNew, int lvl,
454 ContactHierarchy& H) {
455 const Kokkos::View<long long*, CpMem> winner = scratch.bodyWinner;
456 const Kokkos::View<std::uint64_t*, CpMem> colorMask = scratch.bodyColorMask;
457 const auto& manifolds = elig.manifolds;
458 const int numManifolds = elig.numManifolds;
459 const auto& mColor = elig.mColor;
460 const auto& vn0 = elig.vn0;
461 const auto& vt0 = elig.vt0;
462 const auto& persistent = elig.persistent;
463 const auto& posPred = elig.posPred;
464 const auto& gHat = elig.gHat;
465 const auto& qsThr = elig.qsThr;
466 const auto& gateMask = elig.gateMask;
467 auto grp = S.grp;
468 auto cp = S.colorPacked;
469 const int slotShift = 6 * (lvl - 1);
470 Kokkos::parallel_for(
471 "peclet::dem::ml_color_mask_reset", Kokkos::RangePolicy<CpExec>(space, 0, ngNew),
472 KOKKOS_LAMBDA(int g) { colorMask(g) = 0; });
473 // temp per-manifold state via mate-array-free trick: track "uncoloured" in the packed slot
474 // itself (63 = pending here; eligibility recomputed per round).
475 int remaining = 1, prevRemaining = -1, maxc = -1;
476 for (int round = 0; round < 64 && remaining > 0; ++round) {
477 Kokkos::parallel_for(
478 "peclet::dem::ml_color_reset_winner", Kokkos::RangePolicy<CpExec>(space, 0, ngNew),
479 KOKKOS_LAMBDA(int g) { winner(g) = -1; });
480 Kokkos::parallel_for(
481 "peclet::dem::ml_color_contend", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
482 KOKKOS_LAMBDA(int idx) {
483 const ManifoldC m = manifolds(idx);
484 if (!mldetail::eligible(m, idx, mColor, vn0, vt0, persistent, posPred, gHat, qsThr,
485 gateMask))
486 return;
487 if (((cp(idx) >> slotShift) & 63) != kMlSlotSkip || !(cp(idx) & kMlPendingSkipBit))
488 return; // committed (or marked skip) in an earlier round
489 const int gA = grp(realIdx(m.bodyA));
490 const int gB = (m.bodyB >= 0) ? grp(realIdx(m.bodyB)) : -1;
491 if (gB == gA)
492 return; // internal to an aggregate at this level
493 const long long key = colorKey(idx);
494 Kokkos::atomic_max(&winner(gA), key);
495 if (gB >= 0)
496 Kokkos::atomic_max(&winner(gB), key);
497 });
498 int rem = 0;
499 Kokkos::parallel_reduce(
500 "peclet::dem::ml_color_commit", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
501 KOKKOS_LAMBDA(int idx, int& acc) {
502 const ManifoldC m = manifolds(idx);
503 if (!mldetail::eligible(m, idx, mColor, vn0, vt0, persistent, posPred, gHat, qsThr,
504 gateMask))
505 return;
506 if (((cp(idx) >> slotShift) & 63) != kMlSlotSkip || !(cp(idx) & kMlPendingSkipBit))
507 return;
508 const int gA = grp(realIdx(m.bodyA));
509 const int gB = (m.bodyB >= 0) ? grp(realIdx(m.bodyB)) : -1;
510 if (gB == gA)
511 return;
512 const long long key = colorKey(idx);
513 if (winner(gA) != key || (gB >= 0 && winner(gB) != key)) {
514 acc += 1;
515 return;
516 }
517 std::uint64_t forbidden = colorMask(gA);
518 if (gB >= 0)
519 forbidden |= colorMask(gB);
520 int c = 0; // lowest free colour among 0..62; never forced (§4.4)
521 while (c < kMlSlotSkip && ((forbidden >> c) & 1))
522 ++c;
523 if (c == kMlSlotSkip) {
524 cp(idx) &= ~kMlPendingSkipBit; // keeps slot 63: skipped at this level
525 return;
526 }
527 cp(idx) = (cp(idx) & ~(63ll << slotShift)) | (static_cast<long long>(c) << slotShift);
528 const std::uint64_t bit = std::uint64_t(1) << c;
529 colorMask(gA) |= bit;
530 if (gB >= 0)
531 colorMask(gB) |= bit;
532 },
533 rem);
534 space.fence();
535 if (rem == prevRemaining)
536 break; // safety bound: leftovers keep slot 63 and are skipped at this level
537 prevRemaining = rem;
538 remaining = rem;
539 }
540 Kokkos::parallel_for(
541 "peclet::dem::ml_color_clear_skip", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
542 KOKKOS_LAMBDA(int idx) { cp(idx) |= kMlPendingSkipBit; });
543 Kokkos::parallel_reduce(
544 "peclet::dem::ml_color_max", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
545 KOKKOS_LAMBDA(int idx, int& mx) {
546 const int c = static_cast<int>((cp(idx) >> slotShift) & 63);
547 if (c != kMlSlotSkip && c > mx)
548 mx = c;
549 },
550 Kokkos::Max<int>(maxc));
551 space.fence();
552 H.numColors.push_back(maxc + 1);
553}
554
560 const MlEligibility& elig, Kokkos::View<const int*, CpMem> realIdx,
561 Kokkos::View<const float*, CpMem> invMass, int numReal, MlScratch& S,
562 const ColorScratch& scratch, bool excludeImmovable = false,
563 Kokkos::View<const unsigned char*, CpMem> asleep = {}, const MlBodyViews& body = {}) {
564 ContactHierarchy H;
565 CpExec space;
566 if (elig.numManifolds <= 0 || numReal <= 0)
567 return H;
568 // A sleeper carries a small POSITIVE effective inverse mass (heavy but not rigid, so the fine PGS
569 // does not diverge against it), so the invMass==0 test alone no longer identifies it — exclude by
570 // the asleep flag too. Genuinely-pinned bodies (real invMass 0) stay caught by the ==0 branch.
571 const bool haveAsleep = asleep.extent(0) > 0;
572 { // level-0 composed map = identity; packed colours all "skip"
573 auto grp = S.grp;
574 Kokkos::parallel_for(
575 "peclet::dem::ml_grp_init", Kokkos::RangePolicy<CpExec>(space, 0, numReal),
576 KOKKOS_LAMBDA(int i) { grp(i) = i; });
577 auto cp = S.colorPacked;
578 Kokkos::parallel_for(
579 "peclet::dem::ml_packed_init", Kokkos::RangePolicy<CpExec>(space, 0, elig.numManifolds),
580 KOKKOS_LAMBDA(int idx) { cp(idx) = ~0ll; }); // every 6-bit slot = 63 (skip)
581 }
582
583 int ngPrev = numReal; // group count of the finer level (level 0 = real bodies)
584 int parentOff = 0, groupOff = 0;
585 const int parentCap = static_cast<int>(S.parent.extent(0));
586 const int groupCap = static_cast<int>(S.invMassG.extent(0));
587 const bool haveGeometry = S.invIG.extent(0) >= S.invMassG.extent(0) &&
588 static_cast<int>(S.accD.extent(0)) >= numReal &&
589 body.quat.extent(0) > 0 && body.invIc.extent(0) > 0;
590
591 for (int lvl = 1; lvl <= kMlMaxLevels; ++lvl) {
592 if (parentOff + ngPrev > parentCap)
593 break; // pool exhausted (matching stalled repeatedly) -- use what we have
594 // ---- greedy random-priority matching on the current group graph ----
595 matchMlLevelGroups(space, elig, realIdx, invMass, excludeImmovable, asleep, haveAsleep, S,
596 scratch.bodyWinner, ngPrev);
597 // ---- compact new group ids: matched pair -> one id (leader = smaller), singleton keeps ----
598 int ngNew = 0;
599 {
600 auto mate = S.mate;
601 auto parent = S.parent;
602 const int off = parentOff;
603 Kokkos::parallel_scan(
604 "peclet::dem::ml_compact", Kokkos::RangePolicy<CpExec>(space, 0, ngPrev),
605 KOKKOS_LAMBDA(int g, int& run, const bool final) {
606 const bool leader = (mate(g) >= g);
607 if (leader)
608 ++run;
609 if (final && leader)
610 parent(off + g) = run - 1;
611 },
612 ngNew);
613 Kokkos::parallel_for(
614 "peclet::dem::ml_parent_nonleader", Kokkos::RangePolicy<CpExec>(space, 0, ngPrev),
615 KOKKOS_LAMBDA(int g) {
616 if (mate(g) < g)
617 parent(off + g) = parent(off + mate(g));
618 });
619 }
620 if (ngNew >= ngPrev || ngNew > (9 * ngPrev) / 10)
621 break; // matching stalled: deeper levels would not shrink the problem
622 if (groupOff + ngNew > groupCap)
623 break;
624 // ---- compose the body -> group map and record the level ----
625 {
626 auto grp = S.grp;
627 auto parent = S.parent;
628 const int off = parentOff;
629 Kokkos::parallel_for(
630 "peclet::dem::ml_grp_compose", Kokkos::RangePolicy<CpExec>(space, 0, numReal),
631 KOKKOS_LAMBDA(int i) { grp(i) = parent(off + grp(i)); });
632 }
633 // ---- per-group inverse mass ----
634 {
635 auto grp = S.grp;
636 auto massG = S.massG;
637 auto invMassG = S.invMassG;
638 const int off = groupOff;
639 Kokkos::parallel_for(
640 "peclet::dem::ml_mass_reset", Kokkos::RangePolicy<CpExec>(space, 0, ngNew),
641 KOKKOS_LAMBDA(int g) { massG(off + g) = 0.0f; });
642 Kokkos::parallel_for(
643 "peclet::dem::ml_mass_accum", Kokkos::RangePolicy<CpExec>(space, 0, numReal),
644 KOKKOS_LAMBDA(int i) {
645 Kokkos::atomic_add(&massG(off + grp(i)), mldetail::effMass(invMass(i)));
646 });
647 Kokkos::parallel_for(
648 "peclet::dem::ml_mass_invert", Kokkos::RangePolicy<CpExec>(space, 0, ngNew),
649 KOKKOS_LAMBDA(int g) { invMassG(off + g) = 1.0f / massG(off + g); });
650 }
651 // ---- rigid-aggregate geometry of this level (§2.3; the pools are allocated lazily) ----
652 if (haveGeometry)
653 buildMlLevelGeometry(S, groupOff, ngNew, numReal, elig.posPred, invMass, body.quat,
654 body.invIc);
655 // ---- colour the crossing manifolds of this level on the group graph ----
656 colorMlLevelManifolds(space, elig, realIdx, S, scratch, ngNew, lvl, H);
657 H.groupOff.push_back(groupOff);
658 H.numGroups.push_back(ngNew);
659 H.parentOff.push_back(parentOff);
660 H.numLevels = lvl;
661 parentOff += ngPrev;
662 groupOff += ngNew;
663 ngPrev = ngNew;
664 if (ngNew <= 32)
665 break; // coarse enough: a handful of super-bodies solves in one sweep
666 }
667 space.fence();
668 return H;
669}
670
682inline void buildCoarseBuckets(const ContactHierarchy& H, MlScratch& S, int numManifolds,
683 Kokkos::View<int*, CpMem> colorScratch,
684 Kokkos::View<int*, CpMem> perm, Kokkos::View<int*, CpMem> cursor,
685 std::vector<std::vector<int>>& offs) {
686 offs.assign(static_cast<std::size_t>(H.numLevels), {});
687 if (numManifolds <= 0)
688 return;
689 CpExec space;
690 for (int lvl = 1; lvl <= H.numLevels; ++lvl) {
691 const int slotShift = 6 * (lvl - 1);
692 const int nCol = H.numColors[static_cast<std::size_t>(lvl) - 1];
693 auto cp = S.colorPacked;
694 auto cs = colorScratch;
695 Kokkos::parallel_for(
696 "peclet::dem::ml_bucket_colors", Kokkos::RangePolicy<CpExec>(space, 0, numManifolds),
697 KOKKOS_LAMBDA(int idx) {
698 const int c = static_cast<int>((cp(idx) >> slotShift) & 63);
699 cs(idx) = (c < nCol) ? c : -1;
700 });
701 auto seg =
702 Kokkos::subview(perm, Kokkos::pair<int, int>((lvl - 1) * numManifolds, lvl * numManifolds));
703 buildColorBuckets(Kokkos::View<const int*, CpMem>(colorScratch), numManifolds, nCol, seg,
704 cursor, offs[static_cast<std::size_t>(lvl) - 1]);
705 }
706}
707
718 Kokkos::View<const ManifoldC*, CpMem> manifolds;
719 Kokkos::View<const int*, CpMem> realIdx;
720 Kokkos::View<const int*, CpMem> grp;
721 Kokkos::View<float* [3], CpMem> velG;
722 Kokkos::View<const float*, CpMem> invMassG;
723 Kokkos::View<float*, CpMem> lambdaAcc;
724 Kokkos::View<float, CpMem> maxApproach;
725 Kokkos::View<const float*, CpMem> restRel;
726 // the rigid coarse space (§2.3-§2.5)
728 Kokkos::View<const float* [3], CpMem> originG;
729 Kokkos::View<const float* [3], CpMem> comOffG;
730 Kokkos::View<float* [3], CpMem> angG;
731 Kokkos::View<float* [3], CpMem> angG0;
732 Kokkos::View<const float* [6], CpMem> invIG;
733
736 struct Row {
737 int gA, gB;
739 float lenN, vn, sgn, invMA, invMB, w;
740 };
741 KOKKOS_FUNCTION bool row(int idx, int off, Row& r) const {
742 // Poisson release in flight on this pair: the coarse e = 0 solve targets vtil = 0 on
743 // the SHARED accumulator and would retract the just-injected separation velocity —
744 // the releasing contact skips the coarse transport this substep.
745 if (restRel.extent(0) > 0 && restRel(idx) > 0.0f)
746 return false;
747 const ManifoldC m = manifolds(idx);
748 const int gA = grp(realIdx(m.bodyA));
749 const int gB = (m.bodyB >= 0) ? grp(realIdx(m.bodyB)) : -1;
750 const float invN = 1.0f / static_cast<float>(m.num_points);
751 const F3 Nsum{m.normal_sum.x, m.normal_sum.y, m.normal_sum.z};
752 const float lenN = Kokkos::sqrt(dot3(Nsum, Nsum));
753 if (lenN < 1e-9f)
754 return false;
755 const F3 rAavg = scale3(F3{m.rA_sum.x, m.rA_sum.y, m.rA_sum.z}, invN);
756 const F3 rBavg = scale3(F3{m.rB_sum.x, m.rB_sum.y, m.rB_sum.z}, invN);
757 const F3 diffCenters = (gB < 0) ? rAavg : sub3(rAavg, rBavg);
758 const F3 vA{velG(off + gA, 0), velG(off + gA, 1), velG(off + gA, 2)};
759 F3 vB{0, 0, 0};
760 if (gB >= 0)
761 vB = F3{velG(off + gB, 0), velG(off + gB, 1), velG(off + gB, 2)};
762 else
763 vB = scale3(F3{m.wallVel_sum.x, m.wallVel_sum.y, m.wallVel_sum.z}, invN);
764 float vn = dot3(sub3(vA, vB), Nsum);
765 const float alignment = dot3(Nsum, diffCenters);
766 const float sgn = (alignment > 0.0f) ? 1.0f : -1.0f;
767 const float invMA = invMassG(off + gA);
768 const float invMB = (gB >= 0) ? invMassG(off + gB) : 0.0f;
769 float w = dot3(Nsum, Nsum) * (invMA + invMB);
770 // The rigid rows: arms about the aggregates' centres of mass, T_A = TauA + d_A x N and
771 // T_B = TauB - d_B x N (canonical positions: a wrap image's arm is relative to its own centre,
772 // the offset d to the canonical body's group), the rotational terms appended to vn and w.
773 const F3 dA =
774 mldetail::memberOffset(body.posPred, realIdx(m.bodyA), originG, comOffG, off + gA);
775 const F3 TA =
777 const F3 wA{angG(off + gA, 0), angG(off + gA, 1), angG(off + gA, 2)};
778 vn = vn + dot3(TA, wA);
779 F3 TB{0, 0, 0};
780 if (gB >= 0) {
781 const F3 dB =
782 mldetail::memberOffset(body.posPred, realIdx(m.bodyB), originG, comOffG, off + gB);
784 cross3v(dB, Nsum));
785 const F3 wB{angG(off + gB, 0), angG(off + gB, 1), angG(off + gB, 2)};
786 vn = vn + dot3(TB, wB);
787 }
788 w = w + dot3(TA, mldetail::symMul(invIG, off + gA, TA));
789 if (gB >= 0)
790 w = w + dot3(TB, mldetail::symMul(invIG, off + gB, TB));
791 if (w <= 0.0f)
792 return false;
793 r = Row{gA, gB, Nsum, TA, TB, lenN, vn, sgn, invMA, invMB, w};
794 return true;
795 }
796
797 KOKKOS_FUNCTION void solveOne(int idx, int off) const {
798 Row r;
799 if (!row(idx, off, r))
800 return;
801 const int gA = r.gA, gB = r.gB;
802 const float w = r.w, invMA = r.invMA, invMB = r.invMB;
803 const float vtil = r.sgn * r.vn;
804 const float dp = vtil / w; // e = 0: target 0 (pure inelastic support)
805 const float pOld = lambdaAcc(idx);
806 float pNew = pOld + dp;
807 if (pNew < 0.0f)
808 pNew = 0.0f;
809 const float d = pNew - pOld;
810 if (d == 0.0f)
811 return;
812 lambdaAcc(idx) = pNew;
813 Kokkos::atomic_max(&maxApproach(), Kokkos::fabs(d) * w / r.lenN);
814 const float lambda = -r.sgn * d;
815 const F3 J = scale3(r.Nsum, lambda);
816 velG(off + gA, 0) += J.x * invMA;
817 velG(off + gA, 1) += J.y * invMA;
818 velG(off + gA, 2) += J.z * invMA;
819 if (gB >= 0) {
820 velG(off + gB, 0) -= J.x * invMB;
821 velG(off + gB, 1) -= J.y * invMB;
822 velG(off + gB, 2) -= J.z * invMB;
823 }
824 const F3 dwA = mldetail::symMul(invIG, off + gA, scale3(r.TA, lambda));
825 angG(off + gA, 0) += dwA.x;
826 angG(off + gA, 1) += dwA.y;
827 angG(off + gA, 2) += dwA.z;
828 if (gB >= 0) {
829 const F3 dwB = mldetail::symMul(invIG, off + gB, scale3(r.TB, lambda));
830 angG(off + gB, 0) += dwB.x;
831 angG(off + gB, 1) += dwB.y;
832 angG(off + gB, 2) += dwB.z;
833 }
834 }
835
836 // ---- restrict / prolong, rotational part (§2.4), shared by the launch path and the fused
837 // kernel (the translational restriction stays inline in both) ----
839 template <class VV>
840 KOKKOS_FUNCTION void restrictAngular(int i, int off, int g, float m, const VV& velPred) const {
841 const F3 d = mldetail::memberOffset(body.posPred, i, originG, comOffG, off + g);
842 const F3 v{velPred(i, 0), velPred(i, 1), velPred(i, 2)};
843 const F4 q{body.quat(i, 0), body.quat(i, 1), body.quat(i, 2), body.quat(i, 3)};
844 const F3 ic{body.invIc(i, 0), body.invIc(i, 1), body.invIc(i, 2)};
845 const F3 wq{body.angVelPred(i, 0), body.angVelPred(i, 1), body.angVelPred(i, 2)};
846 const F3 L = add3(scale3(cross3v(d, v), m), mldetail::spinInertiaTimes(q, ic, wq));
847 Kokkos::atomic_add(&angG(off + g, 0), L.x);
848 Kokkos::atomic_add(&angG(off + g, 1), L.y);
849 Kokkos::atomic_add(&angG(off + g, 2), L.z);
850 }
851
852 KOKKOS_FUNCTION void normalizeAngular(int gi) const {
853 const F3 L{angG(gi, 0), angG(gi, 1), angG(gi, 2)};
854 const F3 W = mldetail::symMul(invIG, gi, L);
855 angG(gi, 0) = angG0(gi, 0) = W.x;
856 angG(gi, 1) = angG0(gi, 1) = W.y;
857 angG(gi, 2) = angG0(gi, 2) = W.z;
858 }
859
860 template <class VV, class VV0>
861 KOKKOS_FUNCTION void prolongRigid(int i, int off, int g, const VV& velPred,
862 const VV0& velG0) const {
863 const F3 dW{angG(off + g, 0) - angG0(off + g, 0), angG(off + g, 1) - angG0(off + g, 1),
864 angG(off + g, 2) - angG0(off + g, 2)};
865 const F3 d = mldetail::memberOffset(body.posPred, i, originG, comOffG, off + g);
866#if defined(PECLET_DEM_TEST_MUTANT) && PECLET_DEM_TEST_MUTANT == 8
867 const F3 cr{0.0f, 0.0f, 0.0f}; // G-A4 mutant 8: the prolongation drops (Omega - Omega0) x d
868 (void)d;
869#else
870 const F3 cr = cross3v(dW, d);
871#endif
872 velPred(i, 0) += (velG(off + g, 0) - velG0(off + g, 0)) + cr.x;
873 velPred(i, 1) += (velG(off + g, 1) - velG0(off + g, 1)) + cr.y;
874 velPred(i, 2) += (velG(off + g, 2) - velG0(off + g, 2)) + cr.z;
875 body.angVelPred(i, 0) += dW.x;
876 body.angVelPred(i, 1) += dW.y;
877 body.angVelPred(i, 2) += dW.z;
878 }
879};
880
884 const MlBodyViews& body) {
885 return MlCoarseSweep{mv.manifolds,
886 mv.realIdx,
887 Kokkos::View<const int*, CpMem>(S.grp),
888 S.velG,
889 Kokkos::View<const float*, CpMem>(S.invMassG),
890 mv.lambdaAcc,
891 mv.maxApproach,
892 mv.restRel,
893 body,
894 Kokkos::View<const float* [3], CpMem>(S.originG),
895 Kokkos::View<const float* [3], CpMem>(S.comOffG),
896 S.angG,
897 S.angG0,
898 Kokkos::View<const float* [6], CpMem>(S.invIG)};
899}
900
904 int numLevels = 0, numReal = 0, coarseSweeps = 0;
909 int permBase[kMlMaxLevels] = {}; // level's segment base in bkPerm
910 int offsBase[kMlMaxLevels] = {}; // level's colour-offset base in the flat device offs
911};
912
916 Kokkos::View<const int*, CpMem> offsDev;
917 Kokkos::View<unsigned*, CpMem> bar;
919 int maxWork = 0;
920};
921
922#ifdef KOKKOS_ENABLE_CUDA
929__device__ inline void demMlCoarseCycleDevice(
930 const MlCoarseSweep& f, const Kokkos::View<const int*, CpMem>& parent,
931 const Kokkos::View<const float*, CpMem>& invMass,
932 const Kokkos::View<float* [3], CpMem>& velPred, const Kokkos::View<float* [3], CpMem>& velG0,
933 const Kokkos::View<const float*, CpMem>& massG, const Kokkos::View<int*, CpMem>& grpW,
934 const Kokkos::View<const int*, CpMem>& bkPerm, const Kokkos::View<const int*, CpMem>& offsDev,
935 const MlFusedMeta& meta, unsigned* bar, unsigned& k, int tid, int stride) {
936 for (int i = tid; i < meta.numReal; i += stride) // reset the composed map to identity
937 grpW(i) = i;
938 demGridBarrier(bar, k++);
939 for (int lvl = 1; lvl <= meta.numLevels; ++lvl) {
940 const int off = meta.groupOff[lvl - 1], ng = meta.numGroups[lvl - 1];
941 const int pOff = meta.parentOff[lvl - 1], nCol = meta.numColors[lvl - 1];
942 for (int i = tid; i < meta.numReal; i += stride) // compose to this level
943 grpW(i) = parent(pOff + grpW(i));
944 demGridBarrier(bar, k++);
945 for (int g = tid; g < ng; g += stride) { // restrict: reset
946 f.velG(off + g, 0) = f.velG(off + g, 1) = f.velG(off + g, 2) = 0.0f;
947 f.angG(off + g, 0) = f.angG(off + g, 1) = f.angG(off + g, 2) = 0.0f;
948 }
949 demGridBarrier(bar, k++);
950 for (int i = tid; i < meta.numReal; i += stride) { // restrict: momentum accumulate
951 const float m = mldetail::effMass(invMass(i));
952 const int g = grpW(i);
953 Kokkos::atomic_add(&f.velG(off + g, 0), m * velPred(i, 0));
954 Kokkos::atomic_add(&f.velG(off + g, 1), m * velPred(i, 1));
955 Kokkos::atomic_add(&f.velG(off + g, 2), m * velPred(i, 2));
956 f.restrictAngular(i, off, g, m, velPred);
957 }
958 demGridBarrier(bar, k++);
959 for (int g = tid; g < ng; g += stride) { // restrict: normalize + snapshot V0
960 const float invM = 1.0f / massG(off + g);
961 for (int c = 0; c < 3; ++c) {
962 f.velG(off + g, c) *= invM;
963 velG0(off + g, c) = f.velG(off + g, c);
964 }
965 f.normalizeAngular(off + g);
966 }
967 demGridBarrier(bar, k++);
968 for (int s = 0; s < meta.coarseSweeps; ++s)
969 for (int color = 0; color < nCol; ++color) {
970 const int b = offsDev(meta.offsBase[lvl - 1] + color);
971 const int e = offsDev(meta.offsBase[lvl - 1] + color + 1);
972 if (b == e)
973 continue; // empty class: nothing written, no barrier (uniform: same offsets read)
974 for (int i2 = b + tid; i2 < e; i2 += stride)
975 f.solveOne(bkPerm(meta.permBase[lvl - 1] + i2), off);
976 demGridBarrier(bar, k++);
977 }
978 for (int i = tid; i < meta.numReal; i += stride) // prolongate: the rigid motion
979 f.prolongRigid(i, off, grpW(i), velPred, velG0);
980 demGridBarrier(bar, k++);
981 }
982}
983
984__global__ void demFusedCoarseCycleK(
985 MlCoarseSweep f, Kokkos::View<const int*, CpMem> parent,
986 Kokkos::View<const float*, CpMem> invMass, Kokkos::View<float* [3], CpMem> velPred,
987 Kokkos::View<float* [3], CpMem> velG0, Kokkos::View<const float*, CpMem> massG,
988 Kokkos::View<int*, CpMem> grpW, Kokkos::View<const int*, CpMem> bkPerm,
989 Kokkos::View<const int*, CpMem> offsDev, MlFusedMeta meta, unsigned* bar) {
990 const int stride = gridDim.x * blockDim.x;
991 const int tid = blockIdx.x * blockDim.x + threadIdx.x;
992 unsigned k = 0;
993 demMlCoarseCycleDevice(f, parent, invMass, velPred, velG0, massG, grpW, bkPerm, offsDev, meta,
994 bar, k, tid, stride);
995}
996
1002__global__ void demFusedMlLoopK(
1003 PGSManifoldSweep fine, Kokkos::View<const int*, CpMem> vPerm,
1004 Kokkos::View<const int*, CpMem> vOffs, int vCols, MlCoarseSweep f,
1005 Kokkos::View<const int*, CpMem> parent, Kokkos::View<const float*, CpMem> invMass,
1006 Kokkos::View<float* [3], CpMem> velPred, Kokkos::View<float* [3], CpMem> velG0,
1007 Kokkos::View<const float*, CpMem> massG, Kokkos::View<int*, CpMem> grpW,
1008 Kokkos::View<const int*, CpMem> bkPerm, Kokkos::View<const int*, CpMem> offsDev,
1009 MlFusedMeta meta, int maxIters, float tol, float* resQS, unsigned* bar) {
1010 const int stride = gridDim.x * blockDim.x;
1011 const int tid = blockIdx.x * blockDim.x + threadIdx.x;
1012 unsigned k = 0;
1013 for (int it = 0; it < maxIters; ++it) {
1014 if (tid == 0)
1015 *resQS = 0.0f;
1016 demGridBarrier(bar, k++);
1017 for (int c = 0; c < vCols; ++c) { // fine colored smoothing sweep
1018 const int b = vOffs(c), e = vOffs(c + 1);
1019 if (b == e)
1020 continue;
1021 for (int i = b + tid; i < e; i += stride)
1022 fine.solveOne(vPerm(i));
1023 demGridBarrier(bar, k++);
1024 }
1025 demMlCoarseCycleDevice(f, parent, invMass, velPred, velG0, massG, grpW, bkPerm, offsDev, meta,
1026 bar, k, tid, stride);
1027 const float r = *reinterpret_cast<volatile float*>(resQS);
1028 if (r <= tol)
1029 break;
1030 demGridBarrier(bar, k++); // every block has read resQS before the next zero
1031 }
1032}
1033#endif // KOKKOS_ENABLE_CUDA
1034
1035#ifdef KOKKOS_ENABLE_CUDA
1039inline bool demLaunchFusedMlLoop(CpExec& space, const PGSManifoldSweep& fine,
1040 Kokkos::View<const int*, CpMem> vPerm, const FusedSweepCtx& velCtx,
1041 int vCols, const MlManifoldViews& mv,
1042 Kokkos::View<const float*, CpMem> invMass,
1043 Kokkos::View<float* [3], CpMem> velPred, MlScratch& S,
1044 Kokkos::View<const int*, CpMem> bkPerm, const MlFusedCtx& ml,
1045 int maxIters, float tol, const MlBodyViews& body) {
1046 const Kokkos::View<float, CpMem> maxApproachQS = mv.maxApproach;
1047 const int maxGrid =
1048 std::min(demFusedMaxGrid(demFusedMlLoopK), (static_cast<int>(ml.bar.extent(0)) - 1) / 8);
1049 if (maxGrid <= 0 || vCols <= 0 || velCtx.maxBucket <= 0 || ml.maxWork <= 0)
1050 return false;
1051 const MlCoarseSweep f = makeMlCoarseSweep(mv, S, body);
1052 const int work = std::max(velCtx.maxBucket, ml.maxWork);
1053 const int want = (work + kFusedBlock - 1) / kFusedBlock;
1054 const int grid = want < maxGrid ? want : maxGrid;
1055 cudaStream_t str = space.cuda_stream();
1056 cudaMemsetAsync(ml.bar.data(), 0, (static_cast<std::size_t>(grid) * 8 + 1) * sizeof(unsigned),
1057 str);
1058 demFusedMlLoopK<<<grid, kFusedBlock, 0, str>>>(
1059 fine, vPerm, velCtx.offsDev, vCols, f, Kokkos::View<const int*, CpMem>(S.parent), invMass,
1060 velPred, S.velG0, Kokkos::View<const float*, CpMem>(S.massG), S.grp, bkPerm, ml.offsDev,
1061 ml.meta, maxIters, tol, maxApproachQS.data(), ml.bar.data());
1062 return true;
1063}
1064#endif // KOKKOS_ENABLE_CUDA
1065
1071 const std::vector<std::vector<int>>& bkOffs, int numManifolds,
1072 int numReal, int coarseSweeps,
1073 Kokkos::View<int*, CpMem> offsDev,
1074 Kokkos::View<unsigned*, CpMem> bar) {
1075 MlFusedCtx ctx;
1076#ifdef KOKKOS_ENABLE_CUDA
1077 if (H.numLevels <= 0 || H.numLevels > kMlMaxLevels || numReal <= 0)
1078 return ctx;
1079 std::vector<int> flat;
1080 ctx.meta.numLevels = H.numLevels;
1081 ctx.meta.numReal = numReal;
1082 ctx.meta.coarseSweeps = coarseSweeps;
1083 int maxWork = numReal; // compose/restrict/prolongate phases (ng <= numReal always)
1084 for (int lvl = 1; lvl <= H.numLevels; ++lvl) {
1085 const auto& lo = bkOffs[static_cast<std::size_t>(lvl) - 1];
1086 if (lo.size() != static_cast<std::size_t>(H.numColors[lvl - 1]) + 1)
1087 return ctx; // bucket build skipped this level (empty) — keep the launch path
1088 ctx.meta.groupOff[lvl - 1] = H.groupOff[lvl - 1];
1089 ctx.meta.numGroups[lvl - 1] = H.numGroups[lvl - 1];
1090 ctx.meta.parentOff[lvl - 1] = H.parentOff[lvl - 1];
1091 ctx.meta.numColors[lvl - 1] = H.numColors[lvl - 1];
1092 ctx.meta.permBase[lvl - 1] = (lvl - 1) * numManifolds;
1093 ctx.meta.offsBase[lvl - 1] = static_cast<int>(flat.size());
1094 for (std::size_t c = 0; c + 1 < lo.size(); ++c)
1095 maxWork = std::max(maxWork, lo[c + 1] - lo[c]);
1096 flat.insert(flat.end(), lo.begin(), lo.end());
1097 }
1098 if (flat.empty() || flat.size() > offsDev.extent(0))
1099 return ctx;
1100 const Kokkos::View<const int*, Kokkos::HostSpace, Kokkos::MemoryUnmanaged> h(flat.data(),
1101 flat.size());
1102 auto d = Kokkos::subview(offsDev, Kokkos::pair<std::size_t, std::size_t>(0, flat.size()));
1103 Kokkos::deep_copy(space, d, h);
1104 ctx.offsDev = Kokkos::View<const int*, CpMem>(offsDev);
1105 ctx.bar = bar;
1106 ctx.maxWork = maxWork;
1107#else
1108 (void)space;
1109 (void)H;
1110 (void)bkOffs;
1111 (void)numManifolds;
1112 (void)numReal;
1113 (void)coarseSweeps;
1114 (void)offsDev;
1115 (void)bar;
1116#endif
1117 return ctx;
1118}
1119
1120inline void multilevelCoarseCycle(const MlManifoldViews& mv, int numManifolds,
1121 Kokkos::View<const float*, CpMem> invMass,
1122 Kokkos::View<float* [3], CpMem> velPred, int numReal,
1123 const ContactHierarchy& H, MlScratch& S, int coarseSweeps,
1124 const MlBodyViews& body,
1125 const std::vector<std::vector<int>>* bkOffs = nullptr,
1126 Kokkos::View<const int*, CpMem> bkPerm = {},
1127 const MlFusedCtx* fused = nullptr) {
1128 CpExec space;
1129 // coarse colored PGS sweeps: e = 0, shared lambda accumulator (the per-manifold body is
1130 // MlCoarseSweep::solveOne — shared verbatim with the fused kernel)
1131 const MlCoarseSweep fSweep = makeMlCoarseSweep(mv, S, body);
1132#ifdef KOKKOS_ENABLE_CUDA
1133 if (fused && fused->maxWork > 0) {
1134 const int maxGrid = std::min(demFusedMaxGrid(demFusedCoarseCycleK),
1135 (static_cast<int>(fused->bar.extent(0)) - 1) / 8);
1136 if (maxGrid > 0) {
1137 const int want = (fused->maxWork + kFusedBlock - 1) / kFusedBlock;
1138 const int grid = want < maxGrid ? want : maxGrid;
1139 cudaStream_t str = space.cuda_stream();
1140 cudaMemsetAsync(fused->bar.data(), 0,
1141 (static_cast<std::size_t>(grid) * 8 + 1) * sizeof(unsigned), str);
1142 demFusedCoarseCycleK<<<grid, kFusedBlock, 0, str>>>(
1143 fSweep, Kokkos::View<const int*, CpMem>(S.parent), invMass, velPred, S.velG0,
1144 Kokkos::View<const float*, CpMem>(S.massG), S.grp, bkPerm, fused->offsDev, fused->meta,
1145 fused->bar.data());
1146 return;
1147 }
1148 }
1149#else
1150 (void)fused;
1151#endif
1152 { // reset the composed map to identity; each level applies its parent map on top
1153 auto grp = S.grp;
1154 Kokkos::parallel_for(
1155 "peclet::dem::ml_cycle_grp_init", Kokkos::RangePolicy<CpExec>(space, 0, numReal),
1156 KOKKOS_LAMBDA(int i) { grp(i) = i; });
1157 }
1158 for (int lvl = 1; lvl <= H.numLevels; ++lvl) {
1159 const int off = H.groupOff[lvl - 1];
1160 const int ng = H.numGroups[lvl - 1];
1161 const int pOff = H.parentOff[lvl - 1];
1162 const int nCol = H.numColors[lvl - 1];
1163 const int slotShift = 6 * (lvl - 1);
1164 auto grp = S.grp;
1165 { // compose to this level
1166 auto parent = S.parent;
1167 Kokkos::parallel_for(
1168 "peclet::dem::ml_cycle_compose", Kokkos::RangePolicy<CpExec>(space, 0, numReal),
1169 KOKKOS_LAMBDA(int i) { grp(i) = parent(pOff + grp(i)); });
1170 }
1171 { // restrict: V_g = sum(m v) / sum(m) (momentum-conserving), snapshot V0; Omega_g =
1172 // invI_g sum [m d x v + J w] (the M-orthogonal projection onto rigid motions, §2.2)
1173 auto velG = S.velG;
1174 auto velG0 = S.velG0;
1175 auto massG = S.massG;
1176 Kokkos::parallel_for(
1177 "peclet::dem::ml_restrict_reset", Kokkos::RangePolicy<CpExec>(space, 0, ng),
1178 KOKKOS_LAMBDA(int g) {
1179 velG(off + g, 0) = velG(off + g, 1) = velG(off + g, 2) = 0.0f;
1180 fSweep.angG(off + g, 0) = fSweep.angG(off + g, 1) = fSweep.angG(off + g, 2) = 0.0f;
1181 });
1182 Kokkos::parallel_for(
1183 "peclet::dem::ml_restrict_accum", Kokkos::RangePolicy<CpExec>(space, 0, numReal),
1184 KOKKOS_LAMBDA(int i) {
1185 const float m = mldetail::effMass(invMass(i));
1186 const int g = grp(i);
1187 Kokkos::atomic_add(&velG(off + g, 0), m * velPred(i, 0));
1188 Kokkos::atomic_add(&velG(off + g, 1), m * velPred(i, 1));
1189 Kokkos::atomic_add(&velG(off + g, 2), m * velPred(i, 2));
1190 fSweep.restrictAngular(i, off, g, m, velPred);
1191 });
1192 Kokkos::parallel_for(
1193 "peclet::dem::ml_restrict_norm", Kokkos::RangePolicy<CpExec>(space, 0, ng),
1194 KOKKOS_LAMBDA(int g) {
1195 const float invM = 1.0f / massG(off + g);
1196 for (int c = 0; c < 3; ++c) {
1197 velG(off + g, c) *= invM;
1198 velG0(off + g, c) = velG(off + g, c);
1199 }
1200 fSweep.normalizeAngular(off + g);
1201 });
1202 }
1203 for (int s = 0; s < coarseSweeps; ++s) {
1204 for (int color = 0; color < nCol; ++color) {
1205 auto cp = S.colorPacked;
1206 const bool dense = bkOffs != nullptr;
1207 int rb = 0, re = numManifolds;
1208 if (dense) {
1209 const auto& lo = (*bkOffs)[static_cast<std::size_t>(lvl) - 1];
1210 rb = (lvl - 1) * numManifolds + lo[static_cast<std::size_t>(color)];
1211 re = (lvl - 1) * numManifolds + lo[static_cast<std::size_t>(color) + 1];
1212 if (rb == re)
1213 continue;
1214 }
1215 Kokkos::parallel_for(
1216 "peclet::dem::ml_coarse_pgs", Kokkos::RangePolicy<CpExec>(space, rb, re),
1217 KOKKOS_LAMBDA(int i2) {
1218 const int idx = dense ? bkPerm(i2) : i2;
1219 if (!dense && static_cast<int>((cp(idx) >> slotShift) & 63) != color)
1220 return;
1221 fSweep.solveOne(idx, off);
1222 });
1223 }
1224 }
1225 { // prolongate: every member takes its aggregate's rigid motion, dV + dOmega x d, dOmega
1226 auto velG0 = S.velG0;
1227 Kokkos::parallel_for(
1228 "peclet::dem::ml_prolongate", Kokkos::RangePolicy<CpExec>(space, 0, numReal),
1229 KOKKOS_LAMBDA(int i) { fSweep.prolongRigid(i, off, grp(i), velPred, velG0); });
1230 }
1231 }
1232}
1233
1234} // namespace peclet::dem
1235
1236#endif // DEM_SOLVER_MULTILEVEL_HPP
dem — portable (Kokkos) contact->manifold reduction, replacing the thrust-based reduce_contacts_to_ma...
bool eligible(const ManifoldC &m, int idx, Kokkos::View< const int *, CpMem > mColor, Kokkos::View< const float *, CpMem > vn0, Kokkos::View< const float *[3], CpMem > vt0, Kokkos::View< const unsigned char *, CpMem > persistent, Kokkos::View< const float *[3], CpMem > posPred, F3 gHat, float qsThr, int gateMask)
Coarse-eligibility of a manifold: active + base-coloured (non-dup) + quasi-static approach (|vn0| <= ...
float effMass(float invMass)
Effective mass with fixed bodies (invMass == 0) mapped to a huge-but-finite mass so the momentum-weig...
F3 symMul(const V6 &S, int g, F3 v)
Symmetric 3x3 (xx, yy, zz, xy, xz, yz) times v.
F3 spinInertiaTimes(F4 q, F3 invIc, F3 w)
J_q w: the member's world-frame spin inertia R diag(1 / max(invIc, 1e-30)) R^T applied to w (§2....
D3 rotateD(double qx, double qy, double qz, double qw, D3 v)
bool canonical(const Kokkos::View< const float *[3], CpMem > &posPred, const Kokkos::View< const int *, CpMem > &realIdx, int slot)
A slot sits at its canonical body's position, bitwise (false for a periodic image).
F3 memberOffset(const VX &posPred, int i, const Kokkos::View< const float *[3], CpMem > &originG, const Kokkos::View< const float *[3], CpMem > &comOffG, int gi)
Member offset from its group's centre of mass, d_q = fl(fl(x_q - O_g) - c_g) (§2.3 step 2): recompute...
constexpr int kGatePersistent
Optional eligibility gates beyond the quasi-static approach test (a SELECTION, not a sink – impulses ...
constexpr int kMlSlotSkip
F3 cross3v(F3 a, F3 b)
MlCoarseSweep makeMlCoarseSweep(const MlManifoldViews &mv, const MlScratch &S, const MlBodyViews &body)
The coarse sweep over the multilevel scratch + the body views (the rigid views stay empty when the la...
CpExec::memory_space CpMem
void buildCoarseBuckets(const ContactHierarchy &H, MlScratch &S, int numManifolds, Kokkos::View< int *, CpMem > colorScratch, Kokkos::View< int *, CpMem > perm, Kokkos::View< int *, CpMem > cursor, std::vector< std::vector< int > > &offs)
One multilevel stabilization cycle over an already-built hierarchy: fine colored smoothing is the cal...
void buildColorBuckets(Kokkos::View< const int *, CpMem > colorOf, int n, int numColors, Kokkos::View< int *, CpMem > perm, Kokkos::View< int *, CpMem > cursor, std::vector< int > &offs)
Dense colour buckets (numColors <= 64): perm[offs[c] .
F3 invRotateVector(F4 q, F3 v)
F3 ldF3(const V &v, int i)
F3 rotateVector(F4 q, F3 v)
void colorMlLevelManifolds(CpExec &space, const MlEligibility &elig, Kokkos::View< const int *, CpMem > realIdx, const MlScratch &S, const ColorScratch &scratch, int ngNew, int lvl, ContactHierarchy &H)
Colour the crossing manifolds of level lvl (ngNew groups) on the group graph and record the level's c...
float dot3(F3 a, F3 b)
F3 sub3(F3 a, F3 b)
constexpr long long kMlPendingSkipBit
Transient mark of the coarse colouring (docs/contact_solve_framework.md §4.4, "the multilevelcoarse c...
int buildMlLevelGeometry(const MlScratch &S, int off, int ng, int numReal, Kokkos::View< const float *[3], CpMem > posPred, Kokkos::View< const float *, CpMem > invMass, Kokkos::View< const float *[4], CpMem > quat, Kokkos::View< const float *[3], CpMem > invIc)
The per-level geometry of the rigid coarse space (docs/contact_physics_followups.md §2....
Kokkos::DefaultExecutionSpace CpExec
F3 scale3(F3 a, float s)
long long colorKey(int idx)
splitmix32 finalizer: a well-mixed pseudo-random priority per edge index.
F3 add3(F3 a, F3 b)
void multilevelCoarseCycle(const MlManifoldViews &mv, int numManifolds, Kokkos::View< const float *, CpMem > invMass, Kokkos::View< float *[3], CpMem > velPred, int numReal, const ContactHierarchy &H, MlScratch &S, int coarseSweeps, const MlBodyViews &body, const std::vector< std::vector< int > > *bkOffs=nullptr, Kokkos::View< const int *, CpMem > bkPerm={}, const MlFusedCtx *fused=nullptr)
MlFusedCtx demMakeMlFusedCtx(CpExec &space, const ContactHierarchy &H, const std::vector< std::vector< int > > &bkOffs, int numManifolds, int numReal, int coarseSweeps, Kokkos::View< int *, CpMem > offsDev, Kokkos::View< unsigned *, CpMem > bar)
Build the fused-coarse-cycle context from an already-built hierarchy + its dense buckets: flatten the...
constexpr int kMlMaxLevels
6-bit colour slots per level in the packed word; slot value 63 = not crossing / not eligible at that ...
void matchMlLevelGroups(CpExec &space, const MlEligibility &elig, Kokkos::View< const int *, CpMem > realIdx, Kokkos::View< const float *, CpMem > invMass, bool excludeImmovable, Kokkos::View< const unsigned char *, CpMem > asleep, bool haveAsleep, const MlScratch &S, Kokkos::View< long long *, CpMem > winner, int ngPrev)
Greedy random-priority matching on the group graph of the finer level (ngPrev groups,...
ContactHierarchy buildContactHierarchy(const MlEligibility &elig, Kokkos::View< const int *, CpMem > realIdx, Kokkos::View< const float *, CpMem > invMass, int numReal, MlScratch &S, const ColorScratch &scratch, bool excludeImmovable=false, Kokkos::View< const unsigned char *, CpMem > asleep={}, const MlBodyViews &body={})
Build the aggregation hierarchy + per-level crossing-manifold colorings.
dem — fused colour sweeps: one persistent kernel per sweep instead of one kernel launch per colour.
dem — portable (Kokkos) manifold velocity solve (normal restitution impulse).
Per-vertex scratch of the Jones-Plassmann colourings: the round's winning edge key and the committed-...
Kokkos::View< long long *, CpMem > bodyWinner
Kokkos::View< std::uint64_t *, CpMem > bodyColorMask
Host-side description of one built hierarchy (offsets into the packed group pools).
Device-side context for a fused colour sweep: the colour offsets (numColors+1, uploaded from buildCol...
Portable mirror of ManifoldConstraint.
The per-body inputs of the rigid coarse space (§2.3-§2.5): the predicted positions (the member offset...
Kokkos::View< const float *[3], CpMem > posPred
Kokkos::View< const float *[3], CpMem > invIc
Kokkos::View< float *[3], CpMem > angVelPred
Kokkos::View< const float *[4], CpMem > quat
One coarse row, evaluated up to its effective mass (the part solveOne shares with the oracle test's s...
The per-manifold coarse-PGS body (e = 0, shared fine accumulator) lives in MlCoarseSweep so the per-c...
void prolongRigid(int i, int off, int g, const VV &velPred, const VV0 &velG0) const
v_q += (V_g - V0_g) + (Omega_g - Omega0_g) x d_q; w_q += Omega_g - Omega0_g.
bool row(int idx, int off, Row &r) const
Kokkos::View< float *[3], CpMem > velG
Kokkos::View< float *[3], CpMem > angG
Kokkos::View< float *, CpMem > lambdaAcc
Kokkos::View< const ManifoldC *, CpMem > manifolds
Kokkos::View< const float *[3], CpMem > comOffG
Kokkos::View< const int *, CpMem > grp
Kokkos::View< const float *[3], CpMem > originG
Kokkos::View< const int *, CpMem > realIdx
Kokkos::View< const float *, CpMem > restRel
Kokkos::View< const float *[6], CpMem > invIG
Kokkos::View< float *[3], CpMem > angG0
Kokkos::View< const float *, CpMem > invMassG
void normalizeAngular(int gi) const
Omega_g = invI_g L_g, snapshot Omega0_g.
Kokkos::View< float, CpMem > maxApproach
void solveOne(int idx, int off) const
void restrictAngular(int i, int off, int g, float m, const VV &velPred) const
L_g += mu_q (d_q x v_q) + J_q w_q (3 float atomics per member).
The manifolds of a hierarchy build and the inputs of mldetail::eligible (constant over the build): th...
Kokkos::View< const float *[3], CpMem > vt0
Kokkos::View< const unsigned char *, CpMem > persistent
Kokkos::View< const float *, CpMem > vn0
Kokkos::View< const float *[3], CpMem > posPred
Kokkos::View< const int *, CpMem > mColor
Kokkos::View< const ManifoldC *, CpMem > manifolds
Fused-coarse-cycle context: flat per-level colour offsets on device + barrier + meta.
Kokkos::View< unsigned *, CpMem > bar
Kokkos::View< const int *, CpMem > offsDev
Host-POD description of a built hierarchy for the fused coarse-cycle kernel (fixed-size arrays: kerne...
The manifold side of a coarse sweep: the manifolds, their real-body map, the shared impulse accumulat...
Kokkos::View< float, CpMem > maxApproach
Kokkos::View< const ManifoldC *, CpMem > manifolds
Kokkos::View< float *, CpMem > lambdaAcc
Kokkos::View< const float *, CpMem > restRel
Kokkos::View< const int *, CpMem > realIdx
The pair filter of the coarse matching, shared by the bid and the commit kernel of matchMlLevelGroups...
Kokkos::View< const int *, CpMem > realIdx
bool operator()(int idx, int &gA, int &gB) const
Kokkos::View< int *, CpMem > grp
Kokkos::View< const float *, CpMem > invMass
Kokkos::View< const unsigned char *, CpMem > asleep
Device scratch for the multilevel pass, sized once (see Particles::allocate).
Kokkos::View< int *, CpMem > mate
Kokkos::View< float *[3], CpMem > originG
Kokkos::View< float *[3], CpMem > comOffG
Kokkos::View< float *, CpMem > invMassG
Kokkos::View< double *[7], CpMem > accD
Kokkos::View< float *[3], CpMem > angG
Kokkos::View< float *, CpMem > massG
Kokkos::View< float *[3], CpMem > angG0
Kokkos::View< float *[3], CpMem > velG0
Kokkos::View< int *, CpMem > grp
Kokkos::View< long long *, CpMem > colorPacked
Kokkos::View< int *, CpMem > parent
Kokkos::View< float *[6], CpMem > invIG
Kokkos::View< float *[3], CpMem > velG
One full colored PGS sweep.
Double-precision copy of dem_portable's rotateVector (the same formula), for the build.