use alloc::vec::Vec;
use rand_core::Rng;
use super::{
Error,
march::{Batch, Direction, Wave},
};
use crate::radius::{dimension_f64, unit_ball_volume};
use crate::{GoalRegion, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, ValidityChecker};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FmtStarConfig {
pub gamma: f64,
}
impl FmtStarConfig {
#[must_use]
pub fn gamma_lower_bound(dimension: usize, free_volume: f64) -> f64 {
let d = dimension_f64(dimension);
2.0 * libm::pow(1.0 / d, 1.0 / d) * libm::pow(free_volume / unit_ball_volume(d), 1.0 / d)
}
}
#[derive(Debug, Clone)]
pub struct FmtStar<Sp: StateSpace, Sa, C, N = LinearScan<<Sp as StateSpace>::State>> {
space: Sp,
sampler: Sa,
checker: C,
config: FmtStarConfig,
nn: N,
}
impl<Sp, Sa, C> FmtStar<Sp, Sa, C>
where
Sp: StateSpace,
Sa: Sampler<Sp::State>,
C: ValidityChecker<Sp>,
{
pub fn new(space: Sp, sampler: Sa, checker: C, config: FmtStarConfig) -> Result<Self, Error> {
Self::with_nearest_neighbors(space, sampler, checker, config, LinearScan::default())
}
}
impl<Sp, Sa, C, N> FmtStar<Sp, Sa, C, N>
where
Sp: StateSpace,
Sa: Sampler<Sp::State>,
C: ValidityChecker<Sp>,
N: NearestNeighbors<Sp> + Clone,
{
pub fn with_nearest_neighbors(
space: Sp,
sampler: Sa,
checker: C,
config: FmtStarConfig,
nn: N,
) -> Result<Self, Error> {
if !(config.gamma.is_finite() && config.gamma > 0.0) {
return Err(Error::InvalidRadius);
}
Ok(Self {
space,
sampler,
checker,
config,
nn,
})
}
pub fn plan<R: Rng + ?Sized>(
&mut self,
start: &Sp::State,
goal: &GoalRegion<Sp::State>,
samples: usize,
rng: &mut R,
) -> Result<Option<Path<Sp::State>>, Error> {
let validity = self.checker.check_state(start);
if !validity.is_valid() {
return Err(Error::InvalidStart(validity));
}
let states = self.draw_batch(start, goal, samples, rng);
Ok(self.march(states, goal))
}
fn march(
&self,
states: Vec<Sp::State>,
goal: &GoalRegion<Sp::State>,
) -> Option<Path<Sp::State>> {
let mut batch = Batch::new(
&self.space,
&self.checker,
self.config.gamma,
states,
self.nn.clone(),
);
let mut wave = Wave::new(batch.len(), 0, Direction::Outward);
while let Some(z) = wave.peek_open() {
if goal.contains(&self.space, &batch.states[z]) {
let mut states: Vec<_> = wave
.branch(z)
.into_iter()
.map(|node| batch.states[node].clone())
.collect();
states.reverse();
return Some(Path {
states,
cost: wave.cost[z],
});
}
wave.expand(&mut batch, z);
}
None
}
fn draw_batch<R: Rng + ?Sized>(
&mut self,
start: &Sp::State,
goal: &GoalRegion<Sp::State>,
samples: usize,
rng: &mut R,
) -> Vec<Sp::State> {
let mut states = alloc::vec![start.clone()];
for _ in 0..samples {
let state = self.sampler.sample(rng);
if self.checker.check_state(&state).is_valid() {
states.push(state);
}
}
if self.checker.check_state(goal.center()).is_valid() {
states.push(goal.center().clone());
}
states
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Euclidean, Validity};
struct Replay(Vec<[f64; 2]>, usize);
impl Sampler<[f64; 2]> for Replay {
fn sample<R: Rng + ?Sized>(&mut self, _: &mut R) -> [f64; 2] {
self.1 += 1;
self.0[(self.1 - 1) % self.0.len()]
}
}
struct Hole;
impl ValidityChecker<Euclidean<2>> for Hole {
fn check_state(&self, s: &[f64; 2]) -> Validity {
if libm::hypot(s[0] - 5.0, s[1] - 5.0) < 0.1 {
Validity::Invalid
} else {
Validity::Valid
}
}
fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], to: &[f64; 2]) -> Validity {
self.check_state(to)
}
}
#[test]
fn hand_checked_batch_stops_at_the_cheapest_goal_node() {
let sampler = Replay(alloc::vec![[5.0, 5.0], [8.8, 9.0], [3.0, 3.0]], 0);
let mut fmt = FmtStar::new(
Euclidean::<2>,
sampler,
Hole,
FmtStarConfig { gamma: 100.0 },
)
.expect("valid");
let goal = GoalRegion::new([9.0, 9.0], 0.5);
let mut rng = rand_pcg::Pcg64Mcg::new(1);
let path = fmt
.plan(&[1.0, 1.0], &goal, 3, &mut rng)
.expect("valid")
.expect("solved");
assert_eq!(path.states, [[1.0, 1.0], [8.8, 9.0]]);
assert!((path.cost - libm::hypot(7.8, 8.0)).abs() < 1e-12);
assert_eq!(
fmt.plan(&[5.0, 5.0], &goal, 3, &mut rng),
Err(Error::InvalidStart(Validity::Invalid))
);
}
}