1use std::collections::VecDeque;
47use std::ops::Range;
48
49use nalgebra::{Matrix2, UnitQuaternion, Vector2, Vector3};
50use visloc_core::geometry::SE3;
51
52const MAX_FIX_WHEEL_GAP_NS: i64 = 200_000_000;
55const FIX_WHEEL_HISTORY_NS: i64 = 10_000_000_000;
57const MAX_WAITING_FIXES: usize = 100;
59const VIO_STDDEV_M: f64 = 0.005;
63const FIX_STDDEV_M: f64 = 0.015;
64
65#[derive(Debug, Clone, PartialEq)]
66pub struct WheelCalibrationConfig {
67 pub max_gap_ns: i64,
69 pub min_turn_deg: f64,
72 pub min_travel_m: f64,
75 pub min_pairs: usize,
77 pub min_fixes: usize,
81 pub max_fix_residual_m: f64,
84 pub window_s: f64,
87 pub segment_s: f64,
92 pub fix_segment_s: f64,
95 pub offset_stddev_m: f64,
99 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum CalibrationSource {
124 Vio,
126 Map,
128 Prior,
130 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#[derive(Debug, Clone, PartialEq)]
147pub struct WheelCalibrationEstimate {
148 pub offset: Vector2<f64>,
151 pub scale: f64,
154 pub vio_scale: Option<f64>,
157 pub body_from_level: UnitQuaternion<f64>,
160 pub tilt_deg: f64,
163 pub rms_m: f64,
166 pub rms_without_offset_m: f64,
167 pub map_rms_m: Option<f64>,
169 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 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 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 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#[derive(Debug, Clone)]
231pub struct WheelCalibration {
232 config: WheelCalibrationConfig,
233 imu_from_body: Option<SE3>,
235 prior: Option<WheelCalibrationEstimate>,
236 vio: VecDeque<(i64, SE3)>,
238 waiting: VecDeque<(i64, SE3)>,
240 wheel_history: VecDeque<(i64, SE3)>,
242 waiting_fixes: VecDeque<(i64, SE3)>,
244 pairs: VecDeque<Pair>,
245 fix_pairs: VecDeque<Pair>,
246}
247
248impl WheelCalibration {
249 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 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 #[must_use]
276 pub fn with_prior(mut self, prior: WheelCalibrationEstimate) -> Self {
277 self.prior = Some(prior);
278 self
279 }
280
281 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 pub fn pairs(&self) -> usize {
292 self.pairs.len()
293 }
294
295 pub fn fixes(&self) -> usize {
297 self.fix_pairs.len()
298 }
299
300 pub fn turned_deg(&self) -> f64 {
302 turned_rad(&self.pairs).to_degrees()
303 }
304
305 pub fn travel_m(&self) -> f64 {
307 travel(&self.pairs)
308 }
309
310 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 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 pub fn fixes_ready(&self) -> bool {
329 self.fix_pairs.len() >= self.config.min_fixes.max(3)
330 }
331
332 pub fn fixes_travelled(&self) -> bool {
335 self.fixes_ready() && self.fix_travel_m() >= self.config.min_travel_m
336 }
337
338 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 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 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 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 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 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#[derive(Debug, Clone, Copy)]
684enum OffsetFit {
685 Held(Vector2<f64>),
686 Fitted(Vector2<f64>, f64),
687}
688
689fn 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
714fn 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 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 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
797fn 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 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 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 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 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 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 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 assert!((estimate.offset - offset).norm() < 1e-4, "{estimate:?}");
964 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 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 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 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 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 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 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 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 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 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 assert_eq!(estimate.fixes, fixes.len() - 1);
1107 }
1108
1109 #[test]
1110 fn stretches_keep_the_wheels_heading_drift_out_of_the_offset() {
1111 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 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}