Skip to main content

sampling_planning/trees/
rrt_connect.rs

1//! RRT-Connect: bidirectional RRT with a greedy connect step (Kuffner and LaValle 2000).
2
3use rand_core::Rng;
4
5use super::{Error, tree::Tree};
6use crate::{
7    LinearScan, NearestNeighbors, Path, Problem, Sampler, StateSpace, Steering, ValidityChecker,
8};
9
10/// Which of the two trees an operation works on.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12enum Side {
13    /// The tree rooted at the start; its edges are traveled from parent to child.
14    Start,
15    /// The tree rooted at the goal center; its edges are traveled from child to parent.
16    Goal,
17}
18
19impl Side {
20    /// The other tree.
21    const fn other(self) -> Self {
22        match self {
23            Self::Start => Self::Goal,
24            Self::Goal => Self::Start,
25        }
26    }
27}
28
29/// One tree with its nearest-neighbor index.
30#[derive(Clone)]
31struct Half<S, N> {
32    /// The tree, rooted at the start or the goal center.
33    tree: Tree<S>,
34    /// Index over the tree's nodes, by node id.
35    nn: N,
36}
37
38/// RRT-Connect: grows one tree from the start and one from the goal center, and after every
39/// extension of one tree greedily steers the other tree toward the new node until it either
40/// reaches it or hits an obstacle.
41///
42/// Finds feasible paths much faster than [`Rrt`](super::Rrt) in open spaces with narrow
43/// passages near the endpoints, but, like RRT, does not improve them; run
44/// [`shortcut`](crate::shortcut()) on the result.
45///
46/// The goal tree is rooted at [`GoalRegion::center`](crate::GoalRegion::center), so the
47/// returned path ends there. Its edges are traveled toward the root, so they are checked in that
48/// direction: a new goal-tree state gets [`ValidityChecker::check_state`] and then
49/// [`ValidityChecker::check_motion`] from itself to its parent.
50///
51/// The trees meet when a steered state is at distance zero from the target state, so
52/// [`Steering::steer`] must return the target itself when it can reach it, as
53/// [`StraightLine`](crate::StraightLine) does.
54///
55/// # Examples
56///
57/// ```
58/// use rand_core::SeedableRng;
59/// use sampling_planning::{
60///     Euclidean, GoalRegion, Problem, StraightLine, UniformBox, Validity, ValidityChecker,
61///     trees::RrtConnect,
62/// };
63///
64/// /// Free space everywhere.
65/// struct Free;
66///
67/// impl ValidityChecker<Euclidean<2>> for Free {
68///     fn check_state(&self, _: &[f64; 2]) -> Validity {
69///         Validity::Valid
70///     }
71///
72///     fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], _: &[f64; 2]) -> Validity {
73///         Validity::Valid
74///     }
75/// }
76///
77/// let problem = Problem {
78///     space: Euclidean::<2>,
79///     sampler: UniformBox::new([0.0, 0.0], [10.0, 10.0]),
80///     checker: Free,
81///     steering: StraightLine::new(1.0),
82///     start: [1.0, 1.0],
83///     goal: GoalRegion::new([9.0, 9.0], 0.5),
84/// };
85///
86/// let mut planner = RrtConnect::new(problem).expect("valid start and goal");
87/// let path = planner.solve(1000, &mut rand_pcg::Pcg64Mcg::seed_from_u64(1));
88///
89/// assert_eq!(path.expect("free space").states.last(), Some(&[9.0, 9.0]));
90/// ```
91#[derive(Clone)]
92pub struct RrtConnect<Sp: StateSpace, Sa, C, St, N = LinearScan<<Sp as StateSpace>::State>> {
93    /// The problem being solved.
94    problem: Problem<Sp, Sa, C, St>,
95    /// The tree rooted at the start.
96    start: Half<Sp::State, N>,
97    /// The tree rooted at the goal center.
98    goal: Half<Sp::State, N>,
99    /// The tree that extends toward the next sample; alternates every iteration.
100    active: Side,
101    /// The first solution found, if any.
102    solution: Option<Path<Sp::State>>,
103}
104
105impl<Sp, Sa, C, St> RrtConnect<Sp, Sa, C, St>
106where
107    Sp: StateSpace,
108    Sa: Sampler<Sp::State>,
109    C: ValidityChecker<Sp>,
110    St: Steering<Sp>,
111{
112    /// Creates a planner with [`LinearScan`] nearest-neighbor indices.
113    ///
114    /// # Errors
115    ///
116    /// - [`Error::InvalidStart`] if the start state is not valid.
117    /// - [`Error::InvalidGoal`] if the goal center is not valid.
118    pub fn new(problem: Problem<Sp, Sa, C, St>) -> Result<Self, Error> {
119        Self::with_nearest_neighbors(problem, LinearScan::default())
120    }
121}
122
123impl<Sp, Sa, C, St, N> RrtConnect<Sp, Sa, C, St, N>
124where
125    Sp: StateSpace,
126    Sa: Sampler<Sp::State>,
127    C: ValidityChecker<Sp>,
128    St: Steering<Sp>,
129    N: NearestNeighbors<Sp> + Clone,
130{
131    /// Creates a planner; each tree gets a clone of the given empty nearest-neighbor index.
132    ///
133    /// # Errors
134    ///
135    /// - [`Error::InvalidStart`] if the start state is not valid.
136    /// - [`Error::InvalidGoal`] if the goal center is not valid.
137    pub fn with_nearest_neighbors(problem: Problem<Sp, Sa, C, St>, nn: N) -> Result<Self, Error> {
138        let start_validity = problem.checker.check_state(&problem.start);
139        if !start_validity.is_valid() {
140            return Err(Error::InvalidStart(start_validity));
141        }
142
143        let goal_validity = problem.checker.check_state(problem.goal.center());
144        if !goal_validity.is_valid() {
145            return Err(Error::InvalidGoal(goal_validity));
146        }
147
148        let solution = problem
149            .goal
150            .contains(&problem.space, &problem.start)
151            .then(|| Path {
152                states: alloc::vec![problem.start.clone()],
153                cost: 0.0,
154            });
155
156        Ok(Self {
157            start: Half::rooted(problem.start.clone(), nn.clone()),
158            goal: Half::rooted(problem.goal.center().clone(), nn),
159            problem,
160            active: Side::Start,
161            solution,
162        })
163    }
164
165    /// Runs one iteration: extends the active tree toward a sample, then connects the other
166    /// tree toward the new node. Returns whether a solution exists afterward.
167    pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
168        if self.solution.is_some() {
169            return true;
170        }
171
172        let side = self.active;
173        self.active = side.other();
174
175        let target = self.problem.sampler.sample(rng);
176        if let Some(new) = self.extend(side, &target) {
177            self.check_direct_goal(side, new);
178
179            if self.solution.is_none() {
180                self.connect(side.other(), new, side);
181            }
182        }
183
184        self.solution.is_some()
185    }
186
187    /// Runs until a solution is found or `max_iterations` iterations have run.
188    ///
189    /// Returns the solution, or `None` if none was found within the budget.
190    pub fn solve<R: Rng + ?Sized>(
191        &mut self,
192        max_iterations: usize,
193        rng: &mut R,
194    ) -> Option<Path<Sp::State>> {
195        for _ in 0..max_iterations {
196            if self.step(rng) {
197                break;
198            }
199        }
200
201        self.solution.clone()
202    }
203
204    /// The solution, or `None` if the trees have not met yet.
205    #[must_use]
206    pub const fn path(&self) -> Option<&Path<Sp::State>> {
207        self.solution.as_ref()
208    }
209
210    /// The number of nodes in both trees, including both roots.
211    #[must_use]
212    pub fn node_count(&self) -> usize {
213        self.start.tree.len() + self.goal.tree.len()
214    }
215
216    /// The tree on `side`.
217    const fn half(&self, side: Side) -> &Half<Sp::State, N> {
218        match side {
219            Side::Start => &self.start,
220            Side::Goal => &self.goal,
221        }
222    }
223
224    /// Takes one steering step on `side` from the node nearest to `target`.
225    ///
226    /// Returns the new node id, or `None` if the motion was not valid.
227    fn extend(&mut self, side: Side, target: &Sp::State) -> Option<usize> {
228        let nearest = self.nearest(side, target);
229
230        self.step_from(side, nearest, target)
231    }
232
233    /// Takes one steering step on `side` from node `from` toward `target`. Returns the new node
234    /// id, or `None` if the edge was not valid.
235    fn step_from(&mut self, side: Side, from: usize, target: &Sp::State) -> Option<usize> {
236        let space = &self.problem.space;
237        let tree = &self.half(side).tree;
238        let new = self.problem.steering.steer(space, tree.state(from), target);
239
240        if !self.is_edge_valid(side, from, &new) {
241            return None;
242        }
243
244        let cost = tree.cost(from) + space.distance(tree.state(from), &new);
245        let half = match side {
246            Side::Start => &mut self.start,
247            Side::Goal => &mut self.goal,
248        };
249        let id = half.tree.add(new.clone(), from, cost);
250        half.nn.insert(id, new);
251
252        Some(id)
253    }
254
255    /// Greedily steers `side` toward node `target` of tree `target_side` until it reaches the
256    /// node (and records the solution) or an edge is not valid.
257    fn connect(&mut self, side: Side, target: usize, target_side: Side) {
258        let goal = self.half(target_side).tree.state(target).clone();
259        let mut current = self.nearest(side, &goal);
260
261        while let Some(next) = self.step_from(side, current, &goal) {
262            let reached = self.half(side).tree.state(next);
263
264            if self.problem.space.distance(reached, &goal) <= 0.0 {
265                self.record_meeting(side, next, target);
266                return;
267            }
268
269            current = next;
270        }
271    }
272
273    /// Records the solution if start-tree node `id`, just added on `side`, is in the goal
274    /// region; the start tree can reach the region before it meets the goal tree.
275    fn check_direct_goal(&mut self, side: Side, id: usize) {
276        let tree = &self.start.tree;
277
278        if side == Side::Start
279            && self
280                .problem
281                .goal
282                .contains(&self.problem.space, tree.state(id))
283        {
284            self.solution = Some(Path {
285                states: tree.path_to(id),
286                cost: tree.cost(id),
287            });
288        }
289    }
290
291    /// Records the path through the meeting node pair: node `id` on `side` and node `other` on
292    /// the opposite tree hold the same state.
293    fn record_meeting(&mut self, side: Side, id: usize, other: usize) {
294        let (start_id, goal_id) = match side {
295            Side::Start => (id, other),
296            Side::Goal => (other, id),
297        };
298
299        let mut states = self.start.tree.path_to(start_id);
300        let mut to_goal = self.goal.tree.path_to(goal_id);
301        to_goal.reverse();
302        states.extend(to_goal.into_iter().skip(1));
303
304        self.solution = Some(Path {
305            states,
306            cost: self.start.tree.cost(start_id) + self.goal.tree.cost(goal_id),
307        });
308    }
309
310    /// The node on `side` nearest to `target`.
311    fn nearest(&self, side: Side, target: &Sp::State) -> usize {
312        self.half(side)
313            .nn
314            .nearest(&self.problem.space, target)
315            .expect("each tree always holds its root")
316    }
317
318    /// Whether the edge between node `parent` on `side` and the new state `new` is valid in
319    /// travel direction: parent to child in the start tree, child to parent in the goal tree.
320    fn is_edge_valid(&self, side: Side, parent: usize, new: &Sp::State) -> bool {
321        let checker = &self.problem.checker;
322        let space = &self.problem.space;
323        let parent_state = self.half(side).tree.state(parent);
324
325        match side {
326            Side::Start => checker.check_motion(space, parent_state, new).is_valid(),
327            Side::Goal => {
328                checker.check_state(new).is_valid()
329                    && checker.check_motion(space, new, parent_state).is_valid()
330            }
331        }
332    }
333}
334
335impl<S: Clone, N> Half<S, N> {
336    /// A tree holding only `root`, indexed as node `0` in the empty index `nn`.
337    fn rooted<Sp>(root: S, mut nn: N) -> Self
338    where
339        Sp: StateSpace<State = S>,
340        N: NearestNeighbors<Sp>,
341    {
342        nn.insert(0, root.clone());
343
344        Self {
345            tree: Tree::new(root),
346            nn,
347        }
348    }
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354    use crate::{Euclidean, GoalRegion, StraightLine, UniformBox, Validity, discretized_motion};
355    use rand_core::SeedableRng;
356
357    /// A checker whose wall at `x = 5` is a one-way gate: motions may cross it only while `x`
358    /// increases, so a solution from left to right is valid only in travel direction.
359    struct OneWay;
360
361    impl ValidityChecker<Euclidean<1>> for OneWay {
362        fn check_state(&self, _: &[f64; 1]) -> Validity {
363            Validity::Valid
364        }
365
366        fn check_motion(&self, space: &Euclidean<1>, from: &[f64; 1], to: &[f64; 1]) -> Validity {
367            let crosses = (from[0] < 5.0) != (to[0] < 5.0);
368
369            if crosses && to[0] < from[0] {
370                Validity::Invalid
371            } else {
372                discretized_motion(space, from, to, 0.1, |_| Validity::Valid)
373            }
374        }
375    }
376
377    #[test]
378    fn paths_are_valid_in_travel_direction() {
379        let problem = Problem {
380            space: Euclidean::<1>,
381            sampler: UniformBox::new([0.0], [10.0]),
382            checker: OneWay,
383            steering: StraightLine::new(0.7),
384            start: [1.0],
385            goal: GoalRegion::new([9.0], 0.1),
386        };
387        let mut planner = RrtConnect::new(problem).expect("valid");
388        let path = planner
389            .solve(10_000, &mut rand_pcg::Pcg64Mcg::seed_from_u64(4))
390            .expect("the gate is passable left to right");
391        for pair in path.states.windows(2) {
392            assert_eq!(
393                OneWay.check_motion(&Euclidean::<1>, &pair[0], &pair[1]),
394                Validity::Valid
395            );
396        }
397
398        assert!((path.cost - 8.0).abs() < 1e-9, "{}", path.cost);
399    }
400
401    #[test]
402    fn one_way_gate_blocks_the_reverse_direction() {
403        // A goal tree that checked parent to child would cross the gate leftward from the goal
404        // and return a path that is invalid in travel direction.
405        let problem = Problem {
406            space: Euclidean::<1>,
407            sampler: UniformBox::new([0.0], [10.0]),
408            checker: OneWay,
409            steering: StraightLine::new(0.7),
410            start: [9.0],
411            goal: GoalRegion::new([1.0], 0.1),
412        };
413        let mut planner = RrtConnect::new(problem).expect("valid");
414
415        assert_eq!(
416            planner.solve(3000, &mut rand_pcg::Pcg64Mcg::seed_from_u64(4)),
417            None
418        );
419    }
420}