1use std::collections::VecDeque;
46
47const PATH_HISTORY_NS: i64 = 30_000_000_000;
51
52use nalgebra::{UnitQuaternion, Vector3};
53use visloc_core::geometry::SE3;
54
55#[derive(Debug, Clone, PartialEq)]
56pub struct OdomCorrectionConfig {
57 pub init_fixes: usize,
59 pub init_fixes_weak: usize,
61 pub reset_after: usize,
63 pub agreement_m: f64,
66 pub gate_m: f64,
68 pub gate_per_m: f64,
71 pub gate_yaw_deg: f64,
73 pub gate_yaw_per_m_deg: f64,
76 pub window_s: f64,
79 pub weak_gate_m: f64,
84 pub weak_gate_yaw_deg: f64,
86}
87
88impl Default for OdomCorrectionConfig {
89 fn default() -> Self {
90 Self {
91 init_fixes: 2,
92 init_fixes_weak: 3,
93 reset_after: 3,
94 agreement_m: 0.10,
95 gate_m: 0.15,
96 gate_per_m: 0.05,
97 gate_yaw_deg: 3.0,
98 gate_yaw_per_m_deg: 1.0,
99 window_s: 5.0,
100 weak_gate_m: 0.0,
101 weak_gate_yaw_deg: 2.0,
102 }
103 }
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum FixOutcome {
109 Pending,
111 Initialized,
113 Accepted,
115 Rejected,
117 Reset,
120 Unused,
122}
123
124#[derive(Debug, Clone, Copy, PartialEq)]
126pub(crate) struct Offset {
127 pub(crate) yaw: f64,
128 pub(crate) translation: Vector3<f64>,
129}
130
131impl Offset {
132 pub(crate) fn rotation(&self) -> UnitQuaternion<f64> {
133 UnitQuaternion::from_axis_angle(&Vector3::z_axis(), self.yaw)
134 }
135
136 pub(crate) fn se3(&self) -> SE3 {
137 SE3::new(self.rotation(), self.translation)
138 }
139}
140
141#[derive(Debug, Clone, PartialEq)]
142struct Fix {
143 timestamp_ns: i64,
144 map_position: Vector3<f64>,
145 odom_position: Vector3<f64>,
146 yaw: f64,
149 weak: bool,
150}
151
152pub(crate) fn yaw_of(rotation: &UnitQuaternion<f64>) -> f64 {
153 let matrix = rotation.to_rotation_matrix();
154 matrix[(1, 0)].atan2(matrix[(0, 0)])
155}
156
157pub(crate) fn wrap_angle(angle: f64) -> f64 {
158 (angle + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI
159}
160
161fn fit(fixes: &[&Fix]) -> Offset {
164 let (sin, cos) = fixes.iter().fold((0.0, 0.0), |(sin, cos), fix| {
165 (sin + fix.yaw.sin(), cos + fix.yaw.cos())
166 });
167 let yaw = sin.atan2(cos);
168 let rotation = UnitQuaternion::from_axis_angle(&Vector3::z_axis(), yaw);
169 let translation = fixes
170 .iter()
171 .map(|fix| fix.map_position - rotation * fix.odom_position)
172 .sum::<Vector3<f64>>()
173 / fixes.len() as f64;
174 Offset { yaw, translation }
175}
176
177fn residuals(offset: &Offset, fix: &Fix) -> (f64, f64) {
178 let predicted = offset.rotation() * fix.odom_position + offset.translation;
179 (
180 (predicted - fix.map_position).norm(),
181 wrap_angle(fix.yaw - offset.yaw).abs().to_degrees(),
182 )
183}
184
185#[derive(Debug, Clone)]
186pub struct OdomCorrection {
187 config: OdomCorrectionConfig,
188 offset: Option<Offset>,
189 window: VecDeque<Fix>,
191 candidates: Vec<Fix>,
193 previous_odom_position: Option<Vector3<f64>>,
196 travel_since_accept_m: f64,
197 path: VecDeque<(i64, f64)>,
200 path_end: Option<Vector3<f64>>,
202 path_at_accept_m: Option<f64>,
204}
205
206impl OdomCorrection {
207 pub fn new(config: OdomCorrectionConfig) -> Self {
208 Self {
209 config,
210 offset: None,
211 window: VecDeque::new(),
212 candidates: Vec::new(),
213 previous_odom_position: None,
214 travel_since_accept_m: 0.0,
215 path: VecDeque::new(),
216 path_end: None,
217 path_at_accept_m: None,
218 }
219 }
220
221 pub const fn config(&self) -> &OdomCorrectionConfig {
222 &self.config
223 }
224
225 pub const fn is_set(&self) -> bool {
227 self.offset.is_some()
228 }
229
230 pub fn map_from_odom(&self) -> Option<SE3> {
232 self.offset.as_ref().map(Offset::se3)
233 }
234
235 pub fn last_fix(&self) -> Option<(i64, Vector3<f64>)> {
239 self.offset?;
240 self.window
241 .back()
242 .map(|fix| (fix.timestamp_ns, fix.odom_position))
243 }
244
245 pub fn map_from_body(&self, odom_from_body: &SE3) -> Option<SE3> {
247 self.map_from_odom()
248 .map(|map_from_odom| map_from_odom.compose(odom_from_body))
249 }
250
251 pub fn observe_odometry(&mut self, timestamp_ns: i64, odom_from_body: &SE3) {
256 if self
257 .path
258 .back()
259 .is_some_and(|(last_ns, _)| timestamp_ns <= *last_ns)
260 {
261 return;
262 }
263 let position = odom_from_body.translation;
264 let length = match (self.path.back(), self.path_end) {
265 (Some((_, length)), Some(end)) => length + (position - end).norm(),
266 _ => 0.0,
267 };
268 self.path.push_back((timestamp_ns, length));
269 self.path_end = Some(position);
270 while self
271 .path
272 .front()
273 .is_some_and(|(first_ns, _)| timestamp_ns - first_ns > PATH_HISTORY_NS)
274 {
275 self.path.pop_front();
276 }
277 }
278
279 fn path_length_at(&self, timestamp_ns: i64) -> Option<f64> {
282 let (first_ns, _) = self.path.front()?;
283 let (last_ns, _) = self.path.back()?;
284 if timestamp_ns < *first_ns || timestamp_ns > *last_ns {
285 return None;
286 }
287 let index = self
288 .path
289 .partition_point(|(stamp, _)| *stamp < timestamp_ns);
290 let (after_ns, after) = self.path[index];
291 if after_ns == timestamp_ns || index == 0 {
292 return Some(after);
293 }
294 let (before_ns, before) = self.path[index - 1];
295 let alpha = (timestamp_ns - before_ns) as f64 / (after_ns - before_ns) as f64;
296 Some(before + alpha * (after - before))
297 }
298
299 pub fn add_fix(
302 &mut self,
303 timestamp_ns: i64,
304 map_from_body: &SE3,
305 odom_from_body: &SE3,
306 ) -> FixOutcome {
307 self.add(timestamp_ns, map_from_body, odom_from_body, false)
308 }
309
310 pub fn add_weak_fix(
315 &mut self,
316 timestamp_ns: i64,
317 map_from_body: &SE3,
318 odom_from_body: &SE3,
319 ) -> FixOutcome {
320 self.add(timestamp_ns, map_from_body, odom_from_body, true)
321 }
322
323 fn add(
324 &mut self,
325 timestamp_ns: i64,
326 map_from_body: &SE3,
327 odom_from_body: &SE3,
328 weak: bool,
329 ) -> FixOutcome {
330 let fix = Fix {
331 timestamp_ns,
332 map_position: map_from_body.translation,
333 odom_position: odom_from_body.translation,
334 yaw: yaw_of(&(map_from_body.rotation * odom_from_body.rotation.inverse())),
335 weak,
336 };
337 if let Some(previous) = self.previous_odom_position {
338 self.travel_since_accept_m += (fix.odom_position - previous).norm();
339 }
340 self.previous_odom_position = Some(fix.odom_position);
341 let path_m = self.path_length_at(timestamp_ns);
342
343 let Some(offset) = self.offset else {
344 return if self.push_initial(fix) {
345 Self::adopt(&mut self.window, &mut self.candidates);
346 self.refit();
347 self.restart_travel(path_m);
348 FixOutcome::Initialized
349 } else {
350 FixOutcome::Pending
351 };
352 };
353
354 let (position_residual, yaw_residual) = residuals(&offset, &fix);
355 if weak {
356 if self.config.weak_gate_m > 0.0
357 && position_residual <= self.config.weak_gate_m
358 && yaw_residual <= self.config.weak_gate_yaw_deg
359 {
360 self.candidates.clear();
361 self.window.push_back(fix);
362 self.refit();
363 self.restart_travel(path_m);
364 return FixOutcome::Accepted;
365 }
366 return FixOutcome::Unused;
367 }
368 let travel = match (path_m, self.path_at_accept_m) {
369 (Some(now), Some(then)) => self.travel_since_accept_m.max(now - then),
370 _ => self.travel_since_accept_m,
371 };
372 let accepted = position_residual <= self.config.gate_m + self.config.gate_per_m * travel
373 && yaw_residual <= self.config.gate_yaw_deg + self.config.gate_yaw_per_m_deg * travel;
374 if accepted {
375 self.candidates.clear();
376 self.window.push_back(fix);
377 self.refit();
378 self.restart_travel(path_m);
379 return FixOutcome::Accepted;
380 }
381 if self.push_candidate(fix, self.config.reset_after) {
382 Self::adopt(&mut self.window, &mut self.candidates);
383 self.refit();
384 self.restart_travel(path_m);
385 FixOutcome::Reset
386 } else {
387 FixOutcome::Rejected
388 }
389 }
390
391 fn restart_travel(&mut self, path_m: Option<f64>) {
393 self.travel_since_accept_m = 0.0;
394 self.path_at_accept_m = path_m;
395 }
396
397 fn push_candidate(&mut self, fix: Fix, needed: usize) -> bool {
400 self.candidates.push(fix);
401 let needed = needed.max(1);
402 if self.candidates.len() > needed {
403 self.candidates.drain(..self.candidates.len() - needed);
404 }
405 self.candidates.len() == needed && self.agree(&self.candidates)
406 }
407
408 fn push_initial(&mut self, fix: Fix) -> bool {
413 let strong = self.config.init_fixes.max(1);
414 let weak = self.config.init_fixes_weak.max(strong);
415 self.candidates.push(fix);
416 if self.candidates.len() > weak {
417 self.candidates.drain(..self.candidates.len() - weak);
418 }
419 for needed in [strong, weak] {
420 let Some(start) = self.candidates.len().checked_sub(needed) else {
421 continue;
422 };
423 let newest = &self.candidates[start..];
424 let required = if newest.iter().any(|fix| fix.weak) {
425 weak
426 } else {
427 strong
428 };
429 if needed == required && self.agree(newest) {
430 self.candidates.drain(..start);
431 return true;
432 }
433 }
434 false
435 }
436
437 fn agree(&self, fixes: &[Fix]) -> bool {
439 let fixes = fixes.iter().collect::<Vec<_>>();
440 let offset = fit(&fixes);
441 fixes.iter().all(|fix| {
442 let (position, yaw) = residuals(&offset, fix);
443 position <= self.config.agreement_m && yaw <= self.config.gate_yaw_deg
444 })
445 }
446
447 fn adopt(window: &mut VecDeque<Fix>, candidates: &mut Vec<Fix>) {
448 window.clear();
449 window.extend(candidates.drain(..));
450 }
451
452 fn refit(&mut self) {
454 let Some(newest) = self.window.back().map(|fix| fix.timestamp_ns) else {
455 return;
456 };
457 let window_ns = (self.config.window_s * 1e9) as i64;
458 while self.window.len() > 1
459 && self
460 .window
461 .front()
462 .is_some_and(|fix| newest - fix.timestamp_ns > window_ns)
463 {
464 self.window.pop_front();
465 }
466 let fixes = self.window.iter().collect::<Vec<_>>();
467 self.offset = Some(fit(&fixes));
468 }
469}
470
471#[cfg(test)]
472mod tests {
473 use super::*;
474
475 const SECOND: i64 = 1_000_000_000;
476
477 fn truth() -> SE3 {
478 SE3::new(
479 UnitQuaternion::from_axis_angle(&Vector3::z_axis(), 0.6),
480 Vector3::new(3.0, -2.0, 0.5),
481 )
482 }
483
484 fn odom(index: usize) -> SE3 {
486 let t = index as f64 * 0.2;
487 SE3::new(
488 UnitQuaternion::from_euler_angles(0.05 * t.sin(), -0.03, 0.4 * t),
489 Vector3::new(t.cos() * 2.0, t.sin() * 2.0, 0.1 * t),
490 )
491 }
492
493 fn fix_at(
494 correction: &mut OdomCorrection,
495 index: usize,
496 map_from_odom: &SE3,
497 shift: Vector3<f64>,
498 ) -> FixOutcome {
499 let odom_from_body = odom(index);
500 let mut map_from_body = map_from_odom.compose(&odom_from_body);
501 map_from_body.translation += shift;
502 correction.add_fix(index as i64 * SECOND / 10, &map_from_body, &odom_from_body)
503 }
504
505 fn assert_pose_close(lhs: &SE3, rhs: &SE3, tolerance: f64) {
506 assert!(
507 (lhs.translation - rhs.translation).norm() < tolerance,
508 "{lhs:?} vs {rhs:?}"
509 );
510 assert!(
511 lhs.rotation.angle_to(&rhs.rotation) < tolerance,
512 "{lhs:?} vs {rhs:?}"
513 );
514 }
515
516 #[test]
517 fn exact_fixes_recover_the_offset_after_initialization() {
518 let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
519 assert_eq!(correction.map_from_body(&odom(0)), None);
520 assert_eq!(
521 fix_at(&mut correction, 0, &truth(), Vector3::zeros()),
522 FixOutcome::Pending
523 );
524 assert_eq!(correction.last_fix(), None);
525 assert_eq!(
526 fix_at(&mut correction, 1, &truth(), Vector3::zeros()),
527 FixOutcome::Initialized
528 );
529 assert_eq!(
530 fix_at(&mut correction, 2, &truth(), Vector3::zeros()),
531 FixOutcome::Accepted
532 );
533 assert_eq!(
534 correction.last_fix(),
535 Some((2 * SECOND / 10, odom(2).translation))
536 );
537 for index in [3, 10, 40] {
538 let pose = correction.map_from_body(&odom(index)).expect("set");
539 assert_pose_close(&pose, &truth().compose(&odom(index)), 1e-9);
540 }
541 }
542
543 #[test]
544 fn a_wrong_first_fix_does_not_place_the_trajectory() {
545 let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
546 let off = Vector3::new(1.5, 0.0, 0.0);
547 assert_eq!(
548 fix_at(&mut correction, 0, &truth(), off),
549 FixOutcome::Pending
550 );
551 assert_eq!(
552 fix_at(&mut correction, 1, &truth(), Vector3::zeros()),
553 FixOutcome::Pending
554 );
555 assert_eq!(
556 fix_at(&mut correction, 2, &truth(), Vector3::zeros()),
557 FixOutcome::Initialized
558 );
559 assert_pose_close(&correction.map_from_odom().unwrap(), &truth(), 1e-9);
560 }
561
562 #[test]
563 fn an_outlier_is_rejected_and_leaves_the_offset_alone() {
564 let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
565 for index in 0..4 {
566 fix_at(&mut correction, index, &truth(), Vector3::zeros());
567 }
568 assert_eq!(
569 fix_at(&mut correction, 4, &truth(), Vector3::new(0.0, 2.0, 0.0)),
570 FixOutcome::Rejected
571 );
572 assert_pose_close(&correction.map_from_odom().unwrap(), &truth(), 1e-9);
573 assert_eq!(
574 fix_at(&mut correction, 5, &truth(), Vector3::zeros()),
575 FixOutcome::Accepted
576 );
577 }
578
579 fn weak_fix_at(
580 correction: &mut OdomCorrection,
581 index: usize,
582 shift: Vector3<f64>,
583 ) -> FixOutcome {
584 let odom_from_body = odom(index);
585 let mut map_from_body = truth().compose(&odom_from_body);
586 map_from_body.translation += shift;
587 correction.add_weak_fix(index as i64 * SECOND / 10, &map_from_body, &odom_from_body)
588 }
589
590 #[test]
591 fn weak_fixes_need_three_agreeing_and_only_set_the_first_offset() {
592 let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
594 assert_eq!(
595 weak_fix_at(&mut correction, 0, Vector3::zeros()),
596 FixOutcome::Pending
597 );
598 assert_eq!(
599 weak_fix_at(&mut correction, 1, Vector3::zeros()),
600 FixOutcome::Pending
601 );
602 assert_eq!(
603 weak_fix_at(&mut correction, 2, Vector3::zeros()),
604 FixOutcome::Initialized
605 );
606 assert_pose_close(&correction.map_from_odom().unwrap(), &truth(), 1e-9);
607
608 let mut mixed = OdomCorrection::new(OdomCorrectionConfig::default());
610 assert_eq!(
611 weak_fix_at(&mut mixed, 0, Vector3::zeros()),
612 FixOutcome::Pending
613 );
614 assert_eq!(
615 fix_at(&mut mixed, 1, &truth(), Vector3::zeros()),
616 FixOutcome::Pending
617 );
618 assert_eq!(
619 fix_at(&mut mixed, 2, &truth(), Vector3::zeros()),
620 FixOutcome::Initialized
621 );
622 let mut strong = OdomCorrection::new(OdomCorrectionConfig::default());
624 assert_eq!(
625 fix_at(&mut strong, 0, &truth(), Vector3::zeros()),
626 FixOutcome::Pending
627 );
628 assert_eq!(
629 fix_at(&mut strong, 1, &truth(), Vector3::zeros()),
630 FixOutcome::Initialized
631 );
632
633 let mut broken = OdomCorrection::new(OdomCorrectionConfig::default());
636 let off = Vector3::new(1.5, 0.0, 0.0);
637 assert_eq!(
638 weak_fix_at(&mut broken, 0, Vector3::zeros()),
639 FixOutcome::Pending
640 );
641 assert_eq!(weak_fix_at(&mut broken, 1, off), FixOutcome::Pending);
642 assert_eq!(
643 weak_fix_at(&mut broken, 2, Vector3::zeros()),
644 FixOutcome::Pending
645 );
646 assert_eq!(
647 weak_fix_at(&mut broken, 3, Vector3::zeros()),
648 FixOutcome::Pending
649 );
650 assert_eq!(
651 weak_fix_at(&mut broken, 4, Vector3::zeros()),
652 FixOutcome::Initialized
653 );
654 assert_pose_close(&broken.map_from_odom().unwrap(), &truth(), 1e-9);
655
656 let before = correction.map_from_odom().unwrap();
658 assert_eq!(weak_fix_at(&mut correction, 3, off), FixOutcome::Unused);
659 assert_eq!(
660 weak_fix_at(&mut correction, 4, Vector3::zeros()),
661 FixOutcome::Unused
662 );
663 assert_pose_close(&correction.map_from_odom().unwrap(), &before, 1e-12);
664 assert_eq!(
665 fix_at(&mut correction, 5, &truth(), Vector3::zeros()),
666 FixOutcome::Accepted
667 );
668 }
669
670 #[test]
671 fn a_weak_gate_accepts_close_weak_fixes_after_the_first_offset() {
672 let mut correction = OdomCorrection::new(OdomCorrectionConfig {
673 weak_gate_m: 0.05,
674 ..OdomCorrectionConfig::default()
675 });
676 for index in 0..2 {
677 fix_at(&mut correction, index, &truth(), Vector3::zeros());
678 }
679 assert!(correction.is_set());
680 let close = Vector3::new(0.03, 0.0, 0.0);
682 assert_eq!(weak_fix_at(&mut correction, 2, close), FixOutcome::Accepted);
683 let moved = correction.map_from_odom().unwrap().translation - truth().translation;
684 assert!((moved - close / 3.0).norm() < 1e-9, "{moved:?}");
685 assert_eq!(
687 weak_fix_at(&mut correction, 3, Vector3::new(0.08, 0.0, 0.0)),
688 FixOutcome::Unused
689 );
690 }
691
692 #[test]
693 fn agreeing_rejected_fixes_reset_the_offset_after_an_odometry_jump() {
694 let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
695 for index in 0..4 {
696 fix_at(&mut correction, index, &truth(), Vector3::zeros());
697 }
698 let jumped = SE3::new(
700 UnitQuaternion::from_axis_angle(&Vector3::z_axis(), 0.75),
701 Vector3::new(2.0, -1.0, 0.5),
702 );
703 assert_eq!(
704 fix_at(&mut correction, 4, &jumped, Vector3::zeros()),
705 FixOutcome::Rejected
706 );
707 assert_eq!(
708 fix_at(&mut correction, 5, &jumped, Vector3::zeros()),
709 FixOutcome::Rejected
710 );
711 assert_eq!(
712 fix_at(&mut correction, 6, &jumped, Vector3::zeros()),
713 FixOutcome::Reset
714 );
715 assert_pose_close(&correction.map_from_odom().unwrap(), &jumped, 1e-9);
716 }
717
718 #[test]
719 fn the_gate_widens_with_travel_since_the_last_accepted_fix() {
720 let config = OdomCorrectionConfig::default();
721 let mut near = OdomCorrection::new(config.clone());
722 let mut far = OdomCorrection::new(config);
723 for index in 0..3 {
724 fix_at(&mut near, index, &truth(), Vector3::zeros());
725 fix_at(&mut far, index, &truth(), Vector3::zeros());
726 }
727 let drift = Vector3::new(0.0, 0.0, 0.3);
730 assert_eq!(fix_at(&mut near, 3, &truth(), drift), FixOutcome::Rejected);
731 assert_eq!(
732 fix_at(&mut far, 20, &truth(), Vector3::new(5.0, 0.0, 0.0)),
733 FixOutcome::Rejected
734 );
735 assert_eq!(fix_at(&mut far, 40, &truth(), drift), FixOutcome::Accepted);
736 }
737
738 #[test]
739 fn observed_odometry_measures_travel_along_the_path() {
740 let config = OdomCorrectionConfig::default();
741 let mut sampled = OdomCorrection::new(config.clone());
742 let mut observed = OdomCorrection::new(config);
743 for index in 0..=40 {
746 observed.observe_odometry(index as i64 * SECOND / 10, &odom(index));
747 }
748 for index in 0..3 {
749 fix_at(&mut sampled, index, &truth(), Vector3::zeros());
750 fix_at(&mut observed, index, &truth(), Vector3::zeros());
751 }
752 let drift = Vector3::new(0.0, 0.0, 0.3);
756 assert_eq!(
757 fix_at(&mut sampled, 31, &truth(), drift),
758 FixOutcome::Rejected
759 );
760 assert_eq!(
761 fix_at(&mut observed, 31, &truth(), drift),
762 FixOutcome::Accepted
763 );
764 assert_eq!(
766 fix_at(&mut observed, 32, &truth(), drift * 2.0),
767 FixOutcome::Rejected
768 );
769 }
770
771 #[test]
772 fn noisy_fixes_average_within_the_window() {
773 let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
774 for index in 0..20 {
776 let sign = if index % 2 == 0 { 1.0 } else { -1.0 };
777 fix_at(
778 &mut correction,
779 index,
780 &truth(),
781 Vector3::new(0.02 * sign, 0.0, 0.0),
782 );
783 }
784 let estimate = correction.map_from_odom().unwrap();
785 assert!((estimate.translation - truth().translation).norm() < 0.005);
786 assert_eq!(correction.window.len(), 20);
788 }
789
790 #[test]
791 fn old_fixes_leave_the_window() {
792 let mut correction = OdomCorrection::new(OdomCorrectionConfig {
793 window_s: 1.0,
794 ..OdomCorrectionConfig::default()
795 });
796 for index in 0..30 {
797 fix_at(&mut correction, index, &truth(), Vector3::zeros());
798 }
799 assert_eq!(correction.window.len(), 11);
801 }
802}