#[cfg(test)]
mod tests;
use core::fmt;
use polyzonotope::{Containment, SparsePolyZonotope};
use sampling_planning::{
Euclidean, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, rand_core::Rng, unit_f64,
};
pub use crate::robust_rrt::Problem;
use crate::{Cost, Goal, Node, PolytopeGoal, Reach, SafetyVerdict, Steer, check_edge, node};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Config {
pub goal_bias: f64,
pub gamma: f64,
pub max_radius: f64,
pub rewire_budget: usize,
pub cost: Cost,
}
impl Config {
#[must_use]
pub const fn new(gamma: f64, max_radius: f64) -> Self {
Self {
goal_bias: 0.1,
gamma,
max_radius,
rewire_budget: 64,
cost: Cost::Length,
}
}
#[must_use]
pub const fn unbounded(gamma: f64, max_radius: f64) -> Self {
Self {
rewire_budget: usize::MAX,
..Self::new(gamma, max_radius)
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Error {
StartNotSafe(SafetyVerdict),
GoalBiasOutOfRange,
InvalidGamma,
InvalidMaxRadius,
InvalidCostWeight,
}
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]"),
Self::InvalidGamma => f.write_str("gamma must be positive and finite"),
Self::InvalidMaxRadius => f.write_str("max radius must be positive"),
Self::InvalidCostWeight => f.write_str("cost weight must be finite and non-negative"),
}
}
}
impl core::error::Error for Error {}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Stats {
pub rewires: usize,
pub rejected_rewires: usize,
pub skipped_rewires: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Rejection {
OverBudget,
Cycle,
NotReached,
EdgeUnproven,
DescendantUnproven,
GoalLost,
NotCheaper,
CostIncreased,
}
struct Edge<C> {
parent: usize,
control: C,
set: SparsePolyZonotope,
cost: f64,
}
struct Proven {
sets: Vec<SparsePolyZonotope>,
costs: Vec<f64>,
in_goal: Vec<bool>,
}
pub struct RobustRrtStar<R: Reach<N>, Sa, const N: usize, G = PolytopeGoal<N>> {
problem: Problem<R, Sa, N, G>,
config: Config,
nodes: Vec<Node<R::Control, N>>,
costs: Vec<f64>,
children: Vec<Vec<usize>>,
in_goal: Vec<bool>,
nn: LinearScan<[f64; N]>,
stats: Stats,
cover: Vec<SparsePolyZonotope>,
near: Vec<usize>,
}
impl<R, Sa, const N: usize, G> RobustRrtStar<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> {
validate(&config)?;
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(),
costs: Vec::new(),
children: Vec::new(),
in_goal: Vec::new(),
nn: LinearScan::default(),
stats: Stats::default(),
cover: Vec::new(),
near: Vec::new(),
};
planner.push(root, 0.0);
Ok(planner)
}
pub fn step<Rg: Rng + ?Sized>(&mut self, rng: &mut Rg) -> bool {
let target = self.draw(rng);
let Some((fallback, nominal)) = self.extend(&target) else {
return false;
};
let mut near = core::mem::take(&mut self.near);
self.nn
.within_radius(&Euclidean::<N>, &nominal, self.radius(), &mut near);
let edge = self.choose_parent(fallback, &nominal, &near);
let id = self.insert(edge, nominal);
self.rewire_neighbors(id, &near);
self.near = near;
true
}
pub fn run<Rg: Rng + ?Sized>(&mut self, iterations: usize, rng: &mut Rg) {
for _ in 0..iterations {
self.step(rng);
}
}
#[must_use]
pub fn nodes(&self) -> &[Node<R::Control, N>] {
&self.nodes
}
#[must_use]
pub fn cost(&self, node: usize) -> f64 {
self.costs[node]
}
#[must_use]
pub fn goal_node(&self) -> Option<usize> {
(0..self.nodes.len())
.filter(|&id| self.in_goal[id])
.min_by(|&a, &b| self.costs[a].total_cmp(&self.costs[b]))
}
#[must_use]
pub const fn stats(&self) -> Stats {
self.stats
}
#[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]>> {
let goal = self.goal_node()?;
let states = node::nominal_path(&self.nodes, goal).states;
Some(Path {
states,
cost: self.costs[goal],
})
}
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 extend(&mut self, target: &[f64; N]) -> Option<(Edge<R::Control>, [f64; N])> {
let parent = self
.nn
.nearest(&Euclidean::<N>, target)
.expect("the tree always holds the root");
let (control, nominal) = self
.problem
.reach
.steer(&self.nodes[parent].nominal, target);
let length = Euclidean::<N>.distance(&self.nodes[parent].nominal, &nominal);
if length.is_nan() || length <= 0.0 {
return None;
}
let set = prove(
&self.problem,
&mut self.cover,
&self.nodes[parent].set,
&control,
)?;
let cost = self.costs[parent] + self.config.cost.edge(length, &set);
Some((
Edge {
parent,
control,
set,
cost,
},
nominal,
))
}
fn radius(&self) -> f64 {
let n = count_to_f64(self.nodes.len() + 1);
let d = count_to_f64(N.max(1));
(self.config.gamma * (n.ln() / n).powf(1.0 / d)).min(self.config.max_radius)
}
fn choose_parent(
&mut self,
fallback: Edge<R::Control>,
nominal: &[f64; N],
near: &[usize],
) -> Edge<R::Control> {
let mut candidates: Vec<(f64, usize)> = near
.iter()
.map(|&id| (self.length_bound(id, nominal), id))
.filter(|&(bound, id)| bound < fallback.cost && id != fallback.parent)
.collect();
candidates.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
let mut best = fallback;
for (bound, id) in candidates {
if bound >= best.cost {
break;
}
if let Some(edge) = self.connect(id, nominal)
&& edge.cost < best.cost
{
best = edge;
}
}
best
}
fn rewire_neighbors(&mut self, id: usize, near: &[usize]) {
let mut budget = self.config.rewire_budget;
for &node in near {
if self.length_bound(id, &self.nodes[node].nominal) >= self.costs[node] {
continue;
}
match self.try_rewire(node, id, &mut budget) {
Ok(()) => self.stats.rewires += 1,
Err(Rejection::OverBudget) => self.stats.skipped_rewires += 1,
Err(_) => self.stats.rejected_rewires += 1,
}
}
}
fn try_rewire(
&mut self,
node: usize,
parent: usize,
budget: &mut usize,
) -> Result<(), Rejection> {
let subtree = self.subtree(node, *budget).ok_or(Rejection::OverBudget)?;
if subtree.iter().any(|&(id, _)| id == parent) {
return Err(Rejection::Cycle);
}
let control = self
.exact_control(parent, &self.nodes[node].nominal)
.ok_or(Rejection::NotReached)?;
let sets = self.prove_subtree(parent, &control, &subtree, budget)?;
let costs = self.subtree_costs(parent, &subtree, &sets)?;
let in_goal = self.goal_flags(&subtree, &sets)?;
self.commit(
parent,
control,
&subtree,
Proven {
sets,
costs,
in_goal,
},
);
Ok(())
}
fn subtree(&self, node: usize, limit: usize) -> Option<Vec<(usize, usize)>> {
let mut entries = vec![(node, 0)];
let mut next = 0;
while next < entries.len() {
let id = entries[next].0;
entries.extend(self.children[id].iter().map(|&child| (child, next)));
if entries.len() > limit {
return None;
}
next += 1;
}
Some(entries)
}
fn prove_subtree(
&mut self,
parent: usize,
control: &R::Control,
subtree: &[(usize, usize)],
budget: &mut usize,
) -> Result<Vec<SparsePolyZonotope>, Rejection> {
let mut sets: Vec<SparsePolyZonotope> = Vec::with_capacity(subtree.len());
let root_set = prove(
&self.problem,
&mut self.cover,
&self.nodes[parent].set,
control,
);
*budget = budget.saturating_sub(1);
sets.push(root_set.ok_or(Rejection::EdgeUnproven)?);
for &(id, parent_entry) in &subtree[1..] {
let control = self.nodes[id]
.control
.as_ref()
.expect("non-root nodes have one");
let set = prove(&self.problem, &mut self.cover, &sets[parent_entry], control);
*budget = budget.saturating_sub(1);
sets.push(set.ok_or(Rejection::DescendantUnproven)?);
}
Ok(sets)
}
fn subtree_costs(
&self,
parent: usize,
subtree: &[(usize, usize)],
sets: &[SparsePolyZonotope],
) -> Result<Vec<f64>, Rejection> {
let mut costs: Vec<f64> = Vec::with_capacity(subtree.len());
for (entry, (&(id, parent_entry), set)) in subtree.iter().zip(sets).enumerate() {
let (from, base) = if entry == 0 {
(parent, self.costs[parent])
} else {
(subtree[parent_entry].0, costs[parent_entry])
};
let length =
Euclidean::<N>.distance(&self.nodes[from].nominal, &self.nodes[id].nominal);
let cost = base + self.config.cost.edge(length, set);
if entry == 0 && cost >= self.costs[id] {
return Err(Rejection::NotCheaper);
}
if cost > self.costs[id] {
return Err(Rejection::CostIncreased);
}
costs.push(cost);
}
Ok(costs)
}
fn goal_flags(
&self,
subtree: &[(usize, usize)],
sets: &[SparsePolyZonotope],
) -> Result<Vec<bool>, Rejection> {
subtree
.iter()
.zip(sets)
.map(|(&(id, _), set)| {
let inside = self.reaches_goal(set);
if self.in_goal[id] && !inside {
Err(Rejection::GoalLost)
} else {
Ok(inside)
}
})
.collect()
}
fn commit(
&mut self,
parent: usize,
control: R::Control,
subtree: &[(usize, usize)],
proven: Proven,
) {
let node = subtree[0].0;
let old = self.nodes[node].parent.expect("the root is never rewired");
self.children[old].retain(|&child| child != node);
self.children[parent].push(node);
self.nodes[node].parent = Some(parent);
self.nodes[node].control = Some(control);
let entries = proven
.sets
.into_iter()
.zip(proven.costs)
.zip(proven.in_goal);
for (&(id, _), ((set, cost), inside)) in subtree.iter().zip(entries) {
self.costs[id] = cost;
self.nodes[id].set = set;
self.in_goal[id] = inside;
}
}
fn connect(&mut self, from: usize, nominal: &[f64; N]) -> Option<Edge<R::Control>> {
let control = self.exact_control(from, nominal)?;
let set = prove(
&self.problem,
&mut self.cover,
&self.nodes[from].set,
&control,
)?;
let length = Euclidean::<N>.distance(&self.nodes[from].nominal, nominal);
let cost = self.costs[from] + self.config.cost.edge(length, &set);
Some(Edge {
parent: from,
control,
set,
cost,
})
}
fn exact_control(&self, from: usize, nominal: &[f64; N]) -> Option<R::Control> {
let (control, end) = self.problem.reach.steer(&self.nodes[from].nominal, nominal);
#[expect(
clippy::float_cmp,
reason = "the stored controls of the node's children start exactly at `nominal`"
)]
let reached = end == *nominal;
reached.then_some(control)
}
fn insert(&mut self, edge: Edge<R::Control>, nominal: [f64; N]) -> usize {
let cost = edge.cost;
let id = self.push(
Node {
nominal,
set: edge.set,
parent: Some(edge.parent),
control: Some(edge.control),
},
cost,
);
self.children[edge.parent].push(id);
id
}
fn push(&mut self, node: Node<R::Control, N>, cost: f64) -> usize {
let id = self.nodes.len();
self.in_goal.push(self.reaches_goal(&node.set));
self.costs.push(cost);
self.children.push(Vec::new());
NearestNeighbors::<Euclidean<N>>::insert(&mut self.nn, id, node.nominal);
self.nodes.push(node);
id
}
fn length_bound(&self, via: usize, nominal: &[f64; N]) -> f64 {
self.costs[via] + Euclidean::<N>.distance(&self.nodes[via].nominal, nominal)
}
fn reaches_goal(&self, set: &SparsePolyZonotope) -> bool {
self.problem.goal.containment(set) == Containment::Inside
}
}
fn prove<R: Reach<N>, Sa, const N: usize, G>(
problem: &Problem<R, Sa, N, G>,
cover: &mut Vec<SparsePolyZonotope>,
initial: &SparsePolyZonotope,
control: &R::Control,
) -> Option<SparsePolyZonotope> {
let (verdict, end) = check_edge(&problem.reach, &problem.obstacles, initial, control, cover);
verdict.is_safe().then_some(end)
}
fn validate(config: &Config) -> Result<(), Error> {
if !(0.0..=1.0).contains(&config.goal_bias) {
return Err(Error::GoalBiasOutOfRange);
}
if !(config.gamma.is_finite() && config.gamma > 0.0) {
return Err(Error::InvalidGamma);
}
if config.max_radius.is_nan() || config.max_radius <= 0.0 {
return Err(Error::InvalidMaxRadius);
}
if !config.cost.is_valid() {
return Err(Error::InvalidCostWeight);
}
Ok(())
}
fn count_to_f64(count: usize) -> f64 {
f64::from(u32::try_from(count).unwrap_or(u32::MAX))
}