Skip to main content

sampling_planning/nearest/
linear.rs

1//! Brute-force nearest neighbors.
2
3use alloc::vec::Vec;
4
5use super::{NearestNeighbors, RemovableNeighbors, k_best::KBest};
6use crate::StateSpace;
7
8/// Checks every stored state on each query: O(n) per query, no preprocessing.
9///
10/// Exact for any metric and fine for a few thousand nodes. Use a spatial index for more.
11#[derive(Debug, Clone)]
12pub struct LinearScan<S> {
13    /// Stored nodes as `(id, state)` in insertion order.
14    entries: Vec<(usize, S)>,
15}
16
17impl<S> Default for LinearScan<S> {
18    fn default() -> Self {
19        Self {
20            entries: Vec::new(),
21        }
22    }
23}
24
25impl<Sp: StateSpace> NearestNeighbors<Sp> for LinearScan<Sp::State> {
26    fn insert(&mut self, id: usize, state: Sp::State) {
27        self.entries.push((id, state));
28    }
29
30    fn nearest(&self, space: &Sp, query: &Sp::State) -> Option<usize> {
31        let mut best: Option<(usize, f64)> = None;
32
33        for (id, state) in &self.entries {
34            let distance = space.distance(state, query);
35
36            // Strict comparison keeps the earliest node on ties and skips NaN distances.
37            if best.is_none_or(|(_, best_distance)| distance < best_distance) {
38                best = Some((*id, distance));
39            }
40        }
41
42        best.map(|(id, _)| id)
43    }
44
45    fn within_radius(&self, space: &Sp, query: &Sp::State, radius: f64, out: &mut Vec<usize>) {
46        out.clear();
47        out.extend(
48            self.entries
49                .iter()
50                .filter(|(_, state)| space.distance(state, query) <= radius)
51                .map(|(id, _)| *id),
52        );
53    }
54
55    fn k_nearest(&self, space: &Sp, query: &Sp::State, k: usize, out: &mut Vec<usize>) {
56        let mut best = KBest::new(k);
57
58        for (rank, (_, state)) in self.entries.iter().enumerate() {
59            best.offer(space.distance(state, query), rank);
60        }
61
62        out.clear();
63        out.extend(
64            best.into_sorted_ranks()
65                .into_iter()
66                .map(|rank| self.entries[rank].0),
67        );
68    }
69
70    fn len(&self) -> usize {
71        self.entries.len()
72    }
73}
74
75impl<Sp: StateSpace> RemovableNeighbors<Sp> for LinearScan<Sp::State> {
76    /// Removes the node with `id` in `O(n)`, keeping the insertion order of the rest.
77    fn remove(&mut self, id: usize) -> bool {
78        let Some(index) = self.entries.iter().position(|(entry, _)| *entry == id) else {
79            return false;
80        };
81
82        self.entries.remove(index);
83
84        true
85    }
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91    use crate::Euclidean;
92    use alloc::vec;
93
94    /// A structure holding the 1D points 0, 2, 4 and 2 again with ids 10 to 13.
95    fn points() -> LinearScan<[f64; 1]> {
96        let mut nn = LinearScan::default();
97
98        for (id, x) in [(10, 0.0), (11, 2.0), (12, 4.0), (13, 2.0)] {
99            NearestNeighbors::<Euclidean<1>>::insert(&mut nn, id, [x]);
100        }
101
102        nn
103    }
104
105    #[test]
106    fn nearest_prefers_earliest_on_ties() {
107        let nn = points();
108
109        assert_eq!(nn.nearest(&Euclidean::<1>, &[2.1]), Some(11));
110        assert_eq!(nn.nearest(&Euclidean::<1>, &[-5.0]), Some(10));
111        assert_eq!(NearestNeighbors::<Euclidean<1>>::len(&nn), 4);
112    }
113
114    #[test]
115    fn nearest_of_empty_is_none() {
116        let nn = LinearScan::<[f64; 1]>::default();
117
118        assert_eq!(nn.nearest(&Euclidean::<1>, &[0.0]), None);
119    }
120
121    #[test]
122    fn within_radius_is_inclusive_and_ordered() {
123        let mut out = vec![99];
124        points().within_radius(&Euclidean::<1>, &[3.0], 1.0, &mut out);
125
126        assert_eq!(out, [11, 12, 13]);
127    }
128
129    #[test]
130    fn k_nearest_orders_by_distance_then_insertion() {
131        let nn = points();
132        let mut out = vec![99];
133
134        nn.k_nearest(&Euclidean::<1>, &[2.0], 3, &mut out);
135        assert_eq!(
136            out,
137            [11, 13, 10],
138            "the tie at the cut goes to the earlier node"
139        );
140
141        nn.k_nearest(&Euclidean::<1>, &[2.9], 10, &mut out);
142        assert_eq!(out, [11, 13, 12, 10]);
143
144        nn.k_nearest(&Euclidean::<1>, &[2.9], 0, &mut out);
145        assert_eq!(out, [] as [usize; 0]);
146    }
147
148    #[test]
149    fn remove_forgets_one_node() {
150        let mut nn = points();
151
152        assert!(RemovableNeighbors::<Euclidean<1>>::remove(&mut nn, 11));
153        assert!(!RemovableNeighbors::<Euclidean<1>>::remove(&mut nn, 11));
154        assert_eq!(nn.nearest(&Euclidean::<1>, &[2.1]), Some(13));
155    }
156}