Skip to main content

sampling_planning/roadmaps/
fmt_star.rs

1//! FMT*: the fast marching tree (Janson, Schmerling, Clark and Pavone 2015).
2
3use alloc::vec::Vec;
4
5use rand_core::Rng;
6
7use super::{
8    Error,
9    march::{Batch, Direction, Wave},
10};
11use crate::radius::{dimension_f64, unit_ball_volume};
12use crate::{GoalRegion, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, ValidityChecker};
13
14/// Settings for [`FmtStar`].
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct FmtStarConfig {
17    /// The connection radius constant: with `n` nodes in `d` dimensions, nodes within
18    /// `gamma * (ln n / n)^(1/d)` are neighbors.
19    ///
20    /// Asymptotic optimality needs `gamma` above [`FmtStarConfig::gamma_lower_bound`].
21    /// Positive and finite.
22    pub gamma: f64,
23}
24
25impl FmtStarConfig {
26    /// The smallest `gamma` for which FMT* is asymptotically optimal (Janson et al. 2015,
27    /// Theorem 4.1, with `eta = 0`): `2 (1/d)^(1/d) (free_volume / zeta_d)^(1/d)`, where
28    /// `zeta_d` is the volume of the unit `d`-ball.
29    ///
30    /// The theorem needs `(1 + eta)` times this for some `eta > 0`, so pick `gamma` somewhat
31    /// above it. `free_volume` is the Lebesgue measure of the obstacle-free space; the volume of
32    /// the sampling box is a safe over-estimate.
33    #[must_use]
34    pub fn gamma_lower_bound(dimension: usize, free_volume: f64) -> f64 {
35        let d = dimension_f64(dimension);
36
37        2.0 * libm::pow(1.0 / d, 1.0 / d) * libm::pow(free_volume / unit_ball_volume(d), 1.0 / d)
38    }
39}
40
41/// FMT*: draws a batch of samples, then marches a tree outward from the start in order of
42/// cost-to-come, connecting each unvisited neighbor of the cheapest open node to its locally
43/// cheapest open neighbor.
44///
45/// Single-query and asymptotically optimal, like [`RrtStar`](crate::trees::RrtStar), but it
46/// checks each motion at most once and only for the locally best parent, so it typically needs
47/// far fewer collision checks. Each [`FmtStar::plan`] call draws a fresh batch.
48///
49/// Edges are direct motions checked in travel direction, parent to child. The goal center is
50/// added as a sample when it is valid.
51///
52/// # Examples
53///
54/// ```
55/// use rand_core::SeedableRng;
56/// use sampling_planning::{
57///     Euclidean, GoalRegion, UniformBox, Validity, ValidityChecker,
58///     roadmaps::{FmtStar, FmtStarConfig},
59/// };
60///
61/// /// Free space everywhere.
62/// struct Free;
63///
64/// impl ValidityChecker<Euclidean<2>> for Free {
65///     fn check_state(&self, _: &[f64; 2]) -> Validity {
66///         Validity::Valid
67///     }
68///
69///     fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], _: &[f64; 2]) -> Validity {
70///         Validity::Valid
71///     }
72/// }
73///
74/// let sampler = UniformBox::new([0.0, 0.0], [10.0, 10.0]);
75/// let config = FmtStarConfig { gamma: 1.5 * FmtStarConfig::gamma_lower_bound(2, 100.0) };
76/// let mut fmt = FmtStar::new(Euclidean::<2>, sampler, Free, config).expect("valid");
77///
78/// let goal = GoalRegion::new([9.0, 9.0], 0.5);
79/// let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(1);
80/// let path = fmt.plan(&[1.0, 1.0], &goal, 1000, &mut rng).expect("valid start");
81///
82/// assert!(path.expect("free space").cost < 11.5);
83/// ```
84#[derive(Debug, Clone)]
85pub struct FmtStar<Sp: StateSpace, Sa, C, N = LinearScan<<Sp as StateSpace>::State>> {
86    /// The configuration space.
87    space: Sp,
88    /// Draws the sample batch.
89    sampler: Sa,
90    /// Decides which states and motions are allowed.
91    checker: C,
92    /// The settings; `gamma` is positive and finite.
93    config: FmtStarConfig,
94    /// An empty index, cloned for every batch.
95    nn: N,
96}
97
98impl<Sp, Sa, C> FmtStar<Sp, Sa, C>
99where
100    Sp: StateSpace,
101    Sa: Sampler<Sp::State>,
102    C: ValidityChecker<Sp>,
103{
104    /// Creates a planner with a [`LinearScan`] nearest-neighbor index.
105    ///
106    /// # Errors
107    ///
108    /// [`Error::InvalidRadius`] if `gamma` is not positive and finite.
109    pub fn new(space: Sp, sampler: Sa, checker: C, config: FmtStarConfig) -> Result<Self, Error> {
110        Self::with_nearest_neighbors(space, sampler, checker, config, LinearScan::default())
111    }
112}
113
114impl<Sp, Sa, C, N> FmtStar<Sp, Sa, C, N>
115where
116    Sp: StateSpace,
117    Sa: Sampler<Sp::State>,
118    C: ValidityChecker<Sp>,
119    N: NearestNeighbors<Sp> + Clone,
120{
121    /// Creates a planner; every batch gets a clone of the given empty nearest-neighbor index.
122    ///
123    /// # Errors
124    ///
125    /// [`Error::InvalidRadius`] if `gamma` is not positive and finite.
126    pub fn with_nearest_neighbors(
127        space: Sp,
128        sampler: Sa,
129        checker: C,
130        config: FmtStarConfig,
131        nn: N,
132    ) -> Result<Self, Error> {
133        if !(config.gamma.is_finite() && config.gamma > 0.0) {
134            return Err(Error::InvalidRadius);
135        }
136
137        Ok(Self {
138            space,
139            sampler,
140            checker,
141            config,
142            nn,
143        })
144    }
145
146    /// Draws `samples` states, keeps the valid ones, and marches from `start` until a node in
147    /// `goal` is the cheapest open node.
148    ///
149    /// Returns `None` if the wavefront dies out first: the batch does not connect start and
150    /// goal under the current radius.
151    ///
152    /// # Errors
153    ///
154    /// [`Error::InvalidStart`] if `start` does not check as valid.
155    pub fn plan<R: Rng + ?Sized>(
156        &mut self,
157        start: &Sp::State,
158        goal: &GoalRegion<Sp::State>,
159        samples: usize,
160        rng: &mut R,
161    ) -> Result<Option<Path<Sp::State>>, Error> {
162        let validity = self.checker.check_state(start);
163        if !validity.is_valid() {
164            return Err(Error::InvalidStart(validity));
165        }
166
167        let states = self.draw_batch(start, goal, samples, rng);
168
169        Ok(self.march(states, goal))
170    }
171
172    /// Marches one outward wave from node `0` over `states` until the cheapest open node lies
173    /// in `goal`, and returns the path to it.
174    fn march(
175        &self,
176        states: Vec<Sp::State>,
177        goal: &GoalRegion<Sp::State>,
178    ) -> Option<Path<Sp::State>> {
179        let mut batch = Batch::new(
180            &self.space,
181            &self.checker,
182            self.config.gamma,
183            states,
184            self.nn.clone(),
185        );
186        let mut wave = Wave::new(batch.len(), 0, Direction::Outward);
187
188        while let Some(z) = wave.peek_open() {
189            if goal.contains(&self.space, &batch.states[z]) {
190                let mut states: Vec<_> = wave
191                    .branch(z)
192                    .into_iter()
193                    .map(|node| batch.states[node].clone())
194                    .collect();
195                states.reverse();
196
197                return Some(Path {
198                    states,
199                    cost: wave.cost[z],
200                });
201            }
202
203            wave.expand(&mut batch, z);
204        }
205
206        None
207    }
208
209    /// The start, the valid samples and, when valid, the goal center, in that order.
210    fn draw_batch<R: Rng + ?Sized>(
211        &mut self,
212        start: &Sp::State,
213        goal: &GoalRegion<Sp::State>,
214        samples: usize,
215        rng: &mut R,
216    ) -> Vec<Sp::State> {
217        let mut states = alloc::vec![start.clone()];
218
219        for _ in 0..samples {
220            let state = self.sampler.sample(rng);
221
222            if self.checker.check_state(&state).is_valid() {
223                states.push(state);
224            }
225        }
226
227        if self.checker.check_state(goal.center()).is_valid() {
228            states.push(goal.center().clone());
229        }
230
231        states
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238    use crate::{Euclidean, Validity};
239
240    /// Replays a fixed list of states, cycling.
241    struct Replay(Vec<[f64; 2]>, usize);
242
243    impl Sampler<[f64; 2]> for Replay {
244        fn sample<R: Rng + ?Sized>(&mut self, _: &mut R) -> [f64; 2] {
245            self.1 += 1;
246            self.0[(self.1 - 1) % self.0.len()]
247        }
248    }
249
250    /// Free space, except around the state (5, 5).
251    struct Hole;
252
253    impl ValidityChecker<Euclidean<2>> for Hole {
254        fn check_state(&self, s: &[f64; 2]) -> Validity {
255            if libm::hypot(s[0] - 5.0, s[1] - 5.0) < 0.1 {
256                Validity::Invalid
257            } else {
258                Validity::Valid
259            }
260        }
261
262        fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], to: &[f64; 2]) -> Validity {
263            self.check_state(to)
264        }
265    }
266
267    #[test]
268    fn hand_checked_batch_stops_at_the_cheapest_goal_node() {
269        let sampler = Replay(alloc::vec![[5.0, 5.0], [8.8, 9.0], [3.0, 3.0]], 0);
270        let mut fmt = FmtStar::new(
271            Euclidean::<2>,
272            sampler,
273            Hole,
274            FmtStarConfig { gamma: 100.0 },
275        )
276        .expect("valid");
277        let goal = GoalRegion::new([9.0, 9.0], 0.5);
278        let mut rng = rand_pcg::Pcg64Mcg::new(1);
279
280        // Every node connects straight to the start; (8.8, 9) is the cheapest goal node, and the
281        // invalid (5, 5) never enters the batch.
282        let path = fmt
283            .plan(&[1.0, 1.0], &goal, 3, &mut rng)
284            .expect("valid")
285            .expect("solved");
286        assert_eq!(path.states, [[1.0, 1.0], [8.8, 9.0]]);
287        assert!((path.cost - libm::hypot(7.8, 8.0)).abs() < 1e-12);
288
289        assert_eq!(
290            fmt.plan(&[5.0, 5.0], &goal, 3, &mut rng),
291            Err(Error::InvalidStart(Validity::Invalid))
292        );
293    }
294}