use alloc::vec::Vec;
use rand_core::Rng;
use super::{
Error,
march::{Batch, Direction, Status, Wave},
};
use crate::radius::{dimension_f64, unit_ball_volume};
use crate::{GoalRegion, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, ValidityChecker};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Termination {
FirstMeeting,
#[default]
Optimal,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BfmtStarConfig {
pub gamma: f64,
pub termination: Termination,
}
impl BfmtStarConfig {
#[must_use]
pub const fn new(gamma: f64) -> Self {
Self {
gamma,
termination: Termination::Optimal,
}
}
#[must_use]
pub fn gamma_lower_bound(dimension: usize, free_volume: f64) -> f64 {
let d = dimension_f64(dimension);
4.0 * libm::pow(1.0 / d, 1.0 / d) * libm::pow(free_volume / unit_ball_volume(d), 1.0 / d)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Side {
Start,
Goal,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Connection {
node: usize,
cost: f64,
through_goal_tree: bool,
}
#[derive(Debug, Clone)]
pub struct BfmtStar<Sp: StateSpace, Sa, C, N = LinearScan<<Sp as StateSpace>::State>> {
space: Sp,
sampler: Sa,
checker: C,
config: BfmtStarConfig,
nn: N,
}
impl<Sp, Sa, C> BfmtStar<Sp, Sa, C>
where
Sp: StateSpace,
Sa: Sampler<Sp::State>,
C: ValidityChecker<Sp>,
{
pub fn new(space: Sp, sampler: Sa, checker: C, config: BfmtStarConfig) -> Result<Self, Error> {
Self::with_nearest_neighbors(space, sampler, checker, config, LinearScan::default())
}
}
impl<Sp, Sa, C, N> BfmtStar<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: BfmtStarConfig,
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 validity = self.checker.check_state(goal.center());
if !validity.is_valid() {
return Err(Error::InvalidGoal(validity));
}
if goal.contains(&self.space, start) {
return Ok(Some(Path {
states: alloc::vec![start.clone()],
cost: 0.0,
}));
}
let mut states = alloc::vec![start.clone()];
states.extend(
(0..samples)
.map(|_| self.sampler.sample(rng))
.filter(|state| self.checker.check_state(state).is_valid()),
);
states.push(goal.center().clone());
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 n = batch.len();
let mut march = Bidirectional {
start: Wave::new(n, 0, Direction::Outward),
goal: Wave::new(n, n - 1, Direction::Inward),
best: None,
};
let mut side = Side::Start;
while let Some(z) = march.wave_mut(side).peek_open() {
let fresh = march.wave_mut(side).expand(&mut batch, z);
march.record_connections(&batch, goal, side, &fresh);
if self.should_stop(&march, side, z) {
break;
}
side = march.next_side(side);
}
march.best.map(|best| march.path(&batch, best))
}
fn should_stop(&self, march: &Bidirectional, side: Side, z: usize) -> bool {
match self.config.termination {
Termination::FirstMeeting => march.best.is_some(),
Termination::Optimal => march.wave(other(side)).status[z] == Status::Closed,
}
}
}
struct Bidirectional {
start: Wave,
goal: Wave,
best: Option<Connection>,
}
impl Bidirectional {
const fn wave(&self, side: Side) -> &Wave {
match side {
Side::Start => &self.start,
Side::Goal => &self.goal,
}
}
const fn wave_mut(&mut self, side: Side) -> &mut Wave {
match side {
Side::Start => &mut self.start,
Side::Goal => &mut self.goal,
}
}
fn next_side(&mut self, side: Side) -> Side {
if self.wave_mut(other(side)).peek_open().is_some() {
other(side)
} else {
side
}
}
fn record_connections<Sp: StateSpace, C, N>(
&mut self,
batch: &Batch<'_, Sp, C, N>,
goal: &GoalRegion<Sp::State>,
side: Side,
fresh: &[usize],
) {
for &x in fresh {
if self.goal.status[x] != Status::Unvisited && self.start.status[x] != Status::Unvisited
{
self.offer(x, self.start.cost[x] + self.goal.cost[x], true);
}
if side == Side::Start && goal.contains(batch.space, &batch.states[x]) {
self.offer(x, self.start.cost[x], false);
}
}
}
fn offer(&mut self, node: usize, cost: f64, through_goal_tree: bool) {
if self.best.is_none_or(|best| cost < best.cost) {
self.best = Some(Connection {
node,
cost,
through_goal_tree,
});
}
}
fn path<Sp: StateSpace, C, N>(
&self,
batch: &Batch<'_, Sp, C, N>,
best: Connection,
) -> Path<Sp::State> {
let mut nodes = self.start.branch(best.node);
nodes.reverse();
if best.through_goal_tree {
nodes.extend(self.goal.branch(best.node).into_iter().skip(1));
}
Path {
states: nodes
.iter()
.map(|&node| batch.states[node].clone())
.collect(),
cost: best.cost,
}
}
}
const fn other(side: Side) -> Side {
match side {
Side::Start => Side::Goal,
Side::Goal => Side::Start,
}
}