Skip to main content

sampling_planning/trees/
rrt_sharp.rs

1//! RRT#: RRT* with dynamic-programming replanning (Arslan and Tsiotras 2013).
2
3use alloc::{collections::BinaryHeap, vec::Vec};
4
5use rand_core::Rng;
6
7use super::{Error, RrtStarConfig, targets::draw_target};
8use crate::graph::Entry;
9use crate::{
10    LinearScan, NearestNeighbors, Path, Problem, Sampler, StateSpace, Steering, ValidityChecker,
11};
12
13/// Whether a graph edge has been motion-checked.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15enum EdgeStatus {
16    /// Not checked yet.
17    Unchecked,
18    /// Checked and valid.
19    Valid,
20    /// Checked and invalid or unknown; never traveled.
21    Invalid,
22}
23
24/// A directed graph edge, stored at its source vertex.
25#[derive(Debug, Clone)]
26struct Edge {
27    /// The target vertex.
28    to: usize,
29    /// The edge length under [`StateSpace::distance`].
30    cost: f64,
31    /// Whether the motion along the edge was checked, and how.
32    status: EdgeStatus,
33}
34
35/// A graph vertex with its LPA*-style cost estimates.
36#[derive(Debug, Clone)]
37struct Vertex<S> {
38    /// The state.
39    state: S,
40    /// The cost-to-come committed by the last replanning; infinite until the vertex is
41    /// processed. Never below `lmc`.
42    g: f64,
43    /// The one-step lookahead `min over valid in-edges (g(u) + c(u, v))`; zero for the root.
44    lmc: f64,
45    /// The admissible cost-to-go `max(0, d(v, goal center) - tolerance)`.
46    h: f64,
47    /// The in-neighbor that attains `lmc`; `None` for the root and unreached vertices.
48    parent: Option<usize>,
49    /// The outgoing edges, checked lazily.
50    out: Vec<Edge>,
51}
52
53/// RRT#: grows a graph like RRG and keeps the cost-to-come of every promising vertex optimal on
54/// that graph by replanning after each extension (Arslan and Tsiotras 2013).
55///
56/// Each iteration extends the nearest vertex toward a goal-biased sample, like
57/// [`RrtStar`](super::RrtStar), and links the new vertex both ways to its neighbors (the same
58/// radius or k-nearest rule, from [`RrtStarConfig`]). Instead of RRT*'s one-step rewiring, a
59/// replanning step then runs an LPA*-like relaxation: vertices whose lookahead cost `lmc`
60/// improved are processed cheapest key (`lmc + h`) first, until no queued vertex can beat the
61/// best goal vertex. Vertices that cannot (`lmc + h >= c_best`) stay unprocessed. Because the
62/// graph only grows and edge costs are fixed, costs only decrease and the underconsistent case
63/// of LPA* never occurs.
64///
65/// After every step the cost of [`RrtSharp::best_path`] is the shortest-path cost to the goal
66/// region on the current graph, so it never increases and improves faster per sample than
67/// RRT*.
68///
69/// Edges are motion-checked lazily, in travel direction, and at most once: only when they would
70/// lower a vertex's `lmc`. This is sound for directional checkers and costs fewer checks than
71/// checking every graph edge eagerly. Informed sampling works as in RRT*.
72///
73/// The secondary key of the paper, `min(g, lmc)`, is replaced by the vertex id as the tie
74/// break, which keeps runs deterministic.
75///
76/// # Examples
77///
78/// ```
79/// use rand_core::SeedableRng;
80/// use sampling_planning::{
81///     Euclidean, GoalRegion, Problem, StraightLine, UniformBox, Validity, ValidityChecker,
82///     trees::{RrtSharp, RrtStarConfig},
83/// };
84///
85/// /// Free space everywhere.
86/// struct Free;
87///
88/// impl ValidityChecker<Euclidean<2>> for Free {
89///     fn check_state(&self, _: &[f64; 2]) -> Validity {
90///         Validity::Valid
91///     }
92///
93///     fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], _: &[f64; 2]) -> Validity {
94///         Validity::Valid
95///     }
96/// }
97///
98/// let problem = Problem {
99///     space: Euclidean::<2>,
100///     sampler: UniformBox::new([0.0, 0.0], [10.0, 10.0]),
101///     checker: Free,
102///     steering: StraightLine::new(1.0),
103///     start: [1.0, 1.0],
104///     goal: GoalRegion::new([9.0, 9.0], 0.5),
105/// };
106///
107/// let gamma = 1.5 * RrtStarConfig::gamma_lower_bound(2, 100.0);
108/// let mut planner = RrtSharp::new(problem, RrtStarConfig::new(gamma, 1.0)).expect("valid");
109/// planner.run(1000, &mut rand_pcg::Pcg64Mcg::seed_from_u64(1));
110///
111/// assert!(planner.best_path().expect("free space").cost < 11.5);
112/// ```
113#[derive(Clone)]
114pub struct RrtSharp<Sp: StateSpace, Sa, C, St, N = LinearScan<<Sp as StateSpace>::State>> {
115    /// The problem being solved.
116    problem: Problem<Sp, Sa, C, St>,
117    /// The validated settings.
118    config: RrtStarConfig,
119    /// The graph vertices, indexed by vertex id; vertex `0` is the start.
120    vertices: Vec<Vertex<Sp::State>>,
121    /// Index over all vertex states, by vertex id.
122    nn: N,
123    /// Vertices with `lmc < g`, keyed by `lmc + h` at push time; stale entries are skipped.
124    queue: BinaryHeap<Entry>,
125    /// Vertices inside the goal region.
126    goal_vertices: Vec<usize>,
127    /// The goal vertex with the lowest committed cost `g`, if any is reached.
128    best_goal: Option<usize>,
129    /// Reused buffer for neighbor queries.
130    near: Vec<usize>,
131}
132
133impl<Sp, Sa, C, St> RrtSharp<Sp, Sa, C, St>
134where
135    Sp: StateSpace,
136    Sa: Sampler<Sp::State>,
137    C: ValidityChecker<Sp>,
138    St: Steering<Sp>,
139{
140    /// Creates a planner with a [`LinearScan`] nearest-neighbor index.
141    ///
142    /// # Errors
143    ///
144    /// The same as [`RrtSharp::with_nearest_neighbors`].
145    pub fn new(problem: Problem<Sp, Sa, C, St>, config: RrtStarConfig) -> Result<Self, Error> {
146        Self::with_nearest_neighbors(problem, config, LinearScan::default())
147    }
148}
149
150impl<Sp, Sa, C, St, N> RrtSharp<Sp, Sa, C, St, N>
151where
152    Sp: StateSpace,
153    Sa: Sampler<Sp::State>,
154    C: ValidityChecker<Sp>,
155    St: Steering<Sp>,
156    N: NearestNeighbors<Sp>,
157{
158    /// Creates a planner with the given empty nearest-neighbor index.
159    ///
160    /// # Errors
161    ///
162    /// - [`Error::InvalidStart`] if the start state is not valid.
163    /// - [`Error::GoalBiasOutOfRange`] if the goal bias is not in `[0, 1]`.
164    /// - [`Error::InvalidGamma`] if `gamma` (or the k-nearest constant) is not positive and
165    ///   finite.
166    /// - [`Error::InvalidMaxRadius`] if `max_radius` is not positive.
167    pub fn with_nearest_neighbors(
168        problem: Problem<Sp, Sa, C, St>,
169        config: RrtStarConfig,
170        mut nn: N,
171    ) -> Result<Self, Error> {
172        config.validate()?;
173
174        if !(0.0..=1.0).contains(&config.goal_bias) {
175            return Err(Error::GoalBiasOutOfRange);
176        }
177
178        let validity = problem.checker.check_state(&problem.start);
179        if !validity.is_valid() {
180            return Err(Error::InvalidStart(validity));
181        }
182
183        let start = problem.start.clone();
184        let in_goal = problem.goal.contains(&problem.space, &start);
185        nn.insert(0, start.clone());
186
187        Ok(Self {
188            vertices: alloc::vec![Vertex {
189                h: heuristic(&problem, &start),
190                state: start,
191                g: 0.0,
192                lmc: 0.0,
193                parent: None,
194                out: Vec::new(),
195            }],
196            goal_vertices: if in_goal { alloc::vec![0] } else { Vec::new() },
197            best_goal: in_goal.then_some(0),
198            problem,
199            config,
200            nn,
201            queue: BinaryHeap::new(),
202            near: Vec::new(),
203        })
204    }
205
206    /// Runs one iteration: extend, then replan. Returns whether a vertex was added.
207    pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
208        let Some((nearest, new)) = self.extend_target(rng) else {
209            return false;
210        };
211
212        let id = self.add_vertex(new, nearest);
213        self.enqueue_if_promising(id);
214        self.replan();
215
216        true
217    }
218
219    /// Runs `iterations` iterations.
220    pub fn run<R: Rng + ?Sized>(&mut self, iterations: usize, rng: &mut R) {
221        for _ in 0..iterations {
222            self.step(rng);
223        }
224    }
225
226    /// Draws a target, steers the nearest vertex toward it and checks that motion. Returns the
227    /// nearest vertex and the new state, or `None` if the motion is not valid.
228    fn extend_target<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Option<(usize, Sp::State)> {
229        let bound = self.informed_bound();
230        let target = draw_target(&mut self.problem, self.config.goal_bias, bound, rng);
231        let space = &self.problem.space;
232        let nearest = self
233            .nn
234            .nearest(space, &target)
235            .expect("the graph always holds the start");
236        let from = &self.vertices[nearest].state;
237        let new = self.problem.steering.steer(space, from, &target);
238
239        self.problem
240            .checker
241            .check_motion(space, from, &new)
242            .is_valid()
243            .then_some((nearest, new))
244    }
245
246    /// The informed-set bound `c_best + tolerance`, or `None` when informed sampling is off or
247    /// no solution exists yet.
248    fn informed_bound(&self) -> Option<f64> {
249        if !self.config.informed {
250            return None;
251        }
252
253        let best = self.best_goal?;
254
255        Some(self.vertices[best].g + self.problem.goal.tolerance())
256    }
257
258    /// Adds a vertex at `state`, linked both ways to its neighbors and to `nearest` (whose edge
259    /// to `state` is known to be valid), and sets its lookahead cost from the cheapest valid
260    /// in-edge.
261    fn add_vertex(&mut self, state: Sp::State, nearest: usize) -> usize {
262        let id = self.vertices.len();
263        let mut near = core::mem::take(&mut self.near);
264        self.config.neighbors(
265            &self.problem.space,
266            &self.nn,
267            &state,
268            id + 1,
269            |other| &self.vertices[other].state,
270            &mut near,
271        );
272
273        if !near.contains(&nearest) {
274            near.push(nearest);
275        }
276
277        self.vertices.push(Vertex {
278            h: heuristic(&self.problem, &state),
279            state: state.clone(),
280            g: f64::INFINITY,
281            lmc: f64::INFINITY,
282            parent: None,
283            out: Vec::new(),
284        });
285        self.link(id, nearest, &near);
286        self.choose_parent(id);
287
288        if self.problem.goal.contains(&self.problem.space, &state) {
289            self.goal_vertices.push(id);
290        }
291
292        self.nn.insert(id, state);
293        self.near = near;
294
295        id
296    }
297
298    /// Adds unchecked edges between the new vertex `id` and every vertex in `near`, both ways;
299    /// the edge from `nearest` is already known to be valid.
300    fn link(&mut self, id: usize, nearest: usize, near: &[usize]) {
301        for &other in near {
302            let cost = self
303                .problem
304                .space
305                .distance(&self.vertices[other].state, &self.vertices[id].state);
306            let into = if other == nearest {
307                EdgeStatus::Valid
308            } else {
309                EdgeStatus::Unchecked
310            };
311
312            self.vertices[other].out.push(Edge {
313                to: id,
314                cost,
315                status: into,
316            });
317            let back = self
318                .problem
319                .space
320                .distance(&self.vertices[id].state, &self.vertices[other].state);
321            self.vertices[id].out.push(Edge {
322                to: other,
323                cost: back,
324                status: EdgeStatus::Unchecked,
325            });
326        }
327    }
328
329    /// Sets `lmc` and the parent of the new vertex `id` from its cheapest valid in-edge, checking
330    /// candidates in order of cost until one is valid.
331    fn choose_parent(&mut self, id: usize) {
332        let mut candidates: Vec<(f64, usize, usize)> = self.vertices[id]
333            .out
334            .iter()
335            .map(|edge| edge.to)
336            .filter_map(|from| {
337                let slot = self.vertices[from].out.iter().rposition(|e| e.to == id)?;
338                let cost = self.vertices[from].g + self.vertices[from].out[slot].cost;
339
340                cost.is_finite().then_some((cost, from, slot))
341            })
342            .collect();
343        candidates.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
344
345        for (cost, from, slot) in candidates {
346            if self.is_edge_valid(from, slot) {
347                self.vertices[id].lmc = cost;
348                self.vertices[id].parent = Some(from);
349                return;
350            }
351        }
352    }
353
354    /// Whether edge `slot` of vertex `from` is valid, checking and caching it on first use.
355    fn is_edge_valid(&mut self, from: usize, slot: usize) -> bool {
356        let edge = &self.vertices[from].out[slot];
357
358        match edge.status {
359            EdgeStatus::Valid => true,
360            EdgeStatus::Invalid => false,
361            EdgeStatus::Unchecked => {
362                let valid = self
363                    .problem
364                    .checker
365                    .check_motion(
366                        &self.problem.space,
367                        &self.vertices[from].state,
368                        &self.vertices[edge.to].state,
369                    )
370                    .is_valid();
371                self.vertices[from].out[slot].status = if valid {
372                    EdgeStatus::Valid
373                } else {
374                    EdgeStatus::Invalid
375                };
376
377                valid
378            }
379        }
380    }
381
382    /// Queues vertex `id` if it is inconsistent (`lmc < g`) and could still improve the best
383    /// solution (`lmc + h < c_best`).
384    fn enqueue_if_promising(&mut self, id: usize) {
385        let vertex = &self.vertices[id];
386        let key = vertex.lmc + vertex.h;
387
388        if vertex.lmc < vertex.g && key < self.best_cost() {
389            self.queue.push(Entry {
390                cost: key,
391                node: id,
392            });
393        }
394    }
395
396    /// The committed cost of the best goal vertex, or infinity.
397    fn best_cost(&self) -> f64 {
398        self.best_goal
399            .map_or(f64::INFINITY, |id| self.vertices[id].g)
400    }
401
402    /// Processes queued vertices cheapest key first until none can beat the best goal vertex:
403    /// commits `g = lmc` and relaxes the outgoing edges.
404    fn replan(&mut self) {
405        while let Some(&Entry { cost: key, node }) = self.queue.peek() {
406            if key >= self.best_cost() {
407                return;
408            }
409
410            self.queue.pop();
411            if self.is_stale(key, node) {
412                continue;
413            }
414
415            self.vertices[node].g = self.vertices[node].lmc;
416            self.record_goal(node);
417            self.relax_out_edges(node);
418        }
419    }
420
421    /// Whether a queue entry with `key` for `node` is outdated: the vertex was processed since,
422    /// or its key changed.
423    #[expect(
424        clippy::float_cmp,
425        reason = "a current entry carries exactly the key computed from the current lmc"
426    )]
427    fn is_stale(&self, key: f64, node: usize) -> bool {
428        let vertex = &self.vertices[node];
429
430        vertex.g <= vertex.lmc || key != vertex.lmc + vertex.h
431    }
432
433    /// Makes the just-processed `node` the best goal vertex if it is a goal vertex and cheaper.
434    fn record_goal(&mut self, node: usize) {
435        let in_goal = self
436            .problem
437            .goal
438            .contains(&self.problem.space, &self.vertices[node].state);
439
440        if in_goal && self.vertices[node].g < self.best_cost() {
441            self.best_goal = Some(node);
442        }
443    }
444
445    /// Lowers `lmc` of every successor of `node` that is cheaper through `node` and reachable by
446    /// a valid edge, and queues it.
447    fn relax_out_edges(&mut self, node: usize) {
448        let g = self.vertices[node].g;
449
450        for slot in 0..self.vertices[node].out.len() {
451            let Edge { to, cost, .. } = self.vertices[node].out[slot];
452            let candidate = g + cost;
453
454            if candidate < self.vertices[to].lmc && self.is_edge_valid(node, slot) {
455                self.vertices[to].lmc = candidate;
456                self.vertices[to].parent = Some(node);
457                self.enqueue_if_promising(to);
458            }
459        }
460    }
461
462    /// The cheapest path to the goal region on the current graph, or `None` if the goal was
463    /// not reached yet. Its cost never increases as iterations run.
464    #[must_use]
465    pub fn best_path(&self) -> Option<Path<Sp::State>> {
466        let goal = self.best_goal?;
467        let mut states = Vec::new();
468        let mut cost = 0.0;
469        let mut current = Some(goal);
470
471        while let Some(id) = current {
472            let vertex = &self.vertices[id];
473            states.push(vertex.state.clone());
474
475            if let Some(parent) = vertex.parent {
476                cost += self
477                    .problem
478                    .space
479                    .distance(&self.vertices[parent].state, &vertex.state);
480            }
481
482            current = vertex.parent;
483        }
484
485        states.reverse();
486
487        Some(Path { states, cost })
488    }
489
490    /// The number of graph vertices, including the start.
491    #[must_use]
492    pub fn node_count(&self) -> usize {
493        self.vertices.len()
494    }
495}
496
497/// The admissible cost-to-go `max(0, d(state, goal center) - tolerance)`.
498fn heuristic<Sp: StateSpace, Sa, C, St>(
499    problem: &Problem<Sp, Sa, C, St>,
500    state: &Sp::State,
501) -> f64 {
502    (problem.space.distance(state, problem.goal.center()) - problem.goal.tolerance()).max(0.0)
503}
504
505#[cfg(test)]
506mod tests {
507    use super::*;
508    use crate::graph::{Arc, shortest_path};
509    use crate::{Euclidean, GoalRegion, StraightLine, UniformBox, Validity, discretized_motion};
510    use rand_core::SeedableRng;
511
512    /// A wall at `x` in `[4, 6]` for `y < 8` in a 10 x 10 box.
513    struct Wall;
514
515    impl ValidityChecker<Euclidean<2>> for Wall {
516        fn check_state(&self, s: &[f64; 2]) -> Validity {
517            if (4.0..=6.0).contains(&s[0]) && s[1] < 8.0 {
518                Validity::Invalid
519            } else {
520                Validity::Valid
521            }
522        }
523
524        fn check_motion(&self, space: &Euclidean<2>, from: &[f64; 2], to: &[f64; 2]) -> Validity {
525            discretized_motion(space, from, to, 0.02, |s| self.check_state(s))
526        }
527    }
528
529    /// An RRT# planner on the wall world.
530    fn planner() -> RrtSharp<Euclidean<2>, UniformBox<2>, Wall, StraightLine> {
531        let problem = Problem {
532            space: Euclidean::<2>,
533            sampler: UniformBox::new([0.0; 2], [10.0; 2]),
534            checker: Wall,
535            steering: StraightLine::new(1.0),
536            start: [1.0, 1.0],
537            goal: GoalRegion::new([9.0, 1.0], 0.5),
538        };
539        let gamma = 1.5 * RrtStarConfig::gamma_lower_bound(2, 100.0);
540
541        RrtSharp::new(problem, RrtStarConfig::new(gamma, 1.0)).expect("valid")
542    }
543
544    /// Dijkstra over every graph edge that is valid when checked eagerly.
545    fn eager_optimum(planner: &RrtSharp<Euclidean<2>, UniformBox<2>, Wall, StraightLine>) -> f64 {
546        let space = Euclidean::<2>;
547        let vertices = &planner.vertices;
548        let route = shortest_path(
549            vertices.len(),
550            0,
551            |id| planner.goal_vertices.contains(&id),
552            |id, out: &mut Vec<Arc>| {
553                out.clear();
554                out.extend(
555                    vertices[id]
556                        .out
557                        .iter()
558                        .filter(|e| {
559                            Wall.check_motion(&space, &vertices[id].state, &vertices[e.to].state)
560                                .is_valid()
561                        })
562                        .map(|e| Arc {
563                            to: e.to,
564                            cost: e.cost,
565                            edge: None,
566                        }),
567                );
568            },
569        );
570
571        route.map_or(f64::INFINITY, |route| route.cost)
572    }
573
574    #[test]
575    fn replanning_keeps_the_graph_optimum_with_lazy_checks() {
576        let mut planner = planner();
577        let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(2);
578        let mut checked = 0;
579
580        for _ in 0..8 {
581            planner.run(250, &mut rng);
582
583            let best = planner.best_path().map_or(f64::INFINITY, |path| path.cost);
584            let optimum = eager_optimum(&planner);
585            assert!((best - optimum).abs() < 1e-9, "{best} vs {optimum}");
586            checked += usize::from(best.is_finite());
587        }
588
589        assert!(checked > 4, "solved early enough");
590
591        let unchecked = planner
592            .vertices
593            .iter()
594            .flat_map(|v| &v.out)
595            .filter(|e| e.status == EdgeStatus::Unchecked)
596            .count();
597        assert!(unchecked > 0, "lazy checking skips edges");
598    }
599}