chombo-discharge
Loading...
Searching...
No Matches
ParticleManagement::detail Namespace Reference

Internal-only implementation details of the ParticleManagement API. More...

Classes

struct  KDLeaf
 One leaf of a kd tree: a contiguous index range into the (in-place reordered) particle buffer, plus its axis-aligned bounding box. More...
struct  NNPooledParticle
 Pooled per-round record for one particle: the particle plus its cached boundary-exposure flag. More...
struct  NNFallbackCandidate
 One additional ranked candidate beyond a query's primary nearest neighbor. More...
struct  NNMergeEdge
 One candidate merge edge: a single particle's own nearest-neighbor query result. More...
struct  NNMergeProposal
 A cross-patch merge proposal: one particle's own nearest-neighbor query result, bundled as a self-contained, atomic pair for shipment to whichever rank owns the candidate. More...
struct  NNMergeVerdict
 The judge's reply to one proposal. More...
struct  NNMergeResult
 One resolved merge: the two consumed particles' ids and the newly created merged particle (not yet placed into any patch – see placeMergedParticles()). More...
struct  NNCellKeyHasher
 Hash functor for NNCellKey – REQUIRED whenever NNCellKey is used as a hash-map key; NNCellKey must never be used as an ordered (std::map or std::set) key. More...
struct  NNSpatialIndex
 A patch's spatial index for one round: an EBGeometry point-cloud index (PointCloudBVH or PointCloudHashGrid, selected via Cloud) over the whole patch (every local valid particle followed by every ghost) plus its precomputed k-nearest-neighbor graph. More...
struct  NNCellMeta
 Per-point metadata carried by a one-cell spatial index's PointCloudBVH: a particle's global id and whether it is a local-valid particle of the patch the index was built for. More...
struct  NNPatchWork
 One patch's identity for the duration of a merge round: its AMR level, local DataIndex, and its own level's cell spacing. More...

Typedefs

using NNCellKey = std::pair<int, IntVect>
 A cell key together with the AMR level it was computed on – see cellKeyOf()'s warning.
