Skip to main content

KdTree

Struct KdTree 

Source
pub struct KdTree<const N: usize> { /* private fields */ }
Expand description

A k-d tree over [f64; N] states for the Euclidean metric.

Nodes are inserted one at a time without rebalancing. The split axis cycles with the depth. Planners insert random samples, which keeps the tree balanced in expectation; a sorted insertion order degrades it to a list until KdTree::rebalance is called.

Removal (RemovableNeighbors) finds the node through an id index, marks it, and rebuilds the tree balanced once removed nodes outnumber live ones.

Queries return exactly what LinearScan returns, including its tie breaking toward the earliest inserted state, because both compare the same StateSpace::distance values. Expected cost per query is O(log n) in low dimensions; beyond roughly ten dimensions the pruning stops paying off and a linear scan is as fast.

§Examples

use sampling_planning::{Euclidean, KdTree, NearestNeighbors};

let mut tree = KdTree::<2>::default();
tree.insert(7, [0.0, 0.0]);
tree.insert(8, [3.0, 4.0]);

assert_eq!(tree.nearest(&Euclidean::<2>, &[2.5, 3.0]), Some(8));

Implementations§

Source§

impl<const N: usize> KdTree<N>

Source

pub fn rebalance(&mut self)

Rebuilds the tree as a balanced k-d tree over the live nodes, dropping removed ones.

Each subtree splits at the median of its states along the axis of its depth, so the depth is O(log n) whatever the insertion order was. Insertion ranks keep their relative order, so query results do not change. Costs O(n log^2 n).

Removal calls this automatically once removed nodes outnumber live ones. Call it by hand after inserting many states in sorted order, which degrades the incremental tree to a list.

§Examples
use sampling_planning::{Euclidean, KdTree, NearestNeighbors};

let mut tree = KdTree::<1>::default();
for id in 0..100 {
    tree.insert(id, [f64::from(u32::try_from(id).expect("small"))]);
}

tree.rebalance();
assert_eq!(tree.nearest(&Euclidean::<1>, &[41.2]), Some(41));

Trait Implementations§

Source§

impl<const N: usize> Clone for KdTree<N>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<const N: usize> Debug for KdTree<N>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<const N: usize> Default for KdTree<N>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<const N: usize> NearestNeighbors<Euclidean<N>> for KdTree<N>

Source§

fn insert(&mut self, id: usize, state: [f64; N])

Adds a node with the given id.
Source§

fn nearest(&self, space: &Euclidean<N>, query: &[f64; N]) -> Option<usize>

The id of the node closest to query, or None if the structure is empty.
Source§

fn within_radius( &self, space: &Euclidean<N>, query: &[f64; N], radius: f64, out: &mut Vec<usize>, )

Replaces the contents of out with the ids of all nodes within radius of query, in insertion order.
Source§

fn k_nearest( &self, space: &Euclidean<N>, query: &[f64; N], k: usize, out: &mut Vec<usize>, )

Replaces the contents of out with the ids of the k nodes closest to query, closest first. Read more
Source§

fn len(&self) -> usize

The number of stored nodes.
Source§

fn is_empty(&self) -> bool

Whether no node is stored.
Source§

impl<const N: usize> RemovableNeighbors<Euclidean<N>> for KdTree<N>

Source§

fn remove(&mut self, id: usize) -> bool

Removes the node with id in O(log n) amortized.

The node is first marked as removed and keeps splitting space. Once removed nodes outnumber live ones, the tree is rebuilt balanced over the live nodes (KdTree::rebalance), so memory and query cost track the live node count.

Auto Trait Implementations§

§

impl<const N: usize> Forget for KdTree<N>

§

impl<const N: usize> Freeze for KdTree<N>
where Vec<Node<N>>: Freeze,

§

impl<const N: usize> Move for KdTree<N>

§

impl<const N: usize> RefUnwindSafe for KdTree<N>
where Vec<Node<N>>: RefUnwindSafe,

§

impl<const N: usize> Send for KdTree<N>
where Vec<Node<N>>: Send,

§

impl<const N: usize> Sync for KdTree<N>
where Vec<Node<N>>: Sync,

§

impl<const N: usize> Unpin for KdTree<N>
where Vec<Node<N>>: Unpin,

§

impl<const N: usize> UnsafeUnpin for KdTree<N>
where Vec<Node<N>>: UnsafeUnpin,

§

impl<const N: usize> UnwindSafe for KdTree<N>
where Vec<Node<N>>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.