use core::{cmp::Ordering, fmt};
use std::collections::{BinaryHeap, HashMap};
use polyzonotope::{Containment, Interval, IntervalBox, Polytope, SparsePolyZonotope};
use sampling_planning::{Euclidean, Path, StateSpace};
use crate::{
Cost, Goal, Node, Obstacles, PolytopeGoal, Reach, SafetyVerdict, Steer, check_edge,
containment::decide_within, node,
};
#[derive(Debug, Clone)]
pub struct Problem<R, const N: usize, G = PolytopeGoal<N>> {
pub reach: R,
pub obstacles: Obstacles,
pub start: [f64; N],
pub start_set: SparsePolyZonotope,
pub goal: G,
pub primitives: Vec<[f64; N]>,
pub bounds: Option<([f64; N], [f64; N])>,
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum GoalRadius {
#[default]
Infinite,
Fixed(f64),
FromGoal,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Config {
pub resolution: f64,
pub goal_radius: GoalRadius,
pub max_expansions: usize,
pub cost: Cost,
pub prune_superseded_subtrees: bool,
pub dedup: Dedup,
pub bounds_contain_sets: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Dedup {
#[default]
Hull,
Proven {
tolerance: f64,
},
}
impl Dedup {
pub const PROVEN_TOLERANCE: f64 = 1e-9;
#[must_use]
pub const fn proven() -> Self {
Self::Proven {
tolerance: Self::PROVEN_TOLERANCE,
}
}
}
impl Default for Config {
fn default() -> Self {
Self {
resolution: 1e-6,
goal_radius: GoalRadius::Infinite,
max_expansions: 10_000,
cost: Cost::Length,
prune_superseded_subtrees: false,
dedup: Dedup::Hull,
bounds_contain_sets: false,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Error {
StartNotSafe(SafetyVerdict),
ResolutionOutOfRange,
GoalRadiusOutOfRange,
GoalRadiusUnavailable,
InvalidBounds,
InvalidDedupTolerance,
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::ResolutionOutOfRange => f.write_str("resolution must be positive and finite"),
Self::GoalRadiusOutOfRange => f.write_str("goal radius must be non-negative"),
Self::GoalRadiusUnavailable => f.write_str("the goal provides no radius"),
Self::InvalidDedupTolerance => {
f.write_str("dedup tolerance must be finite and non-negative")
}
Self::InvalidBounds => {
f.write_str("bounds must be ordered, not NaN, and contain the start")
}
Self::InvalidCostWeight => f.write_str("cost weight must be finite and non-negative"),
}
}
}
impl core::error::Error for Error {}
#[derive(Debug, Clone, Copy)]
struct Entry {
f: f64,
id: usize,
}
impl Ord for Entry {
fn cmp(&self, other: &Self) -> Ordering {
other.f.total_cmp(&self.f).then(other.id.cmp(&self.id))
}
}
impl PartialOrd for Entry {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Entry {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Entry {}
pub struct ReachSearch<R: Reach<N>, const N: usize, G = PolytopeGoal<N>> {
problem: Problem<R, N, G>,
config: Config,
nodes: Vec<Node<R::Control, N>>,
costs: Vec<f64>,
hulls: Vec<IntervalBox>,
cells: HashMap<[i64; N], Vec<usize>>,
open: BinaryHeap<Entry>,
superseded: Vec<bool>,
expansions: usize,
goal_radius: f64,
workspace: Option<Polytope>,
children: Vec<Vec<usize>>,
pruned: usize,
goal_node: Option<usize>,
cover: Vec<SparsePolyZonotope>,
}
impl<R, const N: usize, G> ReachSearch<R, N, G>
where
R: Reach<N> + Steer<N, R::Control>,
G: Goal<N>,
{
pub fn new(problem: Problem<R, N, G>, config: Config) -> Result<Self, Error> {
let goal_radius = validate(&problem, &config)?;
let workspace = workspace(&problem, &config);
if workspace
.as_ref()
.is_some_and(|box_| !is_inside(&problem.start_set, box_, &problem.obstacles))
{
return Err(Error::InvalidBounds);
}
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 search = Self {
problem,
config,
nodes: Vec::new(),
costs: Vec::new(),
hulls: Vec::new(),
cells: HashMap::new(),
open: BinaryHeap::new(),
superseded: Vec::new(),
expansions: 0,
goal_radius,
workspace,
children: Vec::new(),
pruned: 0,
goal_node: None,
cover: Vec::new(),
};
let hull = root.set.interval_hull();
search.push(root, 0.0, hull);
Ok(search)
}
pub fn solve(&mut self) -> Option<Path<[f64; N]>> {
let budget = self.expansions + self.config.max_expansions;
while self.goal_node.is_none() && self.expansions < budget {
let Some(Entry { id, .. }) = self.open.pop() else {
break;
};
if self.superseded[id] {
continue;
}
if self.reaches_goal(id) {
self.goal_node = Some(id);
} else {
self.expand(id);
}
}
self.path()
}
#[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 const fn goal_node(&self) -> Option<usize> {
self.goal_node
}
#[must_use]
pub const fn pruned(&self) -> usize {
self.pruned
}
#[must_use]
pub const fn expansions(&self) -> usize {
self.expansions
}
#[must_use]
pub fn is_exhausted(&self) -> bool {
self.open.iter().all(|entry| self.superseded[entry.id])
}
#[must_use]
pub const fn problem(&self) -> &Problem<R, 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 expand(&mut self, id: usize) {
self.expansions += 1;
for k in 0..self.problem.primitives.len() {
if let Some((child, cost, hull)) = self.successor(id, k) {
self.push(child, cost, hull);
}
}
}
fn successor(
&mut self,
id: usize,
k: usize,
) -> Option<(Node<R::Control, N>, f64, IntervalBox)> {
let parent = &self.nodes[id];
let offset = &self.problem.primitives[k];
let target = core::array::from_fn(|i| parent.nominal[i] + offset[i]);
let (control, nominal) = self.problem.reach.steer(&parent.nominal, &target);
let length = Euclidean::<N>.distance(&parent.nominal, &nominal);
if length.is_nan() || length <= 0.0 || !self.in_bounds(&nominal) {
return None;
}
let (verdict, end) = check_edge(
&self.problem.reach,
&self.problem.obstacles,
&parent.set,
&control,
&mut self.cover,
);
let set = end.filter(|_| verdict.is_safe())?;
if !self.sets_in_workspace(&set) {
return None;
}
let cost = self.costs[id] + self.config.cost.edge(length, &set);
let hull = set.interval_hull();
if self.is_dominated(&nominal, &set, &hull, cost) {
return None;
}
let child = Node {
nominal,
set,
parent: Some(id),
control: Some(control),
};
Some((child, cost, hull))
}
fn is_dominated(
&self,
nominal: &[f64; N],
set: &SparsePolyZonotope,
hull: &IntervalBox,
cost: f64,
) -> bool {
self.cells.get(&self.cell(nominal)).is_some_and(|ids| {
ids.iter().any(|&e| {
!self.superseded[e]
&& self.costs[e] <= cost
&& self.covers((&self.nodes[e].set, &self.hulls[e]), (set, hull))
})
})
}
fn dominated_by(
&self,
nominal: &[f64; N],
set: &SparsePolyZonotope,
hull: &IntervalBox,
cost: f64,
) -> Vec<usize> {
self.cells
.get(&self.cell(nominal))
.map(|ids| {
ids.iter()
.copied()
.filter(|&e| {
cost <= self.costs[e]
&& self.covers((set, hull), (&self.nodes[e].set, &self.hulls[e]))
})
.collect()
})
.unwrap_or_default()
}
fn covers(
&self,
inner: (&SparsePolyZonotope, &IntervalBox),
outer: (&SparsePolyZonotope, &IntervalBox),
) -> bool {
match self.config.dedup {
Dedup::Hull => box_within(inner.1, outer.1, 0.0),
Dedup::Proven { tolerance } => {
let splits = self.problem.obstacles.max_splits();
box_within(inner.1, outer.1, tolerance)
&& decide_within(inner.0, outer.0, tolerance, splits)
.unwrap_or_else(|| box_within(inner.1, outer.1, 0.0))
}
}
}
fn push(&mut self, node: Node<R::Control, N>, cost: f64, hull: IntervalBox) {
let id = self.nodes.len();
let f = cost + self.heuristic(&node.nominal);
let dominated = self.dominated_by(&node.nominal, &node.set, &hull, cost);
self.cells
.entry(self.cell(&node.nominal))
.or_default()
.push(id);
if let Some(parent) = node.parent {
self.children[parent].push(id);
}
self.hulls.push(hull);
self.superseded.push(false);
self.costs.push(cost);
self.children.push(Vec::new());
self.nodes.push(node);
self.open.push(Entry { f, id });
for e in dominated {
self.supersede(e, id);
}
}
fn supersede(&mut self, e: usize, by: usize) {
self.superseded[e] = true;
if !self.config.prune_superseded_subtrees {
return;
}
let ancestors = node::branch(&self.nodes, by);
if ancestors.contains(&e) {
return;
}
let mut stack = self.children[e].clone();
while let Some(id) = stack.pop() {
if !self.superseded[id] {
self.superseded[id] = true;
self.pruned += 1;
}
stack.extend_from_slice(&self.children[id]);
}
}
fn sets_in_workspace(&self, end: &SparsePolyZonotope) -> bool {
self.workspace.as_ref().is_none_or(|box_| {
let obstacles = &self.problem.obstacles;
is_inside(end, box_, obstacles)
&& self.cover.iter().all(|set| is_inside(set, box_, obstacles))
})
}
fn in_bounds(&self, nominal: &[f64; N]) -> bool {
self.problem.bounds.is_none_or(|(lower, upper)| {
(0..N).all(|i| lower[i] <= nominal[i] && nominal[i] <= upper[i])
})
}
fn heuristic(&self, nominal: &[f64; N]) -> f64 {
let distance = Euclidean::<N>.distance(nominal, &self.problem.goal.center());
(distance - self.goal_radius).max(0.0)
}
fn cell(&self, nominal: &[f64; N]) -> [i64; N] {
#[expect(
clippy::cast_possible_truncation,
reason = "cells only group nodes for deduplication; a saturated cell is harmless"
)]
core::array::from_fn(|i| (nominal[i] / self.config.resolution).round() as i64)
}
fn reaches_goal(&self, id: usize) -> bool {
self.problem.goal.containment(&self.nodes[id].set) == Containment::Inside
}
}
fn workspace<R, const N: usize, G>(
problem: &Problem<R, N, G>,
config: &Config,
) -> Option<Polytope> {
let (lower, upper) = problem.bounds.filter(|_| config.bounds_contain_sets)?;
let box_ = IntervalBox((0..N).map(|i| Interval::new(lower[i], upper[i])).collect());
Some(Polytope::from_box(&box_))
}
fn is_inside(set: &SparsePolyZonotope, box_: &Polytope, obstacles: &Obstacles) -> bool {
set.containment(box_, obstacles.max_splits()) == Containment::Inside
}
fn validate<R, const N: usize, G: Goal<N>>(
problem: &Problem<R, N, G>,
config: &Config,
) -> Result<f64, Error> {
if !(config.resolution.is_finite() && config.resolution > 0.0) {
return Err(Error::ResolutionOutOfRange);
}
if !config.cost.is_valid() {
return Err(Error::InvalidCostWeight);
}
if let Dedup::Proven { tolerance } = config.dedup
&& !(tolerance.is_finite() && tolerance >= 0.0)
{
return Err(Error::InvalidDedupTolerance);
}
if let Some((lower, upper)) = problem.bounds {
let contains_start =
(0..N).all(|i| lower[i] <= problem.start[i] && problem.start[i] <= upper[i]);
if !contains_start {
return Err(Error::InvalidBounds);
}
}
match config.goal_radius {
GoalRadius::Infinite => Ok(f64::INFINITY),
GoalRadius::Fixed(radius) if radius.is_nan() || radius < 0.0 => {
Err(Error::GoalRadiusOutOfRange)
}
GoalRadius::Fixed(radius) => Ok(radius),
GoalRadius::FromGoal => problem.goal.radius().ok_or(Error::GoalRadiusUnavailable),
}
}
fn box_within(inner: &IntervalBox, outer: &IntervalBox, tolerance: f64) -> bool {
inner.dim() == outer.dim()
&& inner
.0
.iter()
.zip(&outer.0)
.all(|(i, o)| o.lo - tolerance <= i.lo && i.hi <= o.hi + tolerance)
}
#[cfg(test)]
mod tests {
use polyzonotope::{Interval, Zonotope};
use sampling_planning::StraightLine;
use super::*;
use crate::WithSteering;
struct Snap;
impl Reach<2> for Snap {
type Control = [f64; 2];
fn propagate(
&self,
_: &SparsePolyZonotope,
end: &[f64; 2],
cover: &mut Vec<SparsePolyZonotope>,
) -> Option<SparsePolyZonotope> {
cover.push(square(*end, 0.1));
Some(square(*end, 0.1))
}
}
fn square(center: [f64; 2], half_width: f64) -> SparsePolyZonotope {
let b = IntervalBox(
center
.iter()
.map(|c| Interval::new(c - half_width, c + half_width))
.collect(),
);
SparsePolyZonotope::from_zonotope(&Zonotope::from_box(&b))
}
fn empty_search(prune: bool) -> ReachSearch<WithSteering<Snap, StraightLine>, 2> {
let problem = Problem {
reach: WithSteering::new(Snap, StraightLine::new(1.0)),
obstacles: Obstacles::new(Vec::new(), 0),
start: [0.0, 0.0],
start_set: square([0.0, 0.0], 0.1),
goal: PolytopeGoal::from_box(&IntervalBox(vec![Interval::new(8.0, 9.0); 2]), 0),
primitives: Vec::new(),
bounds: None,
};
let config = Config {
prune_superseded_subtrees: prune,
..Config::default()
};
ReachSearch::new(problem, config).expect("valid")
}
fn push(
search: &mut ReachSearch<WithSteering<Snap, StraightLine>, 2>,
parent: usize,
nominal: [f64; 2],
cost: f64,
half_width: f64,
) -> usize {
let set = square(nominal, half_width);
let hull = set.interval_hull();
let node = Node {
nominal,
set,
parent: Some(parent),
control: Some(nominal),
};
search.push(node, cost, hull);
search.nodes.len() - 1
}
#[test]
fn superseding_prunes_the_old_subtree_only_when_asked() {
for prune in [false, true] {
let mut search = empty_search(prune);
let a = push(&mut search, 0, [1.0, 0.0], 1.0, 0.3);
let b = push(&mut search, a, [2.0, 0.0], 2.0, 0.3);
let c = push(&mut search, b, [3.0, 0.0], 3.0, 0.3);
let other = push(&mut search, 0, [0.0, 1.0], 1.0, 0.3);
let d = push(&mut search, 0, [1.0, 0.0], 0.5, 0.1);
assert!(search.superseded[a], "d is cheaper and narrower than a");
assert_eq!(search.superseded[b], prune);
assert_eq!(search.superseded[c], prune);
assert!(!search.superseded[other] && !search.superseded[d]);
assert_eq!(search.pruned(), if prune { 2 } else { 0 });
}
}
#[test]
fn proven_dedup_keeps_a_node_the_hull_test_wrongly_drops() {
let diamond = SparsePolyZonotope::from_zonotope(&Zonotope::new(
nalgebra::DVector::from_column_slice(&[1.0, 0.0]),
nalgebra::DMatrix::from_column_slice(2, 2, &[0.5, 0.5, 0.5, -0.5]),
));
let diamond_hull = diamond.interval_hull();
for (dedup, dropped) in [
(Dedup::Hull, true),
(Dedup::Proven { tolerance: 0.0 }, false),
] {
let mut search = empty_search(false);
search.config.dedup = dedup;
push(&mut search, 0, [1.0, 0.0], 1.0, 0.6);
assert_eq!(
search.is_dominated(&[1.0, 0.0], &diamond, &diamond_hull, 2.0),
dropped,
"{dedup:?}"
);
}
let mut search = empty_search(false);
search.config.dedup = Dedup::Proven { tolerance: 0.0 };
push(&mut search, 0, [1.0, 0.0], 1.0, 0.3);
assert!(
search.is_dominated(&[1.0, 0.0], &diamond, &diamond_hull, 2.0),
"a box of half width 0.3 is proven inside"
);
}
#[test]
fn pruning_never_touches_the_branch_of_the_superseding_node() {
let mut search = empty_search(true);
let a = push(&mut search, 0, [1.0, 0.0], 1.0, 0.3);
let b = push(&mut search, a, [2.0, 0.0], 1.0, 0.3);
let d = push(&mut search, b, [1.0, 0.0], 1.0, 0.1);
assert!(search.superseded[a]);
assert!(!search.superseded[b] && !search.superseded[d]);
assert_eq!(search.pruned(), 0);
}
#[test]
fn open_list_pops_lowest_f_then_oldest() {
let mut open = BinaryHeap::new();
for (f, id) in [(2.0, 0), (1.0, 1), (1.0, 2), (3.0, 3)] {
open.push(Entry { f, id });
}
let order: Vec<usize> = core::iter::from_fn(|| open.pop().map(|e| e.id)).collect();
assert_eq!(order, [1, 2, 0, 3]);
}
#[test]
fn box_within_compares_every_bound() {
let b = |lo: f64, hi: f64| IntervalBox(vec![Interval::new(lo, hi); 2]);
let box_within_exact =
|inner: &IntervalBox, outer: &IntervalBox| box_within(inner, outer, 0.0);
assert!(box_within_exact(&b(1.0, 2.0), &b(0.0, 3.0)));
assert!(box_within_exact(&b(1.0, 2.0), &b(1.0, 2.0)));
assert!(!box_within_exact(&b(0.0, 3.0), &b(1.0, 2.0)));
assert!(!box_within_exact(&b(0.5, 3.5), &b(0.0, 3.0)));
assert!(box_within(&b(0.5, 3.5), &b(0.0, 3.0), 0.5));
}
}