use alloc::vec::Vec;
use rand_core::Rng;
use super::{Error, targets::draw_target, tree::Tree};
use crate::{NearestNeighbors, Path, Problem, Sampler, StateSpace, Steering, ValidityChecker};
#[derive(Clone)]
pub(super) struct Growth<Sp: StateSpace, Sa, C, St, N> {
pub(super) problem: Problem<Sp, Sa, C, St>,
pub(super) tree: Tree<Sp::State>,
pub(super) nn: N,
goal_nodes: Vec<usize>,
pub(super) goal_bias: f64,
}
impl<Sp, Sa, C, St, N> Growth<Sp, Sa, C, St, N>
where
Sp: StateSpace,
Sa: Sampler<Sp::State>,
C: ValidityChecker<Sp>,
St: Steering<Sp>,
N: NearestNeighbors<Sp>,
{
pub(super) fn new(
problem: Problem<Sp, Sa, C, St>,
goal_bias: f64,
mut nn: N,
) -> Result<Self, Error> {
if !(0.0..=1.0).contains(&goal_bias) {
return Err(Error::GoalBiasOutOfRange);
}
let validity = problem.checker.check_state(&problem.start);
if !validity.is_valid() {
return Err(Error::InvalidStart(validity));
}
let start = problem.start.clone();
let goal_nodes = if problem.goal.contains(&problem.space, &start) {
alloc::vec![0]
} else {
Vec::new()
};
nn.insert(0, start.clone());
Ok(Self {
tree: Tree::new(start),
problem,
nn,
goal_nodes,
goal_bias,
})
}
pub(super) fn propose<R: Rng + ?Sized>(&mut self, rng: &mut R) -> (usize, Sp::State) {
let target = self.draw(rng);
self.propose_toward(&target)
}
pub(super) fn propose_toward(&self, target: &Sp::State) -> (usize, Sp::State) {
let nearest = self
.nn
.nearest(&self.problem.space, target)
.expect("the tree always holds the root");
let new =
self.problem
.steering
.steer(&self.problem.space, self.tree.state(nearest), target);
(nearest, new)
}
pub(super) fn draw<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Sp::State {
draw_target(&mut self.problem, self.goal_bias, None, rng)
}
pub(super) fn is_motion_valid(&self, from: usize, to: &Sp::State) -> bool {
self.problem
.checker
.check_motion(&self.problem.space, self.tree.state(from), to)
.is_valid()
}
pub(super) fn cost_via(&self, from: usize, to: &Sp::State) -> f64 {
self.tree.cost(from) + self.problem.space.distance(self.tree.state(from), to)
}
pub(super) fn add(&mut self, state: Sp::State, parent: usize, cost: f64) -> usize {
if self.problem.goal.contains(&self.problem.space, &state) {
self.goal_nodes.push(self.tree.len());
}
let id = self.tree.add(state.clone(), parent, cost);
self.nn.insert(id, state);
id
}
pub(super) fn has_solution(&self) -> bool {
!self.goal_nodes.is_empty()
}
pub(super) fn best_cost(&self) -> Option<f64> {
self.best_goal_node().map(|id| self.tree.cost(id))
}
pub(super) fn best_path(&self) -> Option<Path<Sp::State>> {
self.best_goal_node().map(|id| Path {
states: self.tree.path_to(id),
cost: self.tree.cost(id),
})
}
fn best_goal_node(&self) -> Option<usize> {
let mut best: Option<usize> = None;
for &id in &self.goal_nodes {
if best.is_none_or(|b| self.tree.cost(id) < self.tree.cost(b)) {
best = Some(id);
}
}
best
}
}