Skip to main content

sampling_planning/
shortcut.rs

1//! Path post-processing: shortcutting solution paths.
2//!
3//! Sampling-based planners return jagged paths. Both functions here replace pieces of a path
4//! by direct motions that check as [`Validity::Valid`](crate::Validity::Valid), so the result
5//! is still a solution, and never return a path that is more expensive than their input.
6//!
7//! Shortcuts produce edges longer than one steering step. Both functions take a `max_edge`
8//! bound for callers whose checkers or controllers rely on short edges (reachable-set checks,
9//! for example); pass [`f64::INFINITY`] to allow any length.
10
11use alloc::vec::Vec;
12
13use rand_core::Rng;
14
15use crate::{Path, StateSpace, ValidityChecker, unit_f64};
16
17/// Greedy vertex shortcutting: from each kept state, jumps to the furthest later state that a
18/// direct, valid motion of length at most `max_edge` reaches.
19///
20/// Deterministic, keeps the first and last state, and only drops states. Each step tries the
21/// candidates from the end of the path backward, so a path of `m` states costs `O(m^2)`
22/// motion checks in the worst case and `O(m)` when long shortcuts exist.
23///
24/// # Examples
25///
26/// ```
27/// use sampling_planning::{Euclidean, Path, Validity, ValidityChecker, shortcut};
28///
29/// /// Free space everywhere.
30/// struct Free;
31///
32/// impl ValidityChecker<Euclidean<2>> for Free {
33///     fn check_state(&self, _: &[f64; 2]) -> Validity {
34///         Validity::Valid
35///     }
36///
37///     fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], _: &[f64; 2]) -> Validity {
38///         Validity::Valid
39///     }
40/// }
41///
42/// let zigzag = Path {
43///     states: vec![[0.0, 0.0], [1.0, 1.0], [2.0, 0.0]],
44///     cost: 2.0 * 2.0_f64.sqrt(),
45/// };
46/// let straight = shortcut(&Euclidean::<2>, &Free, &zigzag, f64::INFINITY);
47///
48/// assert_eq!(straight.states, [[0.0, 0.0], [2.0, 0.0]]);
49/// assert!((straight.cost - 2.0).abs() < 1e-12);
50/// ```
51pub fn shortcut<Sp, C>(
52    space: &Sp,
53    checker: &C,
54    path: &Path<Sp::State>,
55    max_edge: f64,
56) -> Path<Sp::State>
57where
58    Sp: StateSpace,
59    C: ValidityChecker<Sp>,
60{
61    let states = &path.states;
62    let mut kept = Vec::new();
63    let mut current = 0;
64
65    while current + 1 < states.len() {
66        kept.push(states[current].clone());
67        current = furthest_reachable(space, checker, states, current, max_edge);
68    }
69
70    kept.extend(states.last().cloned());
71
72    cheaper(space, kept, path)
73}
74
75/// The index of the furthest state after `from` that a direct valid motion of length at most
76/// `max_edge` reaches; `from + 1` (the existing edge) if no longer jump works.
77fn furthest_reachable<Sp, C>(
78    space: &Sp,
79    checker: &C,
80    states: &[Sp::State],
81    from: usize,
82    max_edge: f64,
83) -> usize
84where
85    Sp: StateSpace,
86    C: ValidityChecker<Sp>,
87{
88    (from + 2..states.len())
89        .rev()
90        .find(|&to| is_direct_motion_allowed(space, checker, &states[from], &states[to], max_edge))
91        .unwrap_or(from + 1)
92}
93
94/// Whether the direct motion from `from` to `to` is at most `max_edge` long and valid.
95fn is_direct_motion_allowed<Sp, C>(
96    space: &Sp,
97    checker: &C,
98    from: &Sp::State,
99    to: &Sp::State,
100    max_edge: f64,
101) -> bool
102where
103    Sp: StateSpace,
104    C: ValidityChecker<Sp>,
105{
106    space.distance(from, to) <= max_edge && checker.check_motion(space, from, to).is_valid()
107}
108
109/// Randomized shortcutting: `attempts` times, picks two random points along the path and
110/// replaces the piece between them by a direct motion if that is valid, at most `max_edge`
111/// long and strictly cheaper.
112///
113/// Unlike [`shortcut`] the endpoints of a shortcut lie anywhere on the path, not only at its
114/// states, so it also straightens corners. All three motions of a splice are checked: from
115/// the state before the cut to its first point, across the cut, and from its second point to
116/// the state after it. Run [`shortcut`] afterward to drop states that became redundant.
117///
118/// # Examples
119///
120/// ```
121/// use rand_core::SeedableRng;
122/// use sampling_planning::{Euclidean, Path, Validity, ValidityChecker, shortcut_random};
123///
124/// /// Free space everywhere.
125/// struct Free;
126///
127/// impl ValidityChecker<Euclidean<2>> for Free {
128///     fn check_state(&self, _: &[f64; 2]) -> Validity {
129///         Validity::Valid
130///     }
131///
132///     fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], _: &[f64; 2]) -> Validity {
133///         Validity::Valid
134///     }
135/// }
136///
137/// let corner = Path { states: vec![[0.0, 0.0], [2.0, 0.0], [2.0, 2.0]], cost: 4.0 };
138/// let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(1);
139/// let smoothed = shortcut_random(&Euclidean::<2>, &Free, &corner, f64::INFINITY, 50, &mut rng);
140///
141/// assert!(smoothed.cost < 3.0);
142/// ```
143pub fn shortcut_random<Sp, C, R>(
144    space: &Sp,
145    checker: &C,
146    path: &Path<Sp::State>,
147    max_edge: f64,
148    attempts: usize,
149    rng: &mut R,
150) -> Path<Sp::State>
151where
152    Sp: StateSpace,
153    C: ValidityChecker<Sp>,
154    R: Rng + ?Sized,
155{
156    let mut states = path.states.clone();
157
158    for _ in 0..attempts {
159        if states.len() < 3 {
160            break;
161        }
162
163        let cut = RandomCut::draw(space, &states, rng);
164        if let Some(spliced) = cut.splice(space, checker, &states, max_edge) {
165            states = spliced;
166        }
167    }
168
169    cheaper(space, states, path)
170}
171
172/// A candidate shortcut between two points on a path, given as segment index and fraction.
173struct RandomCut {
174    /// The segment `(states[i], states[i + 1])` holding the first point.
175    first_segment: usize,
176    /// Fraction in `[0, 1)` along the first segment.
177    first_t: f64,
178    /// The segment holding the second point; at least `first_segment`.
179    second_segment: usize,
180    /// Fraction in `[0, 1)` along the second segment.
181    second_t: f64,
182}
183
184impl RandomCut {
185    /// Draws two points uniformly by arc length along the path `states` (at least 2 states).
186    fn draw<Sp: StateSpace, R: Rng + ?Sized>(
187        space: &Sp,
188        states: &[Sp::State],
189        rng: &mut R,
190    ) -> Self {
191        let lengths: Vec<f64> = states
192            .windows(2)
193            .map(|pair| space.distance(&pair[0], &pair[1]))
194            .collect();
195        let total: f64 = lengths.iter().sum();
196        let (a, b) = (unit_f64(rng) * total, unit_f64(rng) * total);
197        let ((first_segment, first_t), (second_segment, second_t)) =
198            (locate(&lengths, a.min(b)), locate(&lengths, a.max(b)));
199
200        Self {
201            first_segment,
202            first_t,
203            second_segment,
204            second_t,
205        }
206    }
207
208    /// The path with the piece between the two points replaced by a direct motion, or `None`
209    /// if the cut is invalid, too long, within one segment or not strictly cheaper.
210    fn splice<Sp, C>(
211        &self,
212        space: &Sp,
213        checker: &C,
214        states: &[Sp::State],
215        max_edge: f64,
216    ) -> Option<Vec<Sp::State>>
217    where
218        Sp: StateSpace,
219        C: ValidityChecker<Sp>,
220    {
221        if self.first_segment >= self.second_segment {
222            return None;
223        }
224
225        let point =
226            |segment: usize, t: f64| space.interpolate(&states[segment], &states[segment + 1], t);
227        let from = point(self.first_segment, self.first_t);
228        let to = point(self.second_segment, self.second_t);
229
230        let old = space.distance(&from, &states[self.first_segment + 1])
231            + path_length(space, &states[self.first_segment + 1..=self.second_segment])
232            + space.distance(&states[self.second_segment], &to);
233        if space.distance(&from, &to) >= old {
234            return None;
235        }
236
237        // The stubs are pieces of checked motions, but a sampled or reachable-set check of a
238        // whole motion proves nothing about a piece of it, so they are checked on their own.
239        let before = &states[self.first_segment];
240        let after = &states[self.second_segment + 1];
241        let allowed = checker.check_motion(space, before, &from).is_valid()
242            && is_direct_motion_allowed(space, checker, &from, &to, max_edge)
243            && checker.check_motion(space, &to, after).is_valid();
244
245        if !allowed {
246            return None;
247        }
248
249        let mut spliced = states[..=self.first_segment].to_vec();
250        spliced.extend([from, to]);
251        spliced.extend_from_slice(&states[self.second_segment + 1..]);
252
253        Some(spliced)
254    }
255}
256
257/// The segment index and the fraction along it at arc length `s` of a path with the given
258/// segment lengths.
259fn locate(lengths: &[f64], s: f64) -> (usize, f64) {
260    let mut remaining = s;
261
262    for (segment, &length) in lengths.iter().enumerate() {
263        if remaining < length {
264            return (segment, remaining / length);
265        }
266
267        remaining -= length;
268    }
269
270    (lengths.len() - 1, 1.0)
271}
272
273/// The sum of the distances between consecutive `states`.
274fn path_length<Sp: StateSpace>(space: &Sp, states: &[Sp::State]) -> f64 {
275    states
276        .windows(2)
277        .map(|pair| space.distance(&pair[0], &pair[1]))
278        .sum()
279}
280
281/// `states` as a path, unless rounding made it more expensive than `original`.
282fn cheaper<Sp: StateSpace>(
283    space: &Sp,
284    states: Vec<Sp::State>,
285    original: &Path<Sp::State>,
286) -> Path<Sp::State> {
287    let cost = path_length(space, &states);
288
289    if cost <= original.cost {
290        Path { states, cost }
291    } else {
292        original.clone()
293    }
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299    use crate::{Euclidean, Validity, discretized_motion};
300    use rand_core::SeedableRng;
301
302    /// A wall at `x` in `[1.4, 1.6]` for `y < 1.5`.
303    struct Wall;
304
305    impl ValidityChecker<Euclidean<2>> for Wall {
306        fn check_state(&self, s: &[f64; 2]) -> Validity {
307            if (1.4..=1.6).contains(&s[0]) && s[1] < 1.5 {
308                Validity::Invalid
309            } else {
310                Validity::Valid
311            }
312        }
313
314        fn check_motion(&self, space: &Euclidean<2>, from: &[f64; 2], to: &[f64; 2]) -> Validity {
315            discretized_motion(space, from, to, 0.01, |s| self.check_state(s))
316        }
317    }
318
319    /// A path over the wall: up, across, down, in unit-ish steps.
320    fn detour() -> Path<[f64; 2]> {
321        let states = alloc::vec![
322            [0.0, 0.0],
323            [0.0, 1.0],
324            [0.0, 2.0],
325            [1.5, 2.0],
326            [3.0, 2.0],
327            [3.0, 0.0]
328        ];
329        let cost = path_length(&Euclidean::<2>, &states);
330
331        Path { states, cost }
332    }
333
334    /// Asserts that every segment of `path` is valid and at most `max_edge` long.
335    fn assert_valid(path: &Path<[f64; 2]>, max_edge: f64) {
336        for pair in path.states.windows(2) {
337            assert_eq!(
338                Wall.check_motion(&Euclidean::<2>, &pair[0], &pair[1]),
339                Validity::Valid
340            );
341            assert!(Euclidean::<2>.distance(&pair[0], &pair[1]) <= max_edge);
342        }
343    }
344
345    #[test]
346    fn greedy_shortcut_keeps_endpoints_and_validity() {
347        let path = detour();
348        let short = shortcut(&Euclidean::<2>, &Wall, &path, f64::INFINITY);
349
350        assert_eq!(short.states.first(), path.states.first());
351        assert_eq!(short.states.last(), path.states.last());
352        assert!(short.cost < path.cost);
353        assert_valid(&short, f64::INFINITY);
354        assert_eq!(short.states, [[0.0, 0.0], [1.5, 2.0], [3.0, 0.0]]);
355    }
356
357    #[test]
358    fn greedy_shortcut_respects_max_edge() {
359        let path = detour();
360        let short = shortcut(&Euclidean::<2>, &Wall, &path, 2.0);
361
362        assert!(short.cost <= path.cost);
363        assert_eq!(short.states.len(), path.states.len() - 1);
364        assert_valid(&short, 2.0);
365    }
366
367    #[test]
368    fn random_shortcut_never_increases_cost() {
369        let path = detour();
370        let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(9);
371        let smoothed = shortcut_random(&Euclidean::<2>, &Wall, &path, f64::INFINITY, 200, &mut rng);
372
373        assert_eq!(smoothed.states.first(), path.states.first());
374        assert_eq!(smoothed.states.last(), path.states.last());
375        assert!(smoothed.cost < path.cost - 0.5, "{}", smoothed.cost);
376        assert!((smoothed.cost - path_length(&Euclidean::<2>, &smoothed.states)).abs() < 1e-12);
377        assert_valid(&smoothed, f64::INFINITY);
378    }
379}