1use std::collections::VecDeque;
14
15use nalgebra::{UnitQuaternion, Vector3};
16use visloc_core::geometry::SE3;
17
18#[derive(Debug, Clone, PartialEq)]
19pub struct GyroWheelConfig {
20 pub still_m: f64,
23 pub still_deg: f64,
25 pub settle_s: f64,
28 pub average_samples: usize,
31 pub max_gyro_gap_s: f64,
34}
35
36impl Default for GyroWheelConfig {
37 fn default() -> Self {
38 Self {
39 still_m: 0.0005,
40 still_deg: 0.01,
41 settle_s: 0.5,
42 average_samples: 4_000,
43 max_gyro_gap_s: 0.1,
44 }
45 }
46}
47
48#[derive(Debug, Clone, Copy)]
50struct RunningMean<T> {
51 mean: T,
52 count: usize,
53}
54
55impl<T> RunningMean<T>
56where
57 T: Copy
58 + std::ops::Add<Output = T>
59 + std::ops::Sub<Output = T>
60 + std::ops::Mul<f64, Output = T>,
61{
62 fn add(&mut self, value: T, cap: usize) {
63 self.count = (self.count + 1).min(cap.max(1));
64 self.mean = self.mean + (value - self.mean) * (1.0 / self.count as f64);
65 }
66}
67
68#[derive(Debug, Clone, Copy)]
69struct GyroSample {
70 timestamp_ns: i64,
71 heading: f64,
73 rate: f64,
75 acceleration: Vector3<f64>,
76}
77
78#[derive(Debug, Clone)]
81pub struct GyroWheelOdometry {
82 config: GyroWheelConfig,
83 gyro: VecDeque<GyroSample>,
85 up_still: RunningMean<Vector3<f64>>,
88 up_any: RunningMean<Vector3<f64>>,
89 bias: RunningMean<f64>,
90 last: Option<(i64, SE3, Option<f64>, Option<i64>)>,
93 position: Vector3<f64>,
95 heading: f64,
96}
97
98impl GyroWheelOdometry {
99 pub fn new(config: GyroWheelConfig) -> Self {
100 Self {
101 config,
102 gyro: VecDeque::new(),
103 up_still: RunningMean {
104 mean: Vector3::zeros(),
105 count: 0,
106 },
107 up_any: RunningMean {
108 mean: Vector3::zeros(),
109 count: 0,
110 },
111 bias: RunningMean {
112 mean: 0.0,
113 count: 0,
114 },
115 last: None,
116 position: Vector3::zeros(),
117 heading: 0.0,
118 }
119 }
120
121 pub fn bias(&self) -> Option<f64> {
123 (self.bias.count > 0).then_some(self.bias.mean)
124 }
125
126 pub fn up(&self) -> Option<Vector3<f64>> {
128 let mean = if self.up_still.count > 0 {
129 self.up_still.mean
130 } else {
131 self.up_any.mean
132 };
133 mean.try_normalize(1e-9)
134 }
135
136 pub fn add_imu(
139 &mut self,
140 timestamp_ns: i64,
141 angular_velocity: &Vector3<f64>,
142 linear_acceleration: &Vector3<f64>,
143 ) {
144 if self
145 .gyro
146 .back()
147 .is_some_and(|last| timestamp_ns <= last.timestamp_ns)
148 {
149 return;
150 }
151 if self.up_still.count == 0 {
152 self.up_any
153 .add(*linear_acceleration, self.config.average_samples);
154 }
155 let Some(up) = self.up() else {
156 return;
157 };
158 let rate = angular_velocity.dot(&up);
159 let heading = match self.gyro.back() {
160 Some(last) => {
161 let dt = (timestamp_ns - last.timestamp_ns) as f64 * 1e-9;
162 if dt > self.config.max_gyro_gap_s {
163 last.heading
164 } else {
165 last.heading + (0.5 * (last.rate + rate) - self.bias.mean) * dt
166 }
167 }
168 None => 0.0,
169 };
170 self.gyro.push_back(GyroSample {
171 timestamp_ns,
172 heading,
173 rate,
174 acceleration: *linear_acceleration,
175 });
176 self.prune();
177 }
178
179 fn prune(&mut self) {
182 let Some((keep_from, ..)) = self.last.as_ref() else {
183 return;
184 };
185 while self.gyro.len() > 2 && self.gyro[1].timestamp_ns <= *keep_from {
186 self.gyro.pop_front();
187 }
188 }
189
190 fn heading_at(&self, timestamp_ns: i64) -> Option<f64> {
193 let max_gap_ns = (self.config.max_gyro_gap_s * 1e9) as i64;
194 let index = self
195 .gyro
196 .partition_point(|sample| sample.timestamp_ns < timestamp_ns);
197 match (
198 index.checked_sub(1).map(|i| self.gyro[i]),
199 self.gyro.get(index),
200 ) {
201 (_, Some(after)) if after.timestamp_ns == timestamp_ns => Some(after.heading),
202 (Some(before), Some(after))
203 if after.timestamp_ns - before.timestamp_ns <= max_gap_ns =>
204 {
205 let alpha = (timestamp_ns - before.timestamp_ns) as f64
206 / (after.timestamp_ns - before.timestamp_ns) as f64;
207 Some(before.heading + alpha * (after.heading - before.heading))
208 }
209 (Some(before), None) if timestamp_ns - before.timestamp_ns <= max_gap_ns => Some(
210 before.heading
211 + (before.rate - self.bias.mean)
212 * (timestamp_ns - before.timestamp_ns) as f64
213 * 1e-9,
214 ),
215 _ => None,
216 }
217 }
218
219 pub fn wheel(&mut self, timestamp_ns: i64, odom_from_wheel: &SE3) -> SE3 {
223 let yaw = yaw_of(&odom_from_wheel.rotation);
224 let gyro_heading = self.heading_at(timestamp_ns);
225 match self.last.take() {
226 None => {
227 self.position = odom_from_wheel.translation;
228 self.heading = yaw;
229 self.last = Some((timestamp_ns, odom_from_wheel.clone(), gyro_heading, None));
230 }
231 Some((last_ns, last_pose, last_gyro, still_since)) => {
232 if timestamp_ns <= last_ns {
233 self.last = Some((last_ns, last_pose, last_gyro, still_since));
234 return self.pose();
235 }
236 let step = last_pose.rotation.inverse()
237 * (odom_from_wheel.translation - last_pose.translation);
238 let turn = wrap_angle(yaw - yaw_of(&last_pose.rotation));
239 let still = step.norm() < self.config.still_m
240 && turn.abs() < self.config.still_deg.to_radians();
241 let max_gap_ns = (self.config.max_gyro_gap_s * 1e9) as i64;
244 let gapless = self
245 .gyro
246 .iter()
247 .zip(self.gyro.iter().skip(1))
248 .all(|(a, b)| b.timestamp_ns - a.timestamp_ns <= max_gap_ns);
249 let delta = if still {
250 0.0
251 } else {
252 match (last_gyro, gyro_heading) {
253 (Some(from), Some(to)) if gapless => to - from,
254 _ => turn,
255 }
256 };
257 self.position +=
258 UnitQuaternion::from_axis_angle(&Vector3::z_axis(), self.heading) * step;
259 self.heading = wrap_angle(self.heading + delta);
260 let still_since = if still {
261 Some(still_since.unwrap_or(last_ns))
262 } else {
263 None
264 };
265 if still_since
269 .is_some_and(|since| last_ns - since >= (self.config.settle_s * 1e9) as i64)
270 {
271 let cap = self.config.average_samples;
272 for sample in self.gyro.iter().filter(|sample| {
273 sample.timestamp_ns > last_ns && sample.timestamp_ns <= timestamp_ns
274 }) {
275 self.bias.add(sample.rate, cap);
276 self.up_still.add(sample.acceleration, cap);
277 }
278 }
279 self.last = Some((
280 timestamp_ns,
281 odom_from_wheel.clone(),
282 gyro_heading,
283 still_since,
284 ));
285 }
286 }
287 self.prune();
288 self.pose()
289 }
290
291 fn pose(&self) -> SE3 {
292 SE3::new(
293 UnitQuaternion::from_axis_angle(&Vector3::z_axis(), self.heading),
294 self.position,
295 )
296 }
297}
298
299fn yaw_of(rotation: &UnitQuaternion<f64>) -> f64 {
300 let matrix = rotation.to_rotation_matrix();
301 matrix[(1, 0)].atan2(matrix[(0, 0)])
302}
303
304fn wrap_angle(angle: f64) -> f64 {
305 (angle + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI
306}
307
308#[cfg(test)]
309mod tests {
310 use super::*;
311
312 const MS: i64 = 1_000_000;
313
314 type Sample = (i64, SE3, SE3, Vector3<f64>, Vector3<f64>);
316
317 fn run(bias: f64) -> Vec<Sample> {
321 let mount = UnitQuaternion::from_euler_angles(1.4, -0.3, 2.0);
322 let (mut truth, mut wheels) = ((0.0, 0.0, 0.3), (0.0, 0.0, 0.3));
323 let mut samples = Vec::new();
324 let mut index = 0;
325 for (seconds, speed, turn) in [
328 (1.0, 0.0, 0.0),
329 (4.0, 0.5, 0.0),
330 (3.0, 0.0, std::f64::consts::PI / 3.0),
331 (4.0, 0.5, 0.0),
332 (3.0, 0.4, std::f64::consts::FRAC_PI_6),
333 (1.5, 0.0, 0.0),
334 (2.0, 0.5, 0.0),
335 ] {
336 for _ in 0..(seconds * 200.0) as usize {
337 let dt = 0.005;
338 for (pose, gain) in [(&mut truth, 1.0), (&mut wheels, 1.05)] {
339 pose.0 += speed * f64::cos(pose.2) * dt;
340 pose.1 += speed * f64::sin(pose.2) * dt;
341 pose.2 += turn * gain * dt;
342 }
343 let at = |(x, y, yaw): (f64, f64, f64)| {
344 SE3::new(
345 UnitQuaternion::from_axis_angle(&Vector3::z_axis(), yaw),
346 Vector3::new(x, y, 0.0),
347 )
348 };
349 let gyro = mount.inverse() * Vector3::new(0.0, 0.0, turn + bias);
350 let accel = mount.inverse() * Vector3::new(0.0, 0.0, 9.81);
351 index += 1;
352 samples.push((index * 5 * MS, at(truth), at(wheels), gyro, accel));
353 }
354 }
355 samples
356 }
357
358 fn fuse(bias: f64, imu: bool) -> (SE3, SE3, SE3, GyroWheelOdometry) {
361 let mut odometry = GyroWheelOdometry::new(GyroWheelConfig::default());
362 let mut last = None;
363 for (index, (t, truth, wheels, gyro, accel)) in run(bias).into_iter().enumerate() {
364 if imu {
365 odometry.add_imu(t, &gyro, &accel);
366 }
367 if index % 10 == 0 {
368 let fused = odometry.wheel(t, &wheels);
369 last = Some((truth, wheels, fused));
370 }
371 }
372 let (truth, wheels, fused) = last.expect("wheel poses");
373 (truth, wheels, fused, odometry)
374 }
375
376 fn heading_error_deg(a: &SE3, b: &SE3) -> f64 {
377 wrap_angle(yaw_of(&a.rotation) - yaw_of(&b.rotation)).to_degrees()
378 }
379
380 #[test]
381 fn the_gyro_keeps_the_heading_the_wheels_lose_in_turns() {
382 let bias = 0.004; let (truth, wheels, fused, odometry) = fuse(bias, true);
384 assert!(heading_error_deg(&truth, &wheels).abs() > 13.0);
386 assert!((truth.translation - wheels.translation).norm() > 0.5);
387 assert!((odometry.bias().expect("bias") - bias).abs() < 1e-9);
391 let mount = UnitQuaternion::from_euler_angles(1.4, -0.3, 2.0);
392 assert!((mount * odometry.up().expect("up") - Vector3::z()).norm() < 1e-9);
393 assert!(heading_error_deg(&truth, &fused).abs() < 0.01, "{fused:?}");
395 assert!(
396 (truth.translation - fused.translation).norm() < 0.002,
397 "{fused:?}"
398 );
399 }
400
401 #[test]
402 fn without_a_gyro_the_wheels_pass_through() {
403 let (_, wheels, fused, odometry) = fuse(0.0, false);
404 assert_eq!(odometry.bias(), None);
405 assert!(heading_error_deg(&wheels, &fused).abs() < 1e-9);
406 assert!((wheels.translation - fused.translation).norm() < 1e-9);
407 }
408
409 #[test]
410 fn across_a_gyro_gap_the_wheels_turn() {
411 let mut odometry = GyroWheelOdometry::new(GyroWheelConfig::default());
412 let up = Vector3::new(0.0, 0.0, 9.81);
413 let turn = |yaw: f64| {
414 SE3::new(
415 UnitQuaternion::from_axis_angle(&Vector3::z_axis(), yaw),
416 Vector3::zeros(),
417 )
418 };
419 odometry.add_imu(0, &Vector3::new(0.0, 0.0, 1.0), &up);
420 odometry.wheel(0, &turn(0.0));
421 odometry.add_imu(500 * MS, &Vector3::new(0.0, 0.0, 1.0), &up);
423 let fused = odometry.wheel(500 * MS, &turn(0.5));
424 assert!((yaw_of(&fused.rotation) - 0.5).abs() < 1e-9);
425 }
426}