linkcell/lib.rs
1//! Periodic linked-cell k-nearest neighbour search.
2//!
3//! vesin builds cutoff pair lists. nanoflann builds Euclidean KD-trees
4//! without a minimum-image convention. This crate is the missing piece:
5//! Allen and Tildesley's linked cells, a k-heap per source, and an
6//! index box that grows one axis at a time until the k-th neighbour
7//! cannot lie past an unvisited face. The pair itself is Rapaport's
8//! cell shift, not a per-pair nearest integer. [`pairs_within`] is the
9//! cutoff pair list with integer cell shifts (vesin/tonari `ijS`);
10//! [`knearest`] unique-indexes.
11//!
12//! # Algorithm
13//!
14//! 1. **Fold** every position into the primary cell
15//! ([`Cell::fractional`], then [`Cell::cartesian`]).
16//! 2. **Bin** the folded points on a fractional mesh. The bin count
17//! along each axis uses the perpendicular face width, so a sheared
18//! dump is not treated as orthogonal.
19//! 3. **Grow an index box** of linked cells. The first visit is the
20//! 3×3×3 around the home bin. After that, only an axis whose
21//! unvisited plane is still inside the k-th neighbour grows.
22//! Occupants are stored in cell order. A neighbour cell whose slab
23//! cannot beat the worst heap entry is skipped. The cap is the
24//! space diagonal over the minimum cell height, so a shift outside
25//! `{-1,0,1}` is still visited when it is the Euclidean image.
26//!
27//! The walk basis depends on the cell. An orthorhombic box, including
28//! a rectangular film, is used as stored. A restricted triclinic box
29//! (LAMMPS dump bounds, a CON angle, a hexagonal prism) is
30//! tilt-reduced in place and the shift is triangular. A general
31//! orientation is Minkowski-reduced. If either reduction fails, the
32//! walk keeps the caller's cell. [`pairs_within`] keeps the caller's
33//! basis on every call, because the reported shift is an integer
34//! combination of that H.
35//!
36//! Pair distances in the walk are not a per-pair minimum-image wrap.
37//! After the fold, a neighbour stencil `(jx, jy, jz)` contributes
38//! [`Cell::lattice_shift`] and [`Cell::dist2_shifted`]: a Cartesian
39//! subtract plus one lattice vector (the vesin / LAMMPS ghost trick).
40//! Orthorhombic boxes set the [`Cell::is_ortho`] flag and skip the two
41//! 3x3 matvecs: three independent wraps, and the shift is a scaled
42//! diagonal. The Highway batch ([`dist2_ortho_diffs`]) is that wrap
43//! for a raw difference. [`knearest_brute`] uses it on an orthorhombic
44//! box. [`pairs_within`] keeps the stencil image and does not wrap
45//! the shifted difference again.
46//!
47//! # Why a unique-cell stamp is wrong
48//!
49//! A stamp that visits each linked cell once, with a **single** shift
50//! for every occupant, is not a minimum-image convention. Occupants of
51//! one cell can need **different** images of the same source (a wide
52//! bin, or a source near a face). The walk keys on the integer stencil
53//! `(jx, jy, jz)`, including wraps: the same `rem_euclid` bin may
54//! appear with more than one [`Cell::lattice_shift`].
55//!
56//! # Output
57//!
58//! [`knearest`] returns one [`Neighbors`] row per input point, nearest
59//! first. [`knearest_into`] writes a packed `n * k` index buffer
60//! (`-1` in unused slots), the same layout as `lc_knearest`.
61//!
62//! # Cost
63//!
64//! Binning is linear in the active points plus the bin count. More
65//! than 1,000,000 bins on one axis, or more than 16,777,216 bins in
66//! the mesh, is [`Error::TooManyCells`].
67//!
68//! [`pairs_within`] keeps the caller's basis. The image count is the
69//! product of `2 * ceil(cutoff / width) + 1` over the three axes, and
70//! a count above 2^24 is [`Error::TooManyImages`]. With the default
71//! bin edge the reach is at most a small constant (the occupancy
72//! integer is clamped to `1..=6`) whenever that edge is shorter than
73//! every box width. One bin that holds every point makes the candidate
74//! tests quadratic.
75//!
76//! [`knearest`] takes no cutoff. Each source keeps a heap of `k`
77//! entries (`k <= 16` stays on the stack) and grows an index box until
78//! the worst entry is at most the squared gap to every unvisited plane,
79//! or until the radius reaches the space diagonal of the walk cell in
80//! units of the shortest bin edge. A filled lattice stops in the first
81//! shells. `k = n - 1`, or every point in a few bins, reads every other
82//! point.
83//!
84//! # Features
85//!
86//! `parallel` is on by default. An unmasked k-nearest query of at least
87//! 8192 points runs on one linkcell thread team when this build has it: bin,
88//! count, scan, fill, and select, with a private histogram and scratch
89//! on each thread. Masked and smaller queries use rayon.
90//! `--no-default-features` drops rayon and serializes the walk (re-enable
91//! `capi` if the C ABI is still required). The per-source k-heap
92//! (`KHeap`) stays on the stack for `k <= 16`; larger `k` spills to the
93//! heap.
94//!
95//! The mesh fold, the k-nearest SoA scan, and cutoff pairs use AVX-512
96//! (eight lanes), AVX2 (four lanes), or NEON (two lanes) when the CPU
97//! has that path. AVX-512 also requires AVX-512VL, POPCNT, and FMA.
98//! AVX2 is selected only when FMA is present too. Stored sums are
99//! separate multiplies and adds, in the scalar order, so every stored
100//! value matches the scalar path bit for bit. Pair screening may use
101//! FMA inside its margin test. The value it stores is the direct sum
102//! of squares. The fold floor is minimage `floor_fast`, truncation on
103//! every architecture. `LINKCELL_SIMD` forces `scalar`, `avx2`, `avx512`, or
104//! `neon`. [`simd_path`] reports the path in use. Neighbour rows, pair
105//! rows, and the fold are bitwise identical across thread counts. The
106//! `timing` feature exports `SimdTiming` for benchmark counters.
107//!
108//! # Examples
109//!
110//! Periodic image, not the raw Cartesian vector:
111//!
112//! ```
113//! use linkcell::{knearest, Cell};
114//!
115//! # fn main() -> Result<(), linkcell::Error> {
116//! let sim = Cell::ortho(10.0, 10.0, 10.0)?;
117//! let xyz = [[0.2, 0.0, 0.0], [9.4, 0.0, 0.0]];
118//! let rows = knearest(&xyz, &sim, 1, None, None)?;
119//! assert_eq!(rows[0].indices, vec![1]);
120//! assert!((rows[0].dist2[0] - 0.64).abs() < 1e-12);
121//! # Ok(())
122//! # }
123//! ```
124//!
125//! Two occupants of one linked cell (the whole box is a single bin)
126//! need different images of the source. A unique-cell stamp with one
127//! shift cannot serve both.
128//!
129//! ```
130//! use linkcell::{knearest, Cell};
131//!
132//! # fn main() -> Result<(), linkcell::Error> {
133//! let sim = Cell::ortho(10.0, 10.0, 10.0)?;
134//! let xyz = [[0.1, 0.0, 0.0], [1.0, 0.0, 0.0], [9.8, 0.0, 0.0]];
135//! let rows = knearest(&xyz, &sim, 2, None, Some(10.0))?;
136//! assert_eq!(rows[0].indices, vec![2, 1]);
137//! assert!((rows[0].dist2[0] - 0.09).abs() < 1e-12);
138//! assert!((rows[0].dist2[1] - 0.81).abs() < 1e-12);
139//! # Ok(())
140//! # }
141//! ```
142//!
143//! Packed `n * k` indices, unused slots `-1`:
144//!
145//! ```
146//! use linkcell::{knearest_into, Cell};
147//!
148//! # fn main() -> Result<(), linkcell::Error> {
149//! let sim = Cell::ortho(10.0, 10.0, 10.0)?;
150//! let xyz = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]];
151//! let mut out = [0; 4];
152//! knearest_into(&xyz, &sim, 2, None, None, &mut out)?;
153//! assert_eq!(out, [1, -1, 0, -1]);
154//! # Ok(())
155//! # }
156//! ```
157//!
158//! The C ABI (`lc_*`) is the hourglass waist: packed `n * k` indices,
159//! matching squared distances, and `lc_pairs_within` for a cutoff
160//! list with the caller's shift. C++ lives in `include/linkcell.hpp`
161//! as a RAII header over that ABI.
162
163#![deny(missing_docs)]
164
165mod bins;
166mod cell;
167mod error;
168mod knearest;
169mod open_cell;
170mod pairs;
171mod partition;
172#[cfg(any(feature = "capi", test))]
173mod place;
174mod pop;
175mod replica;
176mod simd;
177mod skin;
178mod skin_simd;
179mod team;
180#[cfg(feature = "capi")]
181mod vesin_abi;
182#[cfg(feature = "capi")]
183pub use vesin_abi::{NeighborCalc, VesinOptions};
184
185pub use cell::{
186 dist2_many, dist2_ortho_diffs, dist2_pairs, reduce_pairs, reduce_pairs_packed, wrap_many, Cell,
187};
188pub use error::Error;
189pub use knearest::{
190 knearest, knearest_brute, knearest_csr, knearest_into, knearest_into_d2, knearest_into_many,
191 knearest_team_threads, pin_knearest_to_least_loaded, shutdown_knearest_team, Neighbors,
192};
193pub use open_cell::{cell_for_pbc, pairs_open, pairs_within_pbc, stencil_builds, PbcQuery};
194pub use pairs::{
195 pairs_within, pairs_within_columns, pairs_within_count, pairs_within_csr, pairs_within_into,
196 Pair, PairColumns, PairCsr,
197};
198pub use partition::{
199 cell_graph, cell_grid, curve_split_device, derived_balance, derived_balance_f64, edge_cut,
200 exclusive_prefix, fused_masks, halo, halo_width, hilbert_key, histogram, mark_reached,
201 mesh_cut, morton_cmp, morton_key, owned_cells, partition, partition_graph, prefix_assign,
202 profile_ns, profile_reset, rank_mask, replicate_graph, score, timer_resolution_ns, CellGraph,
203 CellGrid, MeshCut, Method, PartRequest, PartScore, RankMask, DEFAULT_METHOD,
204};
205pub use pop::{
206 efficiencies as pop_efficiencies, engage as pop_engage, prepare as pop_prepare,
207 reset as pop_reset, snapshot as pop_snapshot,
208};
209pub use replica::ReplicaList;
210pub use simd::{avx512_ready, simd_path};
211#[cfg(feature = "timing")]
212pub use simd::{simd_timing, SimdTiming};
213pub use skin::SkinList;
214
215#[cfg(feature = "parallel")]
216thread_local! {
217 static ON_CALLER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
218}
219
220/// True while a search asked to run on one thread is on the calling thread.
221#[cfg(feature = "parallel")]
222pub(crate) fn on_caller() -> bool {
223 rayon::current_thread_index().is_none() && ON_CALLER.with(std::cell::Cell::get)
224}
225
226/// Threads the walk may split over. A one-thread search on the caller is
227/// one: asked from outside a pool, rayon builds its global pool at
228/// `RAYON_NUM_THREADS` or the cpu count, and the walk then splits over it.
229#[cfg(feature = "parallel")]
230pub(crate) fn pool_width() -> usize {
231 if on_caller() {
232 1
233 } else {
234 rayon::current_num_threads()
235 }
236}
237
238/// Runs `work` on this thread as a one-thread search.
239#[cfg(all(feature = "parallel", feature = "capi"))]
240pub(crate) fn run_on_caller<R>(work: impl FnOnce() -> R) -> R {
241 struct Restore(bool);
242 impl Drop for Restore {
243 fn drop(&mut self) {
244 ON_CALLER.with(|flag| flag.set(self.0));
245 }
246 }
247 let _restore = Restore(ON_CALLER.with(|flag| flag.replace(true)));
248 work()
249}
250
251#[cfg(feature = "capi")]
252mod capi;
253#[cfg(feature = "tune")]
254mod tune;
255#[cfg(feature = "capi")]
256pub use capi::*;