Skip to main content

visloc_localization/
odom_correction.rs

1//! Correcting gravity-aligned odometry into a map's frame with intermittent
2//! map fixes.
3//!
4//! Map-based localization gives an absolute pose only for some images (those
5//! that match the map well enough), while odometry such as VIO gives a pose for
6//! every frame but drifts. [`OdomCorrection`] keeps the transform from the
7//! odometry frame to the map frame (`map -> odom` in REP-105), updated from
8//! each map fix, so every odometry pose can be reported in the map frame.
9//!
10//! Both frames are assumed gravity-aligned (z up), as a VIO world and a map
11//! built by VIO are. The offset is then four degrees of freedom: a yaw about
12//! the vertical and a translation. Roll and pitch come from the odometry,
13//! which observes gravity directly.
14//!
15//! The correction is causal: it only uses fixes already added. Per fix it
16//!
17//! - **initializes** once `init_fixes` consecutive fixes agree on one offset,
18//!   so a single wrong fix cannot place the trajectory;
19//! - **accepts** a fix whose map pose lies within a gate of where the current
20//!   offset puts the odometry pose; the gate widens with the odometry
21//!   distance travelled since the last accepted fix, to absorb drift;
22//!   that distance is the odometry's path through the poses passed to
23//!   [`OdomCorrection::observe_odometry`], or, without them, the straight
24//!   lines between the odometry positions of consecutive fixes, which
25//!   undercount a path that turns or doubles back;
26//! - **rejects** any other fix, and **resets** the offset when `reset_after`
27//!   consecutive rejected fixes agree with each other (the odometry itself
28//!   jumped, or the earlier offset was wrong).
29//!
30//! A *weak* fix ([`OdomCorrection::add_weak_fix`]) is a localization with
31//! fewer inliers than a fix needs, which is more often wrong. Weak fixes help
32//! to set the first offset, and then `init_fixes_weak` (more than
33//! `init_fixes`) consecutive fixes must agree. Under lighting the map was not
34//! built in, the first images that localize at all often have too few
35//! inliers for a fix. Once the offset is set, weak fixes are not used by
36//! default; with `weak_gate_m` set, one that lies that close to where the
37//! offset puts the odometry pose is accepted, which keeps the offset
38//! following the odometry's drift where full fixes are rare. It never
39//! counts toward a reset.
40//!
41//! The offset is the mean over the accepted fixes of the last `window_s`
42//! seconds (circular mean for the yaw), which averages out localization noise
43//! while following slow odometry drift.
44
45use std::collections::VecDeque;
46
47/// How far back [`OdomCorrection::observe_odometry`] keeps the odometry's
48/// path. A fix older than that, relative to the newest odometry pose, falls
49/// back to the straight-line distance.
50const PATH_HISTORY_NS: i64 = 30_000_000_000;
51
52use nalgebra::{UnitQuaternion, Vector3};
53use visloc_core::geometry::SE3;
54
55#[derive(Debug, Clone, PartialEq)]
56pub struct OdomCorrectionConfig {
57    /// Consecutive mutually consistent fixes needed before the first offset.
58    pub init_fixes: usize,
59    /// ... when any of them is weak ([`OdomCorrection::add_weak_fix`]).
60    pub init_fixes_weak: usize,
61    /// Consecutive mutually consistent rejected fixes that replace the offset.
62    pub reset_after: usize,
63    /// Position tolerance, in metres, for fixes to count as agreeing with
64    /// each other (initialization, reset).
65    pub agreement_m: f64,
66    /// Position gate, in metres, for accepting a fix right after another.
67    pub gate_m: f64,
68    /// Extra position gate per metre of odometry travel since the last
69    /// accepted fix.
70    pub gate_per_m: f64,
71    /// Yaw gate, in degrees, for agreement and acceptance.
72    pub gate_yaw_deg: f64,
73    /// Extra yaw gate, in degrees, per metre of odometry travel since the
74    /// last accepted fix.
75    pub gate_yaw_per_m_deg: f64,
76    /// Accepted fixes older than this (relative to the newest) leave the
77    /// averaging window.
78    pub window_s: f64,
79    /// Once the offset is set, a weak fix within this distance of where the
80    /// offset puts the odometry pose (and within `weak_gate_yaw_deg`) is
81    /// accepted like a fix; 0, the default, leaves weak fixes unused then.
82    /// Unlike a fix's gate, it does not widen with travel.
83    pub weak_gate_m: f64,
84    /// Yaw gate, in degrees, for accepting a weak fix (`weak_gate_m`).
85    pub weak_gate_yaw_deg: f64,
86}
87
88impl Default for OdomCorrectionConfig {
89    fn default() -> Self {
90        Self {
91            init_fixes: 2,
92            init_fixes_weak: 3,
93            reset_after: 3,
94            agreement_m: 0.10,
95            gate_m: 0.15,
96            gate_per_m: 0.05,
97            gate_yaw_deg: 3.0,
98            gate_yaw_per_m_deg: 1.0,
99            window_s: 5.0,
100            weak_gate_m: 0.0,
101            weak_gate_yaw_deg: 2.0,
102        }
103    }
104}
105
106/// What [`OdomCorrection::add_fix`] did with a fix.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum FixOutcome {
109    /// No offset yet; the fix waits for agreeing ones.
110    Pending,
111    /// This fix completed initialization.
112    Initialized,
113    /// The fix agreed with the offset and updated it.
114    Accepted,
115    /// The fix disagreed with the offset and was not used.
116    Rejected,
117    /// This fix completed a run of agreeing rejected fixes, which replaced
118    /// the offset.
119    Reset,
120    /// A weak fix after the offset was set: not used.
121    Unused,
122}
123
124/// Four-degree-of-freedom transform: `p_map = Rz(yaw) * p_odom + translation`.
125#[derive(Debug, Clone, Copy, PartialEq)]
126pub(crate) struct Offset {
127    pub(crate) yaw: f64,
128    pub(crate) translation: Vector3<f64>,
129}
130
131impl Offset {
132    pub(crate) fn rotation(&self) -> UnitQuaternion<f64> {
133        UnitQuaternion::from_axis_angle(&Vector3::z_axis(), self.yaw)
134    }
135
136    pub(crate) fn se3(&self) -> SE3 {
137        SE3::new(self.rotation(), self.translation)
138    }
139}
140
141#[derive(Debug, Clone, PartialEq)]
142struct Fix {
143    timestamp_ns: i64,
144    map_position: Vector3<f64>,
145    odom_position: Vector3<f64>,
146    /// Yaw of `map_from_body * odom_from_body^-1`, the offset this fix alone
147    /// implies.
148    yaw: f64,
149    weak: bool,
150}
151
152pub(crate) fn yaw_of(rotation: &UnitQuaternion<f64>) -> f64 {
153    let matrix = rotation.to_rotation_matrix();
154    matrix[(1, 0)].atan2(matrix[(0, 0)])
155}
156
157pub(crate) fn wrap_angle(angle: f64) -> f64 {
158    (angle + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI
159}
160
161/// Mean offset over `fixes` (non-empty): circular mean yaw, then the mean
162/// translation under that yaw.
163fn fit(fixes: &[&Fix]) -> Offset {
164    let (sin, cos) = fixes.iter().fold((0.0, 0.0), |(sin, cos), fix| {
165        (sin + fix.yaw.sin(), cos + fix.yaw.cos())
166    });
167    let yaw = sin.atan2(cos);
168    let rotation = UnitQuaternion::from_axis_angle(&Vector3::z_axis(), yaw);
169    let translation = fixes
170        .iter()
171        .map(|fix| fix.map_position - rotation * fix.odom_position)
172        .sum::<Vector3<f64>>()
173        / fixes.len() as f64;
174    Offset { yaw, translation }
175}
176
177fn residuals(offset: &Offset, fix: &Fix) -> (f64, f64) {
178    let predicted = offset.rotation() * fix.odom_position + offset.translation;
179    (
180        (predicted - fix.map_position).norm(),
181        wrap_angle(fix.yaw - offset.yaw).abs().to_degrees(),
182    )
183}
184
185#[derive(Debug, Clone)]
186pub struct OdomCorrection {
187    config: OdomCorrectionConfig,
188    offset: Option<Offset>,
189    /// Accepted fixes inside the averaging window, oldest first.
190    window: VecDeque<Fix>,
191    /// Pending (before initialization) or consecutive rejected fixes.
192    candidates: Vec<Fix>,
193    /// Odometry position of the previous fix, and the odometry path length
194    /// (sampled at fixes) since the last accepted one.
195    previous_odom_position: Option<Vector3<f64>>,
196    travel_since_accept_m: f64,
197    /// Observed odometry, oldest first: stamp and path length from the first
198    /// observed pose. Covers at most `PATH_HISTORY_NS`.
199    path: VecDeque<(i64, f64)>,
200    /// Position of the newest observed odometry pose.
201    path_end: Option<Vector3<f64>>,
202    /// Path length at the last accepted fix, when the path covered it.
203    path_at_accept_m: Option<f64>,
204}
205
206impl OdomCorrection {
207    pub fn new(config: OdomCorrectionConfig) -> Self {
208        Self {
209            config,
210            offset: None,
211            window: VecDeque::new(),
212            candidates: Vec::new(),
213            previous_odom_position: None,
214            travel_since_accept_m: 0.0,
215            path: VecDeque::new(),
216            path_end: None,
217            path_at_accept_m: None,
218        }
219    }
220
221    pub const fn config(&self) -> &OdomCorrectionConfig {
222        &self.config
223    }
224
225    /// Whether the offset is set, i.e. odometry poses have a map pose.
226    pub const fn is_set(&self) -> bool {
227        self.offset.is_some()
228    }
229
230    /// The current odometry-to-map transform, once set.
231    pub fn map_from_odom(&self) -> Option<SE3> {
232        self.offset.as_ref().map(Offset::se3)
233    }
234
235    /// Timestamp and odometry position of the newest fix the offset uses.
236    /// The error of [`Self::map_from_body`] grows with the odometry travel
237    /// (and time) since this fix, so callers can use it to judge a pose.
238    pub fn last_fix(&self) -> Option<(i64, Vector3<f64>)> {
239        self.offset?;
240        self.window
241            .back()
242            .map(|fix| (fix.timestamp_ns, fix.odom_position))
243    }
244
245    /// An odometry pose expressed in the map frame, once set.
246    pub fn map_from_body(&self, odom_from_body: &SE3) -> Option<SE3> {
247        self.map_from_odom()
248            .map(|map_from_odom| map_from_odom.compose(odom_from_body))
249    }
250
251    /// Adds an odometry pose, so the gate measures the odometry's travel
252    /// along its path rather than between fixes. Poses must arrive in time
253    /// order (older or repeated stamps are ignored), but may run ahead of the
254    /// fixes: a fix's travel is read off the path at its own stamp.
255    pub fn observe_odometry(&mut self, timestamp_ns: i64, odom_from_body: &SE3) {
256        if self
257            .path
258            .back()
259            .is_some_and(|(last_ns, _)| timestamp_ns <= *last_ns)
260        {
261            return;
262        }
263        let position = odom_from_body.translation;
264        let length = match (self.path.back(), self.path_end) {
265            (Some((_, length)), Some(end)) => length + (position - end).norm(),
266            _ => 0.0,
267        };
268        self.path.push_back((timestamp_ns, length));
269        self.path_end = Some(position);
270        while self
271            .path
272            .front()
273            .is_some_and(|(first_ns, _)| timestamp_ns - first_ns > PATH_HISTORY_NS)
274        {
275            self.path.pop_front();
276        }
277    }
278
279    /// Path length of the observed odometry at `timestamp_ns`, interpolated
280    /// between the poses around it; `None` outside the observed path.
281    fn path_length_at(&self, timestamp_ns: i64) -> Option<f64> {
282        let (first_ns, _) = self.path.front()?;
283        let (last_ns, _) = self.path.back()?;
284        if timestamp_ns < *first_ns || timestamp_ns > *last_ns {
285            return None;
286        }
287        let index = self
288            .path
289            .partition_point(|(stamp, _)| *stamp < timestamp_ns);
290        let (after_ns, after) = self.path[index];
291        if after_ns == timestamp_ns || index == 0 {
292            return Some(after);
293        }
294        let (before_ns, before) = self.path[index - 1];
295        let alpha = (timestamp_ns - before_ns) as f64 / (after_ns - before_ns) as f64;
296        Some(before + alpha * (after - before))
297    }
298
299    /// Adds a map fix: the body's map pose from localization, and its
300    /// odometry pose at the same instant. Fixes must arrive in time order.
301    pub fn add_fix(
302        &mut self,
303        timestamp_ns: i64,
304        map_from_body: &SE3,
305        odom_from_body: &SE3,
306    ) -> FixOutcome {
307        self.add(timestamp_ns, map_from_body, odom_from_body, false)
308    }
309
310    /// Adds a weak fix: a localization with fewer inliers than a fix needs.
311    /// It counts toward setting the first offset, which then takes
312    /// `init_fixes_weak` agreeing fixes, and is [`FixOutcome::Unused`] once
313    /// the offset is set.
314    pub fn add_weak_fix(
315        &mut self,
316        timestamp_ns: i64,
317        map_from_body: &SE3,
318        odom_from_body: &SE3,
319    ) -> FixOutcome {
320        self.add(timestamp_ns, map_from_body, odom_from_body, true)
321    }
322
323    fn add(
324        &mut self,
325        timestamp_ns: i64,
326        map_from_body: &SE3,
327        odom_from_body: &SE3,
328        weak: bool,
329    ) -> FixOutcome {
330        let fix = Fix {
331            timestamp_ns,
332            map_position: map_from_body.translation,
333            odom_position: odom_from_body.translation,
334            yaw: yaw_of(&(map_from_body.rotation * odom_from_body.rotation.inverse())),
335            weak,
336        };
337        if let Some(previous) = self.previous_odom_position {
338            self.travel_since_accept_m += (fix.odom_position - previous).norm();
339        }
340        self.previous_odom_position = Some(fix.odom_position);
341        let path_m = self.path_length_at(timestamp_ns);
342
343        let Some(offset) = self.offset else {
344            return if self.push_initial(fix) {
345                Self::adopt(&mut self.window, &mut self.candidates);
346                self.refit();
347                self.restart_travel(path_m);
348                FixOutcome::Initialized
349            } else {
350                FixOutcome::Pending
351            };
352        };
353
354        let (position_residual, yaw_residual) = residuals(&offset, &fix);
355        if weak {
356            if self.config.weak_gate_m > 0.0
357                && position_residual <= self.config.weak_gate_m
358                && yaw_residual <= self.config.weak_gate_yaw_deg
359            {
360                self.candidates.clear();
361                self.window.push_back(fix);
362                self.refit();
363                self.restart_travel(path_m);
364                return FixOutcome::Accepted;
365            }
366            return FixOutcome::Unused;
367        }
368        let travel = match (path_m, self.path_at_accept_m) {
369            (Some(now), Some(then)) => self.travel_since_accept_m.max(now - then),
370            _ => self.travel_since_accept_m,
371        };
372        let accepted = position_residual <= self.config.gate_m + self.config.gate_per_m * travel
373            && yaw_residual <= self.config.gate_yaw_deg + self.config.gate_yaw_per_m_deg * travel;
374        if accepted {
375            self.candidates.clear();
376            self.window.push_back(fix);
377            self.refit();
378            self.restart_travel(path_m);
379            return FixOutcome::Accepted;
380        }
381        if self.push_candidate(fix, self.config.reset_after) {
382            Self::adopt(&mut self.window, &mut self.candidates);
383            self.refit();
384            self.restart_travel(path_m);
385            FixOutcome::Reset
386        } else {
387            FixOutcome::Rejected
388        }
389    }
390
391    /// Measures travel from a fix just accepted, at path length `path_m`.
392    fn restart_travel(&mut self, path_m: Option<f64>) {
393        self.travel_since_accept_m = 0.0;
394        self.path_at_accept_m = path_m;
395    }
396
397    /// Appends to the candidate run, keeping only its last `needed` fixes,
398    /// and reports whether that many now agree on one offset.
399    fn push_candidate(&mut self, fix: Fix, needed: usize) -> bool {
400        self.candidates.push(fix);
401        let needed = needed.max(1);
402        if self.candidates.len() > needed {
403            self.candidates.drain(..self.candidates.len() - needed);
404        }
405        self.candidates.len() == needed && self.agree(&self.candidates)
406    }
407
408    /// Appends to the candidate run before the first offset and reports
409    /// whether its newest fixes now set it: `init_fixes` of them agreeing, or
410    /// `init_fixes_weak` when any of those is weak. On success the run keeps
411    /// only those.
412    fn push_initial(&mut self, fix: Fix) -> bool {
413        let strong = self.config.init_fixes.max(1);
414        let weak = self.config.init_fixes_weak.max(strong);
415        self.candidates.push(fix);
416        if self.candidates.len() > weak {
417            self.candidates.drain(..self.candidates.len() - weak);
418        }
419        for needed in [strong, weak] {
420            let Some(start) = self.candidates.len().checked_sub(needed) else {
421                continue;
422            };
423            let newest = &self.candidates[start..];
424            let required = if newest.iter().any(|fix| fix.weak) {
425                weak
426            } else {
427                strong
428            };
429            if needed == required && self.agree(newest) {
430                self.candidates.drain(..start);
431                return true;
432            }
433        }
434        false
435    }
436
437    /// Whether `fixes` agree on one offset.
438    fn agree(&self, fixes: &[Fix]) -> bool {
439        let fixes = fixes.iter().collect::<Vec<_>>();
440        let offset = fit(&fixes);
441        fixes.iter().all(|fix| {
442            let (position, yaw) = residuals(&offset, fix);
443            position <= self.config.agreement_m && yaw <= self.config.gate_yaw_deg
444        })
445    }
446
447    fn adopt(window: &mut VecDeque<Fix>, candidates: &mut Vec<Fix>) {
448        window.clear();
449        window.extend(candidates.drain(..));
450    }
451
452    /// Drops fixes outside the window and re-estimates the offset.
453    fn refit(&mut self) {
454        let Some(newest) = self.window.back().map(|fix| fix.timestamp_ns) else {
455            return;
456        };
457        let window_ns = (self.config.window_s * 1e9) as i64;
458        while self.window.len() > 1
459            && self
460                .window
461                .front()
462                .is_some_and(|fix| newest - fix.timestamp_ns > window_ns)
463        {
464            self.window.pop_front();
465        }
466        let fixes = self.window.iter().collect::<Vec<_>>();
467        self.offset = Some(fit(&fixes));
468    }
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474
475    const SECOND: i64 = 1_000_000_000;
476
477    fn truth() -> SE3 {
478        SE3::new(
479            UnitQuaternion::from_axis_angle(&Vector3::z_axis(), 0.6),
480            Vector3::new(3.0, -2.0, 0.5),
481        )
482    }
483
484    /// Odometry pose `index` on a curved, tilting path.
485    fn odom(index: usize) -> SE3 {
486        let t = index as f64 * 0.2;
487        SE3::new(
488            UnitQuaternion::from_euler_angles(0.05 * t.sin(), -0.03, 0.4 * t),
489            Vector3::new(t.cos() * 2.0, t.sin() * 2.0, 0.1 * t),
490        )
491    }
492
493    fn fix_at(
494        correction: &mut OdomCorrection,
495        index: usize,
496        map_from_odom: &SE3,
497        shift: Vector3<f64>,
498    ) -> FixOutcome {
499        let odom_from_body = odom(index);
500        let mut map_from_body = map_from_odom.compose(&odom_from_body);
501        map_from_body.translation += shift;
502        correction.add_fix(index as i64 * SECOND / 10, &map_from_body, &odom_from_body)
503    }
504
505    fn assert_pose_close(lhs: &SE3, rhs: &SE3, tolerance: f64) {
506        assert!(
507            (lhs.translation - rhs.translation).norm() < tolerance,
508            "{lhs:?} vs {rhs:?}"
509        );
510        assert!(
511            lhs.rotation.angle_to(&rhs.rotation) < tolerance,
512            "{lhs:?} vs {rhs:?}"
513        );
514    }
515
516    #[test]
517    fn exact_fixes_recover_the_offset_after_initialization() {
518        let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
519        assert_eq!(correction.map_from_body(&odom(0)), None);
520        assert_eq!(
521            fix_at(&mut correction, 0, &truth(), Vector3::zeros()),
522            FixOutcome::Pending
523        );
524        assert_eq!(correction.last_fix(), None);
525        assert_eq!(
526            fix_at(&mut correction, 1, &truth(), Vector3::zeros()),
527            FixOutcome::Initialized
528        );
529        assert_eq!(
530            fix_at(&mut correction, 2, &truth(), Vector3::zeros()),
531            FixOutcome::Accepted
532        );
533        assert_eq!(
534            correction.last_fix(),
535            Some((2 * SECOND / 10, odom(2).translation))
536        );
537        for index in [3, 10, 40] {
538            let pose = correction.map_from_body(&odom(index)).expect("set");
539            assert_pose_close(&pose, &truth().compose(&odom(index)), 1e-9);
540        }
541    }
542
543    #[test]
544    fn a_wrong_first_fix_does_not_place_the_trajectory() {
545        let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
546        let off = Vector3::new(1.5, 0.0, 0.0);
547        assert_eq!(
548            fix_at(&mut correction, 0, &truth(), off),
549            FixOutcome::Pending
550        );
551        assert_eq!(
552            fix_at(&mut correction, 1, &truth(), Vector3::zeros()),
553            FixOutcome::Pending
554        );
555        assert_eq!(
556            fix_at(&mut correction, 2, &truth(), Vector3::zeros()),
557            FixOutcome::Initialized
558        );
559        assert_pose_close(&correction.map_from_odom().unwrap(), &truth(), 1e-9);
560    }
561
562    #[test]
563    fn an_outlier_is_rejected_and_leaves_the_offset_alone() {
564        let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
565        for index in 0..4 {
566            fix_at(&mut correction, index, &truth(), Vector3::zeros());
567        }
568        assert_eq!(
569            fix_at(&mut correction, 4, &truth(), Vector3::new(0.0, 2.0, 0.0)),
570            FixOutcome::Rejected
571        );
572        assert_pose_close(&correction.map_from_odom().unwrap(), &truth(), 1e-9);
573        assert_eq!(
574            fix_at(&mut correction, 5, &truth(), Vector3::zeros()),
575            FixOutcome::Accepted
576        );
577    }
578
579    fn weak_fix_at(
580        correction: &mut OdomCorrection,
581        index: usize,
582        shift: Vector3<f64>,
583    ) -> FixOutcome {
584        let odom_from_body = odom(index);
585        let mut map_from_body = truth().compose(&odom_from_body);
586        map_from_body.translation += shift;
587        correction.add_weak_fix(index as i64 * SECOND / 10, &map_from_body, &odom_from_body)
588    }
589
590    #[test]
591    fn weak_fixes_need_three_agreeing_and_only_set_the_first_offset() {
592        // Two weak fixes do not set the offset; a third agreeing one does.
593        let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
594        assert_eq!(
595            weak_fix_at(&mut correction, 0, Vector3::zeros()),
596            FixOutcome::Pending
597        );
598        assert_eq!(
599            weak_fix_at(&mut correction, 1, Vector3::zeros()),
600            FixOutcome::Pending
601        );
602        assert_eq!(
603            weak_fix_at(&mut correction, 2, Vector3::zeros()),
604            FixOutcome::Initialized
605        );
606        assert_pose_close(&correction.map_from_odom().unwrap(), &truth(), 1e-9);
607
608        // A strong fix after a weak one: still three, since one is weak.
609        let mut mixed = OdomCorrection::new(OdomCorrectionConfig::default());
610        assert_eq!(
611            weak_fix_at(&mut mixed, 0, Vector3::zeros()),
612            FixOutcome::Pending
613        );
614        assert_eq!(
615            fix_at(&mut mixed, 1, &truth(), Vector3::zeros()),
616            FixOutcome::Pending
617        );
618        assert_eq!(
619            fix_at(&mut mixed, 2, &truth(), Vector3::zeros()),
620            FixOutcome::Initialized
621        );
622        // Two strong fixes alone, as before.
623        let mut strong = OdomCorrection::new(OdomCorrectionConfig::default());
624        assert_eq!(
625            fix_at(&mut strong, 0, &truth(), Vector3::zeros()),
626            FixOutcome::Pending
627        );
628        assert_eq!(
629            fix_at(&mut strong, 1, &truth(), Vector3::zeros()),
630            FixOutcome::Initialized
631        );
632
633        // A wrong weak fix breaks the run; three agreeing ones after it set
634        // the offset to theirs.
635        let mut broken = OdomCorrection::new(OdomCorrectionConfig::default());
636        let off = Vector3::new(1.5, 0.0, 0.0);
637        assert_eq!(
638            weak_fix_at(&mut broken, 0, Vector3::zeros()),
639            FixOutcome::Pending
640        );
641        assert_eq!(weak_fix_at(&mut broken, 1, off), FixOutcome::Pending);
642        assert_eq!(
643            weak_fix_at(&mut broken, 2, Vector3::zeros()),
644            FixOutcome::Pending
645        );
646        assert_eq!(
647            weak_fix_at(&mut broken, 3, Vector3::zeros()),
648            FixOutcome::Pending
649        );
650        assert_eq!(
651            weak_fix_at(&mut broken, 4, Vector3::zeros()),
652            FixOutcome::Initialized
653        );
654        assert_pose_close(&broken.map_from_odom().unwrap(), &truth(), 1e-9);
655
656        // Once set, weak fixes are not used, however far off.
657        let before = correction.map_from_odom().unwrap();
658        assert_eq!(weak_fix_at(&mut correction, 3, off), FixOutcome::Unused);
659        assert_eq!(
660            weak_fix_at(&mut correction, 4, Vector3::zeros()),
661            FixOutcome::Unused
662        );
663        assert_pose_close(&correction.map_from_odom().unwrap(), &before, 1e-12);
664        assert_eq!(
665            fix_at(&mut correction, 5, &truth(), Vector3::zeros()),
666            FixOutcome::Accepted
667        );
668    }
669
670    #[test]
671    fn a_weak_gate_accepts_close_weak_fixes_after_the_first_offset() {
672        let mut correction = OdomCorrection::new(OdomCorrectionConfig {
673            weak_gate_m: 0.05,
674            ..OdomCorrectionConfig::default()
675        });
676        for index in 0..2 {
677            fix_at(&mut correction, index, &truth(), Vector3::zeros());
678        }
679        assert!(correction.is_set());
680        // 3 cm off: inside the weak gate, and it moves the offset.
681        let close = Vector3::new(0.03, 0.0, 0.0);
682        assert_eq!(weak_fix_at(&mut correction, 2, close), FixOutcome::Accepted);
683        let moved = correction.map_from_odom().unwrap().translation - truth().translation;
684        assert!((moved - close / 3.0).norm() < 1e-9, "{moved:?}");
685        // 8 cm off: inside a fix's gate, outside the weak one.
686        assert_eq!(
687            weak_fix_at(&mut correction, 3, Vector3::new(0.08, 0.0, 0.0)),
688            FixOutcome::Unused
689        );
690    }
691
692    #[test]
693    fn agreeing_rejected_fixes_reset_the_offset_after_an_odometry_jump() {
694        let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
695        for index in 0..4 {
696            fix_at(&mut correction, index, &truth(), Vector3::zeros());
697        }
698        // The odometry jumped: from now on the true offset is a different one.
699        let jumped = SE3::new(
700            UnitQuaternion::from_axis_angle(&Vector3::z_axis(), 0.75),
701            Vector3::new(2.0, -1.0, 0.5),
702        );
703        assert_eq!(
704            fix_at(&mut correction, 4, &jumped, Vector3::zeros()),
705            FixOutcome::Rejected
706        );
707        assert_eq!(
708            fix_at(&mut correction, 5, &jumped, Vector3::zeros()),
709            FixOutcome::Rejected
710        );
711        assert_eq!(
712            fix_at(&mut correction, 6, &jumped, Vector3::zeros()),
713            FixOutcome::Reset
714        );
715        assert_pose_close(&correction.map_from_odom().unwrap(), &jumped, 1e-9);
716    }
717
718    #[test]
719    fn the_gate_widens_with_travel_since_the_last_accepted_fix() {
720        let config = OdomCorrectionConfig::default();
721        let mut near = OdomCorrection::new(config.clone());
722        let mut far = OdomCorrection::new(config);
723        for index in 0..3 {
724            fix_at(&mut near, index, &truth(), Vector3::zeros());
725            fix_at(&mut far, index, &truth(), Vector3::zeros());
726        }
727        // 0.3 m off: beyond the 0.15 m base gate right after a fix, inside it
728        // after several metres of travel (sampled by an outlier fix on the way).
729        let drift = Vector3::new(0.0, 0.0, 0.3);
730        assert_eq!(fix_at(&mut near, 3, &truth(), drift), FixOutcome::Rejected);
731        assert_eq!(
732            fix_at(&mut far, 20, &truth(), Vector3::new(5.0, 0.0, 0.0)),
733            FixOutcome::Rejected
734        );
735        assert_eq!(fix_at(&mut far, 40, &truth(), drift), FixOutcome::Accepted);
736    }
737
738    #[test]
739    fn observed_odometry_measures_travel_along_the_path() {
740        let config = OdomCorrectionConfig::default();
741        let mut sampled = OdomCorrection::new(config.clone());
742        let mut observed = OdomCorrection::new(config);
743        // The odometry runs ahead of the fixes, as a localization finishes
744        // after later odometry has arrived.
745        for index in 0..=40 {
746            observed.observe_odometry(index as i64 * SECOND / 10, &odom(index));
747        }
748        for index in 0..3 {
749            fix_at(&mut sampled, index, &truth(), Vector3::zeros());
750            fix_at(&mut observed, index, &truth(), Vector3::zeros());
751        }
752        // Almost a full circle (11.6 m of path) ends 1.1 m from the last
753        // fix: 0.3 m off is outside the gate that straight line gives, and
754        // inside the one the path gives.
755        let drift = Vector3::new(0.0, 0.0, 0.3);
756        assert_eq!(
757            fix_at(&mut sampled, 31, &truth(), drift),
758            FixOutcome::Rejected
759        );
760        assert_eq!(
761            fix_at(&mut observed, 31, &truth(), drift),
762            FixOutcome::Accepted
763        );
764        // Travel restarts at the accepted fix.
765        assert_eq!(
766            fix_at(&mut observed, 32, &truth(), drift * 2.0),
767            FixOutcome::Rejected
768        );
769    }
770
771    #[test]
772    fn noisy_fixes_average_within_the_window() {
773        let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
774        // Alternating +-2 cm noise along x averages out.
775        for index in 0..20 {
776            let sign = if index % 2 == 0 { 1.0 } else { -1.0 };
777            fix_at(
778                &mut correction,
779                index,
780                &truth(),
781                Vector3::new(0.02 * sign, 0.0, 0.0),
782            );
783        }
784        let estimate = correction.map_from_odom().unwrap();
785        assert!((estimate.translation - truth().translation).norm() < 0.005);
786        // A 5 s window at 10 fixes per second keeps all 20 fixes.
787        assert_eq!(correction.window.len(), 20);
788    }
789
790    #[test]
791    fn old_fixes_leave_the_window() {
792        let mut correction = OdomCorrection::new(OdomCorrectionConfig {
793            window_s: 1.0,
794            ..OdomCorrectionConfig::default()
795        });
796        for index in 0..30 {
797            fix_at(&mut correction, index, &truth(), Vector3::zeros());
798        }
799        // 0.1 s apart: the newest fix and the ten before it are within 1 s.
800        assert_eq!(correction.window.len(), 11);
801    }
802}