use core::fmt;
use polyzonotope::{Containment, SparsePolyZonotope};
use sampling_planning::{
Euclidean, LinearScan, NearestNeighbors, Path, Sampler, rand_core::Rng, unit_f64,
};
use crate::{Goal, Node, Obstacles, PolytopeGoal, Reach, SafetyVerdict, Steer, check_edge, node};
#[derive(Debug, Clone)]
pub struct Problem<R, Sa, const N: usize, G = PolytopeGoal<N>> {
pub reach: R,
pub obstacles: Obstacles,
pub sampler: Sa,
pub start: [f64; N],
pub start_set: SparsePolyZonotope,
pub goal: G,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Config {
pub goal_bias: f64,
}
impl Default for Config {
fn default() -> Self {
Self { goal_bias: 0.1 }
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Error {
StartNotSafe(SafetyVerdict),
GoalBiasOutOfRange,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::StartNotSafe(verdict) => write!(f, "start set is not proven safe ({verdict:?})"),
Self::GoalBiasOutOfRange => f.write_str("goal bias must be in [0, 1]"),
}
}
}
impl core::error::Error for Error {}
pub struct RobustRrt<R: Reach<N>, Sa, const N: usize, G = PolytopeGoal<N>> {
problem: Problem<R, Sa, N, G>,
config: Config,
nodes: Vec<Node<R::Control, N>>,
nn: LinearScan<[f64; N]>,
goal_node: Option<usize>,
cover: Vec<SparsePolyZonotope>,
}
impl<R, Sa, const N: usize, G> RobustRrt<R, Sa, N, G>
where
R: Reach<N> + Steer<N, R::Control>,
Sa: Sampler<[f64; N]>,
G: Goal<N>,
{
pub fn new(problem: Problem<R, Sa, N, G>, config: Config) -> Result<Self, Error> {
if !(0.0..=1.0).contains(&config.goal_bias) {
return Err(Error::GoalBiasOutOfRange);
}
let verdict = problem.obstacles.check_set(&problem.start_set);
if !verdict.is_safe() {
return Err(Error::StartNotSafe(verdict));
}
let root = Node {
nominal: problem.start,
set: problem.start_set.clone(),
parent: None,
control: None,
};
let mut planner = Self {
problem,
config,
nodes: Vec::new(),
nn: LinearScan::default(),
goal_node: None,
cover: Vec::new(),
};
planner.add(root);
Ok(planner)
}
pub fn step<Rg: Rng + ?Sized>(&mut self, rng: &mut Rg) -> bool {
let target = self.draw(rng);
let nearest = self
.nn
.nearest(&Euclidean::<N>, &target)
.expect("the tree always holds the root");
let parent = &self.nodes[nearest];
let (control, nominal) = self.problem.reach.steer(&parent.nominal, &target);
let (verdict, end) = check_edge(
&self.problem.reach,
&self.problem.obstacles,
&parent.set,
&control,
&mut self.cover,
);
let Some(set) = end.filter(|_| verdict.is_safe()) else {
return false;
};
self.add(Node {
nominal,
set,
parent: Some(nearest),
control: Some(control),
});
true
}
pub fn solve<Rg: Rng + ?Sized>(
&mut self,
max_iterations: usize,
rng: &mut Rg,
) -> Option<Path<[f64; N]>> {
for _ in 0..max_iterations {
if self.goal_node.is_some() {
break;
}
self.step(rng);
}
self.path()
}
#[must_use]
pub fn nodes(&self) -> &[Node<R::Control, N>] {
&self.nodes
}
#[must_use]
pub const fn goal_node(&self) -> Option<usize> {
self.goal_node
}
#[must_use]
pub const fn problem(&self) -> &Problem<R, Sa, N, G> {
&self.problem
}
#[must_use]
pub fn branch(&self, node: usize) -> Vec<usize> {
node::branch(&self.nodes, node)
}
#[must_use]
pub fn path(&self) -> Option<Path<[f64; N]>> {
Some(node::nominal_path(&self.nodes, self.goal_node?))
}
fn draw<Rg: Rng + ?Sized>(&mut self, rng: &mut Rg) -> [f64; N] {
if unit_f64(rng) < self.config.goal_bias {
self.problem.goal.center()
} else {
self.problem.sampler.sample(rng)
}
}
fn add(&mut self, node: Node<R::Control, N>) {
let id = self.nodes.len();
if self.goal_node.is_none() && self.reaches_goal(&node.set) {
self.goal_node = Some(id);
}
NearestNeighbors::<Euclidean<N>>::insert(&mut self.nn, id, node.nominal);
self.nodes.push(node);
}
fn reaches_goal(&self, set: &SparsePolyZonotope) -> bool {
self.problem.goal.containment(set) == Containment::Inside
}
}