use alloc::vec::Vec;
use crate::StateSpace;
#[derive(Debug, Clone)]
pub(super) struct Tree<S> {
nodes: Vec<Node<S>>,
}
#[derive(Debug, Clone)]
struct Node<S> {
state: S,
parent: Option<usize>,
cost: f64,
children: Vec<usize>,
}
impl<S: Clone> Tree<S> {
pub(super) fn new(state: S) -> Self {
Self {
nodes: alloc::vec![Node {
state,
parent: None,
cost: 0.0,
children: Vec::new(),
}],
}
}
pub(super) fn len(&self) -> usize {
self.nodes.len()
}
pub(super) fn state(&self, id: usize) -> &S {
&self.nodes[id].state
}
pub(super) fn cost(&self, id: usize) -> f64 {
self.nodes[id].cost
}
pub(super) fn add(&mut self, state: S, parent: usize, cost: f64) -> usize {
let id = self.nodes.len();
self.nodes.push(Node {
state,
parent: Some(parent),
cost,
children: Vec::new(),
});
self.nodes[parent].children.push(id);
id
}
pub(super) fn reparent<Sp>(&mut self, space: &Sp, id: usize, parent: usize, cost: f64)
where
Sp: StateSpace<State = S>,
{
if let Some(old) = self.nodes[id].parent {
self.nodes[old].children.retain(|&child| child != id);
}
self.nodes[id].parent = Some(parent);
self.nodes[id].cost = cost;
self.nodes[parent].children.push(id);
self.propagate_costs(space, id);
}
fn propagate_costs<Sp>(&mut self, space: &Sp, id: usize)
where
Sp: StateSpace<State = S>,
{
let mut stack = self.nodes[id].children.clone();
while let Some(child) = stack.pop() {
let parent = self.nodes[child].parent.expect("a child has a parent");
let edge = space.distance(&self.nodes[parent].state, &self.nodes[child].state);
self.nodes[child].cost = self.nodes[parent].cost + edge;
stack.extend_from_slice(&self.nodes[child].children);
}
}
pub(super) fn path_to(&self, id: usize) -> Vec<S> {
let mut states = Vec::new();
let mut current = Some(id);
while let Some(node) = current {
states.push(self.nodes[node].state.clone());
current = self.nodes[node].parent;
}
states.reverse();
states
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Euclidean;
#[test]
fn reparent_updates_descendants_and_children() {
let space = Euclidean::<1>;
let mut tree = Tree::new([0.0]);
let a = tree.add([5.0], 0, 5.0);
let b = tree.add([6.0], a, 6.0);
let c = tree.add([7.0], b, 7.0);
let shortcut = tree.add([5.5], 0, 5.5);
tree.reparent(&space, b, shortcut, 6.0);
assert_eq!(tree.nodes[b].parent, Some(shortcut));
assert_eq!(tree.nodes[a].children, []);
tree.reparent(&space, shortcut, 0, 1.0);
assert!((tree.cost(b) - 1.5).abs() < 1e-12);
assert!((tree.cost(c) - 2.5).abs() < 1e-12);
assert_eq!(tree.path_to(c), [[0.0], [5.5], [6.0], [7.0]]);
}
}