Skip to main content

robust_planning/
robust_rrt.rs

1//! Robust-RRT: an RRT whose nodes carry the reachable set they are reached with.
2//!
3//! Each iteration steers the nearest node toward a goal-biased sample, propagates that node's
4//! reachable set along the edge and keeps the edge only if every set covering it is proven
5//! disjoint from every obstacle. Uncertainty therefore builds up along a branch. A node
6//! reaches the goal only when its whole set is proven inside the goal region.
7//!
8//! ```mermaid
9//! graph LR
10//!     Sample["sample (goal-biased)"] --> Nearest
11//!     Nearest --> Steer["steer: control"]
12//!     Steer --> Propagate["propagate set"]
13//!     Propagate --> Check["check cover"]
14//!     Check -->|safe| Add["add node"]
15//!     Check -->|indeterminate| Sample
16//!     Add --> Goal["set inside goal?"]
17//! ```
18
19use core::fmt;
20
21use polyzonotope::{Containment, SparsePolyZonotope};
22use sampling_planning::{
23    Euclidean, LinearScan, NearestNeighbors, Path, Sampler, rand_core::Rng, unit_f64,
24};
25
26use crate::{Goal, Node, Obstacles, PolytopeGoal, Reach, SafetyVerdict, Steer, check_edge, node};
27
28/// Everything [`RobustRrt`] needs to know about the world.
29///
30/// The goal defaults to a [`PolytopeGoal`]; any [`Goal`] works.
31#[derive(Debug, Clone)]
32pub struct Problem<R, Sa, const N: usize, G = PolytopeGoal<N>> {
33    /// The dynamics model that steers and propagates.
34    pub reach: R,
35    /// The obstacles and their split budget.
36    pub obstacles: Obstacles,
37    /// Draws the states the tree grows toward.
38    pub sampler: Sa,
39    /// The nominal start state, which steering starts from.
40    pub start: [f64; N],
41    /// Every state the system may start in. Must be proven safe.
42    pub start_set: SparsePolyZonotope,
43    /// The goal region. A node reaches it when its set is proven inside; goal-biased
44    /// samples draw [`Goal::center`].
45    pub goal: G,
46}
47
48/// Settings for [`RobustRrt`].
49#[derive(Debug, Clone, Copy, PartialEq)]
50pub struct Config {
51    /// Probability in `[0, 1]` of extending toward the goal's [`Goal::center`] instead of
52    /// a random sample.
53    pub goal_bias: f64,
54}
55
56impl Default for Config {
57    /// A goal bias of 10 %.
58    fn default() -> Self {
59        Self { goal_bias: 0.1 }
60    }
61}
62
63/// Why a [`RobustRrt`] could not be created.
64#[derive(Debug, Clone, PartialEq)]
65pub enum Error {
66    /// The start set is not proven safe; carries the verdict.
67    StartNotSafe(SafetyVerdict),
68    /// [`Config::goal_bias`] is not in `[0, 1]`.
69    GoalBiasOutOfRange,
70}
71
72impl fmt::Display for Error {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        match self {
75            Self::StartNotSafe(verdict) => write!(f, "start set is not proven safe ({verdict:?})"),
76            Self::GoalBiasOutOfRange => f.write_str("goal bias must be in [0, 1]"),
77        }
78    }
79}
80
81impl core::error::Error for Error {}
82
83/// The Robust-RRT planner.
84///
85/// Every edge in the tree is proven safe over its whole duration, every intermediate time
86/// step included, from the reachable set of its parent. Runs are reproducible: all randomness
87/// comes from the caller's RNG.
88pub struct RobustRrt<R: Reach<N>, Sa, const N: usize, G = PolytopeGoal<N>> {
89    /// The problem being solved.
90    problem: Problem<R, Sa, N, G>,
91    /// Settings.
92    config: Config,
93    /// Tree nodes by id; node `0` is the root.
94    nodes: Vec<Node<R::Control, N>>,
95    /// Index over the nominal states of all nodes, using node ids.
96    nn: LinearScan<[f64; N]>,
97    /// The first node whose set is proven inside the goal region.
98    goal_node: Option<usize>,
99    /// Scratch buffer for the cover sets of the edge being checked.
100    cover: Vec<SparsePolyZonotope>,
101}
102
103impl<R, Sa, const N: usize, G> RobustRrt<R, Sa, N, G>
104where
105    R: Reach<N> + Steer<N, R::Control>,
106    Sa: Sampler<[f64; N]>,
107    G: Goal<N>,
108{
109    /// Checks the start set and plants the root.
110    ///
111    /// # Errors
112    ///
113    /// - [`Error::StartNotSafe`] if the start set is not proven disjoint from every obstacle.
114    /// - [`Error::GoalBiasOutOfRange`] if the goal bias is not in `[0, 1]`.
115    pub fn new(problem: Problem<R, Sa, N, G>, config: Config) -> Result<Self, Error> {
116        if !(0.0..=1.0).contains(&config.goal_bias) {
117            return Err(Error::GoalBiasOutOfRange);
118        }
119
120        let verdict = problem.obstacles.check_set(&problem.start_set);
121
122        if !verdict.is_safe() {
123            return Err(Error::StartNotSafe(verdict));
124        }
125
126        let root = Node {
127            nominal: problem.start,
128            set: problem.start_set.clone(),
129            parent: None,
130            control: None,
131        };
132
133        let mut planner = Self {
134            problem,
135            config,
136            nodes: Vec::new(),
137            nn: LinearScan::default(),
138            goal_node: None,
139            cover: Vec::new(),
140        };
141        planner.add(root);
142
143        Ok(planner)
144    }
145
146    /// Runs one iteration. Returns whether a node was added.
147    ///
148    /// # Panics
149    ///
150    /// Panics if the model's sets do not have the obstacles' dimension.
151    pub fn step<Rg: Rng + ?Sized>(&mut self, rng: &mut Rg) -> bool {
152        let target = self.draw(rng);
153        let nearest = self
154            .nn
155            .nearest(&Euclidean::<N>, &target)
156            .expect("the tree always holds the root");
157        let parent = &self.nodes[nearest];
158        let (control, nominal) = self.problem.reach.steer(&parent.nominal, &target);
159        let (verdict, end) = check_edge(
160            &self.problem.reach,
161            &self.problem.obstacles,
162            &parent.set,
163            &control,
164            &mut self.cover,
165        );
166        let Some(set) = end.filter(|_| verdict.is_safe()) else {
167            return false;
168        };
169
170        self.add(Node {
171            nominal,
172            set,
173            parent: Some(nearest),
174            control: Some(control),
175        });
176
177        true
178    }
179
180    /// Runs until the goal is reached or at most `max_iterations` iterations.
181    ///
182    /// Returns the path to the goal, or `None` if none was found within the budget.
183    pub fn solve<Rg: Rng + ?Sized>(
184        &mut self,
185        max_iterations: usize,
186        rng: &mut Rg,
187    ) -> Option<Path<[f64; N]>> {
188        for _ in 0..max_iterations {
189            if self.goal_node.is_some() {
190                break;
191            }
192
193            self.step(rng);
194        }
195
196        self.path()
197    }
198
199    /// All tree nodes by id; node `0` is the root.
200    #[must_use]
201    pub fn nodes(&self) -> &[Node<R::Control, N>] {
202        &self.nodes
203    }
204
205    /// The first node whose set was proven inside the goal region, if any.
206    #[must_use]
207    pub const fn goal_node(&self) -> Option<usize> {
208        self.goal_node
209    }
210
211    /// The problem being solved.
212    #[must_use]
213    pub const fn problem(&self) -> &Problem<R, Sa, N, G> {
214        &self.problem
215    }
216
217    /// The node ids from the root to `node`, inclusive.
218    ///
219    /// # Panics
220    ///
221    /// Panics if `node` is not a node id.
222    #[must_use]
223    pub fn branch(&self, node: usize) -> Vec<usize> {
224        node::branch(&self.nodes, node)
225    }
226
227    /// The nominal path to the goal node, or `None` if the goal was not reached yet.
228    ///
229    /// The cost is the Euclidean length of the nominal path.
230    #[must_use]
231    pub fn path(&self) -> Option<Path<[f64; N]>> {
232        Some(node::nominal_path(&self.nodes, self.goal_node?))
233    }
234
235    /// Draws the goal center with the configured probability, otherwise a sampler state.
236    fn draw<Rg: Rng + ?Sized>(&mut self, rng: &mut Rg) -> [f64; N] {
237        if unit_f64(rng) < self.config.goal_bias {
238            self.problem.goal.center()
239        } else {
240            self.problem.sampler.sample(rng)
241        }
242    }
243
244    /// Adds `node` to the tree and records it if it is the first to reach the goal.
245    fn add(&mut self, node: Node<R::Control, N>) {
246        let id = self.nodes.len();
247
248        if self.goal_node.is_none() && self.reaches_goal(&node.set) {
249            self.goal_node = Some(id);
250        }
251
252        NearestNeighbors::<Euclidean<N>>::insert(&mut self.nn, id, node.nominal);
253        self.nodes.push(node);
254    }
255
256    /// Whether `set` is proven inside the goal region.
257    fn reaches_goal(&self, set: &SparsePolyZonotope) -> bool {
258        self.problem.goal.containment(set) == Containment::Inside
259    }
260}