peclet-dem 1.1.0
Performance-portable XPBD Discrete Element Method (Kokkos + ArborX)
Loading...
Searching...
No Matches
mpi_halo.hpp
Go to the documentation of this file.
1
29#ifndef PECLET_DEM_MPI_HALO_HPP
30#define PECLET_DEM_MPI_HALO_HPP
31#ifdef PECLET_DEM_MPI
32
33#include <mpi.h>
34
35#include <algorithm>
36#include <array>
37#include <cmath>
38#include <cstddef>
39#include <cstring>
40#include <Kokkos_Core.hpp>
41#include <limits>
42#include <stdexcept>
43#include <string>
44#include <type_traits>
45#include <unordered_map>
46#include <vector>
47
48#include "dem_portable.hpp" // F3, F4
49#include "particles.hpp" // Particles, V3/V4/Vf/Vi, CpExec/CpMem
50#include "peclet/core/common/types.hpp"
51#include "peclet/core/common/view.hpp"
52#include "peclet/core/decomp/block_decomposer.hpp"
53#include "peclet/core/halo/particle_halo.hpp"
54#include "peclet/core/halo/particle_halo_topology.hpp"
55#include "peclet/core/halo/particle_migrator.hpp"
56#include "peclet/core/halo/particle_rebalance.hpp"
57
58namespace peclet::dem {
59
60// All non-position per-particle state in one record, so the substep gather is a single MPI exchange
61// (latency dominates the host-staged path). Mirrors MpiParticleHalo::GatherPack; positions are
62// forwarded separately (they need the periodic image shift). invMass is its own field here (the
63// CUDA SoA carries it in pos.w; the Kokkos SoA keeps it in a separate array). POD =>
64// MPI_BYTE-copyable.
65struct MpiGatherPack {
66 F3 vel, velPred, angVel, angVelPred, invInertia;
67 F4 quat, quatPred;
68 float scale, invMass;
69 int shape;
70 // Modern-solver state a ghost must mirror from its owner: the global id (persistent-pair keys
71 // are gid-based — local slots are not stable identities across ranks / halo rebuilds), the
72 // material id (the narrowphase reads matId by RAW slot index), and the owner's warm grounded
73 // level (Guendelman support levels; the rank-local propagation sweeps continue from it, so a
74 // support chain crossing a rank boundary stays grounded).
75 int gid;
76 unsigned char material, grounded;
77 // Poisson-restitution orphan account (owner-authoritative; a ghost copy's rank-local credits and
78 // drawdowns are delivered to the owner by the velocity reverse, then the next mirror).
79 float orphan, orphanVPeak;
80};
81
82// One persistent-contact ledger entry carried through an ownership migration: the gid-based pair
83// key plus the previous substep's converged normal / tangential impulses and position-channel
84// load (the warm start + Coulomb-bound carry). POD => MPI_BYTE-copyable.
85struct WarmPairEntry {
86 unsigned long long key;
87 float lambda;
88 float lambdaT[3];
89 float posImpulse;
90 float restBank; // event-level (Poisson) restitution: remaining owed separation impulse
91 float restVPeak; // ... and the event's peak approach speed (> 0 = event active)
92};
93// Per-particle cap on carried pairs (sphere kissing number 12 + wall; lowest-weight entries are
94// dropped beyond it — a dropped entry only costs the receiving rank a cold warm-start there).
95inline constexpr int kWarmCarryMax = 14;
96
97// One force-engine (Hertz–Mindlin) per-pair history entry carried through an ownership migration:
98// the gid-based pair key + the Mindlin shear spring xi. The lagged patch stiffness (snPair) is NOT
99// carried — it resets at every pair-list rebuild anyway, and a migration forces one.
100struct HertzPairEntry {
101 unsigned long long key;
102 float xi[3];
103};
104
105// The committed per-particle state that defines a particle across steps — everything except its
106// position (which drives ownership and travels as the migrator's coordinate) and the predicted /
107// delta / ghost scratch the step rebuilds. This is the payload moved when a particle changes owner
108// during a load re-balance. POD => MPI_BYTE-copyable. Carries the particle's slice of the
109// persistent-contact ledger (each pair rides on BOTH locally owned endpoints; the unpack dedupes
110// by key) plus its grounded level, so a rebalance does not cold-restart the statics force
111// network. After the move the pair's owner under the new topology (ContactOwnership) uses its
112// copy; a non-owner's copy is gathered but never applied or committed, and vanishes after one
113// substep.
114struct MigratePack {
115 F4 quat;
116 F3 vel, angVel, invInertia;
117 float invMass, scale, targetScale;
118 int shapeId;
119 float planeFric0, planeFric1;
120 int gid;
121 int srcRank; // the sending rank: arrivals are re-ordered by it (see the file note)
122 unsigned char materialId, groundedLevel, numWarm, numHertz;
123 float orphan, orphanVPeak; // Poisson orphan account rides with its body across ownership
124 // External force / torque (a coupled run sets them before step_mpi; a drift migration inside
125 // the call must carry them -- docs/contact_solve_framework.md §5.2).
126 F3 extForce, extTorque;
127 WarmPairEntry warm[kWarmCarryMax];
128 // Force-engine (Hertz–Mindlin) history: the particle's slice of the cached pair list's Mindlin
129 // springs plus its per-(particle, wall) shear history + lagged wall patch stiffness.
130 HertzPairEntry hertz[kWarmCarryMax];
131 float hertzXiWall[Particles::kHertzMaxWalls][3];
132 float hertzSnWall[Particles::kHertzMaxWalls];
133};
134
135// Integer periodic image triple, each component in {-1, 0, 1}, packed as sum (c + 1) 4^d; and its
136// negation (the image the partner's owner must hold this body at).
137KOKKOS_INLINE_FUNCTION int imagePack(int x, int y, int z) {
138 return (x + 1) + 4 * (y + 1) + 16 * (z + 1);
139}
140KOKKOS_INLINE_FUNCTION int imageNegate(int p) {
141 const int x = p % 4 - 1, y = (p / 4) % 4 - 1, z = (p / 16) % 4 - 1;
142 return imagePack(-x, -y, -z);
143}
144
145// Which rank solves a contact (docs/mpi_momentum_conservation.md §2.1): EXACTLY ONE of the ranks
146// that see it. On this rank, slots [0, numReal) are owned and the rest are ghosts; for a ghost
147// slot g, ghostSource(g - numReal) is the rank it came from (this rank for a periodic
148// self-ghost); for an owned slot o, copyRanks[copyOffsets(o), copyOffsets(o+1)) are the ranks o
149// is ghosted to (cross-rank only). A contact between an owned o and a ghost g is owned here when
150// the ghost's owner cannot see the pair (it does not hold o as a ghost), else by the owner of the
151// lower-gid body; a body against its own periodic image is never owned. A wall contact belongs to
152// its body's owner. Built by ParticleHalo::contactOwnership over the current topology.
153struct ContactOwnership {
154 int rank;
155 int numReal;
156 Kokkos::View<const int*, CpMem> gid, ghostSource, copyOffsets, copyRanks;
157 // Image-aware (WO-9, §5.3): ghostImage(g - numReal) is the integer periodic image of ghost slot
158 // g, copyImage(k) that of send entry k (packed per axis as image + 1 in base 4). With every image
159 // sent, "the partner's owner sees the pair" means it holds THIS owned body at the opposite image.
160 Kokkos::View<const int*, CpMem> ghostImage, copyImage;
161 // Periodic self-images (a ghost of this rank's own body): selfImage[selfOffsets(o),
162 // selfOffsets(o+1)) are the images at which owned o is held as a self-ghost here.
163 Kokkos::View<const int*, CpMem> selfOffsets, selfImage;
164 KOKKOS_INLINE_FUNCTION bool operator()(const ContactC& c) const {
165 const int a = c.bodyA, b = c.bodyB;
166 if (b < 0)
167 return a < numReal; // wall contact: its body's owner
168 const bool ao = a < numReal, bo = b < numReal;
169 if (ao && bo)
170 return true; // both owned here
171 if (!ao && !bo)
172 return false; // cannot occur (queries come from owned bodies); defensive
173#if defined(PECLET_DEM_TEST_MUTANT) && PECLET_DEM_TEST_MUTANT == 1
174 return false; // G13 mutant 1 (docs/contact_solve_framework.md §9): no cross-rank pair is
175 // solved
176#endif
177 const int o = ao ? a : b, g = ao ? b : a;
178 if (gid(o) == gid(g))
179 return false; // a body against its own periodic image
180 const int s = ghostSource(g - numReal);
181 if (s == rank) {
182 // A self-image contact: its twin (the partner owned here, this body as a self-ghost at the
183 // opposite image) exists only if this rank holds o at that image. A body owned from across
184 // a periodic face (drift slack, §5.1) can have one orientation only -- then this one owns
185 // the pair, as in the cross-rank rule below (§12 S23).
186 const int want = imageNegate(ghostImage(g - numReal));
187 bool twin = false;
188 for (int k = selfOffsets(o); k < selfOffsets(o + 1); ++k)
189 if (selfImage(k) == want) {
190 twin = true;
191 break;
192 }
193 if (!twin)
194 return true;
195 } else {
196 bool partnerSees = false;
197 const int want = imageNegate(ghostImage(g - numReal));
198 for (int k = copyOffsets(o); k < copyOffsets(o + 1); ++k)
199 if (copyRanks(k) == s && copyImage(k) == want) {
200 partnerSees = true;
201 break;
202 }
203 if (!partnerSees)
204 return true; // the partner's owner cannot see this pair
205 }
206 return gid(o) < gid(g); // both owners see it (or a self-image twin): the lower gid's owner
207 }
208};
209
210// Ghost -> owner reverse payloads (docs/mpi_momentum_conservation.md §2.3). A ghost's accumulated
211// change since its baseline -- exactly what this rank's owned contacts wrote into it -- is summed
212// onto its owner by core's ParticleHalo<3>::reverse, which accumulates through
213// Kokkos::atomic_add: that applies the operator+ below. So operator+ SUMS the velocity, angular
214// velocity and orphan-account increments and takes the MAX of orphanPeak (an event peak speed,
215// not an additive quantity). POD => MPI_BYTE-copyable.
216struct VelocityIncrement {
217 float v[3];
218 float w[3];
219 float orphan;
220 float orphanPeak;
221};
222KOKKOS_INLINE_FUNCTION VelocityIncrement operator+(const VelocityIncrement& a,
223 const VelocityIncrement& b) {
224 VelocityIncrement r;
225 for (int d = 0; d < 3; ++d) {
226 r.v[d] = a.v[d] + b.v[d];
227 r.w[d] = a.w[d] + b.w[d];
228 }
229 r.orphan = a.orphan + b.orphan;
230 r.orphanPeak = a.orphanPeak > b.orphanPeak ? a.orphanPeak : b.orphanPeak;
231 return r;
232}
233// Position-phase payload: the predicted-position increment (the projection is translation-only).
234// Summed by core's reverse (Kokkos::atomic_add applies this operator+).
235struct PositionIncrement {
236 float x[3];
237};
238KOKKOS_INLINE_FUNCTION PositionIncrement operator+(const PositionIncrement& a,
239 const PositionIncrement& b) {
240 PositionIncrement r;
241 for (int d = 0; d < 3; ++d)
242 r.x[d] = a.x[d] + b.x[d];
243 return r;
244}
245
246// --- free-function pack/unpack kernels (namespace scope: nvcc forbids KOKKOS_LAMBDA in member fns)
247// ---
248
249inline void haloPackF3(V3 field, peclet::core::View<F3> owned, int n) {
250 Kokkos::parallel_for(
251 "peclet::dem::halo::packF3", Kokkos::RangePolicy<CpExec>(0, n),
252 KOKKOS_LAMBDA(int i) { owned(i) = F3{field(i, 0), field(i, 1), field(i, 2)}; });
253}
254inline void haloPackF4(V4 field, peclet::core::View<F4> owned, int n) {
255 Kokkos::parallel_for(
256 "peclet::dem::halo::packF4", Kokkos::RangePolicy<CpExec>(0, n),
257 KOKKOS_LAMBDA(int i) { owned(i) = F4{field(i, 0), field(i, 1), field(i, 2), field(i, 3)}; });
258}
259// The ghost slots a ghost kernel visits: topology ghost g in [0, ng) lives at the canonical SoA
260// slot no + slot(g) (no = the owned count).
261struct GhostRange {
262 Vi slot;
263 int no;
264 int ng;
265};
266
267// ghost[g] -> field(no+slot(g),:), optionally adding the per-ghost periodic image shift (positions
268// only). `slot` maps the topology's ghost index (message-arrival block order) to the canonical
269// slot (ascending source rank); shift stays indexed by the topology's g.
270inline void haloUnpackF3(V3 field, peclet::core::View<F3> ghost, peclet::core::View<F3> shift,
271 const GhostRange& ghosts, bool doShift) {
272 const Vi slot = ghosts.slot;
273 const int no = ghosts.no;
274 const int ng = ghosts.ng;
275 Kokkos::parallel_for(
276 "peclet::dem::halo::unpackF3", Kokkos::RangePolicy<CpExec>(0, ng), KOKKOS_LAMBDA(int g) {
277 F3 v = ghost(g);
278 if (doShift) {
279 v.x += shift(g).x;
280 v.y += shift(g).y;
281 v.z += shift(g).z;
282 }
283 const int s = no + slot(g);
284 field(s, 0) = v.x;
285 field(s, 1) = v.y;
286 field(s, 2) = v.z;
287 });
288}
289inline void haloUnpackF4(V4 field, peclet::core::View<F4> ghost, const GhostRange& ghosts) {
290 const Vi slot = ghosts.slot;
291 const int no = ghosts.no;
292 const int ng = ghosts.ng;
293 Kokkos::parallel_for(
294 "peclet::dem::halo::unpackF4", Kokkos::RangePolicy<CpExec>(0, ng), KOKKOS_LAMBDA(int g) {
295 const int s = no + slot(g);
296 field(s, 0) = ghost(g).x;
297 field(s, 1) = ghost(g).y;
298 field(s, 2) = ghost(g).z;
299 field(s, 3) = ghost(g).w;
300 });
301}
302
303inline void haloPackGather(const BodyState& body, const BodyPred& pred, Vi gid,
304 Kokkos::View<unsigned char*, CpMem> materialId,
305 Kokkos::View<unsigned char*, CpMem> grounded, Vf orphan, Vf orphanVPeak,
306 peclet::core::View<MpiGatherPack> owned, int n) {
307 const V3 vel = body.vel;
308 const V3 velPred = pred.velPred;
309 const V3 angVel = body.angVel;
310 const V3 angVelPred = pred.angVelPred;
311 const V3 invInertia = body.invInertia;
312 const V4 quat = body.quat;
313 const V4 quatPred = pred.quatPred;
314 const Vf scale = body.scale;
315 const Vf invMass = body.invMass;
316 const Vi shapeId = body.shapeId;
317 Kokkos::parallel_for(
318 "peclet::dem::halo::packGather", Kokkos::RangePolicy<CpExec>(0, n), KOKKOS_LAMBDA(int i) {
319 MpiGatherPack g;
320 g.vel = F3{vel(i, 0), vel(i, 1), vel(i, 2)};
321 g.velPred = F3{velPred(i, 0), velPred(i, 1), velPred(i, 2)};
322 g.angVel = F3{angVel(i, 0), angVel(i, 1), angVel(i, 2)};
323 g.angVelPred = F3{angVelPred(i, 0), angVelPred(i, 1), angVelPred(i, 2)};
324 g.invInertia = F3{invInertia(i, 0), invInertia(i, 1), invInertia(i, 2)};
325 g.quat = F4{quat(i, 0), quat(i, 1), quat(i, 2), quat(i, 3)};
326 g.quatPred = F4{quatPred(i, 0), quatPred(i, 1), quatPred(i, 2), quatPred(i, 3)};
327 g.scale = scale(i);
328 g.invMass = invMass(i);
329 g.shape = shapeId(i);
330 g.gid = gid(i);
331 g.material = materialId(i);
332 g.grounded = grounded(i);
333 g.orphan = orphan(i);
334 g.orphanVPeak = orphanVPeak(i);
335 owned(i) = g;
336 });
337}
338// Unpack the gathered owner state into the ghost slots [no, no+ng) (ghost g -> slot no+slot(g), as
339// in haloUnpackF3) and self-map realIndices (the owner is remote: velocity/position changes
340// landing on the ghost slot are delivered to it by the next reconciliation's reverse).
341inline void haloUnpackGather(const BodyState& body, const BodyPred& pred, Vi realIndices, Vi gid,
342 Kokkos::View<unsigned char*, CpMem> materialId,
343 Kokkos::View<unsigned char*, CpMem> grounded, Vf orphan,
344 Vf orphanVPeak, peclet::core::View<MpiGatherPack> ghost,
345 const GhostRange& ghosts) {
346 const Vi slot = ghosts.slot;
347 const int no = ghosts.no;
348 const int ng = ghosts.ng;
349 const V3 vel = body.vel;
350 const V3 velPred = pred.velPred;
351 const V3 angVel = body.angVel;
352 const V3 angVelPred = pred.angVelPred;
353 const V3 invInertia = body.invInertia;
354 const V4 quat = body.quat;
355 const V4 quatPred = pred.quatPred;
356 const Vf scale = body.scale;
357 const Vf invMass = body.invMass;
358 const Vi shapeId = body.shapeId;
359 Kokkos::parallel_for(
360 "peclet::dem::halo::unpackGather", Kokkos::RangePolicy<CpExec>(0, ng), KOKKOS_LAMBDA(int g) {
361 const MpiGatherPack p = ghost(g);
362 const int s = no + slot(g);
363 vel(s, 0) = p.vel.x;
364 vel(s, 1) = p.vel.y;
365 vel(s, 2) = p.vel.z;
366 velPred(s, 0) = p.velPred.x;
367 velPred(s, 1) = p.velPred.y;
368 velPred(s, 2) = p.velPred.z;
369 angVel(s, 0) = p.angVel.x;
370 angVel(s, 1) = p.angVel.y;
371 angVel(s, 2) = p.angVel.z;
372 angVelPred(s, 0) = p.angVelPred.x;
373 angVelPred(s, 1) = p.angVelPred.y;
374 angVelPred(s, 2) = p.angVelPred.z;
375 invInertia(s, 0) = p.invInertia.x;
376 invInertia(s, 1) = p.invInertia.y;
377 invInertia(s, 2) = p.invInertia.z;
378 quat(s, 0) = p.quat.x;
379 quat(s, 1) = p.quat.y;
380 quat(s, 2) = p.quat.z;
381 quat(s, 3) = p.quat.w;
382 quatPred(s, 0) = p.quatPred.x;
383 quatPred(s, 1) = p.quatPred.y;
384 quatPred(s, 2) = p.quatPred.z;
385 quatPred(s, 3) = p.quatPred.w;
386 scale(s) = p.scale;
387 invMass(s) = p.invMass;
388 shapeId(s) = p.shape;
389 realIndices(s) = s;
390 gid(s) = p.gid;
391 materialId(s) = p.material;
392 grounded(s) = p.grounded;
393 orphan(s) = p.orphan;
394 orphanVPeak(s) = p.orphanVPeak;
395 });
396}
397
398// --- ghost -> owner reconciliation kernels (docs/mpi_momentum_conservation.md §2.3). In every
399// ghost kernel g in [0, ng) is the TOPOLOGY ghost index (the order core's forward/reverse use) and
400// s = no + slot(g) its canonical SoA slot. ---
401
402// The velocity phase's per-slot state that the halo kernels read and write: the predicted
403// linear / angular velocity, the orphan account B and its peak. The ghosts' baselines of the same
404// four quantities (indexed by topology ghost g) travel in one too.
405struct VelocityPhaseViews {
406 V3 velPred;
407 V3 angVelPred;
408 Vf orphan;
409 Vf orphanPeak;
410};
411
412// Velocity baselines: base*(g) = the ghost slot's current value.
413inline void haloMarkVelocityBaseline(const VelocityPhaseViews& vel, const VelocityPhaseViews& base,
414 const GhostRange& ghosts) {
415 const Vi slot = ghosts.slot;
416 const int no = ghosts.no;
417 const int ng = ghosts.ng;
418 const V3 velPred = vel.velPred;
419 const V3 angVelPred = vel.angVelPred;
420 const Vf orphan = vel.orphan;
421 const Vf orphanPeak = vel.orphanPeak;
422 const V3 baseV = base.velPred;
423 const V3 baseW = base.angVelPred;
424 const Vf baseO = base.orphan;
425 const Vf basePk = base.orphanPeak;
426 Kokkos::parallel_for(
427 "peclet::dem::halo::markVelBase", Kokkos::RangePolicy<CpExec>(0, ng), KOKKOS_LAMBDA(int g) {
428 const int s = no + slot(g);
429 for (int d = 0; d < 3; ++d) {
430 baseV(g, d) = velPred(s, d);
431 baseW(g, d) = angVelPred(s, d);
432 }
433 baseO(g) = orphan(s);
434 basePk(g) = orphanPeak(s);
435 });
436}
437// inc(g) = ghost slot - baseline, component-wise; the peak travels only if it rose above its
438// baseline (else 0), so a decayed owner peak is never undone.
439inline void haloPackVelocityIncrement(const VelocityPhaseViews& vel, const VelocityPhaseViews& base,
440 peclet::core::View<VelocityIncrement> inc,
441 const GhostRange& ghosts) {
442 const Vi slot = ghosts.slot;
443 const int no = ghosts.no;
444 const int ng = ghosts.ng;
445 const V3 velPred = vel.velPred;
446 const V3 angVelPred = vel.angVelPred;
447 const Vf orphan = vel.orphan;
448 const Vf orphanPeak = vel.orphanPeak;
449 const V3 baseV = base.velPred;
450 const V3 baseW = base.angVelPred;
451 const Vf baseO = base.orphan;
452 const Vf basePk = base.orphanPeak;
453 Kokkos::parallel_for(
454 "peclet::dem::halo::packVelInc", Kokkos::RangePolicy<CpExec>(0, ng), KOKKOS_LAMBDA(int g) {
455 const int s = no + slot(g);
456 VelocityIncrement r;
457 for (int d = 0; d < 3; ++d) {
458 r.v[d] = velPred(s, d) - baseV(g, d);
459 r.w[d] = angVelPred(s, d) - baseW(g, d);
460 }
461 r.orphan = orphan(s) - baseO(g);
462 r.orphanPeak = orphanPeak(s) > basePk(g) ? orphanPeak(s) : 0.0f;
463 inc(g) = r;
464 });
465}
466// Owned rows [0, no) take the summed increments of all their ghost copies.
467inline void haloApplyVelocityIncrement(const VelocityPhaseViews& vel,
468 peclet::core::View<VelocityIncrement> ownedInc, int no) {
469 const V3 velPred = vel.velPred;
470 const V3 angVelPred = vel.angVelPred;
471 const Vf orphan = vel.orphan;
472 const Vf orphanPeak = vel.orphanPeak;
473 Kokkos::parallel_for(
474 "peclet::dem::halo::applyVelInc", Kokkos::RangePolicy<CpExec>(0, no), KOKKOS_LAMBDA(int i) {
475 const VelocityIncrement r = ownedInc(i);
476 for (int d = 0; d < 3; ++d) {
477 velPred(i, d) += r.v[d];
478 angVelPred(i, d) += r.w[d];
479 }
480 orphan(i) = Kokkos::fmax(0.0f, orphan(i) + r.orphan);
481 orphanPeak(i) = Kokkos::fmax(orphanPeak(i), r.orphanPeak);
482 });
483}
484inline void haloMarkPositionBaseline(V3 posPred, V3 baseX, const GhostRange& ghosts) {
485 const Vi slot = ghosts.slot;
486 const int no = ghosts.no;
487 const int ng = ghosts.ng;
488 Kokkos::parallel_for(
489 "peclet::dem::halo::markPosBase", Kokkos::RangePolicy<CpExec>(0, ng), KOKKOS_LAMBDA(int g) {
490 const int s = no + slot(g);
491 for (int d = 0; d < 3; ++d)
492 baseX(g, d) = posPred(s, d);
493 });
494}
495// A position increment is a difference of two values in one image frame, so it needs no periodic
496// shift on its way to the owner.
497inline void haloPackPositionIncrement(V3 posPred, V3 baseX,
498 peclet::core::View<PositionIncrement> inc,
499 const GhostRange& ghosts) {
500 const Vi slot = ghosts.slot;
501 const int no = ghosts.no;
502 const int ng = ghosts.ng;
503 Kokkos::parallel_for(
504 "peclet::dem::halo::packPosInc", Kokkos::RangePolicy<CpExec>(0, ng), KOKKOS_LAMBDA(int g) {
505 const int s = no + slot(g);
506 PositionIncrement r;
507 for (int d = 0; d < 3; ++d)
508 r.x[d] = posPred(s, d) - baseX(g, d);
509 inc(g) = r;
510 });
511}
512inline void haloApplyPositionIncrement(V3 posPred, peclet::core::View<PositionIncrement> ownedInc,
513 int no) {
514 Kokkos::parallel_for(
515 "peclet::dem::halo::applyPosInc", Kokkos::RangePolicy<CpExec>(0, no), KOKKOS_LAMBDA(int i) {
516 const PositionIncrement r = ownedInc(i);
517 for (int d = 0; d < 3; ++d)
518 posPred(i, d) += r.x[d];
519 });
520}
521// The legacy-friction contact count, column 1 of planeFriction: ghost -> owner sum, then back.
522inline void haloPackGhostColumn(Kokkos::View<float* [2], CpMem> pf,
523 peclet::core::View<float> ghostVal, const GhostRange& ghosts) {
524 const Vi slot = ghosts.slot;
525 const int no = ghosts.no;
526 const int ng = ghosts.ng;
527 Kokkos::parallel_for(
528 "peclet::dem::halo::packGhostCol", Kokkos::RangePolicy<CpExec>(0, ng),
529 KOKKOS_LAMBDA(int g) { ghostVal(g) = pf(no + slot(g), 1); });
530}
531inline void haloAddOwnedColumn(Kokkos::View<float* [2], CpMem> pf,
532 peclet::core::View<float> ownedVal, int no) {
533 Kokkos::parallel_for(
534 "peclet::dem::halo::addOwnedCol", Kokkos::RangePolicy<CpExec>(0, no),
535 KOKKOS_LAMBDA(int i) { pf(i, 1) += ownedVal(i); });
536}
537inline void haloPackOwnedColumn(Kokkos::View<float* [2], CpMem> pf,
538 peclet::core::View<float> ownedVal, int no) {
539 Kokkos::parallel_for(
540 "peclet::dem::halo::packOwnedCol", Kokkos::RangePolicy<CpExec>(0, no),
541 KOKKOS_LAMBDA(int i) { ownedVal(i) = pf(i, 1); });
542}
543inline void haloUnpackGhostColumn(Kokkos::View<float* [2], CpMem> pf,
544 peclet::core::View<float> ghostVal, const GhostRange& ghosts) {
545 const Vi slot = ghosts.slot;
546 const int no = ghosts.no;
547 const int ng = ghosts.ng;
548 Kokkos::parallel_for(
549 "peclet::dem::halo::unpackGhostCol", Kokkos::RangePolicy<CpExec>(0, ng),
550 KOKKOS_LAMBDA(int g) { pf(no + slot(g), 1) = ghostVal(g); });
551}
552// The Jacobi count-averaging counts (constraintCounts: per body slot, the contacts this rank
553// solved at it): ghost -> owner sum, then back. Integers, so the sum is exact in any order.
554inline void haloPackGhostCount(Vi counts, peclet::core::View<int> ghostCnt,
555 const GhostRange& ghosts) {
556 const Vi slot = ghosts.slot;
557 const int no = ghosts.no;
558 const int ng = ghosts.ng;
559 Kokkos::parallel_for(
560 "peclet::dem::halo::packGhostCount", Kokkos::RangePolicy<CpExec>(0, ng),
561 KOKKOS_LAMBDA(int g) { ghostCnt(g) = counts(no + slot(g)); });
562}
563inline void haloAddPackOwnedCount(Vi counts, peclet::core::View<int> ownedCnt, int no) {
564 Kokkos::parallel_for(
565 "peclet::dem::halo::addPackOwnedCount", Kokkos::RangePolicy<CpExec>(0, no),
566 KOKKOS_LAMBDA(int i) {
567 counts(i) += ownedCnt(i);
568 ownedCnt(i) = counts(i);
569 });
570}
571inline void haloUnpackGhostCount(Vi counts, peclet::core::View<int> ghostCnt,
572 const GhostRange& ghosts) {
573 const Vi slot = ghosts.slot;
574 const int no = ghosts.no;
575 const int ng = ghosts.ng;
576 Kokkos::parallel_for(
577 "peclet::dem::halo::unpackGhostCount", Kokkos::RangePolicy<CpExec>(0, ng),
578 KOKKOS_LAMBDA(int g) { counts(no + slot(g)) = ghostCnt(g); });
579}
580
581// --- fused owner -> ghost forwards (WO-5): one exchange instead of two when rotation is forwarded.
582// Pure copies (plus the same float shift add as haloUnpackF3), so bit-identical to the separate
583// forwards. POD => MPI_BYTE-copyable. ---
584struct VelocityState {
585 float v[3];
586 float w[3];
587};
588struct PositionState {
589 float x[3];
590 float q[4];
591};
592// Owner-side packs for a forward take an optional row list (`rows`, n = its length): the forward
593// reads the owned array only at the send and self-image rows (the interface), so packing those
594// rows alone is the same exchange. Empty `rows`: rows [0, n).
595inline void haloPackVelocityState(const BodyPred& pred, peclet::core::View<VelocityState> owned,
596 int n, Vi rows = {}) {
597 const V3 velPred = pred.velPred;
598 const V3 angVelPred = pred.angVelPred;
599 const bool list = rows.extent(0) > 0;
600 Kokkos::parallel_for(
601 "peclet::dem::halo::packVelState", Kokkos::RangePolicy<CpExec>(0, n), KOKKOS_LAMBDA(int j) {
602 const int i = list ? rows(j) : j;
603 VelocityState r;
604 for (int d = 0; d < 3; ++d) {
605 r.v[d] = velPred(i, d);
606 r.w[d] = angVelPred(i, d);
607 }
608 owned(i) = r;
609 });
610}
611inline void haloUnpackVelocityState(const BodyPred& pred, peclet::core::View<VelocityState> ghost,
612 const GhostRange& ghosts) {
613 const Vi slot = ghosts.slot;
614 const int no = ghosts.no;
615 const int ng = ghosts.ng;
616 const V3 velPred = pred.velPred;
617 const V3 angVelPred = pred.angVelPred;
618 Kokkos::parallel_for(
619 "peclet::dem::halo::unpackVelState", Kokkos::RangePolicy<CpExec>(0, ng),
620 KOKKOS_LAMBDA(int g) {
621 const VelocityState r = ghost(g);
622 const int s = no + slot(g);
623 for (int d = 0; d < 3; ++d) {
624 velPred(s, d) = r.v[d];
625 angVelPred(s, d) = r.w[d];
626 }
627 });
628}
629inline void haloPackPositionState(const BodyPred& pred, peclet::core::View<PositionState> owned,
630 int n, Vi rows = {}) {
631 const V3 posPred = pred.posPred;
632 const V4 quatPred = pred.quatPred;
633 const bool list = rows.extent(0) > 0;
634 Kokkos::parallel_for(
635 "peclet::dem::halo::packPosState", Kokkos::RangePolicy<CpExec>(0, n), KOKKOS_LAMBDA(int j) {
636 const int i = list ? rows(j) : j;
637 PositionState r;
638 for (int d = 0; d < 3; ++d)
639 r.x[d] = posPred(i, d);
640 for (int d = 0; d < 4; ++d)
641 r.q[d] = quatPred(i, d);
642 owned(i) = r;
643 });
644}
645// The periodic image shift is added to x exactly as haloUnpackF3 adds it (one float add per axis).
646inline void haloUnpackPositionState(const BodyPred& pred, peclet::core::View<PositionState> ghost,
647 peclet::core::View<F3> shift, const GhostRange& ghosts) {
648 const Vi slot = ghosts.slot;
649 const int no = ghosts.no;
650 const int ng = ghosts.ng;
651 const V3 posPred = pred.posPred;
652 const V4 quatPred = pred.quatPred;
653 Kokkos::parallel_for(
654 "peclet::dem::halo::unpackPosState", Kokkos::RangePolicy<CpExec>(0, ng),
655 KOKKOS_LAMBDA(int g) {
656 const PositionState r = ghost(g);
657 const F3 sh = shift(g);
658 const int s = no + slot(g);
659 posPred(s, 0) = r.x[0] + sh.x;
660 posPred(s, 1) = r.x[1] + sh.y;
661 posPred(s, 2) = r.x[2] + sh.z;
662 for (int d = 0; d < 4; ++d)
663 quatPred(s, d) = r.q[d];
664 });
665}
666
667// --- rank-level M (docs/contact_solve_framework.md §13.3): the opening exchange, the a-weighted
668// pack, the k-weighted owner apply, the orphan shares and the velocity slot map. All payloads are
669// POD (MPI_BYTE-copyable); core's reverse accumulates through Kokkos::atomic_add, which applies
670// operator+ (sums floats and ints, max of the peak). In every ghost kernel g is the TOPOLOGY ghost
671// index and s = no + slot(g) its canonical SoA slot, as above. ---
672
673// PGS opening, reverse: the warm-start increments (raw: known impulses) plus the slot's local
674// active copy counts a_vel, a_pos.
675struct OpeningIncrement {
676 float v[3];
677 float w[3];
678 float orphan;
679 float orphanPeak;
680 int aVel;
681 int aPos;
682};
683KOKKOS_INLINE_FUNCTION OpeningIncrement operator+(const OpeningIncrement& a,
684 const OpeningIncrement& b) {
685 OpeningIncrement r;
686 for (int d = 0; d < 3; ++d) {
687 r.v[d] = a.v[d] + b.v[d];
688 r.w[d] = a.w[d] + b.w[d];
689 }
690 r.orphan = a.orphan + b.orphan;
691 r.orphanPeak = a.orphanPeak > b.orphanPeak ? a.orphanPeak : b.orphanPeak;
692 r.aVel = a.aVel + b.aVel;
693 r.aPos = a.aPos + b.aPos;
694 return r;
695}
696// PGS opening, forward: the owner's state, orphan balance B and peak, and the global counts k
697// (with rotation 40 B; without, w is dropped: 28 B).
698struct OpeningState {
699 float v[3];
700 float w[3];
701 float B;
702 float peak;
703 int kVel;
704 int kPos;
705};
706struct OpeningStateNoRot {
707 float v[3];
708 float B;
709 float peak;
710 int kVel;
711 int kPos;
712};
713// Later velocity forwards under Poisson: VelocityState plus the balance and peak (32 B; without
714// rotation 20 B).
715struct VelocityStateB {
716 float v[3];
717 float w[3];
718 float B;
719 float peak;
720};
721struct VelocityStateBNoRot {
722 float v[3];
723 float B;
724 float peak;
725};
726
727inline void haloPackOpeningIncrement(const VelocityPhaseViews& vel, const VelocityPhaseViews& base,
728 Vi aVel, Vi aPos, peclet::core::View<OpeningIncrement> inc,
729 const GhostRange& ghosts) {
730 const Vi slot = ghosts.slot;
731 const int no = ghosts.no;
732 const int ng = ghosts.ng;
733 const V3 velPred = vel.velPred;
734 const V3 angVelPred = vel.angVelPred;
735 const Vf orphan = vel.orphan;
736 const Vf orphanPeak = vel.orphanPeak;
737 const V3 baseV = base.velPred;
738 const V3 baseW = base.angVelPred;
739 const Vf baseO = base.orphan;
740 const Vf basePk = base.orphanPeak;
741 Kokkos::parallel_for(
742 "peclet::dem::halo::packOpenInc", Kokkos::RangePolicy<CpExec>(0, ng), KOKKOS_LAMBDA(int g) {
743 const int s = no + slot(g);
744 OpeningIncrement r;
745 for (int d = 0; d < 3; ++d) {
746 r.v[d] = velPred(s, d) - baseV(g, d);
747 r.w[d] = angVelPred(s, d) - baseW(g, d);
748 }
749 r.orphan = orphan(s) - baseO(g);
750 r.orphanPeak = orphanPeak(s) > basePk(g) ? orphanPeak(s) : 0.0f;
751 r.aVel = aVel(s);
752 r.aPos = aPos(s);
753 inc(g) = r;
754 });
755}
756// Owned rows: the raw add (exactly haloApplyVelocityIncrement), then k = max(1, a(own) + sum a).
757inline void haloApplyOpening(const VelocityPhaseViews& vel, Vi aVel, Vi aPos, Vi kVel, Vi kPos,
758 peclet::core::View<OpeningIncrement> ownedInc, int no) {
759 const V3 velPred = vel.velPred;
760 const V3 angVelPred = vel.angVelPred;
761 const Vf orphan = vel.orphan;
762 const Vf orphanPeak = vel.orphanPeak;
763 Kokkos::parallel_for(
764 "peclet::dem::halo::applyOpen", Kokkos::RangePolicy<CpExec>(0, no), KOKKOS_LAMBDA(int i) {
765 const OpeningIncrement r = ownedInc(i);
766 for (int d = 0; d < 3; ++d) {
767 velPred(i, d) += r.v[d];
768 angVelPred(i, d) += r.w[d];
769 }
770 orphan(i) = Kokkos::fmax(0.0f, orphan(i) + r.orphan);
771 orphanPeak(i) = Kokkos::fmax(orphanPeak(i), r.orphanPeak);
772 const int kv = aVel(i) + r.aVel, kp = aPos(i) + r.aPos;
773 kVel(i) = kv > 1 ? kv : 1;
774 kPos(i) = kp > 1 ? kp : 1;
775 });
776}
777template <class S>
778inline void haloPackOpeningState(const VelocityPhaseViews& vel, Vi kVel, Vi kPos,
779 peclet::core::View<S> owned, int no) {
780 const V3 velPred = vel.velPred;
781 const V3 angVelPred = vel.angVelPred;
782 const Vf orphan = vel.orphan;
783 const Vf orphanPeak = vel.orphanPeak;
784 Kokkos::parallel_for(
785 "peclet::dem::halo::packOpenState", Kokkos::RangePolicy<CpExec>(0, no), KOKKOS_LAMBDA(int i) {
786 const V3& wv = angVelPred; // captured outside the constexpr-if (nvcc)
787 S r;
788 for (int d = 0; d < 3; ++d)
789 r.v[d] = velPred(i, d);
790 if constexpr (std::is_same_v<S, OpeningState>) {
791 for (int d = 0; d < 3; ++d)
792 r.w[d] = wv(i, d);
793 }
794 r.B = orphan(i);
795 r.peak = orphanPeak(i);
796 r.kVel = kVel(i);
797 r.kPos = kPos(i);
798 owned(i) = r;
799 });
800}
801template <class S>
802inline void haloUnpackOpeningState(const VelocityPhaseViews& vel, Vi kVel, Vi kPos,
803 peclet::core::View<S> ghost, const GhostRange& ghosts) {
804 const Vi slot = ghosts.slot;
805 const int no = ghosts.no;
806 const int ng = ghosts.ng;
807 const V3 velPred = vel.velPred;
808 const V3 angVelPred = vel.angVelPred;
809 const Vf orphan = vel.orphan;
810 const Vf orphanPeak = vel.orphanPeak;
811 Kokkos::parallel_for(
812 "peclet::dem::halo::unpackOpenState", Kokkos::RangePolicy<CpExec>(0, ng),
813 KOKKOS_LAMBDA(int g) {
814 const V3& wv = angVelPred; // captured outside the constexpr-if (nvcc)
815 const S r = ghost(g);
816 const int s = no + slot(g);
817 for (int d = 0; d < 3; ++d)
818 velPred(s, d) = r.v[d];
819 if constexpr (std::is_same_v<S, OpeningState>) {
820 for (int d = 0; d < 3; ++d)
821 wv(s, d) = r.w[d];
822 }
823 orphan(s) = r.B;
824 orphanPeak(s) = r.peak;
825 kVel(s) = r.kVel;
826 kPos(s) = r.kPos;
827 });
828}
829template <class S>
830inline void haloPackVelocityStateB(const VelocityPhaseViews& vel, peclet::core::View<S> owned,
831 int no, Vi rows = {}) {
832 const V3 velPred = vel.velPred;
833 const V3 angVelPred = vel.angVelPred;
834 const Vf orphan = vel.orphan;
835 const Vf orphanPeak = vel.orphanPeak;
836 const bool list = rows.extent(0) > 0;
837 Kokkos::parallel_for(
838 "peclet::dem::halo::packVelStateB", Kokkos::RangePolicy<CpExec>(0, no), KOKKOS_LAMBDA(int j) {
839 const int i = list ? rows(j) : j;
840 const V3& wv = angVelPred; // captured outside the constexpr-if (nvcc)
841 S r;
842 for (int d = 0; d < 3; ++d)
843 r.v[d] = velPred(i, d);
844 if constexpr (std::is_same_v<S, VelocityStateB>) {
845 for (int d = 0; d < 3; ++d)
846 r.w[d] = wv(i, d);
847 }
848 r.B = orphan(i);
849 r.peak = orphanPeak(i);
850 owned(i) = r;
851 });
852}
853template <class S>
854inline void haloUnpackVelocityStateB(const VelocityPhaseViews& vel, peclet::core::View<S> ghost,
855 const GhostRange& ghosts) {
856 const Vi slot = ghosts.slot;
857 const int no = ghosts.no;
858 const int ng = ghosts.ng;
859 const V3 velPred = vel.velPred;
860 const V3 angVelPred = vel.angVelPred;
861 const Vf orphan = vel.orphan;
862 const Vf orphanPeak = vel.orphanPeak;
863 Kokkos::parallel_for(
864 "peclet::dem::halo::unpackVelStateB", Kokkos::RangePolicy<CpExec>(0, ng),
865 KOKKOS_LAMBDA(int g) {
866 const V3& wv = angVelPred; // captured outside the constexpr-if (nvcc)
867 const S r = ghost(g);
868 const int s = no + slot(g);
869 for (int d = 0; d < 3; ++d)
870 velPred(s, d) = r.v[d];
871 if constexpr (std::is_same_v<S, VelocityStateB>) {
872 for (int d = 0; d < 3; ++d)
873 wv(s, d) = r.w[d];
874 }
875 orphan(s) = r.B;
876 orphanPeak(s) = r.peak;
877 });
878}
879// Owner seeds (§4.6 step 4): the owned rows' values at the last reconciliation. The seeds, the M
880// applies and the orphan restore take the phase's M row list (ParticleHalo::buildMRows: the
881// interface rows plus every k > 1 row; n = its length) -- no other owned row reads a seed or
882// receives an increment. Empty `rows`: rows [0, n).
883inline void haloMarkOwnerVelocitySeeds(V3 velPred, V3 angVelPred, Vf orphan, V3 seedV, V3 seedW,
884 Vf seedO, int no, Vi rows = {}) {
885 const bool list = rows.extent(0) > 0;
886 Kokkos::parallel_for(
887 "peclet::dem::halo::markOwnerVelSeed", Kokkos::RangePolicy<CpExec>(0, no),
888 KOKKOS_LAMBDA(int j) {
889 const int i = list ? rows(j) : j;
890 for (int d = 0; d < 3; ++d) {
891 seedV(i, d) = velPred(i, d);
892 seedW(i, d) = angVelPred(i, d);
893 }
894 seedO(i) = orphan(i);
895 });
896}
897inline void haloMarkOwnerPositionSeeds(V3 posPred, V3 seedX, int no, Vi rows = {}) {
898 const bool list = rows.extent(0) > 0;
899 Kokkos::parallel_for(
900 "peclet::dem::halo::markOwnerPosSeed", Kokkos::RangePolicy<CpExec>(0, no),
901 KOKKOS_LAMBDA(int j) {
902 const int i = list ? rows(j) : j;
903 for (int d = 0; d < 3; ++d)
904 seedX(i, d) = posPred(i, d);
905 });
906}
907// Orphan shares (§13.3): every slot [0, n) of a body with k_vel > 1 -- owned row and ghosts --
908// holds B / k of the balance B it holds now (the owner's, just forwarded); k = 1 keeps B.
909inline void haloSetOrphanShares(Vf orphan, Vi kVel, int n) {
910 Kokkos::parallel_for(
911 "peclet::dem::halo::orphanShares", Kokkos::RangePolicy<CpExec>(0, n), KOKKOS_LAMBDA(int q) {
912 const int k = kVel(q);
913 if (k > 1)
914 orphan(q) = orphan(q) / static_cast<float>(k);
915 });
916}
917// The M rows of a phase, ascending: owned rows on the interface (`mark`) or with k > 1 (see
918// ParticleHalo::buildMRows). Returns their count.
919inline int haloBuildMRows(Vi k, Kokkos::View<const unsigned char*, CpMem> mark, Vi rows, int no) {
920 int cnt = 0;
921 Kokkos::parallel_scan(
922 "peclet::dem::halo::mRows", Kokkos::RangePolicy<CpExec>(0, no),
923 KOKKOS_LAMBDA(int i, int& run, const bool final) {
924 if (mark(i) != 0 || k(i) > 1) {
925 if (final)
926 rows(run) = i;
927 ++run;
928 }
929 },
930 cnt);
931 return cnt;
932}
933// ---- the fused rank-level M reconciliation (docs/contact_solve_framework.md §13.3) ----
934// One reconciliation is three dem kernels around core's reverse and forward:
935// 1. MPackZero: every ghost's a-weighted increment, and the phase's M rows zeroed (one launch);
936// 2. MApply: per M row the k-weighted owner apply, then -- for an interface row -- the forward
937// payload, the owner seeds and (Poisson) the owner's orphan share;
938// 3. MUnpack: per ghost the forwarded payload, its consensus correction (§12 S14), its orphan
939// share and its new baseline.
940// Bit for bit the unfused sequence pack / zero / reverse / apply / pack / forward / unpack /
941// consensus / seeds / shares / baselines: every owned row and every ghost slot sees the same
942// operations in the same order (the forward reads only the payload rows, which nothing writes
943// after MApply; the owner seeds and the pre-share payload take the post-apply values the forward
944// leaves untouched). The payload type S picks the forwarded fields: VelocityStateB (v, w, B, peak),
945// VelocityStateBNoRot (v, B, peak), VelocityState (v, w) or F3 (v alone); PositionState (x, q) or
946// F3 (x alone). The periodic image shift is added to a ghost position exactly as haloUnpackF3 does.
947KOKKOS_INLINE_FUNCTION float payloadLin(const F3& r, int d) {
948 return d == 0 ? r.x : (d == 1 ? r.y : r.z);
949}
950KOKKOS_INLINE_FUNCTION void setPayloadLin(F3& r, int d, float x) {
951 (d == 0 ? r.x : (d == 1 ? r.y : r.z)) = x;
952}
953template <class S>
954KOKKOS_INLINE_FUNCTION float payloadLin(const S& r, int d) {
955 if constexpr (std::is_same_v<S, PositionState>)
956 return r.x[d];
957 else
958 return r.v[d];
959}
960template <class S>
961KOKKOS_INLINE_FUNCTION void setPayloadLin(S& r, int d, float x) {
962 if constexpr (std::is_same_v<S, PositionState>)
963 r.x[d] = x;
964 else
965 r.v[d] = x;
966}
967template <class S>
968inline constexpr bool kPayloadW =
969 std::is_same_v<S, VelocityState> || std::is_same_v<S, VelocityStateB>;
970template <class S>
971inline constexpr bool kPayloadB =
972 std::is_same_v<S, VelocityStateB> || std::is_same_v<S, VelocityStateBNoRot>;
973
974// 1 (velocity). inc = a(s) (x - baseline) for v, w and the orphan account; the peak travels only
975// from an active slot that raised it. A slot with a = 0 is never written by the phase; a debug
976// build checks that its increment is zero (a non-zero one would be dropped).
977inline void haloVelocityMPackZero(const VelocityPhaseViews& vel, const VelocityPhaseViews& base,
978 Vi aVel, peclet::core::View<VelocityIncrement> inc,
979 const GhostRange& ghosts,
980 peclet::core::View<VelocityIncrement> ownedInc, Vi rows,
981 int nRows) {
982 const Vi slot = ghosts.slot;
983 const int no = ghosts.no;
984 const int ng = ghosts.ng;
985 const V3 velPred = vel.velPred;
986 const V3 angVelPred = vel.angVelPred;
987 const Vf orphan = vel.orphan;
988 const Vf orphanPeak = vel.orphanPeak;
989 const V3 baseV = base.velPred;
990 const V3 baseW = base.angVelPred;
991 const Vf baseO = base.orphan;
992 const Vf basePk = base.orphanPeak;
993 Kokkos::parallel_for(
994 "peclet::dem::halo::velMPackZero", Kokkos::RangePolicy<CpExec>(0, ng + nRows),
995 KOKKOS_LAMBDA(int j) {
996 if (j >= ng) {
997 ownedInc(rows(j - ng)) = VelocityIncrement{};
998 return;
999 }
1000 const int g = j;
1001 const int s = no + slot(g);
1002 const float f = static_cast<float>(aVel(s));
1003 VelocityIncrement r;
1004 for (int d = 0; d < 3; ++d) {
1005 r.v[d] = f * (velPred(s, d) - baseV(g, d));
1006 r.w[d] = f * (angVelPred(s, d) - baseW(g, d));
1007 }
1008 r.orphan = f * (orphan(s) - baseO(g));
1009 r.orphanPeak = (f > 0.0f && orphanPeak(s) > basePk(g)) ? orphanPeak(s) : 0.0f;
1010#ifndef NDEBUG
1011 if (aVel(s) == 0) {
1012 bool moved = orphan(s) != baseO(g);
1013 for (int d = 0; d < 3; ++d)
1014 moved = moved || velPred(s, d) != baseV(g, d) || angVelPred(s, d) != baseW(g, d);
1015 if (moved)
1016 Kokkos::abort(
1017 "peclet::dem rank-level M: an inactive velocity slot (a = 0) was written");
1018 }
1019#endif
1020 inc(g) = r;
1021 });
1022}
1023// 2 (velocity). The apply (§13.3 table): k <= 1 is c771e07's raw add, bit for bit; k > 1 takes
1024// x = seed + (a(own) (x - seed) + sum inc) / k, and the balance
1025// B_new = max(0, B + a(own) (orphan - B / k) + sum inc) (the owner row holds the share B / k).
1026// Clamp hits are counted (split_stats.orphanClamps; must stay 0), and a debug build asserts the
1027// pre-clamp balance is >= -1e-6 max(B, 1e-30). Then the payload (interface rows), the seeds, and
1028// under Poisson (`shares`) the owner's share B / k.
1029template <class S>
1030inline void haloVelocityMApply(const VelocityPhaseViews& vel, V3 seedV, V3 seedW, Vf seedO, Vi aVel,
1031 Vi kVel, peclet::core::View<VelocityIncrement> ownedInc,
1032 Kokkos::View<int, CpMem> clamps,
1033 Kokkos::View<float, CpMem> consensus, Vi rows, int nRows,
1034 Kokkos::View<const unsigned char*, CpMem> iface,
1035 peclet::core::View<S> out, bool shares) {
1036 const V3 velPred = vel.velPred;
1037 const V3 angVelPred = vel.angVelPred;
1038 const Vf orphan = vel.orphan;
1039 const Vf orphanPeak = vel.orphanPeak;
1040 Kokkos::parallel_for(
1041 "peclet::dem::halo::velMApply", Kokkos::RangePolicy<CpExec>(0, nRows), KOKKOS_LAMBDA(int j) {
1042 const V3& wv = angVelPred; // captured outside the constexpr-if (nvcc)
1043 const Vf& ov = orphan;
1044 const Vf& pv = orphanPeak;
1045 const int i = rows(j);
1046 const VelocityIncrement r = ownedInc(i);
1047 const int k = kVel(i);
1048 float pre;
1049 if (k <= 1) {
1050 for (int d = 0; d < 3; ++d) {
1051 velPred(i, d) += r.v[d];
1052 angVelPred(i, d) += r.w[d];
1053 }
1054 pre = orphan(i) + r.orphan;
1055 } else {
1056 const float kf = static_cast<float>(k), af = static_cast<float>(aVel(i));
1057 float c2 = 0.0f; // §12 S14: the owner copy's consensus correction (increment form)
1058 for (int d = 0; d < 3; ++d) {
1059#if defined(PECLET_DEM_TEST_MUTANT) && PECLET_DEM_TEST_MUTANT == 2
1060 const float own = velPred(i, d) - seedV(i, d),
1061 mean = af * own + r.v[d]; // G13 mutant 2
1062#else
1063 const float own = velPred(i, d) - seedV(i, d), mean = (af * own + r.v[d]) / kf;
1064#endif
1065 c2 += (mean - own) * (mean - own);
1066 velPred(i, d) = seedV(i, d) + mean;
1067 angVelPred(i, d) = seedW(i, d) + (af * (angVelPred(i, d) - seedW(i, d)) + r.w[d]) / kf;
1068 }
1069 if (af > 0.0f && c2 > 0.0f)
1070 Kokkos::atomic_max(&consensus(), Kokkos::sqrt(c2));
1071 const float B = seedO(i);
1072 pre = B + af * (orphan(i) - B / kf) + r.orphan;
1073#ifndef NDEBUG
1074 if (!(pre >= -1e-6f * Kokkos::fmax(B, 1e-30f)))
1075 Kokkos::abort("peclet::dem rank-level M: the orphan balance was overdrawn");
1076#endif
1077 }
1078 if (pre < 0.0f)
1079 Kokkos::atomic_add(&clamps(), 1);
1080 orphan(i) = Kokkos::fmax(0.0f, pre);
1081 orphanPeak(i) = Kokkos::fmax(orphanPeak(i), r.orphanPeak);
1082 if (iface(i) != 0) {
1083 S p;
1084 for (int d = 0; d < 3; ++d)
1085 setPayloadLin(p, d, velPred(i, d));
1086 if constexpr (kPayloadW<S>) {
1087 for (int d = 0; d < 3; ++d)
1088 p.w[d] = wv(i, d);
1089 }
1090 if constexpr (kPayloadB<S>) {
1091 p.B = ov(i);
1092 p.peak = pv(i);
1093 }
1094 out(i) = p;
1095 }
1096 for (int d = 0; d < 3; ++d) {
1097 seedV(i, d) = velPred(i, d);
1098 seedW(i, d) = angVelPred(i, d);
1099 }
1100 seedO(i) = orphan(i);
1101 if (shares && k > 1)
1102 orphan(i) = orphan(i) / static_cast<float>(k);
1103 });
1104}
1105// 3 (velocity). The ghost copies: the payload; §12 S14's consensus correction of every ACTIVE ghost
1106// copy (a > 0) of a k > 1 body, |(x_new - baseline) - inc / a| (inc = the a-weighted increment it
1107// packed, still in the send buffer), atomic-maxed into `consensus`; the share B / k; the baseline.
1108template <class S>
1109inline void haloVelocityMUnpack(const VelocityPhaseViews& vel, peclet::core::View<S> ghost,
1110 const VelocityPhaseViews& base, Vi aVel, Vi kVel,
1111 peclet::core::View<VelocityIncrement> inc,
1112 Kokkos::View<float, CpMem> consensus, const GhostRange& ghosts,
1113 bool shares) {
1114 const Vi slot = ghosts.slot;
1115 const int no = ghosts.no;
1116 const int ng = ghosts.ng;
1117 const V3 velPred = vel.velPred;
1118 const V3 angVelPred = vel.angVelPred;
1119 const Vf orphan = vel.orphan;
1120 const Vf orphanPeak = vel.orphanPeak;
1121 const V3 baseV = base.velPred;
1122 const V3 baseW = base.angVelPred;
1123 const Vf baseO = base.orphan;
1124 const Vf basePk = base.orphanPeak;
1125 Kokkos::parallel_for(
1126 "peclet::dem::halo::velMUnpack", Kokkos::RangePolicy<CpExec>(0, ng), KOKKOS_LAMBDA(int g) {
1127 const V3& wv = angVelPred; // captured outside the constexpr-if (nvcc)
1128 const Vf& ov = orphan;
1129 const Vf& pv = orphanPeak;
1130 const S p = ghost(g);
1131 const int s = no + slot(g);
1132 for (int d = 0; d < 3; ++d)
1133 velPred(s, d) = payloadLin(p, d);
1134 if constexpr (kPayloadW<S>) {
1135 for (int d = 0; d < 3; ++d)
1136 wv(s, d) = p.w[d];
1137 }
1138 if constexpr (kPayloadB<S>) {
1139 ov(s) = p.B;
1140 pv(s) = p.peak;
1141 }
1142 const int k = kVel(s);
1143 if (aVel(s) > 0 && k > 1) {
1144 const float af = static_cast<float>(aVel(s));
1145 const VelocityIncrement r = inc(g);
1146 float c2 = 0.0f;
1147 for (int d = 0; d < 3; ++d) {
1148 const float e = (velPred(s, d) - baseV(g, d)) - r.v[d] / af;
1149 c2 += e * e;
1150 }
1151 if (c2 > 0.0f)
1152 Kokkos::atomic_max(&consensus(), Kokkos::sqrt(c2));
1153 }
1154 if (shares && k > 1)
1155 orphan(s) = orphan(s) / static_cast<float>(k);
1156 for (int d = 0; d < 3; ++d) {
1157 baseV(g, d) = velPred(s, d);
1158 baseW(g, d) = angVelPred(s, d);
1159 }
1160 baseO(g) = orphan(s);
1161 basePk(g) = orphanPeak(s);
1162 });
1163}
1164// Phase end (§13.3): the owner row of a k > 1 body gets its balance back,
1165// B_seed + a(own) (orphan - B_seed / k); after the phase-final sync this is B_seed exactly.
1166inline void haloRestoreOrphanBalance(Vf orphan, Vf seedO, Vi aVel, Vi kVel, int no, Vi rows = {}) {
1167 const bool list = rows.extent(0) > 0;
1168 Kokkos::parallel_for(
1169 "peclet::dem::halo::restoreOrphan", Kokkos::RangePolicy<CpExec>(0, no), KOKKOS_LAMBDA(int j) {
1170 const int i = list ? rows(j) : j;
1171 const int k = kVel(i);
1172 if (k <= 1)
1173 return;
1174 const float kf = static_cast<float>(k), B = seedO(i);
1175 orphan(i) = B + static_cast<float>(aVel(i)) * (orphan(i) - B / kf);
1176 });
1177}
1178// 1 (position). inc = a(s) (x - baseline), and the phase's M rows zeroed.
1179inline void haloPositionMPackZero(V3 posPred, V3 baseX, Vi aPos,
1180 peclet::core::View<PositionIncrement> inc,
1181 const GhostRange& ghosts,
1182 peclet::core::View<PositionIncrement> ownedInc, Vi rows,
1183 int nRows) {
1184 const Vi slot = ghosts.slot;
1185 const int no = ghosts.no;
1186 const int ng = ghosts.ng;
1187 Kokkos::parallel_for(
1188 "peclet::dem::halo::posMPackZero", Kokkos::RangePolicy<CpExec>(0, ng + nRows),
1189 KOKKOS_LAMBDA(int j) {
1190 if (j >= ng) {
1191 ownedInc(rows(j - ng)) = PositionIncrement{};
1192 return;
1193 }
1194 const int g = j;
1195 const int s = no + slot(g);
1196 const float f = static_cast<float>(aPos(s));
1197 PositionIncrement r;
1198 for (int d = 0; d < 3; ++d)
1199 r.x[d] = f * (posPred(s, d) - baseX(g, d));
1200#ifndef NDEBUG
1201 if (aPos(s) == 0 && (posPred(s, 0) != baseX(g, 0) || posPred(s, 1) != baseX(g, 1) ||
1202 posPred(s, 2) != baseX(g, 2)))
1203 Kokkos::abort("peclet::dem rank-level M: an inactive position slot (a = 0) was written");
1204#endif
1205 inc(g) = r;
1206 });
1207}
1208// 2 (position). The apply (raw add for k <= 1), the payload of an interface row, the seed.
1209template <class S>
1210inline void haloPositionMApply(const BodyPred& pred, V3 seedX, Vi aPos, Vi kPos,
1211 peclet::core::View<PositionIncrement> ownedInc,
1212 Kokkos::View<float, CpMem> consensus, Vi rows, int nRows,
1213 Kokkos::View<const unsigned char*, CpMem> iface,
1214 peclet::core::View<S> out) {
1215 const V3 posPred = pred.posPred;
1216 const V4 quatPred = pred.quatPred;
1217 Kokkos::parallel_for(
1218 "peclet::dem::halo::posMApply", Kokkos::RangePolicy<CpExec>(0, nRows), KOKKOS_LAMBDA(int j) {
1219 const V4& qv = quatPred; // captured outside the constexpr-if (nvcc)
1220 const int i = rows(j);
1221 const PositionIncrement r = ownedInc(i);
1222 const int k = kPos(i);
1223 if (k <= 1) {
1224 for (int d = 0; d < 3; ++d)
1225 posPred(i, d) += r.x[d];
1226 } else {
1227 const float kf = static_cast<float>(k), af = static_cast<float>(aPos(i));
1228 float c2 = 0.0f; // §12 S14: the owner copy's consensus correction (increment form)
1229 for (int d = 0; d < 3; ++d) {
1230 const float own = posPred(i, d) - seedX(i, d), mean = (af * own + r.x[d]) / kf;
1231 c2 += (mean - own) * (mean - own);
1232 posPred(i, d) = seedX(i, d) + mean;
1233 }
1234 if (af > 0.0f && c2 > 0.0f)
1235 Kokkos::atomic_max(&consensus(), Kokkos::sqrt(c2));
1236 }
1237 if (iface(i) != 0) {
1238 S p;
1239 for (int d = 0; d < 3; ++d)
1240 setPayloadLin(p, d, posPred(i, d));
1241 if constexpr (std::is_same_v<S, PositionState>) {
1242 for (int d = 0; d < 4; ++d)
1243 p.q[d] = qv(i, d);
1244 }
1245 out(i) = p;
1246 }
1247 for (int d = 0; d < 3; ++d)
1248 seedX(i, d) = posPred(i, d);
1249 });
1250}
1251// 3 (position). The ghost copies: the payload (+ the periodic image shift), the consensus
1252// correction, the baseline.
1253template <class S>
1254inline void haloPositionMUnpack(const BodyPred& pred, peclet::core::View<S> ghost,
1255 peclet::core::View<F3> shift, V3 baseX, Vi aPos, Vi kPos,
1256 peclet::core::View<PositionIncrement> inc,
1257 Kokkos::View<float, CpMem> consensus, const GhostRange& ghosts) {
1258 const Vi slot = ghosts.slot;
1259 const int no = ghosts.no;
1260 const int ng = ghosts.ng;
1261 const V3 posPred = pred.posPred;
1262 const V4 quatPred = pred.quatPred;
1263 Kokkos::parallel_for(
1264 "peclet::dem::halo::posMUnpack", Kokkos::RangePolicy<CpExec>(0, ng), KOKKOS_LAMBDA(int g) {
1265 const V4& qv = quatPred; // captured outside the constexpr-if (nvcc)
1266 const S p = ghost(g);
1267 const F3 sh = shift(g);
1268 const int s = no + slot(g);
1269 posPred(s, 0) = payloadLin(p, 0) + sh.x;
1270 posPred(s, 1) = payloadLin(p, 1) + sh.y;
1271 posPred(s, 2) = payloadLin(p, 2) + sh.z;
1272 if constexpr (std::is_same_v<S, PositionState>) {
1273 for (int d = 0; d < 4; ++d)
1274 qv(s, d) = p.q[d];
1275 }
1276 if (aPos(s) > 0 && kPos(s) > 1) {
1277 const float af = static_cast<float>(aPos(s));
1278 const PositionIncrement r = inc(g);
1279 float c2 = 0.0f;
1280 for (int d = 0; d < 3; ++d) {
1281 const float e = (posPred(s, d) - baseX(g, d)) - r.x[d] / af;
1282 c2 += e * e;
1283 }
1284 if (c2 > 0.0f)
1285 Kokkos::atomic_max(&consensus(), Kokkos::sqrt(c2));
1286 }
1287 for (int d = 0; d < 3; ++d)
1288 baseX(g, d) = posPred(s, d);
1289 });
1290}
1291// The g = 0 path's counts-only opening (§13.3): reverse a_pos, owner k_pos, forward k_pos.
1292inline void haloPackGhostInt(Vi src, peclet::core::View<int> ghost, const GhostRange& ghosts) {
1293 const Vi slot = ghosts.slot;
1294 const int no = ghosts.no;
1295 const int ng = ghosts.ng;
1296 Kokkos::parallel_for(
1297 "peclet::dem::halo::packGhostInt", Kokkos::RangePolicy<CpExec>(0, ng),
1298 KOKKOS_LAMBDA(int g) { ghost(g) = src(no + slot(g)); });
1299}
1300inline void haloOwnerCountK(Vi a, Vi k, peclet::core::View<int> owned, int no) {
1301 Kokkos::parallel_for(
1302 "peclet::dem::halo::ownerCountK", Kokkos::RangePolicy<CpExec>(0, no), KOKKOS_LAMBDA(int i) {
1303 const int kk = a(i) + owned(i);
1304 k(i) = kk > 1 ? kk : 1;
1305 owned(i) = k(i);
1306 });
1307}
1308inline void haloUnpackGhostInt(Vi dst, peclet::core::View<int> ghost, const GhostRange& ghosts) {
1309 const Vi slot = ghosts.slot;
1310 const int no = ghosts.no;
1311 const int ng = ghosts.ng;
1312 Kokkos::parallel_for(
1313 "peclet::dem::halo::unpackGhostInt", Kokkos::RangePolicy<CpExec>(0, ng),
1314 KOKKOS_LAMBDA(int g) { dst(no + slot(g)) = ghost(g); });
1315}
1316// Rank-level X (docs/contact_solve_framework.md §1.4, §13.5 WO-6): the g = 0 opening carries, with
1317// a_pos, the velocity activity mask -- bit col(r) of every rank on which the body has an active
1318// velocity copy. Reverse: OR the masks, sum the counts; forward: the owner's OR and k_pos. 16 B per
1319// ghost each way, in the opening's single round.
1320struct PositionCountsMask {
1321 unsigned long long mask;
1322 int aPos;
1323 int pad;
1324};
1325KOKKOS_INLINE_FUNCTION PositionCountsMask operator+(const PositionCountsMask& a,
1326 const PositionCountsMask& b) {
1327 return PositionCountsMask{a.mask | b.mask, a.aPos + b.aPos, 0};
1328}
1329inline void haloPackGhostCountsMask(Vi aVel, Vi aPos, peclet::core::View<PositionCountsMask> ghost,
1330 const GhostRange& ghosts, unsigned long long bit) {
1331 const Vi slot = ghosts.slot;
1332 const int no = ghosts.no;
1333 const int ng = ghosts.ng;
1334 Kokkos::parallel_for(
1335 "peclet::dem::halo::packCountsMask", Kokkos::RangePolicy<CpExec>(0, ng),
1336 KOKKOS_LAMBDA(int g) {
1337 const int s = no + slot(g);
1338 ghost(g) = PositionCountsMask{aVel(s) > 0 ? bit : 0ull, aPos(s), 0};
1339 });
1340}
1341inline void haloOwnerCountsMask(Vi aVel, Vi aPos, Vi kPos,
1342 Kokkos::View<unsigned long long*, CpMem> velMask,
1343 peclet::core::View<PositionCountsMask> owned,
1344 unsigned long long bit, int no) {
1345 Kokkos::parallel_for(
1346 "peclet::dem::halo::ownerCountsMask", Kokkos::RangePolicy<CpExec>(0, no),
1347 KOKKOS_LAMBDA(int i) {
1348 const PositionCountsMask r = owned(i);
1349 const int kk = aPos(i) + r.aPos;
1350 kPos(i) = kk > 1 ? kk : 1;
1351 const unsigned long long m = r.mask | (aVel(i) > 0 ? bit : 0ull);
1352 velMask(i) = m;
1353 owned(i) = PositionCountsMask{m, kPos(i), 0};
1354 });
1355}
1356inline void haloUnpackCountsMask(Vi kPos, Kokkos::View<unsigned long long*, CpMem> velMask,
1357 peclet::core::View<PositionCountsMask> ghost,
1358 const GhostRange& ghosts) {
1359 const Vi slot = ghosts.slot;
1360 const int no = ghosts.no;
1361 const int ng = ghosts.ng;
1362 Kokkos::parallel_for(
1363 "peclet::dem::halo::unpackCountsMask", Kokkos::RangePolicy<CpExec>(0, ng),
1364 KOKKOS_LAMBDA(int g) {
1365 const int s = no + slot(g);
1366 kPos(s) = ghost(g).aPos;
1367 velMask(s) = ghost(g).mask;
1368 });
1369}
1370
1371// The velocity slot map (§6.2): ghost slot no + j takes the canonical slot canon(j) of its body on
1372// this rank (the owned slot for a self image, else the lowest ghost slot with its gid).
1373inline void haloMapVelocitySlots(Vi realIndices, Vi canon, int no, int ng) {
1374 Kokkos::parallel_for(
1375 "peclet::dem::halo::mapVelSlots", Kokkos::RangePolicy<CpExec>(0, ng),
1376 KOKKOS_LAMBDA(int j) { realIndices(no + j) = canon(j); });
1377}
1378
1388class ParticleHalo {
1389 public:
1390 // Block decomposition over the GLOBAL domain (the per-block solver stays non-periodic; the halo
1391 // supplies the periodic wrap). gsize is the ORB cell grid. Mirrors MpiParticleHalo::init.
1392 void initMpi(std::array<double, 3> origin, std::array<double, 3> size, std::array<long, 3> gsize,
1393 std::array<bool, 3> periodic, MPI_Comm comm) {
1394 comm_ = comm;
1395 int sz = 1;
1396 MPI_Comm_rank(comm_, &rank_);
1397 MPI_Comm_size(comm_, &sz);
1398 dec_.init(static_cast<std::size_t>(sz), peclet::core::IVec<3>{gsize[0], gsize[1], gsize[2]});
1399 peclet::core::halo::DomainMap<3> map;
1400 for (int i = 0; i < 3; ++i) {
1401 map.origin[i] = origin[i];
1402 map.cellSize[i] = size[i] / static_cast<double>(gsize[i]);
1403 map.periodic[i] = periodic[i];
1404 }
1405 map_ = map;
1406 mig_.init(dec_, rank_, map, comm_);
1407 halo_.init(mig_);
1408 inited_ = true;
1409 }
1410 // Shared-decomposition overload: adopt an EXTERNALLY-built ORB (so dem shares one BlockDecomposer
1411 // with the flow solver in a coupled run, and migrateTo() can move onto a re-decomposed
1412 // partition). `size`/`origin` map the ORB cell grid (= dec.globalSize()) to the physical domain.
1413 void initMpi(const peclet::core::decomp::BlockDecomposer<3>& dec, std::array<double, 3> origin,
1414 std::array<double, 3> size, std::array<bool, 3> periodic, MPI_Comm comm) {
1415 comm_ = comm;
1416 MPI_Comm_rank(comm_, &rank_);
1417 dec_ = dec;
1418 const auto& gs = dec.globalSize();
1419 peclet::core::halo::DomainMap<3> map;
1420 for (int i = 0; i < 3; ++i) {
1421 map.origin[i] = origin[i];
1422 map.cellSize[i] = size[i] / static_cast<double>(gs[i]);
1423 map.periodic[i] = periodic[i];
1424 }
1425 map_ = map;
1426 mig_.init(dec_, rank_, map, comm_);
1427 halo_.init(mig_);
1428 inited_ = true;
1429 }
1430 const peclet::core::decomp::BlockDecomposer<3>& decomposer() const { return dec_; }
1431
1435 int rankColor() const { return rankColor_; }
1436 int numRankColors() const { return numRankColors_; }
1437
1438 bool inited() const { return inited_; }
1439 int rank() const { return rank_; }
1440 int numGhost() const { return numGhost_; }
1441
1449 void setVerletSkin(float skin) { verletSkin_ = skin < 0.0f ? 0.0f : skin; }
1450 float verletSkin() const { return verletSkin_; }
1454 void invalidateTopology() { haveTopo_ = false; }
1457 long numRebuilds() const { return nRebuild_; }
1458 long numGathers() const { return nGather_; }
1459
1460 // Rebuild the owner<->ghost correspondence over the current owned positions and populate the
1461 // ghost slots [numReal, numReal+numGhost) with the owners' full forwarded state. Sets
1462 // P.numParticles. Returns numReal+numGhost. Faithful port of Simulation::mpi_gather_ghosts.
1463 int gather(Particles& P, double rcut) {
1464 const int no = P.numReal;
1465 ++nGather_;
1466
1467 // Decide whether to rebuild the owner↔ghost topology or reuse the cached one (Verlet skin, D2).
1468 // A rebuild is forced when reuse is off (skin==0), on the first gather, when the owned count
1469 // changed (a migration happened ⇒ topology invalid), when the band differs from the one the
1470 // cached lists were built with (enable_mpi_step again with another rcut or skin, or the
1471 // default band following the particle size -- a list built with a narrower band lacks the
1472 // ghosts the new one needs), or when an owned particle has displaced ≥ skin since the last
1473 // build (a particle could have entered the rcut band without being in the rcut+skin list).
1474 const double band = rcut + static_cast<double>(verletSkin_);
1475 ensureRankColoring(band);
1476 // Rank-level M (§13.3) is per substep: nothing of it crosses a gather.
1477 velM_ = posM_ = orphanShares_ = false;
1478 bool rebuild = (verletSkin_ <= 0.0f) || !haveTopo_ || (no != lastNumReal_) || band != lastBand_;
1479 if (!rebuild && maxOwnedDisplacement(P.pos, no) >= verletSkin_)
1480 rebuild = true;
1481 // The build is collective (an NBX round) and the forwards run over the topology it fixes, but
1482 // every test above except `skin <= 0` is rank-local: one rank's particles can cross the skin
1483 // while its neighbours' rest. So the decision is global -- any rank rebuilding makes all ranks
1484 // rebuild (a rank-local rebuild deadlocks its NBX against the neighbours' forwards). With
1485 // reuse off every rank rebuilds unconditionally, and no reduction is needed.
1486 if (verletSkin_ > 0.0f) {
1487 int mine = rebuild ? 1 : 0, any = 0;
1488 MPI_Allreduce(&mine, &any, 1, MPI_INT, MPI_LOR, comm_);
1489 rebuild = any != 0;
1490 }
1491 numReal_ = no;
1492
1493 if (rebuild) {
1494 ++nRebuild_;
1495 // (1) download owned positions, (re)build the host halo topology, capture it on device.
1496 auto hpos = Kokkos::create_mirror_view(P.pos);
1497 Kokkos::deep_copy(hpos, P.pos);
1498 std::vector<peclet::core::Vec<3>> pv(static_cast<std::size_t>(no));
1499 // Ghost SELECTION runs on the ownership coordinate: on a non-periodic axis a position
1500 // outside the domain is clamped onto it, exactly as core's cellOf clamps it for ownership
1501 // (docs/contact_solve_framework.md §5, §12 S20). Clamping is a projection onto a convex box,
1502 // so it never lengthens a distance: every pair within the reach stays within the band of
1503 // its partner's owner. The ghosts' forwarded positions are the true ones (the image shift
1504 // on a non-periodic axis is 0 either way).
1505 const auto& gsz = dec_.globalSize();
1506 for (int i = 0; i < no; ++i) {
1507 double q[3] = {hpos(i, 0), hpos(i, 1), hpos(i, 2)};
1508 for (int d = 0; d < 3; ++d)
1509 if (!map_.periodic[d])
1510 q[d] = std::clamp(q[d], map_.origin[d],
1511 map_.origin[d] + static_cast<double>(gsz[d]) * map_.cellSize[d]);
1512 pv[i] = peclet::core::Vec<3>{q[0], q[1], q[2]};
1513 }
1514 // includePeriodicSelf: a rank that owns a full (undecomposed) periodic axis -- a "x1" ORB
1515 // axis (e.g. z of a 2x2x1 layout) or np=1 -- is its own periodic image on that axis, so the
1516 // periodic neighbours are local self-ghosts the cross-rank exchange never makes. This
1517 // supplies them.
1518 // allImages (docs/contact_solve_framework.md §5.3, WO-9): EVERY periodic image of a particle
1519 // within the band goes to a destination rank, one ghost per image -- a pair that wraps across
1520 // an undecomposed periodic axis needs a second image on the same rank, which the one-image
1521 // rule dropped (FOLLOWUPS 4b). Reverse sums every image's increment onto the owner.
1522 halo_.build(pv, band, /*includePeriodicSelf=*/true, /*allImages=*/true);
1523 dev_.init(halo_);
1524 const int ng = static_cast<int>(halo_.numGhost());
1525 // The halo topology (forward / device self-gather) writes ALL ng ghost slots [no, no+ng); the
1526 // Particles SoA must have room for them. Silently truncating ng here would leave the halo
1527 // writing past the truncated count -> out-of-bounds SoA writes (memory corruption, not a
1528 // clean drop). So require adequate capacity and fail loudly instead. Size Simulation capacity
1529 // for the worst-case ghost band (a fully periodic box at rcut+skin needs a thick boundary
1530 // layer of ghosts).
1531 if (no + ng > P.capacity)
1532 throw std::runtime_error(
1533 "ParticleHalo::gather: ghost overflow -- need capacity >= " + std::to_string(no + ng) +
1534 " (numReal=" + std::to_string(no) + " + numGhost=" + std::to_string(ng) + "), have " +
1535 std::to_string(P.capacity) + "; increase the Simulation capacity.");
1536 const auto topo = halo_.flatten();
1537 numGhost_ = ng;
1538 numSend_ = static_cast<int>(topo.sendIdx.size());
1539 allocBuffers(no, ng);
1540 uploadShift(topo);
1541 const std::vector<int> hSlot = uploadGhostSlots(topo, ng);
1542 buildOwnershipMaps(topo, no, ng, hSlot);
1543 numReceived_ = static_cast<int>(topo.numReceived);
1544 selfIdx_.assign(topo.selfIdx.begin(), topo.selfIdx.end());
1545 buildInterfaceRows(topo, no);
1546 // Snapshot the owned positions at build time — the reference for the displacement check.
1547 if (verletSkin_ > 0.0f) {
1548 if (refPos_.extent(0) < static_cast<std::size_t>(no))
1549 refPos_ = V3("peclet::dem::halo::refPos", static_cast<std::size_t>(P.capacity));
1550 Kokkos::deep_copy(Kokkos::subview(refPos_, std::pair<int, int>(0, no), Kokkos::ALL),
1551 Kokkos::subview(P.pos, std::pair<int, int>(0, no), Kokkos::ALL));
1552 }
1553 haveTopo_ = true;
1554 lastNumReal_ = no;
1555 lastBand_ = band;
1556 canonStale_ = true; // the velocity slot map follows the new ghost set (mapVelocitySlots)
1557 }
1558
1559 const int ng = numGhost_;
1560 P.numParticles = no + ng;
1561 // self-map realIndices for the reals (owner deltas land on themselves); done every step like
1562 // demStep.
1563 selfMapReals(P.realIndices, no);
1564 if (!exchanges())
1565 return no;
1566
1567 // (2) positions (committed + predicted) with the periodic image shift. d_pos_pred was already
1568 // advanced by predict_velocity, so it is forwarded too (NOT copied from pos) -- see CUDA
1569 // comment.
1570 forwardPositions(P.pos);
1571 forwardPositions(P.posPred);
1572
1573 // (3) all other state packed into one record -> single exchange -> ghost slots + self-mapped
1574 // idx.
1575 haloPackGather(P.bodyState(), P.bodyPred(), P.gid, P.materialId, P.groundedLevel, P.bodyOrphan,
1576 P.bodyOrphanVPeak, ownedPack_, no);
1577 dev_.forward(ownedPack_, ghostPack_);
1578 haloUnpackGather(P.bodyState(), P.bodyPred(), P.realIndices, P.gid, P.materialId,
1579 P.groundedLevel, P.bodyOrphan, P.bodyOrphanVPeak, ghostPack_,
1580 GhostRange{ghostSlot_, no, ng});
1581 return no + ng;
1582 }
1583
1584 MPI_Comm comm() const { return comm_; }
1588 bool exchanges() const { return numGhost_ > 0 || numSend_ > 0; }
1589
1590 // Dynamic load re-balance: re-decompose the ORB by per-block particle COUNT (weighted ORB) and
1591 // migrate each owned particle, with its committed state, to its new owner. A pure redistribution
1592 // of the same global particle set (count conserved, per-particle state preserved) — only
1593 // ownership and this rank's owned slice change; the physics result is unchanged. Must be called
1594 // at a step boundary (committed pos/quat/vel/angVel valid; predicted/delta/ghost scratch are
1595 // rebuilt next gather()). Returns this rank's new owned count. No-op-safe at np=1.
1596 // Weighted re-decompose by particle count (the equal-cell ORB imbalances as particles cluster)
1597 // and migrate owners. dec_ updated in place; mig_ points to it. Returns the new owned count.
1598 int rebalance(Particles& P) {
1599 std::vector<peclet::core::Vec<3>> pos;
1600 std::vector<char> payload;
1601 packState(P, pos, payload);
1602 const std::size_t newN = peclet::core::halo::rebalanceByParticleCount(
1603 dec_, mig_, pos, payload, sizeof(MigratePack), comm_);
1604 orderArrivalsBySource(pos, payload, newN);
1605 if ((int)newN > P.capacity)
1606 throw std::runtime_error("ParticleHalo::rebalance: owned overflow -- rank received " +
1607 std::to_string(newN) + " particles, capacity " +
1608 std::to_string(P.capacity));
1609 unpackState(P, pos, payload, newN);
1610 return (int)newN;
1611 }
1618 int migrateToBlocks(Particles& P) {
1619 std::vector<peclet::core::Vec<3>> pos;
1620 std::vector<char> payload;
1621 packState(P, pos, payload);
1622 const std::size_t newN = mig_.migrate(pos, payload, sizeof(MigratePack));
1623 orderArrivalsBySource(pos, payload, newN);
1624 if ((int)newN > P.capacity)
1625 throw std::runtime_error("ParticleHalo::migrateToBlocks: owned overflow -- rank received " +
1626 std::to_string(newN) + " particles, capacity " +
1627 std::to_string(P.capacity));
1628 unpackState(P, pos, payload, newN);
1629 haveTopo_ = false;
1630 return (int)newN;
1631 }
1634 struct BlockBox {
1635 F3 lo, hi, period;
1636 };
1637 BlockBox blockBox() const {
1638 const auto blk = dec_.block(static_cast<std::size_t>(rank_));
1639 const auto& gs = dec_.globalSize();
1640 float lo[3], hi[3], L[3];
1641 for (int d = 0; d < 3; ++d) {
1642 lo[d] = static_cast<float>(map_.origin[d] +
1643 static_cast<double>(blk.origin[d]) * map_.cellSize[d]);
1644 hi[d] = static_cast<float>(map_.origin[d] + static_cast<double>(blk.origin[d] + blk.size[d]) *
1645 map_.cellSize[d]);
1646 L[d] = map_.periodic[d] ? static_cast<float>(static_cast<double>(gs[d]) * map_.cellSize[d])
1647 : 0.0f;
1648 // Ownership clamps a position outside a non-periodic domain onto the boundary cells
1649 // (core ParticleMigrator::cellOf), so a boundary block owns the half-space beyond it.
1650 if (!map_.periodic[d]) {
1651 if (blk.origin[d] == 0)
1652 lo[d] = -std::numeric_limits<float>::infinity();
1653 if (blk.origin[d] + blk.size[d] == gs[d])
1654 hi[d] = std::numeric_limits<float>::infinity();
1655 }
1656 }
1657 return BlockBox{F3{lo[0], lo[1], lo[2]}, F3{hi[0], hi[1], hi[2]}, F3{L[0], L[1], L[2]}};
1658 }
1659 // Migrate particles onto an EXTERNALLY-supplied decomposition (dynamic co-rebalancing: the same
1660 // BlockDecomposer the flow solver redistributes onto). Pure ownership move — counts/state
1661 // conserved. Must be called at a step boundary. No-op-safe at np=1.
1662 int migrateTo(Particles& P, const peclet::core::decomp::BlockDecomposer<3>& newDec) {
1663 std::vector<peclet::core::Vec<3>> pos;
1664 std::vector<char> payload;
1665 packState(P, pos, payload);
1666 dec_ =
1667 newDec; // in place: mig_ still points at dec_; mig_.migrate() sends to dec_.ownerOf(...)
1668 colorBand_ = -1.0; // the rank colouring follows the decomposition (§1.4)
1669 const std::size_t newN = mig_.migrate(pos, payload, sizeof(MigratePack));
1670 orderArrivalsBySource(pos, payload, newN);
1671 if ((int)newN > P.capacity)
1672 throw std::runtime_error("ParticleHalo::migrateTo: owned overflow -- rank received " +
1673 std::to_string(newN) + " particles, capacity " +
1674 std::to_string(P.capacity));
1675 unpackState(P, pos, payload, newN);
1676 return (int)newN;
1677 }
1678 // Migrate onto the weighted ORB of per-cell weights `w` (global x-fastest, matching the ORB
1679 // grid). The Lagrangian half of the co-rebalance: dem builds the SAME deterministic partition
1680 // flow does from the same weight field, so no BlockDecomposer object crosses the language
1681 // boundary. `align` > 1 builds core's ALIGNED weighted ORB (every split plane on a multiple of
1682 // `align` cells, coarse-first: amr/docs/amr_mg_core_boundary.md §11.4) -- the partition flow's
1683 // rebalanceByWeights chose for its pressure multigrid, which dem must reproduce to stay
1684 // co-located. `align` == 1 is the plain weighted ORB, exactly the pre-`align` call. The caller
1685 // (Simulation::migrateToWeights) has validated `w` and `align` against the ORB grid.
1686 int migrateToWeights(Particles& P, const std::vector<peclet::core::Real>& w, int align = 1) {
1687 int size = 1;
1688 MPI_Comm_size(comm_, &size);
1689 if (align == 1) {
1690 peclet::core::decomp::BlockDecomposer<3> newDec((std::size_t)size, dec_.globalSize(), w);
1691 return migrateTo(P, newDec);
1692 }
1693 peclet::core::decomp::BlockDecomposer<3> newDec;
1694 newDec.init((std::size_t)size, dec_.globalSize(), w,
1695 peclet::core::IVec<3>{align, align, align});
1696 return migrateTo(P, newDec);
1697 }
1698
1699 private:
1700 // Download the committed state and pack each owned particle's record (position drives
1701 // ownership; the rest is the payload); gidToLocal maps each gid to its local index.
1702 std::vector<MigratePack> packParticleRecords(
1703 const Particles& P, std::vector<peclet::core::Vec<3>>& pos, std::vector<char>& payload,
1704 std::unordered_map<unsigned, int>& gidToLocal) const {
1705 const int no = P.numReal;
1706 auto h_pos = Kokkos::create_mirror_view(P.pos);
1707 auto h_quat = Kokkos::create_mirror_view(P.quat);
1708 auto h_vel = Kokkos::create_mirror_view(P.vel);
1709 auto h_angVel = Kokkos::create_mirror_view(P.angVel);
1710 auto h_invI = Kokkos::create_mirror_view(P.invInertia);
1711 auto h_invM = Kokkos::create_mirror_view(P.invMass);
1712 auto h_scale = Kokkos::create_mirror_view(P.scale);
1713 auto h_tScale = Kokkos::create_mirror_view(P.targetScale);
1714 auto h_shape = Kokkos::create_mirror_view(P.shapeId);
1715 auto h_pf = Kokkos::create_mirror_view(P.planeFriction);
1716 auto h_gid = Kokkos::create_mirror_view(P.gid);
1717 auto h_mat = Kokkos::create_mirror_view(P.materialId);
1718 auto h_grd = Kokkos::create_mirror_view(P.groundedLevel);
1719 Kokkos::deep_copy(h_pos, P.pos);
1720 Kokkos::deep_copy(h_quat, P.quat);
1721 Kokkos::deep_copy(h_vel, P.vel);
1722 Kokkos::deep_copy(h_angVel, P.angVel);
1723 Kokkos::deep_copy(h_invI, P.invInertia);
1724 Kokkos::deep_copy(h_invM, P.invMass);
1725 Kokkos::deep_copy(h_scale, P.scale);
1726 Kokkos::deep_copy(h_tScale, P.targetScale);
1727 Kokkos::deep_copy(h_shape, P.shapeId);
1728 Kokkos::deep_copy(h_pf, P.planeFriction);
1729 Kokkos::deep_copy(h_gid, P.gid);
1730 Kokkos::deep_copy(h_mat, P.materialId);
1731 Kokkos::deep_copy(h_grd, P.groundedLevel);
1732 auto h_orp = Kokkos::create_mirror_view(P.bodyOrphan);
1733 auto h_ovp = Kokkos::create_mirror_view(P.bodyOrphanVPeak);
1734 Kokkos::deep_copy(h_orp, P.bodyOrphan);
1735 Kokkos::deep_copy(h_ovp, P.bodyOrphanVPeak);
1736 auto h_ef = Kokkos::create_mirror_view(P.extForce);
1737 auto h_et = Kokkos::create_mirror_view(P.extTorque);
1738 Kokkos::deep_copy(h_ef, P.extForce);
1739 Kokkos::deep_copy(h_et, P.extTorque);
1740 pos.assign((std::size_t)no, peclet::core::Vec<3>{});
1741 payload.assign((std::size_t)no * sizeof(MigratePack), 0);
1742 std::vector<MigratePack> packs((std::size_t)no);
1743 gidToLocal.reserve((std::size_t)no * 2);
1744 for (int i = 0; i < no; ++i) {
1745 pos[(std::size_t)i] = peclet::core::Vec<3>{h_pos(i, 0), h_pos(i, 1), h_pos(i, 2)};
1746 MigratePack& m = packs[(std::size_t)i];
1747 m.quat = F4{h_quat(i, 0), h_quat(i, 1), h_quat(i, 2), h_quat(i, 3)};
1748 m.vel = F3{h_vel(i, 0), h_vel(i, 1), h_vel(i, 2)};
1749 m.angVel = F3{h_angVel(i, 0), h_angVel(i, 1), h_angVel(i, 2)};
1750 m.invInertia = F3{h_invI(i, 0), h_invI(i, 1), h_invI(i, 2)};
1751 m.invMass = h_invM(i);
1752 m.scale = h_scale(i);
1753 m.targetScale = h_tScale(i);
1754 m.shapeId = h_shape(i);
1755 m.planeFric0 = h_pf(i, 0);
1756 m.planeFric1 = h_pf(i, 1);
1757 m.gid = h_gid(i);
1758 m.srcRank = rank_;
1759 m.materialId = h_mat(i);
1760 m.groundedLevel = h_grd(i);
1761 m.orphan = h_orp(i);
1762 m.orphanVPeak = h_ovp(i);
1763 m.extForce = F3{h_ef(i, 0), h_ef(i, 1), h_ef(i, 2)};
1764 m.extTorque = F3{h_et(i, 0), h_et(i, 1), h_et(i, 2)};
1765 m.numWarm = 0;
1766 gidToLocal.emplace(static_cast<unsigned>(h_gid(i)), i);
1767 }
1768 return packs;
1769 }
1770 // Distribute the previous-substep converged ledger onto its endpoint particles: each pair
1771 // rides on BOTH locally-owned endpoints (after the move either endpoint's new rank may own the
1772 // pair; the unpack dedupes by key). Beyond kWarmCarryMax the lowest-|impulse| entry is
1773 // evicted — a dropped pair merely warm-starts cold on the receiving rank.
1774 static void carryWarmLedger(const Particles& P, std::vector<MigratePack>& packs,
1775 const std::unordered_map<unsigned, int>& gidToLocal) {
1776 if (P.prevPairCount > 0) {
1777 const int pc = P.prevPairCount;
1778 // Full-view mirrors (not row-range subviews): a row range of a LayoutLeft float*[3] view is
1779 // non-contiguous, and a device->host deep_copy of it has no copy mechanism on CUDA.
1780 auto h_k = Kokkos::create_mirror_view(P.prevPairKeys);
1781 auto h_l = Kokkos::create_mirror_view(P.prevLambda);
1782 auto h_lt = Kokkos::create_mirror_view(P.prevLambdaT);
1783 auto h_pi = Kokkos::create_mirror_view(P.prevPosImpulse);
1784 auto h_rb = Kokkos::create_mirror_view(P.prevRestBank);
1785 auto h_rv = Kokkos::create_mirror_view(P.prevRestVPeak);
1786 Kokkos::deep_copy(h_k, P.prevPairKeys);
1787 Kokkos::deep_copy(h_l, P.prevLambda);
1788 Kokkos::deep_copy(h_lt, P.prevLambdaT);
1789 Kokkos::deep_copy(h_pi, P.prevPosImpulse);
1790 Kokkos::deep_copy(h_rb, P.prevRestBank);
1791 Kokkos::deep_copy(h_rv, P.prevRestVPeak);
1792 auto attach = [&](int i, const WarmPairEntry& e, float w) {
1793 MigratePack& m = packs[(std::size_t)i];
1794 if (m.numWarm < kWarmCarryMax) {
1795 m.warm[m.numWarm++] = e;
1796 return;
1797 }
1798 int worst = 0;
1799 float worstW = 1e30f;
1800 for (int s = 0; s < kWarmCarryMax; ++s) {
1801 const float ws = std::fabs(m.warm[s].lambda) + std::fabs(m.warm[s].posImpulse);
1802 if (ws < worstW) {
1803 worstW = ws;
1804 worst = s;
1805 }
1806 }
1807 if (w > worstW)
1808 m.warm[worst] = e;
1809 };
1810 for (int e = 0; e < pc; ++e) {
1811 const unsigned long long k = h_k(e);
1812 if (k == ~0ull)
1813 continue;
1814 WarmPairEntry we;
1815 we.key = k;
1816 we.lambda = h_l(e);
1817 we.lambdaT[0] = h_lt(e, 0);
1818 we.lambdaT[1] = h_lt(e, 1);
1819 we.lambdaT[2] = h_lt(e, 2);
1820 we.posImpulse = h_pi(e);
1821 we.restBank = h_rb(e);
1822 we.restVPeak = h_rv(e);
1823 if (we.lambda == 0.0f && we.posImpulse == 0.0f && we.lambdaT[0] == 0.0f &&
1824 we.lambdaT[1] == 0.0f && we.lambdaT[2] == 0.0f && we.restBank == 0.0f)
1825 continue; // dead entry: carrying it only evicts live ones
1826 const float w = std::fabs(we.lambda) + std::fabs(we.posImpulse) + std::fabs(we.restBank);
1827 const unsigned hi = static_cast<unsigned>(k >> 32);
1828 const unsigned lo = static_cast<unsigned>(k & 0xFFFFFFFFu);
1829 if (auto it = gidToLocal.find(hi); it != gidToLocal.end())
1830 attach(it->second, we, w);
1831 if (lo != 0xFFFFFFFFu)
1832 if (auto it = gidToLocal.find(lo); it != gidToLocal.end())
1833 attach(it->second, we, w);
1834 }
1835 }
1836 }
1837 // Force-engine (Hertz–Mindlin) history. Pack the LIVE cached-pair springs (hertzKeys/hertzXi
1838 // hold the current values; keys are gid-based) onto their locally-owned endpoints.
1839 static void carryHertzLedger(const Particles& P, std::vector<MigratePack>& packs,
1840 const std::unordered_map<unsigned, int>& gidToLocal) {
1841 if (P.hertzNumPairs > 0) {
1842 const int hn = P.hertzNumPairs;
1843 auto h_hk = Kokkos::create_mirror_view(P.hertzKeys);
1844 auto h_hx = Kokkos::create_mirror_view(P.hertzXi);
1845 Kokkos::deep_copy(h_hk, P.hertzKeys);
1846 Kokkos::deep_copy(h_hx, P.hertzXi);
1847 auto attachHertz = [&](int i, const HertzPairEntry& e, float w) {
1848 MigratePack& m = packs[(std::size_t)i];
1849 if (m.numHertz < kWarmCarryMax) {
1850 m.hertz[m.numHertz++] = e;
1851 return;
1852 }
1853 int worst = 0;
1854 float worstW = 1e30f;
1855 for (int s = 0; s < kWarmCarryMax; ++s) {
1856 const float ws = std::fabs(m.hertz[s].xi[0]) + std::fabs(m.hertz[s].xi[1]) +
1857 std::fabs(m.hertz[s].xi[2]);
1858 if (ws < worstW) {
1859 worstW = ws;
1860 worst = s;
1861 }
1862 }
1863 if (w > worstW)
1864 m.hertz[worst] = e;
1865 };
1866 for (int e = 0; e < hn; ++e) {
1867 HertzPairEntry he;
1868 he.key = h_hk(e);
1869 he.xi[0] = h_hx(e, 0);
1870 he.xi[1] = h_hx(e, 1);
1871 he.xi[2] = h_hx(e, 2);
1872 if (he.xi[0] == 0.0f && he.xi[1] == 0.0f && he.xi[2] == 0.0f)
1873 continue; // open / historyless pair: nothing worth carrying
1874 const float w = std::fabs(he.xi[0]) + std::fabs(he.xi[1]) + std::fabs(he.xi[2]);
1875 const unsigned hi = static_cast<unsigned>(he.key >> 32);
1876 const unsigned lo = static_cast<unsigned>(he.key & 0xFFFFFFFFu);
1877 if (auto it = gidToLocal.find(hi); it != gidToLocal.end())
1878 attachHertz(it->second, he, w);
1879 if (auto it = gidToLocal.find(lo); it != gidToLocal.end())
1880 attachHertz(it->second, he, w);
1881 }
1882 }
1883 }
1884 // Force-engine (Hertz–Mindlin) wall history: each particle's wall-history slots, verbatim.
1885 static void packWallHistory(const Particles& P, std::vector<MigratePack>& packs, int no) {
1886 auto h_xw = Kokkos::create_mirror_view(P.hertzXiWall);
1887 auto h_sw = Kokkos::create_mirror_view(P.hertzSnWall);
1888 Kokkos::deep_copy(h_xw, P.hertzXiWall);
1889 Kokkos::deep_copy(h_sw, P.hertzSnWall);
1890 for (int i = 0; i < no; ++i)
1891 for (int wi = 0; wi < Particles::kHertzMaxWalls; ++wi) {
1892 const int slot = i * Particles::kHertzMaxWalls + wi;
1893 MigratePack& m = packs[(std::size_t)i];
1894 m.hertzXiWall[wi][0] = h_xw(slot, 0);
1895 m.hertzXiWall[wi][1] = h_xw(slot, 1);
1896 m.hertzXiWall[wi][2] = h_xw(slot, 2);
1897 m.hertzSnWall[wi] = h_sw(slot);
1898 }
1899 }
1900 // Download the committed state and pack it (position drives ownership; the rest is the payload).
1901 // Each particle also carries its slice of the persistent-contact ledger (see MigratePack).
1902 void packState(Particles& P, std::vector<peclet::core::Vec<3>>& pos, std::vector<char>& payload) {
1903 const int no = P.numReal;
1904 std::unordered_map<unsigned, int> gidToLocal;
1905 std::vector<MigratePack> packs = packParticleRecords(P, pos, payload, gidToLocal);
1906 carryWarmLedger(P, packs, gidToLocal);
1907 carryHertzLedger(P, packs, gidToLocal);
1908 packWallHistory(P, packs, no);
1909 for (int i = 0; i < no; ++i)
1910 std::memcpy(&payload[(std::size_t)i * sizeof(MigratePack)], &packs[(std::size_t)i],
1911 sizeof(MigratePack));
1912 }
1913 // Unpack the migrated particles back into the SoA [0,newN) and upload; rebuild the rank's
1914 // persistent-contact ledger (prevPairKeys sorted + aligned impulse stores) from the union of the
1915 // arriving particles' carried slices.
1916 void unpackState(Particles& P, const std::vector<peclet::core::Vec<3>>& pos,
1917 const std::vector<char>& payload, std::size_t newN) {
1918 auto h_pos = Kokkos::create_mirror_view(P.pos);
1919 auto h_quat = Kokkos::create_mirror_view(P.quat);
1920 auto h_vel = Kokkos::create_mirror_view(P.vel);
1921 auto h_angVel = Kokkos::create_mirror_view(P.angVel);
1922 auto h_invI = Kokkos::create_mirror_view(P.invInertia);
1923 auto h_invM = Kokkos::create_mirror_view(P.invMass);
1924 auto h_scale = Kokkos::create_mirror_view(P.scale);
1925 auto h_tScale = Kokkos::create_mirror_view(P.targetScale);
1926 auto h_shape = Kokkos::create_mirror_view(P.shapeId);
1927 auto h_pf = Kokkos::create_mirror_view(P.planeFriction);
1928 auto h_gid = Kokkos::create_mirror_view(P.gid);
1929 auto h_mat = Kokkos::create_mirror_view(P.materialId);
1930 auto h_grd = Kokkos::create_mirror_view(P.groundedLevel);
1931 auto h_orp = Kokkos::create_mirror_view(P.bodyOrphan);
1932 auto h_ovp = Kokkos::create_mirror_view(P.bodyOrphanVPeak);
1933 Kokkos::deep_copy(h_orp, P.bodyOrphan); // slots past newN keep defined values
1934 Kokkos::deep_copy(h_ovp, P.bodyOrphanVPeak);
1935 auto h_ef = Kokkos::create_mirror_view(P.extForce);
1936 auto h_et = Kokkos::create_mirror_view(P.extTorque);
1937 Kokkos::deep_copy(h_ef, P.extForce);
1938 Kokkos::deep_copy(h_et, P.extTorque);
1939 std::vector<WarmPairEntry> ledger;
1940 ledger.reserve(newN * 4);
1941 std::vector<HertzPairEntry> hertzLedger;
1942 hertzLedger.reserve(newN * 4);
1943 auto h_xw = Kokkos::create_mirror_view(P.hertzXiWall);
1944 auto h_sw = Kokkos::create_mirror_view(P.hertzSnWall);
1945 Kokkos::deep_copy(h_xw, P.hertzXiWall); // slots past newN keep defined values on CUDA mirrors
1946 Kokkos::deep_copy(h_sw, P.hertzSnWall);
1947 for (std::size_t i = 0; i < newN; ++i) {
1948 h_pos((int)i, 0) = pos[i][0];
1949 h_pos((int)i, 1) = pos[i][1];
1950 h_pos((int)i, 2) = pos[i][2];
1951 MigratePack m;
1952 std::memcpy(&m, &payload[i * sizeof(MigratePack)], sizeof(MigratePack));
1953 h_quat((int)i, 0) = m.quat.x;
1954 h_quat((int)i, 1) = m.quat.y;
1955 h_quat((int)i, 2) = m.quat.z;
1956 h_quat((int)i, 3) = m.quat.w;
1957 h_vel((int)i, 0) = m.vel.x;
1958 h_vel((int)i, 1) = m.vel.y;
1959 h_vel((int)i, 2) = m.vel.z;
1960 h_angVel((int)i, 0) = m.angVel.x;
1961 h_angVel((int)i, 1) = m.angVel.y;
1962 h_angVel((int)i, 2) = m.angVel.z;
1963 h_invI((int)i, 0) = m.invInertia.x;
1964 h_invI((int)i, 1) = m.invInertia.y;
1965 h_invI((int)i, 2) = m.invInertia.z;
1966 h_invM((int)i) = m.invMass;
1967 h_scale((int)i) = m.scale;
1968 h_tScale((int)i) = m.targetScale;
1969 h_shape((int)i) = m.shapeId;
1970 h_pf((int)i, 0) = m.planeFric0;
1971 h_pf((int)i, 1) = m.planeFric1;
1972 h_gid((int)i) = m.gid;
1973 h_mat((int)i) = m.materialId;
1974 h_grd((int)i) = m.groundedLevel;
1975 h_orp((int)i) = m.orphan;
1976 h_ovp((int)i) = m.orphanVPeak;
1977 h_ef((int)i, 0) = m.extForce.x;
1978 h_ef((int)i, 1) = m.extForce.y;
1979 h_ef((int)i, 2) = m.extForce.z;
1980 h_et((int)i, 0) = m.extTorque.x;
1981 h_et((int)i, 1) = m.extTorque.y;
1982 h_et((int)i, 2) = m.extTorque.z;
1983 for (int s = 0; s < (int)m.numWarm && s < kWarmCarryMax; ++s)
1984 ledger.push_back(m.warm[s]);
1985 for (int s = 0; s < (int)m.numHertz && s < kWarmCarryMax; ++s)
1986 hertzLedger.push_back(m.hertz[s]);
1987 for (int wi = 0; wi < Particles::kHertzMaxWalls; ++wi) {
1988 const int slot = (int)i * Particles::kHertzMaxWalls + wi;
1989 h_xw(slot, 0) = m.hertzXiWall[wi][0];
1990 h_xw(slot, 1) = m.hertzXiWall[wi][1];
1991 h_xw(slot, 2) = m.hertzXiWall[wi][2];
1992 h_sw(slot) = m.hertzSnWall[wi];
1993 }
1994 }
1995 Kokkos::deep_copy(P.pos, h_pos);
1996 Kokkos::deep_copy(P.quat, h_quat);
1997 Kokkos::deep_copy(P.vel, h_vel);
1998 Kokkos::deep_copy(P.angVel, h_angVel);
1999 Kokkos::deep_copy(P.invInertia, h_invI);
2000 Kokkos::deep_copy(P.invMass, h_invM);
2001 Kokkos::deep_copy(P.scale, h_scale);
2002 Kokkos::deep_copy(P.targetScale, h_tScale);
2003 Kokkos::deep_copy(P.shapeId, h_shape);
2004 Kokkos::deep_copy(P.planeFriction, h_pf);
2005 Kokkos::deep_copy(P.gid, h_gid);
2006 Kokkos::deep_copy(P.materialId, h_mat);
2007 Kokkos::deep_copy(P.groundedLevel, h_grd);
2008 Kokkos::deep_copy(P.bodyOrphan, h_orp);
2009 Kokkos::deep_copy(P.bodyOrphanVPeak, h_ovp);
2010 Kokkos::deep_copy(P.extForce, h_ef);
2011 Kokkos::deep_copy(P.extTorque, h_et);
2012
2013 // Ledger rebuild: sort by key, dedupe (a pair arrives once per locally-received endpoint; the
2014 // duplicates carry identical values), clamp to the store capacity, upload sorted + aligned —
2015 // exactly the layout the warm-start gather's binary search expects.
2016 std::sort(ledger.begin(), ledger.end(),
2017 [](const WarmPairEntry& a, const WarmPairEntry& b) { return a.key < b.key; });
2018 ledger.erase(
2019 std::unique(ledger.begin(), ledger.end(),
2020 [](const WarmPairEntry& a, const WarmPairEntry& b) { return a.key == b.key; }),
2021 ledger.end());
2022 const int nl = std::min<int>((int)ledger.size(), (int)P.prevPairKeys.extent(0));
2023 {
2024 auto hk = Kokkos::create_mirror_view(P.prevPairKeys);
2025 auto hl = Kokkos::create_mirror_view(P.prevLambda);
2026 auto hlt = Kokkos::create_mirror_view(P.prevLambdaT);
2027 auto hpi = Kokkos::create_mirror_view(P.prevPosImpulse);
2028 auto hrb = Kokkos::create_mirror_view(P.prevRestBank);
2029 auto hrv = Kokkos::create_mirror_view(P.prevRestVPeak);
2030 Kokkos::deep_copy(hk, P.prevPairKeys); // preserve tail entries beyond nl
2031 Kokkos::deep_copy(hl, P.prevLambda);
2032 Kokkos::deep_copy(hlt, P.prevLambdaT);
2033 Kokkos::deep_copy(hpi, P.prevPosImpulse);
2034 Kokkos::deep_copy(hrb, P.prevRestBank);
2035 Kokkos::deep_copy(hrv, P.prevRestVPeak);
2036 for (int e = 0; e < nl; ++e) {
2037 hk(e) = ledger[(std::size_t)e].key;
2038 hl(e) = ledger[(std::size_t)e].lambda;
2039 hlt(e, 0) = ledger[(std::size_t)e].lambdaT[0];
2040 hlt(e, 1) = ledger[(std::size_t)e].lambdaT[1];
2041 hlt(e, 2) = ledger[(std::size_t)e].lambdaT[2];
2042 hpi(e) = ledger[(std::size_t)e].posImpulse;
2043 hrb(e) = ledger[(std::size_t)e].restBank;
2044 hrv(e) = ledger[(std::size_t)e].restVPeak;
2045 }
2046 Kokkos::deep_copy(P.prevPairKeys, hk);
2047 Kokkos::deep_copy(P.prevLambda, hl);
2048 Kokkos::deep_copy(P.prevLambdaT, hlt);
2049 Kokkos::deep_copy(P.prevPosImpulse, hpi);
2050 Kokkos::deep_copy(P.prevRestBank, hrb);
2051 Kokkos::deep_copy(P.prevRestVPeak, hrv);
2052 }
2053 P.prevPairCount = nl;
2054
2055 // Force-engine history rebuild: wall slots verbatim per (new local index, wall); the pair
2056 // ledger sorted + deduped into the hertzPrev store (the exact layout hertzRebuildPairs'
2057 // key-carry binary search expects), and the cached pair LIST invalidated — local pair slots
2058 // reference pre-migration indices, so the next force step must rebuild (and re-gathers the
2059 // halo then). A fresh rank may never have allocated the prev store: size it here.
2060 Kokkos::deep_copy(P.hertzXiWall, h_xw);
2061 Kokkos::deep_copy(P.hertzSnWall, h_sw);
2062 std::sort(hertzLedger.begin(), hertzLedger.end(),
2063 [](const HertzPairEntry& a, const HertzPairEntry& b) { return a.key < b.key; });
2064 hertzLedger.erase(std::unique(hertzLedger.begin(), hertzLedger.end(),
2065 [](const HertzPairEntry& a, const HertzPairEntry& b) {
2066 return a.key == b.key;
2067 }),
2068 hertzLedger.end());
2069 const int nh = (int)hertzLedger.size();
2070 if ((int)P.hertzPrevKeys.extent(0) < nh) {
2071 P.hertzPrevKeys = Kokkos::View<unsigned long long*, CpMem>("hertzPrevKeys", nh);
2072 P.hertzPrevXi = Kokkos::View<float* [3], CpMem>("hertzPrevXi", nh);
2073 }
2074 if (nh > 0) {
2075 auto hk = Kokkos::create_mirror_view(P.hertzPrevKeys);
2076 auto hx = Kokkos::create_mirror_view(P.hertzPrevXi);
2077 Kokkos::deep_copy(hk, P.hertzPrevKeys);
2078 Kokkos::deep_copy(hx, P.hertzPrevXi);
2079 for (int e = 0; e < nh; ++e) {
2080 hk(e) = hertzLedger[(std::size_t)e].key;
2081 hx(e, 0) = hertzLedger[(std::size_t)e].xi[0];
2082 hx(e, 1) = hertzLedger[(std::size_t)e].xi[1];
2083 hx(e, 2) = hertzLedger[(std::size_t)e].xi[2];
2084 }
2085 Kokkos::deep_copy(P.hertzPrevKeys, hk);
2086 Kokkos::deep_copy(P.hertzPrevXi, hx);
2087 }
2088 P.hertzPrevCount = nh;
2089 P.hertzNumPairs = -1;
2090
2091 P.numReal = (int)newN;
2092 P.numParticles = (int)newN;
2093 // The cached owner<->ghost topology (sendIdx, selfIdx, refPos_) is slot-indexed over the
2094 // PRE-migration owned set. Reusing it is still sound when every slot's new occupant lies within
2095 // the skin of that slot's build position (the displacement check is per slot, and every forward
2096 // re-packs the occupant's full state, gid included), but that is an accident of where the
2097 // arrivals land, not an invariant of the migration -- so drop it and let the next gather()
2098 // rebuild. A migration already pays a host round trip; the rebuild adds one NBX round.
2099 haveTopo_ = false;
2100 }
2101
2102 public:
2103 // owner slice [0,numReal) -> ghost slots [numReal,..), verbatim (velocity / angular velocity).
2104 void forward(V3 field) {
2105 if (!exchanges())
2106 return;
2107 haloPackF3(field, ownedF3_, numReal_);
2108 dev_.forward(ownedF3_, ghostF3_);
2109 haloUnpackF3(field, ghostF3_, shiftDev_, ghosts(), /*doShift=*/false);
2110 }
2111 // owner slice -> ghost slots with the periodic image shift added (positions).
2112 void forwardPositions(V3 field) {
2113 if (!exchanges())
2114 return;
2115 haloPackF3(field, ownedF3_, numReal_);
2116 dev_.forward(ownedF3_, ghostF3_);
2117 haloUnpackF3(field, ghostF3_, shiftDev_, ghosts(), /*doShift=*/true);
2118 }
2119 // owner slice -> ghost slots, verbatim (quaternions).
2120 void forward4(V4 field) {
2121 if (!exchanges())
2122 return;
2123 haloPackF4(field, ownedF4_, numReal_);
2124 dev_.forward(ownedF4_, ghostF4_);
2125 haloUnpackF4(field, ghostF4_, ghosts());
2126 }
2127
2129 ContactOwnership contactOwnership(const Particles& P) const {
2130 return ContactOwnership{rank_, numReal_, P.gid, ghostSource_, copyOffsets_,
2131 copyRanks_, ghostImage_, copyImage_, selfOffsets_, selfImage_};
2132 }
2133
2137 std::vector<float> debugGhostShiftsBySlot() const {
2138 std::vector<float> out(3 * static_cast<std::size_t>(numGhost_ > 0 ? numGhost_ : 0), 0.0f);
2139 if (numGhost_ <= 0)
2140 return out;
2141 auto hs = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), shiftDev_);
2142 auto hk = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), ghostSlot_);
2143 for (int g = 0; g < numGhost_; ++g) {
2144 const int s = hk(g);
2145 out[3 * s] = hs(g).x;
2146 out[3 * s + 1] = hs(g).y;
2147 out[3 * s + 2] = hs(g).z;
2148 }
2149 return out;
2150 }
2151
2152 // ---- ghost -> owner reconciliation (docs/mpi_momentum_conservation.md §2.3) ----
2153 // Every sync below is COLLECTIVE (a reverse, then a forward, over a possibly one-sided
2154 // topology): it may be skipped only when this rank neither sends nor receives (exchanges()),
2155 // never because this rank "wrote no ghost" -- that is rank-local and deadlocks the neighbours.
2156
2158 void markVelocityBaseline(Particles& P) {
2159 if (numGhost_ <= 0)
2160 return;
2161 haloMarkVelocityBaseline(
2162 VelocityPhaseViews{P.velPred, P.angVelPred, P.bodyOrphan, P.bodyOrphanVPeak},
2163 velocityBaselines(), ghosts());
2164 }
2172 void syncVelocities(Particles& P, bool rotation) {
2173 if (!exchanges())
2174 return;
2175 if (velM_) {
2176 syncVelocitiesM(P, rotation);
2177 return;
2178 }
2179 haloPackVelocityIncrement(
2180 VelocityPhaseViews{P.velPred, P.angVelPred, P.bodyOrphan, P.bodyOrphanVPeak},
2181 velocityBaselines(), ghostVelInc_, ghosts());
2182 Kokkos::deep_copy(
2183 Kokkos::subview(ownedVelInc_, std::pair<std::size_t, std::size_t>(0, numReal_)),
2184 VelocityIncrement{});
2185 dev_.reverse(ghostVelInc_, ownedVelInc_);
2186 haloApplyVelocityIncrement(
2187 VelocityPhaseViews{P.velPred, P.angVelPred, P.bodyOrphan, P.bodyOrphanVPeak}, ownedVelInc_,
2188 numReal_);
2189 if (rotation) { // one fused exchange of (velPred, angVelPred)
2190 haloPackVelocityState(P.bodyPred(), ownedVelState_, nIface_, iface_);
2191 dev_.forward(ownedVelState_, ghostVelState_);
2192 haloUnpackVelocityState(P.bodyPred(), ghostVelState_, ghosts());
2193 } else {
2194 forward(P.velPred);
2195 }
2196 markVelocityBaseline(P);
2197 }
2200 void publishPositions(Particles& P, bool rotation) {
2201 if (!exchanges())
2202 return;
2203 forwardPositionState(P, rotation);
2204 markPositionPublished(P);
2205 }
2207 void forwardPositionState(Particles& P, bool rotation) {
2208 if (rotation) { // one fused exchange of (posPred + periodic shift, quatPred)
2209 haloPackPositionState(P.bodyPred(), ownedPosState_, nIface_, iface_);
2210 dev_.forward(ownedPosState_, ghostPosState_);
2211 haloUnpackPositionState(P.bodyPred(), ghostPosState_, shiftDev_, ghosts());
2212 } else {
2213 forwardPositions(P.posPred);
2214 }
2215 }
2217 void markPositionPublished(Particles& P) {
2218 haloMarkPositionBaseline(P.posPred, basePos_, ghosts());
2219 if (posM_) // rank-level M (§13.3 step 9): the owners' position seeds
2220 haloMarkOwnerPositionSeeds(P.posPred, ownerSeedPos_, nPosRows_, posRows_);
2221 }
2227 void syncPositions(Particles& P, bool rotation) {
2228 if (!exchanges())
2229 return;
2230 if (posM_) { // the fused M reconciliation (MPackZero, reverse, MApply, forward, MUnpack)
2231 haloPositionMPackZero(P.posPred, basePos_, P.aPos, ghostPosInc_, ghosts(), ownedPosInc_,
2232 posRows_, nPosRows_);
2233 dev_.reverse(ghostPosInc_, ownedPosInc_);
2234 if (rotation)
2235 positionMRound(P, ownedPosState_, ghostPosState_);
2236 else
2237 positionMRound(P, ownedF3_, ghostF3_);
2238 return;
2239 }
2240 haloPackPositionIncrement(P.posPred, basePos_, ghostPosInc_, ghosts());
2241 Kokkos::deep_copy(
2242 Kokkos::subview(ownedPosInc_, std::pair<std::size_t, std::size_t>(0, numReal_)),
2243 PositionIncrement{});
2244 dev_.reverse(ghostPosInc_, ownedPosInc_);
2245 haloApplyPositionIncrement(P.posPred, ownedPosInc_, numReal_);
2246 publishPositions(P, rotation);
2247 }
2248
2249 // ---- rank-level M (docs/contact_solve_framework.md §13.3) ----
2251 bool velocityMassSplit() const { return velM_; }
2252 bool positionMassSplit() const { return posM_; }
2253
2261 void openVelocityPhase(Particles& P, bool rotation, bool shares) {
2262 if (!exchanges())
2263 return;
2264 ensureClampCounter(P);
2265 const int no = numReal_, ng = numGhost_;
2266 haloPackOpeningIncrement(
2267 VelocityPhaseViews{P.velPred, P.angVelPred, P.bodyOrphan, P.bodyOrphanVPeak},
2268 velocityBaselines(), P.aVel, P.aPos, ghostOpenInc_, GhostRange{ghostSlot_, no, ng});
2269 Kokkos::deep_copy(Kokkos::subview(ownedOpenInc_, std::pair<std::size_t, std::size_t>(0, no)),
2270 OpeningIncrement{});
2271 dev_.reverse(ghostOpenInc_, ownedOpenInc_);
2272 haloApplyOpening(VelocityPhaseViews{P.velPred, P.angVelPred, P.bodyOrphan, P.bodyOrphanVPeak},
2273 P.aVel, P.aPos, P.kVel, P.kPos, ownedOpenInc_, no);
2274 if (rotation) {
2275 haloPackOpeningState(
2276 VelocityPhaseViews{P.velPred, P.angVelPred, P.bodyOrphan, P.bodyOrphanVPeak}, P.kVel,
2277 P.kPos, ownedOpenState_, no);
2278 dev_.forward(ownedOpenState_, ghostOpenState_);
2279 haloUnpackOpeningState(
2280 VelocityPhaseViews{P.velPred, P.angVelPred, P.bodyOrphan, P.bodyOrphanVPeak}, P.kVel,
2281 P.kPos, ghostOpenState_, GhostRange{ghostSlot_, no, ng});
2282 } else {
2283 haloPackOpeningState(
2284 VelocityPhaseViews{P.velPred, P.angVelPred, P.bodyOrphan, P.bodyOrphanVPeak}, P.kVel,
2285 P.kPos, ownedOpenStateNR_, no);
2286 dev_.forward(ownedOpenStateNR_, ghostOpenStateNR_);
2287 haloUnpackOpeningState(
2288 VelocityPhaseViews{P.velPred, P.angVelPred, P.bodyOrphan, P.bodyOrphanVPeak}, P.kVel,
2289 P.kPos, ghostOpenStateNR_, GhostRange{ghostSlot_, no, ng});
2290 }
2291 buildMRows(P.kVel, velRows_, nVelRows_);
2292 buildMRows(P.kPos, posRows_, nPosRows_);
2293 velM_ = posM_ = true;
2294 orphanShares_ = shares;
2295 markVelocityReconciled(P);
2296 }
2304 void openPositionCounts(Particles& P, bool velocityMask) {
2305 if (!exchanges())
2306 return;
2307 const int no = numReal_, ng = numGhost_;
2308 if (velocityMask) {
2309 const unsigned long long bit = 1ull << rankColor_;
2310 haloPackGhostCountsMask(P.aVel, P.aPos, ghostCM_, GhostRange{ghostSlot_, no, ng}, bit);
2311 Kokkos::deep_copy(Kokkos::subview(ownedCM_, std::pair<std::size_t, std::size_t>(0, no)),
2312 PositionCountsMask{0ull, 0, 0});
2313 dev_.reverse(ghostCM_, ownedCM_);
2314 haloOwnerCountsMask(P.aVel, P.aPos, P.kPos, P.velMask, ownedCM_, bit, no);
2315 dev_.forward(ownedCM_, ghostCM_);
2316 haloUnpackCountsMask(P.kPos, P.velMask, ghostCM_, GhostRange{ghostSlot_, no, ng});
2317 buildMRows(P.kPos, posRows_, nPosRows_);
2318 posM_ = true;
2319 return;
2320 }
2321 haloPackGhostInt(P.aPos, ghostCnt_, GhostRange{ghostSlot_, no, ng});
2322 Kokkos::deep_copy(Kokkos::subview(ownedCnt_, std::pair<std::size_t, std::size_t>(0, no)), 0);
2323 dev_.reverse(ghostCnt_, ownedCnt_);
2324 haloOwnerCountK(P.aPos, P.kPos, ownedCnt_, no);
2325 dev_.forward(ownedCnt_, ghostCnt_);
2326 haloUnpackGhostInt(P.kPos, ghostCnt_, GhostRange{ghostSlot_, no, ng});
2327 buildMRows(P.kPos, posRows_, nPosRows_);
2328 posM_ = true;
2329 }
2331 void restoreOrphanBalance(Particles& P) {
2332 if (!velM_ || !orphanShares_)
2333 return;
2334 haloRestoreOrphanBalance(P.bodyOrphan, ownerSeedOrphan_, P.aVel, P.kVel, nVelRows_, velRows_);
2335 }
2345 void mapVelocitySlots(Particles& P) {
2346 const int no = numReal_, ng = numGhost_;
2347 if (ng <= 0)
2348 return;
2349 if (canonStale_ || ghostCanon_.extent(0) < static_cast<std::size_t>(ng)) {
2350 const int nr = numReceived_; // cross-rank ghost slots [0, nr); self ghosts [nr, ng)
2351 auto hg =
2352 Kokkos::create_mirror_view(Kokkos::subview(P.gid, std::pair<int, int>(no, no + nr)));
2353 Kokkos::deep_copy(hg, Kokkos::subview(P.gid, std::pair<int, int>(no, no + nr)));
2354 std::vector<std::pair<int, int>> key(static_cast<std::size_t>(nr));
2355 for (int g = 0; g < nr; ++g)
2356 key[static_cast<std::size_t>(g)] = {hg(g), g};
2357 std::sort(key.begin(), key.end());
2358 std::vector<int> canon(static_cast<std::size_t>(ng));
2359 for (std::size_t p = 0; p < key.size();) {
2360 std::size_t e = p;
2361 while (e < key.size() && key[e].first == key[p].first)
2362 ++e;
2363 const int c = no + key[p].second; // the lowest ghost slot of this gid
2364 for (std::size_t t = p; t < e; ++t)
2365 canon[static_cast<std::size_t>(key[t].second)] = c;
2366 p = e;
2367 }
2368 for (int g = nr; g < ng; ++g) // a local self ghost: its owned row
2369 canon[static_cast<std::size_t>(g)] = selfIdx_[static_cast<std::size_t>(g - nr)];
2370 ghostCanon_ = peclet::core::toDevice(canon, "peclet::dem::halo::ghostCanon");
2371 canonStale_ = false;
2372 }
2373 haloMapVelocitySlots(P.realIndices, ghostCanon_, no, ng);
2374 }
2375
2376 private:
2385 void ensureRankColoring(double band) {
2386 // Keyed on the band AND a fingerprint of the decomposition, so every way the blocks can
2387 // change (rebalance, migrateTo, migrate_to_weights, a re-init) recolours.
2388 const int nb = static_cast<int>(dec_.numBlocks());
2389 unsigned long long fp = 1469598103934665603ull;
2390 for (int b = 0; b < nb; ++b) {
2391 const auto blk = dec_.block(static_cast<std::size_t>(b));
2392 for (int d = 0; d < 3; ++d) {
2393 fp = (fp ^ static_cast<unsigned long long>(blk.origin[d])) * 1099511628211ull;
2394 fp = (fp ^ static_cast<unsigned long long>(blk.size[d])) * 1099511628211ull;
2395 }
2396 }
2397 if (band == colorBand_ && fp == colorFingerprint_)
2398 return;
2399 colorBand_ = band;
2400 colorFingerprint_ = fp;
2401 const auto& gs = dec_.globalSize();
2402 std::vector<std::array<double, 6>> box(static_cast<std::size_t>(nb));
2403 for (int b = 0; b < nb; ++b) {
2404 const auto blk = dec_.block(static_cast<std::size_t>(b));
2405 for (int d = 0; d < 3; ++d) {
2406 box[b][d] = map_.origin[d] + static_cast<double>(blk.origin[d]) * map_.cellSize[d];
2407 box[b][3 + d] = box[b][d] + static_cast<double>(blk.size[d]) * map_.cellSize[d];
2408 }
2409 }
2410 const double lim2 = 4.0 * band * band;
2411 auto adjacent = [&](int a, int b) {
2412 double d2 = 0.0;
2413 for (int d = 0; d < 3; ++d) {
2414 const double L = static_cast<double>(gs[d]) * map_.cellSize[d];
2415 auto gap = [&](double shift) {
2416 const double loB = box[b][d] + shift, hiB = box[b][3 + d] + shift;
2417 return std::max(0.0, std::max(box[a][d] - hiB, loB - box[a][3 + d]));
2418 };
2419 double g = gap(0.0);
2420 if (map_.periodic[d])
2421 g = std::min(g, std::min(gap(L), gap(-L)));
2422 d2 += g * g;
2423 }
2424 return d2 <= lim2;
2425 };
2426 std::vector<int> col(static_cast<std::size_t>(nb), 0);
2427 int maxc = 0;
2428 for (int r = 0; r < nb; ++r) {
2429 unsigned long long used = 0ull;
2430 for (int q = 0; q < r; ++q)
2431 if (adjacent(r, q))
2432 used |= 1ull << col[q];
2433 int c = 0;
2434 while (c < 64 && ((used >> c) & 1ull))
2435 ++c;
2436 if (c >= 64)
2437 throw std::runtime_error(
2438 "ParticleHalo: the rank graph needs more than 64 colours for rank-level X "
2439 "(docs/contact_solve_framework.md §1.4); the blocks are too small for the band");
2440 col[r] = c;
2441 maxc = std::max(maxc, c);
2442 }
2443 rankColor_ = col[static_cast<std::size_t>(rank_)];
2444 numRankColors_ = maxc + 1;
2445 }
2448 void buildInterfaceRows(const peclet::core::halo::ParticleHaloTopology<3>::FlatTopo& t, int no) {
2449 std::vector<unsigned char> mark(static_cast<std::size_t>(std::max(no, 1)), 0);
2450 for (const auto i : t.sendIdx)
2451 mark[static_cast<std::size_t>(i)] = 1;
2452 for (const auto i : t.selfIdx)
2453 mark[static_cast<std::size_t>(i)] = 1;
2454 std::vector<int> rows;
2455 for (int i = 0; i < no; ++i)
2456 if (mark[static_cast<std::size_t>(i)])
2457 rows.push_back(i);
2458 nIface_ = static_cast<int>(rows.size());
2459 if (rows.empty())
2460 rows.push_back(0); // never read (n = 0); keeps the list non-empty (an empty one = all rows)
2461 iface_ = peclet::core::toDevice(rows, "peclet::dem::halo::ifaceRows");
2462 ifaceMark_ = peclet::core::toDevice(mark, "peclet::dem::halo::ifaceMark");
2463 }
2468 void buildMRows(Vi k, Vi& rows, int& nRows) {
2469 const int no = numReal_;
2470 if (rows.extent(0) < static_cast<std::size_t>(std::max(no, 1)))
2471 rows = Vi("peclet::dem::halo::mRows", static_cast<std::size_t>(std::max(no, 1)));
2472 nRows = haloBuildMRows(k, ifaceMark_, rows, no);
2473 }
2474 void ensureClampCounter(Particles& P) {
2475 if (P.orphanClampCount.data() == nullptr)
2476 P.orphanClampCount = Kokkos::View<int, CpMem>("peclet::dem::orphanClampCount");
2477 }
2480 void markVelocityReconciled(Particles& P) {
2481 haloMarkOwnerVelocitySeeds(P.velPred, P.angVelPred, P.bodyOrphan, ownerSeedVel_,
2482 ownerSeedAngVel_, ownerSeedOrphan_, nVelRows_, velRows_);
2483 if (orphanShares_)
2484 haloSetOrphanShares(P.bodyOrphan, P.kVel, numReal_ + numGhost_);
2485 markVelocityBaseline(P);
2486 }
2489 void syncVelocitiesM(Particles& P, bool rotation) {
2490 haloVelocityMPackZero(
2491 VelocityPhaseViews{P.velPred, P.angVelPred, P.bodyOrphan, P.bodyOrphanVPeak},
2492 velocityBaselines(), P.aVel, ghostVelInc_, ghosts(), ownedVelInc_, velRows_, nVelRows_);
2493 dev_.reverse(ghostVelInc_, ownedVelInc_);
2494 if (orphanShares_) {
2495 if (rotation)
2496 velocityMRound(P, ownedVelStateB_, ghostVelStateB_);
2497 else
2498 velocityMRound(P, ownedVelStateBNR_, ghostVelStateBNR_);
2499 } else if (rotation) {
2500 velocityMRound(P, ownedVelState_, ghostVelState_);
2501 } else {
2502 velocityMRound(P, ownedF3_, ghostF3_);
2503 }
2504 }
2506 template <class S>
2507 void velocityMRound(Particles& P, peclet::core::View<S> owned, peclet::core::View<S> ghost) {
2508 haloVelocityMApply(VelocityPhaseViews{P.velPred, P.angVelPred, P.bodyOrphan, P.bodyOrphanVPeak},
2509 ownerSeedVel_, ownerSeedAngVel_, ownerSeedOrphan_, P.aVel, P.kVel,
2510 ownedVelInc_, P.orphanClampCount, P.maxConsensus, velRows_, nVelRows_,
2511 ifaceMark_, owned, orphanShares_);
2512 dev_.forward(owned, ghost);
2513 haloVelocityMUnpack(
2514 VelocityPhaseViews{P.velPred, P.angVelPred, P.bodyOrphan, P.bodyOrphanVPeak}, ghost,
2515 velocityBaselines(), P.aVel, P.kVel, ghostVelInc_, P.maxConsensus, ghosts(), orphanShares_);
2516 }
2518 template <class S>
2519 void positionMRound(Particles& P, peclet::core::View<S> owned, peclet::core::View<S> ghost) {
2520 haloPositionMApply(P.bodyPred(), ownerSeedPos_, P.aPos, P.kPos, ownedPosInc_, P.maxConsensus,
2521 posRows_, nPosRows_, ifaceMark_, owned);
2522 dev_.forward(owned, ghost);
2523 haloPositionMUnpack(P.bodyPred(), ghost, shiftDev_, basePos_, P.aPos, P.kPos, ghostPosInc_,
2524 P.maxConsensus, ghosts());
2525 }
2526
2527 public:
2531 void syncFrictionCounts(Particles& P) {
2532 if (!exchanges())
2533 return;
2534 haloPackGhostColumn(P.planeFriction, ghostVal_, ghosts());
2535 Kokkos::deep_copy(Kokkos::subview(ownedVal_, std::pair<std::size_t, std::size_t>(0, numReal_)),
2536 0.0f);
2537 dev_.reverse(ghostVal_, ownedVal_);
2538 haloAddOwnedColumn(P.planeFriction, ownedVal_, numReal_);
2539 haloPackOwnedColumn(P.planeFriction, ownedVal_, numReal_);
2540 dev_.forward(ownedVal_, ghostVal_);
2541 haloUnpackGhostColumn(P.planeFriction, ghostVal_, ghosts());
2542 }
2548 void syncContactCounts(Particles& P) {
2549 if (!exchanges())
2550 return;
2551 haloPackGhostCount(P.constraintCounts, ghostCnt_, ghosts());
2552 Kokkos::deep_copy(Kokkos::subview(ownedCnt_, std::pair<std::size_t, std::size_t>(0, numReal_)),
2553 0);
2554 dev_.reverse(ghostCnt_, ownedCnt_);
2555 haloAddPackOwnedCount(P.constraintCounts, ownedCnt_, numReal_);
2556 dev_.forward(ownedCnt_, ghostCnt_);
2557 haloUnpackGhostCount(P.constraintCounts, ghostCnt_, ghosts());
2558 }
2559
2560 void selfMapReals(Vi realIndices, int no) {
2561 Kokkos::parallel_for(
2562 "peclet::dem::halo::selfMapReals", Kokkos::RangePolicy<CpExec>(0, no),
2563 KOKKOS_LAMBDA(int i) { realIndices(i) = i; });
2564 }
2565
2566 private:
2567 void allocBuffers(int no, int ng) {
2568 // Exact-sized: ParticleHalo::forward host-stages a deep_copy into the ghost View, so
2569 // its extent must equal numGhost; owned is indexed by sendIdx in [0,numReal).
2570 ownedF3_ = peclet::core::View<F3>("peclet::dem::halo::ownedF3", no);
2571 ghostF3_ = peclet::core::View<F3>("peclet::dem::halo::ghostF3", ng);
2572 ownedF4_ = peclet::core::View<F4>("peclet::dem::halo::ownedF4", no);
2573 ghostF4_ = peclet::core::View<F4>("peclet::dem::halo::ghostF4", ng);
2574 ownedPack_ = peclet::core::View<MpiGatherPack>("peclet::dem::halo::ownedPack", no);
2575 ghostPack_ = peclet::core::View<MpiGatherPack>("peclet::dem::halo::ghostPack", ng);
2576 // Reconciliation buffers: grow-only (core's reverse/forward address [0, numReceived) and the
2577 // self tail by subview/index, and owned rows through sendIdx/selfIdx < no).
2578 const std::size_t g1 = static_cast<std::size_t>(std::max(ng, 1)),
2579 o1 = static_cast<std::size_t>(std::max(no, 1));
2580 if (baseVel_.extent(0) < g1) {
2581 baseVel_ = V3("peclet::dem::halo::baseVel", g1);
2582 baseAngVel_ = V3("peclet::dem::halo::baseAngVel", g1);
2583 basePos_ = V3("peclet::dem::halo::basePos", g1);
2584 baseOrphan_ = Vf("peclet::dem::halo::baseOrphan", g1);
2585 baseOrphanPeak_ = Vf("peclet::dem::halo::baseOrphanPeak", g1);
2586 ghostVelInc_ = peclet::core::View<VelocityIncrement>("peclet::dem::halo::ghostVelInc", g1);
2587 ghostPosInc_ = peclet::core::View<PositionIncrement>("peclet::dem::halo::ghostPosInc", g1);
2588 ghostVal_ = peclet::core::View<float>("peclet::dem::halo::ghostVal", g1);
2589 ghostCnt_ = peclet::core::View<int>("peclet::dem::halo::ghostCnt", g1);
2590 ghostCM_ = peclet::core::View<PositionCountsMask>("peclet::dem::halo::ghostCM", g1);
2591 ghostVelState_ = peclet::core::View<VelocityState>("peclet::dem::halo::ghostVelState", g1);
2592 ghostPosState_ = peclet::core::View<PositionState>("peclet::dem::halo::ghostPosState", g1);
2593 ghostOpenInc_ = peclet::core::View<OpeningIncrement>("peclet::dem::halo::ghostOpenInc", g1);
2594 ghostOpenState_ = peclet::core::View<OpeningState>("peclet::dem::halo::ghostOpenState", g1);
2595 ghostOpenStateNR_ =
2596 peclet::core::View<OpeningStateNoRot>("peclet::dem::halo::ghostOpenStateNR", g1);
2597 ghostVelStateB_ = peclet::core::View<VelocityStateB>("peclet::dem::halo::ghostVelStateB", g1);
2598 ghostVelStateBNR_ =
2599 peclet::core::View<VelocityStateBNoRot>("peclet::dem::halo::ghostVelStateBNR", g1);
2600 }
2601 if (ownedVelInc_.extent(0) < o1) {
2602 ownedVelInc_ = peclet::core::View<VelocityIncrement>("peclet::dem::halo::ownedVelInc", o1);
2603 ownedPosInc_ = peclet::core::View<PositionIncrement>("peclet::dem::halo::ownedPosInc", o1);
2604 ownedVal_ = peclet::core::View<float>("peclet::dem::halo::ownedVal", o1);
2605 ownedCnt_ = peclet::core::View<int>("peclet::dem::halo::ownedCnt", o1);
2606 ownedCM_ = peclet::core::View<PositionCountsMask>("peclet::dem::halo::ownedCM", o1);
2607 ownedVelState_ = peclet::core::View<VelocityState>("peclet::dem::halo::ownedVelState", o1);
2608 ownedPosState_ = peclet::core::View<PositionState>("peclet::dem::halo::ownedPosState", o1);
2609 ownedOpenInc_ = peclet::core::View<OpeningIncrement>("peclet::dem::halo::ownedOpenInc", o1);
2610 ownedOpenState_ = peclet::core::View<OpeningState>("peclet::dem::halo::ownedOpenState", o1);
2611 ownedOpenStateNR_ =
2612 peclet::core::View<OpeningStateNoRot>("peclet::dem::halo::ownedOpenStateNR", o1);
2613 ownedVelStateB_ = peclet::core::View<VelocityStateB>("peclet::dem::halo::ownedVelStateB", o1);
2614 ownedVelStateBNR_ =
2615 peclet::core::View<VelocityStateBNoRot>("peclet::dem::halo::ownedVelStateBNR", o1);
2616 ownerSeedVel_ = V3("peclet::dem::halo::ownerSeedVel", o1);
2617 ownerSeedAngVel_ = V3("peclet::dem::halo::ownerSeedAngVel", o1);
2618 ownerSeedOrphan_ = Vf("peclet::dem::halo::ownerSeedOrphan", o1);
2619 ownerSeedPos_ = V3("peclet::dem::halo::ownerSeedPos", o1);
2620 }
2621 }
2622 // The maps the contact-ownership rule reads (docs/mpi_momentum_conservation.md §2.1), built on
2623 // the host from the flattened topology at every rebuild:
2624 // ghostSource_(s - no) the rank ghost slot s was received from (this rank for a periodic
2625 // self-ghost), indexed by the CANONICAL offset;
2626 // copyOffsets_/copyRanks_ CSR over owned rows: the ranks each owned row is ghosted to
2627 // (cross-rank only, ascending -- sendRanks is ascending).
2628 void buildOwnershipMaps(const peclet::core::halo::ParticleHaloTopology<3>::FlatTopo& t, int no,
2629 int ng, const std::vector<int>& hSlot) {
2630 const std::size_t g1 = static_cast<std::size_t>(std::max(ng, 1));
2631 std::vector<int> src(g1, rank_); // the self tail [numReceived, ng) stays rank_
2632 for (std::size_t k = 0; k < t.recvRanks.size(); ++k)
2633 for (int j = 0; j < t.recvCounts[k]; ++j)
2634 src[static_cast<std::size_t>(hSlot[static_cast<std::size_t>(t.recvOffsets[k]) + j])] =
2635 t.recvRanks[k];
2636 std::vector<int> off(static_cast<std::size_t>(no) + 1, 0);
2637 for (const auto i : t.sendIdx)
2638 ++off[static_cast<std::size_t>(i) + 1];
2639 for (int i = 0; i < no; ++i)
2640 off[static_cast<std::size_t>(i) + 1] += off[static_cast<std::size_t>(i)];
2641 // Integer image of a shift: round(shift / L) on a periodic axis, 0 otherwise (§5.3).
2642 const auto& gsz = dec_.globalSize();
2643 auto imageOf = [&](const peclet::core::Vec<3>& sh) {
2644 int c[3] = {0, 0, 0};
2645 for (int d = 0; d < 3; ++d)
2646 if (map_.periodic[d]) {
2647 const double L = static_cast<double>(gsz[d]) * map_.cellSize[d];
2648 c[d] = static_cast<int>(std::lround(sh[d] / L));
2649 }
2650 return imagePack(c[0], c[1], c[2]);
2651 };
2652 std::vector<int> gimg(g1, imagePack(0, 0, 0));
2653 for (std::size_t j = 0; j < t.shift.size(); ++j)
2654 gimg[static_cast<std::size_t>(hSlot[j])] = imageOf(t.shift[j]);
2655 std::vector<int> ranks(std::max<std::size_t>(t.sendIdx.size(), 1), -1);
2656 std::vector<int> imgs(std::max<std::size_t>(t.sendIdx.size(), 1), imagePack(0, 0, 0));
2657 std::vector<int> cur(off.begin(), off.end() - 1);
2658 for (std::size_t k = 0; k < t.sendRanks.size(); ++k)
2659 for (int j = t.sendOffsets[k]; j < t.sendOffsets[k + 1]; ++j) {
2660 const std::size_t at =
2661 static_cast<std::size_t>(cur[static_cast<std::size_t>(t.sendIdx[j])]++);
2662 ranks[at] = t.sendRanks[k];
2663 imgs[at] = imageOf(t.sendShift[static_cast<std::size_t>(j)]);
2664 }
2665 // Self-image CSR over owned rows: the self tail [numReceived, ng) of the topology.
2666 std::vector<int> soff(static_cast<std::size_t>(no) + 1, 0);
2667 for (const auto i : t.selfIdx)
2668 ++soff[static_cast<std::size_t>(i) + 1];
2669 for (int i = 0; i < no; ++i)
2670 soff[static_cast<std::size_t>(i) + 1] += soff[static_cast<std::size_t>(i)];
2671 std::vector<int> simg(std::max<std::size_t>(t.selfIdx.size(), 1), imagePack(0, 0, 0));
2672 {
2673 std::vector<int> scur(soff.begin(), soff.end() - 1);
2674 for (std::size_t j = 0; j < t.selfIdx.size(); ++j)
2675 simg[static_cast<std::size_t>(scur[static_cast<std::size_t>(t.selfIdx[j])]++)] =
2676 imageOf(t.shift[static_cast<std::size_t>(t.numReceived) + j]);
2677 }
2678 selfOffsets_ = peclet::core::toDevice(soff, "peclet::dem::halo::selfOffsets");
2679 selfImage_ = peclet::core::toDevice(simg, "peclet::dem::halo::selfImage");
2680 ghostSource_ = peclet::core::toDevice(src, "peclet::dem::halo::ghostSource");
2681 ghostImage_ = peclet::core::toDevice(gimg, "peclet::dem::halo::ghostImage");
2682 copyOffsets_ = peclet::core::toDevice(off, "peclet::dem::halo::copyOffsets");
2683 copyRanks_ = peclet::core::toDevice(ranks, "peclet::dem::halo::copyRanks");
2684 copyImage_ = peclet::core::toDevice(imgs, "peclet::dem::halo::copyImage");
2685 }
2686 // Max Euclidean displacement of any owned particle since the last topology build (device reduce +
2687 // one scalar read-back) — the Verlet-skin reuse criterion.
2688 // public: nvcc forbids an extended __host__ __device__ (KOKKOS_LAMBDA) lambda inside a private
2689 // method.
2690 public:
2691 float maxOwnedDisplacement(const V3& pos, int no) const {
2692 // A rank that owns nothing has moved nothing. (It used to report "moved", and under the
2693 // global rebuild vote one empty rank then rebuilt every rank's halo at every gather.) An owned
2694 // count change forces the rebuild on its own, before this is asked.
2695 if (no <= 0)
2696 return 0.0f;
2697 if (refPos_.extent(0) < static_cast<std::size_t>(no))
2698 return 1e30f;
2699 float md = 0.0f;
2700 V3 p = pos, r = refPos_;
2701 Kokkos::parallel_reduce(
2702 "peclet::dem::halo::maxdisp", Kokkos::RangePolicy<CpExec>(0, no),
2703 KOKKOS_LAMBDA(const int i, float& m) {
2704 const float dx = p(i, 0) - r(i, 0), dy = p(i, 1) - r(i, 1), dz = p(i, 2) - r(i, 2);
2705 const float d = Kokkos::sqrt(dx * dx + dy * dy + dz * dz);
2706 if (d > m)
2707 m = d;
2708 },
2709 Kokkos::Max<float>(md));
2710 return md;
2711 }
2712
2713 private:
2714 // The ghosts' velocity-phase baselines (topology ghost order), as one VelocityPhaseViews.
2715 // This rank's ghost slots (GhostRange: ghostSlot_ over [numReal_, numReal_ + numGhost_)).
2716 GhostRange ghosts() const { return {ghostSlot_, numReal_, numGhost_}; }
2717 VelocityPhaseViews velocityBaselines() const {
2718 return {baseVel_, baseAngVel_, baseOrphan_, baseOrphanPeak_};
2719 }
2720 // Canonical ghost placement: topology ghost g -> slot offset in [0, ng). The received blocks go
2721 // in ascending source rank (core numbers them in message-arrival order); the local periodic
2722 // self-ghosts [numReceived, ng) keep their place after them.
2723 std::vector<int> uploadGhostSlots(const peclet::core::halo::ParticleHaloTopology<3>::FlatTopo& t,
2724 int ng) {
2725 std::vector<std::size_t> blocks(t.recvRanks.size());
2726 for (std::size_t k = 0; k < blocks.size(); ++k)
2727 blocks[k] = k;
2728 std::sort(blocks.begin(), blocks.end(),
2729 [&](std::size_t a, std::size_t b) { return t.recvRanks[a] < t.recvRanks[b]; });
2730 if (ghostSlot_.extent(0) < static_cast<std::size_t>(std::max(ng, 1)))
2731 ghostSlot_ = Vi("peclet::dem::halo::ghostSlot", static_cast<std::size_t>(std::max(ng, 1)));
2732 auto h = Kokkos::create_mirror_view(ghostSlot_);
2733 int next = 0;
2734 for (std::size_t k : blocks)
2735 for (int j = 0; j < t.recvCounts[k]; ++j)
2736 h(static_cast<int>(t.recvOffsets[k]) + j) = next++;
2737 for (int g = next; g < ng; ++g)
2738 h(g) = g;
2739 Kokkos::deep_copy(ghostSlot_, h);
2740 std::vector<int> hs(static_cast<std::size_t>(std::max(ng, 0)));
2741 for (int g = 0; g < ng; ++g)
2742 hs[static_cast<std::size_t>(g)] = h(g);
2743 return hs;
2744 }
2745 // Canonical owned order after a migration: core keeps this rank's stayers first (in their old
2746 // order) and appends the lastReceived() arrivals message by message, in arrival order. Stably
2747 // re-order the arrivals by their sending rank; within one sender the order is the sender's.
2748 void orderArrivalsBySource(std::vector<peclet::core::Vec<3>>& pos, std::vector<char>& payload,
2749 std::size_t newN) {
2750 const std::size_t nArr = mig_.lastReceived();
2751 if (nArr < 2 || nArr > newN)
2752 return;
2753 const std::size_t first = newN - nArr;
2754 std::vector<int> src(nArr);
2755 for (std::size_t k = 0; k < nArr; ++k)
2756 std::memcpy(&src[k],
2757 &payload[(first + k) * sizeof(MigratePack) + offsetof(MigratePack, srcRank)],
2758 sizeof(int));
2759 if (std::is_sorted(src.begin(), src.end()))
2760 return;
2761 std::vector<std::size_t> perm(nArr);
2762 for (std::size_t k = 0; k < nArr; ++k)
2763 perm[k] = k;
2764 std::stable_sort(perm.begin(), perm.end(),
2765 [&](std::size_t a, std::size_t b) { return src[a] < src[b]; });
2766 std::vector<peclet::core::Vec<3>> p2(nArr);
2767 std::vector<char> b2(nArr * sizeof(MigratePack));
2768 for (std::size_t k = 0; k < nArr; ++k) {
2769 p2[k] = pos[first + perm[k]];
2770 std::memcpy(&b2[k * sizeof(MigratePack)], &payload[(first + perm[k]) * sizeof(MigratePack)],
2771 sizeof(MigratePack));
2772 }
2773 std::copy(p2.begin(), p2.end(), pos.begin() + static_cast<std::ptrdiff_t>(first));
2774 std::memcpy(&payload[first * sizeof(MigratePack)], b2.data(), b2.size());
2775 }
2776
2777 void uploadShift(const peclet::core::halo::ParticleHaloTopology<3>::FlatTopo& t) {
2778 std::vector<F3> hs(t.shift.size());
2779 for (std::size_t i = 0; i < t.shift.size(); ++i)
2780 hs[i] = F3{static_cast<float>(t.shift[i][0]), static_cast<float>(t.shift[i][1]),
2781 static_cast<float>(t.shift[i][2])};
2782 shiftDev_ = peclet::core::toDevice(hs, "peclet::dem::halo::shift");
2783 }
2784
2785 bool inited_ = false;
2786 int rank_ = 0, numReal_ = 0, numGhost_ = 0;
2787 int numSend_ = 0; // owned copies this rank sends per forward (cross-rank; set at each rebuild)
2788 // Verlet-skin reuse state (D2): skin width, the build-time owned positions, and the cache-valid
2789 // flags.
2790 float verletSkin_ = 0.0f;
2791 bool haveTopo_ = false;
2792 int lastNumReal_ = -1;
2793 double lastBand_ = -1.0; // rcut + skin of the cached topology
2794 long nRebuild_ = 0, nGather_ = 0;
2795 V3 refPos_;
2796 MPI_Comm comm_ = MPI_COMM_NULL;
2797 peclet::core::decomp::BlockDecomposer<3> dec_;
2798 peclet::core::halo::DomainMap<3> map_; // physical<->cell mapping (for migrateTo)
2799 peclet::core::halo::ParticleMigrator<3> mig_;
2800 peclet::core::halo::ParticleHaloTopology<3> halo_;
2801 peclet::core::halo::ParticleHalo<3> dev_;
2802 peclet::core::View<F3> ownedF3_, ghostF3_, shiftDev_;
2803 Vi ghostSlot_; // topology ghost index -> canonical ghost slot offset (see uploadGhostSlots)
2804 peclet::core::View<F4> ownedF4_, ghostF4_;
2805 peclet::core::View<MpiGatherPack> ownedPack_, ghostPack_;
2806 // Reconciliation state (§2.3): per-ghost baselines in TOPOLOGY ghost order, the reverse payloads
2807 // and the count-column buffers -- all grow-only.
2808 V3 baseVel_, baseAngVel_, basePos_;
2809 Vf baseOrphan_, baseOrphanPeak_;
2810 peclet::core::View<VelocityIncrement> ghostVelInc_, ownedVelInc_;
2811 peclet::core::View<PositionIncrement> ghostPosInc_, ownedPosInc_;
2812 peclet::core::View<float> ghostVal_, ownedVal_;
2813 peclet::core::View<int> ghostCnt_, ownedCnt_;
2814 peclet::core::View<PositionCountsMask> ghostCM_, ownedCM_;
2815 // Rank-level X (§1.4): this rank's colour and the number of colours, for the band they were
2816 // computed with (-1: stale; reset whenever the decomposition changes).
2817 int rankColor_ = 0, numRankColors_ = 1;
2818 double colorBand_ = -1.0;
2819 unsigned long long colorFingerprint_ = 0ull;
2820 peclet::core::View<VelocityState> ghostVelState_, ownedVelState_; // fused forwards (rotation)
2821 peclet::core::View<PositionState> ghostPosState_, ownedPosState_;
2822 // Ownership maps (§2.1; see buildOwnershipMaps).
2823 Kokkos::View<int*, CpMem> ghostSource_, copyOffsets_, copyRanks_, ghostImage_, copyImage_,
2824 selfOffsets_, selfImage_;
2825 // Rank-level M (docs/contact_solve_framework.md §13.3): the opening / Poisson forward payloads,
2826 // the owner seeds [0, numReal) (grow-only), this substep's mode flags (reset by gather), and
2827 // the velocity slot map (§6.2).
2828 peclet::core::View<OpeningIncrement> ghostOpenInc_, ownedOpenInc_;
2829 peclet::core::View<OpeningState> ghostOpenState_, ownedOpenState_;
2830 peclet::core::View<OpeningStateNoRot> ghostOpenStateNR_, ownedOpenStateNR_;
2831 peclet::core::View<VelocityStateB> ghostVelStateB_, ownedVelStateB_;
2832 peclet::core::View<VelocityStateBNoRot> ghostVelStateBNR_, ownedVelStateBNR_;
2833 V3 ownerSeedVel_, ownerSeedAngVel_, ownerSeedPos_;
2834 Vf ownerSeedOrphan_;
2835 bool velM_ = false, posM_ = false, orphanShares_ = false;
2836 bool canonStale_ = true;
2837 int numReceived_ = 0; // cross-rank ghosts of the current topology (FlatTopo::numReceived)
2838 Vi iface_; // interface rows (buildInterfaceRows); nIface_ of them
2839 Kokkos::View<unsigned char*, CpMem> ifaceMark_;
2840 int nIface_ = 0;
2841 Vi velRows_, posRows_; // the phases' M rows (buildMRows)
2842 int nVelRows_ = 0, nPosRows_ = 0;
2843 std::vector<int> selfIdx_; // owned row of each local self ghost (FlatTopo::selfIdx)
2844 Kokkos::View<int*, CpMem> ghostCanon_;
2845};
2846
2847} // namespace peclet::dem
2848
2849#endif // PECLET_DEM_MPI
2850#endif // PECLET_DEM_MPI_HALO_HPP
dem — portable POD types + math + analytic SDFs shared by the Kokkos kernel ports.
Kokkos::View< float *, CpMem > Vf
Kokkos::View< int *, CpMem > Vi
CpExec::memory_space CpMem
Kokkos::View< float *[3], CpMem > V3
Kokkos::View< float *[4], CpMem > V4
dem — portable (Kokkos) particle SoA container: the storage the dem flip pivots on.
int MPI_Allreduce(const void *a, void *b, int c, MPI_Datatype d, MPI_Op e, MPI_Comm f)
Definition pmpi.cpp:6
The substep's predicted body state (Particles::bodyPred()).
A body's state, one row per particle slot (Particles::bodyState()).