visloc-localization 0.5.0

Stateless map-based visual-localization pipeline for visloc-rs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
//! Correcting gravity-aligned odometry into a map's frame with intermittent
//! map fixes.
//!
//! Map-based localization gives an absolute pose only for some images (those
//! that match the map well enough), while odometry such as VIO gives a pose for
//! every frame but drifts. [`OdomCorrection`] keeps the transform from the
//! odometry frame to the map frame (`map -> odom` in REP-105), updated from
//! each map fix, so every odometry pose can be reported in the map frame.
//!
//! Both frames are assumed gravity-aligned (z up), as a VIO world and a map
//! built by VIO are. The offset is then four degrees of freedom: a yaw about
//! the vertical and a translation. Roll and pitch come from the odometry,
//! which observes gravity directly.
//!
//! The correction is causal: it only uses fixes already added. Per fix it
//!
//! - **initializes** once `init_fixes` consecutive fixes agree on one offset,
//!   so a single wrong fix cannot place the trajectory;
//! - **accepts** a fix whose map pose lies within a gate of where the current
//!   offset puts the odometry pose; the gate widens with the odometry
//!   distance travelled since the last accepted fix, to absorb drift;
//!   that distance is the odometry's path through the poses passed to
//!   [`OdomCorrection::observe_odometry`], or, without them, the straight
//!   lines between the odometry positions of consecutive fixes, which
//!   undercount a path that turns or doubles back;
//! - **rejects** any other fix, and **resets** the offset when `reset_after`
//!   consecutive rejected fixes agree with each other (the odometry itself
//!   jumped, or the earlier offset was wrong).
//!
//! A *weak* fix ([`OdomCorrection::add_weak_fix`]) is a localization with
//! fewer inliers than a fix needs, which is more often wrong. Weak fixes help
//! to set the first offset, and then `init_fixes_weak` (more than
//! `init_fixes`) consecutive fixes must agree. Under lighting the map was not
//! built in, the first images that localize at all often have too few
//! inliers for a fix. Once the offset is set, weak fixes are not used by
//! default; with `weak_gate_m` set, one that lies that close to where the
//! offset puts the odometry pose is accepted, which keeps the offset
//! following the odometry's drift where full fixes are rare. It never
//! counts toward a reset.
//!
//! The offset is the mean over the accepted fixes of the last `window_s`
//! seconds (circular mean for the yaw), which averages out localization noise
//! while following slow odometry drift.

use std::collections::VecDeque;

/// How far back [`OdomCorrection::observe_odometry`] keeps the odometry's
/// path. A fix older than that, relative to the newest odometry pose, falls
/// back to the straight-line distance.
const PATH_HISTORY_NS: i64 = 30_000_000_000;

use nalgebra::{UnitQuaternion, Vector3};
use visloc_core::geometry::SE3;

#[derive(Debug, Clone, PartialEq)]
pub struct OdomCorrectionConfig {
    /// Consecutive mutually consistent fixes needed before the first offset.
    pub init_fixes: usize,
    /// ... when any of them is weak ([`OdomCorrection::add_weak_fix`]).
    pub init_fixes_weak: usize,
    /// Consecutive mutually consistent rejected fixes that replace the offset.
    pub reset_after: usize,
    /// Position tolerance, in metres, for fixes to count as agreeing with
    /// each other (initialization, reset).
    pub agreement_m: f64,
    /// Position gate, in metres, for accepting a fix right after another.
    pub gate_m: f64,
    /// Extra position gate per metre of odometry travel since the last
    /// accepted fix.
    pub gate_per_m: f64,
    /// Yaw gate, in degrees, for agreement and acceptance.
    pub gate_yaw_deg: f64,
    /// Extra yaw gate, in degrees, per metre of odometry travel since the
    /// last accepted fix.
    pub gate_yaw_per_m_deg: f64,
    /// Accepted fixes older than this (relative to the newest) leave the
    /// averaging window.
    pub window_s: f64,
    /// Once the offset is set, a weak fix within this distance of where the
    /// offset puts the odometry pose (and within `weak_gate_yaw_deg`) is
    /// accepted like a fix; 0, the default, leaves weak fixes unused then.
    /// Unlike a fix's gate, it does not widen with travel.
    pub weak_gate_m: f64,
    /// Yaw gate, in degrees, for accepting a weak fix (`weak_gate_m`).
    pub weak_gate_yaw_deg: f64,
}

