kups.core.neighborlist
¶
Neighbor lists, periodic edges, and composable search pipelines.
Dense and cell-list searches share masks and compaction. CellListCache
retains cell occupants for neighbor searches and incremental pair evaluation.
AdaptiveNeighborList
¶
Bases: NeighborList[Literal[2]]
Neighbor list that dispatches to the cheapest backing implementation.
Holds (implementation, cost) pairs and, on each call, picks the
implementation whose :class:NeighborListCost is smallest for that call's
counts. Augment by appending pairs to :attr:implementations; the seeded
implementations share the UniversalNeighborlistParameters capacities, so
growing one grows the shared state.
Attributes:
| Name | Type | Description |
|---|---|---|
implementations |
tuple[NeighborListCandidate, ...]
|
Candidate :class: |
Source code in src/kups/core/neighborlist/adaptive.py
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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 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 | |
from_state(state, cutoffs)
classmethod
¶
Seed from a state exposing neighborlist_params.
Source code in src/kups/core/neighborlist/adaptive.py
new(state, lens, cutoffs)
classmethod
¶
Seed the library implementations with their default cost guesses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
S
|
Object exposing |
required |
lens
|
Lens[S, IsUniversalNeighborlistParams]
|
Lens focusing the shared |
required |
cutoffs
|
Table[SystemId, Array]
|
Per-system cutoffs bound onto each implementation. |
required |
Returns:
| Type | Description |
|---|---|
AdaptiveNeighborList
|
An |
Source code in src/kups/core/neighborlist/adaptive.py
pair_candidates(keys, systems, *, inclusion, exclusion)
¶
Full neighbors with shared group masks and retained image flags.
Apply group masks shared by every pair term before compaction. Terms
with differing policies apply their remaining masks during evaluation.
Uses the same selectors and capacity repair as normal graph construction.
The selected implementation must satisfy SelectableNeighborList.
Source code in src/kups/core/neighborlist/adaptive.py
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. |
cutoffs |
Table[SystemId, Array]
|
Per-system cutoff distances used by this neighbor list. |
Example
Source code in src/kups/core/neighborlist/all_dense.py
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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | |
selector(query_size, systems)
¶
Build the candidate selector shared by graph and pair evaluation.
Source code in src/kups/core/neighborlist/all_dense.py
AllDenseSelector
¶
Selector that emits every (i, j) pair across all systems.
Source code in src/kups/core/neighborlist/all_dense.py
CandidateBatch
¶
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.
Attributes:
| Name | Type | Description |
|---|---|---|
edges |
Edges[D]
|
Candidate edges (indices + fractional shifts), keyed by
|
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
CellListCache
¶
Bases: NamedTuple
Slot-sorted particle rows with per-cell occupancy and stencil tables.
Slots 0 .. n-1 hold the particles, slots up to n_pad are padding,
and slot n_pad is the inactive sentinel filling empty table entries.
Inactive rows occupy no cell entry and emit no candidates.
Attributes:
| Name | Type | Description |
|---|---|---|
rows |
CellRows[Data]
|
Per-slot rows, leaves |
slot_of_row |
Array
|
Slot of each original particle row, |
cells |
Array
|
Slot ids per cell, |
stencil |
Array
|
Neighbor cell ids per cell, |
bins |
Array
|
Per-system bin counts, |
block_bounds |
BlockBounds
|
Bounds of the active rows in each run of
|
Source code in src/kups/core/neighborlist/cell_list_cache.py
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 | |
block_size
property
¶
Slots per spatial block.
max_cells_per_system
property
¶
Allocated capacity, derived from the stored array shapes.
bin_rows(particles, systems, data)
¶
Bin further particles (e.g. proposal queries) into this table's cells.
Source code in src/kups/core/neighborlist/cell_list_cache.py
block_rows(blocks)
¶
Rows of whole blocks, leaves (*blocks.shape, block_size, ...).
Block ids must be in bounds; callers mask padded ids themselves.
Source code in src/kups/core/neighborlist/cell_list_cache.py
candidate_chunks(cell, chunk_size)
¶
Group candidate columns into blocks, with a leading chunk axis.
Columns from every neighboring cell share a block. Entirely unused
blocks can be skipped without reducing cell occupancy capacity.
The shape is (n_chunks, *cell.shape, stencil_width * chunk_size);
the last block is sentinel-padded.
Source code in src/kups/core/neighborlist/cell_list_cache.py
candidates(cell)
¶
Candidate slots of the given cells, (..., stencil_width * cell_capacity).
Source code in src/kups/core/neighborlist/cell_list_cache.py
select(ctx)
¶
Look up occupants for CellListSelector using the stored grid.
The cache must correspond to ctx.keys in original row order.
Candidate ids are mapped back to those rows; the shared selector uses
original coordinates when computing periodic shifts.
Source code in src/kups/core/neighborlist/cell_list_cache.py
CellListCacheParameters
¶
Static shapes of a cell table.
Attributes:
| Name | Type | Description |
|---|---|---|
chunk_size |
int
|
Query rows processed per local scan step; the padded slot count is a multiple of it. |
max_cells_per_system |
int
|
Capacity for spatial bins per system
( |
cell_capacity |
int
|
Maximum active particles per bin (asserted). |
stencil_width |
int
|
Distinct neighbor cells per cell. 27 is always valid;
with fewer than three bins along an axis the stencil wraps onto
duplicates and |
key_chunk_size |
int | None
|
Optional keys per block: columns of each neighboring cell
for |
key_layout |
Literal['cells', 'slots']
|
Read neighboring cells, or traverse all particle slots. Slot traversal still applies the exact distance and pair masks. |
max_images_per_pair |
int
|
Capacity for each pair's periodic-image window. Estimated from the cutoff and cell geometry; one in the minimum-image regime. |
key_block_size |
int
|
Slots per spatial block. Slots are ordered by a
spatial bisection tree at build time and each block keeps
fractional bounds of its active rows, maintained on updates.
Local fused evaluations then skip blocks that are provably
beyond the cutoff of every query and gather only the remaining
blocks, in batches of |
Source code in src/kups/core/neighborlist/cell_list_cache.py
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 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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 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 | |
slot_multiple
property
¶
Padded slot counts are multiples of the query chunk and block size.
estimate(particles, systems, cutoffs, *, chunk_size=64, occupancy_factor=2.0, occupancy_headroom=32, key_chunk_size=None, key_layout='cells', key_block_size=8)
classmethod
¶
Estimate parameters from a concrete state.
Sizes cell_capacity from the exact per-cell occupancy of the
active particles with multiplicative and additive headroom to absorb
density growth (e.g. GCMC insertions); violations at runtime fail the
assertions in build_cell_list_cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
particles
|
Table[ParticleId, NeighborListPoints]
|
Current (possibly buffered) particle table. |
required |
systems
|
Table[SystemId, HasCell[AnyPeriodicity]]
|
System table with cells. |
required |
cutoffs
|
Table[SystemId, Array]
|
Per-system cutoff radii. |
required |
chunk_size
|
int
|
Query rows per local scan step. |
64
|
occupancy_factor
|
float
|
Multiplier on the observed maximum occupancy. |
2.0
|
occupancy_headroom
|
int
|
Additive slack on top of the scaled occupancy. |
32
|
key_chunk_size
|
int | Literal['auto'] | None
|
Keys per block, or |
None
|
key_layout
|
Literal['cells', 'slots', 'auto']
|
|
'cells'
|
key_block_size
|
int
|
Slots per spatial block. Blocks are culled only
in the minimum-image regime, where |
8
|
Returns:
| Type | Description |
|---|---|
Self
|
Static parameters for the table. |
Source code in src/kups/core/neighborlist/cell_list_cache.py
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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 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 | |
CellListCacheUpdatePatch
¶
Bases: Patch[State]
Accept-conditional update of a persistent cell table.
Accepted rows refresh their coordinates and payload. Only rows changing
cells are removed and reinserted (overflow asserted); moves within a cell
retain membership. On CPU, a wholly rejected proposal skips both operations.
Slots retain their original row identity, so slot_of_row stays valid.
Spatial sort order is not maintained after moves. Changed rows are ranked
within their destination cell by counting earlier rows bound for it.
Attributes:
| Name | Type | Description |
|---|---|---|
slots |
Array
|
Slots of the changed rows, |
system_idx |
Index[SystemId]
|
Original proposal system ids for acceptance; |
new |
CellRows[Data]
|
Rows after the update, leaves |
lens |
Lens[State, CellListCache[Data]]
|
Lens to the cell table in the state. |
Source code in src/kups/core/neighborlist/cell_list_cache.py
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 | |
CellListNeighborList
¶
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.
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.
cache optionally supplies an initialized CellListCache for the
current particles and cutoff. It retains occupant slots and neighboring
cells between calls; accepted moves must update it along with the particles.
Rebuild it when the cell, cutoff, or particle row layout changes.
Without a cache, the same grid algorithm joins particle and query cell hashes.
Candidate storage is O(N) for well-distributed particles at fixed density and cutoff. Uncached lookup sorts cell hashes; cached lookup gathers slots. 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. |
cutoffs |
Table[SystemId, Array]
|
Per-system cutoff distances used by this neighbor list. |
cache |
CellListLookup | None
|
Current cell occupants, or |
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
- Nonperiodic outliers remain searchable in boundary bins; many outliers can increase the candidate count.
Example
Source code in src/kups/core/neighborlist/cell_list.py
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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 | |
selector(query_size, systems)
¶
Build the candidate selector shared by graph and pair evaluation.
Source code in src/kups/core/neighborlist/cell_list.py
CellListSelector
¶
Selector for the cell-list algorithm.
Joins cell hashes, or reads occupants from an optional initialized cache,
then replicates per image multiplicity when max(cutoff/perp) > 0.5.
Set promise_unique_cells when the caller guarantees at least three cells
along every periodic axis,
so each query's stencil cells are already distinct; this skips the
per-query cell deduplication in the uncached lookup.
Source code in src/kups/core/neighborlist/cell_list.py
CellRows
¶
Bases: NamedTuple
Binned particle rows: what a cell table stores per slot.
Attributes:
| Name | Type | Description |
|---|---|---|
frac |
Array
|
Folded fractional positions, |
system |
Index[SystemId]
|
System index (0 where inactive). |
inclusion |
Index[InclusionId]
|
Inclusion index; out of bounds for inactive rows. |
exclusion |
Index[ExclusionId]
|
Exclusion index. |
data |
Data
|
Caller payload (e.g. kernel features), leaves |
cell |
Array
|
Global cell id; the sentinel cell where inactive. |
Source code in src/kups/core/neighborlist/cell_list_cache.py
positions
property
¶
Fractional coordinates for the neighbor pipeline.
concatenate(*parts)
staticmethod
¶
Join rows, aligning index vocabularies and preserving count bounds.
Source code in src/kups/core/neighborlist/cell_list_cache.py
pad(padding, *, sentinel_cell)
¶
Append inactive rows with finite geometry and zero-filled payloads.
Source code in src/kups/core/neighborlist/cell_list_cache.py
Compactor
¶
Bases: Protocol
Produces compacted 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. |
cutoffs |
Table[SystemId, Array]
|
Per-system cutoff distances used by this neighbor list. |
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
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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | |
selector(query_size, systems)
¶
Build the candidate selector shared by graph and pair evaluation.
Source code in src/kups/core/neighborlist/dense.py
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
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 | |
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[AnyPeriodicity]]
|
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[AnyPeriodicity]]
|
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
EmptyNeighborList
¶
Neighbor list that emits an :class:Edges[D] with zero rows.
The degree field is the runtime arity carried by the emitted edges;
it must match the type parameter D.
Attributes:
| Name | Type | Description |
|---|---|---|
degree |
int
|
Edge arity ( |
Source code in src/kups/core/neighborlist/fixed.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
FixedEdgesNeighborList
¶
Neighbor list for a fixed topology edge set.
Full self-graph calls return all fixed topology rows with shifts computed
from the current particle positions. Affected self-graph calls pass
keyword-only queried_keys after updated particle data has been written
into keys; the neighbor list returns only fixed rows touched by those
affected keys ids. queries is reserved for true bipartite
neighbor-list implementations and is not a fixed-edge update mechanism.
Attributes:
| Name | Type | Description |
|---|---|---|
indices |
Index[ParticleId]
|
Fixed edge topology. Shifts are intentionally not stored; they are computed from the call's current particle positions. |
avg_edges |
Capacity[int] | None
|
Update-only average affected-edge capacity per affected
|
Source code in src/kups/core/neighborlist/fixed.py
InBoundsMask
¶
Drops candidates whose key/query indices fall outside the valid inclusion-segment range.
Implements the per-side inclusion.valid_mask 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 key/query 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.
The degree parameter tracks which candidate arity the mask accepts. Pair
masks implement Mask[Literal[2]] by annotating their batch argument
as CandidateBatch[Literal[2]]; degree-agnostic masks use a generic
__call__ method.
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
¶
Bases: Compactor[D]
In-place compaction: failing entries become OOB indices and zero shifts.
No size change; preserves the candidate count from the selector. Pair candidates are already in their output index space.
Source code in src/kups/core/neighborlist/compact.py
MirrorPairEdges
¶
Bases: Postprocessor[Literal[2]]
Append reversed pair edges for undirected graph outputs.
The default mirrors only self-graph update calls selected by
ctx.queried_keys. Full self-neighbor calls already emit both directions
before compaction, while queried_keys calls operate on affected ids in
the already-updated keys table and are deduplicated by
QueriedKeysDedupMask. Their reverse edges are restored after compaction.
Attributes:
| Name | Type | Description |
|---|---|---|
only_when_queried_keys |
bool
|
When |
Source code in src/kups/core/neighborlist/postprocess.py
NeighborList
¶
Bases: Protocol
Protocol for neighbor list construction algorithms.
Implementations find groups of particles within a cutoff distance, handling periodic boundary conditions and inclusion/exclusion masks. The degree parameter tracks the arity of the emitted edge tuples.
Source code in src/kups/core/neighborlist/types.py
__call__(keys, systems, *, queries=None, queried_keys=None)
¶
Find particle groups for a self-graph or bipartite query.
queries and queried_keys are mutually exclusive; the overloads
above reject calls that pass both.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
Table[ParticleId, P]
|
Particle table that the returned |
required |
systems
|
Table[SystemId, NeighborListSystems]
|
Indexed system data with cell information. |
required |
queries
|
Table[ParticleId, P] | None
|
Optional bipartite query table. Each edge then connects a
|
None
|
queried_keys
|
Index[ParticleId] | None
|
Optional subset of |
None
|
Returns:
| Type | Description |
|---|---|
Edges[D]
|
Edges whose columns index |
Source code in src/kups/core/neighborlist/types.py
NeighborListCandidate
¶
A backing neighbor list paired with its cost estimator.
Attributes:
| Name | Type | Description |
|---|---|---|
neighborlist |
NeighborList[Literal[2]]
|
The candidate implementation. |
cost |
NeighborListCost
|
Estimates the implementation's cost for a call's counts. |
Source code in src/kups/core/neighborlist/adaptive.py
NeighborListCost
¶
Bases: Protocol
Estimates the relative runtime cost of a neighbor list for one call.
Lower is cheaper; :class:AdaptiveNeighborList dispatches to the minimum.
Return math.inf to mark an implementation invalid for the given shape.
Source code in src/kups/core/neighborlist/adaptive.py
NeighborListFactory
¶
Bases: Protocol
Constructs a pair :class:NeighborList for a given state and cutoffs.
Used by radius-based potential factories so the construction strategy
can be swapped without coupling the potential to a concrete
neighbor-list class. The library default is
:meth:kups.core.neighborlist.AdaptiveNeighborList.from_state,
which is contravariant-compatible with any state satisfying
:class:IsNeighborListState.
The State type parameter is contravariant (it appears only in
input position in __call__), so a factory written against a
broader state protocol can be passed where a narrower one is expected.
Source code in src/kups/core/neighborlist/types.py
Pipeline
¶
Selector → mask sequence → compactor → postprocessors.
Attributes:
| Name | Type | Description |
|---|---|---|
selector |
CandidateSelector[D]
|
Produces a |
masks |
tuple[Mask[D], ...]
|
Tuple of mask criteria over |
compactor |
Compactor[D]
|
Produces compacted |
postprocessors |
tuple[Postprocessor[D], ...]
|
Edge transforms applied sequentially after compaction. |
Source code in src/kups/core/neighborlist/pipeline.py
PipelineContext
¶
Read-only inputs shared by every mask and the compactor.
Positions in keys and optional queries are in fractional
coordinates (transformed by
[_prepare][kups.core.neighborlist.pipeline._prepare]).
Edges index keys, or for bipartite queries the union of keys and
queries, whose particle ids must then be disjoint.
Attributes:
| Name | Type | Description |
|---|---|---|
keys |
Table[ParticleId, NeighborListPoints]
|
Key particle table in fractional coords. |
queries |
Table[ParticleId, NeighborListPoints] | None
|
Query particle table in fractional coords for true bipartite
queries. |
systems |
Table[SystemId, NeighborListSystems]
|
Indexed system data with cell information. |
queried_keys |
Index[ParticleId] | None
|
|
Source code in src/kups/core/neighborlist/types.py
edge_keys
property
¶
Particle ids addressed by candidate and edge indices.
edge_query_table
property
¶
Table holding the second endpoint of each pair.
query_table
property
¶
Table used to enumerate query candidates.
queries is reserved for true bipartite calls. queried_keys
selects a self-graph update subset from keys and is lifted back to
keys ids before masks and compaction see the batch.
endpoints(batch)
¶
Key and query rows of each candidate pair.
Source code in src/kups/core/neighborlist/types.py
Postprocessor
¶
Bases: Protocol
Transforms compacted edges using the pipeline context.
Postprocessors run sequentially after compaction. They may change the
number of rows, but must preserve the edge degree D.
Source code in src/kups/core/neighborlist/types.py
PrecomputedEdgesSelector
¶
Selector that wraps precomputed Edges for both refine variants.
Precomputed edges index keys, or for a bipartite queries call the
union of keys and queries, matching the neighbor-list convention.
Attributes:
| Name | Type | Description |
|---|---|---|
candidates |
Edges[Literal[2]]
|
Precomputed edges. |
recompute_mic_shifts |
bool
|
When |
Source code in src/kups/core/neighborlist/refine.py
QueriedKeysDedupMask
¶
Deduplicate self-graph update candidates.
Pair selectors emit candidates in keys space. When ctx.queried_keys
is set, the query side was restricted to those affected keys rows.
We keep edges whose key endpoint is unaffected, plus one orientation for
edges where both endpoints are affected: key > query, or for self-image
rows (i, i, ±s) the lexicographically positive shift.
MirrorPairEdges restores the reverse orientation after compaction.
Returns all-True for full self-graphs and bipartite queries.
Source code in src/kups/core/neighborlist/masks.py
ReduceCompactor
¶
Bases: Compactor[D]
Compact surviving candidates to a size-bounded Edges[D].
Compacts whole candidate rows, so pair neighbor lists and fixed higher-degree topology share the same implementation.
Source code in src/kups/core/neighborlist/compact.py
compact_batch(keep, batch, ctx)
¶
Compact edges together with the image flags needed by pair kernels.
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. |
cutoffs |
Table[SystemId, Array]
|
Per-system cutoff distances used by this refinement. |
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, cells)
# Share across potentials with different cutoffs
lj_nl = RefineCutoffNeighborList(
candidates=base_edges, avg_edges=cap1, cutoffs=lj_cutoffs
)
lj_edges = lj_nl(particles, cells) # LJ cutoff
coulomb_nl = RefineCutoffNeighborList(
candidates=base_edges, avg_edges=cap2, cutoffs=coulomb_cutoffs
)
coulomb_edges = coulomb_nl(particles, cells) # Coulomb cutoff
Source code in src/kups/core/neighborlist/refine.py
179 180 181 182 183 184 185 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 | |
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, cells)
# Share across potentials with different masks
lj_nl = RefineMaskNeighborList(candidates=base_edges)
lj_edges = lj_nl(lj_particles, cells) # 1-4 exclusions
coulomb_nl = RefineMaskNeighborList(candidates=base_edges)
coulomb_edges = coulomb_nl(coulomb_particles, cells) # 1-2 exclusions only
Source code in src/kups/core/neighborlist/refine.py
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 172 173 174 175 176 | |
SelectableNeighborList
¶
Bases: NeighborList[D], Protocol
Neighbor list whose selector can be reused with different pipeline masks.
This additional capability lets pair evaluators retain image metadata and
defer group masks that differ between terms. Ordinary NeighborList
implementations need only provide their existing edge-producing call.
Source code in src/kups/core/neighborlist/types.py
SkinMargin
¶
Per-system completeness accounting of a stored skin list.
Attributes:
| Name | Type | Description |
|---|---|---|
consumed |
Array
|
Worst-case distance (Å) by which atom motion and cell
deformation since the build can have pulled a non-listed pair
inward, |
budget |
Array
|
Distance (Å) such a pair had to spare at build time — the
effective skin |
Source code in src/kups/core/neighborlist/verlet.py
headroom
property
¶
budget - consumed; the stored list is complete while >= 0.
SkinReference
¶
Geometry snapshot taken when the skin list was built.
skin_margin measures the
drift of the current geometry relative to this snapshot. The arrays must
not alias the live position/cell buffers (donated jitted steps would then
receive the same buffer twice).
Attributes:
| Name | Type | Description |
|---|---|---|
positions |
Array
|
Cartesian positions at the build, |
cell |
Cell[AnyPeriodicity]
|
|
Source code in src/kups/core/neighborlist/verlet.py
TouchesQueriedKeysMask
¶
Keep fixed-topology rows touched by ctx.queried_keys.
When no affected-index subset is active, every row is kept. This lets fixed topology use the same pipeline for full and patch-shaped calls.
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 candidate pairs per particle after
periodic-image replication (equals |
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(keys, systems, *, queries=None, queried_keys=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 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
all_dense_cost(num_particles, num_systems)
¶
Default cost for :class:AllDenseNearestNeighborList.
O(N^2) across all particles, so it ties dense for a single system and is
invalid (inf) for multiple systems, which it would incorrectly merge.
Source code in src/kups/core/neighborlist/adaptive.py
build_cell_list_cache(particles, systems, cutoffs, data, parameters)
¶
Bin, sort, and tabulate the particles of a point cloud.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
particles
|
Table[ParticleId, NeighborListPoints]
|
Particle table (positions, system, inclusion, exclusion). |
required |
systems
|
Table[SystemId, HasCell[AnyPeriodicity]]
|
System table with cells. |
required |
cutoffs
|
Table[SystemId, Array]
|
Per-system cutoff radii sizing the bins. |
required |
data
|
Data
|
Per-particle payload to carry per slot, leaves |
required |
parameters
|
CellListCacheParameters
|
Static table shapes. |
required |
Returns:
| Type | Description |
|---|---|
CellListCache[Data]
|
The cell table. |
Source code in src/kups/core/neighborlist/cell_list_cache.py
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 | |
cell_candidates(keys, queries, index, systems, cutoffs, max_images_per_pair)
¶
Adapt a cell-table query to the standard neighbor pipeline.
index contains key slots per query row. Without queries the rows of
keys query each other, so geometry and masks have a single
implementation. Periodic images expand only this chunk, with capacity
bounded per pair.
Source code in src/kups/core/neighborlist/cell_list_cache.py
cell_list_cost(num_particles, num_systems)
¶
Default cost for :class:CellListNeighborList (O(N) with a large
constant, crossing dense at _CELL_LIST_CROSSOVER particles per system).
Source code in src/kups/core/neighborlist/adaptive.py
cell_rows(particles, systems, bins, max_cells, data)
¶
Fold and bin particles into global cells system * max_cells + local.
Particles with an out-of-bounds inclusion index (the buffered-row
convention) are inactive and land in the sentinel cell n_systems *
max_cells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
particles
|
Table[ParticleId, NeighborListPoints]
|
Particle table (positions, system, inclusion, exclusion). |
required |
systems
|
Table[SystemId, HasCell[AnyPeriodicity]]
|
System table with cells. |
required |
bins
|
Array
|
Per-system bin counts, |
required |
max_cells
|
int
|
Allocated cell capacity per system. |
required |
data
|
Data
|
Per-particle payload carried along. |
required |
Returns:
| Type | Description |
|---|---|
CellRows[Data]
|
The binned rows. |
Source code in src/kups/core/neighborlist/cell_list_cache.py
dense_cost(num_particles, num_systems)
¶
Default cost for :class:DenseNearestNeighborList (O(N^2/K)).
effective_build_radii(cutoffs, skin, cell)
¶
Per-system build radius: cutoff + skin, clamped to a single image.
Reusing stored edges keeps exactly one periodic image per pair, so the build radius must stay below half the cell's smallest perpendicular length on every periodic axis — beyond that, second images enter the build sphere and the reuse path would drop them. A cell that compresses mid-run thus degrades to a thinner effective skin (more frequent rebuilds) instead of an incomplete list. No clamp applies in vacuum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cutoffs
|
Array
|
True cutoffs (Å), |
required |
skin
|
ArrayLike
|
Requested skin width (Å). |
required |
cell
|
Cell[AnyPeriodicity]
|
|
required |
Returns:
| Type | Description |
|---|---|
Array
|
Build radii (Å), |
Source code in src/kups/core/neighborlist/verlet.py
neighborlist_changes(neighborlist, lh, rh, systems, 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
|
NeighborList[Literal[2]]
|
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 |
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
skin_margin(particles, systems, reference, cutoffs, skin)
¶
How much of the skin list's safety margin the geometry has used up.
A skin list built at radius r_build stays complete for the true
cutoff as long as no pair that was outside r_build at build time
has come inside cutoff since. Two things move pairs inward:
- Cell deformation. Between the build and now the cell changed by the
linear map
F = h_ref⁻¹ h_now(row-vector convention), which maps every build-time pair vectord— including those to periodic images — tod @ F. A linear map cannot shrink any vector by more than its smallest singular value:|d @ F| >= σ_min(F) |d|for alld. So the affine part of the motion leaves every non-listed pair at distance at leastσ_min(F) r_build, an inward move of at mostr_build (1 - σ_min(F))— and none at all if the cell only expanded (σ_min >= 1). Becauseσ_minsees the whole map, pure shear counts like any other strain, unlike per-axis length ratios. - Atom motion on top of the deformation. Each atom's non-affine
displacement is
u_i = x_i - x_i_ref @ F— what remains after riding the cell — minimum-image wrapped in the current cell so that a boundary crossing (even along a sheared lattice vector) is undone exactly (a genuine non-affine drift beyond half a cell would be under-measured, but rebuilds fire at skin scale long before that). A pair distance changes by at most the two endpoint displacements,2 max|u|.
The stored list is therefore complete while, per system,
consumed := 2 max|u| + r_build max(0, 1 - σ_min(F)) <= r_build - cutoff =: budget
i.e. while the worst-case inward motion of a non-listed pair (consumed) has not eaten the extra radius the build added on top of the cutoff (budget). Pairs never span systems, so the accounting is fully per system: one hot system neither charges nor rebuilds the others.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
particles
|
Table[ParticleId, HasPositionsAndSystemIndex]
|
Current particle table (positions and system index). |
required |
systems
|
Table[SystemId, NeighborListSystems]
|
Current system table (cells). |
required |
reference
|
SkinReference
|
Positions and cell snapshot taken at the last build. |
required |
cutoffs
|
Table[SystemId, Array]
|
True cutoffs (Å) per system. |
required |
skin
|
ArrayLike
|
Requested skin width (Å) the list was built with. |
required |
Returns:
| Type | Description |
|---|---|
Table[SystemId, SkinMargin]
|
Per-system |
Table[SystemId, SkinMargin]
|
table ( |