Skip to main content

sampling_planning/space/
so2.rs

1//! The rotation group SO(2): planar orientations.
2
3use core::f64::consts::{PI, TAU};
4
5use rand_core::Rng;
6
7use crate::{Sampler, StateSpace, unit_f64};
8
9/// Wraps an angle in radians into `[-pi, pi)`.
10///
11/// # Examples
12///
13/// ```
14/// use sampling_planning::wrap_angle;
15///
16/// assert!((wrap_angle(3.0 * std::f64::consts::PI) + std::f64::consts::PI).abs() < 1e-12);
17/// assert_eq!(wrap_angle(0.5), 0.5);
18/// ```
19#[must_use]
20pub fn wrap_angle(angle: f64) -> f64 {
21    let wrapped = angle - TAU * libm::floor((angle + PI) / TAU);
22
23    // Rounding can land exactly on +pi; that is the same orientation as -pi.
24    if wrapped >= PI {
25        wrapped - TAU
26    } else {
27        wrapped
28    }
29}
30
31/// The signed shortest rotation from `from` to `to`, in `[-pi, pi)`.
32///
33/// A half turn is reported as `-pi`, so the result is deterministic for antipodal angles.
34#[must_use]
35pub fn angle_difference(from: f64, to: f64) -> f64 {
36    wrap_angle(to - from)
37}
38
39/// The space of planar orientations: angles in radians, identified modulo `2 pi`.
40///
41/// The distance is the length of the shorter arc, at most `pi`; interpolation turns along that
42/// arc. States may be any finite angle; results of [`StateSpace::interpolate`] are wrapped
43/// into `[-pi, pi)`, except that `t = 0` and `t = 1` return the endpoints verbatim.
44///
45/// # Examples
46///
47/// ```
48/// use sampling_planning::{So2, StateSpace};
49///
50/// let (a, b) = (3.0, -3.0);
51/// assert!((So2.distance(&a, &b) - (2.0 * std::f64::consts::PI - 6.0)).abs() < 1e-12);
52/// ```
53#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
54pub struct So2;
55
56impl StateSpace for So2 {
57    type State = f64;
58
59    fn dimension(&self) -> usize {
60        1
61    }
62
63    fn distance(&self, from: &f64, to: &f64) -> f64 {
64        libm::fabs(angle_difference(*from, *to))
65    }
66
67    fn interpolate(&self, from: &f64, to: &f64, t: f64) -> f64 {
68        interpolate_angle(*from, *to, t)
69    }
70}
71
72/// Turns from `from` toward `to` along the shorter arc by the fraction `t`, wrapped into
73/// `[-pi, pi)`; `t = 0` and `t = 1` return the endpoints verbatim.
74pub(crate) fn interpolate_angle(from: f64, to: f64, t: f64) -> f64 {
75    if t <= 0.0 {
76        from
77    } else if t >= 1.0 {
78        to
79    } else {
80        wrap_angle(from + t * angle_difference(from, to))
81    }
82}
83
84/// Samples orientations uniformly from `[-pi, pi)`.
85#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
86pub struct UniformAngle;
87
88impl Sampler<f64> for UniformAngle {
89    fn sample<R: Rng + ?Sized>(&mut self, rng: &mut R) -> f64 {
90        uniform_angle(rng)
91    }
92}
93
94/// A uniform angle in `[-pi, pi)` from one RNG draw.
95pub(crate) fn uniform_angle<R: Rng + ?Sized>(rng: &mut R) -> f64 {
96    TAU * unit_f64(rng) - PI
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102    use rand_core::SeedableRng;
103
104    #[test]
105    fn wrapping_covers_both_directions_and_the_seam() {
106        assert!((wrap_angle(PI) + PI).abs() < 1e-15);
107        assert!((wrap_angle(-PI) + PI).abs() < 1e-15);
108        assert!((wrap_angle(7.0) - (7.0 - TAU)).abs() < 1e-12);
109        assert!((wrap_angle(-7.0) - (TAU - 7.0)).abs() < 1e-12);
110        assert!((angle_difference(3.0, -3.0) - (TAU - 6.0)).abs() < 1e-12);
111        assert!((angle_difference(-3.0, 3.0) + (TAU - 6.0)).abs() < 1e-12);
112    }
113
114    #[test]
115    fn interpolation_takes_the_short_way_across_the_seam() {
116        let (a, b) = (3.0, -3.0);
117        let mid = So2.interpolate(&a, &b, 0.5);
118
119        assert!((libm::fabs(mid) - PI).abs() < 1e-12, "{mid}");
120        assert_eq!(So2.interpolate(&a, &b, 0.0), a);
121        assert_eq!(So2.interpolate(&a, &b, 1.0), b);
122        assert!((So2.distance(&a, &mid) - 0.5 * So2.distance(&a, &b)).abs() < 1e-12);
123    }
124
125    #[test]
126    fn distance_is_a_metric_on_samples() {
127        let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(1);
128
129        for _ in 0..1000 {
130            let [a, b, c] = [(); 3].map(|()| UniformAngle.sample(&mut rng));
131            assert!((-PI..PI).contains(&a));
132            assert!((So2.distance(&a, &b) - So2.distance(&b, &a)).abs() < 1e-12);
133            assert!(So2.distance(&a, &b) <= PI);
134            assert!(So2.distance(&a, &c) <= So2.distance(&a, &b) + So2.distance(&b, &c) + 1e-12);
135        }
136    }
137}