sampling_planning/roadmaps/bfmt_star.rs
1//! BFMT*: the bidirectional fast marching tree (Starek et al. 2015).
2
3use alloc::vec::Vec;
4
5use rand_core::Rng;
6
7use super::{
8 Error,
9 march::{Batch, Direction, Status, Wave},
10};
11use crate::radius::{dimension_f64, unit_ball_volume};
12use crate::{GoalRegion, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, ValidityChecker};
13
14/// When [`BfmtStar`] stops marching.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
16pub enum Termination {
17 /// Stop at the first expansion in which the two trees touch, and return the cheapest
18 /// connection found in it (Algorithm 1 of Starek et al. as printed). Fastest, but in general
19 /// not the cheapest path through the batch.
20 FirstMeeting,
21 /// Keep marching until the node just expanded in one tree was already expanded in the
22 /// other, and return the cheapest connection found by then (the "best path" criterion of
23 /// Starek et al., Section III-C, and OMPL's default).
24 #[default]
25 Optimal,
26}
27
28/// Settings for [`BfmtStar`].
29#[derive(Debug, Clone, Copy, PartialEq)]
30pub struct BfmtStarConfig {
31 /// The connection radius constant: with `n` nodes in `d` dimensions, nodes within
32 /// `gamma * (ln n / n)^(1/d)` are neighbors.
33 ///
34 /// Asymptotic optimality needs `gamma` above [`BfmtStarConfig::gamma_lower_bound`].
35 /// Positive and finite.
36 pub gamma: f64,
37 /// When to stop; [`Termination::Optimal`] by default.
38 pub termination: Termination,
39}
40
41impl BfmtStarConfig {
42 /// A config with radius constant `gamma` and [`Termination::Optimal`].
43 #[must_use]
44 pub const fn new(gamma: f64) -> Self {
45 Self {
46 gamma,
47 termination: Termination::Optimal,
48 }
49 }
50
51 /// The radius constant of Starek et al. 2015, Theorem 4.1 with `eta = 0`:
52 /// `4 (1/d)^(1/d) (free_volume / zeta_d)^(1/d)`, twice FMT*'s.
53 ///
54 /// The theorem needs `(1 + eta)^(1/d)` times this for some `eta >= 0`, so this value is
55 /// already admissible; OMPL uses FMT*'s smaller constant instead. `free_volume` is the
56 /// Lebesgue measure of the obstacle-free space; the volume of the sampling box is a safe
57 /// over-estimate.
58 #[must_use]
59 pub fn gamma_lower_bound(dimension: usize, free_volume: f64) -> f64 {
60 let d = dimension_f64(dimension);
61
62 4.0 * libm::pow(1.0 / d, 1.0 / d) * libm::pow(free_volume / unit_ball_volume(d), 1.0 / d)
63 }
64}
65
66/// Which of the two trees an operation works on.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68enum Side {
69 /// The tree rooted at the start; edges traveled away from the root.
70 Start,
71 /// The tree rooted at the goal center; edges traveled toward the root.
72 Goal,
73}
74
75/// The cheapest solution found so far.
76#[derive(Debug, Clone, Copy, PartialEq)]
77struct Connection {
78 /// The node where the solution leaves the start tree.
79 node: usize,
80 /// The total cost.
81 cost: f64,
82 /// Whether the path continues through the goal tree to the goal center; `false` when
83 /// `node` itself lies in the goal region.
84 through_goal_tree: bool,
85}
86
87/// BFMT*: marches one tree outward from the start and one inward from the goal center over the
88/// same batch, alternating expansions, and joins them where they meet (Starek, Gomez,
89/// Schmerling, Janson, Moreno and Pavone 2015).
90///
91/// Each expansion is an FMT* step on the current tree: connect the unvisited neighbors of its
92/// cheapest open node `z` to their locally cheapest open neighbor. A newly connected node that
93/// the other tree already holds is a connection with cost `cost_start(x) + cost_goal(x)`; the
94/// cheapest one is kept. After each expansion the trees swap ("swap every time"), unless the
95/// other tree's wavefront is empty. [`Termination`] decides when to stop.
96///
97/// Goal-tree edges are traveled toward the goal, so they are checked from child to parent,
98/// which keeps directional checkers sound. The goal center must be valid. A start-tree node
99/// inside the goal region is also a solution, ending there.
100///
101/// Like [`FmtStar`](super::FmtStar) it is asymptotically optimal and checks each motion at most
102/// once; growing two trees from both ends typically settles fewer nodes.
103///
104/// # Examples
105///
106/// ```
107/// use rand_core::SeedableRng;
108/// use sampling_planning::{
109/// Euclidean, GoalRegion, UniformBox, Validity, ValidityChecker,
110/// roadmaps::{BfmtStar, BfmtStarConfig},
111/// };
112///
113/// /// Free space everywhere.
114/// struct Free;
115///
116/// impl ValidityChecker<Euclidean<2>> for Free {
117/// fn check_state(&self, _: &[f64; 2]) -> Validity {
118/// Validity::Valid
119/// }
120///
121/// fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], _: &[f64; 2]) -> Validity {
122/// Validity::Valid
123/// }
124/// }
125///
126/// let sampler = UniformBox::new([0.0, 0.0], [10.0, 10.0]);
127/// let config = BfmtStarConfig::new(BfmtStarConfig::gamma_lower_bound(2, 100.0));
128/// let mut bfmt = BfmtStar::new(Euclidean::<2>, sampler, Free, config).expect("valid");
129///
130/// let goal = GoalRegion::new([9.0, 9.0], 0.5);
131/// let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(1);
132/// let path = bfmt.plan(&[1.0, 1.0], &goal, 1000, &mut rng).expect("valid endpoints");
133///
134/// assert!(path.expect("free space").cost < 11.5);
135/// ```
136#[derive(Debug, Clone)]
137pub struct BfmtStar<Sp: StateSpace, Sa, C, N = LinearScan<<Sp as StateSpace>::State>> {
138 /// The configuration space.
139 space: Sp,
140 /// Draws the sample batch.
141 sampler: Sa,
142 /// Decides which states and motions are allowed.
143 checker: C,
144 /// The settings; `gamma` is positive and finite.
145 config: BfmtStarConfig,
146 /// An empty index, cloned for every batch.
147 nn: N,
148}
149
150impl<Sp, Sa, C> BfmtStar<Sp, Sa, C>
151where
152 Sp: StateSpace,
153 Sa: Sampler<Sp::State>,
154 C: ValidityChecker<Sp>,
155{
156 /// Creates a planner with a [`LinearScan`] nearest-neighbor index.
157 ///
158 /// # Errors
159 ///
160 /// [`Error::InvalidRadius`] if `gamma` is not positive and finite.
161 pub fn new(space: Sp, sampler: Sa, checker: C, config: BfmtStarConfig) -> Result<Self, Error> {
162 Self::with_nearest_neighbors(space, sampler, checker, config, LinearScan::default())
163 }
164}
165
166impl<Sp, Sa, C, N> BfmtStar<Sp, Sa, C, N>
167where
168 Sp: StateSpace,
169 Sa: Sampler<Sp::State>,
170 C: ValidityChecker<Sp>,
171 N: NearestNeighbors<Sp> + Clone,
172{
173 /// Creates a planner; every batch gets a clone of the given empty nearest-neighbor index.
174 ///
175 /// # Errors
176 ///
177 /// [`Error::InvalidRadius`] if `gamma` is not positive and finite.
178 pub fn with_nearest_neighbors(
179 space: Sp,
180 sampler: Sa,
181 checker: C,
182 config: BfmtStarConfig,
183 nn: N,
184 ) -> Result<Self, Error> {
185 if !(config.gamma.is_finite() && config.gamma > 0.0) {
186 return Err(Error::InvalidRadius);
187 }
188
189 Ok(Self {
190 space,
191 sampler,
192 checker,
193 config,
194 nn,
195 })
196 }
197
198 /// Draws `samples` states, keeps the valid ones, and marches from both `start` and the
199 /// center of `goal` until [`Termination`] says to stop.
200 ///
201 /// Returns `None` if both wavefronts die out without a connection.
202 ///
203 /// # Errors
204 ///
205 /// - [`Error::InvalidStart`] if `start` does not check as valid.
206 /// - [`Error::InvalidGoal`] if the goal center does not check as valid.
207 pub fn plan<R: Rng + ?Sized>(
208 &mut self,
209 start: &Sp::State,
210 goal: &GoalRegion<Sp::State>,
211 samples: usize,
212 rng: &mut R,
213 ) -> Result<Option<Path<Sp::State>>, Error> {
214 let validity = self.checker.check_state(start);
215 if !validity.is_valid() {
216 return Err(Error::InvalidStart(validity));
217 }
218
219 let validity = self.checker.check_state(goal.center());
220 if !validity.is_valid() {
221 return Err(Error::InvalidGoal(validity));
222 }
223
224 if goal.contains(&self.space, start) {
225 return Ok(Some(Path {
226 states: alloc::vec![start.clone()],
227 cost: 0.0,
228 }));
229 }
230
231 let mut states = alloc::vec![start.clone()];
232 states.extend(
233 (0..samples)
234 .map(|_| self.sampler.sample(rng))
235 .filter(|state| self.checker.check_state(state).is_valid()),
236 );
237 states.push(goal.center().clone());
238
239 Ok(self.march(states, goal))
240 }
241
242 /// Marches both trees over `states`: node `0` is the start, the last node the goal center.
243 fn march(
244 &self,
245 states: Vec<Sp::State>,
246 goal: &GoalRegion<Sp::State>,
247 ) -> Option<Path<Sp::State>> {
248 let mut batch = Batch::new(
249 &self.space,
250 &self.checker,
251 self.config.gamma,
252 states,
253 self.nn.clone(),
254 );
255 let n = batch.len();
256 let mut march = Bidirectional {
257 start: Wave::new(n, 0, Direction::Outward),
258 goal: Wave::new(n, n - 1, Direction::Inward),
259 best: None,
260 };
261 let mut side = Side::Start;
262
263 while let Some(z) = march.wave_mut(side).peek_open() {
264 let fresh = march.wave_mut(side).expand(&mut batch, z);
265 march.record_connections(&batch, goal, side, &fresh);
266
267 if self.should_stop(&march, side, z) {
268 break;
269 }
270
271 side = march.next_side(side);
272 }
273
274 march.best.map(|best| march.path(&batch, best))
275 }
276
277 /// Whether to stop after expanding `z` in the tree on `side`.
278 fn should_stop(&self, march: &Bidirectional, side: Side, z: usize) -> bool {
279 match self.config.termination {
280 Termination::FirstMeeting => march.best.is_some(),
281 Termination::Optimal => march.wave(other(side)).status[z] == Status::Closed,
282 }
283 }
284}
285
286/// The two waves of one BFMT* run and the best connection so far.
287struct Bidirectional {
288 /// The tree rooted at the start.
289 start: Wave,
290 /// The tree rooted at the goal center.
291 goal: Wave,
292 /// The cheapest solution found so far.
293 best: Option<Connection>,
294}
295
296impl Bidirectional {
297 /// The wave on `side`.
298 const fn wave(&self, side: Side) -> &Wave {
299 match side {
300 Side::Start => &self.start,
301 Side::Goal => &self.goal,
302 }
303 }
304
305 /// The wave on `side`, mutably.
306 const fn wave_mut(&mut self, side: Side) -> &mut Wave {
307 match side {
308 Side::Start => &mut self.start,
309 Side::Goal => &mut self.goal,
310 }
311 }
312
313 /// The side to expand next: the other one, unless its wavefront is empty.
314 fn next_side(&mut self, side: Side) -> Side {
315 if self.wave_mut(other(side)).peek_open().is_some() {
316 other(side)
317 } else {
318 side
319 }
320 }
321
322 /// Records the solutions through the nodes just connected on `side`: nodes held by both
323 /// trees, and start-tree nodes inside the goal region.
324 fn record_connections<Sp: StateSpace, C, N>(
325 &mut self,
326 batch: &Batch<'_, Sp, C, N>,
327 goal: &GoalRegion<Sp::State>,
328 side: Side,
329 fresh: &[usize],
330 ) {
331 for &x in fresh {
332 if self.goal.status[x] != Status::Unvisited && self.start.status[x] != Status::Unvisited
333 {
334 self.offer(x, self.start.cost[x] + self.goal.cost[x], true);
335 }
336
337 if side == Side::Start && goal.contains(batch.space, &batch.states[x]) {
338 self.offer(x, self.start.cost[x], false);
339 }
340 }
341 }
342
343 /// Keeps the solution through `node` if it is cheaper than the best so far.
344 fn offer(&mut self, node: usize, cost: f64, through_goal_tree: bool) {
345 if self.best.is_none_or(|best| cost < best.cost) {
346 self.best = Some(Connection {
347 node,
348 cost,
349 through_goal_tree,
350 });
351 }
352 }
353
354 /// The states of the solution `best`: the start-tree branch to its node, then, if it goes
355 /// through the goal tree, the goal-tree branch to the goal center.
356 fn path<Sp: StateSpace, C, N>(
357 &self,
358 batch: &Batch<'_, Sp, C, N>,
359 best: Connection,
360 ) -> Path<Sp::State> {
361 let mut nodes = self.start.branch(best.node);
362 nodes.reverse();
363
364 if best.through_goal_tree {
365 nodes.extend(self.goal.branch(best.node).into_iter().skip(1));
366 }
367
368 Path {
369 states: nodes
370 .iter()
371 .map(|&node| batch.states[node].clone())
372 .collect(),
373 cost: best.cost,
374 }
375 }
376}
377
378/// The other side.
379const fn other(side: Side) -> Side {
380 match side {
381 Side::Start => Side::Goal,
382 Side::Goal => Side::Start,
383 }
384}