1use nalgebra::{UnitQuaternion, Vector3};
45
46#[derive(Debug, Clone, PartialEq)]
50pub struct VisualInertialInitializerConfig {
51 pub gravity_world: Vector3<f64>,
54 pub min_stationary_window_seconds: f64,
59 pub max_gyro_std: f64,
63 pub max_mean_gyro_magnitude: f64,
68 pub max_accel_std: f64,
71 pub max_accel_magnitude_error: f64,
76 pub min_samples: usize,
79 pub detector_window_seconds: f64,
94}
95
96impl Default for VisualInertialInitializerConfig {
97 fn default() -> Self {
98 Self {
99 gravity_world: Vector3::new(0.0, 0.0, -9.81),
100 min_stationary_window_seconds: 0.5,
101 max_gyro_std: 0.05,
102 max_mean_gyro_magnitude: 0.05,
103 max_accel_std: 0.5,
104 max_accel_magnitude_error: 0.5,
105 min_samples: 50,
106 detector_window_seconds: f64::INFINITY,
110 }
111 }
112}
113
114#[derive(Debug, Clone, PartialEq)]
115struct ImuSampleRecord {
116 gyro: Vector3<f64>,
117 accel: Vector3<f64>,
118 dt: f64,
119}
120
121#[derive(Debug, Clone, PartialEq)]
125pub struct VisualInertialInitializer {
126 config: VisualInertialInitializerConfig,
127 samples: Vec<ImuSampleRecord>,
128}
129
130#[derive(Debug, Clone, PartialEq)]
133pub struct VisualInertialInitializationResult {
134 pub gravity_world: Vector3<f64>,
138 pub initial_rotation_body_to_world: UnitQuaternion<f64>,
141 pub initial_velocity_world: Vector3<f64>,
144 pub bias_gyro: Vector3<f64>,
146 pub bias_acc: Vector3<f64>,
151 pub samples_consumed: usize,
153 pub duration_seconds: f64,
155 pub gyro_std: Vector3<f64>,
158 pub accel_std: Vector3<f64>,
161 pub mean_accel_magnitude: f64,
163}
164
165impl VisualInertialInitializationResult {
166 pub fn gravity_alignment_residual_deg(
182 &self,
183 ground_truth_rotation_body_to_world: &UnitQuaternion<f64>,
184 ) -> f64 {
185 let g_norm = self.gravity_world.norm();
186 if !g_norm.is_finite() || g_norm <= f64::EPSILON {
187 return 0.0;
188 }
189 let world_up = -self.gravity_world / g_norm;
190 let recovered_body_up = self.initial_rotation_body_to_world.inverse() * world_up;
191 let gt_body_up = ground_truth_rotation_body_to_world.inverse() * world_up;
192 recovered_body_up
193 .dot(>_body_up)
194 .clamp(-1.0, 1.0)
195 .acos()
196 .to_degrees()
197 }
198}
199
200#[derive(Debug, Clone, PartialEq)]
202pub enum StationaryRejectionReason {
203 InsufficientSamples {
204 have: usize,
205 need: usize,
206 },
207 InsufficientDuration {
208 have: f64,
209 need: f64,
210 },
211 GyroNoiseTooHigh {
212 observed: Vector3<f64>,
213 limit: f64,
214 },
215 MeanGyroMagnitudeTooHigh {
216 observed: f64,
217 limit: f64,
218 },
219 AccelNoiseTooHigh {
220 observed: Vector3<f64>,
221 limit: f64,
222 },
223 AccelMagnitudeMismatch {
224 observed: f64,
225 expected: f64,
226 tolerance: f64,
227 },
228}
229
230impl VisualInertialInitializer {
231 pub const fn new(config: VisualInertialInitializerConfig) -> Self {
236 Self {
237 config,
238 samples: Vec::new(),
239 }
240 }
241
242 pub fn push_sample(&mut self, gyro: Vector3<f64>, accel: Vector3<f64>, dt: f64) {
247 if dt <= 0.0 || !dt.is_finite() {
248 return;
249 }
250 self.samples.push(ImuSampleRecord { gyro, accel, dt });
251 }
252
253 pub fn samples_seen(&self) -> usize {
255 self.samples.len()
256 }
257
258 pub fn buffered_duration_seconds(&self) -> f64 {
260 self.samples.iter().map(|s| s.dt).sum()
261 }
262
263 pub fn reset(&mut self) {
265 self.samples.clear();
266 }
267
268 pub const fn config(&self) -> &VisualInertialInitializerConfig {
270 &self.config
271 }
272
273 pub fn try_initialize(
284 &self,
285 ) -> Result<VisualInertialInitializationResult, StationaryRejectionReason> {
286 let (slice, slice_duration) = self.detector_window_slice();
287 if slice.len() < self.config.min_samples {
288 return Err(StationaryRejectionReason::InsufficientSamples {
289 have: slice.len(),
290 need: self.config.min_samples,
291 });
292 }
293 if slice_duration < self.config.min_stationary_window_seconds {
294 return Err(StationaryRejectionReason::InsufficientDuration {
295 have: slice_duration,
296 need: self.config.min_stationary_window_seconds,
297 });
298 }
299
300 let total_dt = slice_duration;
308 let gyro_mean = slice
309 .iter()
310 .fold(Vector3::<f64>::zeros(), |acc, s| acc + s.gyro * s.dt)
311 / total_dt;
312 let accel_mean = slice
313 .iter()
314 .fold(Vector3::<f64>::zeros(), |acc, s| acc + s.accel * s.dt)
315 / total_dt;
316 let mut gyro_var = Vector3::<f64>::zeros();
317 let mut accel_var = Vector3::<f64>::zeros();
318 for sample in slice {
319 let dg = sample.gyro - gyro_mean;
320 let da = sample.accel - accel_mean;
321 gyro_var += Vector3::new(dg.x * dg.x, dg.y * dg.y, dg.z * dg.z) * sample.dt;
322 accel_var += Vector3::new(da.x * da.x, da.y * da.y, da.z * da.z) * sample.dt;
323 }
324 gyro_var /= total_dt;
325 accel_var /= total_dt;
326 let gyro_std = Vector3::new(gyro_var.x.sqrt(), gyro_var.y.sqrt(), gyro_var.z.sqrt());
327 let accel_std = Vector3::new(accel_var.x.sqrt(), accel_var.y.sqrt(), accel_var.z.sqrt());
328
329 if gyro_std
330 .iter()
331 .any(|s| !s.is_finite() || *s > self.config.max_gyro_std)
332 {
333 return Err(StationaryRejectionReason::GyroNoiseTooHigh {
334 observed: gyro_std,
335 limit: self.config.max_gyro_std,
336 });
337 }
338 let mean_gyro_magnitude = gyro_mean.norm();
339 if !mean_gyro_magnitude.is_finite()
340 || mean_gyro_magnitude > self.config.max_mean_gyro_magnitude
341 {
342 return Err(StationaryRejectionReason::MeanGyroMagnitudeTooHigh {
343 observed: mean_gyro_magnitude,
344 limit: self.config.max_mean_gyro_magnitude,
345 });
346 }
347 if accel_std
348 .iter()
349 .any(|s| !s.is_finite() || *s > self.config.max_accel_std)
350 {
351 return Err(StationaryRejectionReason::AccelNoiseTooHigh {
352 observed: accel_std,
353 limit: self.config.max_accel_std,
354 });
355 }
356
357 let gravity_magnitude = self.config.gravity_world.norm();
358 let mean_accel_magnitude = accel_mean.norm();
359 if (mean_accel_magnitude - gravity_magnitude).abs() > self.config.max_accel_magnitude_error
360 {
361 return Err(StationaryRejectionReason::AccelMagnitudeMismatch {
362 observed: mean_accel_magnitude,
363 expected: gravity_magnitude,
364 tolerance: self.config.max_accel_magnitude_error,
365 });
366 }
367 if mean_accel_magnitude <= f64::EPSILON {
368 return Err(StationaryRejectionReason::AccelMagnitudeMismatch {
369 observed: mean_accel_magnitude,
370 expected: gravity_magnitude,
371 tolerance: self.config.max_accel_magnitude_error,
372 });
373 }
374
375 let world_up = -self.config.gravity_world;
382 let rotation = UnitQuaternion::rotation_between(&accel_mean, &world_up)
383 .unwrap_or_else(UnitQuaternion::identity);
384
385 let inverse_rotation = rotation.inverse();
390 let bias_acc = accel_mean - inverse_rotation * world_up;
391
392 Ok(VisualInertialInitializationResult {
393 gravity_world: self.config.gravity_world,
394 initial_rotation_body_to_world: rotation,
395 initial_velocity_world: Vector3::zeros(),
396 bias_gyro: gyro_mean,
397 bias_acc,
398 samples_consumed: slice.len(),
399 duration_seconds: slice_duration,
400 gyro_std,
401 accel_std,
402 mean_accel_magnitude,
403 })
404 }
405
406 fn detector_window_slice(&self) -> (&[ImuSampleRecord], f64) {
414 let window = self.config.detector_window_seconds;
415 if !window.is_finite() || window <= 0.0 {
416 let dur: f64 = self.samples.iter().map(|s| s.dt).sum();
417 return (&self.samples[..], dur);
418 }
419 let mut acc_dt = 0.0;
420 let mut start_idx = self.samples.len();
421 for i in (0..self.samples.len()).rev() {
422 acc_dt += self.samples[i].dt;
423 start_idx = i;
424 if acc_dt >= window {
425 break;
426 }
427 }
428 (&self.samples[start_idx..], acc_dt)
429 }
430}
431
432#[cfg(test)]
433mod tests {
434 use super::*;
435 use nalgebra::Rotation3;
436
437 fn euroc_config() -> VisualInertialInitializerConfig {
438 VisualInertialInitializerConfig::default()
439 }
440
441 #[test]
442 fn default_config_uses_z_up_gravity() {
443 let config = VisualInertialInitializerConfig::default();
444 assert!((config.gravity_world - Vector3::new(0.0, 0.0, -9.81)).norm() < 1.0e-12);
445 }
446
447 #[test]
448 fn stationary_level_window_recovers_zero_rotation_and_zero_biases() {
449 let mut initializer = VisualInertialInitializer::new(euroc_config());
450 let dt = 0.005; let target_accel = -Vector3::new(0.0, 0.0, -9.81); for _ in 0..200 {
453 initializer.push_sample(Vector3::zeros(), target_accel, dt);
454 }
455 let result = initializer
456 .try_initialize()
457 .expect("stationary window should recover bootstrap");
458 assert_eq!(result.samples_consumed, 200);
459 assert!((result.duration_seconds - 1.0).abs() < 1.0e-9);
460 assert!(result.initial_velocity_world.norm() < 1.0e-12);
461 assert!(result.bias_gyro.norm() < 1.0e-12);
462 assert!(result.bias_acc.norm() < 1.0e-9);
463 assert!(result.initial_rotation_body_to_world.angle().abs() < 1.0e-9);
464 assert!(result.gyro_std.norm() < 1.0e-12);
465 assert!(result.accel_std.norm() < 1.0e-12);
466 assert!((result.mean_accel_magnitude - 9.81).abs() < 1.0e-9);
467 }
468
469 #[test]
470 fn tilted_stationary_window_recovers_rotation() {
471 let mut initializer = VisualInertialInitializer::new(euroc_config());
472 let dt = 0.005;
473 #[allow(clippy::approx_constant)]
482 let rotation_w_b = Rotation3::from_axis_angle(&Vector3::x_axis(), 0.5236);
483 let world_up = Vector3::new(0.0, 0.0, 9.81);
484 let accel_body = rotation_w_b.inverse() * world_up;
485 for _ in 0..200 {
486 initializer.push_sample(Vector3::zeros(), accel_body, dt);
487 }
488 let result = initializer
489 .try_initialize()
490 .expect("tilted stationary should still recover bootstrap");
491 let lifted = result.initial_rotation_body_to_world * accel_body;
494 assert!((lifted - world_up).norm() < 1.0e-9);
495 assert!(result.bias_acc.norm() < 1.0e-9);
496 let recovered = Rotation3::from(result.initial_rotation_body_to_world);
500 let delta = rotation_w_b * recovered.inverse();
501 assert!(delta.angle().abs() < 1.0e-9);
502 }
503
504 #[test]
505 fn nonzero_gyro_mean_becomes_bias() {
506 let mut initializer = VisualInertialInitializer::new(euroc_config());
507 let dt = 0.005;
508 let gyro_bias = Vector3::new(0.01, -0.02, 0.005);
509 let accel_body = Vector3::new(0.0, 0.0, 9.81);
510 for _ in 0..200 {
511 initializer.push_sample(gyro_bias, accel_body, dt);
512 }
513 let result = initializer.try_initialize().expect("ok");
514 assert!((result.bias_gyro - gyro_bias).norm() < 1.0e-12);
515 }
516
517 #[test]
518 fn rejects_low_variance_constant_rotation_as_non_stationary() {
519 let mut initializer = VisualInertialInitializer::new(euroc_config());
520 for _ in 0..100 {
521 initializer.push_sample(
522 Vector3::new(0.0, 0.0, 0.08),
523 Vector3::new(0.0, 0.0, 9.81),
524 0.01,
525 );
526 }
527 match initializer.try_initialize().expect_err("constant rotation") {
528 StationaryRejectionReason::MeanGyroMagnitudeTooHigh { observed, limit } => {
529 assert!((observed - 0.08).abs() < 1.0e-12);
530 assert_eq!(limit, 0.05);
531 }
532 other => panic!("expected MeanGyroMagnitudeTooHigh, got {other:?}"),
533 }
534 }
535
536 #[test]
537 fn rejects_noisy_gyro() {
538 let mut initializer = VisualInertialInitializer::new(euroc_config());
539 let dt = 0.005;
540 let accel_body = Vector3::new(0.0, 0.0, 9.81);
541 for i in 0..200 {
542 let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
544 let gyro = Vector3::new(sign, 0.0, 0.0);
545 initializer.push_sample(gyro, accel_body, dt);
546 }
547 match initializer.try_initialize().expect_err("should reject") {
548 StationaryRejectionReason::GyroNoiseTooHigh { observed, limit } => {
549 assert!(observed.x > limit);
550 }
551 other => panic!("expected GyroNoiseTooHigh, got {other:?}"),
552 }
553 }
554
555 #[test]
556 fn rejects_noisy_accel() {
557 let mut initializer = VisualInertialInitializer::new(euroc_config());
558 let dt = 0.005;
559 for i in 0..200 {
560 let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
561 let accel = Vector3::new(2.0 * sign, 0.0, 9.81);
562 initializer.push_sample(Vector3::zeros(), accel, dt);
563 }
564 match initializer.try_initialize().expect_err("should reject") {
565 StationaryRejectionReason::AccelNoiseTooHigh { observed, limit } => {
566 assert!(observed.x > limit);
567 }
568 other => panic!("expected AccelNoiseTooHigh, got {other:?}"),
569 }
570 }
571
572 #[test]
573 fn rejects_accel_magnitude_mismatch() {
574 let mut initializer = VisualInertialInitializer::new(euroc_config());
575 let dt = 0.005;
576 let accel_body = Vector3::new(0.0, 0.0, 2.0); for _ in 0..200 {
578 initializer.push_sample(Vector3::zeros(), accel_body, dt);
579 }
580 match initializer.try_initialize().expect_err("should reject") {
581 StationaryRejectionReason::AccelMagnitudeMismatch {
582 observed,
583 expected,
584 tolerance,
585 } => {
586 assert!((observed - 2.0).abs() < 1.0e-9);
587 assert!((expected - 9.81).abs() < 1.0e-9);
588 assert!(tolerance > 0.0);
589 }
590 other => panic!("expected AccelMagnitudeMismatch, got {other:?}"),
591 }
592 }
593
594 #[test]
595 fn rejects_insufficient_samples() {
596 let mut initializer = VisualInertialInitializer::new(euroc_config());
597 let dt = 0.005;
598 let accel_body = Vector3::new(0.0, 0.0, 9.81);
599 for _ in 0..10 {
600 initializer.push_sample(Vector3::zeros(), accel_body, dt);
601 }
602 match initializer.try_initialize().expect_err("should reject") {
603 StationaryRejectionReason::InsufficientSamples { have, need } => {
604 assert_eq!(have, 10);
605 assert_eq!(need, 50);
606 }
607 other => panic!("expected InsufficientSamples, got {other:?}"),
608 }
609 }
610
611 #[test]
612 fn rejects_insufficient_duration() {
613 let config = VisualInertialInitializerConfig {
614 min_samples: 10,
615 min_stationary_window_seconds: 1.0,
616 ..Default::default()
617 };
618 let mut initializer = VisualInertialInitializer::new(config);
619 let dt = 0.005;
620 let accel_body = Vector3::new(0.0, 0.0, 9.81);
621 for _ in 0..50 {
623 initializer.push_sample(Vector3::zeros(), accel_body, dt);
624 }
625 match initializer.try_initialize().expect_err("should reject") {
626 StationaryRejectionReason::InsufficientDuration { have, need } => {
627 assert!((have - 0.25).abs() < 1.0e-9);
628 assert!((need - 1.0).abs() < 1.0e-9);
629 }
630 other => panic!("expected InsufficientDuration, got {other:?}"),
631 }
632 }
633
634 #[test]
635 fn reset_clears_buffered_samples() {
636 let mut initializer = VisualInertialInitializer::new(euroc_config());
637 initializer.push_sample(Vector3::zeros(), Vector3::new(0.0, 0.0, 9.81), 0.005);
638 assert_eq!(initializer.samples_seen(), 1);
639 initializer.reset();
640 assert_eq!(initializer.samples_seen(), 0);
641 assert!((initializer.buffered_duration_seconds() - 0.0).abs() < 1.0e-12);
642 }
643
644 #[test]
645 fn push_sample_drops_nonpositive_dt() {
646 let mut initializer = VisualInertialInitializer::new(euroc_config());
647 let accel = Vector3::new(0.0, 0.0, 9.81);
648 initializer.push_sample(Vector3::zeros(), accel, 0.0);
649 initializer.push_sample(Vector3::zeros(), accel, -0.005);
650 initializer.push_sample(Vector3::zeros(), accel, f64::NAN);
651 assert_eq!(initializer.samples_seen(), 0);
652 }
653
654 #[test]
655 fn default_detector_window_seconds_is_infinity() {
656 let config = VisualInertialInitializerConfig::default();
660 assert!(config.detector_window_seconds.is_infinite());
661 assert!(config.detector_window_seconds > 0.0);
662 }
663
664 #[test]
665 fn time_weighted_statistics_match_unweighted_for_uniform_dt() {
666 let mut initializer = VisualInertialInitializer::new(euroc_config());
673 let dt = 0.005;
674 for i in 0..200 {
675 let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
680 let gyro = Vector3::new(sign * 0.001, 0.0, 0.0);
681 let accel = Vector3::new(0.0, 0.0, 9.81 + (i as f64) * 1.0e-6);
682 initializer.push_sample(gyro, accel, dt);
683 }
684 let result = initializer
685 .try_initialize()
686 .expect("clean stationary stream");
687 assert!(result.bias_gyro.norm() < 1.0e-15);
691 assert!((result.gyro_std.x - 0.001).abs() < 1.0e-12);
693 }
694
695 #[test]
696 fn time_weighted_statistics_shift_mean_under_nonuniform_dt() {
697 let config = VisualInertialInitializerConfig {
703 min_samples: 2,
704 min_stationary_window_seconds: 0.0,
705 max_gyro_std: f64::INFINITY,
706 max_mean_gyro_magnitude: f64::INFINITY,
707 max_accel_std: f64::INFINITY,
708 max_accel_magnitude_error: f64::INFINITY,
709 ..Default::default()
710 };
711 let mut initializer = VisualInertialInitializer::new(config);
712 initializer.push_sample(Vector3::zeros(), Vector3::new(0.0, 0.0, 9.81), 0.001);
714 initializer.push_sample(
716 Vector3::new(1.0, 0.0, 0.0),
717 Vector3::new(0.0, 0.0, 9.81),
718 0.999,
719 );
720 let result = initializer.try_initialize().expect("predicates relaxed");
721 assert!(
724 (result.bias_gyro.x - 0.999).abs() < 1.0e-12,
725 "time-weighted mean expected 0.999, got {}",
726 result.bias_gyro.x
727 );
728 }
729
730 #[test]
731 fn sliding_window_non_stationary_then_stationary_succeeds() {
732 let config = VisualInertialInitializerConfig {
740 min_samples: 50,
741 min_stationary_window_seconds: 0.5,
742 detector_window_seconds: 1.0,
743 ..Default::default()
744 };
745 let mut initializer = VisualInertialInitializer::new(config);
746 let dt = 0.005; let accel_body = Vector3::new(0.0, 0.0, 9.81);
748 for i in 0..100 {
750 let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
751 initializer.push_sample(Vector3::new(sign, 0.0, 0.0), accel_body, dt);
752 }
753 for _ in 0..300 {
755 initializer.push_sample(Vector3::zeros(), accel_body, dt);
756 }
757 let result = initializer
758 .try_initialize()
759 .expect("trailing 1.0 s window is clean");
760 assert_eq!(result.samples_consumed, 200);
764 assert!((result.duration_seconds - 1.0).abs() < 1.0e-9);
765 assert!(result.bias_gyro.norm() < 1.0e-12);
768 assert!(result.gyro_std.norm() < 1.0e-12);
769 assert_eq!(initializer.samples_seen(), 400);
772 }
773
774 #[test]
775 fn sliding_window_rejects_when_recent_samples_are_noisy() {
776 let config = VisualInertialInitializerConfig {
781 min_samples: 50,
782 min_stationary_window_seconds: 0.4,
783 detector_window_seconds: 0.5,
784 ..Default::default()
785 };
786 let mut initializer = VisualInertialInitializer::new(config);
787 let dt = 0.005;
788 let accel_body = Vector3::new(0.0, 0.0, 9.81);
789 for _ in 0..300 {
790 initializer.push_sample(Vector3::zeros(), accel_body, dt);
791 }
792 for i in 0..100 {
793 let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
794 initializer.push_sample(Vector3::new(sign, 0.0, 0.0), accel_body, dt);
795 }
796 match initializer
797 .try_initialize()
798 .expect_err("trailing slice is noisy")
799 {
800 StationaryRejectionReason::GyroNoiseTooHigh { observed, limit } => {
801 assert!(observed.x > limit);
802 }
803 other => panic!("expected GyroNoiseTooHigh, got {other:?}"),
804 }
805 }
806
807 #[test]
808 fn sliding_window_insufficient_when_trailing_slice_too_short() {
809 let config = VisualInertialInitializerConfig {
815 min_samples: 10,
816 min_stationary_window_seconds: 0.5,
817 detector_window_seconds: 0.1,
818 ..Default::default()
819 };
820 let mut initializer = VisualInertialInitializer::new(config);
821 let dt = 0.005;
822 let accel_body = Vector3::new(0.0, 0.0, 9.81);
823 for _ in 0..400 {
824 initializer.push_sample(Vector3::zeros(), accel_body, dt);
825 }
826 match initializer
827 .try_initialize()
828 .expect_err("slice is shorter than required")
829 {
830 StationaryRejectionReason::InsufficientDuration { have, need } => {
831 assert!(have < need);
834 assert!((need - 0.5).abs() < 1.0e-9);
835 assert!(have > 0.0 && have < 0.5);
836 }
837 other => panic!("expected InsufficientDuration, got {other:?}"),
838 }
839 }
840
841 #[test]
842 fn gravity_alignment_residual_is_invariant_under_world_yaw() {
843 let mut config = euroc_config();
854 config.max_accel_std = 1.0e-6;
857 let world_gravity = config.gravity_world;
858 let world_up_axis = nalgebra::Unit::new_normalize(-world_gravity);
859
860 let tilt = UnitQuaternion::from_axis_angle(&Vector3::x_axis(), 30f64.to_radians());
865 let yaw = UnitQuaternion::from_axis_angle(&world_up_axis, 30f64.to_radians());
866
867 let gt_a = tilt;
868 let gt_b = yaw * tilt;
869
870 let accel_a = gt_a.inverse() * (-world_gravity);
873 let accel_b = gt_b.inverse() * (-world_gravity);
874
875 let dt = 0.005;
876 let mut initializer_a = VisualInertialInitializer::new(config.clone());
877 let mut initializer_b = VisualInertialInitializer::new(config);
878 for _ in 0..200 {
879 initializer_a.push_sample(Vector3::zeros(), accel_a, dt);
880 initializer_b.push_sample(Vector3::zeros(), accel_b, dt);
881 }
882 let result_a = initializer_a.try_initialize().expect("stream A stationary");
883 let result_b = initializer_b.try_initialize().expect("stream B stationary");
884
885 let residual_a = result_a.gravity_alignment_residual_deg(>_a);
888 let residual_b = result_b.gravity_alignment_residual_deg(>_b);
889 assert!(residual_a < 1.0e-6, "stream A residual = {residual_a} deg");
890 assert!(residual_b < 1.0e-6, "stream B residual = {residual_b} deg");
891
892 let full_residual_b_deg = gt_b
899 .rotation_to(&result_b.initial_rotation_body_to_world)
900 .angle()
901 .to_degrees();
902 assert!(
903 (full_residual_b_deg - 30.0).abs() < 1.0e-4,
904 "stream B full residual should be ~30°, got {full_residual_b_deg}"
905 );
906 }
907
908 #[test]
909 fn gravity_alignment_residual_returns_zero_for_zero_gravity_config() {
910 let mut result_zero_g = VisualInertialInitializationResult {
914 gravity_world: Vector3::zeros(),
915 initial_rotation_body_to_world: UnitQuaternion::identity(),
916 initial_velocity_world: Vector3::zeros(),
917 bias_gyro: Vector3::zeros(),
918 bias_acc: Vector3::zeros(),
919 samples_consumed: 0,
920 duration_seconds: 0.0,
921 gyro_std: Vector3::zeros(),
922 accel_std: Vector3::zeros(),
923 mean_accel_magnitude: 0.0,
924 };
925 let any_gt = UnitQuaternion::from_axis_angle(&Vector3::x_axis(), 0.5);
926 assert_eq!(result_zero_g.gravity_alignment_residual_deg(&any_gt), 0.0);
927 result_zero_g.gravity_world = Vector3::new(0.0, 0.0, -9.81);
930 let tilt = UnitQuaternion::from_axis_angle(&Vector3::x_axis(), std::f64::consts::FRAC_PI_2);
931 let residual_deg = result_zero_g.gravity_alignment_residual_deg(&tilt);
932 assert!(
933 (residual_deg - 90.0).abs() < 1.0e-9,
934 "identity vs 90° tilt residual = {residual_deg} deg"
935 );
936 }
937
938 #[test]
939 fn accel_magnitude_mismatch_absorbed_by_bias_when_within_tolerance() {
940 let mut initializer = VisualInertialInitializer::new(euroc_config());
941 let dt = 0.005;
942 let accel_body = Vector3::new(0.0, 0.0, 9.95);
945 for _ in 0..200 {
946 initializer.push_sample(Vector3::zeros(), accel_body, dt);
947 }
948 let result = initializer.try_initialize().expect("ok");
949 let recovered_world_accel =
950 result.initial_rotation_body_to_world * (accel_body - result.bias_acc);
951 let expected_world_accel = -result.gravity_world;
952 assert!((recovered_world_accel - expected_world_accel).norm() < 1.0e-9);
953 assert!(result.bias_acc.norm() > 0.0);
954 }
955}