Skip to main content

sampling_planning/space/
se2.rs

1//! The planar rigid-body space SE(2): position and heading.
2
3use rand_core::Rng;
4
5use super::so2::{angle_difference, interpolate_angle, uniform_angle};
6use crate::{Sampler, StateSpace, UniformBox};
7
8/// A planar pose: position `(x, y)` and heading `theta` in radians.
9///
10/// Shared by [`Se2`], [`Dubins`](crate::Dubins) and [`ReedsShepp`](crate::ReedsShepp). It is a
11/// struct rather than `[f64; 3]` so that samplers and nearest-neighbor structures for
12/// Euclidean coordinate vectors cannot be applied to it by accident.
13#[derive(Debug, Clone, Copy, Default, PartialEq)]
14pub struct Se2State {
15    /// The x coordinate.
16    pub x: f64,
17    /// The y coordinate.
18    pub y: f64,
19    /// The heading in radians, counterclockwise from the x axis. Any finite angle; spaces
20    /// return headings wrapped into `[-pi, pi)`.
21    pub theta: f64,
22}
23
24impl Se2State {
25    /// The pose at `(x, y)` with heading `theta`.
26    #[must_use]
27    pub const fn new(x: f64, y: f64, theta: f64) -> Self {
28        Self { x, y, theta }
29    }
30}
31
32/// SE(2) with the metric `|p_1 - p_2| + rotation_weight * |angle(theta_1, theta_2)|`.
33///
34/// A weighted sum of the Euclidean position metric and the SO(2) arc length, so it is a metric
35/// (OMPL's `SE2StateSpace` weighs the rotation by 0.5 by default; here the weight is explicit).
36/// Interpolation moves the position on a straight line and turns along the shorter arc at the
37/// same time, the geodesic of this metric. `t = 0` and `t = 1` return the endpoints verbatim.
38///
39/// This is the space of a holonomic planar robot. Car-like robots that cannot move sideways use
40/// [`Dubins`](crate::Dubins) or [`ReedsShepp`](crate::ReedsShepp) instead.
41///
42/// # Examples
43///
44/// ```
45/// use sampling_planning::{Se2, Se2State, StateSpace};
46///
47/// let space = Se2::new(0.5);
48/// let (a, b) = (Se2State::new(0.0, 0.0, 0.0), Se2State::new(3.0, 4.0, 1.0));
49///
50/// assert!((space.distance(&a, &b) - 5.5).abs() < 1e-12);
51/// ```
52#[derive(Debug, Clone, Copy, PartialEq)]
53pub struct Se2 {
54    /// The weight of the heading term; positive and finite. Units of distance per radian.
55    rotation_weight: f64,
56}
57
58impl Se2 {
59    /// The space with the given rotation weight.
60    ///
61    /// # Panics
62    ///
63    /// Panics if `rotation_weight` is not positive and finite.
64    #[must_use]
65    pub fn new(rotation_weight: f64) -> Self {
66        assert!(
67            rotation_weight.is_finite() && rotation_weight > 0.0,
68            "rotation weight must be positive and finite"
69        );
70
71        Self { rotation_weight }
72    }
73
74    /// The weight of the heading term.
75    #[must_use]
76    pub const fn rotation_weight(&self) -> f64 {
77        self.rotation_weight
78    }
79}
80
81impl StateSpace for Se2 {
82    type State = Se2State;
83
84    fn dimension(&self) -> usize {
85        3
86    }
87
88    fn distance(&self, from: &Se2State, to: &Se2State) -> f64 {
89        let position = libm::hypot(to.x - from.x, to.y - from.y);
90        let rotation = libm::fabs(angle_difference(from.theta, to.theta));
91
92        position + self.rotation_weight * rotation
93    }
94
95    fn interpolate(&self, from: &Se2State, to: &Se2State, t: f64) -> Se2State {
96        if t <= 0.0 {
97            return *from;
98        }
99
100        if t >= 1.0 {
101            return *to;
102        }
103
104        Se2State {
105            x: from.x + (to.x - from.x) * t,
106            y: from.y + (to.y - from.y) * t,
107            theta: interpolate_angle(from.theta, to.theta, t),
108        }
109    }
110}
111
112/// Samples poses uniformly: positions from an axis-aligned box, headings from `[-pi, pi)`.
113///
114/// Works for [`Se2`], [`Dubins`](crate::Dubins) and [`ReedsShepp`](crate::ReedsShepp). It does
115/// not sample informed sets directly; informed planners fall back to rejection.
116#[derive(Debug, Clone, Copy, PartialEq)]
117pub struct UniformSe2 {
118    /// The position box.
119    position: UniformBox<2>,
120}
121
122impl UniformSe2 {
123    /// A sampler over the position box spanned by `lower` and `upper` and all headings.
124    ///
125    /// # Panics
126    ///
127    /// Panics if any bound is not finite or `lower > upper` on any axis.
128    #[must_use]
129    pub fn new(lower: [f64; 2], upper: [f64; 2]) -> Self {
130        Self {
131            position: UniformBox::new(lower, upper),
132        }
133    }
134
135    /// Whether the position of `state` lies in the closed position box.
136    #[must_use]
137    pub fn contains(&self, state: &Se2State) -> bool {
138        self.position.contains(&[state.x, state.y])
139    }
140}
141
142impl Sampler<Se2State> for UniformSe2 {
143    fn sample<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Se2State {
144        let [x, y] = self.position.sample(rng);
145
146        Se2State {
147            x,
148            y,
149            theta: uniform_angle(rng),
150        }
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157    use core::f64::consts::PI;
158    use rand_core::SeedableRng;
159
160    #[test]
161    fn interpolation_is_linear_in_position_and_short_in_heading() {
162        let space = Se2::new(1.0);
163        let a = Se2State::new(0.0, 0.0, 3.0);
164        let b = Se2State::new(2.0, -2.0, -3.0);
165        let mid = space.interpolate(&a, &b, 0.5);
166
167        assert_eq!((mid.x, mid.y), (1.0, -1.0));
168        assert!((libm::fabs(mid.theta) - PI).abs() < 1e-12);
169        assert!((space.distance(&a, &mid) - 0.5 * space.distance(&a, &b)).abs() < 1e-12);
170        assert_eq!(space.interpolate(&a, &b, 0.0), a);
171        assert_eq!(space.interpolate(&a, &b, 1.0), b);
172    }
173
174    #[test]
175    fn distance_is_a_metric_on_samples() {
176        let space = Se2::new(0.7);
177        let mut sampler = UniformSe2::new([-5.0, -5.0], [5.0, 5.0]);
178        let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(2);
179
180        for _ in 0..1000 {
181            let [a, b, c] = [(); 3].map(|()| sampler.sample(&mut rng));
182            assert!(sampler.contains(&a) && (-PI..PI).contains(&a.theta));
183            assert!((space.distance(&a, &b) - space.distance(&b, &a)).abs() < 1e-12);
184            assert!(
185                space.distance(&a, &c) <= space.distance(&a, &b) + space.distance(&b, &c) + 1e-9
186            );
187        }
188
189        let a = Se2State::new(1.0, 1.0, 1.0);
190        assert!(space.distance(&a, &a).abs() < f64::EPSILON);
191    }
192
193    #[test]
194    #[should_panic(expected = "rotation weight")]
195    fn rejects_non_positive_weights() {
196        let _ = Se2::new(0.0);
197    }
198}