use alloc::vec::Vec;
use rand_core::Rng;
use super::{Error, growth::Growth, targets::draw_target};
use crate::{
LinearScan, NearestNeighbors, Path, Problem, Sampler, StateSpace, Steering, ValidityChecker,
radius::{
dimension_f64, k_constant_lower_bound, k_nearest_count, shrinking_radius, unit_ball_volume,
},
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RrtStarConfig {
pub goal_bias: f64,
pub gamma: f64,
pub k_nearest: Option<f64>,
pub max_radius: f64,
pub informed: bool,
}
pub const INFORMED_ATTEMPTS: usize = 64;
impl RrtStarConfig {
#[must_use]
pub const fn new(gamma: f64, max_radius: f64) -> Self {
Self {
goal_bias: 0.05,
gamma,
k_nearest: None,
max_radius,
informed: false,
}
}
#[must_use]
pub const fn k_nearest(k_constant: f64, max_radius: f64) -> Self {
Self {
k_nearest: Some(k_constant),
..Self::new(1.0, max_radius)
}
}
#[must_use]
pub fn k_constant_lower_bound(dimension: usize) -> f64 {
libm::pow(2.0, dimension_f64(dimension) + 1.0) * k_constant_lower_bound(dimension)
}
#[must_use]
pub const fn informed(self) -> Self {
Self {
informed: true,
..self
}
}
pub(super) fn validate(&self) -> Result<(), Error> {
let constant = self.k_nearest.unwrap_or(self.gamma);
if !(constant.is_finite() && constant > 0.0) {
return Err(Error::InvalidGamma);
}
if self.max_radius.is_nan() || self.max_radius <= 0.0 {
return Err(Error::InvalidMaxRadius);
}
Ok(())
}
pub(super) fn neighbors<'a, Sp, N>(
&self,
space: &Sp,
nn: &N,
state: &Sp::State,
n: usize,
state_of: impl Fn(usize) -> &'a Sp::State,
out: &mut Vec<usize>,
) where
Sp: StateSpace,
Sp::State: 'a,
N: NearestNeighbors<Sp>,
{
let Some(k_constant) = self.k_nearest else {
let radius = shrinking_radius(self.gamma, n, dimension_f64(space.dimension()));
nn.within_radius(space, state, radius.min(self.max_radius), out);
return;
};
nn.k_nearest(space, state, k_nearest_count(k_constant, n), out);
if self.max_radius.is_finite() {
out.retain(|&id| space.distance(state_of(id), state) <= self.max_radius);
}
}
#[must_use]
pub fn gamma_lower_bound(dimension: usize, free_volume: f64) -> f64 {
let d = dimension_f64(dimension);
libm::pow(
2.0 * (1.0 + 1.0 / d) * free_volume / unit_ball_volume(d),
1.0 / d,
)
}
}
#[derive(Clone)]
pub struct RrtStar<Sp: StateSpace, Sa, C, St, N = LinearScan<<Sp as StateSpace>::State>> {
growth: Growth<Sp, Sa, C, St, N>,
config: RrtStarConfig,
near: Vec<usize>,
}
impl<Sp, Sa, C, St> RrtStar<Sp, Sa, C, St>
where
Sp: StateSpace,
Sa: Sampler<Sp::State>,
C: ValidityChecker<Sp>,
St: Steering<Sp>,
{
pub fn new(problem: Problem<Sp, Sa, C, St>, config: RrtStarConfig) -> Result<Self, Error> {
Self::with_nearest_neighbors(problem, config, LinearScan::default())
}
}
impl<Sp, Sa, C, St, N> RrtStar<Sp, Sa, C, St, N>
where
Sp: StateSpace,
Sa: Sampler<Sp::State>,
C: ValidityChecker<Sp>,
St: Steering<Sp>,
N: NearestNeighbors<Sp>,
{
pub fn with_nearest_neighbors(
problem: Problem<Sp, Sa, C, St>,
config: RrtStarConfig,
nn: N,
) -> Result<Self, Error> {
config.validate()?;
Ok(Self {
growth: Growth::new(problem, config.goal_bias, nn)?,
config,
near: Vec::new(),
})
}
pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
let target = self.draw_target(rng);
let (nearest, new) = self.growth.propose_toward(&target);
if !self.growth.is_motion_valid(nearest, &new) {
return false;
}
let mut near = core::mem::take(&mut self.near);
self.neighbors(&new, &mut near);
let (parent, cost) = self.choose_parent(nearest, &new, &near);
let id = self.growth.add(new, parent, cost);
self.rewire(id, &near);
self.near = near;
true
}
fn draw_target<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Sp::State {
let bound = self.informed_bound();
draw_target(&mut self.growth.problem, self.growth.goal_bias, bound, rng)
}
fn informed_bound(&self) -> Option<f64> {
if !self.config.informed {
return None;
}
let best = self.growth.best_cost()?;
Some(best + self.growth.problem.goal.tolerance())
}
fn neighbors(&self, state: &Sp::State, near: &mut Vec<usize>) {
let tree = &self.growth.tree;
self.config.neighbors(
&self.growth.problem.space,
&self.growth.nn,
state,
tree.len() + 1,
|id| tree.state(id),
near,
);
}
fn choose_parent(&self, nearest: usize, new: &Sp::State, near: &[usize]) -> (usize, f64) {
let mut best = (nearest, self.growth.cost_via(nearest, new));
for &candidate in near {
let cost = self.growth.cost_via(candidate, new);
if cost < best.1 && self.growth.is_motion_valid(candidate, new) {
best = (candidate, cost);
}
}
best
}
fn rewire(&mut self, id: usize, near: &[usize]) {
let space = &self.growth.problem.space;
for &node in near {
let tree = &self.growth.tree;
let cost = self.growth.cost_via(id, tree.state(node));
if cost < tree.cost(node) && self.is_rewire_valid(id, node) {
self.growth.tree.reparent(space, node, id, cost);
}
}
}
fn is_rewire_valid(&self, from: usize, to: usize) -> bool {
self.growth
.is_motion_valid(from, self.growth.tree.state(to))
}
pub fn run<R: Rng + ?Sized>(&mut self, iterations: usize, rng: &mut R) {
for _ in 0..iterations {
self.step(rng);
}
}
#[must_use]
pub fn best_path(&self) -> Option<Path<Sp::State>> {
self.growth.best_path()
}
#[must_use]
pub fn node_count(&self) -> usize {
self.growth.tree.len()
}
}