use std::collections::VecDeque;
const PATH_HISTORY_NS: i64 = 30_000_000_000;
use nalgebra::{UnitQuaternion, Vector3};
use visloc_core::geometry::SE3;
#[derive(Debug, Clone, PartialEq)]
pub struct OdomCorrectionConfig {
pub init_fixes: usize,
pub init_fixes_weak: usize,
pub reset_after: usize,
pub agreement_m: f64,
pub gate_m: f64,
pub gate_per_m: f64,
pub gate_yaw_deg: f64,
pub gate_yaw_per_m_deg: f64,
pub window_s: f64,
pub weak_gate_m: f64,
pub weak_gate_yaw_deg: f64,
}
impl Default for OdomCorrectionConfig {
fn default() -> Self {
Self {
init_fixes: 2,
init_fixes_weak: 3,
reset_after: 3,
agreement_m: 0.10,
gate_m: 0.15,
gate_per_m: 0.05,
gate_yaw_deg: 3.0,
gate_yaw_per_m_deg: 1.0,
window_s: 5.0,
weak_gate_m: 0.0,
weak_gate_yaw_deg: 2.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FixOutcome {
Pending,
Initialized,
Accepted,
Rejected,
Reset,
Unused,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Offset {
pub(crate) yaw: f64,
pub(crate) translation: Vector3<f64>,
}
impl Offset {
pub(crate) fn rotation(&self) -> UnitQuaternion<f64> {
UnitQuaternion::from_axis_angle(&Vector3::z_axis(), self.yaw)
}
pub(crate) fn se3(&self) -> SE3 {
SE3::new(self.rotation(), self.translation)
}
}
#[derive(Debug, Clone, PartialEq)]
struct Fix {
timestamp_ns: i64,
map_position: Vector3<f64>,
odom_position: Vector3<f64>,
yaw: f64,
weak: bool,
}
pub(crate) fn yaw_of(rotation: &UnitQuaternion<f64>) -> f64 {
let matrix = rotation.to_rotation_matrix();
matrix[(1, 0)].atan2(matrix[(0, 0)])
}
pub(crate) fn wrap_angle(angle: f64) -> f64 {
(angle + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI
}
fn fit(fixes: &[&Fix]) -> Offset {
let (sin, cos) = fixes.iter().fold((0.0, 0.0), |(sin, cos), fix| {
(sin + fix.yaw.sin(), cos + fix.yaw.cos())
});
let yaw = sin.atan2(cos);
let rotation = UnitQuaternion::from_axis_angle(&Vector3::z_axis(), yaw);
let translation = fixes
.iter()
.map(|fix| fix.map_position - rotation * fix.odom_position)
.sum::<Vector3<f64>>()
/ fixes.len() as f64;
Offset { yaw, translation }
}
fn residuals(offset: &Offset, fix: &Fix) -> (f64, f64) {
let predicted = offset.rotation() * fix.odom_position + offset.translation;
(
(predicted - fix.map_position).norm(),
wrap_angle(fix.yaw - offset.yaw).abs().to_degrees(),
)
}
#[derive(Debug, Clone)]
pub struct OdomCorrection {
config: OdomCorrectionConfig,
offset: Option<Offset>,
window: VecDeque<Fix>,
candidates: Vec<Fix>,
previous_odom_position: Option<Vector3<f64>>,
travel_since_accept_m: f64,
path: VecDeque<(i64, f64)>,
path_end: Option<Vector3<f64>>,
path_at_accept_m: Option<f64>,
}
impl OdomCorrection {
pub fn new(config: OdomCorrectionConfig) -> Self {
Self {
config,
offset: None,
window: VecDeque::new(),
candidates: Vec::new(),
previous_odom_position: None,
travel_since_accept_m: 0.0,
path: VecDeque::new(),
path_end: None,
path_at_accept_m: None,
}
}
pub const fn config(&self) -> &OdomCorrectionConfig {
&self.config
}
pub const fn is_set(&self) -> bool {
self.offset.is_some()
}
pub fn map_from_odom(&self) -> Option<SE3> {
self.offset.as_ref().map(Offset::se3)
}
pub fn last_fix(&self) -> Option<(i64, Vector3<f64>)> {
self.offset?;
self.window
.back()
.map(|fix| (fix.timestamp_ns, fix.odom_position))
}
pub fn map_from_body(&self, odom_from_body: &SE3) -> Option<SE3> {
self.map_from_odom()
.map(|map_from_odom| map_from_odom.compose(odom_from_body))
}
pub fn observe_odometry(&mut self, timestamp_ns: i64, odom_from_body: &SE3) {
if self
.path
.back()
.is_some_and(|(last_ns, _)| timestamp_ns <= *last_ns)
{
return;
}
let position = odom_from_body.translation;
let length = match (self.path.back(), self.path_end) {
(Some((_, length)), Some(end)) => length + (position - end).norm(),
_ => 0.0,
};
self.path.push_back((timestamp_ns, length));
self.path_end = Some(position);
while self
.path
.front()
.is_some_and(|(first_ns, _)| timestamp_ns - first_ns > PATH_HISTORY_NS)
{
self.path.pop_front();
}
}
fn path_length_at(&self, timestamp_ns: i64) -> Option<f64> {
let (first_ns, _) = self.path.front()?;
let (last_ns, _) = self.path.back()?;
if timestamp_ns < *first_ns || timestamp_ns > *last_ns {
return None;
}
let index = self
.path
.partition_point(|(stamp, _)| *stamp < timestamp_ns);
let (after_ns, after) = self.path[index];
if after_ns == timestamp_ns || index == 0 {
return Some(after);
}
let (before_ns, before) = self.path[index - 1];
let alpha = (timestamp_ns - before_ns) as f64 / (after_ns - before_ns) as f64;
Some(before + alpha * (after - before))
}
pub fn add_fix(
&mut self,
timestamp_ns: i64,
map_from_body: &SE3,
odom_from_body: &SE3,
) -> FixOutcome {
self.add(timestamp_ns, map_from_body, odom_from_body, false)
}
pub fn add_weak_fix(
&mut self,
timestamp_ns: i64,
map_from_body: &SE3,
odom_from_body: &SE3,
) -> FixOutcome {
self.add(timestamp_ns, map_from_body, odom_from_body, true)
}
fn add(
&mut self,
timestamp_ns: i64,
map_from_body: &SE3,
odom_from_body: &SE3,
weak: bool,
) -> FixOutcome {
let fix = Fix {
timestamp_ns,
map_position: map_from_body.translation,
odom_position: odom_from_body.translation,
yaw: yaw_of(&(map_from_body.rotation * odom_from_body.rotation.inverse())),
weak,
};
if let Some(previous) = self.previous_odom_position {
self.travel_since_accept_m += (fix.odom_position - previous).norm();
}
self.previous_odom_position = Some(fix.odom_position);
let path_m = self.path_length_at(timestamp_ns);
let Some(offset) = self.offset else {
return if self.push_initial(fix) {
Self::adopt(&mut self.window, &mut self.candidates);
self.refit();
self.restart_travel(path_m);
FixOutcome::Initialized
} else {
FixOutcome::Pending
};
};
let (position_residual, yaw_residual) = residuals(&offset, &fix);
if weak {
if self.config.weak_gate_m > 0.0
&& position_residual <= self.config.weak_gate_m
&& yaw_residual <= self.config.weak_gate_yaw_deg
{
self.candidates.clear();
self.window.push_back(fix);
self.refit();
self.restart_travel(path_m);
return FixOutcome::Accepted;
}
return FixOutcome::Unused;
}
let travel = match (path_m, self.path_at_accept_m) {
(Some(now), Some(then)) => self.travel_since_accept_m.max(now - then),
_ => self.travel_since_accept_m,
};
let accepted = position_residual <= self.config.gate_m + self.config.gate_per_m * travel
&& yaw_residual <= self.config.gate_yaw_deg + self.config.gate_yaw_per_m_deg * travel;
if accepted {
self.candidates.clear();
self.window.push_back(fix);
self.refit();
self.restart_travel(path_m);
return FixOutcome::Accepted;
}
if self.push_candidate(fix, self.config.reset_after) {
Self::adopt(&mut self.window, &mut self.candidates);
self.refit();
self.restart_travel(path_m);
FixOutcome::Reset
} else {
FixOutcome::Rejected
}
}
fn restart_travel(&mut self, path_m: Option<f64>) {
self.travel_since_accept_m = 0.0;
self.path_at_accept_m = path_m;
}
fn push_candidate(&mut self, fix: Fix, needed: usize) -> bool {
self.candidates.push(fix);
let needed = needed.max(1);
if self.candidates.len() > needed {
self.candidates.drain(..self.candidates.len() - needed);
}
self.candidates.len() == needed && self.agree(&self.candidates)
}
fn push_initial(&mut self, fix: Fix) -> bool {
let strong = self.config.init_fixes.max(1);
let weak = self.config.init_fixes_weak.max(strong);
self.candidates.push(fix);
if self.candidates.len() > weak {
self.candidates.drain(..self.candidates.len() - weak);
}
for needed in [strong, weak] {
let Some(start) = self.candidates.len().checked_sub(needed) else {
continue;
};
let newest = &self.candidates[start..];
let required = if newest.iter().any(|fix| fix.weak) {
weak
} else {
strong
};
if needed == required && self.agree(newest) {
self.candidates.drain(..start);
return true;
}
}
false
}
fn agree(&self, fixes: &[Fix]) -> bool {
let fixes = fixes.iter().collect::<Vec<_>>();
let offset = fit(&fixes);
fixes.iter().all(|fix| {
let (position, yaw) = residuals(&offset, fix);
position <= self.config.agreement_m && yaw <= self.config.gate_yaw_deg
})
}
fn adopt(window: &mut VecDeque<Fix>, candidates: &mut Vec<Fix>) {
window.clear();
window.extend(candidates.drain(..));
}
fn refit(&mut self) {
let Some(newest) = self.window.back().map(|fix| fix.timestamp_ns) else {
return;
};
let window_ns = (self.config.window_s * 1e9) as i64;
while self.window.len() > 1
&& self
.window
.front()
.is_some_and(|fix| newest - fix.timestamp_ns > window_ns)
{
self.window.pop_front();
}
let fixes = self.window.iter().collect::<Vec<_>>();
self.offset = Some(fit(&fixes));
}
}
#[cfg(test)]
mod tests {
use super::*;
const SECOND: i64 = 1_000_000_000;
fn truth() -> SE3 {
SE3::new(
UnitQuaternion::from_axis_angle(&Vector3::z_axis(), 0.6),
Vector3::new(3.0, -2.0, 0.5),
)
}
fn odom(index: usize) -> SE3 {
let t = index as f64 * 0.2;
SE3::new(
UnitQuaternion::from_euler_angles(0.05 * t.sin(), -0.03, 0.4 * t),
Vector3::new(t.cos() * 2.0, t.sin() * 2.0, 0.1 * t),
)
}
fn fix_at(
correction: &mut OdomCorrection,
index: usize,
map_from_odom: &SE3,
shift: Vector3<f64>,
) -> FixOutcome {
let odom_from_body = odom(index);
let mut map_from_body = map_from_odom.compose(&odom_from_body);
map_from_body.translation += shift;
correction.add_fix(index as i64 * SECOND / 10, &map_from_body, &odom_from_body)
}
fn assert_pose_close(lhs: &SE3, rhs: &SE3, tolerance: f64) {
assert!(
(lhs.translation - rhs.translation).norm() < tolerance,
"{lhs:?} vs {rhs:?}"
);
assert!(
lhs.rotation.angle_to(&rhs.rotation) < tolerance,
"{lhs:?} vs {rhs:?}"
);
}
#[test]
fn exact_fixes_recover_the_offset_after_initialization() {
let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
assert_eq!(correction.map_from_body(&odom(0)), None);
assert_eq!(
fix_at(&mut correction, 0, &truth(), Vector3::zeros()),
FixOutcome::Pending
);
assert_eq!(correction.last_fix(), None);
assert_eq!(
fix_at(&mut correction, 1, &truth(), Vector3::zeros()),
FixOutcome::Initialized
);
assert_eq!(
fix_at(&mut correction, 2, &truth(), Vector3::zeros()),
FixOutcome::Accepted
);
assert_eq!(
correction.last_fix(),
Some((2 * SECOND / 10, odom(2).translation))
);
for index in [3, 10, 40] {
let pose = correction.map_from_body(&odom(index)).expect("set");
assert_pose_close(&pose, &truth().compose(&odom(index)), 1e-9);
}
}
#[test]
fn a_wrong_first_fix_does_not_place_the_trajectory() {
let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
let off = Vector3::new(1.5, 0.0, 0.0);
assert_eq!(
fix_at(&mut correction, 0, &truth(), off),
FixOutcome::Pending
);
assert_eq!(
fix_at(&mut correction, 1, &truth(), Vector3::zeros()),
FixOutcome::Pending
);
assert_eq!(
fix_at(&mut correction, 2, &truth(), Vector3::zeros()),
FixOutcome::Initialized
);
assert_pose_close(&correction.map_from_odom().unwrap(), &truth(), 1e-9);
}
#[test]
fn an_outlier_is_rejected_and_leaves_the_offset_alone() {
let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
for index in 0..4 {
fix_at(&mut correction, index, &truth(), Vector3::zeros());
}
assert_eq!(
fix_at(&mut correction, 4, &truth(), Vector3::new(0.0, 2.0, 0.0)),
FixOutcome::Rejected
);
assert_pose_close(&correction.map_from_odom().unwrap(), &truth(), 1e-9);
assert_eq!(
fix_at(&mut correction, 5, &truth(), Vector3::zeros()),
FixOutcome::Accepted
);
}
fn weak_fix_at(
correction: &mut OdomCorrection,
index: usize,
shift: Vector3<f64>,
) -> FixOutcome {
let odom_from_body = odom(index);
let mut map_from_body = truth().compose(&odom_from_body);
map_from_body.translation += shift;
correction.add_weak_fix(index as i64 * SECOND / 10, &map_from_body, &odom_from_body)
}
#[test]
fn weak_fixes_need_three_agreeing_and_only_set_the_first_offset() {
let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
assert_eq!(
weak_fix_at(&mut correction, 0, Vector3::zeros()),
FixOutcome::Pending
);
assert_eq!(
weak_fix_at(&mut correction, 1, Vector3::zeros()),
FixOutcome::Pending
);
assert_eq!(
weak_fix_at(&mut correction, 2, Vector3::zeros()),
FixOutcome::Initialized
);
assert_pose_close(&correction.map_from_odom().unwrap(), &truth(), 1e-9);
let mut mixed = OdomCorrection::new(OdomCorrectionConfig::default());
assert_eq!(
weak_fix_at(&mut mixed, 0, Vector3::zeros()),
FixOutcome::Pending
);
assert_eq!(
fix_at(&mut mixed, 1, &truth(), Vector3::zeros()),
FixOutcome::Pending
);
assert_eq!(
fix_at(&mut mixed, 2, &truth(), Vector3::zeros()),
FixOutcome::Initialized
);
let mut strong = OdomCorrection::new(OdomCorrectionConfig::default());
assert_eq!(
fix_at(&mut strong, 0, &truth(), Vector3::zeros()),
FixOutcome::Pending
);
assert_eq!(
fix_at(&mut strong, 1, &truth(), Vector3::zeros()),
FixOutcome::Initialized
);
let mut broken = OdomCorrection::new(OdomCorrectionConfig::default());
let off = Vector3::new(1.5, 0.0, 0.0);
assert_eq!(
weak_fix_at(&mut broken, 0, Vector3::zeros()),
FixOutcome::Pending
);
assert_eq!(weak_fix_at(&mut broken, 1, off), FixOutcome::Pending);
assert_eq!(
weak_fix_at(&mut broken, 2, Vector3::zeros()),
FixOutcome::Pending
);
assert_eq!(
weak_fix_at(&mut broken, 3, Vector3::zeros()),
FixOutcome::Pending
);
assert_eq!(
weak_fix_at(&mut broken, 4, Vector3::zeros()),
FixOutcome::Initialized
);
assert_pose_close(&broken.map_from_odom().unwrap(), &truth(), 1e-9);
let before = correction.map_from_odom().unwrap();
assert_eq!(weak_fix_at(&mut correction, 3, off), FixOutcome::Unused);
assert_eq!(
weak_fix_at(&mut correction, 4, Vector3::zeros()),
FixOutcome::Unused
);
assert_pose_close(&correction.map_from_odom().unwrap(), &before, 1e-12);
assert_eq!(
fix_at(&mut correction, 5, &truth(), Vector3::zeros()),
FixOutcome::Accepted
);
}
#[test]
fn a_weak_gate_accepts_close_weak_fixes_after_the_first_offset() {
let mut correction = OdomCorrection::new(OdomCorrectionConfig {
weak_gate_m: 0.05,
..OdomCorrectionConfig::default()
});
for index in 0..2 {
fix_at(&mut correction, index, &truth(), Vector3::zeros());
}
assert!(correction.is_set());
let close = Vector3::new(0.03, 0.0, 0.0);
assert_eq!(weak_fix_at(&mut correction, 2, close), FixOutcome::Accepted);
let moved = correction.map_from_odom().unwrap().translation - truth().translation;
assert!((moved - close / 3.0).norm() < 1e-9, "{moved:?}");
assert_eq!(
weak_fix_at(&mut correction, 3, Vector3::new(0.08, 0.0, 0.0)),
FixOutcome::Unused
);
}
#[test]
fn agreeing_rejected_fixes_reset_the_offset_after_an_odometry_jump() {
let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
for index in 0..4 {
fix_at(&mut correction, index, &truth(), Vector3::zeros());
}
let jumped = SE3::new(
UnitQuaternion::from_axis_angle(&Vector3::z_axis(), 0.75),
Vector3::new(2.0, -1.0, 0.5),
);
assert_eq!(
fix_at(&mut correction, 4, &jumped, Vector3::zeros()),
FixOutcome::Rejected
);
assert_eq!(
fix_at(&mut correction, 5, &jumped, Vector3::zeros()),
FixOutcome::Rejected
);
assert_eq!(
fix_at(&mut correction, 6, &jumped, Vector3::zeros()),
FixOutcome::Reset
);
assert_pose_close(&correction.map_from_odom().unwrap(), &jumped, 1e-9);
}
#[test]
fn the_gate_widens_with_travel_since_the_last_accepted_fix() {
let config = OdomCorrectionConfig::default();
let mut near = OdomCorrection::new(config.clone());
let mut far = OdomCorrection::new(config);
for index in 0..3 {
fix_at(&mut near, index, &truth(), Vector3::zeros());
fix_at(&mut far, index, &truth(), Vector3::zeros());
}
let drift = Vector3::new(0.0, 0.0, 0.3);
assert_eq!(fix_at(&mut near, 3, &truth(), drift), FixOutcome::Rejected);
assert_eq!(
fix_at(&mut far, 20, &truth(), Vector3::new(5.0, 0.0, 0.0)),
FixOutcome::Rejected
);
assert_eq!(fix_at(&mut far, 40, &truth(), drift), FixOutcome::Accepted);
}
#[test]
fn observed_odometry_measures_travel_along_the_path() {
let config = OdomCorrectionConfig::default();
let mut sampled = OdomCorrection::new(config.clone());
let mut observed = OdomCorrection::new(config);
for index in 0..=40 {
observed.observe_odometry(index as i64 * SECOND / 10, &odom(index));
}
for index in 0..3 {
fix_at(&mut sampled, index, &truth(), Vector3::zeros());
fix_at(&mut observed, index, &truth(), Vector3::zeros());
}
let drift = Vector3::new(0.0, 0.0, 0.3);
assert_eq!(
fix_at(&mut sampled, 31, &truth(), drift),
FixOutcome::Rejected
);
assert_eq!(
fix_at(&mut observed, 31, &truth(), drift),
FixOutcome::Accepted
);
assert_eq!(
fix_at(&mut observed, 32, &truth(), drift * 2.0),
FixOutcome::Rejected
);
}
#[test]
fn noisy_fixes_average_within_the_window() {
let mut correction = OdomCorrection::new(OdomCorrectionConfig::default());
for index in 0..20 {
let sign = if index % 2 == 0 { 1.0 } else { -1.0 };
fix_at(
&mut correction,
index,
&truth(),
Vector3::new(0.02 * sign, 0.0, 0.0),
);
}
let estimate = correction.map_from_odom().unwrap();
assert!((estimate.translation - truth().translation).norm() < 0.005);
assert_eq!(correction.window.len(), 20);
}
#[test]
fn old_fixes_leave_the_window() {
let mut correction = OdomCorrection::new(OdomCorrectionConfig {
window_s: 1.0,
..OdomCorrectionConfig::default()
});
for index in 0..30 {
fix_at(&mut correction, index, &truth(), Vector3::zeros());
}
assert_eq!(correction.window.len(), 11);
}
}