Skip to main content

sampling_planning/
nearest.rs

1//! Nearest-neighbor structures over planner nodes.
2
3mod k_best;
4mod kd_tree;
5mod linear;
6
7use alloc::vec::Vec;
8
9use crate::StateSpace;
10pub use kd_tree::KdTree;
11pub use linear::LinearScan;
12
13/// Stores planner nodes by id and answers proximity queries under a [`StateSpace`] metric.
14///
15/// Ids are the planner's node ids, so the structure needs no back-pointers. Queries break
16/// ties toward the earliest inserted state, which keeps seeded runs reproducible.
17pub trait NearestNeighbors<Sp: StateSpace> {
18    /// Adds a node with the given id.
19    fn insert(&mut self, id: usize, state: Sp::State);
20
21    /// The id of the node closest to `query`, or `None` if the structure is empty.
22    fn nearest(&self, space: &Sp, query: &Sp::State) -> Option<usize>;
23
24    /// Replaces the contents of `out` with the ids of all nodes within `radius` of `query`,
25    /// in insertion order.
26    fn within_radius(&self, space: &Sp, query: &Sp::State, radius: f64, out: &mut Vec<usize>);
27
28    /// Replaces the contents of `out` with the ids of the `k` nodes closest to `query`, closest
29    /// first.
30    ///
31    /// Equal distances are ordered by insertion, earliest first, and the same rule decides which
32    /// nodes make the cut at the `k`-th place. Fewer than `k` ids are returned only when fewer
33    /// nodes are stored. Nodes at a NaN distance are never returned.
34    fn k_nearest(&self, space: &Sp, query: &Sp::State, k: usize, out: &mut Vec<usize>);
35
36    /// The number of stored nodes.
37    fn len(&self) -> usize;
38
39    /// Whether no node is stored.
40    fn is_empty(&self) -> bool {
41        self.len() == 0
42    }
43}
44
45/// A [`NearestNeighbors`] structure that can also forget nodes.
46///
47/// Planners that keep only a sparse set of active nodes (SST) need this. It is a separate trait
48/// so that structures that cannot remove cheaply still work with every other planner.
49pub trait RemovableNeighbors<Sp: StateSpace>: NearestNeighbors<Sp> {
50    /// Removes the node with `id`. Returns whether such a node was stored.
51    ///
52    /// Ids should be unique among the stored nodes; if an id was inserted twice, which of the
53    /// two nodes is removed depends on the structure. A removed id may be inserted again, and
54    /// then counts as the newest node for tie breaking.
55    fn remove(&mut self, id: usize) -> bool;
56}