use alloc::vec::Vec;
use rand_core::Rng;
use crate::{Path, StateSpace, ValidityChecker, unit_f64};
pub fn shortcut<Sp, C>(
space: &Sp,
checker: &C,
path: &Path<Sp::State>,
max_edge: f64,
) -> Path<Sp::State>
where
Sp: StateSpace,
C: ValidityChecker<Sp>,
{
let states = &path.states;
let mut kept = Vec::new();
let mut current = 0;
while current + 1 < states.len() {
kept.push(states[current].clone());
current = furthest_reachable(space, checker, states, current, max_edge);
}
kept.extend(states.last().cloned());
cheaper(space, kept, path)
}
fn furthest_reachable<Sp, C>(
space: &Sp,
checker: &C,
states: &[Sp::State],
from: usize,
max_edge: f64,
) -> usize
where
Sp: StateSpace,
C: ValidityChecker<Sp>,
{
(from + 2..states.len())
.rev()
.find(|&to| is_direct_motion_allowed(space, checker, &states[from], &states[to], max_edge))
.unwrap_or(from + 1)
}
fn is_direct_motion_allowed<Sp, C>(
space: &Sp,
checker: &C,
from: &Sp::State,
to: &Sp::State,
max_edge: f64,
) -> bool
where
Sp: StateSpace,
C: ValidityChecker<Sp>,
{
space.distance(from, to) <= max_edge && checker.check_motion(space, from, to).is_valid()
}
pub fn shortcut_random<Sp, C, R>(
space: &Sp,
checker: &C,
path: &Path<Sp::State>,
max_edge: f64,
attempts: usize,
rng: &mut R,
) -> Path<Sp::State>
where
Sp: StateSpace,
C: ValidityChecker<Sp>,
R: Rng + ?Sized,
{
let mut states = path.states.clone();
for _ in 0..attempts {
if states.len() < 3 {
break;
}
let cut = RandomCut::draw(space, &states, rng);
if let Some(spliced) = cut.splice(space, checker, &states, max_edge) {
states = spliced;
}
}
cheaper(space, states, path)
}
struct RandomCut {
first_segment: usize,
first_t: f64,
second_segment: usize,
second_t: f64,
}
impl RandomCut {
fn draw<Sp: StateSpace, R: Rng + ?Sized>(
space: &Sp,
states: &[Sp::State],
rng: &mut R,
) -> Self {
let lengths: Vec<f64> = states
.windows(2)
.map(|pair| space.distance(&pair[0], &pair[1]))
.collect();
let total: f64 = lengths.iter().sum();
let (a, b) = (unit_f64(rng) * total, unit_f64(rng) * total);
let ((first_segment, first_t), (second_segment, second_t)) =
(locate(&lengths, a.min(b)), locate(&lengths, a.max(b)));
Self {
first_segment,
first_t,
second_segment,
second_t,
}
}
fn splice<Sp, C>(
&self,
space: &Sp,
checker: &C,
states: &[Sp::State],
max_edge: f64,
) -> Option<Vec<Sp::State>>
where
Sp: StateSpace,
C: ValidityChecker<Sp>,
{
if self.first_segment >= self.second_segment {
return None;
}
let point =
|segment: usize, t: f64| space.interpolate(&states[segment], &states[segment + 1], t);
let from = point(self.first_segment, self.first_t);
let to = point(self.second_segment, self.second_t);
let old = space.distance(&from, &states[self.first_segment + 1])
+ path_length(space, &states[self.first_segment + 1..=self.second_segment])
+ space.distance(&states[self.second_segment], &to);
if space.distance(&from, &to) >= old {
return None;
}
let before = &states[self.first_segment];
let after = &states[self.second_segment + 1];
let allowed = checker.check_motion(space, before, &from).is_valid()
&& is_direct_motion_allowed(space, checker, &from, &to, max_edge)
&& checker.check_motion(space, &to, after).is_valid();
if !allowed {
return None;
}
let mut spliced = states[..=self.first_segment].to_vec();
spliced.extend([from, to]);
spliced.extend_from_slice(&states[self.second_segment + 1..]);
Some(spliced)
}
}
fn locate(lengths: &[f64], s: f64) -> (usize, f64) {
let mut remaining = s;
for (segment, &length) in lengths.iter().enumerate() {
if remaining < length {
return (segment, remaining / length);
}
remaining -= length;
}
(lengths.len() - 1, 1.0)
}
fn path_length<Sp: StateSpace>(space: &Sp, states: &[Sp::State]) -> f64 {
states
.windows(2)
.map(|pair| space.distance(&pair[0], &pair[1]))
.sum()
}
fn cheaper<Sp: StateSpace>(
space: &Sp,
states: Vec<Sp::State>,
original: &Path<Sp::State>,
) -> Path<Sp::State> {
let cost = path_length(space, &states);
if cost <= original.cost {
Path { states, cost }
} else {
original.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Euclidean, Validity, discretized_motion};
use rand_core::SeedableRng;
struct Wall;
impl ValidityChecker<Euclidean<2>> for Wall {
fn check_state(&self, s: &[f64; 2]) -> Validity {
if (1.4..=1.6).contains(&s[0]) && s[1] < 1.5 {
Validity::Invalid
} else {
Validity::Valid
}
}
fn check_motion(&self, space: &Euclidean<2>, from: &[f64; 2], to: &[f64; 2]) -> Validity {
discretized_motion(space, from, to, 0.01, |s| self.check_state(s))
}
}
fn detour() -> Path<[f64; 2]> {
let states = alloc::vec![
[0.0, 0.0],
[0.0, 1.0],
[0.0, 2.0],
[1.5, 2.0],
[3.0, 2.0],
[3.0, 0.0]
];
let cost = path_length(&Euclidean::<2>, &states);
Path { states, cost }
}
fn assert_valid(path: &Path<[f64; 2]>, max_edge: f64) {
for pair in path.states.windows(2) {
assert_eq!(
Wall.check_motion(&Euclidean::<2>, &pair[0], &pair[1]),
Validity::Valid
);
assert!(Euclidean::<2>.distance(&pair[0], &pair[1]) <= max_edge);
}
}
#[test]
fn greedy_shortcut_keeps_endpoints_and_validity() {
let path = detour();
let short = shortcut(&Euclidean::<2>, &Wall, &path, f64::INFINITY);
assert_eq!(short.states.first(), path.states.first());
assert_eq!(short.states.last(), path.states.last());
assert!(short.cost < path.cost);
assert_valid(&short, f64::INFINITY);
assert_eq!(short.states, [[0.0, 0.0], [1.5, 2.0], [3.0, 0.0]]);
}
#[test]
fn greedy_shortcut_respects_max_edge() {
let path = detour();
let short = shortcut(&Euclidean::<2>, &Wall, &path, 2.0);
assert!(short.cost <= path.cost);
assert_eq!(short.states.len(), path.states.len() - 1);
assert_valid(&short, 2.0);
}
#[test]
fn random_shortcut_never_increases_cost() {
let path = detour();
let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(9);
let smoothed = shortcut_random(&Euclidean::<2>, &Wall, &path, f64::INFINITY, 200, &mut rng);
assert_eq!(smoothed.states.first(), path.states.first());
assert_eq!(smoothed.states.last(), path.states.last());
assert!(smoothed.cost < path.cost - 0.5, "{}", smoothed.cost);
assert!((smoothed.cost - path_length(&Euclidean::<2>, &smoothed.states)).abs() < 1e-12);
assert_valid(&smoothed, f64::INFINITY);
}
}