using NNWalkCell = IntVect
 A non-level-qualified cell index, distinct from NNCellKey, used where a cell is expressed in a single consistent frame (the query patch's own level).
using NNCellCloud = EBGeometry::PointCloudBVH<Real, NNCellMeta>
 One cell's PointCloudBVH for the one-cell nearest-neighbor merge, over every local valid and ghost particle whose cellKeyOf() falls in that cell.
using NNCellSpatialIndex = std::unordered_map<NNWalkCell, std::shared_ptr<NNCellCloud>, LevelTiles::TileHasher>
 A patch's one-cell spatial index: one NNCellCloud per occupied cell, keyed by NNWalkCell (see its docs for the single-frame convention this uses).
using PositionLocator = std::function<LevelTiles::LevelAndBox(const RealVect& a_position)>
 Locate-by-position callback – see placeMergedParticles().

Functions

template<typename Packed>
void buildKDQuotaLeaves (std::vector< MergeParticle< Packed > > &a_particles, FArrayBox &a_used, std::vector< KDLeaf > &a_leaves, const int a_ppc, const Real a_weightMedianCellWidths, const RealVect &a_dx, const RealVect &a_probLo, const FArrayBox &a_cellCounts) noexcept
 Build one whole-patch kd tree: partition a_particles by position into leaves, each of which becomes exactly one super-particle, subject to a live per-cell leaf quota of a_ppc.
template<typename T>
std::vector< T > kdExchangeByRank (const std::vector< std::vector< T > > &a_sendByRank)
 Generic Alltoallv-style exchange for a trivially-copyable record type: send a per-destination-rank bucket, return the flat concatenation of everything received.
template<typename Packed>
void kdBBox (RealVect &a_boxLo, RealVect &a_boxHi, const std::vector< MergeParticle< Packed > > &a_particles, const std::size_t a_lo, const std::size_t a_hi) noexcept
 Axis-aligned bounding box of particles[a_lo, a_hi).
Real kdMaxAxisSpan (const RealVect &a_boxLo, const RealVect &a_boxHi, const RealVect &a_dx) noexcept
 Largest per-axis extent of [a_boxLo,a_boxHi], expressed as a fraction of that axis's own cell width.
IntVect kdCellKeyOf (const RealVect &a_position, const RealVect &a_probLo, const RealVect &a_dx) noexcept
 The unclamped, position-derived cell index a physical position falls in.
bool kdIntVectLess (const IntVect &a_lhs, const IntVect &a_rhs) noexcept
 Strict weak ordering over IntVect, lexicographic component-wise.
template<typename Packed>
void kdFillCellHistogram (FArrayBox &a_counts, const std::vector< MergeParticle< Packed > > &a_particles, const RealVect &a_probLo, const RealVect &a_dx) noexcept
 Tally a per-cell particle-count histogram over one patch's gathered particles.
template<typename Packed, typename PosValid>
void kdCapCellWeights (std::vector< MergeParticle< Packed > > &a_particles, const FArrayBox &a_cellCounts, const FArrayBox &a_cellWeights, const int a_ppc, const KDSplitPlacement a_splitPlacement, const RealVect &a_probLo, const RealVect &a_dx, const PosValid &a_isPositionValid) noexcept
 Cap every resident particle in a crowded cell at that cell's target leaf weight, splitting the ones above it into pieces.
template<typename Packed>
std::size_t kdSplitCountMedian (std::vector< MergeParticle< Packed > > &a_particles, const std::size_t a_lo, const std::size_t a_hi, const int a_axis) noexcept
 Split particles[a_lo,a_hi) in place by the longest axis at the count-median – the sole split rule used by buildKDQuotaLeaves().
template<typename Packed>
std::size_t kdSplitWeightMedian (std::vector< MergeParticle< Packed > > &a_particles, const std::size_t a_lo, const std::size_t a_hi, const int a_axis) noexcept
 Split particles[a_lo,a_hi) in place by the longest axis at the WEIGHT median – the plane with half this node's total particle weight on either side.
void kdBoxRealBounds (RealVect &a_boxLo, RealVect &a_boxHi, const Box &a_box, const RealVect &a_dx, const RealVect &a_probLo) noexcept
 Real-space bounds of a box: the half-open region [lo, hi) that its cells cover.
void kdCheckCentroid (const RealVect &a_centroid, const Real a_totalWeight, const RealVect &a_boxLo, const RealVect &a_boxHi) noexcept
 Debug-only sanity check on a merged particle's position: a weighted centroid of positions that all lie within [a_boxLo,a_boxHi], using strictly positive weights, is mathematically guaranteed to itself lie within that same box.
template<typename Packed>
RealVect kdPlaceMerged (const KDPlacement a_placement, const RealVect &a_centroid, const Real a_totalWeight, const RealVect &a_boxLo, const RealVect &a_boxHi, const std::vector< Real > &a_weights, const std::vector< RealVect > &a_positions) noexcept
 Place the super-particle a leaf reduces to, given the leaf's members and their weighted centroid.
IntVect cellKeyOf (const RealVect &a_position, const RealVect &a_probLo, const RealVect &a_dx) noexcept
 The unclamped, position-derived cell index a given physical position falls in.
template<typename Packed, typename Cloud = EBGeometry::PointCloudBVH<Real, ParticleID>>
void buildNNSpatialIndex (NNSpatialIndex< Packed, Cloud > &a_index, const std::vector< MergeParticle< Packed > > &a_localValid, const std::vector< MergeParticle< Packed > > &a_ghosts, const RealVect &a_probLo, const RealVect &a_dx, const NNCellBudget &a_cellBudget, const int a_kNearest) noexcept
 Build a patch's spatial index for one round: an EBGeometry point-cloud index (see Cloud) over the whole patch (every local valid particle then every ghost) plus its precomputed k-nearest-neighbor graph – UNLESS no cell in this patch could possibly be crowded, in which case nothing is built.
template<typename Packed, typename Cloud = EBGeometry::PointCloudBVH<Real, ParticleID>>
void findNearestNeighborCandidates (std::vector< NNMergeEdge< Packed > > &a_edges, const std::vector< MergeParticle< Packed > > &a_localValid, const std::vector< MergeParticle< Packed > > &a_ghosts, const std::unordered_set< ParticleID > &a_consumedIDs, const NNSpatialIndex< Packed, Cloud > &a_spatialIndex, const std::unordered_map< NNCellKey, int, NNCellKeyHasher > &a_liveCellCount, const RealVect &a_probLo, const RealVect &a_dx, const NNCellBudget &a_cellBudget, const int a_maxFallbackCandidates=0, const std::optional< int > a_maxCellDistance=std::nullopt) noexcept
 For every over-threshold, currently-alive valid particle in a patch, find its single TRUE nearest neighbor among {this patch's own other valid particles} union {every ghost shipped to this patch}.
template<typename Packed>
void buildNNCellSpatialIndex (NNCellSpatialIndex &a_index, const std::vector< MergeParticle< Packed > > &a_localValid, const std::vector< MergeParticle< Packed > > &a_ghosts, const RealVect &a_probLo, const RealVect &a_dx, const NNCellBudget &a_cellBudget) noexcept
 Build a patch's one-cell spatial index for the one-cell nearest-neighbor merge: one PointCloudBVH per occupied cell – UNLESS no cell in this patch could possibly be crowded, in which case nothing is built.
template<typename Packed>
void findNearestNeighborCandidatesOneCell (std::vector< NNMergeEdge< Packed > > &a_edges, const std::vector< MergeParticle< Packed > > &a_localValid, const std::unordered_set< ParticleID > &a_consumedIDs, const NNCellSpatialIndex &a_cellIndex, const std::unordered_map< NNCellKey, int, NNCellKeyHasher > &a_liveCellCount, const RealVect &a_probLo, const RealVect &a_dx, const std::vector< RealVect > &a_dxByLevel, const NNCellBudget &a_cellBudget, const int a_maxFallbackCandidates=0) noexcept
 For every over-threshold, currently-alive valid particle in a patch, find its single TRUE nearest neighbor restricted to its own cell and its Moore-adjacent neighbor cells (Chebyshev cell distance <= 1) – the one-cell counterpart of findNearestNeighborCandidates().
template<typename Packed, typename Combine, typename PosValid, typename Allocator, typename OnMerge>
void resolveTrivialTier (std::unordered_map< NNCellKey, int, NNCellKeyHasher > &a_liveCellCount, std::unordered_set< ParticleID > &a_consumedIDs, std::unordered_set< ParticleID > &a_hasOutgoingCommitment, std::vector< NNMergeResult< Packed > > &a_results, const std::vector< NNMergeEdge< Packed > > &a_edges, const std::unordered_map< ParticleID, NNPooledParticle< Packed > > &a_particlesByID, const Combine &a_combine, const NNCellBudget &a_cellBudget, const RealVect &a_probLo, const std::vector< RealVect > &a_dxByLevel, const PosValid &a_isPositionValid, const Allocator &a_allocateID, const int a_maxFallbackCandidates=0, const std::optional< int > a_maxCellDistance=std::nullopt, unsigned long long *a_crossLevelMergeCount=nullptr, const OnMerge &a_onMergeCommitted=[](const MergeParticle< Packed > &, const MergeParticle< Packed > &, const MergeParticle< Packed > &) { }) noexcept
 Resolve every candidate edge that is safely mergeable with zero cross-rank coordination, and mark which remaining particles have committed to a non-trivial outgoing proposal.
template<typename Packed>
void generateProposals (std::vector< std::vector< NNMergeProposal< Packed > > > &a_proposalsByDestRank, const std::vector< NNMergeEdge< Packed > > &a_edges, const std::unordered_set< ParticleID > &a_hasOutgoingCommitment, const std::unordered_map< ParticleID, NNPooledParticle< Packed > > &a_particlesByID, const int a_numRanks) noexcept
 Package one outgoing proposal for every edge that resolveTrivialTier() could not resolve locally, bucketed by destination rank.
template<typename Packed, typename Combine, typename PosValid, typename Allocator, typename OnMerge>
void judgeProposals (std::unordered_map< NNCellKey, int, NNCellKeyHasher > &a_liveCellCount, std::vector< NNMergeResult< Packed > > &a_results, std::vector< std::vector< NNMergeVerdict > > &a_verdictsByDestRank, const std::vector< NNMergeProposal< Packed > > &a_incomingProposals, const std::unordered_map< ParticleID, NNPooledParticle< Packed > > &a_particlesByID, const std::unordered_set< ParticleID > &a_consumedIDs, const std::unordered_set< ParticleID > &a_hasOutgoingCommitment, const std::map< ParticleID, ParticleID > &a_outgoingTargetOf, const Combine &a_combine, const NNCellBudget &a_cellBudget, const RealVect &a_probLo, const std::vector< RealVect > &a_dxByLevel, const PosValid &a_isPositionValid, const Allocator &a_allocateID, const std::optional< int > a_maxCellDistance=std::nullopt, unsigned long long *a_crossLevelMergeCount=nullptr, const OnMerge &a_onMergeCommitted=[](const MergeParticle< Packed > &, const MergeParticle< Packed > &, const MergeParticle< Packed > &) { }) noexcept
 Judge every incoming proposal that targets a particle this rank owns, and produce the verdicts to send back.
void applyVerdicts (std::unordered_set< ParticleID > &a_consumedIDs, const std::vector< NNMergeVerdict > &a_incomingVerdicts) noexcept
 Apply every verdict addressed to one of this rank's own outgoing proposals: remove the source particle for every accepted proposal, do nothing for rejected ones.
template<typename Packed>
void placeMergedParticles (std::map< std::pair< int, unsigned int >, std::vector< MergeParticle< Packed > > > &a_localByPatch, std::vector< std::vector< MergeParticle< Packed > > > &a_scatterByDestRank, const std::vector< NNMergeResult< Packed > > &a_results, const PositionLocator &a_locate, const int a_thisRank) noexcept
 Point-locate a newly created merged particle against the AMR grid, and bucket it for a scatter exchange if it belongs to someone else.
template<typename P, typename Packed, typename Traits, typename Gather>
void gatherMergeParticles (ParticleContainer< P, Traits > &a_particles, std::vector< NNPatchWork > &a_patchWork, std::vector< std::vector< MergeParticle< Packed > > > &a_patchLocalValid, std::vector< std::vector< MergeParticle< Packed > > > &a_patchGhosts, std::unordered_map< ParticleID, NNPooledParticle< Packed > > &a_particlesByID, std::unordered_map< NNCellKey, int, NNCellKeyHasher > &a_liveCellCount, const AmrMesh &a_amr, const std::string &a_realm, const int a_finestLevel, const RealVect &a_probLo, const std::vector< RealVect > &a_dxByLevel, const int a_ghostWidth, const Gather &a_gather) noexcept
 Gather every patch this rank owns into the backend-agnostic per-patch particle sets and pooled bookkeeping a merge round needs, shared by every search backend.
template<typename P, typename Packed, typename Traits, typename Combine, typename Scatter, typename PosValid, typename Allocator, typename OnMerge>
void finishMergeRound (ParticleContainer< P, Traits > &a_particles, std::unordered_map< ParticleID, NNPooledParticle< Packed > > &a_particlesByID, std::unordered_set< ParticleID > &a_consumedIDs, std::unordered_map< NNCellKey, int, NNCellKeyHasher > &a_liveCellCount, std::vector< NNMergeResult< Packed > > &a_allResults, unsigned long long *a_crossLevelMergeCount, const AmrMesh &a_amr, const std::string &a_realm, const NNCellBudget &a_cellBudget, const Combine &a_combine, const Scatter &a_scatter, const Allocator &a_allocateID, const std::optional< int > a_maxCellDistance, const PosValid &a_isPositionValid, const RealVect &a_probLo, const std::vector< RealVect > &a_dxByLevel, const std::vector< NNPatchWork > &a_patchWork, const std::vector< NNMergeEdge< Packed > > &a_pooledEdges, const std::unordered_set< ParticleID > &a_hasOutgoingCommitment, const OnMerge &a_onMergeCommitted) noexcept
 Finish a merge round: propose/judge/verdict the edges the local tier could not resolve, place every merge result, and apply everything to the real particle containers – the backend-agnostic tail shared by mergeNearestNeighborsTree() and mergeNearestNeighborsOneCell().
template<typename P, typename Packed, typename Traits, typename Cloud, typename Gather, typename Combine, typename Scatter, typename Allocator, typename PosValid, typename OnMerge>
void mergeNearestNeighborsRoundImpl (ParticleContainer< P, Traits > &a_particles, unsigned long long *a_crossLevelMergeCount, const AmrMesh &a_amr, const NNCellBudget &a_cellBudget, const Gather &a_gather, const Combine &a_combine, const Scatter &a_scatter, const Allocator &a_allocateID, const bool a_iterateLocalTierToConvergence, const int a_maxFallbackCandidates, const std::optional< int > a_maxCellDistance, const int a_ghostWidth, const PosValid &a_isPositionValid, const OnMerge &a_onMergeCommitted)
 Shared implementation behind mergeNearestNeighborsTree() and mergeNearestNeighborsHash(): one full round of the whole-patch-tree nearest-neighbor merge, generic over which EBGeometry point-cloud index backs the per-patch spatial search.
Real nnMergeDistSquared (const RealVect &a_a, const RealVect &a_b) noexcept
 Squared Euclidean distance between two physical positions.
int nnMergeChebyshevCellDistance (const IntVect &a_a, const IntVect &a_b) noexcept
 Chebyshev (max-per-axis) distance between two cell-index vectors – see CD_NearestNeighborParticleMerge.H's a_maxCellDistance docs.
bool nnMergeCrossLevelTooFar (const RealVect &a_posA, const int a_levelA, const RealVect &a_posB, const int a_levelB, const RealVect &a_probLo, const std::vector< RealVect > &a_dxByLevel, const int a_maxCellDistance) noexcept
 a_maxCellDistance check for two positions that may be on DIFFERENT AMR levels.
void nnMergeWeightedCentroid (RealVect &a_mergedPos, Real &a_mergedWeight, const RealVect &a_posA, const Real a_weightA, const RealVect &a_posB, const Real a_weightB) noexcept
 Weighted-centroid merge of two positions/weights – shared by resolveTrivialTier() and judgeProposals() so the formula is written exactly once.
Real nnMergePointToCellDistSquared (const RealVect &a_point, const IntVect &a_cell, const RealVect &a_probLo, const RealVect &a_dx) noexcept
 Squared distance from a physical point to a cell's axis-aligned bounding box (0 if the point is inside).
template<typename T>
std::vector< T > nnMergeExchangeByRank (const std::vector< std::vector< T > > &a_sendByRank)
 Generic alltoallv-style exchange: send a per-destination-rank bucket of trivially- copyable records, return the flat concatenation of everything received.
template<typename Packed>
bool nnMergeAnyCellCrowded (const std::vector< MergeParticle< Packed > > &a_localValid, const std::vector< MergeParticle< Packed > > &a_ghosts, const RealVect &a_probLo, const RealVect &a_dx, const NNCellBudget &a_cellBudget) noexcept
 Exact per-cell crowding pre-filter shared by buildNNSpatialIndex()/buildNNCellSpatialIndex(): is any cell in this patch's local+ghost particle set over its a_cellBudget?
template<class P, Real P::* weight, RealVect P::* position>
void buildKDCellLeaves (const std::vector< P > &a_particles, const int a_maxLeaves, const Real a_weightMedianLength, const bool a_capWeights, const std::function< RealVect(const RealVect &)> &a_splitPosition, const BinaryParticleReconcile< P > &a_particleReconcile, std::vector< std::pair< const P *, const P * > > &a_leaves) noexcept
 Build a KD partition of a list of particles and return the leaf particle ranges.
RealVect kdSplitDisplace (const KDSplitPlacement a_placement, const RealVect &a_parent, const RealVect &a_cellLo, const RealVect &a_dx, const Real a_spacing) noexcept
 Place one piece of a split particle.
template<typename T, typename>
T partitionParticles (const T a_numParticles)
 Partition particles so that all MPI rank draw a cumulative number of particles equal to a_numParticles.

Detailed Description

Internal-only implementation details of the ParticleManagement API.

Internal-only implementation details of the ParticleManagement API (continued).

These helpers have no external callers; they are the algorithms sitting behind the public factory/wrapper functions (make*Merger, partitionParticleWeights) and are not part of the public interface. Public callers qualify them with detail::.

Reopens the detail namespace introduced above to house partitionParticles alongside the other internal helpers; see the first detail block for the full rationale. Not part of the public interface – public callers qualify with detail::.

Typedef Documentation

◆ NNCellKey

using ParticleManagement::detail::NNCellKey = std::pair<int, IntVect>

A cell key together with the AMR level it was computed on – see cellKeyOf()'s warning.

Two NNCellKeys are equal only if BOTH the level and the cell index match; a coarse- level cell and an unrelated fine-level cell that happen to share the same bare IntVect are correctly kept distinct because their level differs. This is the key type for every live per-cell count pooled across multiple levels (see a_liveCellCount in resolveTrivialTier()/ judgeProposals()/findNearestNeighborCandidates()).

◆ NNCellSpatialIndex

A patch's one-cell spatial index: one NNCellCloud per occupied cell, keyed by NNWalkCell (see its docs for the single-frame convention this uses).

Empty (no entries) iff no cell in the patch could possibly be crowded – the same per-cell pre-filter as buildNNSpatialIndex(); see buildNNCellSpatialIndex().

◆ NNWalkCell

A non-level-qualified cell index, distinct from NNCellKey, used where a cell is expressed in a single consistent frame (the query patch's own level).

A separate alias from NNCellKey (which is level-qualified for the cross-level crowding-count map) so the two cannot be passed interchangeably. NNWalkCell is always computed with the query patch's own level's dx, even for a cross-level ghost, so candidates are geometrically comparable to the query in one frame (see cellKeyOf()'s warning).

◆ PositionLocator

using ParticleManagement::detail::PositionLocator = std::function<LevelTiles::LevelAndBox(const RealVect& a_position)>

Locate-by-position callback – see placeMergedParticles().

Returns LevelTiles::LevelAndBox, which is what ParticleContainer::findDestination() already produces: an O(1) point->block query on the realm's LevelTiles tile->box hash, the SAME lookup a ParticleContainer uses internally to route its own particles during remap(), never a linear scan over patches. Going through that one mapping keeps it the single source of truth for "which box owns this position".

The callback itself remains, so this header does not depend on ParticleContainer; only the result type is shared. Call frequency is bounded by the number of MERGE RESULTS this round (not by the number of candidate pairs), so a non-inlined indirect call is an acceptable cost – this is not a hot inner-loop path.

Parameters
[in]a_positionPhysical position to locate.
Returns
Which box (level, global grid index) and rank covers it; valid is false off-domain.

Function Documentation

◆ applyVerdicts()

void ParticleManagement::detail::applyVerdicts ( std::unordered_set< ParticleID > & a_consumedIDs,
const std::vector< NNMergeVerdict > & a_incomingVerdicts )
inlinenoexcept

Apply every verdict addressed to one of this rank's own outgoing proposals: remove the source particle for every accepted proposal, do nothing for rejected ones.

Rejected proposals are deliberately a no-op – the source particle is simply left alone and reconsidered in next round's fresh candidate search. This algorithm never internally retries a rejected proposal against a second-best candidate within the same round.

Parameters
[out]a_consumedIDsIds of every source particle whose proposal was accepted – the caller removes these from its own valid particle lists.
[in]a_incomingVerdictsAll verdicts addressed to this rank, pooled from every judge rank (including this rank's own in-process verdict for proposals it judged for itself).

◆ buildKDCellLeaves()

template<class P, Real P::* weight, RealVect P::* position>
void ParticleManagement::detail::buildKDCellLeaves ( const std::vector< P > & a_particles,
const int a_maxLeaves,
const Real a_weightMedianLength,
const bool a_capWeights,
const std::function< RealVect(const RealVect &)> & a_splitPosition,
const BinaryParticleReconcile< P > & a_particleReconcile,
std::vector< std::pair< const P *, const P * > > & a_leaves )
inlinenoexcept

Build a KD partition of a list of particles and return the leaf particle ranges.

Partitions the input particles into at most a_maxLeaves spatial groups ("leaves"). Each split divides the node along the longest bounding-box axis, at the weight median while the node is no wider than a_weightMedianLength and at the count median above that – the same size-dependent rule the whole-patch build uses, and the same one a fixed 'weight' or 'count' setting expresses as a crossover above or below every node's size. Under the weight median the halves carry as nearly equal a weight as possible (differing by at most one physical particle), which may require dividing the median particle itself, in which case a_particleReconcile fixes up the daughters' non-weight members; the count median never divides a particle. This is the partitioning primitive behind super-particle merging: the caller reduces each returned leaf range to a single merged particle.

Implementation note: the tree is built in a flat, reusable per-thread scratch arena (two ping-ponged contiguous particle buffers + a flat range list), so there is no per-node heap allocation, no pointer chasing, and the scratch is reused across calls on the same thread.

Template parameters: P -> Particle type exposing the weight/position data members below P::*weight -> Pointer to the Real data member holding the particle weight P::*position -> Pointer to the RealVect data member holding the particle position.

P must be an AoS-style particle type carrying weight and position as data members – MergeParticle is the one this library provides, and the one every in-tree caller uses. ParticleSoA payload types (ItoParticle, ...) store those two in the container rather than the payload, so pack the columns into such an intermediary AoS structure first.

Parameters
[in]a_particlesInput particles (copied into internal scratch; not modified).
[in]a_maxLeavesMaximum number of leaf nodes (the per-cell target particle count).
[in]a_weightMedianLengthNode size, as a length, at or below which the split plane is the weight median rather than the count median. Negative disables the weight median entirely; a huge value selects it everywhere.
[in]a_capWeightsIf true, divide every input particle heavier than the target leaf weight (total weight / a_maxLeaves) into co-located integer pieces before partitioning, so no single particle can dominate a leaf.
[in]a_splitPositionWhere a split particle's pieces go, given the parent's position. The identity reproduces the parent's position exactly; see KDSplitPlacement for why that is not always what you want.
[in]a_particleReconcileReconciliation callback applied to the two daughters when the median is split.
[out]a_leavesFilled with one {begin,end} pointer pair per leaf.
Warning
The returned ranges alias an internal thread-local buffer that is overwritten on the next call to this function on the same thread. Consume them (reduce each leaf) before calling again.

◆ buildKDQuotaLeaves()

template<typename Packed>
void ParticleManagement::detail::buildKDQuotaLeaves ( std::vector< MergeParticle< Packed > > & a_particles,
FArrayBox & a_used,
std::vector< KDLeaf > & a_leaves,
const int a_ppc,
const Real a_weightMedianCellWidths,
const RealVect & a_dx,
const RealVect & a_probLo,
const FArrayBox & a_cellCounts )
inlinenoexcept

Build one whole-patch kd tree: partition a_particles by position into leaves, each of which becomes exactly one super-particle, subject to a live per-cell leaf quota of a_ppc.

a_particles is reordered IN PLACE, so each returned leaf's [lo,hi) range is contiguous in the reordered buffer; no particle is ever copied or split synthetically.

A leaf collapses to exactly ONE super-particle at its own weighted centroid, so the number of leaves whose centroid falls in a cell is that cell's post-merge population. That count is tracked live in a per-cell map while splitting, and a split that would push a cell past a_ppc is refused. Splitting takes the heaviest candidate leaf first and stops when nothing may legally be split.

Splits are along the longest real-space axis and are deliberately UNSNAPPED to the grid, so a leaf may straddle a cell face and draw members from either side. The split plane is the count median while the node is wider than a_weightMedianCellWidths cell widths, and the weight median once it is narrower: above that scale a split apportions leaves between cells, which is a question of counts; below it the weight median drives the resulting super-particles toward equal weight.

The quota constrains only leaves that can actually merge. mergeKDCarve() and mergeKDPatch() veto any leaf wider than s_kdMaxLeafExtent and leaves its members behind individually, so such a leaf costs its cell its full member count rather than one particle; the quota therefore does not block splitting it further. As a result a cell can finish slightly above a_ppc when a leaf is both too wide to merge and in a cell already at quota, since both available choices overshoot.

Particles in cells at or below a_ppc are excluded from the partition and emitted as singleton leaves. A singleton never merges (the merge threshold is two members), so an uncrowded cell cannot be drained by a neighbour's merge.

Template Parameters
PackedSee MergeParticle.
Parameters
[in,out]a_particlesParticles to partition; reordered in place.
[in,out]a_usedLive per-cell leaf quota for this patch, zeroed on entry. Its box must cover every cell a leaf centroid can fall in, i.e. it needs at least one ghost cell.
[out]a_leavesEvery resulting leaf, in no particular order.
[in]a_ppcTarget particles per cell, enforced here as a per-cell ceiling on leaf count.
[in]a_weightMedianCellWidthsLeaf size, in cell widths, at or below which the split plane switches from the count median to the weight median. 0 disables the weight median.
[in]a_dxThis patch's own cell spacing.
[in]a_probLoPhysical position of the domain's low corner, for computing cell indices.
[in]a_cellCountsPer-cell TRUE particle-count histogram (see kdFillCellHistogram()). A cell is crowded, and its particles eligible to merge, iff its count exceeds a_ppc. A cell outside this box reads as 0 (empty): unlike a_used, whose box coverage is a hard precondition, this lookup guards rather than asserts, since a particle's own cell is always in-box but the guard costs nothing and documents the intent.

◆ buildNNCellSpatialIndex()

template<typename Packed>
void ParticleManagement::detail::buildNNCellSpatialIndex ( NNCellSpatialIndex & a_index,
const std::vector< MergeParticle< Packed > > & a_localValid,
const std::vector< MergeParticle< Packed > > & a_ghosts,
const RealVect & a_probLo,
const RealVect & a_dx,
const NNCellBudget & a_cellBudget )
inlinenoexcept

Build a patch's one-cell spatial index for the one-cell nearest-neighbor merge: one PointCloudBVH per occupied cell – UNLESS no cell in this patch could possibly be crowded, in which case nothing is built.

Every OCCUPIED cell gets a cloud, not just crowded ones – an under-threshold cell can still hold a valid Moore-neighbor candidate for a query in an adjacent crowded cell (see findNearestNeighborCandidatesOneCell()). Uses the same exact per-cell tally as buildNNSpatialIndex() to decide whether to build anything at all for this patch.

Template Parameters
PackedSee MergeParticle.
Parameters
[out]a_indexThe resulting one-cell spatial index.
[in]a_localValidThis patch's own full valid-particle set.
[in]a_ghostsEvery ghost shipped to this patch this round.
[in]a_probLoPhysical position of the domain's low corner.
[in]a_dxCell spacing of THIS PATCH's own level.
[in]a_cellBudgetThe physics-facing per-cell budget used elsewhere this round; used ONLY for the per-cell pre-filter above.

◆ buildNNSpatialIndex()

template<typename Packed, typename Cloud = EBGeometry::PointCloudBVH<Real, ParticleID>>
void ParticleManagement::detail::buildNNSpatialIndex ( NNSpatialIndex< Packed, Cloud > & a_index,
const std::vector< MergeParticle< Packed > > & a_localValid,
const std::vector< MergeParticle< Packed > > & a_ghosts,
const RealVect & a_probLo,
const RealVect & a_dx,
const NNCellBudget & a_cellBudget,
const int a_kNearest )
inlinenoexcept

Build a patch's spatial index for one round: an EBGeometry point-cloud index (see Cloud) over the whole patch (every local valid particle then every ghost) plus its precomputed k-nearest-neighbor graph – UNLESS no cell in this patch could possibly be crowded, in which case nothing is built.

The point cloud carries each point's globalID as metadata; a hit's cloud index decodes ownership (c < nLocal => local valid, else ghost). After the cloud is built, its whole a_kNearest-nearest-neighbor graph is precomputed once via Cloud::allNearestNeighbors() (batched, own-locality-seeded) into a_index.pointCloudGraph and reused across every internal a_iterateLocalTierToConvergence pass (positions never change within a round; only consumed status does, and that is filtered at lookup time – see findNearestNeighborCandidates()).

Per-cell pre-filter: if NO cell in this patch is over its a_cellBudget particles, nothing is built (a_index.pointCloud stays null, exactly as if the patch had zero particles) – the SAME cheap "is this even worth it" check the kd merges effectively get for free by dispatching per cell. This is an EXACT check (not an average-density heuristic, which would be a real bug: a low-average patch can still hold one badly-clustered over-threshold cell): a lightweight per-cell tally of the patch's own particles, keyed exactly as the crowding trigger (cellKeyOf(pos, probLo, dx), local and ghost alike), decides it directly.

Template Parameters
PackedSee MergeParticle.
CloudSee NNSpatialIndex. Constructed with its two-argument constructor (positions, metadata), so this function relies on each Cloud's own default for whatever third construction parameter it takes (target leaf size for PointCloudBVH, target points per cell for PointCloudHashGrid) – both defaults are reasonable, general choices, so neither backend needs bespoke construction logic here.
Parameters
[out]a_indexThe resulting spatial index.
[in]a_localValidThis patch's own full valid-particle set.
[in]a_ghostsEvery ghost shipped to this patch this round.
[in]a_probLoPhysical position of the domain's low corner.
[in]a_dxCell spacing of THIS PATCH's own level.
[in]a_cellBudgetThe physics-facing per-cell budget used elsewhere this round (see mergeNearestNeighborsTree()'s own a_cellBudget) – used ONLY for the per-cell pre-filter above.
[in]a_kNearestk = 1 + a_maxFallbackCandidates – the neighbor count to precompute per point into NNSpatialIndex::pointCloudGraph.

◆ cellKeyOf()

IntVect ParticleManagement::detail::cellKeyOf ( const RealVect & a_position,
const RealVect & a_probLo,
const RealVect & a_dx )
inlinenoexcept

The unclamped, position-derived cell index a given physical position falls in.

The cell-key convention used throughout for the crowding trigger and a_maxCellDistance. Not clamped to any patch's box, so a ghost buckets into its true origin cell and particles in different patches' local frames stay directly comparable.

Warning
a_dx MUST be the cell spacing of the AMR level the position's particle lives on (see MergeParticle::level), never a single fixed dx shared across levels. The returned IntVect is only meaningful together with that level; NNCellKey pairs the two so they cannot be conflated (pooling bare cell keys from different levels aliases coarse- and fine-level cell counts).
Parameters
[in]a_positionPhysical position.
[in]a_probLoPhysical position of the domain's low corner.
[in]a_dxCell spacing (per direction) of the position's OWN level.
Returns
floor((a_position - a_probLo) / a_dx), component-wise.

◆ findNearestNeighborCandidates()

template<typename Packed, typename Cloud = EBGeometry::PointCloudBVH<Real, ParticleID>>
void ParticleManagement::detail::findNearestNeighborCandidates ( std::vector< NNMergeEdge< Packed > > & a_edges,
const std::vector< MergeParticle< Packed > > & a_localValid,
const std::vector< MergeParticle< Packed > > & a_ghosts,
const std::unordered_set< ParticleID > & a_consumedIDs,
const NNSpatialIndex< Packed, Cloud > & a_spatialIndex,
const std::unordered_map< NNCellKey, int, NNCellKeyHasher > & a_liveCellCount,
const RealVect & a_probLo,
const RealVect & a_dx,
const NNCellBudget & a_cellBudget,
const int a_maxFallbackCandidates = 0,
const std::optional< int > a_maxCellDistance = std::nullopt )
inlinenoexcept

For every over-threshold, currently-alive valid particle in a patch, find its single TRUE nearest neighbor among {this patch's own other valid particles} union {every ghost shipped to this patch}.

This is the only place a nearest-neighbor search happens, and it always runs against the full (local + ghost) view, never a local-only view: restricting it biases boundary-adjacent particles toward worse matches than interior ones. Crowding eligibility (is the query's own cell over threshold) is checked here at generation time from the live per-cell counts over valid + ghost occupancy; the symmetric check on the candidate's cell is done later, dynamically, by resolveTrivialTier()/judgeProposals(), since earlier merges this round can change it.

a_localValid/a_ghosts are this patch's full, unfiltered sets for the round; this function does the alive-filtering itself via a_consumedIDs (checked against both the query and every candidate). a_spatialIndex is built once per patch per mergeNearestNeighborsTree() call over the full set and reused across every a_iterateLocalTierToConvergence pass via this same lazy-deletion check, so it is never rebuilt per pass.

Each query's precomputed row is read from a_spatialIndex's k-nearest-neighbor graph (see NNSpatialIndex::pointCloudGraph / buildNNSpatialIndex()), computed once for the whole patch via the EBGeometry SIMD PointCloudBVH's batched allNearestNeighbors(). Per-query work is a row lookup plus filtering: a hit is skipped if its id is in a_consumedIDs, or (when a_maxCellDistance is set) if it lies beyond the bound; survivors feed the shared top-K logic that builds the edge. Self is excluded by the graph (each row is the nearest OTHER points).

a_maxCellDistance, when set, filters the graph row: rows are distance-sorted, so an out-of-bound candidate is farther than the bound and can never displace a within-bound one, and filtering yields exactly the within-bound k-nearest (see its param docs for the exact, safe-but-not-tight bound).

When a_maxFallbackCandidates > 0, the graph is built with k = 1 + a_maxFallbackCandidates, so each row holds the K nearest and NNMergeEdge::fallbackCandidates is populated with candidates 2..K (distance-sorted); resolveTrivialTier() walks that pre-fetched list when the primary is blocked, without re-querying the index.

Template Parameters
PackedSee MergeParticle.
CloudSee NNSpatialIndex.
Parameters
[out]a_edgesOne entry per over-threshold, currently-alive query particle that has at least one candidate (empty if none found).
[in]a_localValidThis patch's own FULL valid-particle set for this round (query sources AND candidates) – see the contract-change note above; not pre-filtered by a_consumedIDs.
[in]a_ghostsEvery ghost shipped to this patch this round (candidates only; ghosts never initiate a query) – also not pre-filtered.
[in]a_consumedIDsLazy-deletion skip set: ids already consumed earlier this round (by an earlier a_iterateLocalTierToConvergence pass, or an earlier query within this same pass). Checked against both the query and every candidate encountered during the walk.
[in]a_spatialIndexThis patch's spatial index for this round (see NNSpatialIndex), built once via buildNNSpatialIndex() over the FULL a_localValid/ a_ghosts sets before any consumption happens.
[in]a_liveCellCountLive particle count (valid + ghost) per level-qualified cell key (see NNCellKey), already reflecting this round's frozen ghost-fill snapshot.
[in]a_probLoPhysical position of the domain's low corner (see cellKeyOf()).
[in]a_dxCell spacing of THIS PATCH's own level (see cellKeyOf()'s warning) – valid here because every query in a_localValid is necessarily on this same level; candidates never have their crowding checked by this function, so a cross-level ghost candidate needs no dx here.
[in]a_cellBudgetPer-cell budget – a cell is eligible while it holds strictly more than this many particles.
[in]a_maxFallbackCandidatesForwarded from resolveTrivialTier() (see its docs); 0 (default) means an ordinary single-nearest query and every edge's fallbackCandidates stays empty.
[in]a_maxCellDistanceSame hard cutoff as resolveTrivialTier()'s own a_maxCellDistance (see its docs); std::nullopt (default) disables it. Applied here purely as an additional, always-safe filter on the graph row – resolveTrivialTier()/judgeProposals() still apply the exact, level-aware, per-axis Chebyshev check (nnMergeCrossLevelTooFar()) downstream regardless, unchanged. The bound used here is deliberately looser: a candidate is dropped only once its EUCLIDEAN distance exceeds a_maxCellDistance * min(a_dx) * sqrt(SpaceDim) – the sqrt(SpaceDim) factor is required because a per-axis Chebyshev cell distance of N does not bound Euclidean physical distance by N * dx alone (a diagonal candidate exactly N cells away in both directions is N * dx * sqrt(SpaceDim) away in a straight line), and this bound must never be tighter than the true Chebyshev cutoff or it could wrongly drop a candidate resolveTrivialTier()/judgeProposals() would still have accepted. Safe but not maximally tight.

◆ findNearestNeighborCandidatesOneCell()

template<typename Packed>
void ParticleManagement::detail::findNearestNeighborCandidatesOneCell ( std::vector< NNMergeEdge< Packed > > & a_edges,
const std::vector< MergeParticle< Packed > > & a_localValid,
const std::unordered_set< ParticleID > & a_consumedIDs,
const NNCellSpatialIndex & a_cellIndex,
const std::unordered_map< NNCellKey, int, NNCellKeyHasher > & a_liveCellCount,
const RealVect & a_probLo,
const RealVect & a_dx,
const std::vector< RealVect > & a_dxByLevel,
const NNCellBudget & a_cellBudget,
const int a_maxFallbackCandidates = 0 )
inlinenoexcept

For every over-threshold, currently-alive valid particle in a patch, find its single TRUE nearest neighbor restricted to its own cell and its Moore-adjacent neighbor cells (Chebyshev cell distance <= 1) – the one-cell counterpart of findNearestNeighborCandidates().

Visits the query's own cell plus every occupied Moore-neighbor cell (up to 3^SpaceDim - 1 of them), ordered by ascending squared point-to-cell distance, querying each cell's PointCloudBVH (the own cell via an external query that also matches the query particle itself, filtered out by id; neighbor cells via an ordinary external query, no self match possible). Stops visiting further cells once a full top-K candidate set has been found and the next cell's minimum possible distance cannot beat or tie the current worst of K – an exact, not approximate, prune, since point-to-cell-AABB distance is a true lower bound on any point inside that cell.

The cell buckets themselves are all keyed in the query patch's OWN level's frame (see buildNNCellSpatialIndex()), so Moore-adjacency in that frame does not, by itself, bound the Chebyshev distance between the query and a candidate on a DIFFERENT AMR level in the finer-of-the-two-levels frame that nnMergeCrossLevelTooFar() (and so resolveTrivialTier()/ judgeProposals()) actually enforce. A same-level candidate is unaffected (query and candidate already share one frame). For a cross-level candidate, this function re-checks it exactly, in that same finer-of-the-two-levels frame, before it is ever considered – so every candidate this function returns is guaranteed at Chebyshev distance <= 1 in the frame the downstream exact check uses, not merely in the query patch's own frame. Callers MUST still forward that same cap (not std::nullopt) as a_maxCellDistance to resolveTrivialTier()/judgeProposals().

Template Parameters
PackedSee MergeParticle.
Parameters
[out]a_edgesOne entry per over-threshold, currently-alive query particle that has at least one candidate.
[in]a_localValidThis patch's own FULL valid-particle set for this round (query sources).
[in]a_consumedIDsLazy-deletion skip set: ids already consumed earlier this round.
[in]a_cellIndexThis patch's one-cell spatial index (see NNCellSpatialIndex), built once via buildNNCellSpatialIndex() over the FULL a_localValid/a_ghosts sets before any consumption happens.
[in]a_liveCellCountLive particle count (valid + ghost) per level-qualified cell key (see NNCellKey).
[in]a_probLoPhysical position of the domain's low corner (see cellKeyOf()).
[in]a_dxCell spacing of THIS PATCH's own level (see cellKeyOf()'s warning).
[in]a_dxByLevelCell spacing per AMR level (see resolveTrivialTier()'s own docs) – needed for the exact cross-level re-check described above.
[in]a_cellBudgetPer-cell budget – a cell is eligible while it holds strictly more than this many particles.
[in]a_maxFallbackCandidatesSame meaning as findNearestNeighborCandidates()'s own parameter; 0 (default) means an ordinary single-nearest query and every edge's fallbackCandidates stays empty.

◆ finishMergeRound()

template<typename P, typename Packed, typename Traits, typename Combine, typename Scatter, typename PosValid, typename Allocator, typename OnMerge>
void ParticleManagement::detail::finishMergeRound ( ParticleContainer< P, Traits > & a_particles,
std::unordered_map< ParticleID, NNPooledParticle< Packed > > & a_particlesByID,
std::unordered_set< ParticleID > & a_consumedIDs,
std::unordered_map< NNCellKey, int, NNCellKeyHasher > & a_liveCellCount,
std::vector< NNMergeResult< Packed > > & a_allResults,
unsigned long long * a_crossLevelMergeCount,
const AmrMesh & a_amr,
const std::string & a_realm,
const NNCellBudget & a_cellBudget,
const Combine & a_combine,
const Scatter & a_scatter,
const Allocator & a_allocateID,
const std::optional< int > a_maxCellDistance,
const PosValid & a_isPositionValid,
const RealVect & a_probLo,
const std::vector< RealVect > & a_dxByLevel,
const std::vector< NNPatchWork > & a_patchWork,
const std::vector< NNMergeEdge< Packed > > & a_pooledEdges,
const std::unordered_set< ParticleID > & a_hasOutgoingCommitment,
const OnMerge & a_onMergeCommitted )
inlinenoexcept

Finish a merge round: propose/judge/verdict the edges the local tier could not resolve, place every merge result, and apply everything to the real particle containers – the backend-agnostic tail shared by mergeNearestNeighborsTree() and mergeNearestNeighborsOneCell().

Runs, in order: derive outgoingTargetOf from a_pooledEdges/a_hasOutgoingCommitment; generateProposals(); exchange proposals; judgeProposals(); exchange verdicts; applyVerdicts(); placeMergedParticles(); exchange the scatter bucket; remove every consumed local-valid particle from the real containers; scatter in every locally-placed and every incoming-scattered merged particle. Identical to steps 3-7 of mergeNearestNeighborsTree()'s own docs.

Template Parameters
PSoA payload type.
PackedOpaque reconciliation payload type.
TraitsColumn descriptor for P.
CombineSee PayloadCombine.
ScatterCallable (ParticleSoA<P,Traits>&, const MergeParticle<Packed>&) -> void.
PosValidSee PositionValid.
AllocatorSee IDAllocator.
OnMergeSee MergeCommittedCallback.
Parameters
[in,out]a_particlesThe real particle container being merged.
[in,out]a_particlesByIDEvery currently-alive local-valid particle and every ghost, pooled rank-wide by id.
[in,out]a_consumedIDsIds already consumed this round; updated in place as judge-side merges commit.
[in,out]a_liveCellCountLive per-cell counts; decremented in place as judge-side merges commit.
[in,out]a_allResultsEvery merge result committed this round (trivial-tier results already inside on entry); judge-side results are appended.
[in,out]a_crossLevelMergeCountOptional diagnostic counter (see MergeCommittedCallback's sibling docs).
[in]a_amrAMR mesh – source of the LevelTiles used to place merged particles.
[in]a_realmRealm name.
[in]a_cellBudgetThe count each cell is drained down to – see NNCellBudget.
[in]a_combineOpaque-payload combine callback.
[in]a_scatterPer-surviving-particle scatter callback.
[in]a_allocateIDFresh-id allocator.
[in]a_maxCellDistancePhysical merge-eligibility cap forwarded to judgeProposals() (see its own docs); the caller's own cap for a tree-backed round, or a hardcoded 1 for a one-cell round (see findNearestNeighborCandidatesOneCell()'s docs on why that value is mandatory there).
[in]a_isPositionValidPosition-validity predicate.
[in]a_probLoPhysical position of the domain's low corner.
[in]a_dxByLevelCell spacing per AMR level.
[in]a_patchWorkOne entry per patch this rank owns (see NNPatchWork), from gatherMergeParticles().
[in]a_pooledEdgesEvery candidate edge produced by the local tier's LAST candidate-search pass, pooled across every patch this rank owns (used to derive outgoingTargetOf; nothing is consumed between the last pass and here, so these are still current).
[in]a_hasOutgoingCommitmentQuery ids the local tier could not resolve trivially.
[in]a_onMergeCommittedOptional per-merge diagnostic callback.

◆ gatherMergeParticles()

template<typename P, typename Packed, typename Traits, typename Gather>
void ParticleManagement::detail::gatherMergeParticles ( ParticleContainer< P, Traits > & a_particles,
std::vector< NNPatchWork > & a_patchWork,
std::vector< std::vector< MergeParticle< Packed > > > & a_patchLocalValid,
std::vector< std::vector< MergeParticle< Packed > > > & a_patchGhosts,
std::unordered_map< ParticleID, NNPooledParticle< Packed > > & a_particlesByID,
std::unordered_map< NNCellKey, int, NNCellKeyHasher > & a_liveCellCount,
const AmrMesh & a_amr,
const std::string & a_realm,
const int a_finestLevel,
const RealVect & a_probLo,
const std::vector< RealVect > & a_dxByLevel,
const int a_ghostWidth,
const Gather & a_gather )
inlinenoexcept

Gather every patch this rank owns into the backend-agnostic per-patch particle sets and pooled bookkeeping a merge round needs, shared by every search backend.

For every patch: splits its leaf into local-valid/ghost MergeParticle vectors (ghosts carrying their TRUE origin AMR level, see MergeParticle::level), computes each local-valid particle's boundary-exposure flag from the realm's same/coarse-to-fine/fine-to-coarse particle ghost masks at the given a_ghostWidth, and pools everything rank-wide into a_particlesByID. a_liveCellCount is derived from the pooled a_particlesByID afterward (once per particle, not once per occurrence, since a ghost can appear in several of this rank's own patches at once). Builds no spatial index – that is backend-specific and is the caller's next step.

Template Parameters
PSoA payload type (see mergeNearestNeighborsTree()).
PackedOpaque reconciliation payload type (see MergeParticle).
TraitsColumn descriptor for P.
GatherCallable (const ParticleSoA<P,Traits>&, std::size_t) -> Packed.
Parameters
[in,out]a_particlesThe real particle container being merged.
[out]a_patchWorkOne entry per patch this rank owns.
[out]a_patchLocalValidThis patch's own local-valid particles, parallel to a_patchWork.
[out]a_patchGhostsEvery ghost shipped to this patch, parallel to a_patchWork.
[out]a_particlesByIDEvery currently-alive local-valid particle and every ghost, pooled rank-wide by id.
[out]a_liveCellCountLive particle count (valid + ghost) per level-qualified cell key, derived from a_particlesByID.
[in]a_amrAMR mesh – source of ghost masks and the patch layout.
[in]a_realmRealm name (a_particles.getRealm()).
[in]a_finestLevelFinest AMR level (a_amr.getFinestLevel()).
[in]a_probLoPhysical position of the domain's low corner.
[in]a_dxByLevelCell spacing per AMR level.
[in]a_ghostWidthParticle ghost halo width already filled by the caller (see mergeNearestNeighborsTree()'s own a_ghostWidth docs).
[in]a_gatherPer-slot gather callback.

◆ generateProposals()

template<typename Packed>
void ParticleManagement::detail::generateProposals ( std::vector< std::vector< NNMergeProposal< Packed > > > & a_proposalsByDestRank,
const std::vector< NNMergeEdge< Packed > > & a_edges,
const std::unordered_set< ParticleID > & a_hasOutgoingCommitment,
const std::unordered_map< ParticleID, NNPooledParticle< Packed > > & a_particlesByID,
const int a_numRanks )
inlinenoexcept

Package one outgoing proposal for every edge that resolveTrivialTier() could not resolve locally, bucketed by destination rank.

Routing rule: ALWAYS to the owner of the candidate (NNMergeEdge::candidateID's owning rank) – never by any id comparison (see NNMergeProposal). If the destination rank equals this rank's own (a boundary-exposed candidate that happens to live in a DIFFERENT patch owned by the same rank), the proposal still goes into the normal per-destination-rank bucket – the caller (mergeNearestNeighborsTree()) is expected to hand the "bucket addressed to myself" directly to judgeProposals() in-process, without an actual MPI round-trip, while every other bucket goes out over MPI. This keeps the decision logic in judgeProposals() completely unaware of whether a given proposal arrived locally or over the network – it still goes through the exact same pooled judge logic, never a shortcut.

Template Parameters
PackedSee MergeParticle.
Parameters
[out]a_proposalsByDestRankOne bucket per rank; a_proposalsByDestRank[r] holds every proposal whose candidate is owned by rank r (including r == this rank's own).
[in]a_edgesCandidate edges from findNearestNeighborCandidates(), for all of this rank's patches.
[in]a_hasOutgoingCommitmentQuery-particle ids that resolveTrivialTier() could not resolve (i.e. exactly the edges this function packages).
[in]a_particlesByIDFull particle data for every currently-alive local valid particle and every ghost, keyed by id (each value an NNPooledParticle wrapping the particle) – needed to build the full MergeParticle bundle for each proposal.
[in]a_numRanksTotal MPI rank count (size of the returned bucket vector).

◆ judgeProposals()

template<typename Packed, typename Combine, typename PosValid, typename Allocator, typename OnMerge>
void ParticleManagement::detail::judgeProposals ( std::unordered_map< NNCellKey, int, NNCellKeyHasher > & a_liveCellCount,
std::vector< NNMergeResult< Packed > > & a_results,
std::vector< std::vector< NNMergeVerdict > > & a_verdictsByDestRank,
const std::vector< NNMergeProposal< Packed > > & a_incomingProposals,
const std::unordered_map< ParticleID, NNPooledParticle< Packed > > & a_particlesByID,
const std::unordered_set< ParticleID > & a_consumedIDs,
const std::unordered_set< ParticleID > & a_hasOutgoingCommitment,
const std::map< ParticleID, ParticleID > & a_outgoingTargetOf,
const Combine & a_combine,
const NNCellBudget & a_cellBudget,
const RealVect & a_probLo,
const std::vector< RealVect > & a_dxByLevel,
const PosValid & a_isPositionValid,
const Allocator & a_allocateID,
const std::optional< int > a_maxCellDistance = std::nullopt,
unsigned long long * a_crossLevelMergeCount = nullptr,
const OnMerge & a_onMergeCommitted = [](const MergeParticle<Packed>&, const MergeParticle<Packed>&, const MergeParticle<Packed>&) { } )
inlinenoexcept

Judge every incoming proposal that targets a particle this rank owns, and produce the verdicts to send back.

The full rule set this function implements, summarized:

  1. Group incoming proposals by target id.
  2. For a target with NO outgoing commitment of its own: the eligible candidate is the minimum-distance incoming proposal (deterministic id tiebreak on exact ties).
  3. For a target that DOES have its own outgoing commitment (i.e. it is simultaneously proposing to something else): normally reject every incoming proposal unconditionally (it is "spoken for") – EXCEPT when its own outgoing target is itself one of its current incoming proposers, a genuinely mutual best-match pair. Blindly rejecting that case causes a PERMANENT deadlock (a stable mutual pair proposes to each other identically every round and is rejected every round, forever, since nothing changes to break the symmetry) – so it must be accepted instead. Because BOTH sides of a mutual pair detect the match independently, a deterministic tiebreak (lower-id side performs the accept, higher-id side falls back to the normal reject) is required, or both sides would accept and double-merge the same two particles.
  4. ALL eligible target decisions (plain-argmin and mutual-match alike) are resolved in ONE globally distance-sorted pass across every target this rank is judging (with an id tiebreak) – NOT by iterating targets in whatever order the incoming-proposal list happens to be in. Accepting one target decrements its cell's live count, which can push a DIFFERENT target sharing that cell below threshold; judging targets in arbitrary order makes that outcome depend on arbitrary processing order. Sorting closest-first with a dynamic per-target threshold recheck (mirroring resolveTrivialTier()'s discipline exactly) removes that dependency.
  5. This handles any number of simultaneous suitors for one particle, not just pairwise boundaries – a corner where 3+ patches meet is resolved by this exact same logic, with no special-casing, since every proposal naming a given target funnels into the same "group by target id" step regardless of how many different ranks it came from.
  6. A_maxCellDistance and a_isPositionValid apply here exactly as they do in resolveTrivialTier() – a physical-validity rule, not a coordination one. An incoming proposal that is too far, or whose weighted-centroid position fails a_isPositionValid, is never eligible to be accepted (skipped as though it did not exist for argmin purposes), REGARDLESS of the mutual-match exception in rule 3 – an invalid position is invalid on both sides of a pair, mutual match or not.

Proposals addressed to this rank's own particles arrive from two sources, pooled identically here: proposals received over MPI from other ranks, and this rank's own generateProposals()-produced bucket addressed to itself (an in-process handoff, no network round-trip – see generateProposals()).

Template Parameters
PackedSee MergeParticle.
CombineSee PayloadCombine.
PosValidSee PositionValid.
Parameters
[in,out]a_liveCellCountLive per-cell counts for this rank's own patches; decremented in place as targets are accepted, in the same distance-sorted processing order (see rule 4 above). Used to dynamically recheck BOTH the target's AND the source's own cell – mirrors resolveTrivialTier()'s symmetric recheck exactly; accepting a proposal whose source's own cell is no longer over threshold (e.g. drained by an earlier merge within this same round) would silently violate the crowding trigger on the source side. If this rank has no live visibility into the source's cell (it was never shipped here as a ghost), the source count defaults to 0 – i.e. rejected – the same conservative default already used when a target's own count is unknown.
[out]a_resultsOne entry per target actually accepted, in the order processed.
[out]a_verdictsByDestRankOne bucket per proposer rank (pre-sized to the total rank count by the caller); every proposal (accepted or not) gets exactly one verdict, addressed back to NNMergeProposal::source's owning rank.
[in]a_incomingProposalsAll proposals targeting a particle this rank owns, pooled from every source rank (including this rank's own in-process bucket).
[in]a_particlesByIDFull particle data for every currently-alive local valid particle and every ghost across all of this rank's patches, keyed by id (each value an NNPooledParticle wrapping the particle) – a target is a potential judge target only if its id is present here AND absent from a_consumedIDs (see that param).
[in]a_consumedIDsIds already consumed this round (by an earlier trivial or judged merge). A target id present in a_particlesByID but ALSO in a_consumedIDs is treated as not-alive – this replaces what used to be a separate, pre-filtered a_myParticlesByID copy of a_particlesByID; checking both containers at the point of use instead avoids rebuilding that copy every round.
[in]a_hasOutgoingCommitmentIds (among a_particlesByID, not in a_consumedIDs) that have their own outgoing commitment this round (needed for rule 3 above).
[in]a_outgoingTargetOfFor an id in a_hasOutgoingCommitment, the id of the particle it is itself proposing to (needed to detect the mutual-match exception in rule 3).
[in]a_combineOpaque-payload combine callback (see PayloadCombine).
[in]a_cellBudgetPer-cell budget (the same budget used everywhere else this round).
[in]a_probLoPhysical position of the domain's low corner (see cellKeyOf()).
[in]a_dxByLevelCell spacing PER AMR LEVEL – see resolveTrivialTier()'s a_dxByLevel docs for why this must never be a single shared dx (a proposal's source and this rank's target can be on different levels).
[in]a_isPositionValidPosition-validity predicate (see PositionValid and rule 6 above).
[in]a_allocateIDFresh-id allocator (see IDAllocator), called once per accepted target.
[in]a_maxCellDistanceSame physical merge-eligibility cap as resolveTrivialTier()'s (see rule 6 above); std::nullopt (default) disables it.
[in,out]a_crossLevelMergeCountOptional diagnostic counter – see resolveTrivialTier()'s docs; incremented once per accepted target whose target/source were on different AMR levels.
[in]a_onMergeCommittedOptional per-merge diagnostic callback – see resolveTrivialTier()'s docs; called with (target, source, merged) for every accepted target.

◆ kdBBox()

template<typename Packed>
void ParticleManagement::detail::kdBBox ( RealVect & a_boxLo,
RealVect & a_boxHi,
const std::vector< MergeParticle< Packed > > & a_particles,
const std::size_t a_lo,
const std::size_t a_hi )
inlinenoexcept

Axis-aligned bounding box of particles[a_lo, a_hi).

Parameters
[out]a_boxLoLow corner.
[out]a_boxHiHigh corner.
[in]a_particlesParticle buffer.
[in]a_loStart of the range (inclusive).
[in]a_hiEnd of the range (exclusive).

◆ kdBoxRealBounds()

void ParticleManagement::detail::kdBoxRealBounds ( RealVect & a_boxLo,
RealVect & a_boxHi,
const Box & a_box,
const RealVect & a_dx,
const RealVect & a_probLo )
inlinenoexcept

Real-space bounds of a box: the half-open region [lo, hi) that its cells cover.

Half-open on purpose – the high corner is the OUTER face of the last cell, so testing pos >= lo && pos < hi per direction partitions space between abutting boxes with no gap and no double-cover, which is exactly the "is this particle still in its own patch" test both callers make.

Parameters
[out]a_boxLoLow corner (inclusive).
[out]a_boxHiHigh corner (exclusive).
[in]a_boxBox whose bounds are wanted.
[in]a_dxGrid spacing at the box's level.
[in]a_probLoLower-left corner of the physical domain.

◆ kdCapCellWeights()

template<typename Packed, typename PosValid>
void ParticleManagement::detail::kdCapCellWeights ( std::vector< MergeParticle< Packed > > & a_particles,
const FArrayBox & a_cellCounts,
const FArrayBox & a_cellWeights,
const int a_ppc,
const KDSplitPlacement a_splitPlacement,
const RealVect & a_probLo,
const RealVect & a_dx,
const PosValid & a_isPositionValid )
inlinenoexcept

Cap every resident particle in a crowded cell at that cell's target leaf weight, splitting the ones above it into pieces.

A particle heavier than a leaf's target weight cannot be equalized away by any partition: it alone sets a floor on whichever leaf it lands in. The whole-patch build is forbidden from dividing a particle mid-tree (see kdSplitWeightMedian()), which is exactly why its super-particle weights come out uneven. Dividing beforehand sidesteps that: it is local, it needs no id arbitration, and it happens before any leaf exists.

Only CROWDED cells are capped (count > a_ppc). An uncrowded cell's particles are emitted as singleton leaves and never merged, so splitting there would raise its population above the target with nothing to bring it back down. Capping a crowded cell only ever raises its count, so it stays crowded and a_cellCounts remains correct for the one thing buildKDQuotaLeaves() asks of it.

Ghosts are never capped. A ghost belongs to another patch, which is capping it too; splitting it here as well would double-count its weight.

A displaced piece is validated with the caller's own position predicate and falls back to the parent's position if it fails. Unlike the per-cell build this has no CellInfo to test the volume fraction with, and a piece that is never merged – its leaf vetoed for width, or lost at a contested boundary – keeps the position it was given, so a raw displacement in a cut cell could otherwise leave a particle inside the solid.

Template Parameters
PackedSee MergeParticle.
Parameters
[in,out]a_particlesGathered particles for this patch; grown in place by the split pieces.
[in]a_cellCountsPer-cell true particle counts (see kdFillCellHistogram()).
[in]a_cellWeightsPer-cell total weight, over the same box as a_cellCounts.
[in]a_ppcTarget particles per cell.
[in]a_splitPlacementWhere each piece goes – see ParticleManagement::KDSplitPlacement.
[in]a_probLoPhysical position of the domain's low corner.
[in]a_dxThis patch's own cell spacing.
[in]a_isPositionValidPredicate rejecting positions inside the embedded boundary.

◆ kdCellKeyOf()

IntVect ParticleManagement::detail::kdCellKeyOf ( const RealVect & a_position,
const RealVect & a_probLo,
const RealVect & a_dx )
inlinenoexcept

The unclamped, position-derived cell index a physical position falls in.

Same convention as the nearest-neighbor merge's cellKeyOf() – not clamped to any patch's box, so positions in different patches' local frames stay directly comparable.

Parameters
[in]a_positionPhysical position.
[in]a_probLoPhysical position of the domain's low corner.
[in]a_dxCell spacing.
Returns
floor((a_position - a_probLo) / a_dx), component-wise.

◆ kdCheckCentroid()

void ParticleManagement::detail::kdCheckCentroid ( const RealVect & a_centroid,
const Real a_totalWeight,
const RealVect & a_boxLo,
const RealVect & a_boxHi )
inlinenoexcept

Debug-only sanity check on a merged particle's position: a weighted centroid of positions that all lie within [a_boxLo,a_boxHi], using strictly positive weights, is mathematically guaranteed to itself lie within that same box.

CH_assert this explicitly (rather than trust the arithmetic silently) so that a stray sign error, a mis-set/negative weight, or a wrong id feeding the wrong position into the accumulation surfaces immediately as an assertion in a DEBUG build, instead of silently producing a merged superparticle placed somewhere non-physical. A relative tolerance accounts for floating- point round-off in the summation, not for any real violation.

Parameters
[in]a_centroidComputed weighted centroid.
[in]a_totalWeightSum of weights used to compute a_centroid.
[in]a_boxLoLow corner of the bounding box every contributing position lies within.
[in]a_boxHiHigh corner of the bounding box every contributing position lies within.

◆ kdExchangeByRank()

template<typename T>
std::vector< T > ParticleManagement::detail::kdExchangeByRank ( const std::vector< std::vector< T > > & a_sendByRank)
inline

Generic Alltoallv-style exchange for a trivially-copyable record type: send a per-destination-rank bucket, return the flat concatenation of everything received.

A deliberate, self-contained duplicate of the nearest-neighbor merge's nnMergeExchangeByRank() (same MPI_Alltoall/Alltoallv shape) rather than a shared dependency – that function lives in a header that transitively pulls in EBGeometry, which this file must not depend on (see this file's own

). In a serial (non-MPI) build, or with a single rank, returns this rank's own bucket unchanged.

Template Parameters
TTrivially-copyable record type (KDClaim, KDVerdict, KDCommit, or MergeParticle<Packed> with Packed itself trivially copyable).
Parameters
[in]a_sendByRankOne bucket per destination rank (size == number of ranks).
Returns
Flat vector of every record received from every rank (including this rank's own bucket addressed to itself).

◆ kdFillCellHistogram()

template<typename Packed>
void ParticleManagement::detail::kdFillCellHistogram ( FArrayBox & a_counts,
const std::vector< MergeParticle< Packed > > & a_particles,
const RealVect & a_probLo,
const RealVect & a_dx )
inlinenoexcept

Tally a per-cell particle-count histogram over one patch's gathered particles.

Built from every particle's own position, so it is unaffected by how buildKDQuotaLeaves() later partitions the space – a node-local count is NOT a safe substitute, see that function's own docs for why. Shared by mergeKDCarve()/mergeKDPatch()/mergeKDInterior(): all three need the same ground truth, and the invariant that it comes from true positions rather than from the partition is easy to break if each keeps its own copy.

a_counts must include at least one ghost cell, since a gathered ghost sits up to one cell outside the patch's own box.

The count is stored in a_counts' Real elements but is always a non-negative integer. A double represents every integer exactly up to 2^53, so consumers – e.g. the crowding test in buildKDQuotaLeaves() – may static_cast<int> it losslessly for any realistic per-cell count.

Template Parameters
PackedSee MergeParticle.
Parameters
[out]a_countsPer-cell counts, zeroed here before tallying.
[in]a_particlesGathered particles for this patch.
[in]a_probLoPhysical position of the domain's low corner.
[in]a_dxThis patch's own cell spacing.

◆ kdIntVectLess()

bool ParticleManagement::detail::kdIntVectLess ( const IntVect & a_lhs,
const IntVect & a_rhs )
inlinenoexcept

Strict weak ordering over IntVect, lexicographic component-wise.

Used to sort/binary-search the per-patch, per-cell TRUE particle-count histogram (see buildKDQuotaLeaves()'s own docs) – IntVect has no built-in total order.

Parameters
[in]a_lhsLeft-hand cell index.
[in]a_rhsRight-hand cell index.
Returns
True iff a_lhs sorts strictly before a_rhs.

◆ kdMaxAxisSpan()

Real ParticleManagement::detail::kdMaxAxisSpan ( const RealVect & a_boxLo,
const RealVect & a_boxHi,
const RealVect & a_dx )
inlinenoexcept

Largest per-axis extent of [a_boxLo,a_boxHi], expressed as a fraction of that axis's own cell width.

The correctness backstop buildKDQuotaLeaves(), mergeKDCarve() and mergeKDPatch() rely on to decide whether a leaf is compact enough to merge: unlike an aggregate VOLUME ratio (a product across axes), this cannot be fooled by an anisotropic (long-and-thin) bounding box – e.g. a box 5 cells long in one axis and 0.2 cells wide in another has volume ratio 1.0 (deceptively "one cell's worth") but a maxAxisSpan of 5.0 (correctly flagged as still spanning several cells). Particles hugging a curved EB surface, or funneled along a narrow L-shaped coarse-fine strip, produce exactly this kind of elongated cluster.

Parameters
[in]a_boxLoLow corner.
[in]a_boxHiHigh corner.
[in]a_dxCell spacing.
Returns
max_dir (a_boxHi[dir] - a_boxLo[dir]) / a_dx[dir].

◆ kdPlaceMerged()

template<typename Packed>
RealVect ParticleManagement::detail::kdPlaceMerged ( const KDPlacement a_placement,
const RealVect & a_centroid,
const Real a_totalWeight,
const RealVect & a_boxLo,
const RealVect & a_boxHi,
const std::vector< Real > & a_weights,
const std::vector< RealVect > & a_positions )
inlinenoexcept

Place the super-particle a leaf reduces to, given the leaf's members and their weighted centroid.

The three placements differ in what they keep of the leaf. The centroid keeps its mean position and discards its spread, so repeated merges contract the sub-cell distribution onto a lattice of leaf centres. Sampling keeps a position one of the leaf's own particles occupied, drawn with probability proportional to weight, which is distribution-preserving. Random keeps only the leaf's extent.

Unlike the per-cell build, these leaves are deliberately not snapped to the grid, so a leaf can straddle a cell face and the placed particle can land in a different cell from the centroid – which is what the per-cell leaf quota counted. That is the algorithm working as intended (a leaf merges across a face precisely because it is allowed to span one), not an error: the quota bounds how many leaves are centred in a cell, not where each leaf's particle ends up.

Template Parameters
PackedSee MergeParticle.
Parameters
[in]a_placementWhich placement to apply.
[in]a_centroidThe leaf's weighted centroid, already computed by the caller.
[in]a_totalWeightThe leaf's total weight, i.e. the sum of a_weights.
[in]a_boxLoLow corner of the leaf's bounding box.
[in]a_boxHiHigh corner of the leaf's bounding box.
[in]a_weightsThe members' weights, parallel to a_positions.
[in]a_positionsThe members' positions, parallel to a_weights. Read only by KDPlacement::Sample, so callers may leave it empty for the other two placements rather than filling a vector no branch will look at.
Returns
The position to give the merged particle. Always inside [a_boxLo, a_boxHi].

◆ kdSplitCountMedian()

template<typename Packed>
std::size_t ParticleManagement::detail::kdSplitCountMedian ( std::vector< MergeParticle< Packed > > & a_particles,
const std::size_t a_lo,
const std::size_t a_hi,
const int a_axis )
inlinenoexcept

Split particles[a_lo,a_hi) in place by the longest axis at the count-median – the sole split rule used by buildKDQuotaLeaves().

The split point is the position-sorted median particle (via nth_element), balancing COUNT as evenly as possible – mirrors the per-cell build's own logic, but by count, never by weight, and with NO synthetic particle splitting (a particle is never divided across the two children). nth_element divides the range in half by count however the positions are distributed, so a tightly clustered node still splits evenly.

Parameters
[in,out]a_particlesParticle buffer; reordered in [a_lo,a_hi).
[in]a_loStart of the range (inclusive).
[in]a_hiEnd of the range (exclusive); a_hi - a_lo must be >= 2.
[in]a_axisSplit axis – the node's longest box axis, precomputed once by the caller (which already needs the box for the span test) rather than re-derived here from a second bounding box.
Returns
The split index: [a_lo,mid) and [mid,a_hi) are the two children, each non-empty.

◆ kdSplitDisplace()

RealVect ParticleManagement::detail::kdSplitDisplace ( const KDSplitPlacement a_placement,
const RealVect & a_parent,
const RealVect & a_cellLo,
const RealVect & a_dx,
const Real a_spacing )
inlinenoexcept

Place one piece of a split particle.

Shared by the per-cell and whole-patch builds so both spread split pieces the same way.

The jitter kernel is TRUNCATED to the cell, not clamped and not reflected. Clamping stacks every out-of-range draw onto the wall. Reflecting folds the overhanging part of the kernel back on top of the part that stayed, doubling the density within half a bandwidth of each wall – and since the fold is per-direction, a parent near a corner is folded once per direction and the corner gets 2^D times the density it should. Truncation is the correct conditional distribution: draw uniformly from the part of the kernel that lies inside the cell. Its only cost is a mild inward bias for parents within half a bandwidth of a wall, which is second order in the bandwidth and has no directional structure.

Parameters
[in]a_placementWhich rule to apply. Center returns the parent's position unchanged.
[in]a_parentThe parent particle's position.
[in]a_cellLoLow corner of the cell the parent lives in.
[in]a_dxCell spacing, per direction.
[in]a_spacingJitter bandwidth – the local mean interparticle spacing.
Returns
The piece's position, always inside the parent's cell.

◆ kdSplitWeightMedian()

template<typename Packed>
std::size_t ParticleManagement::detail::kdSplitWeightMedian ( std::vector< MergeParticle< Packed > > & a_particles,
const std::size_t a_lo,
const std::size_t a_hi,
const int a_axis )
inlinenoexcept

Split particles[a_lo,a_hi) in place by the longest axis at the WEIGHT median – the plane with half this node's total particle weight on either side.

Used instead of the count median so that the resulting leaves carry roughly equal total weight, and therefore so do the super-particles they collapse into. Uniform super-particle weight is what keeps statistical noise down, and is what kd_partition = weight asks for.

Unlike the per-cell build this NEVER divides a particle synthetically, so exact equality is not attainable: once a single particle's weight exceeds a leaf's target weight, that particle alone sets a floor no partition can get under. The bound the per-cell build guarantees (max/min <= 2) is bought precisely by that synthetic division and is therefore out of reach here by construction.

A weight median can land very unevenly BY COUNT – one dominant particle carrying half the node's weight forces a 1-vs-(n-1) split. That is harmless here only because buildKDQuotaLeaves() enforces a hard per-cell leaf quota independently of how the split plane behaves: an uneven split can cost merge quality but cannot leave a cell above target. Under any of the earlier, quota-less formulations the same degeneracy was fatal.

Parameters
[in,out]a_particlesParticle buffer; reordered in [a_lo,a_hi).
[in]a_loStart of the range (inclusive).
[in]a_hiEnd of the range (exclusive); a_hi - a_lo must be >= 2.
[in]a_axisSplit axis – the node's longest box axis, precomputed once by the caller (which already needs the box for the span test) rather than re-derived here from a second bounding box.
Returns
The split index: [a_lo,mid) and [mid,a_hi) are the two children, each non-empty.

◆ mergeNearestNeighborsRoundImpl()

template<typename P, typename Packed, typename Traits, typename Cloud, typename Gather, typename Combine, typename Scatter, typename Allocator, typename PosValid, typename OnMerge>
void ParticleManagement::detail::mergeNearestNeighborsRoundImpl ( ParticleContainer< P, Traits > & a_particles,
unsigned long long * a_crossLevelMergeCount,
const AmrMesh & a_amr,
const NNCellBudget & a_cellBudget,
const Gather & a_gather,
const Combine & a_combine,
const Scatter & a_scatter,
const Allocator & a_allocateID,
const bool a_iterateLocalTierToConvergence,
const int a_maxFallbackCandidates,
const std::optional< int > a_maxCellDistance,
const int a_ghostWidth,
const PosValid & a_isPositionValid,
const OnMerge & a_onMergeCommitted )
inline

Shared implementation behind mergeNearestNeighborsTree() and mergeNearestNeighborsHash(): one full round of the whole-patch-tree nearest-neighbor merge, generic over which EBGeometry point-cloud index backs the per-patch spatial search.

Identical algorithm and public contract to mergeNearestNeighborsTree() (see its own docs for the full step-by-step description) – the only difference between the two public entry points is which Cloud this function is instantiated with: EBGeometry::PointCloudBVH<Real,ParticleID> for mergeNearestNeighborsTree(), EBGeometry::PointCloudHashGrid<Real,ParticleID> for mergeNearestNeighborsHash(). Both point-cloud types expose an identical query interface, so this one implementation serves both without any backend-specific branching.

Template Parameters
CloudEBGeometry point-cloud index type (see NNSpatialIndex).
P,Packed,Traits,Gather,Combine,Scatter,Allocator,PosValid,OnMergeSee mergeNearestNeighborsTree().
Parameters
a_amr,a_particles,a_cellBudget,a_gather,a_combine,a_scatter,a_allocateID,a_iterateLocalTierToConvergence,a_maxFallbackCandidates,a_maxCellDistance,a_ghostWidth,a_isPositionValid,a_crossLevelMergeCount,a_onMergeCommittedSee mergeNearestNeighborsTree().

◆ nnMergeAnyCellCrowded()

template<typename Packed>
bool ParticleManagement::detail::nnMergeAnyCellCrowded ( const std::vector< MergeParticle< Packed > > & a_localValid,
const std::vector< MergeParticle< Packed > > & a_ghosts,
const RealVect & a_probLo,
const RealVect & a_dx,
const NNCellBudget & a_cellBudget )
inlinenoexcept

Exact per-cell crowding pre-filter shared by buildNNSpatialIndex()/buildNNCellSpatialIndex(): is any cell in this patch's local+ghost particle set over its a_cellBudget?

A count-only tally keyed as the crowding trigger (cellKeyOf(pos, probLo, dx), local and ghost alike); checks the true per-cell maximum, not an average density (a low-average patch can still hold one over-threshold cell).

Template Parameters
PackedSee MergeParticle.
Parameters
[in]a_localValidThis patch's own full valid-particle set.
[in]a_ghostsEvery ghost shipped to this patch this round.
[in]a_probLoPhysical position of the domain's low corner.
[in]a_dxCell spacing of THIS PATCH's own level.
[in]a_cellBudgetThe count each cell is drained down to – see NNCellBudget.
Returns
True iff some cell holds strictly more particles than its own budget allows.

◆ nnMergeChebyshevCellDistance()

int ParticleManagement::detail::nnMergeChebyshevCellDistance ( const IntVect & a_a,
const IntVect & a_b )
inlinenoexcept

Chebyshev (max-per-axis) distance between two cell-index vectors – see CD_NearestNeighborParticleMerge.H's a_maxCellDistance docs.

Parameters
[in]a_aFirst cell index.
[in]a_bSecond cell index.
Returns
Max-per-axis distance between a_a and a_b.

◆ nnMergeCrossLevelTooFar()

bool ParticleManagement::detail::nnMergeCrossLevelTooFar ( const RealVect & a_posA,
const int a_levelA,
const RealVect & a_posB,
const int a_levelB,
const RealVect & a_probLo,
const std::vector< RealVect > & a_dxByLevel,
const int a_maxCellDistance )
inlinenoexcept

a_maxCellDistance check for two positions that may be on DIFFERENT AMR levels.

Raw cell indices computed with two different dx values are not directly comparable, so both positions are re-expressed in the finer of the two levels' cell-size units (higher AMR level = finer) before taking the Chebyshev distance. Reduces to the same-level case when a_levelA == a_levelB.

Parameters
[in]a_posAFirst participant's position.
[in]a_levelAFirst participant's AMR level.
[in]a_posBSecond participant's position.
[in]a_levelBSecond participant's AMR level.
[in]a_probLoPhysical position of the domain's low corner.
[in]a_dxByLevelCell spacing per AMR level.
[in]a_maxCellDistanceThe cap (see CD_NearestNeighborParticleMerge.H's a_maxCellDistance docs).
Returns
True iff the pair exceeds a_maxCellDistance.

◆ nnMergeDistSquared()

Real ParticleManagement::detail::nnMergeDistSquared ( const RealVect & a_a,
const RealVect & a_b )
inlinenoexcept

Squared Euclidean distance between two physical positions.

Parameters
[in]a_aFirst position.
[in]a_bSecond position.
Returns
Squared distance between a_a and a_b.

◆ nnMergeExchangeByRank()

template<typename T>
std::vector< T > ParticleManagement::detail::nnMergeExchangeByRank ( const std::vector< std::vector< T > > & a_sendByRank)
inline

Generic alltoallv-style exchange: send a per-destination-rank bucket of trivially- copyable records, return the flat concatenation of everything received.

Packs one bucket per rank and exchanges via MPI_Alltoall (byte counts) + MPI_Alltoallv (payload). In a serial (non-MPI) build, or with a single rank, this returns this rank's own bucket unchanged.

Template Parameters
TTrivially-copyable record type (NNMergeProposal<Packed>, NNMergeVerdict, or MergeParticle<Packed> – all satisfy this given Packed itself is required to).
Parameters
[in]a_sendByRankOne bucket per destination rank (size == number of ranks).
Returns
Flat vector of every record received from every rank (including this rank's own bucket addressed to itself).

◆ nnMergePointToCellDistSquared()

Real ParticleManagement::detail::nnMergePointToCellDistSquared ( const RealVect & a_point,
const IntVect & a_cell,
const RealVect & a_probLo,
const RealVect & a_dx )
inlinenoexcept

Squared distance from a physical point to a cell's axis-aligned bounding box (0 if the point is inside).

Parameters
[in]a_pointPhysical position.
[in]a_cellCell index.
[in]a_probLoPhysical position of the domain's low corner.
[in]a_dxCell spacing.
Returns
Squared distance from a_point to [a_probLo + a_cell*a_dx, a_probLo + (a_cell + 1)*a_dx].

◆ nnMergeWeightedCentroid()

void ParticleManagement::detail::nnMergeWeightedCentroid ( RealVect & a_mergedPos,
Real & a_mergedWeight,
const RealVect & a_posA,
const Real a_weightA,
const RealVect & a_posB,
const Real a_weightB )
inlinenoexcept

Weighted-centroid merge of two positions/weights – shared by resolveTrivialTier() and judgeProposals() so the formula is written exactly once.

Parameters
[out]a_mergedPosWeighted-centroid position.
[out]a_mergedWeightSummed weight.
[in]a_posAFirst particle's position.
[in]a_weightAFirst particle's weight.
[in]a_posBSecond particle's position.
[in]a_weightBSecond particle's weight.

◆ partitionParticles()

template<typename T, typename>
T ParticleManagement::detail::partitionParticles ( const T a_numParticles)
inline

Partition particles so that all MPI rank draw a cumulative number of particles equal to a_numParticles.

Parameters
[in]a_numParticlesTotal number of particles to be drawn.
Returns
Returns the number of particles drawn by each rank.

◆ placeMergedParticles()

template<typename Packed>
void ParticleManagement::detail::placeMergedParticles ( std::map< std::pair< int, unsigned int >, std::vector< MergeParticle< Packed > > > & a_localByPatch,
std::vector< std::vector< MergeParticle< Packed > > > & a_scatterByDestRank,
const std::vector< NNMergeResult< Packed > > & a_results,
const PositionLocator & a_locate,
const int a_thisRank )
inlinenoexcept

Point-locate a newly created merged particle against the AMR grid, and bucket it for a scatter exchange if it belongs to someone else.

Applied UNIFORMLY to every merge result, trivial-tier and judge-decided alike: the union of two patches is not generally convex (T-junctions, corners, refinement boundaries), so even a purely local (same-rank) merge's result can legitimately belong to a third patch, possibly owned by a different rank. Point-location must be O(1) per result (see PositionLocator) – NEVER a linear scan over every patch, which would turn this function into a real bottleneck at large patch counts.

Template Parameters
PackedSee MergeParticle.
Parameters
[out]a_localByPatchResults whose merged particle lands in one of this rank's own patches, bucketed by (level, LevelTiles::LevelAndBox::gridIndex).
[out]a_scatterByDestRankResults whose merged particle belongs to a different rank, bucketed by destination rank (pre-sized to the total rank count by the caller), for one final exchange.
[in]a_resultsEvery merge result produced this round by resolveTrivialTier() and judgeProposals(), pooled together.
[in]a_locateLocate-by-position callback (see PositionLocator).
[in]a_thisRankThis rank's own number – a located box whose rank equals this is what makes a result "local" rather than needing a scatter.

◆ resolveTrivialTier()

template<typename Packed, typename Combine, typename PosValid, typename Allocator, typename OnMerge>
void ParticleManagement::detail::resolveTrivialTier ( std::unordered_map< NNCellKey, int, NNCellKeyHasher > & a_liveCellCount,
std::unordered_set< ParticleID > & a_consumedIDs,
std::unordered_set< ParticleID > & a_hasOutgoingCommitment,
std::vector< NNMergeResult< Packed > > & a_results,
const std::vector< NNMergeEdge< Packed > > & a_edges,
const std::unordered_map< ParticleID, NNPooledParticle< Packed > > & a_particlesByID,
const Combine & a_combine,
const NNCellBudget & a_cellBudget,
const RealVect & a_probLo,
const std::vector< RealVect > & a_dxByLevel,
const PosValid & a_isPositionValid,
const Allocator & a_allocateID,
const int a_maxFallbackCandidates = 0,
const std::optional< int > a_maxCellDistance = std::nullopt,
unsigned long long * a_crossLevelMergeCount = nullptr,
const OnMerge & a_onMergeCommitted = [](const MergeParticle<Packed>&, const MergeParticle<Packed>&, const MergeParticle<Packed>&) { } )
inlinenoexcept

Resolve every candidate edge that is safely mergeable with zero cross-rank coordination, and mark which remaining particles have committed to a non-trivial outgoing proposal.

An edge is trivial-tier eligible iff NEITHER the query nor the candidate is boundary-exposed (see Realm::m_particleGhostExposure) – this check happens AFTER finding the true nearest neighbor, never as a restriction on the search itself.

All eligible edges (across every patch this rank owns) are processed in ONE globally distance-sorted order, with a deterministic secondary tiebreak on participant ids – exact distance ties (e.g. true mutual nearest neighbors) are common enough that leaving them to arbitrary iteration/insertion order produces real, observed nondeterminism that cascades into unrelated pairs several hops away.

At the moment each edge is actually processed (not at generation time): re-verify both participants are still alive (lazy invalidation – skip if either was already consumed by a closer edge processed earlier in this same pass); if the candidate is local, re-verify it has NOT, in the meantime, committed to its OWN outgoing (non-trivial) proposal – a purely geometric "exposed" check on the candidate alone is insufficient, since a non-exposed particle's true nearest neighbor can still be a foreign ghost even though the particle itself is unreachable externally; consuming such a candidate trivially anyway is a real double-consumption bug this dynamic recheck closes. Finally, re-verify both participants' CURRENT cell occupancy (reflecting decrements from edges already processed this pass, not the generation-time snapshot) still exceeds the threshold.

On a successful trivial-tier commit: remove both participants from the caller's own valid particle list (conceptually – see a_consumedIDs), decrement both cells' live counts, and record the merge via a_combine/into a_results. On an edge that cannot be resolved trivially, exactly one of two things happens, and the distinction matters:

  • If the candidate is a ghost, OR either participant is boundary-exposed, OR the candidate turned out to already have its own outgoing commitment: mark the query particle as having an outgoing commitment (see a_hasOutgoingCommitment) so generateProposals() can pick it up. In all three cases the candidate genuinely still exists (it just isn't trivially available right now), so a proposal is meaningful – judgeProposals() already has a rule for "target has its own outgoing commitment" (accept only on a mutual match, reject otherwise), and that rule is exactly what should get a chance to run here, not a silent no-op.
  • If the candidate is stale (already consumed – found dead by the lazy-invalidation check above): do NOT mark the query particle as having an outgoing commitment, and do NOT generate a proposal. There is no meaningful id to propose to. Critically, this also means the query particle is NOT marked "busy" – it remains fully available for some OTHER particle to claim as an ordinary trivial candidate later in this same sorted pass, or via a_maxFallbackCandidates below.
Template Parameters
PackedSee MergeParticle.
CombineSee PayloadCombine.
Parameters
[in,out]a_liveCellCountLive per-cell counts; decremented in place as trivial merges commit, so later edges in the same pass see the up-to-date occupancy.
[in,out]a_consumedIDsIds already consumed this round (by an earlier trivial merge, or found dead for any other reason); an edge referencing a consumed id is stale and skipped. Updated in place.
[out]a_hasOutgoingCommitmentSet of query-particle ids that were NOT resolved trivially (excluding the stale-candidate case, see above) and must go on to generateProposals().
[out]a_resultsOne entry per trivial-tier merge actually committed, in the order they were processed.
[in]a_edgesCandidate edges from findNearestNeighborCandidates(), for ALL patches this rank owns (pooled together so the global distance sort spans the whole rank, not just one patch).
[in]a_particlesByIDFull particle data for every currently-alive local valid particle and every ghost across all of this rank's patches, keyed by id. Each value is an NNPooledParticle: the particle (position/weight/id/rank/ payload, needed to compute a merge's weighted-centroid position and call a_combine, since an edge only carries ids/distance) plus its cached boundary-exposure flag (Realm::m_particleGhostExposure; false for ghosts).
[in]a_combineOpaque-payload combine callback (see PayloadCombine).
[in]a_cellBudgetPer-cell budget, for the dynamic per-cell recheck (same budget used everywhere else this round).
[in]a_probLoPhysical position of the domain's low corner (see cellKeyOf()); needed for the dynamic crowding recheck and a_maxCellDistance.
[in]a_dxByLevelCell spacing PER AMR LEVEL (index 0 = level 0, etc.) – see cellKeyOf()'s warning. Each participant's OWN cell key is computed with a_dxByLevel[participant.level], never a single shared dx: a candidate can legitimately be a ghost from a coarser or finer level than the query's own patch, and getting this wrong silently breaks the dynamic crowding recheck for every level but one.
[in]a_isPositionValidPosition-validity predicate (see PositionValid), called once per otherwise-eligible pair with the weighted-centroid position already computed. Treated exactly like a_maxCellDistance's "too far" case on failure: no proposal for the original candidate, a fallback retry if available, otherwise left unmatched with no side effects.
[in]a_allocateIDFresh-id allocator (see IDAllocator), called once per committed trivial-tier merge.
[in]a_maxFallbackCandidatesDefault 0 (disabled). When a query particle's chosen candidate is blocked (already consumed, or has its own outgoing commitment, or exposed/a ghost) and the query particle itself is NOT exposed, try the edge's NNMergeEdge::fallbackCandidates in order (pre-fetched by findNearestNeighborCandidates() via one K-nearest query, K = 1 + a_maxFallbackCandidates), up to this many extra attempts, before giving up. No fresh query and no already-tried bookkeeping – the list is ascending-distance with no duplicates, so trying the next is advancing an index. Retries resolve immediately at the point of failure rather than being re-sorted into the global order (a retry only fires for an edge whose first choice already failed). A query particle that exhausts every fallback still proposes with its true, original nearest neighbor – fallbacks affect only local trivial-tier eligibility, never what is proposed cross-patch.
[in]a_maxCellDistanceUser-selectable physical merge-eligibility cap, in whole grid cells, using Chebyshev (max-per-axis) distance between the same unclamped, position-derived cell key used for the crowding trigger (floor(pos/dx), see findNearestNeighborCandidates()) – same cell = 0, any Moore-adjacent cell (incl. diagonals) = 1, and so on. The position-derived key (not each patch's local IntVect) is what makes the comparison meaningful across a patch boundary. std::nullopt (default) disables it. A query whose nearest neighbor exceeds the cap is NOT proposed to – this is a physical-validity rule, not a coordination one: the pair is exactly as invalid via judgeProposals() as it would be trivially. If a_maxFallbackCandidates is nonzero the query gets a fallback retry for a closer candidate; otherwise it is left unmatched with no side effects. The cap is inclusive.
[in,out]a_crossLevelMergeCountOptional diagnostic counter (nullptr, the default, disables it entirely – zero cost when not needed): incremented once per committed merge whose two participants were on DIFFERENT AMR levels (query.level != cand.level). NOT reset by this function – the caller owns its lifetime, so counts can be accumulated across a_iterateLocalTierToConvergence's internal iterations, or across this rank's judgeProposals() acceptances too (see that function's own parameter).
[in]a_onMergeCommittedOptional per-merge diagnostic callback (see MergeCommittedCallback); default is a no-op.