Skip to main content

visloc_localization/
wheel_calibration.rs

1//! Where a wheeled robot's odometry is measured, from a run with a VIO or
2//! against a map.
3//!
4//! Wheel odometry reports a point near the middle of the drive axle, about
5//! which the robot turns in place, and keeps that frame level. A robot's
6//! description (`T_imu_body`, the body being e.g. `base_link`) may put the
7//! body a few centimetres from that point and a degree or two off level.
8//! With the camera high above the wheels, either moves the camera pose the
9//! wheel odometry implies by centimetres in every turn. And the VIO, with
10//! the map built from it, may be a few percent off in scale from the
11//! wheels.
12//!
13//! [`WheelCalibration`] pairs wheel odometry poses with reference poses and
14//! fits, in the plane,
15//!
16//! ```text
17//! p_body(t) = s * R(a) * (p_wheel(t) + R(yaw_wheel(t)) * r) + t0
18//! ```
19//!
20//! where `p_body` is the body origin in the reference, `r` the offset (body
21//! frame) of that origin from the wheel odometry's point, and `s`, `a`, `t0`
22//! a similarity between the two trajectories. Turns in place are what reveal
23//! `r`. It also measures the body frame's tilt against the reference's
24//! gravity, which on a level floor is an error of `T_imu_body`.
25//! `scripts/calibrate_wheel_offset.py` fits the same offline.
26//!
27//! The wheel odometry's heading drifts: its wheels slip in turns in place,
28//! by 15 deg in one 350 deg turn on OpenLORIS-Scene's corridor. So `a` and
29//! `t0` hold only over a stretch of a few seconds of VIO pairs
30//! ([`WheelCalibrationConfig::segment_s`]), or a few tens of seconds of map
31//! localizations ([`WheelCalibrationConfig::fix_segment_s`]): each stretch
32//! gets its own, and `r` and `s` are shared. With one `a` over a 120 s
33//! window, `r` took up that drift and wandered by up to 1 m.
34//!
35//! Two references feed it. A VIO ([`WheelCalibration::add_vio`]) follows
36//! every turn, which shows the offset. Localizations against a map
37//! ([`WheelCalibration::add_fix`]) come only where the camera sees the map,
38//! rarely through a turn in place, but they carry the map's own scale and
39//! gravity, which is what a consumer correcting the odometry into that map
40//! needs. A VIO session's scale differs from the map's by a few percent
41//! (by up to 3.6% on OpenLORIS-Scene), so it is reported but not used. So
42//! the offset comes from the VIO, else from the map; the level from the
43//! map, else from the VIO; the scale from the map only; and each from a
44//! prior ([`WheelCalibration::with_prior`]) until the pairs show it.
45
46use std::collections::VecDeque;
47use std::ops::Range;
48
49use nalgebra::{Matrix2, UnitQuaternion, Vector2, Vector3};
50use visloc_core::geometry::SE3;
51
52/// Longest gap between the two wheel poses a map localization is
53/// interpolated between.
54const MAX_FIX_WHEEL_GAP_NS: i64 = 200_000_000;
55/// Wheel poses kept for map localizations, which arrive after their image.
56const FIX_WHEEL_HISTORY_NS: i64 = 10_000_000_000;
57/// Map localizations waiting for a later wheel pose, at most.
58const MAX_WAITING_FIXES: usize = 100;
59/// Typical residuals of the fit (m): against the VIO, and against map
60/// localizations. With [`WheelCalibrationConfig::offset_stddev_m`] they
61/// weigh the offset's prior.
62const VIO_STDDEV_M: f64 = 0.005;
63const FIX_STDDEV_M: f64 = 0.015;
64
65#[derive(Debug, Clone, PartialEq)]
66pub struct WheelCalibrationConfig {
67    /// A wheel pose pairs with the nearest VIO pose at most this far away.
68    pub max_gap_ns: i64,
69    /// The VIO gives the estimate once the wheel odometry has turned this
70    /// many degrees in total over its pairs (which shows the offset) ...
71    pub min_turn_deg: f64,
72    /// ... and travelled this many metres (which shows the scale; turning
73    /// in place alone cannot tell a larger offset from a larger scale) ...
74    pub min_travel_m: f64,
75    /// ... over at least this many pairs.
76    pub min_pairs: usize,
77    /// Map localizations give the level once there are this many, and the
78    /// scale (and without a VIO the offset) once they have also travelled
79    /// `min_travel_m`.
80    pub min_fixes: usize,
81    /// A map localization further than this (m) from the fit through the
82    /// others is left out of it.
83    pub max_fix_residual_m: f64,
84    /// Only pairs from the last `window_s` seconds count (0: all), so that
85    /// a long run's estimate follows the odometry's slow changes.
86    pub window_s: f64,
87    /// VIO pairs within this many seconds of the first of their stretch
88    /// share a heading and a position against the VIO (0: all pairs one
89    /// stretch); the offset and the scale are shared by all. Short enough
90    /// that the wheel odometry's heading drift stays small within one.
91    pub segment_s: f64,
92    /// The same for map localizations, longer: they are sparser and noisier
93    /// than the VIO pairs, so a stretch needs more of them.
94    pub fix_segment_s: f64,
95    /// How far (m) the offset may be from the prior's (or from zero) before
96    /// the pairs show it: the fit holds the offset there where the turns
97    /// seen so far do not show it, as map localizations rarely do.
98    pub offset_stddev_m: f64,
99    /// Level the body frame against the reference's gravity (a level floor).
100    pub level: bool,
101}
102
103impl Default for WheelCalibrationConfig {
104    fn default() -> Self {
105        Self {
106            max_gap_ns: 20_000_000,
107            min_turn_deg: 180.0,
108            min_travel_m: 1.0,
109            min_pairs: 200,
110            min_fixes: 20,
111            max_fix_residual_m: 0.10,
112            window_s: 0.0,
113            segment_s: 5.0,
114            fix_segment_s: 30.0,
115            offset_stddev_m: 0.03,
116            level: true,
117        }
118    }
119}
120
121/// Where a value of a [`WheelCalibrationEstimate`] comes from.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum CalibrationSource {
124    /// The pairs with the VIO.
125    Vio,
126    /// The pairs with map localizations.
127    Map,
128    /// [`WheelCalibration::with_prior`].
129    Prior,
130    /// Nothing: no offset, scale 1, the body frame as given.
131    Default,
132}
133
134impl CalibrationSource {
135    pub const fn name(self) -> &'static str {
136        match self {
137            Self::Vio => "vio",
138            Self::Map => "map",
139            Self::Prior => "prior",
140            Self::Default => "default",
141        }
142    }
143}
144
145/// What [`WheelCalibration::estimate`] found.
146#[derive(Debug, Clone, PartialEq)]
147pub struct WheelCalibrationEstimate {
148    /// Offset, in the body frame and the wheel odometry's units, of the
149    /// body origin from the wheel odometry's point.
150    pub offset: Vector2<f64>,
151    /// The map's scale against the wheel odometry (1 until the map
152    /// localizations show it, or the prior's).
153    pub scale: f64,
154    /// The VIO's scale against the wheel odometry, when it gave the offset
155    /// (not used: a VIO session's scale is not the map's).
156    pub vio_scale: Option<f64>,
157    /// Rotation from the levelled body frame to the given one (identity
158    /// without levelling).
159    pub body_from_level: UnitQuaternion<f64>,
160    /// Tilt of the given body frame against the reference's gravity, in
161    /// degrees.
162    pub tilt_deg: f64,
163    /// RMS residual of the fit that gave the offset, in metres of its
164    /// reference, and that fit without the offset.
165    pub rms_m: f64,
166    pub rms_without_offset_m: f64,
167    /// RMS residual of the map localizations' fit, when they gave a value.
168    pub map_rms_m: Option<f64>,
169    /// Total turn of the wheel odometry over the VIO pairs, in degrees, and
170    /// the number of pairs and of map localizations used.
171    pub turned_deg: f64,
172    pub pairs: usize,
173    pub fixes: usize,
174    pub offset_from: CalibrationSource,
175    pub scale_from: CalibrationSource,
176    pub level_from: CalibrationSource,
177}
178
179impl WheelCalibrationEstimate {
180    /// No calibration: the body where the description puts it, scale 1.
181    pub fn identity() -> Self {
182        Self {
183            offset: Vector2::zeros(),
184            scale: 1.0,
185            vio_scale: None,
186            body_from_level: UnitQuaternion::identity(),
187            tilt_deg: 0.0,
188            rms_m: f64::NAN,
189            rms_without_offset_m: f64::NAN,
190            map_rms_m: None,
191            turned_deg: 0.0,
192            pairs: 0,
193            fixes: 0,
194            offset_from: CalibrationSource::Default,
195            scale_from: CalibrationSource::Default,
196            level_from: CalibrationSource::Default,
197        }
198    }
199
200    /// `T_imu_body` with the body moved to the wheel odometry's point and
201    /// levelled (the wheel odometry's own frame).
202    pub fn imu_from_wheel(&self, imu_from_body: &SE3) -> SE3 {
203        let rotation = imu_from_body.rotation * self.body_from_level;
204        let offset = Vector3::new(self.offset.x, self.offset.y, 0.0);
205        SE3::new(rotation, imu_from_body.translation - rotation * offset)
206    }
207
208    /// The body's pose in the odometry frame, in the map's scale, from a
209    /// wheel odometry pose (of the wheel odometry's point, level).
210    pub fn odom_from_body(&self, odom_from_wheel: &SE3) -> SE3 {
211        let offset = Vector3::new(self.offset.x, self.offset.y, 0.0);
212        SE3::new(
213            odom_from_wheel.rotation * self.body_from_level.inverse(),
214            self.scale * (odom_from_wheel.translation + odom_from_wheel.rotation * offset),
215        )
216    }
217}
218
219#[derive(Debug, Clone, Copy)]
220struct Pair {
221    timestamp_ns: i64,
222    body: Vector2<f64>,
223    wheel: Vector2<f64>,
224    wheel_yaw: f64,
225    up_in_body: Vector3<f64>,
226}
227
228/// Pairs wheel odometry with VIO poses and map localizations as they arrive
229/// and fits where the wheel odometry is measured.
230#[derive(Debug, Clone)]
231pub struct WheelCalibration {
232    config: WheelCalibrationConfig,
233    /// The body in the VIO's IMU frame; VIO poses wait for it.
234    imu_from_body: Option<SE3>,
235    prior: Option<WheelCalibrationEstimate>,
236    /// Recent VIO poses (`world_from_imu`), oldest first.
237    vio: VecDeque<(i64, SE3)>,
238    /// Wheel poses waiting for a later VIO pose.
239    waiting: VecDeque<(i64, SE3)>,
240    /// Recent wheel poses, for map localizations.
241    wheel_history: VecDeque<(i64, SE3)>,
242    /// Map localizations waiting for a later wheel pose.
243    waiting_fixes: VecDeque<(i64, SE3)>,
244    pairs: VecDeque<Pair>,
245    fix_pairs: VecDeque<Pair>,
246}
247
248impl WheelCalibration {
249    /// Pairs with a VIO, `imu_from_body` being the robot description's
250    /// transform from the odometry's body (e.g. `base_link`) to the VIO's
251    /// IMU.
252    pub fn new(config: WheelCalibrationConfig, imu_from_body: SE3) -> Self {
253        let mut calibration = Self::without_vio(config);
254        calibration.imu_from_body = Some(imu_from_body);
255        calibration
256    }
257
258    /// Pairs with map localizations only, until
259    /// [`Self::set_imu_from_body`].
260    pub fn without_vio(config: WheelCalibrationConfig) -> Self {
261        Self {
262            config,
263            imu_from_body: None,
264            prior: None,
265            vio: VecDeque::new(),
266            waiting: VecDeque::new(),
267            wheel_history: VecDeque::new(),
268            waiting_fixes: VecDeque::new(),
269            pairs: VecDeque::new(),
270            fix_pairs: VecDeque::new(),
271        }
272    }
273
274    /// Values for what the pairs do not show yet (e.g. a saved calibration).
275    #[must_use]
276    pub fn with_prior(mut self, prior: WheelCalibrationEstimate) -> Self {
277        self.prior = Some(prior);
278        self
279    }
280
281    /// Where the VIO's IMU sits on the body; VIO poses pair from now on.
282    pub fn set_imu_from_body(&mut self, imu_from_body: SE3) {
283        self.imu_from_body = Some(imu_from_body);
284    }
285
286    pub const fn has_imu_from_body(&self) -> bool {
287        self.imu_from_body.is_some()
288    }
289
290    /// Pairs with the VIO.
291    pub fn pairs(&self) -> usize {
292        self.pairs.len()
293    }
294
295    /// Map localizations paired with the wheel odometry.
296    pub fn fixes(&self) -> usize {
297        self.fix_pairs.len()
298    }
299
300    /// Total turn of the wheel odometry over the VIO pairs, in degrees.
301    pub fn turned_deg(&self) -> f64 {
302        turned_rad(&self.pairs).to_degrees()
303    }
304
305    /// The wheel odometry's path length over the VIO pairs, in its own units.
306    pub fn travel_m(&self) -> f64 {
307        travel(&self.pairs)
308    }
309
310    /// Turn and path of the wheel odometry between map localizations.
311    pub fn fix_turned_deg(&self) -> f64 {
312        turned_rad(&self.fix_pairs).to_degrees()
313    }
314
315    pub fn fix_travel_m(&self) -> f64 {
316        travel(&self.fix_pairs)
317    }
318
319    /// Whether the VIO pairs have seen enough turning and travel to give
320    /// the offset.
321    pub fn is_ready(&self) -> bool {
322        self.pairs.len() >= self.config.min_pairs.max(3)
323            && self.turned_deg() >= self.config.min_turn_deg
324            && self.travel_m() >= self.config.min_travel_m
325    }
326
327    /// Whether there are enough map localizations to give the level.
328    pub fn fixes_ready(&self) -> bool {
329        self.fix_pairs.len() >= self.config.min_fixes.max(3)
330    }
331
332    /// Whether the map localizations have also travelled enough to give the
333    /// scale.
334    pub fn fixes_travelled(&self) -> bool {
335        self.fixes_ready() && self.fix_travel_m() >= self.config.min_travel_m
336    }
337
338    /// Adds a VIO pose (the IMU in the VIO's gravity-aligned world), in time
339    /// order.
340    pub fn add_vio(&mut self, timestamp_ns: i64, world_from_imu: &SE3) {
341        if self.imu_from_body.is_none()
342            || self
343                .vio
344                .back()
345                .is_some_and(|(last, _)| timestamp_ns <= *last)
346        {
347            return;
348        }
349        self.vio.push_back((timestamp_ns, world_from_imu.clone()));
350        while let Some((t, _)) = self.waiting.front() {
351            if *t > timestamp_ns {
352                break;
353            }
354            let (t, wheel) = self.waiting.pop_front().expect("front exists");
355            self.pair(t, &wheel);
356        }
357        // Keep what the waiting wheel poses may still need.
358        let keep_from = self
359            .waiting
360            .front()
361            .map_or(timestamp_ns, |(t, _)| (*t).min(timestamp_ns))
362            - self.config.max_gap_ns;
363        while self.vio.len() > 2 && self.vio[1].0 < keep_from {
364            self.vio.pop_front();
365        }
366    }
367
368    /// Adds a wheel odometry pose (its point, level), in time order.
369    pub fn add_wheel(&mut self, timestamp_ns: i64, odom_from_wheel: &SE3) {
370        if self
371            .wheel_history
372            .back()
373            .is_some_and(|(last, _)| timestamp_ns <= *last)
374        {
375            return;
376        }
377        self.wheel_history
378            .push_back((timestamp_ns, odom_from_wheel.clone()));
379        while self
380            .wheel_history
381            .front()
382            .is_some_and(|(t, _)| timestamp_ns - t > FIX_WHEEL_HISTORY_NS)
383        {
384            self.wheel_history.pop_front();
385        }
386        while self
387            .waiting_fixes
388            .front()
389            .is_some_and(|(t, _)| *t <= timestamp_ns)
390        {
391            let (t, fix) = self.waiting_fixes.pop_front().expect("front exists");
392            self.pair_fix(t, &fix);
393        }
394        if self.imu_from_body.is_none() {
395            return;
396        }
397        if self
398            .vio
399            .back()
400            .is_some_and(|(last, _)| timestamp_ns <= *last)
401        {
402            self.pair(timestamp_ns, odom_from_wheel);
403        } else {
404            self.waiting
405                .push_back((timestamp_ns, odom_from_wheel.clone()));
406        }
407    }
408
409    /// Adds a localization against a map: the body's pose in the map
410    /// (gravity-aligned), at its image's stamp. It pairs with the wheel
411    /// odometry interpolated to that stamp, now or once the wheel odometry
412    /// gets there.
413    pub fn add_fix(&mut self, timestamp_ns: i64, map_from_body: &SE3) {
414        if self
415            .wheel_history
416            .back()
417            .is_some_and(|(last, _)| timestamp_ns <= *last)
418        {
419            self.pair_fix(timestamp_ns, map_from_body);
420        } else if self.waiting_fixes.len() < MAX_WAITING_FIXES {
421            self.waiting_fixes
422                .push_back((timestamp_ns, map_from_body.clone()));
423        }
424    }
425
426    fn pair(&mut self, timestamp_ns: i64, odom_from_wheel: &SE3) {
427        let Some(imu_from_body) = &self.imu_from_body else {
428            return;
429        };
430        let Some((t, world_from_imu)) = self
431            .vio
432            .iter()
433            .min_by_key(|(t, _)| (t - timestamp_ns).abs())
434        else {
435            return;
436        };
437        if (t - timestamp_ns).abs() > self.config.max_gap_ns {
438            return;
439        }
440        let body = world_from_imu.translation + world_from_imu.rotation * imu_from_body.translation;
441        let world_from_body = world_from_imu.rotation * imu_from_body.rotation;
442        let pair = Pair {
443            timestamp_ns,
444            body: body.xy(),
445            wheel: odom_from_wheel.translation.xy(),
446            wheel_yaw: yaw_of(&odom_from_wheel.rotation),
447            up_in_body: world_from_body.inverse() * Vector3::z(),
448        };
449        self.pairs.push_back(pair);
450        drop_older(&mut self.pairs, timestamp_ns, self.config.window_s);
451    }
452
453    fn pair_fix(&mut self, timestamp_ns: i64, map_from_body: &SE3) {
454        let index = self
455            .wheel_history
456            .partition_point(|(t, _)| *t < timestamp_ns);
457        let Some((after_ns, after)) = self.wheel_history.get(index) else {
458            return;
459        };
460        let wheel = if *after_ns == timestamp_ns {
461            after.clone()
462        } else {
463            let Some((before_ns, before)) = index.checked_sub(1).map(|i| &self.wheel_history[i])
464            else {
465                return;
466            };
467            if after_ns - before_ns > MAX_FIX_WHEEL_GAP_NS {
468                return;
469            }
470            let alpha = (timestamp_ns - before_ns) as f64 / (after_ns - before_ns) as f64;
471            SE3::new(
472                before.rotation.slerp(&after.rotation, alpha),
473                before.translation.lerp(&after.translation, alpha),
474            )
475        };
476        let pair = Pair {
477            timestamp_ns,
478            body: map_from_body.translation.xy(),
479            wheel: wheel.translation.xy(),
480            wheel_yaw: yaw_of(&wheel.rotation),
481            up_in_body: map_from_body.rotation.inverse() * Vector3::z(),
482        };
483        if self
484            .fix_pairs
485            .back()
486            .is_some_and(|last| timestamp_ns <= last.timestamp_ns)
487        {
488            return;
489        }
490        self.fix_pairs.push_back(pair);
491        drop_older(&mut self.fix_pairs, timestamp_ns, self.config.window_s);
492    }
493
494    /// The fit over the pairs so far: the offset from the VIO (from the map
495    /// localizations without one), the level from the map localizations
496    /// (from the VIO without them), the scale from the map localizations,
497    /// the rest from the prior. `None` until the VIO pairs are
498    /// [ready](Self::is_ready) or the map localizations
499    /// [ready](Self::fixes_ready).
500    pub fn estimate(&self) -> Option<WheelCalibrationEstimate> {
501        let vio_ready = self.is_ready();
502        let fixes_ready = self.fixes_ready();
503        let fixes_travelled = self.fixes_travelled();
504        if !vio_ready && !fixes_ready {
505            return None;
506        }
507        let prior = self.prior.as_ref();
508        let prior_offset = prior.map_or_else(Vector2::zeros, |prior| prior.offset);
509        let weight = |stddev: f64| {
510            if self.config.offset_stddev_m > 0.0 {
511                (stddev / self.config.offset_stddev_m).powi(2)
512            } else {
513                0.0
514            }
515        };
516        let segment_ns = (self.config.segment_s.max(0.0) * 1e9) as i64;
517        let fix_segment_ns = (self.config.fix_segment_s.max(0.0) * 1e9) as i64;
518        let pairs: Vec<Pair> = self.pairs.iter().copied().collect();
519        let vio_fit = vio_ready.then(|| {
520            fit(
521                &pairs,
522                segment_ns,
523                OffsetFit::Fitted(prior_offset, weight(VIO_STDDEV_M)),
524                30,
525            )
526        });
527
528        let mut fixes: Vec<Pair> = self.fix_pairs.iter().copied().collect();
529        let (offset, offset_from, rms_m, rms_without_offset_m) = if let Some(vio_fit) = &vio_fit {
530            let without = fit(&pairs, segment_ns, OffsetFit::Held(Vector2::zeros()), 0);
531            (
532                vio_fit.offset,
533                CalibrationSource::Vio,
534                vio_fit.rms,
535                without.rms,
536            )
537        } else if fixes_travelled {
538            let fitted = robust_fit(
539                &mut fixes,
540                fix_segment_ns,
541                OffsetFit::Fitted(prior_offset, weight(FIX_STDDEV_M)),
542                self.config.max_fix_residual_m,
543                self.config.min_fixes,
544            );
545            let without = fit(&fixes, fix_segment_ns, OffsetFit::Held(Vector2::zeros()), 0);
546            (
547                fitted.offset,
548                CalibrationSource::Map,
549                fitted.rms,
550                without.rms,
551            )
552        } else if let Some(prior) = prior {
553            (prior.offset, CalibrationSource::Prior, f64::NAN, f64::NAN)
554        } else {
555            (
556                Vector2::zeros(),
557                CalibrationSource::Default,
558                f64::NAN,
559                f64::NAN,
560            )
561        };
562
563        let map_fit = fixes_travelled.then(|| {
564            robust_fit(
565                &mut fixes,
566                fix_segment_ns,
567                OffsetFit::Held(offset),
568                self.config.max_fix_residual_m,
569                self.config.min_fixes,
570            )
571        });
572        let (scale, scale_from) = match (&map_fit, prior) {
573            (Some(map_fit), _) => (map_fit.scale, CalibrationSource::Map),
574            (None, Some(prior)) => (prior.scale, CalibrationSource::Prior),
575            (None, None) => (1.0, CalibrationSource::Default),
576        };
577
578        let mean_up = |pairs: &[Pair]| {
579            pairs
580                .iter()
581                .map(|pair| pair.up_in_body)
582                .sum::<Vector3<f64>>()
583                .normalize()
584        };
585        // The map localizations the scale's fit kept, or all of them.
586        let up = if fixes_ready {
587            Some((mean_up(&fixes), CalibrationSource::Map))
588        } else if vio_ready {
589            Some((mean_up(&pairs), CalibrationSource::Vio))
590        } else {
591            None
592        };
593        let (body_from_level, tilt_deg, level_from) = match (up, prior) {
594            (Some((up, source)), _) => {
595                let tilt_deg = up.z.clamp(-1.0, 1.0).acos().to_degrees();
596                let body_from_level = if self.config.level {
597                    UnitQuaternion::rotation_between(&Vector3::z(), &up)
598                        .unwrap_or_else(UnitQuaternion::identity)
599                } else {
600                    UnitQuaternion::identity()
601                };
602                (body_from_level, tilt_deg, source)
603            }
604            (None, Some(prior)) => (
605                prior.body_from_level,
606                prior.tilt_deg,
607                CalibrationSource::Prior,
608            ),
609            (None, None) => (UnitQuaternion::identity(), 0.0, CalibrationSource::Default),
610        };
611
612        Some(WheelCalibrationEstimate {
613            offset,
614            scale,
615            vio_scale: vio_fit.as_ref().map(|fit| fit.scale),
616            body_from_level,
617            tilt_deg,
618            rms_m,
619            rms_without_offset_m,
620            map_rms_m: map_fit.map(|fit| fit.rms),
621            turned_deg: self.turned_deg(),
622            pairs: self.pairs.len(),
623            fixes: fixes.len(),
624            offset_from,
625            scale_from,
626            level_from,
627        })
628    }
629}
630
631fn drop_older(pairs: &mut VecDeque<Pair>, newest_ns: i64, window_s: f64) {
632    if window_s <= 0.0 {
633        return;
634    }
635    let window_ns = (window_s * 1e9) as i64;
636    while pairs
637        .front()
638        .is_some_and(|pair| newest_ns - pair.timestamp_ns > window_ns)
639    {
640        pairs.pop_front();
641    }
642}
643
644fn turned_rad(pairs: &VecDeque<Pair>) -> f64 {
645    pairs
646        .iter()
647        .zip(pairs.iter().skip(1))
648        .map(|(a, b)| wrap_angle(b.wheel_yaw - a.wheel_yaw).abs())
649        .sum()
650}
651
652fn travel(pairs: &VecDeque<Pair>) -> f64 {
653    pairs
654        .iter()
655        .zip(pairs.iter().skip(1))
656        .map(|(a, b)| (b.wheel - a.wheel).norm())
657        .sum()
658}
659
660fn yaw_of(rotation: &UnitQuaternion<f64>) -> f64 {
661    let matrix = rotation.to_rotation_matrix();
662    matrix[(1, 0)].atan2(matrix[(0, 0)])
663}
664
665fn wrap_angle(angle: f64) -> f64 {
666    (angle + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI
667}
668
669fn rotation2(angle: f64) -> Matrix2<f64> {
670    let (s, c) = angle.sin_cos();
671    Matrix2::new(c, -s, s, c)
672}
673
674struct Fit {
675    offset: Vector2<f64>,
676    scale: f64,
677    rms: f64,
678    residuals: Vec<f64>,
679}
680
681/// The offset in [`fit`]: held, or fitted with a prior and the prior's
682/// weight against a pair's squared residual.
683#[derive(Debug, Clone, Copy)]
684enum OffsetFit {
685    Held(Vector2<f64>),
686    Fitted(Vector2<f64>, f64),
687}
688
689/// The stretches of [`WheelCalibrationConfig::segment_s`] (or
690/// `fix_segment_s`): ranges of pairs (in time order) within `segment_ns` of
691/// the first of theirs, or one for all with 0.
692fn segments(pairs: &[Pair], segment_ns: i64) -> Vec<Range<usize>> {
693    let mut segments = Vec::new();
694    let mut start = 0;
695    for index in 1..pairs.len() {
696        if segment_ns > 0 && pairs[index].timestamp_ns - pairs[start].timestamp_ns > segment_ns {
697            segments.push(start..index);
698            start = index;
699        }
700    }
701    if start < pairs.len() {
702        segments.push(start..pairs.len());
703    }
704    segments
705}
706
707fn mean(points: impl Iterator<Item = Vector2<f64>>) -> Vector2<f64> {
708    let (sum, count) = points.fold((Vector2::zeros(), 0usize), |(sum, count), point| {
709        (sum + point, count + 1)
710    });
711    sum / count.max(1) as f64
712}
713
714/// Offset `r`, scale and residuals of
715/// `body ~ s R(a_k) (wheel + R(yaw) r) + t_k`, with `a_k`, `t_k` for each
716/// stretch of `segment_ns` ([`segments`]) and `s`, `r` shared. Alternates
717/// those with the offset (linear, `t_k` centred out) `iterations` times,
718/// from the held offset or the prior. A fitted offset is drawn to its prior
719/// by the weight, which decides it where the pairs' turns do not.
720fn fit(pairs: &[Pair], segment_ns: i64, offset_fit: OffsetFit, iterations: usize) -> Fit {
721    let segments = segments(pairs, segment_ns);
722    let (mut offset, prior) = match offset_fit {
723        OffsetFit::Held(offset) => (offset, None),
724        OffsetFit::Fitted(prior, weight) => (prior, Some((prior, weight))),
725    };
726    // Each stretch's rotation and centroids, and the scale over all of them.
727    let similarity = |offset: &Vector2<f64>| {
728        let q: Vec<Vector2<f64>> = pairs
729            .iter()
730            .map(|pair| pair.wheel + rotation2(pair.wheel_yaw) * offset)
731            .collect();
732        let (mut stretches, mut dot, mut spread) = (Vec::with_capacity(segments.len()), 0.0, 0.0);
733        for range in &segments {
734            let (q, pairs) = (&q[range.clone()], &pairs[range.clone()]);
735            let mean_q = mean(q.iter().copied());
736            let mean_g = mean(pairs.iter().map(|pair| pair.body));
737            let h = q
738                .iter()
739                .zip(pairs)
740                .map(|(q, pair)| (q - mean_q) * (pair.body - mean_g).transpose())
741                .sum::<Matrix2<f64>>();
742            let rotation = rotation2((h[(0, 1)] - h[(1, 0)]).atan2(h[(0, 0)] + h[(1, 1)]));
743            for (q, pair) in q.iter().zip(pairs) {
744                dot += (pair.body - mean_g).dot(&(rotation * (q - mean_q)));
745                spread += (q - mean_q).norm_squared();
746            }
747            stretches.push((rotation, mean_q, mean_g));
748        }
749        let scale = if spread > 0.0 { dot / spread } else { 1.0 };
750        (stretches, scale, q)
751    };
752    if let Some((prior, weight)) = prior {
753        for _ in 0..iterations {
754            let (stretches, scale, _) = similarity(&offset);
755            // Centred within a stretch, body - s R wheel = s R R(yaw) r + t
756            // leaves the offset alone, linear.
757            let (mut normal, mut rhs) = (Matrix2::identity() * weight, prior * weight);
758            for (range, (rotation, _, _)) in segments.iter().zip(&stretches) {
759                let pairs = &pairs[range.clone()];
760                let count = pairs.len() as f64;
761                let mean_turn = pairs
762                    .iter()
763                    .map(|pair| rotation2(pair.wheel_yaw))
764                    .sum::<Matrix2<f64>>()
765                    / count;
766                let mean_wheel = mean(pairs.iter().map(|pair| pair.wheel));
767                let mean_body = mean(pairs.iter().map(|pair| pair.body));
768                for pair in pairs {
769                    let m = scale * rotation * (rotation2(pair.wheel_yaw) - mean_turn);
770                    let b = pair.body - mean_body - scale * rotation * (pair.wheel - mean_wheel);
771                    normal += m.transpose() * m;
772                    rhs += m.transpose() * b;
773                }
774            }
775            match normal.try_inverse() {
776                Some(inverse) => offset = inverse * rhs,
777                None => break,
778            }
779        }
780    }
781    let (stretches, scale, q) = similarity(&offset);
782    let mut residuals = Vec::with_capacity(pairs.len());
783    for (range, (rotation, mean_q, mean_g)) in segments.iter().zip(&stretches) {
784        for (q, pair) in q[range.clone()].iter().zip(&pairs[range.clone()]) {
785            residuals.push((pair.body - mean_g - scale * rotation * (q - mean_q)).norm());
786        }
787    }
788    let rms = (residuals.iter().map(|r| r * r).sum::<f64>() / pairs.len().max(1) as f64).sqrt();
789    Fit {
790        offset,
791        scale,
792        rms,
793        residuals,
794    }
795}
796
797/// [`fit`] over map localizations, leaving out those further than
798/// `max_residual` from the fit through the rest (twice), as long as
799/// `min_kept` remain. `pairs` keeps those used.
800fn robust_fit(
801    pairs: &mut Vec<Pair>,
802    segment_ns: i64,
803    offset_fit: OffsetFit,
804    max_residual: f64,
805    min_kept: usize,
806) -> Fit {
807    let mut result = fit(pairs, segment_ns, offset_fit, 30);
808    for _ in 0..2 {
809        if max_residual <= 0.0 || result.residuals.iter().all(|r| *r <= max_residual) {
810            break;
811        }
812        let kept: Vec<Pair> = pairs
813            .iter()
814            .zip(&result.residuals)
815            .filter(|(_, r)| **r <= max_residual)
816            .map(|(pair, _)| *pair)
817            .collect();
818        if kept.len() < min_kept.max(3) {
819            break;
820        }
821        *pairs = kept;
822        result = fit(pairs, segment_ns, offset_fit, 30);
823    }
824    result
825}
826
827#[cfg(test)]
828mod tests {
829    use super::*;
830
831    const MS: i64 = 1_000_000;
832
833    fn rz(angle: f64) -> UnitQuaternion<f64> {
834        UnitQuaternion::from_axis_angle(&Vector3::z_axis(), angle)
835    }
836
837    /// A drive: 2 m ahead, a half turn in place, 2 m back, a quarter turn,
838    /// `laps` times; the turns as the wheels measure them `turn_gain` times
839    /// the true ones (1: the true drive).
840    fn drive_laps(laps: usize, turn_gain: f64) -> Vec<(f64, f64, f64)> {
841        let (mut x, mut y, mut yaw, mut poses) = (0.0, 0.0, 0.0, Vec::new());
842        for _ in 0..laps {
843            for (steps, speed, turn) in [
844                (100, 0.02, 0.0),
845                (90, 0.0, std::f64::consts::PI / 90.0),
846                (100, 0.02, 0.0),
847                (45, 0.0, std::f64::consts::PI / 90.0),
848            ] {
849                for _ in 0..steps {
850                    x += speed * f64::cos(yaw);
851                    y += speed * f64::sin(yaw);
852                    yaw += turn * turn_gain;
853                    poses.push((x, y, yaw));
854                }
855            }
856        }
857        poses
858    }
859
860    fn drive() -> Vec<(f64, f64, f64)> {
861        drive_laps(1, 1.0)
862    }
863
864    /// The true `T_imu_body`: the IMU 0.9 m above the body, rotated.
865    fn imu_from_body() -> SE3 {
866        SE3::new(
867            UnitQuaternion::from_euler_angles(-1.55, 0.02, -1.6),
868            Vector3::new(0.03, -0.89, -0.25),
869        )
870    }
871
872    /// The true body pose in a reference `scale` times the wheels', with
873    /// the body origin `offset` from the wheel point.
874    fn body_in(world: &SE3, wheel: &SE3, offset: Vector2<f64>, scale: f64) -> SE3 {
875        let body_position =
876            scale * (wheel.translation + wheel.rotation * Vector3::new(offset.x, offset.y, 0.0));
877        world.compose(&SE3::new(wheel.rotation, body_position))
878    }
879
880    fn wheel_pose((x, y, yaw): (f64, f64, f64)) -> SE3 {
881        SE3::new(rz(yaw), Vector3::new(x, y, 0.0))
882    }
883
884    /// Feeds a run whose body origin is `offset` from the wheel point and
885    /// whose VIO is `scale` times the wheels, and the map localizations
886    /// `fixes` once the wheel pose after their image is in.
887    fn run_with(
888        offset: Vector2<f64>,
889        scale: f64,
890        given: &SE3,
891        fixes: &[(i64, SE3)],
892    ) -> WheelCalibration {
893        let truth = imu_from_body();
894        let world = SE3::new(rz(0.4), Vector3::new(0.3, -1.2, 0.5));
895        let mut calibration =
896            WheelCalibration::new(WheelCalibrationConfig::default(), given.clone());
897        let mut fixes = fixes.iter().peekable();
898        for (index, pose) in drive().into_iter().enumerate() {
899            let wheel = wheel_pose(pose);
900            let world_from_imu = body_in(&world, &wheel, offset, scale).compose(&truth.inverse());
901            let t = wheel_stamp(index);
902            // The VIO runs 2 ms behind the wheels' stamps and arrives first
903            // half the time.
904            if index % 2 == 0 {
905                calibration.add_vio(t + 2 * MS, &world_from_imu);
906                calibration.add_wheel(t, &wheel);
907            } else {
908                calibration.add_wheel(t, &wheel);
909                calibration.add_vio(t + 2 * MS, &world_from_imu);
910            }
911            while let Some((fix_t, fix)) = fixes.next_if(|(fix_t, _)| *fix_t <= t) {
912                calibration.add_fix(*fix_t, fix);
913            }
914        }
915        calibration
916    }
917
918    fn run(offset: Vector2<f64>, scale: f64, given: &SE3) -> WheelCalibration {
919        run_with(offset, scale, given, &[])
920    }
921
922    fn wheel_stamp(index: usize) -> i64 {
923        1_000 * MS + index as i64 * 50 * MS
924    }
925
926    /// Map localizations of [`drive`] halfway between every `every`-th
927    /// wheel pose and the one before: the body in a map `scale` times the
928    /// wheels', with the given body frame tilted by `tilt` against the
929    /// map's gravity.
930    fn fixes(
931        offset: Vector2<f64>,
932        scale: f64,
933        tilt: &UnitQuaternion<f64>,
934        every: usize,
935    ) -> Vec<(i64, SE3)> {
936        let map = SE3::new(rz(-1.1), Vector3::new(4.0, 2.0, 0.0));
937        let poses = drive();
938        (1..poses.len())
939            .step_by(every)
940            .map(|index| {
941                let (a, b) = (wheel_pose(poses[index - 1]), wheel_pose(poses[index]));
942                let wheel = SE3::new(
943                    a.rotation.slerp(&b.rotation, 0.5),
944                    a.translation.lerp(&b.translation, 0.5),
945                );
946                let body = body_in(&map, &wheel, offset, scale);
947                (
948                    wheel_stamp(index) - 25 * MS,
949                    SE3::new(body.rotation * tilt.inverse(), body.translation),
950                )
951            })
952            .collect()
953    }
954
955    #[test]
956    fn recovers_the_offset_scale_and_level() {
957        let offset = Vector2::new(0.041, 0.064);
958        let calibration = run(offset, 1.03, &imu_from_body());
959        assert!(calibration.is_ready());
960        assert!(!calibration.fixes_ready());
961        let estimate = calibration.estimate().expect("estimate");
962        // (The prior, zero, draws the offset by a few hundredths of a mm.)
963        assert!((estimate.offset - offset).norm() < 1e-4, "{estimate:?}");
964        // The VIO's scale is reported, not used: no map localizations, so 1.
965        assert!((estimate.vio_scale.expect("vio") - 1.03).abs() < 1e-5);
966        assert_eq!(estimate.scale, 1.0);
967        assert!(estimate.rms_m < 1e-4);
968        assert!(estimate.rms_without_offset_m > 0.02);
969        assert!(estimate.tilt_deg < 1e-6);
970        assert!(
971            (estimate.turned_deg - 270.0).abs() < 2.5,
972            "{}",
973            estimate.turned_deg
974        );
975        assert_eq!(estimate.pairs, drive().len());
976        assert_eq!(
977            (
978                estimate.offset_from,
979                estimate.scale_from,
980                estimate.level_from
981            ),
982            (
983                CalibrationSource::Vio,
984                CalibrationSource::Default,
985                CalibrationSource::Vio
986            )
987        );
988        assert_eq!(estimate.map_rms_m, None);
989    }
990
991    #[test]
992    fn a_tilted_extrinsic_is_levelled_and_the_body_follows_the_wheels() {
993        let truth = imu_from_body();
994        let tilt = UnitQuaternion::from_euler_angles(0.0, 2f64.to_radians(), 0.0);
995        let given = SE3::new(truth.rotation * tilt, truth.translation);
996        let offset = Vector2::new(0.013, 0.062);
997        let estimate = run(offset, 1.0, &given).estimate().expect("estimate");
998        assert!((estimate.tilt_deg - 2.0).abs() < 1e-6);
999        // Levelled, the given extrinsic becomes the true one (no turn about z).
1000        let imu_from_wheel = estimate.imu_from_wheel(&given);
1001        assert!(imu_from_wheel.rotation.angle_to(&truth.rotation) < 1e-9);
1002        let expected = truth.translation - truth.rotation * Vector3::new(offset.x, offset.y, 0.0);
1003        assert!((imu_from_wheel.translation - expected).norm() < 1e-4);
1004        // The body pose from a wheel pose puts the IMU where the given
1005        // extrinsic says, as the VIO saw it.
1006        let wheel = SE3::new(rz(0.7), Vector3::new(1.0, 2.0, 0.0));
1007        let odom_from_body = estimate.odom_from_body(&wheel);
1008        let imu_from_wheel_pose = wheel.compose(&imu_from_wheel.inverse());
1009        let imu_from_body_pose = odom_from_body.compose(&given.inverse());
1010        assert!((imu_from_wheel_pose.translation - imu_from_body_pose.translation).norm() < 1e-5);
1011        assert!(
1012            imu_from_wheel_pose
1013                .rotation
1014                .angle_to(&imu_from_body_pose.rotation)
1015                < 1e-9
1016        );
1017    }
1018
1019    #[test]
1020    fn not_ready_before_enough_turning() {
1021        let mut calibration =
1022            WheelCalibration::new(WheelCalibrationConfig::default(), imu_from_body());
1023        for index in 0..300 {
1024            let t = index as i64 * 50 * MS;
1025            let pose = SE3::new(rz(0.0), Vector3::new(index as f64 * 0.02, 0.0, 0.0));
1026            calibration.add_vio(t, &pose.compose(&imu_from_body().inverse()));
1027            calibration.add_wheel(t, &pose);
1028        }
1029        assert_eq!(calibration.pairs(), 300);
1030        assert!(calibration.travel_m() > 5.9);
1031        assert!(!calibration.is_ready());
1032        assert!(calibration.estimate().is_none());
1033        // Wheel poses without a VIO pose close enough are not paired.
1034        calibration.add_wheel(400 * 50 * MS, &SE3::identity());
1035        calibration.add_vio(401 * 50 * MS, &SE3::identity());
1036        assert_eq!(calibration.pairs(), 300);
1037    }
1038
1039    #[test]
1040    fn map_localizations_give_the_scale_and_the_level_and_the_vio_the_offset() {
1041        let offset = Vector2::new(0.041, 0.064);
1042        // The VIO is 3 % off the wheels' scale, the map 1.2 %; the map's
1043        // gravity is 1.5 deg off the VIO's for the given body frame.
1044        let tilt = UnitQuaternion::from_euler_angles(1.5f64.to_radians(), 0.0, 0.0);
1045        let fixes = fixes(offset, 1.012, &tilt, 7);
1046        let calibration = run_with(offset, 1.03, &imu_from_body(), &fixes);
1047        assert!(calibration.fixes_ready());
1048        let estimate = calibration.estimate().expect("estimate");
1049        assert_eq!(estimate.offset_from, CalibrationSource::Vio);
1050        assert_eq!(estimate.scale_from, CalibrationSource::Map);
1051        assert_eq!(estimate.level_from, CalibrationSource::Map);
1052        assert!((estimate.offset - offset).norm() < 1e-4);
1053        // (The map's fit holds the VIO's offset, a few hundredths of a mm off.)
1054        assert!((estimate.scale - 1.012).abs() < 1e-4, "{}", estimate.scale);
1055        assert!(
1056            (estimate.tilt_deg - 1.5).abs() < 1e-6,
1057            "{}",
1058            estimate.tilt_deg
1059        );
1060        assert!(estimate.map_rms_m.expect("map fit") < 1e-4);
1061        assert_eq!(estimate.fixes, fixes.len());
1062    }
1063
1064    #[test]
1065    fn map_localizations_alone_hold_the_prior_offset_until_they_turn_and_drop_outliers() {
1066        let offset = Vector2::new(0.03, -0.05);
1067        let prior = WheelCalibrationEstimate {
1068            offset: Vector2::new(0.02, -0.04),
1069            scale: 1.05,
1070            ..WheelCalibrationEstimate::identity()
1071        };
1072        let mut fixes = fixes(offset, 0.99, &UnitQuaternion::identity(), 5);
1073        // One localization (in the turn) is 1 m off.
1074        fixes[30].1.translation.x += 1.0;
1075        let mut calibration =
1076            WheelCalibration::without_vio(WheelCalibrationConfig::default()).with_prior(prior);
1077        let mut pending = fixes.iter().peekable();
1078        let mut checked_before_turn = false;
1079        for (index, pose) in drive().into_iter().enumerate() {
1080            let t = wheel_stamp(index);
1081            // The localizations come in before the wheel pose after them.
1082            while let Some((fix_t, fix)) = pending.next_if(|(fix_t, _)| *fix_t <= t) {
1083                calibration.add_fix(*fix_t, fix);
1084            }
1085            calibration.add_wheel(t, &wheel_pose(pose));
1086            // After 2 m straight on, the scale and the level are known; the
1087            // offset, which no turn has shown yet, stays the prior's.
1088            if !checked_before_turn && calibration.fix_turned_deg() > 0.5 {
1089                checked_before_turn = true;
1090                let estimate = calibration.estimate().expect("2 m of fixes");
1091                assert_eq!(estimate.offset_from, CalibrationSource::Map);
1092                assert!((estimate.offset - Vector2::new(0.02, -0.04)).norm() < 1e-3);
1093                assert_eq!(estimate.scale_from, CalibrationSource::Map);
1094                assert!((estimate.scale - 0.99).abs() < 1e-3, "{}", estimate.scale);
1095            }
1096        }
1097        assert!(checked_before_turn);
1098        assert!(calibration.fix_turned_deg() > 180.0);
1099        let estimate = calibration.estimate().expect("estimate");
1100        assert_eq!(estimate.offset_from, CalibrationSource::Map);
1101        // The turns show the offset; the prior's pull is a fraction of a mm.
1102        assert!((estimate.offset - offset).norm() < 3e-4, "{estimate:?}");
1103        assert!((estimate.scale - 0.99).abs() < 1e-4);
1104        assert!(estimate.tilt_deg < 1e-6);
1105        // The localization 1 m off is left out.
1106        assert_eq!(estimate.fixes, fixes.len() - 1);
1107    }
1108
1109    #[test]
1110    fn stretches_keep_the_wheels_heading_drift_out_of_the_offset() {
1111        // Four laps whose turns the wheels overcount by 5 %, as when they
1112        // slip: their heading drifts 54 deg off the VIO's.
1113        let offset = Vector2::new(0.041, 0.064);
1114        let (truth, world) = (
1115            imu_from_body(),
1116            SE3::new(rz(0.4), Vector3::new(0.3, -1.2, 0.5)),
1117        );
1118        let offset_error = |segment_s: f64| {
1119            let config = WheelCalibrationConfig {
1120                segment_s,
1121                ..WheelCalibrationConfig::default()
1122            };
1123            let mut calibration = WheelCalibration::new(config, truth.clone());
1124            for (index, (body, wheel)) in drive_laps(4, 1.0)
1125                .into_iter()
1126                .zip(drive_laps(4, 1.05))
1127                .enumerate()
1128            {
1129                let t = wheel_stamp(index);
1130                let body = body_in(&world, &wheel_pose(body), offset, 1.0);
1131                calibration.add_vio(t, &body.compose(&truth.inverse()));
1132                calibration.add_wheel(t, &wheel_pose(wheel));
1133            }
1134            let estimate = calibration.estimate().expect("estimate");
1135            (estimate.offset - offset).norm()
1136        };
1137        // 3.6 mm off in 5 s stretches (a turn's own slip stays in), 8 cm
1138        // with one heading for the whole run.
1139        let (stretches, one) = (offset_error(5.0), offset_error(0.0));
1140        assert!(stretches < 0.005, "{stretches}");
1141        assert!(one > 0.05, "{one}");
1142    }
1143
1144    #[test]
1145    fn the_window_keeps_only_recent_pairs() {
1146        let config = WheelCalibrationConfig {
1147            window_s: 5.0,
1148            ..WheelCalibrationConfig::default()
1149        };
1150        let mut calibration = WheelCalibration::new(config, imu_from_body());
1151        for index in 0..300 {
1152            let t = index as i64 * 50 * MS;
1153            let pose = SE3::new(rz(0.0), Vector3::new(index as f64 * 0.02, 0.0, 0.0));
1154            calibration.add_vio(t, &pose.compose(&imu_from_body().inverse()));
1155            calibration.add_wheel(t, &pose);
1156        }
1157        assert_eq!(calibration.pairs(), 101);
1158    }
1159}