Skip to main content

sampling_planning/nearest/
kd_tree.rs

1//! An incremental k-d tree for Euclidean spaces.
2
3use alloc::{collections::BTreeMap, vec::Vec};
4
5use super::{NearestNeighbors, k_best::KBest};
6use crate::{Euclidean, StateSpace};
7
8/// Relative slack added to pruning bounds.
9///
10/// The splitting-plane gap is computed with one subtraction while
11/// [`Euclidean::distance`](crate::StateSpace::distance) goes through a sum of squares and a
12/// square root, so the two can disagree by a few ulps. Visiting a subtree too often only costs
13/// time; pruning one too eagerly could change a result, so the bound errs on the visiting side.
14const PRUNE_SLACK: f64 = 1e-9;
15
16/// A k-d tree over `[f64; N]` states for the [`Euclidean`] metric.
17///
18/// Nodes are inserted one at a time without rebalancing. The split axis cycles with the
19/// depth. Planners insert random samples, which keeps the tree balanced in expectation; a
20/// sorted insertion order degrades it to a list until [`KdTree::rebalance`] is called.
21///
22/// Removal ([`RemovableNeighbors`](crate::RemovableNeighbors)) finds the node through an id
23/// index, marks it, and rebuilds the tree balanced once removed nodes outnumber live ones.
24///
25/// Queries return exactly what [`LinearScan`](crate::LinearScan) returns, including its tie
26/// breaking toward the earliest inserted state, because both compare the same
27/// [`StateSpace::distance`] values. Expected cost per query is `O(log n)` in low dimensions;
28/// beyond roughly ten dimensions the pruning stops paying off and a linear scan is as fast.
29///
30/// # Examples
31///
32/// ```
33/// use sampling_planning::{Euclidean, KdTree, NearestNeighbors};
34///
35/// let mut tree = KdTree::<2>::default();
36/// tree.insert(7, [0.0, 0.0]);
37/// tree.insert(8, [3.0, 4.0]);
38///
39/// assert_eq!(tree.nearest(&Euclidean::<2>, &[2.5, 3.0]), Some(8));
40/// ```
41#[derive(Debug, Clone)]
42pub struct KdTree<const N: usize> {
43    /// All stored nodes, removed ones included until the next rebuild, in insertion order.
44    ///
45    /// The position of a node is its insertion rank, which breaks distance ties. Rebuilds drop
46    /// removed nodes but keep the relative order of the rest.
47    nodes: Vec<Node<N>>,
48    /// The index of the root node in `nodes`; `None` while the tree has no nodes.
49    root: Option<usize>,
50    /// Maps each stored id to the index of its live node, for `O(log n)` removal.
51    ///
52    /// When an id is inserted twice, the newer node wins.
53    by_id: BTreeMap<usize, usize>,
54    /// The number of nodes that were not removed.
55    live: usize,
56}
57
58/// One node of a [`KdTree`].
59#[derive(Debug, Clone)]
60struct Node<const N: usize> {
61    /// The stored state; also the splitting point.
62    state: [f64; N],
63    /// The caller's id for this state.
64    id: usize,
65    /// The split axis, `depth % N` (0 when `N == 0`).
66    axis: usize,
67    /// The subtree with `state[axis]` below this node's, if any.
68    left: Option<usize>,
69    /// The subtree with `state[axis]` at or above this node's, if any.
70    right: Option<usize>,
71    /// Whether the node was removed. Removed nodes still split space but never match.
72    removed: bool,
73}
74
75/// A pending subtree of the balanced build: a range of `order` and where its root attaches.
76#[derive(Debug, Clone, Copy)]
77struct BuildTask {
78    /// The first position of the range in the build order.
79    start: usize,
80    /// One past the last position of the range.
81    end: usize,
82    /// The depth of the subtree root; its split axis is `depth % N`.
83    depth: usize,
84    /// The parent node and whether the subtree is its left child; `None` for the root.
85    parent: Option<(usize, bool)>,
86}
87
88/// The fewest removed nodes that trigger a rebuild, so that tiny trees do not rebuild on every
89/// removal.
90const MIN_REBUILD_TOMBSTONES: usize = 16;
91
92impl<const N: usize> Default for KdTree<N> {
93    fn default() -> Self {
94        Self {
95            nodes: Vec::new(),
96            root: None,
97            by_id: BTreeMap::new(),
98            live: 0,
99        }
100    }
101}
102
103impl<const N: usize> KdTree<N> {
104    /// Rebuilds the tree as a balanced k-d tree over the live nodes, dropping removed ones.
105    ///
106    /// Each subtree splits at the median of its states along the axis of its depth, so the
107    /// depth is `O(log n)` whatever the insertion order was. Insertion ranks keep their relative
108    /// order, so query results do not change. Costs `O(n log^2 n)`.
109    ///
110    /// Removal calls this automatically once removed nodes outnumber live ones. Call it by hand
111    /// after inserting many states in sorted order, which degrades the incremental tree to a
112    /// list.
113    ///
114    /// # Examples
115    ///
116    /// ```
117    /// use sampling_planning::{Euclidean, KdTree, NearestNeighbors};
118    ///
119    /// let mut tree = KdTree::<1>::default();
120    /// for id in 0..100 {
121    ///     tree.insert(id, [f64::from(u32::try_from(id).expect("small"))]);
122    /// }
123    ///
124    /// tree.rebalance();
125    /// assert_eq!(tree.nearest(&Euclidean::<1>, &[41.2]), Some(41));
126    /// ```
127    pub fn rebalance(&mut self) {
128        self.nodes.retain(|node| !node.removed);
129        self.by_id = self
130            .nodes
131            .iter()
132            .enumerate()
133            .map(|(index, node)| (node.id, index))
134            .collect();
135        self.live = self.nodes.len();
136        self.root = self.build_balanced();
137    }
138
139    /// Links all nodes into a balanced tree and returns the root index.
140    fn build_balanced(&mut self) -> Option<usize> {
141        let mut order: Vec<usize> = (0..self.nodes.len()).collect();
142        let mut root = None;
143        let mut tasks = alloc::vec![BuildTask {
144            start: 0,
145            end: order.len(),
146            depth: 0,
147            parent: None,
148        }];
149
150        while let Some(task) = tasks.pop() {
151            if task.start == task.end {
152                continue;
153            }
154
155            let median = self.split_at_median(&mut order[task.start..task.end], task.depth);
156            let node = order[task.start + median];
157            self.attach(node, task, &mut root);
158
159            let mid = task.start + median;
160            tasks.push(BuildTask {
161                start: task.start,
162                end: mid,
163                depth: task.depth + 1,
164                parent: Some((node, true)),
165            });
166            tasks.push(BuildTask {
167                start: mid + 1,
168                end: task.end,
169                depth: task.depth + 1,
170                parent: Some((node, false)),
171            });
172        }
173
174        root
175    }
176
177    /// Sorts `range` along the axis of `depth` and returns the position of the splitting node:
178    /// the first of the nodes that share the median coordinate, so that everything before it
179    /// is strictly smaller, as [`KdTree::goes_left`] expects.
180    #[expect(
181        clippy::float_cmp,
182        reason = "only exactly equal coordinates may go to the right subtree"
183    )]
184    fn split_at_median(&self, range: &mut [usize], depth: usize) -> usize {
185        let axis = Self::axis_of(depth);
186        let coordinate = |index: usize| Self::coordinate(&self.nodes[index].state, axis);
187        range.sort_by(|&a, &b| coordinate(a).total_cmp(&coordinate(b)).then(a.cmp(&b)));
188
189        let mut median = range.len() / 2;
190        while median > 0 && coordinate(range[median - 1]) == coordinate(range[median]) {
191            median -= 1;
192        }
193
194        median
195    }
196
197    /// Resets node `node` as the root of the subtree described by `task` and links it to its
198    /// parent, or records it as the tree root.
199    fn attach(&mut self, node: usize, task: BuildTask, root: &mut Option<usize>) {
200        let entry = &mut self.nodes[node];
201        entry.axis = Self::axis_of(task.depth);
202        entry.left = None;
203        entry.right = None;
204
205        match task.parent {
206            None => *root = Some(node),
207            Some((parent, true)) => self.nodes[parent].left = Some(node),
208            Some((parent, false)) => self.nodes[parent].right = Some(node),
209        }
210    }
211
212    /// The split axis at `depth`: `depth % N`, or 0 when `N == 0`.
213    const fn axis_of(depth: usize) -> usize {
214        if N == 0 { 0 } else { depth % N }
215    }
216
217    /// The coordinate of `state` along `axis`; 0 when `N == 0`.
218    fn coordinate(state: &[f64; N], axis: usize) -> f64 {
219        if N == 0 { 0.0 } else { state[axis] }
220    }
221
222    /// Whether `query` belongs in the left subtree of node `index`.
223    fn goes_left(&self, index: usize, query: &[f64; N]) -> bool {
224        let node = &self.nodes[index];
225
226        N > 0 && query[node.axis] < node.state[node.axis]
227    }
228
229    /// The distance from `query` to the splitting plane of node `index`.
230    fn plane_gap(&self, index: usize, query: &[f64; N]) -> f64 {
231        let node = &self.nodes[index];
232
233        if N == 0 {
234            0.0
235        } else {
236            libm::fabs(query[node.axis] - node.state[node.axis])
237        }
238    }
239
240    /// The near and far children of node `index` as seen from `query`.
241    fn children(&self, index: usize, query: &[f64; N]) -> (Option<usize>, Option<usize>) {
242        let node = &self.nodes[index];
243
244        if self.goes_left(index, query) {
245            (node.left, node.right)
246        } else {
247            (node.right, node.left)
248        }
249    }
250
251    /// The index of the node whose empty child slot `state` falls into, with the side, or
252    /// `None` for an empty tree.
253    fn attachment_point(&self, state: &[f64; N]) -> Option<(usize, bool)> {
254        let mut current = self.root?;
255
256        loop {
257            let left = self.goes_left(current, state);
258            let next = if left {
259                self.nodes[current].left
260            } else {
261                self.nodes[current].right
262            };
263
264            match next {
265                Some(child) => current = child,
266                None => return Some((current, left)),
267            }
268        }
269    }
270
271    /// Whether the candidate `(distance, index)` beats the current best. Earlier insertion
272    /// wins ties; NaN distances never win.
273    #[expect(
274        clippy::float_cmp,
275        reason = "exact ties must break like LinearScan, which compares the same values"
276    )]
277    fn improves(best: Option<(f64, usize)>, distance: f64, index: usize) -> bool {
278        best.is_none_or(|(best_distance, best_index)| {
279            distance < best_distance || (distance == best_distance && index < best_index)
280        })
281    }
282
283    /// Whether removed nodes outnumber live ones by enough to make a rebuild pay off.
284    fn needs_rebuild(&self) -> bool {
285        let tombstones = self.nodes.len() - self.live;
286
287        tombstones >= MIN_REBUILD_TOMBSTONES && tombstones > self.live
288    }
289}
290
291impl<const N: usize> NearestNeighbors<Euclidean<N>> for KdTree<N> {
292    fn insert(&mut self, id: usize, state: [f64; N]) {
293        let index = self.nodes.len();
294        let axis = match self.attachment_point(&state) {
295            None => {
296                self.root = Some(index);
297                0
298            }
299            Some((parent, left)) => {
300                let parent_node = &mut self.nodes[parent];
301
302                if left {
303                    parent_node.left = Some(index);
304                } else {
305                    parent_node.right = Some(index);
306                }
307
308                Self::axis_of(parent_node.axis + 1)
309            }
310        };
311
312        self.nodes.push(Node {
313            state,
314            id,
315            axis,
316            left: None,
317            right: None,
318            removed: false,
319        });
320        self.by_id.insert(id, index);
321        self.live += 1;
322    }
323
324    fn nearest(&self, space: &Euclidean<N>, query: &[f64; N]) -> Option<usize> {
325        let mut best: Option<(f64, usize)> = None;
326        // Pending subtrees with a lower bound on their distance, checked when popped so that
327        // the bound is compared against the best distance found by then.
328        let mut stack = Vec::new();
329        stack.extend(self.root.map(|root| (root, 0.0)));
330
331        while let Some((index, lower_bound)) = stack.pop() {
332            if best.is_some_and(|(d, _)| lower_bound > d * (1.0 + PRUNE_SLACK)) {
333                continue;
334            }
335
336            let node = &self.nodes[index];
337            let distance = space.distance(&node.state, query);
338
339            if !node.removed && Self::improves(best, distance, index) {
340                best = Some((distance, index));
341            }
342
343            // The far side goes on the stack first so that the near side is searched first.
344            let (near, far) = self.children(index, query);
345            let gap = self.plane_gap(index, query);
346            stack.extend(far.map(|far| (far, gap)));
347            stack.extend(near.map(|near| (near, 0.0)));
348        }
349
350        best.map(|(_, index)| self.nodes[index].id)
351    }
352
353    fn within_radius(
354        &self,
355        space: &Euclidean<N>,
356        query: &[f64; N],
357        radius: f64,
358        out: &mut Vec<usize>,
359    ) {
360        let mut hits = Vec::new();
361        let mut stack = Vec::new();
362        let bound = radius * (1.0 + PRUNE_SLACK);
363        stack.extend(self.root);
364
365        while let Some(index) = stack.pop() {
366            let node = &self.nodes[index];
367
368            if !node.removed && space.distance(&node.state, query) <= radius {
369                hits.push(index);
370            }
371
372            let (near, far) = self.children(index, query);
373            stack.extend(near);
374
375            if self.plane_gap(index, query) <= bound {
376                stack.extend(far);
377            }
378        }
379
380        hits.sort_unstable();
381        out.clear();
382        out.extend(hits.iter().map(|&index| self.nodes[index].id));
383    }
384
385    fn k_nearest(&self, space: &Euclidean<N>, query: &[f64; N], k: usize, out: &mut Vec<usize>) {
386        let mut best = KBest::new(k);
387        let mut stack = Vec::new();
388
389        if k > 0 {
390            stack.extend(self.root.map(|root| (root, 0.0)));
391        }
392
393        while let Some((index, lower_bound)) = stack.pop() {
394            if best
395                .bound()
396                .is_some_and(|worst| lower_bound > worst * (1.0 + PRUNE_SLACK))
397            {
398                continue;
399            }
400
401            let node = &self.nodes[index];
402
403            if !node.removed {
404                best.offer(space.distance(&node.state, query), index);
405            }
406
407            let (near, far) = self.children(index, query);
408            let gap = self.plane_gap(index, query);
409            stack.extend(far.map(|far| (far, gap)));
410            stack.extend(near.map(|near| (near, 0.0)));
411        }
412
413        out.clear();
414        out.extend(
415            best.into_sorted_ranks()
416                .into_iter()
417                .map(|index| self.nodes[index].id),
418        );
419    }
420
421    fn len(&self) -> usize {
422        self.live
423    }
424}
425
426impl<const N: usize> super::RemovableNeighbors<Euclidean<N>> for KdTree<N> {
427    /// Removes the node with `id` in `O(log n)` amortized.
428    ///
429    /// The node is first marked as removed and keeps splitting space. Once removed nodes
430    /// outnumber live ones, the tree is rebuilt balanced over the live nodes
431    /// ([`KdTree::rebalance`]), so memory and query cost track the live node count.
432    fn remove(&mut self, id: usize) -> bool {
433        let Some(index) = self.by_id.remove(&id) else {
434            return false;
435        };
436
437        self.nodes[index].removed = true;
438        self.live -= 1;
439
440        if self.needs_rebuild() {
441            self.rebalance();
442        }
443
444        true
445    }
446}
447
448#[cfg(test)]
449mod tests {
450    use super::*;
451    use crate::{LinearScan, RemovableNeighbors, Sampler, UniformBox};
452    use rand_core::{Rng, SeedableRng};
453
454    /// Fills a [`KdTree`] and a [`LinearScan`] with the same points, including duplicates.
455    fn twins(count: usize, seed: u64) -> (KdTree<3>, LinearScan<[f64; 3]>) {
456        let mut sampler = UniformBox::new([0.0; 3], [4.0; 3]);
457        let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(seed);
458        let mut kd = KdTree::default();
459        let mut linear = LinearScan::default();
460
461        for id in 0..count {
462            // Snapping to a coarse grid creates many exact ties and duplicate states.
463            let state = sampler.sample(&mut rng).map(libm::floor);
464            kd.insert(id * 3, state);
465            NearestNeighbors::<Euclidean<3>>::insert(&mut linear, id * 3, state);
466        }
467
468        (kd, linear)
469    }
470
471    #[test]
472    fn matches_linear_scan_exactly() {
473        let (kd, linear) = twins(300, 1);
474        let mut sampler = UniformBox::new([-1.0; 3], [5.0; 3]);
475        let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(2);
476
477        for i in 0..500 {
478            let mut query = sampler.sample(&mut rng);
479            if i % 2 == 0 {
480                query = query.map(libm::round);
481            }
482
483            assert_queries_agree(&kd, &linear, &query, i % 40);
484        }
485    }
486
487    /// Asserts that `kd` and `linear` give identical answers to every query type at `query`.
488    fn assert_queries_agree(
489        kd: &KdTree<3>,
490        linear: &LinearScan<[f64; 3]>,
491        query: &[f64; 3],
492        k: usize,
493    ) {
494        let space = Euclidean::<3>;
495        let (mut a, mut b) = (Vec::new(), Vec::new());
496
497        assert_eq!(kd.nearest(&space, query), linear.nearest(&space, query));
498        kd.within_radius(&space, query, 1.5, &mut a);
499        linear.within_radius(&space, query, 1.5, &mut b);
500        assert_eq!(a, b);
501        kd.k_nearest(&space, query, k, &mut a);
502        linear.k_nearest(&space, query, k, &mut b);
503        assert_eq!(a, b, "k = {k}");
504        assert_eq!(
505            NearestNeighbors::<Euclidean<3>>::len(kd),
506            NearestNeighbors::<Euclidean<3>>::len(linear)
507        );
508    }
509
510    #[test]
511    fn random_inserts_and_removals_across_rebuilds_match_linear_scan() {
512        let mut sampler = UniformBox::new([0.0; 3], [4.0; 3]);
513        let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(9);
514        let mut kd = KdTree::default();
515        let mut linear = LinearScan::default();
516        let mut stored = Vec::new();
517        let mut next_id = 0;
518
519        for step in 0..3000 {
520            let roll = rng.next_u64() % 10;
521
522            if roll < 4 && !stored.is_empty() {
523                let pick = usize::try_from(rng.next_u64() % 1_000_000).expect("small");
524                let id = stored.swap_remove(pick % stored.len());
525                assert!(kd.remove(id));
526                assert!(RemovableNeighbors::<Euclidean<3>>::remove(&mut linear, id));
527            } else if roll < 5 && next_id > 0 && !stored.contains(&(next_id - 1)) {
528                // Re-inserting a removed id makes it the newest node in both structures.
529                let state = sampler.sample(&mut rng).map(libm::floor);
530                kd.insert(next_id - 1, state);
531                NearestNeighbors::<Euclidean<3>>::insert(&mut linear, next_id - 1, state);
532                stored.push(next_id - 1);
533            } else {
534                let state = sampler.sample(&mut rng).map(libm::floor);
535                kd.insert(next_id, state);
536                NearestNeighbors::<Euclidean<3>>::insert(&mut linear, next_id, state);
537                stored.push(next_id);
538                next_id += 1;
539            }
540
541            let query = sampler.sample(&mut rng).map(libm::round);
542            assert_queries_agree(&kd, &linear, &query, step % 25);
543        }
544
545        assert!(kd.nodes.len() < next_id, "rebuilds dropped removed nodes");
546    }
547
548    #[test]
549    fn rebalance_bounds_the_depth_of_sorted_insertions() {
550        let mut kd = KdTree::<2>::default();
551        for id in 0..1024_u32 {
552            kd.insert(
553                usize::try_from(id).expect("small"),
554                [f64::from(id), f64::from(id * 37 % 1024)],
555            );
556        }
557
558        assert!(depth(&kd) > 50, "sorted insertion degrades the tree");
559        kd.rebalance();
560        assert!(depth(&kd) <= 11, "depth {}", depth(&kd));
561        assert_eq!(kd.nearest(&Euclidean::<2>, &[512.2, 511.0]), Some(512));
562    }
563
564    /// The number of nodes on the longest root-to-leaf path.
565    fn depth<const N: usize>(kd: &KdTree<N>) -> usize {
566        let mut deepest = 0;
567        let mut stack: Vec<(usize, usize)> = kd.root.map(|root| (root, 1)).into_iter().collect();
568
569        while let Some((index, level)) = stack.pop() {
570            deepest = deepest.max(level);
571            let node = &kd.nodes[index];
572            stack.extend(node.left.map(|child| (child, level + 1)));
573            stack.extend(node.right.map(|child| (child, level + 1)));
574        }
575
576        deepest
577    }
578
579    #[test]
580    fn removed_nodes_never_match() {
581        let space = Euclidean::<3>;
582        let (mut kd, _) = twins(50, 3);
583
584        let first = kd.nearest(&space, &[1.0, 1.0, 1.0]).expect("non-empty");
585        assert!(kd.remove(first));
586        assert!(!kd.remove(first), "removing twice is a no-op");
587        assert_ne!(kd.nearest(&space, &[1.0, 1.0, 1.0]), Some(first));
588        assert_eq!(NearestNeighbors::<Euclidean<3>>::len(&kd), 49);
589
590        let mut out = Vec::new();
591        kd.within_radius(&space, &[1.0, 1.0, 1.0], 10.0, &mut out);
592        assert_eq!(out.len(), 49);
593    }
594
595    #[test]
596    fn empty_and_zero_dimensional_trees_work() {
597        let empty = KdTree::<2>::default();
598        assert_eq!(empty.nearest(&Euclidean::<2>, &[0.0, 0.0]), None);
599
600        let mut point = KdTree::<0>::default();
601        point.insert(4, []);
602        point.insert(5, []);
603        assert_eq!(point.nearest(&Euclidean::<0>, &[]), Some(4));
604    }
605}