Skip to main content

sampling_planning/space/
euclidean.rs

1//! The Euclidean space R^N.
2
3use crate::StateSpace;
4
5/// The Euclidean space R^N with states `[f64; N]` and straight-line interpolation.
6#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
7pub struct Euclidean<const N: usize>;
8
9impl<const N: usize> StateSpace for Euclidean<N> {
10    type State = [f64; N];
11
12    fn dimension(&self) -> usize {
13        N
14    }
15
16    fn distance(&self, from: &[f64; N], to: &[f64; N]) -> f64 {
17        let squared: f64 = from.iter().zip(to).map(|(a, b)| (b - a) * (b - a)).sum();
18
19        libm::sqrt(squared)
20    }
21
22    fn interpolate(&self, from: &[f64; N], to: &[f64; N], t: f64) -> [f64; N] {
23        core::array::from_fn(|i| from[i] + (to[i] - from[i]) * t)
24    }
25
26    fn is_euclidean(&self) -> bool {
27        true
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34
35    #[test]
36    fn distance_is_euclidean() {
37        assert!((Euclidean::<2>.distance(&[0.0, 0.0], &[3.0, 4.0]) - 5.0).abs() < 1e-12);
38    }
39
40    #[test]
41    fn interpolate_hits_endpoints_and_midpoint() {
42        let (a, b) = ([0.0, 2.0], [4.0, 6.0]);
43
44        assert_eq!(Euclidean::<2>.interpolate(&a, &b, 0.0), a);
45        assert_eq!(Euclidean::<2>.interpolate(&a, &b, 1.0), b);
46        assert_eq!(Euclidean::<2>.interpolate(&a, &b, 0.5), [2.0, 4.0]);
47    }
48}