Skip to main content

sampling_planning/trees/
rrt.rs

1//! RRT: the rapidly-exploring random tree (LaValle 1998).
2
3use rand_core::Rng;
4
5use super::{Error, growth::Growth};
6use crate::{
7    LinearScan, NearestNeighbors, Path, Problem, Sampler, StateSpace, Steering, ValidityChecker,
8};
9
10/// Settings for [`Rrt`].
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub struct RrtConfig {
13    /// Probability in `[0, 1]` of extending toward the goal center instead of a random sample.
14    pub goal_bias: f64,
15}
16
17impl Default for RrtConfig {
18    /// A goal bias of 5 %.
19    fn default() -> Self {
20        Self { goal_bias: 0.05 }
21    }
22}
23
24/// The rapidly-exploring random tree: grows toward random samples, finds a feasible path fast,
25/// but does not improve it.
26///
27/// Each iteration extends the nearest node toward a goal-biased sample by one steering step
28/// and keeps the new node if the motion is [`Validity::Valid`](crate::Validity::Valid).
29#[derive(Clone)]
30pub struct Rrt<Sp: StateSpace, Sa, C, St, N = LinearScan<<Sp as StateSpace>::State>> {
31    /// The tree and problem.
32    growth: Growth<Sp, Sa, C, St, N>,
33}
34
35impl<Sp, Sa, C, St> Rrt<Sp, Sa, C, St>
36where
37    Sp: StateSpace,
38    Sa: Sampler<Sp::State>,
39    C: ValidityChecker<Sp>,
40    St: Steering<Sp>,
41{
42    /// Creates a planner with a [`LinearScan`] nearest-neighbor index.
43    ///
44    /// # Errors
45    ///
46    /// - [`Error::InvalidStart`] if the start state is not valid.
47    /// - [`Error::GoalBiasOutOfRange`] if the goal bias is not in `[0, 1]`.
48    pub fn new(problem: Problem<Sp, Sa, C, St>, config: RrtConfig) -> Result<Self, Error> {
49        Self::with_nearest_neighbors(problem, config, LinearScan::default())
50    }
51}
52
53impl<Sp, Sa, C, St, N> Rrt<Sp, Sa, C, St, N>
54where
55    Sp: StateSpace,
56    Sa: Sampler<Sp::State>,
57    C: ValidityChecker<Sp>,
58    St: Steering<Sp>,
59    N: NearestNeighbors<Sp>,
60{
61    /// Creates a planner with the given empty nearest-neighbor index.
62    ///
63    /// # Errors
64    ///
65    /// - [`Error::InvalidStart`] if the start state is not valid.
66    /// - [`Error::GoalBiasOutOfRange`] if the goal bias is not in `[0, 1]`.
67    pub fn with_nearest_neighbors(
68        problem: Problem<Sp, Sa, C, St>,
69        config: RrtConfig,
70        nn: N,
71    ) -> Result<Self, Error> {
72        Ok(Self {
73            growth: Growth::new(problem, config.goal_bias, nn)?,
74        })
75    }
76
77    /// Runs one iteration. Returns whether a node was added.
78    pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
79        let (nearest, new) = self.growth.propose(rng);
80        if !self.growth.is_motion_valid(nearest, &new) {
81            return false;
82        }
83
84        let cost = self.growth.cost_via(nearest, &new);
85        self.growth.add(new, nearest, cost);
86
87        true
88    }
89
90    /// Runs `iterations` iterations.
91    pub fn run<R: Rng + ?Sized>(&mut self, iterations: usize, rng: &mut R) {
92        for _ in 0..iterations {
93            self.step(rng);
94        }
95    }
96
97    /// Runs until the first solution or at most `max_iterations` iterations.
98    ///
99    /// Returns the solution, or `None` if none was found within the budget.
100    pub fn solve<R: Rng + ?Sized>(
101        &mut self,
102        max_iterations: usize,
103        rng: &mut R,
104    ) -> Option<Path<Sp::State>> {
105        for _ in 0..max_iterations {
106            if self.growth.has_solution() {
107                break;
108            }
109
110            self.step(rng);
111        }
112
113        self.growth.best_path()
114    }
115
116    /// The cheapest path found so far, or `None` if the goal was not reached yet.
117    #[must_use]
118    pub fn best_path(&self) -> Option<Path<Sp::State>> {
119        self.growth.best_path()
120    }
121
122    /// The number of tree nodes, including the root.
123    #[must_use]
124    pub fn node_count(&self) -> usize {
125        self.growth.tree.len()
126    }
127}