sampling_planning/space/
so2.rs1use core::f64::consts::{PI, TAU};
4
5use rand_core::Rng;
6
7use crate::{Sampler, StateSpace, unit_f64};
8
9#[must_use]
20pub fn wrap_angle(angle: f64) -> f64 {
21 let wrapped = angle - TAU * libm::floor((angle + PI) / TAU);
22
23 if wrapped >= PI {
25 wrapped - TAU
26 } else {
27 wrapped
28 }
29}
30
31#[must_use]
35pub fn angle_difference(from: f64, to: f64) -> f64 {
36 wrap_angle(to - from)
37}
38
39#[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
72pub(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#[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
94pub(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}