impl Default for OdomCorrectionConfig {
    fn default() -> Self {
        Self {
            init_fixes: 2,
            init_fixes_weak: 3,
            reset_after: 3,
            agreement_m: 0.10,
            gate_m: 0.15,
            gate_per_m: 0.05,
            gate_yaw_deg: 3.0,
            gate_yaw_per_m_deg: 1.0,
            window_s: 5.0,
            weak_gate_m: 0.0,
            weak_gate_yaw_deg: 2.0,
        }
    }
}

/// What [`OdomCorrection::add_fix`] did with a fix.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FixOutcome {
    /// No offset yet; the fix waits for agreeing ones.
    Pending,
    /// This fix completed initialization.
    Initialized,
    /// The fix agreed with the offset and updated it.
    Accepted,
    /// The fix disagreed with the offset and was not used.
    Rejected,
    /// This fix completed a run of agreeing rejected fixes, which replaced
    /// the offset.
    Reset,
    /// A weak fix after the offset was set: not used.
    Unused,
}

/// Four-degree-of-freedom transform: `p_map = Rz(yaw) * p_odom + translation`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Offset {
    pub(crate) yaw: f64,
    pub(crate) translation: Vector3<f64>,
}

impl Offset {
    pub(crate) fn rotation(&self) -> UnitQuaternion<f64> {
        UnitQuaternion::from_axis_angle(&Vector3::z_axis(), self.yaw)
    }

    pub(crate) fn se3(&self) -> SE3 {
        SE3::new(self.rotation(), self.translation)
    }
}

#[derive(Debug, Clone, PartialEq)]
struct Fix {
    timestamp_ns: i64,
    map_position: Vector3<f64>,
    odom_position: Vector3<f64>,
    /// Yaw of `map_from_body * odom_from_body^-1`, the offset this fix alone
    /// implies.
    yaw: f64,
    weak: bool,
}

pub(crate) fn yaw_of(rotation: &UnitQuaternion<f64>) -> f64 {
    let matrix = rotation.to_rotation_matrix();
    matrix[(1, 0)].atan2(matrix[(0, 0)])
}

