Skip to main content

sampling_planning/trees/
rrt_star.rs

1//! RRT*: the asymptotically optimal RRT (Karaman and Frazzoli 2011).
2
3use alloc::vec::Vec;
4
5use rand_core::Rng;
6
7use super::{Error, growth::Growth, targets::draw_target};
8use crate::{
9    LinearScan, NearestNeighbors, Path, Problem, Sampler, StateSpace, Steering, ValidityChecker,
10    radius::{
11        dimension_f64, k_constant_lower_bound, k_nearest_count, shrinking_radius, unit_ball_volume,
12    },
13};
14
15/// Settings for [`RrtStar`].
16#[derive(Debug, Clone, Copy, PartialEq)]
17pub struct RrtStarConfig {
18    /// Probability in `[0, 1]` of extending toward the goal center instead of a random sample.
19    pub goal_bias: f64,
20    /// The connection radius constant: with `n` nodes in a `d`-dimensional space, nodes within
21    /// `gamma * (ln n / n)^(1/d)` of a new node are candidate parents and rewiring targets.
22    ///
23    /// Asymptotic optimality needs `gamma` above [`RrtStarConfig::gamma_lower_bound`].
24    /// Positive and finite. Unused when [`RrtStarConfig::k_nearest`] is set.
25    pub gamma: f64,
26    /// RRT*-k: when `Some(k_constant)`, the candidate parents and rewiring targets of a new node
27    /// are its `ceil(k_constant * ln n)` nearest nodes (`n` counting the new node) instead of
28    /// the nodes within the `gamma` radius. Neighbors beyond `max_radius` are still dropped.
29    ///
30    /// Asymptotic optimality needs `k_constant` above
31    /// [`RrtStarConfig::k_constant_lower_bound`]. Positive and finite. `None` by default.
32    pub k_nearest: Option<f64>,
33    /// Upper bound on the connection radius, `eta` in Karaman and Frazzoli. Usually the
34    /// steering step, so that no edge is longer than one steering step. Positive; may be
35    /// infinite.
36    pub max_radius: f64,
37    /// Informed sampling (Gammell et al. 2014): once a solution of cost `c` exists, only keep
38    /// samples `x` with `d(start, x) + d(x, goal center) < c + goal tolerance`, the states that
39    /// can still lie on a cheaper path.
40    ///
41    /// Samplers that support it draw from the informed set directly
42    /// ([`Sampler::sample_informed`]); [`UniformBox`](crate::UniformBox) in a Euclidean space
43    /// samples the prolate hyperspheroid around start and goal center whenever it is smaller
44    /// than the box. Other samplers fall back to rejection, which works for every [`Sampler`]
45    /// and [`StateSpace`] but costs up to [`INFORMED_ATTEMPTS`] sampler calls per iteration when
46    /// the informed set is small. Goal bias still applies. Until the first solution the planner
47    /// behaves exactly as without it. Off by default.
48    pub informed: bool,
49}
50
51/// The most samples a rejection-sampled informed iteration draws before it settles for an
52/// uninformed one.
53pub const INFORMED_ATTEMPTS: usize = 64;
54
55impl RrtStarConfig {
56    /// Creates a config with the given radius constant and radius cap, and a goal bias of 5 %.
57    #[must_use]
58    pub const fn new(gamma: f64, max_radius: f64) -> Self {
59        Self {
60            goal_bias: 0.05,
61            gamma,
62            k_nearest: None,
63            max_radius,
64            informed: false,
65        }
66    }
67
68    /// An RRT*-k config: `ceil(k_constant * ln n)` nearest neighbors, capped at `max_radius`,
69    /// and a goal bias of 5 %.
70    #[must_use]
71    pub const fn k_nearest(k_constant: f64, max_radius: f64) -> Self {
72        Self {
73            k_nearest: Some(k_constant),
74            ..Self::new(1.0, max_radius)
75        }
76    }
77
78    /// The smallest k-nearest constant for which RRT*-k is asymptotically optimal (Karaman and
79    /// Frazzoli 2011, Theorem 39): `2^(d + 1) e (1 + 1/d)`. Unlike the radius bound it does not
80    /// depend on the free volume.
81    ///
82    /// This is `2^(d + 1)` times the k-nearest PRM* and RRG bound `e (1 + 1/d)` (Theorems 35 and
83    /// 37). OMPL's RRT* uses this bound times a rewire factor of 1.1.
84    #[must_use]
85    pub fn k_constant_lower_bound(dimension: usize) -> f64 {
86        libm::pow(2.0, dimension_f64(dimension) + 1.0) * k_constant_lower_bound(dimension)
87    }
88
89    /// This config with [`RrtStarConfig::informed`] switched on.
90    #[must_use]
91    pub const fn informed(self) -> Self {
92        Self {
93            informed: true,
94            ..self
95        }
96    }
97
98    /// Checks `gamma` (or the k-nearest constant) and `max_radius`; the goal bias is checked by
99    /// the tree.
100    pub(super) fn validate(&self) -> Result<(), Error> {
101        let constant = self.k_nearest.unwrap_or(self.gamma);
102        if !(constant.is_finite() && constant > 0.0) {
103            return Err(Error::InvalidGamma);
104        }
105
106        if self.max_radius.is_nan() || self.max_radius <= 0.0 {
107            return Err(Error::InvalidMaxRadius);
108        }
109
110        Ok(())
111    }
112
113    /// Replaces `out` with the neighbors of a new node at `state` in a graph that will have `n`
114    /// nodes: within `min(gamma (ln n / n)^(1/d), max_radius)`, or the `ceil(k ln n)` nearest
115    /// within `max_radius`. `state_of` looks up stored states by id.
116    pub(super) fn neighbors<'a, Sp, N>(
117        &self,
118        space: &Sp,
119        nn: &N,
120        state: &Sp::State,
121        n: usize,
122        state_of: impl Fn(usize) -> &'a Sp::State,
123        out: &mut Vec<usize>,
124    ) where
125        Sp: StateSpace,
126        Sp::State: 'a,
127        N: NearestNeighbors<Sp>,
128    {
129        let Some(k_constant) = self.k_nearest else {
130            let radius = shrinking_radius(self.gamma, n, dimension_f64(space.dimension()));
131            nn.within_radius(space, state, radius.min(self.max_radius), out);
132            return;
133        };
134
135        nn.k_nearest(space, state, k_nearest_count(k_constant, n), out);
136
137        if self.max_radius.is_finite() {
138            out.retain(|&id| space.distance(state_of(id), state) <= self.max_radius);
139        }
140    }
141
142    /// The smallest `gamma` for which RRT* is asymptotically optimal (Karaman and Frazzoli
143    /// 2011, Theorem 38): `(2 (1 + 1/d))^(1/d) (free_volume / zeta_d)^(1/d)`, where `zeta_d` is
144    /// the volume of the unit `d`-ball.
145    ///
146    /// `free_volume` is the Lebesgue measure of the obstacle-free space; the volume of the
147    /// sampling box is a safe over-estimate. Pick `gamma` somewhat above this value.
148    #[must_use]
149    pub fn gamma_lower_bound(dimension: usize, free_volume: f64) -> f64 {
150        let d = dimension_f64(dimension);
151
152        libm::pow(
153            2.0 * (1.0 + 1.0 / d) * free_volume / unit_ball_volume(d),
154            1.0 / d,
155        )
156    }
157}
158
159/// RRT*: like [`Rrt`](super::Rrt), but each new node picks the cheapest valid parent among its
160/// neighbors and then rewires neighbors through itself when that is cheaper.
161///
162/// Costs only ever decrease, so the cost of [`RrtStar::best_path`] never increases as
163/// iterations run, and it converges to the optimum as the number of iterations grows.
164#[derive(Clone)]
165pub struct RrtStar<Sp: StateSpace, Sa, C, St, N = LinearScan<<Sp as StateSpace>::State>> {
166    /// The tree and problem.
167    growth: Growth<Sp, Sa, C, St, N>,
168    /// The validated settings.
169    config: RrtStarConfig,
170    /// Reused buffer for neighbor queries, to avoid an allocation per iteration.
171    near: Vec<usize>,
172}
173
174impl<Sp, Sa, C, St> RrtStar<Sp, Sa, C, St>
175where
176    Sp: StateSpace,
177    Sa: Sampler<Sp::State>,
178    C: ValidityChecker<Sp>,
179    St: Steering<Sp>,
180{
181    /// Creates a planner with a [`LinearScan`] nearest-neighbor index.
182    ///
183    /// # Errors
184    ///
185    /// - [`Error::InvalidStart`] if the start state is not valid.
186    /// - [`Error::GoalBiasOutOfRange`] if the goal bias is not in `[0, 1]`.
187    /// - [`Error::InvalidGamma`] if `gamma` is not positive and finite while no k-nearest
188    ///   constant is set, or the k-nearest constant is not positive and finite.
189    /// - [`Error::InvalidMaxRadius`] if `max_radius` is not positive.
190    pub fn new(problem: Problem<Sp, Sa, C, St>, config: RrtStarConfig) -> Result<Self, Error> {
191        Self::with_nearest_neighbors(problem, config, LinearScan::default())
192    }
193}
194
195impl<Sp, Sa, C, St, N> RrtStar<Sp, Sa, C, St, N>
196where
197    Sp: StateSpace,
198    Sa: Sampler<Sp::State>,
199    C: ValidityChecker<Sp>,
200    St: Steering<Sp>,
201    N: NearestNeighbors<Sp>,
202{
203    /// Creates a planner with the given empty nearest-neighbor index.
204    ///
205    /// # Errors
206    ///
207    /// - [`Error::InvalidStart`] if the start state is not valid.
208    /// - [`Error::GoalBiasOutOfRange`] if the goal bias is not in `[0, 1]`.
209    /// - [`Error::InvalidGamma`] if `gamma` is not positive and finite while no k-nearest
210    ///   constant is set, or the k-nearest constant is not positive and finite.
211    /// - [`Error::InvalidMaxRadius`] if `max_radius` is not positive.
212    pub fn with_nearest_neighbors(
213        problem: Problem<Sp, Sa, C, St>,
214        config: RrtStarConfig,
215        nn: N,
216    ) -> Result<Self, Error> {
217        config.validate()?;
218
219        Ok(Self {
220            growth: Growth::new(problem, config.goal_bias, nn)?,
221            config,
222            near: Vec::new(),
223        })
224    }
225
226    /// Runs one iteration. Returns whether a node was added.
227    pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
228        let target = self.draw_target(rng);
229        let (nearest, new) = self.growth.propose_toward(&target);
230        if !self.growth.is_motion_valid(nearest, &new) {
231            return false;
232        }
233
234        let mut near = core::mem::take(&mut self.near);
235        self.neighbors(&new, &mut near);
236
237        let (parent, cost) = self.choose_parent(nearest, &new, &near);
238        let id = self.growth.add(new, parent, cost);
239        self.rewire(id, &near);
240
241        self.near = near;
242        true
243    }
244
245    /// Draws the next growth target: a goal-biased sample, restricted to the informed set when
246    /// informed sampling is on and a solution exists.
247    fn draw_target<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Sp::State {
248        let bound = self.informed_bound();
249
250        draw_target(&mut self.growth.problem, self.growth.goal_bias, bound, rng)
251    }
252
253    /// The informed-set bound `c_best + tolerance`, or `None` when informed sampling is off or
254    /// no solution exists yet.
255    fn informed_bound(&self) -> Option<f64> {
256        if !self.config.informed {
257            return None;
258        }
259
260        let best = self.growth.best_cost()?;
261
262        Some(best + self.growth.problem.goal.tolerance())
263    }
264
265    /// Replaces `near` with the candidate parents and rewiring targets of the new node at
266    /// `state`.
267    fn neighbors(&self, state: &Sp::State, near: &mut Vec<usize>) {
268        let tree = &self.growth.tree;
269
270        self.config.neighbors(
271            &self.growth.problem.space,
272            &self.growth.nn,
273            state,
274            tree.len() + 1,
275            |id| tree.state(id),
276            near,
277        );
278    }
279
280    /// The cheapest parent for `new` among `nearest` and `near`, with its resulting cost.
281    ///
282    /// `nearest` is known to connect validly. Other candidates are motion-checked only when
283    /// they would be cheaper, since checks dominate the run time.
284    fn choose_parent(&self, nearest: usize, new: &Sp::State, near: &[usize]) -> (usize, f64) {
285        let mut best = (nearest, self.growth.cost_via(nearest, new));
286
287        for &candidate in near {
288            let cost = self.growth.cost_via(candidate, new);
289
290            if cost < best.1 && self.growth.is_motion_valid(candidate, new) {
291                best = (candidate, cost);
292            }
293        }
294
295        best
296    }
297
298    /// Moves each node in `near` under node `id` when that lowers its cost and the motion is
299    /// valid.
300    fn rewire(&mut self, id: usize, near: &[usize]) {
301        let space = &self.growth.problem.space;
302
303        for &node in near {
304            let tree = &self.growth.tree;
305            let cost = self.growth.cost_via(id, tree.state(node));
306
307            if cost < tree.cost(node) && self.is_rewire_valid(id, node) {
308                self.growth.tree.reparent(space, node, id, cost);
309            }
310        }
311    }
312
313    /// Whether the motion from node `from` to node `to` checks as valid.
314    fn is_rewire_valid(&self, from: usize, to: usize) -> bool {
315        self.growth
316            .is_motion_valid(from, self.growth.tree.state(to))
317    }
318
319    /// Runs `iterations` iterations.
320    pub fn run<R: Rng + ?Sized>(&mut self, iterations: usize, rng: &mut R) {
321        for _ in 0..iterations {
322            self.step(rng);
323        }
324    }
325
326    /// The cheapest path found so far, or `None` if the goal was not reached yet.
327    #[must_use]
328    pub fn best_path(&self) -> Option<Path<Sp::State>> {
329        self.growth.best_path()
330    }
331
332    /// The number of tree nodes, including the root.
333    #[must_use]
334    pub fn node_count(&self) -> usize {
335        self.growth.tree.len()
336    }
337}