|
chombo-discharge
|
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. | |
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::.
| 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()).
| using ParticleManagement::detail::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).
Empty (no entries) iff no cell in the patch could possibly be crowded – the same per-cell pre-filter as buildNNSpatialIndex(); see buildNNCellSpatialIndex().
| using ParticleManagement::detail::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).
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).
| 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.
| [in] | a_position | Physical position to locate. |
valid is false off-domain.
|
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.
| [out] | a_consumedIDs | Ids of every source particle whose proposal was accepted – the caller removes these from its own valid particle lists. |
| [in] | a_incomingVerdicts | All verdicts addressed to this rank, pooled from every judge rank (including this rank's own in-process verdict for proposals it judged for itself). |
|
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.
| [in] | a_particles | Input particles (copied into internal scratch; not modified). |
| [in] | a_maxLeaves | Maximum number of leaf nodes (the per-cell target particle count). |
| [in] | a_weightMedianLength | Node 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_capWeights | If 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_splitPosition | Where 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_particleReconcile | Reconciliation callback applied to the two daughters when the median is split. |
| [out] | a_leaves | Filled with one {begin,end} pointer pair per leaf. |
|
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.
| Packed | See MergeParticle. |
| [in,out] | a_particles | Particles to partition; reordered in place. |
| [in,out] | a_used | Live 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_leaves | Every resulting leaf, in no particular order. |
| [in] | a_ppc | Target particles per cell, enforced here as a per-cell ceiling on leaf count. |
| [in] | a_weightMedianCellWidths | Leaf 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_dx | This patch's own cell spacing. |
| [in] | a_probLo | Physical position of the domain's low corner, for computing cell indices. |
| [in] | a_cellCounts | Per-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. |
|
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.
| Packed | See MergeParticle. |
| [out] | a_index | The resulting one-cell spatial index. |
| [in] | a_localValid | This patch's own full valid-particle set. |
| [in] | a_ghosts | Every ghost shipped to this patch this round. |
| [in] | a_probLo | Physical position of the domain's low corner. |
| [in] | a_dx | Cell spacing of THIS PATCH's own level. |
| [in] | a_cellBudget | The physics-facing per-cell budget used elsewhere this round; used ONLY for the per-cell pre-filter above. |
|
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.
| Packed | See MergeParticle. |
| Cloud | See 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. |
| [out] | a_index | The resulting spatial index. |
| [in] | a_localValid | This patch's own full valid-particle set. |
| [in] | a_ghosts | Every ghost shipped to this patch this round. |
| [in] | a_probLo | Physical position of the domain's low corner. |
| [in] | a_dx | Cell spacing of THIS PATCH's own level. |
| [in] | a_cellBudget | The 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_kNearest | k = 1 + a_maxFallbackCandidates – the neighbor count to precompute per point into NNSpatialIndex::pointCloudGraph. |
|
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.
| [in] | a_position | Physical position. |
| [in] | a_probLo | Physical position of the domain's low corner. |
| [in] | a_dx | Cell spacing (per direction) of the position's OWN level. |
|
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.
| Packed | See MergeParticle. |
| Cloud | See NNSpatialIndex. |
| [out] | a_edges | One entry per over-threshold, currently-alive query particle that has at least one candidate (empty if none found). |
| [in] | a_localValid | This 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_ghosts | Every ghost shipped to this patch this round (candidates only; ghosts never initiate a query) – also not pre-filtered. |
| [in] | a_consumedIDs | Lazy-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_spatialIndex | This 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_liveCellCount | Live particle count (valid + ghost) per level-qualified cell key (see NNCellKey), already reflecting this round's frozen ghost-fill snapshot. |
| [in] | a_probLo | Physical position of the domain's low corner (see cellKeyOf()). |
| [in] | a_dx | Cell 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_cellBudget | Per-cell budget – a cell is eligible while it holds strictly more than this many particles. |
| [in] | a_maxFallbackCandidates | Forwarded from resolveTrivialTier() (see its docs); 0 (default) means an ordinary single-nearest query and every edge's fallbackCandidates stays empty. |
| [in] | a_maxCellDistance | Same 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. |
|
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().
| Packed | See MergeParticle. |
| [out] | a_edges | One entry per over-threshold, currently-alive query particle that has at least one candidate. |
| [in] | a_localValid | This patch's own FULL valid-particle set for this round (query sources). |
| [in] | a_consumedIDs | Lazy-deletion skip set: ids already consumed earlier this round. |
| [in] | a_cellIndex | This 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_liveCellCount | Live particle count (valid + ghost) per level-qualified cell key (see NNCellKey). |
| [in] | a_probLo | Physical position of the domain's low corner (see cellKeyOf()). |
| [in] | a_dx | Cell spacing of THIS PATCH's own level (see cellKeyOf()'s warning). |
| [in] | a_dxByLevel | Cell spacing per AMR level (see resolveTrivialTier()'s own docs) – needed for the exact cross-level re-check described above. |
| [in] | a_cellBudget | Per-cell budget – a cell is eligible while it holds strictly more than this many particles. |
| [in] | a_maxFallbackCandidates | Same meaning as findNearestNeighborCandidates()'s own parameter; 0 (default) means an ordinary single-nearest query and every edge's fallbackCandidates stays empty. |
|
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.
| P | SoA payload type. |
| Packed | Opaque reconciliation payload type. |
| Traits | Column descriptor for P. |
| Combine | See PayloadCombine. |
| Scatter | Callable (ParticleSoA<P,Traits>&, const MergeParticle<Packed>&) -> void. |
| PosValid | See PositionValid. |
| Allocator | See IDAllocator. |
| OnMerge | See MergeCommittedCallback. |
| [in,out] | a_particles | The real particle container being merged. |
| [in,out] | a_particlesByID | Every currently-alive local-valid particle and every ghost, pooled rank-wide by id. |
| [in,out] | a_consumedIDs | Ids already consumed this round; updated in place as judge-side merges commit. |
| [in,out] | a_liveCellCount | Live per-cell counts; decremented in place as judge-side merges commit. |
| [in,out] | a_allResults | Every merge result committed this round (trivial-tier results already inside on entry); judge-side results are appended. |
| [in,out] | a_crossLevelMergeCount | Optional diagnostic counter (see MergeCommittedCallback's sibling docs). |
| [in] | a_amr | AMR mesh – source of the LevelTiles used to place merged particles. |
| [in] | a_realm | Realm name. |
| [in] | a_cellBudget | The count each cell is drained down to – see NNCellBudget. |
| [in] | a_combine | Opaque-payload combine callback. |
| [in] | a_scatter | Per-surviving-particle scatter callback. |
| [in] | a_allocateID | Fresh-id allocator. |
| [in] | a_maxCellDistance | Physical 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_isPositionValid | Position-validity predicate. |
| [in] | a_probLo | Physical position of the domain's low corner. |
| [in] | a_dxByLevel | Cell spacing per AMR level. |
| [in] | a_patchWork | One entry per patch this rank owns (see NNPatchWork), from gatherMergeParticles(). |
| [in] | a_pooledEdges | Every 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_hasOutgoingCommitment | Query ids the local tier could not resolve trivially. |
| [in] | a_onMergeCommitted | Optional per-merge diagnostic callback. |
|
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.
| P | SoA payload type (see mergeNearestNeighborsTree()). |
| Packed | Opaque reconciliation payload type (see MergeParticle). |
| Traits | Column descriptor for P. |
| Gather | Callable (const ParticleSoA<P,Traits>&, std::size_t) -> Packed. |
| [in,out] | a_particles | The real particle container being merged. |
| [out] | a_patchWork | One entry per patch this rank owns. |
| [out] | a_patchLocalValid | This patch's own local-valid particles, parallel to a_patchWork. |
| [out] | a_patchGhosts | Every ghost shipped to this patch, parallel to a_patchWork. |
| [out] | a_particlesByID | Every currently-alive local-valid particle and every ghost, pooled rank-wide by id. |
| [out] | a_liveCellCount | Live particle count (valid + ghost) per level-qualified cell key, derived from a_particlesByID. |
| [in] | a_amr | AMR mesh – source of ghost masks and the patch layout. |
| [in] | a_realm | Realm name (a_particles.getRealm()). |
| [in] | a_finestLevel | Finest AMR level (a_amr.getFinestLevel()). |
| [in] | a_probLo | Physical position of the domain's low corner. |
| [in] | a_dxByLevel | Cell spacing per AMR level. |
| [in] | a_ghostWidth | Particle ghost halo width already filled by the caller (see mergeNearestNeighborsTree()'s own a_ghostWidth docs). |
| [in] | a_gather | Per-slot gather callback. |
|
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.
| Packed | See MergeParticle. |
| [out] | a_proposalsByDestRank | One bucket per rank; a_proposalsByDestRank[r] holds every proposal whose candidate is owned by rank r (including r == this rank's own). |
| [in] | a_edges | Candidate edges from findNearestNeighborCandidates(), for all of this rank's patches. |
| [in] | a_hasOutgoingCommitment | Query-particle ids that resolveTrivialTier() could not resolve (i.e. exactly the edges this function packages). |
| [in] | a_particlesByID | Full 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_numRanks | Total MPI rank count (size of the returned bucket vector). |
|
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:
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()).
| Packed | See MergeParticle. |
| Combine | See PayloadCombine. |
| PosValid | See PositionValid. |
| [in,out] | a_liveCellCount | Live 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_results | One entry per target actually accepted, in the order processed. |
| [out] | a_verdictsByDestRank | One 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_incomingProposals | All proposals targeting a particle this rank owns, pooled from every source rank (including this rank's own in-process bucket). |
| [in] | a_particlesByID | Full 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_consumedIDs | Ids 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_hasOutgoingCommitment | Ids (among a_particlesByID, not in a_consumedIDs) that have their own outgoing commitment this round (needed for rule 3 above). |
| [in] | a_outgoingTargetOf | For 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_combine | Opaque-payload combine callback (see PayloadCombine). |
| [in] | a_cellBudget | Per-cell budget (the same budget used everywhere else this round). |
| [in] | a_probLo | Physical position of the domain's low corner (see cellKeyOf()). |
| [in] | a_dxByLevel | Cell 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_isPositionValid | Position-validity predicate (see PositionValid and rule 6 above). |
| [in] | a_allocateID | Fresh-id allocator (see IDAllocator), called once per accepted target. |
| [in] | a_maxCellDistance | Same physical merge-eligibility cap as resolveTrivialTier()'s (see rule 6 above); std::nullopt (default) disables it. |
| [in,out] | a_crossLevelMergeCount | Optional diagnostic counter – see resolveTrivialTier()'s docs; incremented once per accepted target whose target/source were on different AMR levels. |
| [in] | a_onMergeCommitted | Optional per-merge diagnostic callback – see resolveTrivialTier()'s docs; called with (target, source, merged) for every accepted target. |
|
inlinenoexcept |
Axis-aligned bounding box of particles[a_lo, a_hi).
| [out] | a_boxLo | Low corner. |
| [out] | a_boxHi | High corner. |
| [in] | a_particles | Particle buffer. |
| [in] | a_lo | Start of the range (inclusive). |
| [in] | a_hi | End of the range (exclusive). |
|
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.
| [out] | a_boxLo | Low corner (inclusive). |
| [out] | a_boxHi | High corner (exclusive). |
| [in] | a_box | Box whose bounds are wanted. |
| [in] | a_dx | Grid spacing at the box's level. |
| [in] | a_probLo | Lower-left corner of the physical domain. |
|
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.
| Packed | See MergeParticle. |
| [in,out] | a_particles | Gathered particles for this patch; grown in place by the split pieces. |
| [in] | a_cellCounts | Per-cell true particle counts (see kdFillCellHistogram()). |
| [in] | a_cellWeights | Per-cell total weight, over the same box as a_cellCounts. |
| [in] | a_ppc | Target particles per cell. |
| [in] | a_splitPlacement | Where each piece goes – see ParticleManagement::KDSplitPlacement. |
| [in] | a_probLo | Physical position of the domain's low corner. |
| [in] | a_dx | This patch's own cell spacing. |
| [in] | a_isPositionValid | Predicate rejecting positions inside the embedded boundary. |
|
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.
| [in] | a_position | Physical position. |
| [in] | a_probLo | Physical position of the domain's low corner. |
| [in] | a_dx | Cell spacing. |
|
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.
| [in] | a_centroid | Computed weighted centroid. |
| [in] | a_totalWeight | Sum of weights used to compute a_centroid. |
| [in] | a_boxLo | Low corner of the bounding box every contributing position lies within. |
| [in] | a_boxHi | High corner of the bounding box every contributing position lies within. |
|
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.
| T | Trivially-copyable record type (KDClaim, KDVerdict, KDCommit, or MergeParticle<Packed> with Packed itself trivially copyable). |
| [in] | a_sendByRank | One bucket per destination rank (size == number of ranks). |
|
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.
| Packed | See MergeParticle. |
| [out] | a_counts | Per-cell counts, zeroed here before tallying. |
| [in] | a_particles | Gathered particles for this patch. |
| [in] | a_probLo | Physical position of the domain's low corner. |
| [in] | a_dx | This patch's own cell spacing. |
|
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.
| [in] | a_lhs | Left-hand cell index. |
| [in] | a_rhs | Right-hand cell index. |
|
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.
| [in] | a_boxLo | Low corner. |
| [in] | a_boxHi | High corner. |
| [in] | a_dx | Cell spacing. |
|
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.
| Packed | See MergeParticle. |
| [in] | a_placement | Which placement to apply. |
| [in] | a_centroid | The leaf's weighted centroid, already computed by the caller. |
| [in] | a_totalWeight | The leaf's total weight, i.e. the sum of a_weights. |
| [in] | a_boxLo | Low corner of the leaf's bounding box. |
| [in] | a_boxHi | High corner of the leaf's bounding box. |
| [in] | a_weights | The members' weights, parallel to a_positions. |
| [in] | a_positions | The 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. |
|
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.
| [in,out] | a_particles | Particle buffer; reordered in [a_lo,a_hi). |
| [in] | a_lo | Start of the range (inclusive). |
| [in] | a_hi | End of the range (exclusive); a_hi - a_lo must be >= 2. |
| [in] | a_axis | Split 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. |
|
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.
| [in] | a_placement | Which rule to apply. Center returns the parent's position unchanged. |
| [in] | a_parent | The parent particle's position. |
| [in] | a_cellLo | Low corner of the cell the parent lives in. |
| [in] | a_dx | Cell spacing, per direction. |
| [in] | a_spacing | Jitter bandwidth – the local mean interparticle spacing. |
|
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.
| [in,out] | a_particles | Particle buffer; reordered in [a_lo,a_hi). |
| [in] | a_lo | Start of the range (inclusive). |
| [in] | a_hi | End of the range (exclusive); a_hi - a_lo must be >= 2. |
| [in] | a_axis | Split 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. |
|
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.
| Cloud | EBGeometry point-cloud index type (see NNSpatialIndex). |
| P,Packed,Traits,Gather,Combine,Scatter,Allocator,PosValid,OnMerge | See mergeNearestNeighborsTree(). |
| 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_onMergeCommitted | See mergeNearestNeighborsTree(). |
|
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).
| Packed | See MergeParticle. |
| [in] | a_localValid | This patch's own full valid-particle set. |
| [in] | a_ghosts | Every ghost shipped to this patch this round. |
| [in] | a_probLo | Physical position of the domain's low corner. |
| [in] | a_dx | Cell spacing of THIS PATCH's own level. |
| [in] | a_cellBudget | The count each cell is drained down to – see NNCellBudget. |
|
inlinenoexcept |
Chebyshev (max-per-axis) distance between two cell-index vectors – see CD_NearestNeighborParticleMerge.H's a_maxCellDistance docs.
| [in] | a_a | First cell index. |
| [in] | a_b | Second cell index. |
|
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.
| [in] | a_posA | First participant's position. |
| [in] | a_levelA | First participant's AMR level. |
| [in] | a_posB | Second participant's position. |
| [in] | a_levelB | Second participant's AMR level. |
| [in] | a_probLo | Physical position of the domain's low corner. |
| [in] | a_dxByLevel | Cell spacing per AMR level. |
| [in] | a_maxCellDistance | The cap (see CD_NearestNeighborParticleMerge.H's a_maxCellDistance docs). |
|
inlinenoexcept |
Squared Euclidean distance between two physical positions.
| [in] | a_a | First position. |
| [in] | a_b | Second position. |
|
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.
| T | Trivially-copyable record type (NNMergeProposal<Packed>, NNMergeVerdict, or MergeParticle<Packed> – all satisfy this given Packed itself is required to). |
| [in] | a_sendByRank | One bucket per destination rank (size == number of ranks). |
|
inlinenoexcept |
Squared distance from a physical point to a cell's axis-aligned bounding box (0 if the point is inside).
| [in] | a_point | Physical position. |
| [in] | a_cell | Cell index. |
| [in] | a_probLo | Physical position of the domain's low corner. |
| [in] | a_dx | Cell spacing. |
|
inlinenoexcept |
Weighted-centroid merge of two positions/weights – shared by resolveTrivialTier() and judgeProposals() so the formula is written exactly once.
| [out] | a_mergedPos | Weighted-centroid position. |
| [out] | a_mergedWeight | Summed weight. |
| [in] | a_posA | First particle's position. |
| [in] | a_weightA | First particle's weight. |
| [in] | a_posB | Second particle's position. |
| [in] | a_weightB | Second particle's weight. |
|
inline |
Partition particles so that all MPI rank draw a cumulative number of particles equal to a_numParticles.
| [in] | a_numParticles | Total number of particles to be drawn. |
|
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.
| Packed | See MergeParticle. |
| [out] | a_localByPatch | Results whose merged particle lands in one of this rank's own patches, bucketed by (level, LevelTiles::LevelAndBox::gridIndex). |
| [out] | a_scatterByDestRank | Results 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_results | Every merge result produced this round by resolveTrivialTier() and judgeProposals(), pooled together. |
| [in] | a_locate | Locate-by-position callback (see PositionLocator). |
| [in] | a_thisRank | This rank's own number – a located box whose rank equals this is what makes a result "local" rather than needing a scatter. |
|
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:
| Packed | See MergeParticle. |
| Combine | See PayloadCombine. |
| [in,out] | a_liveCellCount | Live 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_consumedIDs | Ids 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_hasOutgoingCommitment | Set of query-particle ids that were NOT resolved trivially (excluding the stale-candidate case, see above) and must go on to generateProposals(). |
| [out] | a_results | One entry per trivial-tier merge actually committed, in the order they were processed. |
| [in] | a_edges | Candidate 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_particlesByID | Full 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_combine | Opaque-payload combine callback (see PayloadCombine). |
| [in] | a_cellBudget | Per-cell budget, for the dynamic per-cell recheck (same budget used everywhere else this round). |
| [in] | a_probLo | Physical position of the domain's low corner (see cellKeyOf()); needed for the dynamic crowding recheck and a_maxCellDistance. |
| [in] | a_dxByLevel | Cell 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_isPositionValid | Position-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_allocateID | Fresh-id allocator (see IDAllocator), called once per committed trivial-tier merge. |
| [in] | a_maxFallbackCandidates | Default 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_maxCellDistance | User-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_crossLevelMergeCount | Optional 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_onMergeCommitted | Optional per-merge diagnostic callback (see MergeCommittedCallback); default is a no-op. |