pub(crate) fn wrap_angle(angle: f64) -> f64 {
    (angle + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI
}

/// Mean offset over `fixes` (non-empty): circular mean yaw, then the mean
/// translation under that yaw.
fn fit(fixes: &[&Fix]) -> Offset {
    let (sin, cos) = fixes.iter().fold((0.0, 0.0), |(sin, cos), fix| {
        (sin + fix.yaw.sin(), cos + fix.yaw.cos())
    });
    let yaw = sin.atan2(cos);
    let rotation = UnitQuaternion::from_axis_angle(&Vector3::z_axis(), yaw);
    let translation = fixes
        .iter()
        .map(|fix| fix.map_position - rotation * fix.odom_position)
        .sum::<Vector3<f64>>()
        / fixes.len() as f64;
    Offset { yaw, translation }
}

fn residuals(offset: &Offset, fix: &Fix) -> (f64, f64) {
    let predicted = offset.rotation() * fix.odom_position + offset.translation;
    (
        (predicted - fix.map_position).norm(),
        wrap_angle(fix.yaw - offset.yaw).abs().to_degrees(),
    )
}

#[derive(Debug, Clone)]
pub struct OdomCorrection {
    config: OdomCorrectionConfig,
    offset: Option<Offset>,
    /// Accepted fixes inside the averaging window, oldest first.
    window: VecDeque<Fix>,
    /// Pending (before initialization) or consecutive rejected fixes.
    candidates: Vec<Fix>,
    /// Odometry position of the previous fix, and the odometry path length
    /// (sampled at fixes) since the last accepted one.
    previous_odom_position: Option<Vector3<f64>>,
    travel_since_accept_m: f64,
    /// Observed odometry, oldest first: stamp and path length from the first
    /// observed pose. Covers at most `PATH_HISTORY_NS`.
    path: VecDeque<(i64, f64)>,
    /// Position of the newest observed odometry pose.
    path_end: Option<Vector3<f64>>,
    /// Path length at the last accepted fix, when the path covered it.
    path_at_accept_m: Option<f64>,
}

impl OdomCorrection {
    pub fn new(config: OdomCorrectionConfig) -> Self {
        Self {
            config,
            offset: None,
            window: VecDeque::new(),
            candidates: Vec::new(),
            previous_odom_position: None,
            travel_since_accept_m: 0.0,
            path: VecDeque::new(),
            path_end: None,
            path_at_accept_m: None,
        }
    }

    pub const fn config(&self) -> &OdomCorrectionConfig {
        &self.config
    }

    /// Whether the offset is set, i.e. odometry poses have a map pose.
    pub const fn is_set(&self) -> bool {
        self.offset.is_some()
    }

    /// The current odometry-to-map transform, once set.
    pub fn map_from_odom(&self) -> Option<SE3> {
        self.offset.as_ref().map(Offset::se3)
    }

    /// Timestamp and odometry position of the newest fix the offset uses.
    /// The error of [`Self::map_from_body`] grows with the odometry travel
    /// (and time) since this fix, so callers can use it to judge a pose.
    pub fn last_fix(&self) -> Option<(i64, Vector3<f64>)> {
        self.offset?;
        self.window
            .back()
            .map(|fix| (fix.timestamp_ns, fix.odom_position))
    }

    /// An odometry pose expressed in the map frame, once set.
    pub fn map_from_body(&self, odom_from_body: &SE3) -> Option<SE3> {
        self.map_from_odom()
            .map(|map_from_odom| map_from_odom.compose(odom_from_body))
    }

    /// Adds an odometry pose, so the gate measures the odometry's travel
    /// along its path rather than between fixes. Poses must arrive in time
    /// order (older or repeated stamps are ignored), but may run ahead of the
    /// fixes: a fix's travel is read off the path at its own stamp.
    pub fn observe_odometry(&mut self, timestamp_ns: i64, odom_from_body: &SE3) {
        if self
            .path
            .back()
            .is_some_and(|(last_ns, _)| timestamp_ns <= *last_ns)
        {
            return;
        }
        let position = odom_from_body.translation;
        let length = match (self.path.back(), self.path_end) {
            (Some((_, length)), Some(end)) => length + (position - end).norm(),
            _ => 0.0,
        };
        self.path.push_back((timestamp_ns, length));
        self.path_end = Some(position);
        while self
            .path
            .front()
            .is_some_and(|(first_ns, _)| timestamp_ns - first_ns > PATH_HISTORY_NS)
        {
            self.path.pop_front();
        }
    }

    /// Path length of the observed odometry at `timestamp_ns`, interpolated
    /// between the poses around it; `None` outside the observed path.
    fn path_length_at(&self, timestamp_ns: i64) -> Option<f64> {
        let (first_ns, _) = self.path.front()?;
        let (last_ns, _) = self.path.back()?;
        if timestamp_ns < *first_ns || timestamp_ns > *last_ns {
            return None;
        }
        let index = self
            .path
            .partition_point(|(stamp, _)| *stamp < timestamp_ns);
        let (after_ns, after) = self.path[index];
        if after_ns == timestamp_ns || index == 0 {
            return Some(after);
        }
        let (before_ns, before) = self.path[index - 1];
        let alpha = (timestamp_ns - before_ns) as f64 / (after_ns - before_ns) as f64;
        Some(before + alpha * (after - before))
    }

    /// Adds a map fix: the body's map pose from localization, and its
    /// odometry pose at the same instant. Fixes must arrive in time order.
    pub fn add_fix(
        &mut self,
        timestamp_ns: i64,
        map_from_body: &SE3,
        odom_from_body: &SE3,
    ) -> FixOutcome {
        self.add(timestamp_ns, map_from_body, odom_from_body, false)
    }

    /// Adds a weak fix: a localization with fewer inliers than a fix needs.
    /// It counts toward setting the first offset, which then takes
    /// `init_fixes_weak` agreeing fixes, and is [`FixOutcome::Unused`] once
    /// the offset is set.
    pub fn add_weak_fix(
        &mut self,
        timestamp_ns: i64,
        map_from_body: &SE3,
        odom_from_body: &SE3,
    ) -> FixOutcome {
        self.add(timestamp_ns, map_from_body, odom_from_body, true)
    }

    fn add(
        &mut self,
        timestamp_ns: i64,
        map_from_body: &SE3,
        odom_from_body: &SE3,
        weak: bool,
    ) -> FixOutcome {
        let fix = Fix {
            timestamp_ns,
            map_position: map_from_body.translation,
            odom_position: odom_from_body.translation,
            yaw: yaw_of(&(map_from_body.rotation * odom_from_body.rotation.inverse())),
            weak,
        };
        if let Some(previous) = self.previous_odom_position {
            self.travel_since_accept_m += (fix.odom_position - previous).norm();
        }
        self.previous_odom_position = Some(fix.odom_position);
        let path_m = self.path_length_at(timestamp_ns);

        let Some(offset) = self.offset else {
            return if self.push_initial(fix) {
                Self::adopt(&mut self.window, &mut self.candidates);
                self.refit();
                self.restart_travel(path_m);
                FixOutcome::Initialized
            } else {
                FixOutcome::Pending
            };
        };

        let (position_residual, yaw_residual) = residuals(&offset, &fix);
        if weak {
            if self.config.weak_gate_m > 0.0
                && position_residual <= self.config.weak_gate_m
                && yaw_residual <= self.config.weak_gate_yaw_deg
            {
                self.candidates.clear();
                self.window.push_back(fix);
                self.refit();
                self.restart_travel(path_m);
                return FixOutcome::Accepted;
            }
            return FixOutcome::Unused;
        }
        let travel = match (path_m, self.path_at_accept_m) {
            (Some(now), Some(then)) => self.travel_since_accept_m.max(now - then),
            _ => self.travel_since_accept_m,
        };
        let accepted = position_residual <= self.config.gate_m + self.config.gate_per_m * travel
            && yaw_residual <= self.config.gate_yaw_deg + self.config.gate_yaw_per_m_deg * travel;
        if accepted {
            self.candidates.clear();
            self.window.push_back(fix);
            self.refit();
            self.restart_travel(path_m);
            return FixOutcome::Accepted;
        }
        if self.push_candidate(fix, self.config.reset_after) {
            Self::adopt(&mut self.window, &mut self.candidates);
            self.refit();
            self.restart_travel(path_m);
            FixOutcome::Reset
        } else {
            FixOutcome::Rejected
        }
    }

    /// Measures travel from a fix just accepted, at path length `path_m`.
    fn restart_travel(&mut self, path_m: Option<f64>) {
        self.travel_since_accept_m = 0.0;
        self.path_at_accept_m = path_m;
    }

    /// Appends to the candidate run, keeping only its last `needed` fixes,
    /// and reports whether that many now agree on one offset.
    fn push_candidate(&mut self, fix: Fix, needed: usize) -> bool {
        self.candidates.push(fix);
        let needed = needed.max(1);
        if self.candidates.len() > needed {
            self.candidates.drain(..self.candidates.len() - needed);
        }
        self.candidates.len() == needed && self.agree(&self.candidates)
    }

    /// Appends to the candidate run before the first offset and reports
    /// whether its newest fixes now set it: `init_fixes` of them agreeing, or
    /// `init_fixes_weak` when any of those is weak. On success the run keeps
    /// only those.
    fn push_initial(&mut self, fix: Fix) -> bool {
        let strong = self.config.init_fixes.max(1);
        let weak = self.config.init_fixes_weak.max(strong);
        self.candidates.push(fix);
        if self.candidates.len() > weak {
            self.candidates.drain(..self.candidates.len() - weak);
        }
        for needed in [strong, weak] {
            let Some(start) = self.candidates.len().checked_sub(needed) else {
                continue;
            };
            let newest = &self.candidates[start..];
            let required = if newest.iter().any(|fix| fix.weak) {
                weak
            } else {
                strong
            };
            if needed == required && self.agree(newest) {
                self.candidates.drain(..start);
                return true;
            }
        }
        false
    }

    /// Whether `fixes` agree on one offset.
    fn agree(&self, fixes: &[Fix]) -> bool {
        let fixes = fixes.iter().collect::<Vec<_>>();
        let offset = fit(&fixes);
        fixes.iter().all(|fix| {
            let (position, yaw) = residuals(&offset, fix);
            position <= self.config.agreement_m && yaw <= self.config.gate_yaw_deg
        })
    }

    fn adopt(window: &mut VecDeque<Fix>, candidates: &mut Vec<Fix>) {
        window.clear();
        window.extend(candidates.drain(..));
    }

    /// Drops fixes outside the window and re-estimates the offset.
    fn refit(&mut self) {
        let Some(newest) = self.window.back().map(|fix| fix.timestamp_ns) else {
            return;
        };
        let window_ns = (self.config.window_s * 1e9) as i64;
        while self.window.len() > 1
            && self
                .window
                .front()
                .is_some_and(|fix| newest - fix.timestamp_ns > window_ns)
        {
            self.window.pop_front();
        }
        let fixes = self.window.iter().collect::<Vec<_>>();
        self.offset = Some(fit(&fixes));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const SECOND: i64 = 1_000_000_000;

    fn truth() -> SE3 {
        SE3::new(
            UnitQuaternion::from_axis_angle(&Vector3::z_axis(), 0.6),
            Vector3::new(3.0, -2.0, 0.5),
        )
    }

    /// Odometry pose `index` on a curved, tilting path.
    fn odom(index: usize) -> SE3 {
        let t = index as f64 * 0.2;
        SE3::new(
            UnitQuaternion::from_euler_angles(0.05 * t.sin(), -0.03, 0.4 * t),
            Vector3::new(t.cos() * 2.0, t.sin() * 2.0, 0.1 * t),
        )
    }

    fn fix_at(
        correction: &mut OdomCorrection,
        index: usize,
        map_from_odom: &SE3,
        shift: Vector3<f64>,
    ) -> FixOutcome {
        let odom_from_body = odom(index);
        let mut map_from_body = map_from_odom.compose(&odom_from_body);
        map_from_body.translation += shift;
        correction.add_fix(index as i64 * SECOND / 10, &map_from_body, &odom_from_body)
    }

    fn assert_pose_close(lhs: &SE3, rhs: &SE3, tolerance: f64) {
        assert!(
            (lhs.translation - rhs.translation).norm() < tolerance,
            "{lhs:?} vs {rhs:?}"
        );
        assert!(
            lhs.rotation.angle_to(&rhs.rotation) < tolerance,
            "{lhs:?} vs {rhs:?}"
        );
    }

    #[test]
    fn exact_fixes_recover_the_offset_after_initialization() {
        let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
        assert_eq!(correction.map_from_body(&odom(0)), None);
        assert_eq!(
            fix_at(&mut correction, 0, &truth(), Vector3::zeros()),
            FixOutcome::Pending
        );
        assert_eq!(correction.last_fix(), None);
        assert_eq!(
            fix_at(&mut correction, 1, &truth(), Vector3::zeros()),
            FixOutcome::Initialized
        );
        assert_eq!(
            fix_at(&mut correction, 2, &truth(), Vector3::zeros()),
            FixOutcome::Accepted
        );
        assert_eq!(
            correction.last_fix(),
            Some((2 * SECOND / 10, odom(2).translation))
        );
        for index in [3, 10, 40] {
            let pose = correction.map_from_body(&odom(index)).expect("set");
            assert_pose_close(&pose, &truth().compose(&odom(index)), 1e-9);
        }
    }

    #[test]
    fn a_wrong_first_fix_does_not_place_the_trajectory() {
        let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
        let off = Vector3::new(1.5, 0.0, 0.0);
        assert_eq!(
            fix_at(&mut correction, 0, &truth(), off),
            FixOutcome::Pending
        );
        assert_eq!(
            fix_at(&mut correction, 1, &truth(), Vector3::zeros()),
            FixOutcome::Pending
        );
        assert_eq!(
            fix_at(&mut correction, 2, &truth(), Vector3::zeros()),
            FixOutcome::Initialized
        );
        assert_pose_close(&correction.map_from_odom().unwrap(), &truth(), 1e-9);
    }

    #[test]
    fn an_outlier_is_rejected_and_leaves_the_offset_alone() {
        let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
        for index in 0..4 {
            fix_at(&mut correction, index, &truth(), Vector3::zeros());
        }
        assert_eq!(
            fix_at(&mut correction, 4, &truth(), Vector3::new(0.0, 2.0, 0.0)),
            FixOutcome::Rejected
        );
        assert_pose_close(&correction.map_from_odom().unwrap(), &truth(), 1e-9);
        assert_eq!(
            fix_at(&mut correction, 5, &truth(), Vector3::zeros()),
            FixOutcome::Accepted
        );
    }

    fn weak_fix_at(
        correction: &mut OdomCorrection,
        index: usize,
        shift: Vector3<f64>,
    ) -> FixOutcome {
        let odom_from_body = odom(index);
        let mut map_from_body = truth().compose(&odom_from_body);
        map_from_body.translation += shift;
        correction.add_weak_fix(index as i64 * SECOND / 10, &map_from_body, &odom_from_body)
    }

    #[test]
    fn weak_fixes_need_three_agreeing_and_only_set_the_first_offset() {
        // Two weak fixes do not set the offset; a third agreeing one does.
        let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
        assert_eq!(
            weak_fix_at(&mut correction, 0, Vector3::zeros()),
            FixOutcome::Pending
        );
        assert_eq!(
            weak_fix_at(&mut correction, 1, Vector3::zeros()),
            FixOutcome::Pending
        );
        assert_eq!(
            weak_fix_at(&mut correction, 2, Vector3::zeros()),
            FixOutcome::Initialized
        );
        assert_pose_close(&correction.map_from_odom().unwrap(), &truth(), 1e-9);

        // A strong fix after a weak one: still three, since one is weak.
        let mut mixed = OdomCorrection::new(OdomCorrectionConfig::default());
        assert_eq!(
            weak_fix_at(&mut mixed, 0, Vector3::zeros()),
            FixOutcome::Pending
        );
        assert_eq!(
            fix_at(&mut mixed, 1, &truth(), Vector3::zeros()),
            FixOutcome::Pending
        );
        assert_eq!(
            fix_at(&mut mixed, 2, &truth(), Vector3::zeros()),
            FixOutcome::Initialized
        );
        // Two strong fixes alone, as before.
        let mut strong = OdomCorrection::new(OdomCorrectionConfig::default());
        assert_eq!(
            fix_at(&mut strong, 0, &truth(), Vector3::zeros()),
            FixOutcome::Pending
        );
        assert_eq!(
            fix_at(&mut strong, 1, &truth(), Vector3::zeros()),
            FixOutcome::Initialized
        );

        // A wrong weak fix breaks the run; three agreeing ones after it set
        // the offset to theirs.
        let mut broken = OdomCorrection::new(OdomCorrectionConfig::default());
        let off = Vector3::new(1.5, 0.0, 0.0);
        assert_eq!(
            weak_fix_at(&mut broken, 0, Vector3::zeros()),
            FixOutcome::Pending
        );
        assert_eq!(weak_fix_at(&mut broken, 1, off), FixOutcome::Pending);
        assert_eq!(
            weak_fix_at(&mut broken, 2, Vector3::zeros()),
            FixOutcome::Pending
        );
        assert_eq!(
            weak_fix_at(&mut broken, 3, Vector3::zeros()),
            FixOutcome::Pending
        );
        assert_eq!(
            weak_fix_at(&mut broken, 4, Vector3::zeros()),
            FixOutcome::Initialized
        );
        assert_pose_close(&broken.map_from_odom().unwrap(), &truth(), 1e-9);

        // Once set, weak fixes are not used, however far off.
        let before = correction.map_from_odom().unwrap();
        assert_eq!(weak_fix_at(&mut correction, 3, off), FixOutcome::Unused);
        assert_eq!(
            weak_fix_at(&mut correction, 4, Vector3::zeros()),
            FixOutcome::Unused
        );
        assert_pose_close(&correction.map_from_odom().unwrap(), &before, 1e-12);
        assert_eq!(
            fix_at(&mut correction, 5, &truth(), Vector3::zeros()),
            FixOutcome::Accepted
        );
    }

    #[test]
    fn a_weak_gate_accepts_close_weak_fixes_after_the_first_offset() {
        let mut correction = OdomCorrection::new(OdomCorrectionConfig {
            weak_gate_m: 0.05,
            ..OdomCorrectionConfig::default()
        });
        for index in 0..2 {
            fix_at(&mut correction, index, &truth(), Vector3::zeros());
        }
        assert!(correction.is_set());
        // 3 cm off: inside the weak gate, and it moves the offset.
        let close = Vector3::new(0.03, 0.0, 0.0);
        assert_eq!(weak_fix_at(&mut correction, 2, close), FixOutcome::Accepted);
        let moved = correction.map_from_odom().unwrap().translation - truth().translation;
        assert!((moved - close / 3.0).norm() < 1e-9, "{moved:?}");
        // 8 cm off: inside a fix's gate, outside the weak one.
        assert_eq!(
            weak_fix_at(&mut correction, 3, Vector3::new(0.08, 0.0, 0.0)),
            FixOutcome::Unused
        );
    }

    #[test]
    fn agreeing_rejected_fixes_reset_the_offset_after_an_odometry_jump() {
        let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
        for index in 0..4 {
            fix_at(&mut correction, index, &truth(), Vector3::zeros());
        }
        // The odometry jumped: from now on the true offset is a different one.
        let jumped = SE3::new(
            UnitQuaternion::from_axis_angle(&Vector3::z_axis(), 0.75),
            Vector3::new(2.0, -1.0, 0.5),
        );
        assert_eq!(
            fix_at(&mut correction, 4, &jumped, Vector3::zeros()),
            FixOutcome::Rejected
        );
        assert_eq!(
            fix_at(&mut correction, 5, &jumped, Vector3::zeros()),
            FixOutcome::Rejected
        );
        assert_eq!(
            fix_at(&mut correction, 6, &jumped, Vector3::zeros()),
            FixOutcome::Reset
        );
        assert_pose_close(&correction.map_from_odom().unwrap(), &jumped, 1e-9);
    }

    #[test]
    fn the_gate_widens_with_travel_since_the_last_accepted_fix() {
        let config = OdomCorrectionConfig::default();
        let mut near = OdomCorrection::new(config.clone());
        let mut far = OdomCorrection::new(config);
        for index in 0..3 {
            fix_at(&mut near, index, &truth(), Vector3::zeros());
            fix_at(&mut far, index, &truth(), Vector3::zeros());
        }
        // 0.3 m off: beyond the 0.15 m base gate right after a fix, inside it
        // after several metres of travel (sampled by an outlier fix on the way).
        let drift = Vector3::new(0.0, 0.0, 0.3);
        assert_eq!(fix_at(&mut near, 3, &truth(), drift), FixOutcome::Rejected);
        assert_eq!(
            fix_at(&mut far, 20, &truth(), Vector3::new(5.0, 0.0, 0.0)),
            FixOutcome::Rejected
        );
        assert_eq!(fix_at(&mut far, 40, &truth(), drift), FixOutcome::Accepted);
    }

    #[test]
    fn observed_odometry_measures_travel_along_the_path() {
        let config = OdomCorrectionConfig::default();
        let mut sampled = OdomCorrection::new(config.clone());
        let mut observed = OdomCorrection::new(config);
        // The odometry runs ahead of the fixes, as a localization finishes
        // after later odometry has arrived.
        for index in 0..=40 {
            observed.observe_odometry(index as i64 * SECOND / 10, &odom(index));
        }
        for index in 0..3 {
            fix_at(&mut sampled, index, &truth(), Vector3::zeros());
            fix_at(&mut observed, index, &truth(), Vector3::zeros());
        }
        // Almost a full circle (11.6 m of path) ends 1.1 m from the last
        // fix: 0.3 m off is outside the gate that straight line gives, and
        // inside the one the path gives.
        let drift = Vector3::new(0.0, 0.0, 0.3);
        assert_eq!(
            fix_at(&mut sampled, 31, &truth(), drift),
            FixOutcome::Rejected
        );
        assert_eq!(
            fix_at(&mut observed, 31, &truth(), drift),
            FixOutcome::Accepted
        );
        // Travel restarts at the accepted fix.
        assert_eq!(
            fix_at(&mut observed, 32, &truth(), drift * 2.0),
            FixOutcome::Rejected
        );
    }

    #[test]
    fn noisy_fixes_average_within_the_window() {
        let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
        // Alternating +-2 cm noise along x averages out.
        for index in 0..20 {
            let sign = if index % 2 == 0 { 1.0 } else { -1.0 };
            fix_at(
                &mut correction,
                index,
                &truth(),
                Vector3::new(0.02 * sign, 0.0, 0.0),
            );
        }
        let estimate = correction.map_from_odom().unwrap();
        assert!((estimate.translation - truth().translation).norm() < 0.005);
        // A 5 s window at 10 fixes per second keeps all 20 fixes.
        assert_eq!(correction.window.len(), 20);
    }

    #[test]
    fn old_fixes_leave_the_window() {
        let mut correction = OdomCorrection::new(OdomCorrectionConfig {
            window_s: 1.0,
            ..OdomCorrectionConfig::default()
        });
        for index in 0..30 {
            fix_at(&mut correction, index, &truth(), Vector3::zeros());
        }
        // 0.1 s apart: the newest fix and the ten before it are within 1 s.
        assert_eq!(correction.window.len(), 11);
    }
}