kups.core.neighborlist
¶
Neighbor list construction and edge representations for molecular systems.
This module provides multiple neighbor list algorithms for finding interacting pairs of particles within cutoff distances, with different performance and accuracy trade-offs.
Core Components¶
- Edges: Represents connections between particles with periodic shifts
- NearestNeighborList: Protocol for neighbor search implementations
- Pipeline: Selector → mask sequence → compactor
Neighbor List Implementations¶
Primary Implementations¶
-
CellListNeighborList (Recommended when cutoff << box size)
- O(N) complexity using spatial hashing
- Best when cutoff / box_size < 0.3 (cutoff much smaller than box)
- Honors the cell's per-axis
periodicmask (bulk and bounded non-periodic)
-
- O(N²/K) complexity (K = number of systems)
- Best when cutoff / box_size ~ 1 (cutoff comparable to box)
-
- O(N²) complexity across all systems
- Only for single-system simulations or testing
- Crosses system boundaries (use with caution!)
Refinement Implementations¶
These let one expensive base neighbor list be shared across multiple potentials.
- RefineMaskNeighborList: apply different inclusion/exclusion masks to precomputed edges.
- RefineCutoffNeighborList: refine precomputed edges with new cutoff distances.
Pipeline Primitives¶
Every neighbor list above is a Pipeline
of a CandidateSelector, a
tuple of Mask criteria, and a
Compactor. Users wanting custom
behavior can compose their own pipeline directly.
AllDenseNearestNeighborList
¶
Dense O(N²) neighbor list considering all pairs across all systems.
This implementation generates all possible particle pairs without spatial optimization. It is only suitable for very small systems or testing.
Warning: This crosses system boundaries! Only use for single-system simulations. For multiple systems, use DenseNearestNeighborList instead.
Complexity: O(N²) where N is the total number of particles across all systems.
Attributes:
| Name | Type | Description |
|---|---|---|
avg_edges |
Capacity[int]
|
Capacity manager for edge array. |
avg_image_candidates |
Capacity[int]
|
Capacity manager for image candidate pairs. |
Example
Source code in src/kups/core/neighborlist/all_dense.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
AllDenseSelector
¶
Selector that emits every (i, j) pair across all systems.
Source code in src/kups/core/neighborlist/all_dense.py
CandidateBatch
¶
Bases: NamedTuple
Candidate set of degree D carried through the pipeline.
Reuses Edges[D] for the
(indices, shifts) layout (indices shape (n, D),
shifts shape (n, D-1, 3)); adds the
is_minimum_image flag that
ExclusionMask needs to
keep non-minimum periodic copies of excluded pairs.
Auto-registered as a JAX PyTree because it is a NamedTuple.
Attributes:
| Name | Type | Description |
|---|---|---|
edges |
Edges[D]
|
Candidate edges (indices + fractional shifts). |
is_minimum_image |
Array
|
|
Source code in src/kups/core/neighborlist/types.py
CandidateSelector
¶
Bases: Protocol
Produces a CandidateBatch[D] from the pipeline context.
Owns all candidate-set construction, including any PBC image
replication required when max(cutoff/perp_axis) > 0.5.
Source code in src/kups/core/neighborlist/types.py
CellListNeighborList
¶
Efficient O(N) neighbor list using spatial hashing with cell lists.
This is the recommended implementation when the cutoff is much smaller than the box size. It divides space into a grid of cells and only checks pairs in neighboring cells, achieving linear scaling with system size.
Honors the cell's per-axis periodic mask: stencil offsets that cross a
non-periodic face are routed to an out-of-bounds bin (no key matches), and
minimum-image shifts are zero on non-periodic axes. The fully-periodic path
is byte-identical to the original (gated at trace time on all(periodic))
so PBC kernels see no overhead.
Complexity: O(N) for well-distributed particles where cutoff << box size. Efficiency improves as cutoff/box ratio decreases.
Attributes:
| Name | Type | Description |
|---|---|---|
avg_candidates |
Capacity[int]
|
Capacity for candidate pair storage (from cell list). |
avg_edges |
Capacity[int]
|
Capacity for final edge array. |
cells |
Capacity[int]
|
Capacity for cell hash table (grows with box_size³/cutoff³). |
avg_image_candidates |
Capacity[int]
|
Capacity for image candidate pairs. |
Algorithm
- Partition space into grid cells of size ~cutoff
- Hash each particle to its cell
- For each particle, check only neighboring 27 cells (3D)
- Filter candidates by actual distance
When to use
- When cutoff/box_size << 1 (cutoff much smaller than box)
- Typically cutoff/box < 0.3 for good efficiency
- On non-periodic axes positions must lie inside
[0, L)in real coordinates (the caller's invariant; out-of-range positions are silently routed to the OOB bin)
Example
Source code in src/kups/core/neighborlist/cell_list.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 | |
CellListSelector
¶
Selector for the cell-list algorithm.
Calls the raw spatial-hash candidate emission, then replicates per image
multiplicity when max(cutoff/perp) > 0.5.
Source code in src/kups/core/neighborlist/cell_list.py
Compactor
¶
Bases: Protocol
Produces final Edges[D] from the accumulated keep mask.
Source code in src/kups/core/neighborlist/types.py
DenseNearestNeighborList
¶
Dense O(N²) neighbor list respecting system boundaries.
This implementation generates all particle pairs within each system separately, avoiding cross-system interactions. Efficient when the cutoff is comparable to the box size (cutoff/box ~ 1).
Complexity: O(N² / K²) where N is total particles and K is number of systems.
Attributes:
| Name | Type | Description |
|---|---|---|
avg_candidates |
Capacity[int]
|
Capacity for candidate pair storage. |
avg_edges |
Capacity[int]
|
Capacity for final edge array. |
avg_image_candidates |
Capacity[int]
|
Capacity for image candidate pairs. |
When to use
- When cutoff/box_size ~ 1 (cutoff comparable to box dimensions)
- Small box relative to cutoff (few cells would fit)
- Non-periodic systems
Example
Source code in src/kups/core/neighborlist/dense.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | |
DenseSelector
¶
Selector for the per-system dense O(N²/K²) algorithm.
Source code in src/kups/core/neighborlist/dense.py
DistanceCutoffMask
¶
Drops candidates whose squared real-space distance exceeds cutoff².
Source code in src/kups/core/neighborlist/masks.py
Edges
¶
Bases: Sliceable
Represents edges (connections) between particles in a molecular system.
An edge connects Degree particles, where degree=2 represents pairwise
interactions (bonds), degree=3 represents three-body interactions (angles), etc.
For periodic systems, edges include shift vectors that indicate how many cells to traverse when computing distances between connected particles.
Class Type Parameters:
| Name | Bound or Constraints | Description | Default |
|---|---|---|---|
Degree
|
int
|
Number of particles connected by each edge (static type check) |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
indices |
Index[ParticleId]
|
Particle indices for each edge, shape |
shifts |
Array
|
Periodic shift vectors, shape |
Example
Source code in src/kups/core/neighborlist/edges.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | |
absolute_shifts(particles, systems)
¶
Compute absolute shift vectors for all particles in each edge.
Converts relative shifts to absolute Cartesian shift vectors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
particles
|
Table[ParticleId, HasPositionsAndSystemIndex]
|
Particle data with system index information. |
required |
systems
|
Table[SystemId, HasCell]
|
System data with cell for periodic boundary conditions. |
required |
Returns:
| Type | Description |
|---|---|
Array
|
Array of shape |
Source code in src/kups/core/neighborlist/edges.py
difference_vectors(particles, systems)
¶
Compute difference vectors between connected particles.
For each edge, computes the vector from the first particle to each subsequent particle, accounting for periodic boundary conditions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
particles
|
Table[ParticleId, HasPositionsAndSystemIndex]
|
Particle positions with system index information. |
required |
systems
|
Table[SystemId, HasCell]
|
System data with cell for periodic boundary conditions. |
required |
Returns:
| Type | Description |
|---|---|
Array
|
Array of shape |
Source code in src/kups/core/neighborlist/edges.py
ExclusionMask
¶
Drops minimum-image pairs that share an exclusion segment.
Non-minimum-image periodic copies of excluded pairs survive (allowed when
batch.is_minimum_image is False for that copy).
Source code in src/kups/core/neighborlist/masks.py
InBoundsMask
¶
Drops candidates whose lh/rh indices fall outside the valid inclusion-segment range.
Implements the per-side inclusion.indices < num_labels check used to
guard scatter/gather lookups when the candidate buffer is padded.
Source code in src/kups/core/neighborlist/masks.py
InclusionGroupSelector
¶
Pairs every particle with every other in the same inclusion segment.
Ignores the cutoff entirely. Shifts are int-typed minimum-image
fractional rounds — matches today's all_connected_neighborlist
(which is Ewald-only and assumed fully periodic).
Source code in src/kups/core/neighborlist/all_connected.py
InclusionMatchMask
¶
Drops candidates whose lh/rh inclusion segments differ.
Source code in src/kups/core/neighborlist/masks.py
IsAllDenseNeighborListParams
¶
Bases: Protocol
Protocol for parameters required by AllDenseNearestNeighborList.
Source code in src/kups/core/neighborlist/all_dense.py
IsCellListParams
¶
Bases: Protocol
Protocol for parameters required by CellListNeighborList.
Source code in src/kups/core/neighborlist/cell_list.py
IsDenseNeighborlistParams
¶
Bases: Protocol
Protocol for parameters required by DenseNearestNeighborList.
Source code in src/kups/core/neighborlist/dense.py
IsNeighborListState
¶
Bases: Protocol
Protocol for states that expose neighbor list parameters.
A state satisfying this protocol can be passed to from_state() on any
neighbor list class. The type parameter P determines which neighbor
list types the state can construct (e.g., IsAllDenseNeighborListParams,
IsDenseNeighborlistParams, IsCellListParams, or
IsUniversalNeighborlistParams).
Source code in src/kups/core/neighborlist/types.py
IsUniversalNeighborlistParams
¶
Bases: Protocol
Protocol for parameters required by any neighbor list implementation.
A superset of IsAllDenseNeighborListParams, IsDenseNeighborlistParams,
and IsCellListParams. Satisfying this protocol allows constructing any
of the three neighbor list types.
Source code in src/kups/core/neighborlist/types.py
Mask
¶
Bases: Protocol
Returns this criterion's bool array; pipeline conjuncts the results.
Degree-agnostic at the type level — the pair-only masks shipped here
annotate batch: CandidateBatch (any D) and internally assume
D == 2 via batch.lh_idx / batch.rh_idx. Higher-degree masks
would not use those properties.
Cannot change batch.edges, batch.is_minimum_image, or the
candidate count. Pure (batch, ctx) -> Array.
Source code in src/kups/core/neighborlist/types.py
MaskOnlyCompactor
¶
In-place compaction: failing entries become OOB indices and zero shifts.
No size change; preserves the candidate count from the selector. Applies
the shared rh→lh remap so the output indices live in lh-space — matching
ReduceCompactor's contract.
Source code in src/kups/core/neighborlist/compact.py
NearestNeighborList
¶
Bases: Protocol
Protocol for neighbor list construction algorithms.
Implementations find pairs of particles within a cutoff distance, handling periodic boundary conditions and inclusion/exclusion masks.
Source code in src/kups/core/neighborlist/types.py
__call__(lh, rh, systems, cutoffs, rh_index_remap=None)
¶
Find all particle pairs within the cutoff distance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lh
|
Table[ParticleId, P]
|
Left-hand particles to find neighbors for |
required |
rh
|
Table[ParticleId, P] | None
|
Right-hand particles to search within (or None for self-neighbors) |
required |
systems
|
Table[SystemId, NeighborListSystems]
|
Indexed system data with cell information |
required |
cutoffs
|
Table[SystemId, Array]
|
Indexed cutoff data per system |
required |
rh_index_remap
|
Index[ParticleId] | None
|
Optional index mapping rh particles back to lh
particle IDs for self-interaction exclusion. When |
None
|
Returns:
| Type | Description |
|---|---|
Edges[Literal[2]]
|
Edges connecting particle pairs within cutoff |
Source code in src/kups/core/neighborlist/types.py
Pipeline
¶
Selector → mask sequence → compactor.
Attributes:
| Name | Type | Description |
|---|---|---|
selector |
CandidateSelector[D]
|
Produces a |
masks |
tuple[Mask, ...]
|
Tuple of mask criteria over |
compactor |
Compactor[D]
|
Produces the final |
Source code in src/kups/core/neighborlist/pipeline.py
PipelineContext
¶
Read-only inputs shared by every mask and the compactor.
Positions in lh and rh are in fractional coordinates
(transformed by [_prepare][kups.core.neighborlist.pipeline._prepare]).
There is no out_of_bounds field — masks/compactors that need an
OOB sentinel compute max(ctx.lh.size, ctx.rh.size) locally.
Attributes:
| Name | Type | Description |
|---|---|---|
lh |
Table[ParticleId, NeighborListPoints]
|
Left-hand particle table in fractional coords. |
rh |
Table[ParticleId, NeighborListPoints]
|
Right-hand particle table in fractional coords (== |
systems |
Table[SystemId, NeighborListSystems]
|
Indexed system data with cell information. |
rh_index_remap |
Array | None
|
Raw remap array mapping rh-positions to lh-space
particle IDs, or |
Source code in src/kups/core/neighborlist/types.py
PrecomputedEdgesSelector
¶
Selector that wraps precomputed Edges for both refine variants.
Precomputed edges use the same index convention as the call that produced
them: public lh-space edges when an rh remap is supplied, and raw
rh-space indices for a disjoint rh without a remap. Remapped rh
rows are overlaid onto lh before this selector runs.
Attributes:
| Name | Type | Description |
|---|---|---|
candidates |
Edges[Literal[2]]
|
Precomputed edges (indices in lh-space). |
recompute_mic_shifts |
bool
|
When |
Source code in src/kups/core/neighborlist/refine.py
ReduceCompactor
¶
Compacts surviving candidates to a size-bounded Edges[2].
Applies the shared rh→lh remap, then — when ctx.rh_index_remap is
set — mirrors each surviving edge with its reverse (concatenating shifts
with their negatives). The mirror restores the symmetry that the paired
RemapDedupMask removed upstream.
Source code in src/kups/core/neighborlist/compact.py
RefineCutoffNeighborList
¶
Refine precomputed edges by re-checking distances with new cutoffs.
This neighbor list takes an existing set of candidate edges and filters them by computing actual distances and comparing to cutoffs. Enables sharing a single conservative neighbor list across multiple potentials with different cutoff distances.
Key benefit: Compute expensive neighbor list once with maximum cutoff, then refine for each potential with its specific cutoff (e.g., Lennard-Jones at 10 Å, Coulomb at 15 Å).
Attributes:
| Name | Type | Description |
|---|---|---|
candidates |
Edges[Literal[2]]
|
Precomputed edges to refine (should be conservative/over-inclusive). |
avg_edges |
Capacity[int]
|
Capacity for output edge array. |
Use cases
- Multiple potentials sharing one neighbor list with different cutoffs
- Multi-stage neighbor list construction (coarse then fine)
- Adaptive cutoffs that change during simulation
- Using a static "super" neighbor list with varying actual cutoffs
Example
# Compute base neighbor list once with maximum cutoff
max_cutoff = 15.0 # Maximum of all potential cutoffs
base_edges = base_nl(particles, None, cells, max_cutoff, None)
# Share across potentials with different cutoffs
lj_nl = RefineCutoffNeighborList(candidates=base_edges, avg_edges=cap1)
lj_edges = lj_nl(particles, None, cells, cutoff=10.0, None) # LJ cutoff
coulomb_nl = RefineCutoffNeighborList(candidates=base_edges, avg_edges=cap2)
coulomb_edges = coulomb_nl(particles, None, cells, cutoff=15.0, None) # Coulomb cutoff
Source code in src/kups/core/neighborlist/refine.py
RefineMaskNeighborList
¶
Refine a precomputed neighbor list by applying inclusion/exclusion masks.
This neighbor list takes an existing set of candidate edges and filters them based on segmentation masks, without recomputing distances. Enables sharing a single base neighbor list across multiple potentials with different interaction rules.
Key benefit: Compute expensive neighbor list once, apply different masks for different potentials (e.g., Lennard-Jones excludes 1-4 interactions, Coulomb has different exclusions).
Attributes:
| Name | Type | Description |
|---|---|---|
candidates |
Edges[Literal[2]]
|
Precomputed edges to refine |
Use cases
- Multiple potentials sharing one neighbor list with different exclusions
- Excluding bonded pairs (1-2, 1-3, 1-4) from non-bonded interactions
- Applying group-specific interaction rules
- Multi-scale simulations with different interaction levels
Example
# Compute base neighbor list once
base_edges = base_nl(particles, None, cells, cutoffs, None)
# Share across potentials with different masks
lj_nl = RefineMaskNeighborList(candidates=base_edges)
lj_edges = lj_nl(lj_particles, None, cells, cutoffs, None) # 1-4 exclusions
coulomb_nl = RefineMaskNeighborList(candidates=base_edges)
coulomb_edges = coulomb_nl(coulomb_particles, None, cells, cutoffs, None) # 1-2 exclusions only
Source code in src/kups/core/neighborlist/refine.py
RemapDedupMask
¶
Deduplicate the rh→lh remapped subset.
When ctx.rh_index_remap is set, rh is a subset of lh and each
rh-position maps to an lh-position via rh_index_remap. We then keep
only one direction per pair: edges where lh_idx is not in the
remap (i.e., the pair is lh-only) or where lh_idx >= remapped_rh.
Returns all-True when no remap is in effect.
Source code in src/kups/core/neighborlist/masks.py
UniversalNeighborlistParameters
¶
Concrete parameter dataclass satisfying IsUniversalNeighborlistParams.
Holds the capacity hints needed by every neighbor list implementation.
Use the estimate() classmethod to compute reasonable initial values
from system geometry rather than guessing manually.
Attributes:
| Name | Type | Description |
|---|---|---|
avg_edges |
int
|
Average number of edges per particle (for edge capacity). |
avg_candidates |
int
|
Average number of candidate pairs per particle. |
avg_image_candidates |
int
|
Average number of image candidate pairs per particle. |
cells |
int
|
Maximum number of spatial hash cells across all systems. |
Source code in src/kups/core/neighborlist/parameters.py
estimate(particles_per_system, systems, cutoffs, *, base=2, multiplier=1.0)
classmethod
¶
Estimate parameters for all neighbor list types from system geometry.
Computes conservative initial capacities based on particle density
and cutoff radii. The estimates are rounded up to the next power of
base to amortize future resizing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
particles_per_system
|
Table[SystemId, Array]
|
Number of particles per system. |
required |
systems
|
Table[SystemId, NeighborListSystems]
|
System data with cell information. |
required |
cutoffs
|
Table[SystemId, Array]
|
Cutoff distance per system. |
required |
base
|
float
|
Base for power-of rounding (default 2). |
2
|
multiplier
|
float
|
Safety factor applied to the estimate (default 1.0). |
1.0
|
Returns:
| Type | Description |
|---|---|
UniversalNeighborlistParameters
|
A |
Source code in src/kups/core/neighborlist/parameters.py
all_connected_neighborlist(lh, rh, systems, cutoffs, rh_index_remap=None)
¶
Neighbor list connecting all pairs sharing the same inclusion segment, ignoring distance.
Connects every particle pair that belongs to the same inclusion segment and has differing exclusion segment IDs. The cutoff is ignored for neighbor selection; the cell is used only to compute minimum-image shifts.
Requires max_count to be set on the inclusion Index.
Source code in src/kups/core/neighborlist/all_connected.py
neighborlist_changes(neighborlist, lh, rh, systems, cutoffs, compaction=0.5)
¶
Compute added/removed edges from a particle change in a single call.
Appends proposed positions to the particle array and queries both old
and new interactions at once, then splits the result by filtering
edge indices into removed (before) and added (after) sets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
neighborlist
|
NearestNeighborList
|
Neighbor list implementation. |
required |
lh
|
Table[ParticleId, NeighborListPoints]
|
Full original particle table. |
required |
rh
|
WithIndices[ParticleId, Table[ParticleId, NeighborListPoints]]
|
Proposed changes — |
required |
systems
|
Table[SystemId, NeighborListSystems]
|
Per-system data (cells, etc.). |
required |
cutoffs
|
Table[SystemId, Array]
|
Per-system cutoff distances. |
required |
compaction
|
float
|
Fraction of total edges allocated per output (0–1). 0.5 means each of added/removed gets half the buffer. 1.0 means no compaction — full buffer with masking only. |
0.5
|
Returns:
| Type | Description |
|---|---|
NeighborListChangesResult
|
|
Source code in src/kups/core/neighborlist/changes.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |