Skip to main content

pamoja_kit/
odometry.rs

1//! Dead-reckoning a robot's pose from its motion.
2
3use crate::motion::{clamp, magnitude, wrap_pi, Pose};
4use crate::DiffDrive;
5use libm::{cosf, sinf};
6
7/// Tracks a robot's [`Pose`] by accumulating its motion over time (odometry).
8///
9/// With no GPS indoors, a robot estimates where it is by adding up where it has been: each small
10/// move is integrated onto the running pose. This uses the exact arc model rather than a straight-
11/// line step, so a robot that drives and turns at once follows the curve it actually traces
12/// instead of cutting the corner; over many steps that is markedly more accurate. Feed it either a
13/// body motion (forward speed and yaw rate over a time step) or wheel-distance deltas through a
14/// [`DiffDrive`] model. Dead reckoning drifts, so correct the heading from an absolute source with
15/// [`fuse_heading`](Odometry::fuse_heading) when one is available.
16///
17/// # Examples
18///
19/// ```
20/// use pamoja_kit::{Odometry, Pose};
21///
22/// // Drive a quarter circle of radius 1 m: forward 1 m/s, turning left at 1 rad/s, for pi/2 s.
23/// let mut odom = Odometry::at_origin();
24/// let pose = odom.integrate(1.0, 1.0, core::f32::consts::FRAC_PI_2);
25///
26/// // It ends about (1, 1) facing 90 degrees, the far corner of the arc.
27/// assert!((pose.x - 1.0).abs() < 1e-5);
28/// assert!((pose.y - 1.0).abs() < 1e-5);
29/// assert!((pose.theta - core::f32::consts::FRAC_PI_2).abs() < 1e-5);
30/// ```
31#[derive(Clone, Copy, Debug)]
32pub struct Odometry {
33    pose: Pose,
34}
35
36impl Odometry {
37    /// Creates an estimator starting from a known pose.
38    ///
39    /// # Arguments
40    ///
41    /// * `start` - the initial pose.
42    ///
43    /// # Returns
44    ///
45    /// The estimator.
46    pub fn new(start: Pose) -> Self {
47        Self { pose: start }
48    }
49
50    /// Creates an estimator starting at the origin facing along the x axis.
51    ///
52    /// # Returns
53    ///
54    /// The estimator.
55    pub fn at_origin() -> Self {
56        Self {
57            pose: Pose::origin(),
58        }
59    }
60
61    /// Returns the current pose estimate.
62    ///
63    /// # Returns
64    ///
65    /// The pose accumulated so far.
66    pub fn pose(&self) -> Pose {
67        self.pose
68    }
69
70    /// Resets the estimate to a known pose.
71    ///
72    /// # Arguments
73    ///
74    /// * `pose` - the pose to set.
75    pub fn reset(&mut self, pose: Pose) {
76        self.pose = pose;
77    }
78
79    /// Integrates a body motion over a time step and returns the new pose.
80    ///
81    /// # Arguments
82    ///
83    /// * `linear` - the forward speed.
84    /// * `angular` - the yaw rate, positive turning left.
85    /// * `dt` - the length of the time step.
86    ///
87    /// # Returns
88    ///
89    /// The updated pose.
90    pub fn integrate(&mut self, linear: f32, angular: f32, dt: f32) -> Pose {
91        self.advance(linear * dt, angular * dt);
92        self.pose
93    }
94
95    /// Integrates wheel-distance deltas through a differential-drive model.
96    ///
97    /// # Arguments
98    ///
99    /// * `left` - the distance the left wheel rolled since the last update.
100    /// * `right` - the distance the right wheel rolled since the last update.
101    /// * `drive` - the [`DiffDrive`] model giving the track between the wheels.
102    ///
103    /// # Returns
104    ///
105    /// The updated pose. The wheel deltas are turned into a forward distance and a heading
106    /// change by [`DiffDrive::body_motion`], then integrated as one arc.
107    pub fn integrate_wheels(&mut self, left: f32, right: f32, drive: &DiffDrive) -> Pose {
108        let (distance, heading_change) = drive.body_motion(left, right);
109        self.advance(distance, heading_change);
110        self.pose
111    }
112
113    /// Corrects the heading toward an absolute measurement, the way a compass tames gyro drift.
114    ///
115    /// This is the angular cousin of [`Complementary`](crate::Complementary): it nudges the
116    /// estimated heading along the shortest arc toward an absolute reading (an IMU yaw, a
117    /// magnetometer, a GPS course) by a blend weight, leaving the position untouched.
118    ///
119    /// # Arguments
120    ///
121    /// * `measured` - the absolute heading in radians.
122    /// * `weight` - how strongly to trust the measurement, clamped to `[0, 1]`; zero keeps the
123    ///   dead-reckoned heading, one snaps to `measured`.
124    pub fn fuse_heading(&mut self, measured: f32, weight: f32) {
125        let w = clamp(weight, 0.0, 1.0);
126        let error = wrap_pi(measured - self.pose.theta);
127        self.pose.theta = wrap_pi(self.pose.theta + w * error);
128    }
129
130    // Advances the pose by an arc of forward distance `distance` and heading change
131    // `heading_change`, using the exact integration for a constant-curvature segment.
132    fn advance(&mut self, distance: f32, heading_change: f32) {
133        let theta = self.pose.theta;
134        if magnitude(heading_change) < 1e-6 {
135            self.pose.x += distance * cosf(theta);
136            self.pose.y += distance * sinf(theta);
137            self.pose.theta = wrap_pi(theta + heading_change);
138        } else {
139            let radius = distance / heading_change;
140            let new_theta = theta + heading_change;
141            self.pose.x += radius * (sinf(new_theta) - sinf(theta));
142            self.pose.y += radius * (cosf(theta) - cosf(new_theta));
143            self.pose.theta = wrap_pi(new_theta);
144        }
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151    use core::f32::consts::{FRAC_PI_2, PI};
152
153    #[test]
154    fn driving_straight_moves_along_the_heading() {
155        let mut odom = Odometry::new(Pose::new(0.0, 0.0, FRAC_PI_2)); // facing +y
156        let pose = odom.integrate(2.0, 0.0, 1.0);
157        assert!(pose.x.abs() < 1e-5);
158        assert!((pose.y - 2.0).abs() < 1e-5);
159        assert!((pose.theta - FRAC_PI_2).abs() < 1e-6);
160    }
161
162    #[test]
163    fn a_quarter_circle_lands_at_the_arc_corner() {
164        let mut odom = Odometry::at_origin();
165        let pose = odom.integrate(1.0, 1.0, FRAC_PI_2);
166        assert!((pose.x - 1.0).abs() < 1e-5);
167        assert!((pose.y - 1.0).abs() < 1e-5);
168        assert!((pose.theta - FRAC_PI_2).abs() < 1e-5);
169    }
170
171    #[test]
172    fn wheel_deltas_match_a_spin_in_place() {
173        let drive = DiffDrive::new(0.5);
174        let mut odom = Odometry::at_origin();
175        // Equal and opposite wheel deltas: turn in place, no translation.
176        let pose = odom.integrate_wheels(-0.25, 0.25, &drive);
177        assert!(pose.x.abs() < 1e-6 && pose.y.abs() < 1e-6);
178        assert!((pose.theta - 1.0).abs() < 1e-6); // (0.25 - -0.25) / 0.5 = 1 rad
179    }
180
181    #[test]
182    fn fuse_heading_blends_along_the_shortest_arc() {
183        let mut odom = Odometry::new(Pose::new(0.0, 0.0, 0.1));
184        odom.fuse_heading(0.5, 0.5); // halfway from 0.1 toward 0.5
185        assert!((odom.pose().theta - 0.3).abs() < 1e-6);
186    }
187
188    #[test]
189    fn fuse_heading_takes_the_short_way_across_pi() {
190        let mut odom = Odometry::new(Pose::new(0.0, 0.0, 3.0));
191        // Measured just past pi: the shortest arc wraps through pi, not the long way back.
192        odom.fuse_heading(-3.0, 1.0);
193        assert!((odom.pose().theta - -3.0).abs() < 1e-6);
194        assert!(odom.pose().theta.abs() <= PI);
195    }
196}