Skip to main content

lib_jsl_geometry/algorithms/
kd_trees.rs

1//! k-d trees for nearest-neighbour and range queries in `D` dimensions.
2//!
3//! See the book entry [Spatial trees](https://jwkunz.github.io/lib_jsl/book/geometry/spatial-trees.html#k-d-trees).
4
5use std::cmp::Ordering;
6use std::collections::BinaryHeap;
7
8/// A static, balanced k-d tree over points in `D` dimensions.
9///
10/// Built once in `O(n log n)` by recursive median splits (cycling through the axes), then queried
11/// in roughly `O(log n)` for nearest neighbours. Queries return indices into the point slice the
12/// tree was built from. Points with non-finite coordinates are not indexed.
13#[derive(Debug, Clone)]
14
15pub struct KdTree<const D: usize> {
16    points: Vec<[f64; D]>,
17    /// Point indices arranged so that for each subslice the median is the node and the halves are
18    /// its subtrees.
19    order: Vec<usize>,
20}
21
22#[derive(PartialEq)]
23
24struct Candidate {
25    dist2: f64,
26    index: usize,
27}
28impl Eq for Candidate {}
29impl PartialOrd for Candidate {
30    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
31        Some(self.cmp(other))
32    }
33}
34impl Ord for Candidate {
35    fn cmp(&self, other: &Self) -> Ordering {
36        self.dist2.total_cmp(&other.dist2).then(self.index.cmp(&other.index))
37    }
38}
39
40fn dist2<const D: usize>(a: &[f64; D], b: &[f64; D]) -> f64 {
41    (0..D).map(|k| (a[k] - b[k]) * (a[k] - b[k])).sum()
42}
43
44impl<const D: usize> KdTree<D> {
45    pub fn new(points: &[[f64; D]]) -> Self {
46        let mut order: Vec<usize> = (0..points.len()).filter(|&i| points[i].iter().all(|v| v.is_finite())).collect();
47        Self::build(points, &mut order, 0);
48        KdTree { points: points.to_vec(), order }
49    }
50
51    fn build(points: &[[f64; D]], slice: &mut [usize], depth: usize) {
52        if slice.len() <= 1 {
53            return;
54        }
55        let axis = depth % D;
56        let mid = slice.len() / 2;
57        slice.select_nth_unstable_by(mid, |&a, &b| points[a][axis].total_cmp(&points[b][axis]));
58        let (left, rest) = slice.split_at_mut(mid);
59        Self::build(points, left, depth + 1);
60        Self::build(points, &mut rest[1..], depth + 1);
61    }
62
63    /// Number of indexed points.
64    pub fn len(&self) -> usize {
65        self.order.len()
66    }
67
68    pub fn is_empty(&self) -> bool {
69        self.order.is_empty()
70    }
71
72    /// The closest point to `query` as `(index, distance)`; ties go to the lower index.
73    pub fn nearest(&self, query: [f64; D]) -> Option<(usize, f64)> {
74        self.k_nearest(query, 1).into_iter().next()
75    }
76
77    /// The `k` closest points, nearest first, as `(index, distance)`.
78    pub fn k_nearest(&self, query: [f64; D], k: usize) -> Vec<(usize, f64)> {
79        if k == 0 || self.is_empty() || query.iter().any(|v| !v.is_finite()) {
80            return Vec::new();
81        }
82        let mut heap: BinaryHeap<Candidate> = BinaryHeap::with_capacity(k + 1);
83        self.search_k(&self.order, 0, &query, k, &mut heap);
84        let mut out: Vec<Candidate> = heap.into_vec();
85        out.sort();
86        out.into_iter().map(|c| (c.index, c.dist2.sqrt())).collect()
87    }
88
89    // ANCHOR: k_nearest
90    fn search_k(&self, slice: &[usize], depth: usize, q: &[f64; D], k: usize, heap: &mut BinaryHeap<Candidate>) {
91        if slice.is_empty() {
92            return;
93        }
94        let axis = depth % D;
95        let mid = slice.len() / 2;
96        let node = slice[mid];
97        let cand = Candidate { dist2: dist2(&self.points[node], q), index: node };
98        if heap.len() < k {
99            heap.push(cand);
100        } else if heap.peek().is_some_and(|worst| cand < *worst) {
101            heap.pop();
102            heap.push(cand);
103        }
104        let diff = q[axis] - self.points[node][axis];
105        let (near, far) = if diff < 0.0 { (&slice[..mid], &slice[mid + 1..]) } else { (&slice[mid + 1..], &slice[..mid]) };
106        self.search_k(near, depth + 1, q, k, heap);
107        // The far side can only help if the splitting plane is closer than the current k-th best.
108        if heap.len() < k || heap.peek().is_some_and(|worst| diff * diff <= worst.dist2) {
109            self.search_k(far, depth + 1, q, k, heap);
110        }
111    }
112    // ANCHOR_END: k_nearest
113
114    /// Indices of all points within `radius` of `query` (inclusive), in unspecified order.
115    pub fn within_radius(&self, query: [f64; D], radius: f64) -> Vec<usize> {
116        let mut out = Vec::new();
117        if radius >= 0.0 {
118            self.search_radius(&self.order, 0, &query, radius * radius, &mut out);
119        }
120        out
121    }
122
123    fn search_radius(&self, slice: &[usize], depth: usize, q: &[f64; D], r2: f64, out: &mut Vec<usize>) {
124        if slice.is_empty() {
125            return;
126        }
127        let axis = depth % D;
128        let mid = slice.len() / 2;
129        let node = slice[mid];
130        if dist2(&self.points[node], q) <= r2 {
131            out.push(node);
132        }
133        let diff = q[axis] - self.points[node][axis];
134        if diff <= 0.0 || diff * diff <= r2 {
135            self.search_radius(&slice[..mid], depth + 1, q, r2, out);
136        }
137        if diff >= 0.0 || diff * diff <= r2 {
138            self.search_radius(&slice[mid + 1..], depth + 1, q, r2, out);
139        }
140    }
141
142    // ANCHOR: query_pairs
143    /// All pairs `(i, j)`, `i < j`, of indexed points at distance at most `r` (SciPy's
144    /// `query_pairs`), sorted.
145    pub fn query_pairs(&self, r: f64) -> Vec<(usize, usize)> {
146        let mut out = Vec::new();
147        for &i in &self.order {
148            for j in self.within_radius(self.points[i], r) {
149                if j > i {
150                    out.push((i, j));
151                }
152            }
153        }
154        out.sort_unstable();
155        out
156    }
157
158    /// The number of pairs `(i, j)` with `i` from this tree and `j` from `other` at distance at
159    /// most `r` (SciPy's `count_neighbors` with a scalar radius).
160    pub fn count_neighbors(&self, other: &KdTree<D>, r: f64) -> usize {
161        other.order.iter().map(|&j| self.within_radius(other.points[j], r).len()).sum()
162    }
163    // ANCHOR_END: query_pairs
164
165    /// Indices of all points inside the axis-aligned box `[min, max]` (inclusive).
166    pub fn range_query(&self, min: [f64; D], max: [f64; D]) -> Vec<usize> {
167        let mut out = Vec::new();
168        self.search_box(&self.order, 0, &min, &max, &mut out);
169        out
170    }
171
172    fn search_box(&self, slice: &[usize], depth: usize, min: &[f64; D], max: &[f64; D], out: &mut Vec<usize>) {
173        if slice.is_empty() {
174            return;
175        }
176        let axis = depth % D;
177        let mid = slice.len() / 2;
178        let node = slice[mid];
179        let p = &self.points[node];
180        if (0..D).all(|k| p[k] >= min[k] && p[k] <= max[k]) {
181            out.push(node);
182        }
183        if min[axis] <= p[axis] {
184            self.search_box(&slice[..mid], depth + 1, min, max, out);
185        }
186        if max[axis] >= p[axis] {
187            self.search_box(&slice[mid + 1..], depth + 1, min, max, out);
188        }
189    }
190}
191
192/// A k-d tree on a periodic box `[0, L₁) × … × [0, L_D)` (SciPy's `cKDTree(..., boxsize=L)`):
193/// distances are measured to the nearest periodic image, as in simulations with periodic
194/// boundary conditions. Queries search the `3^D` images of the query point.
195#[derive(Debug, Clone)]
196pub struct PeriodicKdTree<const D: usize> {
197    tree: KdTree<D>,
198    boxsize: [f64; D],
199}
200
201impl<const D: usize> PeriodicKdTree<D> {
202    /// A tree on points inside the box (each coordinate in `[0, Lₖ)`; others are wrapped in).
203    pub fn new(points: &[[f64; D]], boxsize: [f64; D]) -> Result<Self, lib_jsl_core::ErrorsJSL> {
204        if boxsize.iter().any(|l| !(l.is_finite() && *l > 0.0)) {
205            return Err(lib_jsl_core::ErrorsJSL::InvalidInputRange("PeriodicKdTree: the box sizes must be positive"));
206        }
207        let wrapped: Vec<[f64; D]> = points.iter().map(|p| std::array::from_fn(|k| p[k].rem_euclid(boxsize[k]))).collect();
208        Ok(PeriodicKdTree { tree: KdTree::new(&wrapped), boxsize })
209    }
210
211    fn images(&self, q: [f64; D]) -> Vec<[f64; D]> {
212        let q: [f64; D] = std::array::from_fn(|k| q[k].rem_euclid(self.boxsize[k]));
213        let total = 3usize.pow(D as u32);
214        (0..total)
215            .map(|mut c| {
216                std::array::from_fn(|k| {
217                    let shift = (c % 3) as f64 - 1.0;
218                    c /= 3;
219                    q[k] + shift * self.boxsize[k]
220                })
221            })
222            .collect()
223    }
224
225    /// The `k` nearest points under the periodic distance, nearest first.
226    pub fn k_nearest(&self, query: [f64; D], k: usize) -> Vec<(usize, f64)> {
227        let mut best: std::collections::HashMap<usize, f64> = std::collections::HashMap::new();
228        for img in self.images(query) {
229            for (i, d) in self.tree.k_nearest(img, k) {
230                let e = best.entry(i).or_insert(f64::INFINITY);
231                *e = e.min(d);
232            }
233        }
234        let mut out: Vec<(usize, f64)> = best.into_iter().collect();
235        out.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0)));
236        out.truncate(k);
237        out
238    }
239
240    /// The nearest point under the periodic distance.
241    pub fn nearest(&self, query: [f64; D]) -> Option<(usize, f64)> {
242        self.k_nearest(query, 1).into_iter().next()
243    }
244
245    /// All points within `radius` under the periodic distance, sorted by index.
246    pub fn within_radius(&self, query: [f64; D], radius: f64) -> Vec<usize> {
247        let mut out: Vec<usize> = self.images(query).into_iter().flat_map(|img| self.tree.within_radius(img, radius)).collect();
248        out.sort_unstable();
249        out.dedup();
250        out
251    }
252
253    /// All pairs `(i, j)`, `i < j`, within distance `r` under the periodic distance, sorted.
254    pub fn query_pairs(&self, r: f64) -> Vec<(usize, usize)> {
255        let mut out = Vec::new();
256        for &i in &self.tree.order {
257            for j in self.within_radius(self.tree.points[i], r) {
258                if j > i {
259                    out.push((i, j));
260                }
261            }
262        }
263        out.sort_unstable();
264        out
265    }
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271
272    fn lcg(seed: u64) -> impl FnMut() -> f64 {
273        let mut s = seed;
274        move || {
275            s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
276            (s >> 11) as f64 / (1u64 << 53) as f64
277        }
278    }
279
280    fn brute_k<const D: usize>(pts: &[[f64; D]], q: [f64; D], k: usize) -> Vec<(usize, f64)> {
281        let mut all: Vec<(usize, f64)> = pts.iter().enumerate().map(|(i, p)| (i, dist2(p, &q).sqrt())).collect();
282        all.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0)));
283        all.truncate(k);
284        all
285    }
286
287    #[test]
288    fn matches_brute_force_in_2d_and_3d_and_5d() {
289        let mut rnd = lcg(3);
290        let p2: Vec<[f64; 2]> = (0..400).map(|_| [rnd(), rnd()]).collect();
291        let p3: Vec<[f64; 3]> = (0..400).map(|_| [rnd(), rnd(), rnd()]).collect();
292        let p5: Vec<[f64; 5]> = (0..300).map(|_| [rnd(), rnd(), rnd(), rnd(), rnd()]).collect();
293        let (t2, t3, t5) = (KdTree::new(&p2), KdTree::new(&p3), KdTree::new(&p5));
294        for _ in 0..40 {
295            let q2 = [rnd() * 1.2 - 0.1, rnd()];
296            assert_eq!(t2.k_nearest(q2, 7), brute_k(&p2, q2, 7));
297            let q3 = [rnd(), rnd(), rnd()];
298            assert_eq!(t3.nearest(q3).unwrap(), brute_k(&p3, q3, 1)[0]);
299            let q5 = [rnd(), rnd(), rnd(), rnd(), rnd()];
300            assert_eq!(t5.k_nearest(q5, 3), brute_k(&p5, q5, 3));
301        }
302    }
303
304    #[test]
305    fn radius_and_box_queries() {
306        let mut rnd = lcg(11);
307        let pts: Vec<[f64; 3]> = (0..500).map(|_| [rnd() * 10.0, rnd() * 10.0, rnd() * 10.0]).collect();
308        let tree = KdTree::new(&pts);
309        let q = [5.0, 4.0, 6.0];
310        let mut got = tree.within_radius(q, 2.5);
311        got.sort_unstable();
312        let want: Vec<usize> = (0..pts.len()).filter(|&i| dist2(&pts[i], &q).sqrt() <= 2.5).collect();
313        assert_eq!(got, want);
314        let (lo, hi) = ([2.0, 3.0, 1.0], [6.0, 7.0, 4.0]);
315        let mut got = tree.range_query(lo, hi);
316        got.sort_unstable();
317        let want: Vec<usize> = (0..pts.len()).filter(|&i| (0..3).all(|k| pts[i][k] >= lo[k] && pts[i][k] <= hi[k])).collect();
318        assert_eq!(got, want);
319        assert!(tree.within_radius(q, -1.0).is_empty());
320    }
321
322    #[test]
323    fn edge_cases() {
324        let empty: KdTree<2> = KdTree::new(&[]);
325        assert!(empty.is_empty() && empty.nearest([0.0, 0.0]).is_none());
326        let pts = [[1.0, 1.0], [f64::NAN, 0.0], [1.0, 1.0], [3.0, 3.0]];
327        let t = KdTree::new(&pts);
328        assert_eq!(t.len(), 3); // the NaN point is not indexed
329        assert_eq!(t.nearest([1.1, 1.0]).unwrap().0, 0); // duplicate: lower index wins
330        assert_eq!(t.k_nearest([0.0, 0.0], 10).len(), 3);
331        assert!(t.k_nearest([0.0, 0.0], 0).is_empty() && t.k_nearest([f64::NAN, 0.0], 1).is_empty());
332    }
333
334    #[test]
335    fn pairs_and_periodic_distances_match_brute_force() {
336        let mut rnd = lcg(11);
337        let p: Vec<[f64; 2]> = (0..300).map(|_| [rnd(), rnd()]).collect();
338        let t = KdTree::new(&p);
339        let r = 0.06;
340        let mut brute = Vec::new();
341        for i in 0..p.len() {
342            for j in i + 1..p.len() {
343                if dist2(&p[i], &p[j]) <= r * r {
344                    brute.push((i, j));
345                }
346            }
347        }
348        assert_eq!(t.query_pairs(r), brute);
349        assert_eq!(t.count_neighbors(&t, r), 2 * brute.len() + p.len());
350        let pt = PeriodicKdTree::new(&p, [1.0, 1.0]).unwrap();
351        let pd = |a: &[f64; 2], b: &[f64; 2]| (0..2).map(|k| { let d = (a[k] - b[k]).abs(); d.min(1.0 - d).powi(2) }).sum::<f64>().sqrt();
352        for _ in 0..20 {
353            let q = [rnd(), rnd()];
354            let mut all: Vec<(usize, f64)> = p.iter().enumerate().map(|(i, x)| (i, pd(x, &q))).collect();
355            all.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0)));
356            let got = pt.k_nearest(q, 5);
357            for (g, w) in got.iter().zip(&all) {
358                assert_eq!(g.0, w.0);
359                assert!((g.1 - w.1).abs() < 1e-14);
360            }
361        }
362        let wrap_pairs = pt.query_pairs(r).len();
363        assert!(wrap_pairs >= brute.len());
364    }
365}