1use std::collections::{BTreeMap, BTreeSet};
33
34use nalgebra::{DMatrix, DVector, Matrix3, Point3, UnitQuaternion, Vector3};
35use visloc_core::geometry::SE3;
36use visloc_core::types::VisualMap;
37
38use crate::bundle::{BaConfig, BaCostBreakdown, BaResult};
39use crate::imu_preintegration::{ImuPreintegratedDelta, ImuPreintegrationFactor};
40use crate::online_slam_vi_ba::{
41 run_inertial_only_vi_ba, run_inertial_only_vi_ba_with_options, run_viba2_inertial_with_scale,
42 KeyframeImuState, Viba2Config,
43};
44use crate::vi_initializer::VisualInertialInitializationResult;
45use crate::LinearSolver;
46
47#[derive(Debug, Clone, Copy, PartialEq)]
80pub struct BiasReleaseSchedule {
81 pub min_keyframes: usize,
84 pub min_translation_meters: f64,
87}
88
89#[derive(Debug, Clone, PartialEq)]
91pub struct MotionBasedViInitializerConfig {
92 pub min_keyframes: usize,
95 pub min_translation_meters: f64,
99 pub max_solve_keyframes: Option<usize>,
106 pub gravity_world: Vector3<f64>,
110 pub body_to_camera: SE3,
115 pub ba_config: BaConfig,
119 pub viba2: Option<Viba2Config>,
126 pub max_velocity_magnitude_mps: Option<f64>,
136 pub max_gyro_bias_magnitude_rad_s: Option<f64>,
139 pub max_accel_bias_magnitude_mps2: Option<f64>,
142 pub max_final_imu_nis_per_dof: Option<f64>,
147 pub max_final_imu_rotation_residual_rms_rad: Option<f64>,
151 pub max_final_imu_velocity_residual_rms_mps: Option<f64>,
152 pub max_final_imu_position_residual_rms_meters: Option<f64>,
153 pub bias_release: Option<BiasReleaseSchedule>,
160 pub estimate_gravity: bool,
178 pub max_gravity_norm_deviation_ratio: f64,
189 pub estimate_gyro_bias: bool,
212}
213
214impl Default for MotionBasedViInitializerConfig {
215 fn default() -> Self {
216 Self {
217 min_keyframes: 10,
218 min_translation_meters: 2.0,
219 max_solve_keyframes: None,
220 gravity_world: Vector3::new(0.0, 9.81, 0.0),
221 body_to_camera: SE3::identity(),
222 ba_config: BaConfig {
223 linear_solver: LinearSolver::Sparse,
224 max_iterations: 10,
225 ..BaConfig::default()
226 },
227 viba2: None,
228 max_velocity_magnitude_mps: None,
229 max_gyro_bias_magnitude_rad_s: None,
230 max_accel_bias_magnitude_mps2: None,
231 max_final_imu_nis_per_dof: None,
232 max_final_imu_rotation_residual_rms_rad: None,
233 max_final_imu_velocity_residual_rms_mps: None,
234 max_final_imu_position_residual_rms_meters: None,
235 bias_release: None,
236 estimate_gravity: false,
237 max_gravity_norm_deviation_ratio: 0.3,
238 estimate_gyro_bias: false,
239 }
240 }
241}
242
243#[derive(Debug, Clone, PartialEq)]
245pub struct MotionBasedViInitializationResult {
246 pub keyframe_states: BTreeMap<u64, KeyframeImuState>,
248 pub keyframe_ids: Vec<u64>,
250 pub imu_factors_used: usize,
252 pub scale: f64,
256 pub scale_history: Vec<f64>,
260 pub viba2_iterations_run: usize,
263 pub trigger_translation_meters: f64,
266 pub ba_result: BaResult,
269 pub initial_cost_breakdown: BaCostBreakdown,
270 pub final_cost_breakdown: BaCostBreakdown,
271 pub bias_released: bool,
279 pub estimated_gravity_world: Option<Vector3<f64>>,
289 pub estimated_gyro_bias: Option<Vector3<f64>>,
298}
299
300#[derive(Debug, Clone, PartialEq)]
303pub enum MotionBasedViRejectionReason {
304 InsufficientKeyframes { have: usize, need: usize },
306 InsufficientTranslation { have: f64, need: f64 },
309 NoUsableImuFactors,
315 MissingKeyframeData,
318 SolverFailed,
320 VelocityOutOfRange {
329 kf_id: u64,
330 magnitude_mps: f64,
331 limit_mps: f64,
332 },
333 GyroBiasOutOfRange {
335 kf_id: u64,
336 magnitude_rad_s: f64,
337 limit_rad_s: f64,
338 },
339 AccelBiasOutOfRange {
342 kf_id: u64,
343 magnitude_mps2: f64,
344 limit_mps2: f64,
345 },
346 ImuNisOutOfRange {
350 normalized_nis_per_dof: f64,
351 rotation_residual_rms_rad: Option<f64>,
352 velocity_residual_rms_mps: Option<f64>,
353 position_residual_rms_meters: Option<f64>,
354 limit: f64,
355 },
356 ImuRawResidualOutOfRange {
359 rotation_residual_rms_rad: Option<f64>,
360 velocity_residual_rms_mps: Option<f64>,
361 position_residual_rms_meters: Option<f64>,
362 max_rotation_residual_rms_rad: Option<f64>,
363 max_velocity_residual_rms_mps: Option<f64>,
364 max_position_residual_rms_meters: Option<f64>,
365 },
366 AwaitingBiasReleaseExcitation {
373 have_keyframes: usize,
374 need_keyframes: usize,
375 have_translation_meters: f64,
376 need_translation_meters: f64,
377 },
378 GravityEstimateDegenerate,
387 GravityEstimateOutOfRange {
397 raw_norm_mps2: f64,
398 expected_mps2: f64,
399 max_deviation_ratio: f64,
400 },
401 GyroBiasEstimateDegenerate,
407}
408
409#[derive(Debug, Clone, PartialEq)]
411pub enum MotionBasedViInitializationStatus {
412 Waiting {
416 keyframes_observed: usize,
417 cumulative_translation_meters: f64,
418 last_rejection: Option<MotionBasedViRejectionReason>,
419 velocity_stage_completed: bool,
425 last_gravity_alignment: Option<GravityVelocityAlignment>,
430 last_gyro_bias_alignment: Option<GyroBiasAlignment>,
436 },
437 Initialised {
440 result: MotionBasedViInitializationResult,
441 },
442}
443
444#[derive(Debug, Clone, PartialEq)]
449pub struct MotionBasedViInitializer {
450 config: MotionBasedViInitializerConfig,
451 keyframes: Vec<(u64, Point3<f64>)>,
452 cumulative_translation: f64,
453 completed: Option<MotionBasedViInitializationResult>,
454 last_rejection: Option<MotionBasedViRejectionReason>,
455 has_seed_center: bool,
461 velocity_stage: Option<MotionBasedViInitializationResult>,
466 last_gravity_alignment: Option<GravityVelocityAlignment>,
481 last_gyro_bias_alignment: Option<GyroBiasAlignment>,
487}
488
489impl MotionBasedViInitializer {
490 pub const fn new(config: MotionBasedViInitializerConfig) -> Self {
492 Self {
493 config,
494 keyframes: Vec::new(),
495 cumulative_translation: 0.0,
496 completed: None,
497 last_rejection: None,
498 has_seed_center: false,
499 velocity_stage: None,
500 last_gravity_alignment: None,
501 last_gyro_bias_alignment: None,
502 }
503 }
504
505 pub const fn config(&self) -> &MotionBasedViInitializerConfig {
507 &self.config
508 }
509
510 pub const fn set_gravity_world(&mut self, gravity_world: Vector3<f64>) {
519 self.config.gravity_world = gravity_world;
520 }
521
522 pub fn reset(&mut self) {
526 self.keyframes.clear();
527 self.cumulative_translation = 0.0;
528 self.completed = None;
529 self.last_rejection = None;
530 self.has_seed_center = false;
531 self.velocity_stage = None;
532 self.last_gravity_alignment = None;
533 self.last_gyro_bias_alignment = None;
534 }
535
536 pub fn keyframes_observed(&self) -> usize {
538 self.keyframes.len()
539 }
540
541 pub const fn cumulative_translation_meters(&self) -> f64 {
544 self.cumulative_translation
545 }
546
547 pub fn register_keyframe(&mut self, keyframe_id: u64, camera_center_world: Point3<f64>) {
558 if let Some(slot) = self.keyframes.iter_mut().find(|(id, _)| *id == keyframe_id) {
559 slot.1 = camera_center_world;
560 return;
561 }
562 if self.has_seed_center {
563 if let Some(prev) = self.keyframes.last() {
564 self.cumulative_translation += (camera_center_world - prev.1).norm();
565 }
566 } else {
567 self.has_seed_center = true;
568 }
569 self.keyframes.push((keyframe_id, camera_center_world));
570 }
571
572 pub fn is_ready(&self) -> bool {
577 self.completed.is_none()
578 && self.keyframes.len() >= self.config.min_keyframes
579 && self.cumulative_translation >= self.config.min_translation_meters
580 }
581
582 pub const fn result(&self) -> Option<&MotionBasedViInitializationResult> {
584 self.completed.as_ref()
585 }
586
587 pub const fn velocity_stage_result(&self) -> Option<&MotionBasedViInitializationResult> {
594 self.velocity_stage.as_ref()
595 }
596
597 #[cfg(test)]
606 pub(crate) fn set_velocity_stage_result_for_test(
607 &mut self,
608 result: MotionBasedViInitializationResult,
609 ) {
610 self.velocity_stage = Some(result);
611 }
612
613 pub const fn last_gravity_alignment(&self) -> Option<&GravityVelocityAlignment> {
621 self.last_gravity_alignment.as_ref()
622 }
623
624 pub const fn last_gyro_bias_alignment(&self) -> Option<&GyroBiasAlignment> {
632 self.last_gyro_bias_alignment.as_ref()
633 }
634
635 pub fn status(&self) -> MotionBasedViInitializationStatus {
637 if let Some(result) = &self.completed {
638 MotionBasedViInitializationStatus::Initialised {
639 result: result.clone(),
640 }
641 } else {
642 MotionBasedViInitializationStatus::Waiting {
643 keyframes_observed: self.keyframes.len(),
644 cumulative_translation_meters: self.cumulative_translation,
645 last_rejection: self.last_rejection.clone(),
646 velocity_stage_completed: self.velocity_stage.is_some(),
647 last_gravity_alignment: self.last_gravity_alignment.clone(),
648 last_gyro_bias_alignment: self.last_gyro_bias_alignment,
649 }
650 }
651 }
652
653 pub fn try_initialize(
668 &mut self,
669 map: &mut VisualMap,
670 preintegration_factors: &[ImuPreintegrationFactor],
671 static_seed: &VisualInertialInitializationResult,
672 ) -> Result<&MotionBasedViInitializationResult, MotionBasedViRejectionReason> {
673 self.try_initialize_with_bias_seed(
674 map,
675 preintegration_factors,
676 static_seed.bias_gyro,
677 static_seed.bias_acc,
678 )
679 }
680
681 pub fn try_initialize_with_bias_seed(
696 &mut self,
697 map: &mut VisualMap,
698 preintegration_factors: &[ImuPreintegrationFactor],
699 bias_gyro_seed: Vector3<f64>,
700 bias_acc_seed: Vector3<f64>,
701 ) -> Result<&MotionBasedViInitializationResult, MotionBasedViRejectionReason> {
702 if let Some(_existing) = &self.completed {
703 return Ok(self.completed.as_ref().expect("just checked"));
707 }
708
709 let observed = self.keyframes.len();
710 if observed < self.config.min_keyframes {
711 let err = MotionBasedViRejectionReason::InsufficientKeyframes {
712 have: observed,
713 need: self.config.min_keyframes,
714 };
715 self.last_rejection = Some(err.clone());
716 return Err(err);
717 }
718 if self.cumulative_translation < self.config.min_translation_meters {
719 let err = MotionBasedViRejectionReason::InsufficientTranslation {
720 have: self.cumulative_translation,
721 need: self.config.min_translation_meters,
722 };
723 self.last_rejection = Some(err.clone());
724 return Err(err);
725 }
726
727 let bias_free = self.config.bias_release.is_none_or(|schedule| {
732 self.keyframes.len() >= schedule.min_keyframes
733 && self.cumulative_translation >= schedule.min_translation_meters
734 });
735 if !bias_free && self.velocity_stage.is_some() {
736 let schedule = self
739 .config
740 .bias_release
741 .expect("bias_release must be Some when velocity_stage is populated");
742 let err = MotionBasedViRejectionReason::AwaitingBiasReleaseExcitation {
743 have_keyframes: self.keyframes.len(),
744 need_keyframes: schedule.min_keyframes,
745 have_translation_meters: self.cumulative_translation,
746 need_translation_meters: schedule.min_translation_meters,
747 };
748 self.last_rejection = Some(err.clone());
749 return Err(err);
750 }
751
752 let all_kf_ids: Vec<u64> = self.keyframes.iter().map(|(id, _)| *id).collect();
759 let mut kf_ids = all_kf_ids.clone();
760 if let Some(max_solve) = self.config.max_solve_keyframes {
761 if max_solve >= 2 && kf_ids.len() > max_solve {
762 kf_ids = kf_ids[..max_solve].to_vec();
763 }
764 }
765
766 let seed_initial_states = |kf_ids: &[u64], bias_gyro: Vector3<f64>| {
767 let mut initial_states: BTreeMap<u64, KeyframeImuState> = BTreeMap::new();
768 for (idx, &kf_id) in kf_ids.iter().enumerate() {
769 let velocity = if idx == 0 {
770 Vector3::zeros()
771 } else {
772 let prev_id = kf_ids[idx - 1];
773 let factor = preintegration_factors
774 .iter()
775 .find(|f| f.keyframe_id_from == prev_id && f.keyframe_id_to == kf_id);
776 match factor {
777 Some(f) if f.delta.delta_time > 0.0 => {
778 let prev_center = self
779 .keyframes
780 .iter()
781 .find(|(id, _)| *id == prev_id)
782 .expect("previous solve keyframe is registered")
783 .1;
784 let curr_center = self
785 .keyframes
786 .iter()
787 .find(|(id, _)| *id == kf_id)
788 .expect("current solve keyframe is registered")
789 .1;
790 (curr_center - prev_center) / f.delta.delta_time
791 }
792 _ => Vector3::zeros(),
793 }
794 };
795 initial_states.insert(
796 kf_id,
797 KeyframeImuState {
798 velocity_world: velocity,
799 bias_gyro,
800 bias_acc: bias_acc_seed,
801 },
802 );
803 }
804 initial_states
805 };
806 let mut initial_states = seed_initial_states(&kf_ids, bias_gyro_seed);
807
808 for kf_id in &kf_ids {
810 let Some(kf) = map.keyframes.get(kf_id) else {
811 let err = MotionBasedViRejectionReason::MissingKeyframeData;
812 self.last_rejection = Some(err.clone());
813 return Err(err);
814 };
815 if kf.frame.pose.is_none() {
816 let err = MotionBasedViRejectionReason::MissingKeyframeData;
817 self.last_rejection = Some(err.clone());
818 return Err(err);
819 }
820 }
821
822 let mut candidate_map = map.clone();
827 for kf_id in &all_kf_ids {
833 let Some(pose) = candidate_map
834 .keyframes
835 .get_mut(kf_id)
836 .and_then(|kf| kf.frame.pose.as_mut())
837 else {
838 continue;
839 };
840 pose.world_to_camera = self.config.body_to_camera.compose(&pose.world_to_camera);
841 }
842
843 let mut effective_bias_gyro = bias_gyro_seed;
857 let mut estimated_gyro_bias: Option<Vector3<f64>> = None;
858 if self.config.estimate_gyro_bias {
859 let alignment = estimate_gyro_bias_with_window(
860 &candidate_map,
861 &all_kf_ids,
862 preintegration_factors,
863 bias_gyro_seed,
864 );
865 let (alignment, window_ids) = match alignment {
866 Some(found) => found,
867 None => {
868 self.last_gyro_bias_alignment = None;
869 let err = MotionBasedViRejectionReason::GyroBiasEstimateDegenerate;
870 self.last_rejection = Some(err.clone());
871 return Err(err);
872 }
873 };
874 self.last_gyro_bias_alignment = Some(alignment);
878 let magnitude_rad_s = alignment.bias_gyro.norm();
879 if let Some(limit) = self.config.max_gyro_bias_magnitude_rad_s {
880 if magnitude_rad_s > limit {
881 let err = MotionBasedViRejectionReason::GyroBiasOutOfRange {
882 kf_id: window_ids.first().copied().unwrap_or(kf_ids[0]),
883 magnitude_rad_s,
884 limit_rad_s: limit,
885 };
886 self.last_rejection = Some(err.clone());
887 return Err(err);
888 }
889 }
890 if window_ids.len() >= 2 {
891 kf_ids = window_ids;
892 }
893 effective_bias_gyro = alignment.bias_gyro;
894 estimated_gyro_bias = Some(alignment.bias_gyro);
895 initial_states = seed_initial_states(&kf_ids, effective_bias_gyro);
896 }
897
898 let mut estimated_gravity: Option<Vector3<f64>> = None;
909 if self.config.estimate_gravity {
910 let expected_magnitude = self.config.gravity_world.norm();
911 let alignment = estimate_gravity_and_velocities(
912 &candidate_map,
913 &kf_ids,
914 preintegration_factors,
915 effective_bias_gyro,
916 bias_acc_seed,
917 expected_magnitude,
918 );
919 let alignment = match alignment {
920 Some(alignment) => alignment,
921 None => {
922 self.last_gravity_alignment = None;
923 let err = MotionBasedViRejectionReason::GravityEstimateDegenerate;
924 self.last_rejection = Some(err.clone());
925 return Err(err);
926 }
927 };
928 self.last_gravity_alignment = Some(alignment.clone());
936 let deviation_ratio = if expected_magnitude > 0.0 {
937 (alignment.raw_gravity_norm - expected_magnitude).abs() / expected_magnitude
938 } else {
939 f64::INFINITY
940 };
941 if !deviation_ratio.is_finite()
942 || deviation_ratio > self.config.max_gravity_norm_deviation_ratio
943 {
944 let err = MotionBasedViRejectionReason::GravityEstimateOutOfRange {
945 raw_norm_mps2: alignment.raw_gravity_norm,
946 expected_mps2: expected_magnitude,
947 max_deviation_ratio: self.config.max_gravity_norm_deviation_ratio,
948 };
949 self.last_rejection = Some(err.clone());
950 return Err(err);
951 }
952 for (kf_id, velocity) in &alignment.velocities {
953 if let Some(state) = initial_states.get_mut(kf_id) {
954 state.velocity_world = *velocity;
955 }
956 }
957 estimated_gravity = Some(alignment.gravity_world);
958 }
959 let gravity_adjusted_factors: Option<Vec<ImuPreintegrationFactor>> =
965 estimated_gravity.map(|g| {
966 preintegration_factors
967 .iter()
968 .map(|f| {
969 let mut adjusted = f.clone();
970 adjusted.gravity_world = g;
971 adjusted
972 })
973 .collect()
974 });
975 let solve_factors: &[ImuPreintegrationFactor] = gravity_adjusted_factors
976 .as_deref()
977 .unwrap_or(preintegration_factors);
978
979 let result = if !bias_free {
991 let stats = run_inertial_only_vi_ba_with_options(
992 &mut candidate_map,
993 &kf_ids,
994 solve_factors,
995 &initial_states,
996 &self.config.ba_config,
997 false,
998 );
999 let stats = match stats {
1000 Some(s) => s,
1001 None => {
1002 let any_in_window = solve_factors.iter().any(|f| {
1003 kf_ids.contains(&f.keyframe_id_from) && kf_ids.contains(&f.keyframe_id_to)
1004 });
1005 let err = if any_in_window {
1006 MotionBasedViRejectionReason::SolverFailed
1007 } else {
1008 MotionBasedViRejectionReason::NoUsableImuFactors
1009 };
1010 self.last_rejection = Some(err.clone());
1011 return Err(err);
1012 }
1013 };
1014 MotionBasedViInitializationResult {
1015 keyframe_states: stats.keyframe_states,
1016 keyframe_ids: stats.keyframe_ids,
1017 imu_factors_used: stats.imu_factor_count,
1018 scale: 1.0,
1019 scale_history: Vec::new(),
1020 viba2_iterations_run: 0,
1021 trigger_translation_meters: self.cumulative_translation,
1022 ba_result: stats.ba_result,
1023 initial_cost_breakdown: stats.initial_cost_breakdown,
1024 final_cost_breakdown: stats.final_cost_breakdown,
1025 bias_released: false,
1026 estimated_gravity_world: estimated_gravity,
1027 estimated_gyro_bias,
1028 }
1029 } else if let Some(viba2_cfg) = self.config.viba2.clone() {
1030 let stats = run_viba2_inertial_with_scale(
1031 &mut candidate_map,
1032 &kf_ids,
1033 solve_factors,
1034 &initial_states,
1035 &viba2_cfg,
1036 );
1037 let stats = match stats {
1038 Some(s) => s,
1039 None => {
1040 let any_in_window = solve_factors.iter().any(|f| {
1041 kf_ids.contains(&f.keyframe_id_from) && kf_ids.contains(&f.keyframe_id_to)
1042 });
1043 let err = if any_in_window {
1044 MotionBasedViRejectionReason::SolverFailed
1045 } else {
1046 MotionBasedViRejectionReason::NoUsableImuFactors
1047 };
1048 self.last_rejection = Some(err.clone());
1049 return Err(err);
1050 }
1051 };
1052 MotionBasedViInitializationResult {
1053 keyframe_states: stats.keyframe_states,
1054 keyframe_ids: stats.keyframe_ids,
1055 imu_factors_used: stats.imu_factor_count,
1056 scale: stats.scale,
1057 scale_history: stats.scale_history,
1058 viba2_iterations_run: stats.outer_iterations_run,
1059 trigger_translation_meters: self.cumulative_translation,
1060 ba_result: stats.ba_result,
1061 initial_cost_breakdown: stats.initial_cost_breakdown,
1062 final_cost_breakdown: stats.final_cost_breakdown,
1063 bias_released: true,
1064 estimated_gravity_world: estimated_gravity,
1065 estimated_gyro_bias,
1066 }
1067 } else {
1068 let stats = run_inertial_only_vi_ba(
1069 &mut candidate_map,
1070 &kf_ids,
1071 solve_factors,
1072 &initial_states,
1073 &self.config.ba_config,
1074 );
1075 let stats = match stats {
1076 Some(s) => s,
1077 None => {
1078 let any_in_window = solve_factors.iter().any(|f| {
1079 kf_ids.contains(&f.keyframe_id_from) && kf_ids.contains(&f.keyframe_id_to)
1080 });
1081 let err = if any_in_window {
1082 MotionBasedViRejectionReason::SolverFailed
1083 } else {
1084 MotionBasedViRejectionReason::NoUsableImuFactors
1085 };
1086 self.last_rejection = Some(err.clone());
1087 return Err(err);
1088 }
1089 };
1090 MotionBasedViInitializationResult {
1091 keyframe_states: stats.keyframe_states,
1092 keyframe_ids: stats.keyframe_ids,
1093 imu_factors_used: stats.imu_factor_count,
1094 scale: 1.0,
1095 scale_history: Vec::new(),
1096 viba2_iterations_run: 0,
1097 trigger_translation_meters: self.cumulative_translation,
1098 ba_result: stats.ba_result,
1099 initial_cost_breakdown: stats.initial_cost_breakdown,
1100 final_cost_breakdown: stats.final_cost_breakdown,
1101 bias_released: true,
1102 estimated_gravity_world: estimated_gravity,
1103 estimated_gyro_bias,
1104 }
1105 };
1106
1107 let final_cost = &result.final_cost_breakdown;
1108 let rotation_exceeded = self
1109 .config
1110 .max_final_imu_rotation_residual_rms_rad
1111 .is_some_and(|limit| {
1112 final_cost
1113 .imu_rotation_residual_rms_rad
1114 .is_none_or(|value| !value.is_finite() || value > limit)
1115 });
1116 let velocity_exceeded = self
1117 .config
1118 .max_final_imu_velocity_residual_rms_mps
1119 .is_some_and(|limit| {
1120 final_cost
1121 .imu_velocity_residual_rms_mps
1122 .is_none_or(|value| !value.is_finite() || value > limit)
1123 });
1124 let position_exceeded = self
1125 .config
1126 .max_final_imu_position_residual_rms_meters
1127 .is_some_and(|limit| {
1128 final_cost
1129 .imu_position_residual_rms_meters
1130 .is_none_or(|value| !value.is_finite() || value > limit)
1131 });
1132 if rotation_exceeded || velocity_exceeded || position_exceeded {
1133 let err = MotionBasedViRejectionReason::ImuRawResidualOutOfRange {
1134 rotation_residual_rms_rad: final_cost.imu_rotation_residual_rms_rad,
1135 velocity_residual_rms_mps: final_cost.imu_velocity_residual_rms_mps,
1136 position_residual_rms_meters: final_cost.imu_position_residual_rms_meters,
1137 max_rotation_residual_rms_rad: self.config.max_final_imu_rotation_residual_rms_rad,
1138 max_velocity_residual_rms_mps: self.config.max_final_imu_velocity_residual_rms_mps,
1139 max_position_residual_rms_meters: self
1140 .config
1141 .max_final_imu_position_residual_rms_meters,
1142 };
1143 self.last_rejection = Some(err.clone());
1144 return Err(err);
1145 }
1146
1147 if let Some(limit) = self.config.max_final_imu_nis_per_dof {
1148 if let Some(normalized_nis_per_dof) = result
1149 .final_cost_breakdown
1150 .imu_normalized_squared_residual_per_dof
1151 .filter(|value| !value.is_finite() || *value > limit)
1152 {
1153 let err = MotionBasedViRejectionReason::ImuNisOutOfRange {
1154 normalized_nis_per_dof,
1155 rotation_residual_rms_rad: result
1156 .final_cost_breakdown
1157 .imu_rotation_residual_rms_rad,
1158 velocity_residual_rms_mps: result
1159 .final_cost_breakdown
1160 .imu_velocity_residual_rms_mps,
1161 position_residual_rms_meters: result
1162 .final_cost_breakdown
1163 .imu_position_residual_rms_meters,
1164 limit,
1165 };
1166 self.last_rejection = Some(err.clone());
1167 return Err(err);
1168 }
1169 }
1170
1171 if let Some(limit) = self.config.max_velocity_magnitude_mps {
1172 let mut worst: Option<(u64, f64)> = None;
1173 for (kf_id, state) in &result.keyframe_states {
1174 let mag = state.velocity_world.norm();
1175 if mag > limit && worst.is_none_or(|(_, m)| mag > m) {
1176 worst = Some((*kf_id, mag));
1177 }
1178 }
1179 if let Some((kf_id, mag)) = worst {
1180 let err = MotionBasedViRejectionReason::VelocityOutOfRange {
1181 kf_id,
1182 magnitude_mps: mag,
1183 limit_mps: limit,
1184 };
1185 self.last_rejection = Some(err.clone());
1186 return Err(err);
1187 }
1188 }
1189 if let Some(limit) = self.config.max_gyro_bias_magnitude_rad_s {
1190 let worst = result
1191 .keyframe_states
1192 .iter()
1193 .map(|(kf_id, state)| (*kf_id, state.bias_gyro.norm()))
1194 .filter(|(_, magnitude)| *magnitude > limit)
1195 .max_by(|left, right| left.1.total_cmp(&right.1));
1196 if let Some((kf_id, magnitude_rad_s)) = worst {
1197 let err = MotionBasedViRejectionReason::GyroBiasOutOfRange {
1198 kf_id,
1199 magnitude_rad_s,
1200 limit_rad_s: limit,
1201 };
1202 self.last_rejection = Some(err.clone());
1203 return Err(err);
1204 }
1205 }
1206 if let Some(limit) = self.config.max_accel_bias_magnitude_mps2 {
1207 let worst = result
1208 .keyframe_states
1209 .iter()
1210 .map(|(kf_id, state)| (*kf_id, state.bias_acc.norm()))
1211 .filter(|(_, magnitude)| *magnitude > limit)
1212 .max_by(|left, right| left.1.total_cmp(&right.1));
1213 if let Some((kf_id, magnitude_mps2)) = worst {
1214 let err = MotionBasedViRejectionReason::AccelBiasOutOfRange {
1215 kf_id,
1216 magnitude_mps2,
1217 limit_mps2: limit,
1218 };
1219 self.last_rejection = Some(err.clone());
1220 return Err(err);
1221 }
1222 }
1223
1224 if result.bias_released {
1225 self.completed = Some(result);
1227 self.last_rejection = None;
1228 Ok(self.completed.as_ref().expect("just inserted"))
1229 } else {
1230 self.velocity_stage = Some(result);
1234 self.last_rejection = None;
1235 Ok(self.velocity_stage.as_ref().expect("just inserted"))
1236 }
1237 }
1238}
1239
1240#[derive(Debug, Clone, PartialEq)]
1245pub struct GravityVelocityAlignment {
1246 pub gravity_world: Vector3<f64>,
1250 pub raw_gravity_norm: f64,
1258 pub velocities: BTreeMap<u64, Vector3<f64>>,
1264 pub mean_residual_after: f64,
1273 pub window_keyframes: usize,
1280}
1281
1282struct AlignmentFactorRow {
1287 idx_from: usize,
1290 idx_to: usize,
1292 delta_time: f64,
1293 rhs_position: Vector3<f64>,
1297 rhs_velocity: Vector3<f64>,
1299}
1300
1301pub fn estimate_gravity_and_velocities(
1364 map: &VisualMap,
1365 keyframe_ids: &[u64],
1366 factors: &[ImuPreintegrationFactor],
1367 bias_gyro_seed: Vector3<f64>,
1368 bias_acc_seed: Vector3<f64>,
1369 expected_gravity_magnitude: f64,
1370) -> Option<GravityVelocityAlignment> {
1371 const MAX_ALIGNMENT_WINDOW: usize = 10;
1372 const REFINEMENT_ITERATIONS: usize = 4;
1373
1374 if !expected_gravity_magnitude.is_finite() || expected_gravity_magnitude <= 0.0 {
1375 return None;
1376 }
1377
1378 let mut ids: Vec<u64> = keyframe_ids.to_vec();
1379 ids.sort_unstable();
1380 ids.dedup();
1381 if ids.len() > MAX_ALIGNMENT_WINDOW {
1382 let start = ids.len() - MAX_ALIGNMENT_WINDOW;
1383 ids = ids[start..].to_vec();
1384 }
1385 if ids.len() < 2 {
1386 return None;
1387 }
1388 let in_window: BTreeSet<u64> = ids.iter().copied().collect();
1389 let index_of: BTreeMap<u64, usize> =
1390 ids.iter().enumerate().map(|(idx, id)| (*id, idx)).collect();
1391
1392 let mut rotation_body_to_world: BTreeMap<u64, UnitQuaternion<f64>> = BTreeMap::new();
1396 let mut position_world: BTreeMap<u64, Vector3<f64>> = BTreeMap::new();
1397 for id in &ids {
1398 let pose = map.keyframes.get(id)?.frame.pose.as_ref()?;
1399 let world_from_body = pose.camera_to_world();
1400 rotation_body_to_world.insert(*id, world_from_body.rotation);
1401 position_world.insert(*id, world_from_body.translation);
1402 }
1403
1404 let mut rows: Vec<AlignmentFactorRow> = Vec::new();
1405 for factor in factors {
1406 if !in_window.contains(&factor.keyframe_id_from)
1407 || !in_window.contains(&factor.keyframe_id_to)
1408 {
1409 continue;
1410 }
1411 let delta_time = factor.delta.delta_time;
1412 if delta_time.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {
1413 continue;
1414 }
1415 let idx_from = *index_of.get(&factor.keyframe_id_from).expect("windowed id");
1416 let idx_to = *index_of.get(&factor.keyframe_id_to).expect("windowed id");
1417 let r_i = *rotation_body_to_world
1418 .get(&factor.keyframe_id_from)
1419 .expect("windowed id");
1420 let p_i = *position_world
1421 .get(&factor.keyframe_id_from)
1422 .expect("windowed id");
1423 let p_j = *position_world
1424 .get(&factor.keyframe_id_to)
1425 .expect("windowed id");
1426 let (_, delta_velocity, delta_position) =
1427 factor.delta.corrected(&bias_gyro_seed, &bias_acc_seed);
1428 rows.push(AlignmentFactorRow {
1429 idx_from,
1430 idx_to,
1431 delta_time,
1432 rhs_position: (p_j - p_i) - r_i.transform_vector(&delta_position),
1433 rhs_velocity: r_i.transform_vector(&delta_velocity),
1434 });
1435 }
1436 if rows.len() < 2 {
1437 return None;
1438 }
1439
1440 let num_kf = ids.len();
1441 let num_rows = 6 * rows.len();
1442
1443 let mut a = DMatrix::<f64>::zeros(num_rows, 3 * num_kf + 3);
1445 let mut b = DVector::<f64>::zeros(num_rows);
1446 for (r, row) in rows.iter().enumerate() {
1447 let base = 6 * r;
1448 for k in 0..3 {
1449 a[(base + k, 3 * row.idx_from + k)] = row.delta_time;
1450 a[(base + k, 3 * num_kf + k)] = 0.5 * row.delta_time * row.delta_time;
1451 b[base + k] = row.rhs_position[k];
1452
1453 a[(base + 3 + k, 3 * row.idx_from + k)] = -1.0;
1454 a[(base + 3 + k, 3 * row.idx_to + k)] = 1.0;
1455 a[(base + 3 + k, 3 * num_kf + k)] = -row.delta_time;
1456 b[base + 3 + k] = row.rhs_velocity[k];
1457 }
1458 }
1459 let raw_solution = a.svd(true, true).solve(&b, 1.0e-9).ok()?;
1460 let raw_gravity = Vector3::new(
1461 raw_solution[3 * num_kf],
1462 raw_solution[3 * num_kf + 1],
1463 raw_solution[3 * num_kf + 2],
1464 );
1465 let raw_gravity_norm = raw_gravity.norm();
1466 if !raw_gravity_norm.is_finite() || raw_gravity_norm < 1.0e-6 {
1467 return None;
1468 }
1469 let raw_velocities: Vec<Vector3<f64>> = (0..num_kf)
1470 .map(|k| {
1471 Vector3::new(
1472 raw_solution[3 * k],
1473 raw_solution[3 * k + 1],
1474 raw_solution[3 * k + 2],
1475 )
1476 })
1477 .collect();
1478
1479 let mag = expected_gravity_magnitude;
1484 let mut g_hat = raw_gravity / raw_gravity_norm;
1485 let mut velocities_final = raw_velocities;
1486 let mut refined = false;
1487 for _ in 0..REFINEMENT_ITERATIONS {
1488 let (b1, b2) = tangent_basis(&g_hat);
1489 let g0 = mag * g_hat;
1490 let mut a2 = DMatrix::<f64>::zeros(num_rows, 3 * num_kf + 2);
1491 let mut b2vec = DVector::<f64>::zeros(num_rows);
1492 for (r, row) in rows.iter().enumerate() {
1493 let base = 6 * r;
1494 for k in 0..3 {
1495 a2[(base + k, 3 * row.idx_from + k)] = row.delta_time;
1496 a2[(base + k, 3 * num_kf)] = 0.5 * row.delta_time * row.delta_time * mag * b1[k];
1497 a2[(base + k, 3 * num_kf + 1)] =
1498 0.5 * row.delta_time * row.delta_time * mag * b2[k];
1499 b2vec[base + k] =
1500 row.rhs_position[k] - 0.5 * row.delta_time * row.delta_time * g0[k];
1501
1502 a2[(base + 3 + k, 3 * row.idx_from + k)] = -1.0;
1503 a2[(base + 3 + k, 3 * row.idx_to + k)] = 1.0;
1504 a2[(base + 3 + k, 3 * num_kf)] = -row.delta_time * mag * b1[k];
1505 a2[(base + 3 + k, 3 * num_kf + 1)] = -row.delta_time * mag * b2[k];
1506 b2vec[base + 3 + k] = row.rhs_velocity[k] + row.delta_time * g0[k];
1507 }
1508 }
1509 let Ok(solution) = a2.svd(true, true).solve(&b2vec, 1.0e-9) else {
1510 break;
1511 };
1512 let w1 = solution[3 * num_kf];
1513 let w2 = solution[3 * num_kf + 1];
1514 if !w1.is_finite() || !w2.is_finite() {
1515 break;
1516 }
1517 let candidate = g_hat + w1 * b1 + w2 * b2;
1518 let candidate_norm = candidate.norm();
1519 if !candidate_norm.is_finite() || candidate_norm < 1.0e-9 {
1520 break;
1521 }
1522 g_hat = candidate / candidate_norm;
1523 velocities_final = (0..num_kf)
1524 .map(|k| Vector3::new(solution[3 * k], solution[3 * k + 1], solution[3 * k + 2]))
1525 .collect();
1526 refined = true;
1527 }
1528
1529 let gravity_world = if refined {
1530 mag * g_hat
1531 } else {
1532 mag * (raw_gravity / raw_gravity_norm)
1533 };
1534
1535 let mut residual_sum_sq = 0.0;
1536 for row in &rows {
1537 let v_i = velocities_final[row.idx_from];
1538 let v_j = velocities_final[row.idx_to];
1539 let r_pos = (v_i * row.delta_time + 0.5 * row.delta_time * row.delta_time * gravity_world)
1540 - row.rhs_position;
1541 let r_vel = (-v_i + v_j - row.delta_time * gravity_world) - row.rhs_velocity;
1542 residual_sum_sq += r_pos.norm_squared() + r_vel.norm_squared();
1543 }
1544 let mean_residual_after = (residual_sum_sq / (6.0 * rows.len() as f64)).sqrt();
1545
1546 let velocities: BTreeMap<u64, Vector3<f64>> = ids
1547 .iter()
1548 .enumerate()
1549 .map(|(k, id)| (*id, velocities_final[k]))
1550 .collect();
1551
1552 Some(GravityVelocityAlignment {
1553 gravity_world,
1554 raw_gravity_norm,
1555 velocities,
1556 mean_residual_after,
1557 window_keyframes: num_kf,
1558 })
1559}
1560
1561fn tangent_basis(g_hat: &Vector3<f64>) -> (Vector3<f64>, Vector3<f64>) {
1567 let reference = if g_hat.x.abs() < 0.9 {
1568 Vector3::x()
1569 } else {
1570 Vector3::y()
1571 };
1572 let b1 = g_hat.cross(&reference).normalize();
1573 let b2 = g_hat.cross(&b1).normalize();
1574 (b1, b2)
1575}
1576
1577#[derive(Debug, Clone, Copy, PartialEq)]
1583pub struct GyroBiasAlignment {
1584 pub bias_gyro: Vector3<f64>,
1588 pub iterations: usize,
1591 pub rotation_residual_rms_before: f64,
1597 pub rotation_residual_rms_after: f64,
1600}
1601
1602pub fn estimate_gyro_bias(
1645 map: &VisualMap,
1646 keyframe_ids: &[u64],
1647 factors: &[ImuPreintegrationFactor],
1648 bias_gyro_seed: Vector3<f64>,
1649) -> Option<GyroBiasAlignment> {
1650 estimate_gyro_bias_with_window(map, keyframe_ids, factors, bias_gyro_seed)
1651 .map(|(alignment, _)| alignment)
1652}
1653
1654fn estimate_gyro_bias_with_window(
1655 map: &VisualMap,
1656 keyframe_ids: &[u64],
1657 factors: &[ImuPreintegrationFactor],
1658 bias_gyro_seed: Vector3<f64>,
1659) -> Option<(GyroBiasAlignment, Vec<u64>)> {
1660 const MAX_ALIGNMENT_WINDOW: usize = 5;
1661 const MIN_ALIGNMENT_WINDOW: usize = 3;
1662
1663 let mut ids: Vec<u64> = keyframe_ids.to_vec();
1664 ids.sort_unstable();
1665 ids.dedup();
1666 if ids.len() < MIN_ALIGNMENT_WINDOW {
1667 let alignment = estimate_gyro_bias_on_ids(map, &ids, factors, bias_gyro_seed)?;
1668 return Some((alignment, ids));
1669 }
1670
1671 let max_w = MAX_ALIGNMENT_WINDOW.min(ids.len());
1672 let mut best: Option<(GyroBiasAlignment, Vec<u64>)> = None;
1673 for w in MIN_ALIGNMENT_WINDOW..=max_w {
1674 for start in 0..=ids.len() - w {
1675 let subset = ids[start..start + w].to_vec();
1676 let Some(alignment) = estimate_gyro_bias_on_ids(map, &subset, factors, bias_gyro_seed)
1677 else {
1678 continue;
1679 };
1680 if best.as_ref().is_none_or(|(current, _)| {
1681 alignment.rotation_residual_rms_after < current.rotation_residual_rms_after
1682 }) {
1683 best = Some((alignment, subset));
1684 }
1685 }
1686 }
1687 best.or_else(|| {
1688 let alignment = estimate_gyro_bias_on_ids(map, &ids, factors, bias_gyro_seed)?;
1689 Some((alignment, ids))
1690 })
1691}
1692
1693fn estimate_gyro_bias_on_ids(
1694 map: &VisualMap,
1695 ids: &[u64],
1696 factors: &[ImuPreintegrationFactor],
1697 bias_gyro_seed: Vector3<f64>,
1698) -> Option<GyroBiasAlignment> {
1699 const MAX_ITERATIONS: usize = 5;
1700 const CONVERGENCE_STEP_NORM: f64 = 1.0e-10;
1701 if ids.len() < 2 {
1702 return None;
1703 }
1704 let in_window: BTreeSet<u64> = ids.iter().copied().collect();
1705
1706 let mut rotation_body_to_world: BTreeMap<u64, UnitQuaternion<f64>> = BTreeMap::new();
1707 for id in ids {
1708 let pose = map.keyframes.get(id)?.frame.pose.as_ref()?;
1709 rotation_body_to_world.insert(*id, pose.camera_to_world().rotation);
1710 }
1711
1712 struct GyroBiasRow {
1713 r_i: UnitQuaternion<f64>,
1714 r_j: UnitQuaternion<f64>,
1715 delta_index: usize,
1716 }
1717 let mut rows: Vec<GyroBiasRow> = Vec::new();
1718 let mut deltas: Vec<&ImuPreintegratedDelta> = Vec::new();
1719 for factor in factors {
1720 if !in_window.contains(&factor.keyframe_id_from)
1721 || !in_window.contains(&factor.keyframe_id_to)
1722 {
1723 continue;
1724 }
1725 if factor.delta.delta_time <= 0.0 {
1726 continue;
1727 }
1728 let Some(&r_i) = rotation_body_to_world.get(&factor.keyframe_id_from) else {
1729 continue;
1730 };
1731 let Some(&r_j) = rotation_body_to_world.get(&factor.keyframe_id_to) else {
1732 continue;
1733 };
1734 deltas.push(&factor.delta);
1735 rows.push(GyroBiasRow {
1736 r_i,
1737 r_j,
1738 delta_index: deltas.len() - 1,
1739 });
1740 }
1741 if rows.len() < 2 {
1742 return None;
1743 }
1744
1745 let residual_at = |bias_gyro: &Vector3<f64>| -> Vec<Vector3<f64>> {
1751 rows.iter()
1752 .map(|row| {
1753 let delta = deltas[row.delta_index];
1754 let (delta_rot, _, _) = delta.corrected(bias_gyro, &delta.bias_acc_linearisation);
1755 let q_rel = delta_rot.quaternion().inverse() * row.r_i.inverse() * row.r_j;
1756 q_rel.scaled_axis()
1757 })
1758 .collect()
1759 };
1760 let rms = |residuals: &[Vector3<f64>]| -> f64 {
1761 let sum_sq: f64 = residuals.iter().map(|r| r.norm_squared()).sum();
1762 (sum_sq / (3.0 * residuals.len() as f64)).sqrt()
1763 };
1764
1765 let residuals_before = residual_at(&bias_gyro_seed);
1766 let rotation_residual_rms_before = rms(&residuals_before);
1767
1768 let mut bias_gyro = bias_gyro_seed;
1769 let mut residuals_current = residuals_before;
1770 let mut iterations = 0usize;
1771 for iteration in 0..MAX_ITERATIONS {
1772 let mut ata = Matrix3::zeros();
1773 let mut atb = Vector3::zeros();
1774 for (row, residual) in rows.iter().zip(residuals_current.iter()) {
1775 let j = deltas[row.delta_index].j_rotation_bg;
1776 ata += j.transpose() * j;
1777 atb += j.transpose() * *residual;
1778 }
1779 let Some(ata_inv) = ata.try_inverse() else {
1780 if iteration == 0 {
1781 return None;
1782 }
1783 break;
1784 };
1785 let delta_step = ata_inv * atb;
1786 if !delta_step.iter().all(|v| v.is_finite()) {
1787 if iteration == 0 {
1788 return None;
1789 }
1790 break;
1791 }
1792 bias_gyro += delta_step;
1793 iterations += 1;
1794 residuals_current = residual_at(&bias_gyro);
1795 if delta_step.norm() < CONVERGENCE_STEP_NORM {
1796 break;
1797 }
1798 }
1799 let rotation_residual_rms_after = rms(&residuals_current);
1800
1801 Some(GyroBiasAlignment {
1802 bias_gyro,
1803 iterations,
1804 rotation_residual_rms_before,
1805 rotation_residual_rms_after,
1806 })
1807}
1808
1809#[cfg(test)]
1810mod tests {
1811 use super::*;
1812
1813 use nalgebra::{Point3, UnitQuaternion};
1814 use visloc_core::geometry::{Pose, SO3};
1815 use visloc_core::types::{Camera, Frame, Keyframe, VisualMap};
1816
1817 use crate::imu_preintegration::ImuPreintegratedDelta;
1818
1819 fn pinhole_camera() -> Camera {
1820 Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0)
1821 }
1822
1823 fn pose_at_world_center(c: Vector3<f64>) -> Pose {
1824 let r = UnitQuaternion::identity();
1826 Pose::from_world_to_camera(r, -r.transform_vector(&c))
1827 }
1828
1829 fn synthetic_seed() -> VisualInertialInitializationResult {
1830 VisualInertialInitializationResult {
1831 gravity_world: Vector3::new(0.0, 9.81, 0.0),
1832 initial_rotation_body_to_world: UnitQuaternion::identity(),
1833 initial_velocity_world: Vector3::zeros(),
1834 bias_gyro: Vector3::zeros(),
1835 bias_acc: Vector3::zeros(),
1836 samples_consumed: 2000,
1837 duration_seconds: 1.0,
1838 gyro_std: Vector3::zeros(),
1839 accel_std: Vector3::zeros(),
1840 mean_accel_magnitude: 9.81,
1841 }
1842 }
1843
1844 fn no_acceleration_factor(
1845 from_id: u64,
1846 to_id: u64,
1847 delta_t: f64,
1848 gravity: Vector3<f64>,
1849 ) -> ImuPreintegrationFactor {
1850 let mut delta = ImuPreintegratedDelta::identity();
1865 delta.delta_time = delta_t;
1866 delta.delta_velocity = -gravity * delta_t;
1867 delta.delta_position = -0.5 * gravity * delta_t * delta_t;
1868 ImuPreintegrationFactor {
1869 keyframe_id_from: from_id,
1870 keyframe_id_to: to_id,
1871 delta,
1872 gravity_world: gravity,
1873 weight_position: 1.0,
1874 weight_velocity: 1.0,
1875 weight_rotation: 1.0,
1876 }
1877 }
1878
1879 fn no_acceleration_factor_with_assumed_gravity(
1891 from_id: u64,
1892 to_id: u64,
1893 delta_t: f64,
1894 true_gravity: Vector3<f64>,
1895 assumed_gravity: Vector3<f64>,
1896 ) -> ImuPreintegrationFactor {
1897 let mut delta = ImuPreintegratedDelta::identity();
1898 delta.delta_time = delta_t;
1899 delta.delta_velocity = -true_gravity * delta_t;
1900 delta.delta_position = -0.5 * true_gravity * delta_t * delta_t;
1901 ImuPreintegrationFactor {
1902 keyframe_id_from: from_id,
1903 keyframe_id_to: to_id,
1904 delta,
1905 gravity_world: assumed_gravity,
1906 weight_position: 1.0,
1907 weight_velocity: 1.0,
1908 weight_rotation: 1.0,
1909 }
1910 }
1911
1912 fn build_map_at_velocity(num_keyframes: usize, dt: f64, velocity: Vector3<f64>) -> VisualMap {
1920 let mut map = VisualMap::new();
1921 let camera = pinhole_camera();
1922 map.cameras.insert(camera.id, camera.clone());
1923 for i in 0..num_keyframes {
1924 let center = velocity * (i as f64) * dt;
1925 let pose = pose_at_world_center(center);
1926 let frame_id = (i as u64) + 1;
1927 let mut frame = Frame::new(frame_id, camera.id);
1928 frame.pose = Some(pose);
1929 let kf = Keyframe {
1930 frame,
1931 observations: Vec::new(),
1932 };
1933 map.keyframes.insert(frame_id, kf);
1934 }
1935 map
1936 }
1937
1938 fn build_constant_velocity_map(num_keyframes: usize) -> VisualMap {
1939 let mut map = VisualMap::new();
1940 let camera = pinhole_camera();
1941 map.cameras.insert(camera.id, camera.clone());
1942 for i in 0..num_keyframes {
1943 let center = Vector3::new(i as f64, 0.0, 0.0);
1944 let pose = pose_at_world_center(center);
1945 let frame_id = (i as u64) + 1;
1946 let mut frame = Frame::new(frame_id, camera.id);
1947 frame.pose = Some(pose);
1948 let kf = Keyframe {
1949 frame,
1950 observations: Vec::new(),
1951 };
1952 map.keyframes.insert(frame_id, kf);
1953 }
1954 map
1955 }
1956
1957 #[test]
1958 fn trigger_blocked_until_keyframe_threshold_is_met() {
1959 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
1960 min_keyframes: 5,
1961 min_translation_meters: 0.0,
1962 ..MotionBasedViInitializerConfig::default()
1963 });
1964 for i in 0..4 {
1965 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
1966 }
1967 assert!(!init.is_ready(), "fewer keyframes than the threshold");
1968 let mut map = build_constant_velocity_map(4);
1969 let seed = synthetic_seed();
1970 let err = init
1971 .try_initialize(&mut map, &[], &seed)
1972 .expect_err("threshold not met");
1973 match err {
1974 MotionBasedViRejectionReason::InsufficientKeyframes { have, need } => {
1975 assert_eq!(have, 4);
1976 assert_eq!(need, 5);
1977 }
1978 other => panic!("unexpected rejection: {other:?}"),
1979 }
1980 }
1981
1982 #[test]
1983 fn trigger_blocked_until_translation_threshold_is_met() {
1984 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
1985 min_keyframes: 3,
1986 min_translation_meters: 5.0,
1987 ..MotionBasedViInitializerConfig::default()
1988 });
1989 init.register_keyframe(1, Point3::new(0.0, 0.0, 0.0));
1990 init.register_keyframe(2, Point3::new(1.0, 0.0, 0.0));
1991 init.register_keyframe(3, Point3::new(2.0, 0.0, 0.0));
1992 assert_eq!(init.keyframes_observed(), 3);
1993 assert!(
1994 (init.cumulative_translation_meters() - 2.0).abs() < 1e-12,
1995 "cumulative_translation tracks chain length, not endpoint distance"
1996 );
1997 assert!(!init.is_ready());
1998 let mut map = build_constant_velocity_map(3);
1999 let seed = synthetic_seed();
2000 let err = init
2001 .try_initialize(&mut map, &[], &seed)
2002 .expect_err("translation threshold not met");
2003 match err {
2004 MotionBasedViRejectionReason::InsufficientTranslation { have, need } => {
2005 assert!((have - 2.0).abs() < 1e-12);
2006 assert!((need - 5.0).abs() < 1e-12);
2007 }
2008 other => panic!("unexpected rejection: {other:?}"),
2009 }
2010 }
2011
2012 #[test]
2013 fn re_registering_same_keyframe_does_not_double_count_translation() {
2014 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig::default());
2015 init.register_keyframe(1, Point3::new(0.0, 0.0, 0.0));
2016 init.register_keyframe(2, Point3::new(1.0, 0.0, 0.0));
2017 init.register_keyframe(2, Point3::new(1.5, 0.0, 0.0));
2018 assert_eq!(init.keyframes_observed(), 2);
2019 assert!((init.cumulative_translation_meters() - 1.0).abs() < 1e-12);
2023 }
2024
2025 #[test]
2026 fn no_usable_factor_is_reported_distinctly_from_solver_failure() {
2027 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2028 min_keyframes: 3,
2029 min_translation_meters: 1.0,
2030 ..MotionBasedViInitializerConfig::default()
2031 });
2032 for i in 0..3 {
2033 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2034 }
2035 assert!(init.is_ready());
2036 let mut map = build_constant_velocity_map(3);
2037 let seed = synthetic_seed();
2038 let err = init
2039 .try_initialize(&mut map, &[], &seed)
2040 .expect_err("no factors registered");
2041 match err {
2042 MotionBasedViRejectionReason::NoUsableImuFactors => {}
2043 other => panic!("unexpected rejection: {other:?}"),
2044 }
2045 }
2046
2047 #[test]
2048 fn successful_solve_is_cached_and_reset_re_arms() {
2049 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2050 min_keyframes: 3,
2051 min_translation_meters: 1.0,
2052 ..MotionBasedViInitializerConfig::default()
2053 });
2054 let gravity = init.config().gravity_world;
2055 for i in 0..3 {
2056 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2057 }
2058 let mut map = build_constant_velocity_map(3);
2059 let map_before = map.clone();
2060 let seed = synthetic_seed();
2061 let factors = vec![
2062 no_acceleration_factor(1, 2, 1.0, gravity),
2063 no_acceleration_factor(2, 3, 1.0, gravity),
2064 ];
2065
2066 let result = init
2067 .try_initialize(&mut map, &factors, &seed)
2068 .expect("VIBA1 must succeed on synthetic constant-velocity stream")
2069 .clone();
2070 assert_eq!(
2071 map, map_before,
2072 "inertial-only initialization must keep the visual trajectory fixed"
2073 );
2074 assert_eq!(result.keyframe_ids, vec![1, 2, 3]);
2075 assert_eq!(result.imu_factors_used, 2);
2076 assert!((result.scale - 1.0).abs() < 1e-12);
2077 assert!((result.trigger_translation_meters - 2.0).abs() < 1e-12);
2078 for kf_id in [1u64, 2, 3] {
2082 assert!(result.keyframe_states.contains_key(&kf_id));
2083 }
2084 assert!(result.ba_result.final_cost <= result.ba_result.initial_cost + 1e-9);
2085 match init.status() {
2086 MotionBasedViInitializationStatus::Initialised { .. } => {}
2087 other => panic!("expected Initialised, got {other:?}"),
2088 }
2089
2090 let cached = init.try_initialize(&mut map, &factors, &seed).unwrap();
2092 assert_eq!(cached.keyframe_ids, result.keyframe_ids);
2093
2094 init.reset();
2097 assert_eq!(init.keyframes_observed(), 0);
2098 assert!((init.cumulative_translation_meters() - 0.0).abs() < 1e-12);
2099 match init.status() {
2100 MotionBasedViInitializationStatus::Waiting {
2101 keyframes_observed,
2102 cumulative_translation_meters,
2103 ..
2104 } => {
2105 assert_eq!(keyframes_observed, 0);
2106 assert!(cumulative_translation_meters.abs() < 1e-12);
2107 }
2108 other => panic!("expected Waiting after reset, got {other:?}"),
2109 }
2110 }
2111
2112 #[test]
2113 fn stereo_stationary_replay_is_identity() {
2114 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2119 min_keyframes: 3,
2120 min_translation_meters: 0.0,
2121 ..MotionBasedViInitializerConfig::default()
2122 });
2123 let gravity = init.config().gravity_world;
2124 for i in 0..3 {
2125 init.register_keyframe((i as u64) + 1, Point3::new(0.0, 0.0, 0.0));
2126 }
2127 let mut map = VisualMap::new();
2128 let camera = pinhole_camera();
2129 map.cameras.insert(camera.id, camera.clone());
2130 for i in 0..3 {
2131 let pose = pose_at_world_center(Vector3::zeros());
2132 let frame_id = (i as u64) + 1;
2133 let mut frame = Frame::new(frame_id, camera.id);
2134 frame.pose = Some(pose);
2135 let kf = Keyframe {
2136 frame,
2137 observations: Vec::new(),
2138 };
2139 map.keyframes.insert(frame_id, kf);
2140 }
2141 let seed = synthetic_seed();
2142 let factors = vec![
2143 no_acceleration_factor(1, 2, 0.1, gravity),
2144 no_acceleration_factor(2, 3, 0.1, gravity),
2145 ];
2146 let result = init
2147 .try_initialize(&mut map, &factors, &seed)
2148 .expect("identity replay should succeed");
2149 for state in result.keyframe_states.values() {
2150 assert!(
2151 state.velocity_world.norm() < 1e-6,
2152 "vel = {:?}",
2153 state.velocity_world
2154 );
2155 assert!(state.bias_gyro.norm() < 1e-6, "b_g = {:?}", state.bias_gyro);
2156 assert!(state.bias_acc.norm() < 1e-6, "b_a = {:?}", state.bias_acc);
2157 }
2158 }
2159
2160 #[test]
2161 fn max_velocity_magnitude_gate_rejects_when_exceeded() {
2162 let mut probe = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2169 min_keyframes: 3,
2170 min_translation_meters: 1.0,
2171 ..MotionBasedViInitializerConfig::default()
2172 });
2173 let gravity = probe.config().gravity_world;
2174 for i in 0..3 {
2175 probe.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2176 }
2177 let mut probe_map = build_constant_velocity_map(3);
2178 let seed = synthetic_seed();
2179 let factors = vec![
2180 no_acceleration_factor(1, 2, 1.0, gravity),
2181 no_acceleration_factor(2, 3, 1.0, gravity),
2182 ];
2183 let probe_result = probe
2184 .try_initialize(&mut probe_map, &factors, &seed)
2185 .expect("probe run must converge")
2186 .clone();
2187 let max_mag = probe_result
2188 .keyframe_states
2189 .values()
2190 .map(|s| s.velocity_world.norm())
2191 .fold(0.0_f64, f64::max);
2192 assert!(
2197 max_mag > 1.0e-12,
2198 "probe max |v| too small to test the gate: {max_mag}"
2199 );
2200
2201 let mut gated = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2202 min_keyframes: 3,
2203 min_translation_meters: 1.0,
2204 max_velocity_magnitude_mps: Some(max_mag / 2.0),
2205 ..MotionBasedViInitializerConfig::default()
2206 });
2207 for i in 0..3 {
2208 gated.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2209 }
2210 let mut gated_map = build_constant_velocity_map(3);
2211 let gated_map_before = gated_map.clone();
2212 let err = gated
2213 .try_initialize(&mut gated_map, &factors, &seed)
2214 .expect_err("velocity gate must reject the LM result");
2215 assert_eq!(
2216 gated_map, gated_map_before,
2217 "a rejected speculative motion-VI solve must not write poses back"
2218 );
2219 match err {
2220 MotionBasedViRejectionReason::VelocityOutOfRange {
2221 kf_id,
2222 magnitude_mps,
2223 limit_mps,
2224 } => {
2225 assert!([1u64, 2, 3].contains(&kf_id), "kf_id = {kf_id}");
2226 assert!(magnitude_mps > limit_mps);
2227 assert!((limit_mps - max_mag / 2.0).abs() < 1.0e-12);
2228 }
2229 other => panic!("expected VelocityOutOfRange, got {other:?}"),
2230 }
2231 match gated.status() {
2234 MotionBasedViInitializationStatus::Waiting { last_rejection, .. } => {
2235 assert!(matches!(
2236 last_rejection,
2237 Some(MotionBasedViRejectionReason::VelocityOutOfRange { .. })
2238 ));
2239 }
2240 other => panic!("expected Waiting after gate rejection, got {other:?}"),
2241 }
2242 }
2243
2244 #[test]
2245 fn normalized_imu_nis_gate_rejects_inconsistent_promotion() {
2246 let mut probe = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2247 min_keyframes: 3,
2248 min_translation_meters: 1.0,
2249 ..MotionBasedViInitializerConfig::default()
2250 });
2251 let gravity = probe.config().gravity_world;
2252 for i in 0..3 {
2253 probe.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2254 }
2255 let factors = vec![
2256 no_acceleration_factor(1, 2, 1.0, gravity),
2257 no_acceleration_factor(2, 3, 1.0, gravity),
2258 ];
2259 let seed = synthetic_seed();
2260 let mut probe_map = build_constant_velocity_map(3);
2261 let observed = probe
2262 .try_initialize(&mut probe_map, &factors, &seed)
2263 .expect("probe solve")
2264 .final_cost_breakdown
2265 .imu_normalized_squared_residual_per_dof
2266 .expect("IMU factors produce a normalized residual");
2267 assert!(observed.is_finite() && observed > 0.0);
2268
2269 let limit = observed * 0.5;
2270 let mut gated = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2271 min_keyframes: 3,
2272 min_translation_meters: 1.0,
2273 max_final_imu_nis_per_dof: Some(limit),
2274 ..MotionBasedViInitializerConfig::default()
2275 });
2276 for i in 0..3 {
2277 gated.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2278 }
2279 let mut gated_map = build_constant_velocity_map(3);
2280 let map_before = gated_map.clone();
2281 let error = gated
2282 .try_initialize(&mut gated_map, &factors, &seed)
2283 .expect_err("NIS gate must reject the inconsistent promotion");
2284 assert_eq!(gated_map, map_before);
2285 assert!(matches!(
2286 error,
2287 MotionBasedViRejectionReason::ImuNisOutOfRange {
2288 normalized_nis_per_dof,
2289 rotation_residual_rms_rad: _,
2290 velocity_residual_rms_mps: _,
2291 position_residual_rms_meters: _,
2292 limit: rejected_limit,
2293 } if (normalized_nis_per_dof - observed).abs() < 1.0e-9
2294 && (rejected_limit - limit).abs() < 1.0e-12
2295 ));
2296 }
2297
2298 #[test]
2299 fn physical_imu_residual_gate_rejects_inconsistent_promotion() {
2300 let mut probe = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2301 min_keyframes: 3,
2302 min_translation_meters: 1.0,
2303 ..MotionBasedViInitializerConfig::default()
2304 });
2305 let gravity = probe.config().gravity_world;
2306 for i in 0..3 {
2307 probe.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2308 }
2309 let factors = vec![
2310 no_acceleration_factor(1, 2, 1.0, gravity),
2311 no_acceleration_factor(2, 3, 1.0, gravity),
2312 ];
2313 let seed = synthetic_seed();
2314 let mut probe_map = build_constant_velocity_map(3);
2315 let observed = probe
2316 .try_initialize(&mut probe_map, &factors, &seed)
2317 .expect("probe solve")
2318 .final_cost_breakdown
2319 .imu_velocity_residual_rms_mps
2320 .expect("velocity residual");
2321 assert!(observed.is_finite() && observed > 0.0);
2322
2323 let limit = observed * 0.5;
2324 let mut gated = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2325 min_keyframes: 3,
2326 min_translation_meters: 1.0,
2327 max_final_imu_velocity_residual_rms_mps: Some(limit),
2328 ..MotionBasedViInitializerConfig::default()
2329 });
2330 for i in 0..3 {
2331 gated.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2332 }
2333 let mut gated_map = build_constant_velocity_map(3);
2334 let map_before = gated_map.clone();
2335 let error = gated
2336 .try_initialize(&mut gated_map, &factors, &seed)
2337 .expect_err("physical residual gate must reject promotion");
2338 assert_eq!(gated_map, map_before);
2339 assert!(matches!(
2340 error,
2341 MotionBasedViRejectionReason::ImuRawResidualOutOfRange {
2342 velocity_residual_rms_mps: Some(value),
2343 max_velocity_residual_rms_mps: Some(rejected_limit),
2344 ..
2345 } if (value - observed).abs() < 1.0e-9
2346 && (rejected_limit - limit).abs() < 1.0e-12
2347 ));
2348 }
2349
2350 #[test]
2351 fn max_velocity_magnitude_gate_passes_when_under_limit() {
2352 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2355 min_keyframes: 3,
2356 min_translation_meters: 1.0,
2357 max_velocity_magnitude_mps: Some(1.0e6),
2358 ..MotionBasedViInitializerConfig::default()
2359 });
2360 let gravity = init.config().gravity_world;
2361 for i in 0..3 {
2362 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2363 }
2364 let mut map = build_constant_velocity_map(3);
2365 let seed = synthetic_seed();
2366 let factors = vec![
2367 no_acceleration_factor(1, 2, 1.0, gravity),
2368 no_acceleration_factor(2, 3, 1.0, gravity),
2369 ];
2370 let _ = init
2371 .try_initialize(&mut map, &factors, &seed)
2372 .expect("generous limit must accept the LM result");
2373 match init.status() {
2374 MotionBasedViInitializationStatus::Initialised { .. } => {}
2375 other => panic!("expected Initialised, got {other:?}"),
2376 }
2377 }
2378
2379 #[test]
2380 fn gyro_bias_gate_rejects_transactionally() {
2381 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2382 min_keyframes: 3,
2383 min_translation_meters: 1.0,
2384 max_gyro_bias_magnitude_rad_s: Some(0.05),
2385 ..MotionBasedViInitializerConfig::default()
2386 });
2387 let gravity = init.config().gravity_world;
2388 for i in 0..3 {
2389 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2390 }
2391 let mut map = build_constant_velocity_map(3);
2392 let map_before = map.clone();
2393 let factors = vec![
2394 no_acceleration_factor(1, 2, 1.0, gravity),
2395 no_acceleration_factor(2, 3, 1.0, gravity),
2396 ];
2397 let err = init
2398 .try_initialize_with_bias_seed(
2399 &mut map,
2400 &factors,
2401 Vector3::new(0.1, 0.0, 0.0),
2402 Vector3::zeros(),
2403 )
2404 .expect_err("anchored gyro bias must exceed the configured gate");
2405 assert_eq!(map, map_before, "rejected solve must not mutate the map");
2406 assert!(matches!(
2407 err,
2408 MotionBasedViRejectionReason::GyroBiasOutOfRange {
2409 magnitude_rad_s,
2410 limit_rad_s,
2411 ..
2412 } if magnitude_rad_s > limit_rad_s && (limit_rad_s - 0.05).abs() < 1.0e-12
2413 ));
2414 }
2415
2416 #[test]
2417 fn accel_bias_gate_rejects_transactionally() {
2418 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2419 min_keyframes: 3,
2420 min_translation_meters: 1.0,
2421 max_accel_bias_magnitude_mps2: Some(1.0),
2422 ..MotionBasedViInitializerConfig::default()
2423 });
2424 let gravity = init.config().gravity_world;
2425 for i in 0..3 {
2426 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2427 }
2428 let mut map = build_constant_velocity_map(3);
2429 let map_before = map.clone();
2430 let factors = vec![
2431 no_acceleration_factor(1, 2, 1.0, gravity),
2432 no_acceleration_factor(2, 3, 1.0, gravity),
2433 ];
2434 let err = init
2435 .try_initialize_with_bias_seed(
2436 &mut map,
2437 &factors,
2438 Vector3::zeros(),
2439 Vector3::new(2.0, 0.0, 0.0),
2440 )
2441 .expect_err("anchored accel bias must exceed the configured gate");
2442 assert_eq!(map, map_before, "rejected solve must not mutate the map");
2443 assert!(matches!(
2444 err,
2445 MotionBasedViRejectionReason::AccelBiasOutOfRange {
2446 magnitude_mps2,
2447 limit_mps2,
2448 ..
2449 } if magnitude_mps2 > limit_mps2 && (limit_mps2 - 1.0).abs() < 1.0e-12
2450 ));
2451 }
2452
2453 #[test]
2455 fn so3_identity_is_quaternion_identity() {
2456 let r = SO3::identity();
2457 let q = r.quaternion();
2458 assert!((q.w - 1.0).abs() < 1e-12);
2459 assert!((q.i.abs() + q.j.abs() + q.k.abs()) < 1e-12);
2460 }
2461
2462 #[test]
2467 fn viba2_handoff_runs_when_configured_and_reports_scale_history() {
2468 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2469 min_keyframes: 3,
2470 min_translation_meters: 1.0,
2471 gravity_world: Vector3::zeros(),
2472 viba2: Some(Viba2Config {
2473 initial_scale: 1.0,
2474 recover_scale: true,
2475 max_outer_iterations: 3,
2476 scale_tolerance: 1.0e-4,
2477 ..Viba2Config::default()
2478 }),
2479 ..MotionBasedViInitializerConfig::default()
2480 });
2481 let gravity = init.config().gravity_world;
2482 for i in 0..3 {
2483 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2484 }
2485 let mut map = VisualMap::new();
2486 let camera = pinhole_camera();
2487 map.cameras.insert(camera.id, camera.clone());
2488 for i in 0..3 {
2489 let center = Vector3::new(i as f64, 0.0, 0.0);
2490 let pose = pose_at_world_center(center);
2491 let frame_id = (i as u64) + 1;
2492 let mut frame = Frame::new(frame_id, camera.id);
2493 frame.pose = Some(pose);
2494 let kf = Keyframe {
2495 frame,
2496 observations: Vec::new(),
2497 };
2498 map.keyframes.insert(frame_id, kf);
2499 }
2500 let seed = synthetic_seed();
2501 let factors = vec![
2502 no_acceleration_factor(1, 2, 1.0, gravity),
2503 no_acceleration_factor(2, 3, 1.0, gravity),
2504 ];
2505 let result = init
2506 .try_initialize(&mut map, &factors, &seed)
2507 .expect("VIBA2 path should succeed");
2508 assert!(result.scale.is_finite());
2515 assert!(result.viba2_iterations_run >= 1);
2516 assert!(!result.scale_history.is_empty());
2517 assert!((result.scale_history[0] - 1.0).abs() < 1e-12);
2518 }
2519
2520 #[test]
2521 fn no_viba2_config_keeps_scale_history_empty() {
2522 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2523 min_keyframes: 3,
2524 min_translation_meters: 1.0,
2525 ..MotionBasedViInitializerConfig::default()
2526 });
2527 let gravity = init.config().gravity_world;
2528 for i in 0..3 {
2529 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2530 }
2531 let mut map = VisualMap::new();
2532 let camera = pinhole_camera();
2533 map.cameras.insert(camera.id, camera.clone());
2534 for i in 0..3 {
2535 let pose = pose_at_world_center(Vector3::new(i as f64, 0.0, 0.0));
2536 let frame_id = (i as u64) + 1;
2537 let mut frame = Frame::new(frame_id, camera.id);
2538 frame.pose = Some(pose);
2539 let kf = Keyframe {
2540 frame,
2541 observations: Vec::new(),
2542 };
2543 map.keyframes.insert(frame_id, kf);
2544 }
2545 let seed = synthetic_seed();
2546 let factors = vec![
2547 no_acceleration_factor(1, 2, 1.0, gravity),
2548 no_acceleration_factor(2, 3, 1.0, gravity),
2549 ];
2550 let result = init
2551 .try_initialize(&mut map, &factors, &seed)
2552 .expect("VIBA1 path should succeed");
2553 assert!((result.scale - 1.0).abs() < 1e-12);
2554 assert!(result.scale_history.is_empty());
2555 assert_eq!(result.viba2_iterations_run, 0);
2556 }
2557
2558 #[test]
2563 fn legacy_path_without_bias_release_schedule_reports_bias_released_true() {
2564 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2565 min_keyframes: 3,
2566 min_translation_meters: 1.0,
2567 ..MotionBasedViInitializerConfig::default()
2568 });
2569 assert!(init.config().bias_release.is_none());
2570 let gravity = init.config().gravity_world;
2571 for i in 0..3 {
2572 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2573 }
2574 let mut map = build_constant_velocity_map(3);
2575 let seed = synthetic_seed();
2576 let factors = vec![
2577 no_acceleration_factor(1, 2, 1.0, gravity),
2578 no_acceleration_factor(2, 3, 1.0, gravity),
2579 ];
2580 let result = init
2581 .try_initialize(&mut map, &factors, &seed)
2582 .expect("legacy path must succeed");
2583 assert!(
2584 result.bias_released,
2585 "legacy path (bias_release=None) must report bias_released=true"
2586 );
2587 assert!(
2588 init.velocity_stage_result().is_none(),
2589 "legacy path never populates the velocity stage"
2590 );
2591 match init.status() {
2592 MotionBasedViInitializationStatus::Initialised { .. } => {}
2593 other => panic!("expected terminal Initialised, got {other:?}"),
2594 }
2595 }
2596
2597 #[test]
2598 fn bias_release_schedule_stage_a_fires_then_awaits_release_gate() {
2599 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2603 min_keyframes: 3,
2604 min_translation_meters: 1.0,
2605 bias_release: Some(BiasReleaseSchedule {
2606 min_keyframes: 5,
2607 min_translation_meters: 3.0,
2608 }),
2609 ..MotionBasedViInitializerConfig::default()
2610 });
2611 let gravity = init.config().gravity_world;
2612 for i in 0..3 {
2613 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2614 }
2615 assert!(init.is_ready(), "base gates must be satisfied");
2616 let mut map = build_constant_velocity_map(3);
2617 let seed = synthetic_seed();
2618 let factors = vec![
2619 no_acceleration_factor(1, 2, 1.0, gravity),
2620 no_acceleration_factor(2, 3, 1.0, gravity),
2621 ];
2622
2623 let stage_a = init
2624 .try_initialize(&mut map, &factors, &seed)
2625 .expect("Stage A must fire once the base gates are met")
2626 .clone();
2627 assert!(!stage_a.bias_released, "Stage A must not release bias");
2628 for state in stage_a.keyframe_states.values() {
2629 assert!(
2630 (state.bias_gyro - seed.bias_gyro).norm() < 1.0e-12,
2631 "Stage A must not move gyro bias off the seed"
2632 );
2633 assert!(
2634 (state.bias_acc - seed.bias_acc).norm() < 1.0e-12,
2635 "Stage A must not move accel bias off the seed"
2636 );
2637 }
2638 assert!(init.velocity_stage_result().is_some());
2639 match init.status() {
2640 MotionBasedViInitializationStatus::Waiting {
2641 velocity_stage_completed,
2642 ..
2643 } => assert!(
2644 velocity_stage_completed,
2645 "status() must report the completed velocity stage"
2646 ),
2647 other => panic!("expected non-terminal Waiting after Stage A, got {other:?}"),
2648 }
2649
2650 let err = init
2653 .try_initialize(&mut map, &factors, &seed)
2654 .expect_err("release gate not yet met");
2655 match err {
2656 MotionBasedViRejectionReason::AwaitingBiasReleaseExcitation {
2657 have_keyframes,
2658 need_keyframes,
2659 have_translation_meters,
2660 need_translation_meters,
2661 } => {
2662 assert_eq!(have_keyframes, 3);
2663 assert_eq!(need_keyframes, 5);
2664 assert!((have_translation_meters - 2.0).abs() < 1.0e-12);
2665 assert!((need_translation_meters - 3.0).abs() < 1.0e-12);
2666 }
2667 other => panic!("expected AwaitingBiasReleaseExcitation, got {other:?}"),
2668 }
2669 }
2670
2671 #[test]
2672 fn bias_release_schedule_stage_b_fires_once_gate_is_met() {
2673 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2674 min_keyframes: 3,
2675 min_translation_meters: 1.0,
2676 bias_release: Some(BiasReleaseSchedule {
2677 min_keyframes: 5,
2678 min_translation_meters: 3.0,
2679 }),
2680 ..MotionBasedViInitializerConfig::default()
2681 });
2682 let gravity = init.config().gravity_world;
2683 for i in 0..3 {
2684 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2685 }
2686 let mut map = build_constant_velocity_map(5);
2687 let seed = synthetic_seed();
2688 let factors = vec![
2689 no_acceleration_factor(1, 2, 1.0, gravity),
2690 no_acceleration_factor(2, 3, 1.0, gravity),
2691 no_acceleration_factor(3, 4, 1.0, gravity),
2692 no_acceleration_factor(4, 5, 1.0, gravity),
2693 ];
2694
2695 let stage_a = init
2696 .try_initialize(&mut map, &factors, &seed)
2697 .expect("Stage A must fire")
2698 .clone();
2699 assert!(!stage_a.bias_released);
2700
2701 init.register_keyframe(4, Point3::new(3.0, 0.0, 0.0));
2704 init.register_keyframe(5, Point3::new(4.0, 0.0, 0.0));
2705 assert_eq!(init.keyframes_observed(), 5);
2706 assert!((init.cumulative_translation_meters() - 4.0).abs() < 1.0e-9);
2707
2708 let stage_b = init
2709 .try_initialize(&mut map, &factors, &seed)
2710 .expect("Stage B must fire once the release gate is met")
2711 .clone();
2712 assert!(
2713 stage_b.bias_released,
2714 "Stage B must release bias like the legacy path"
2715 );
2716 match init.status() {
2717 MotionBasedViInitializationStatus::Initialised { .. } => {}
2718 other => panic!("expected terminal Initialised after Stage B, got {other:?}"),
2719 }
2720 }
2721
2722 #[test]
2723 fn reset_clears_velocity_stage() {
2724 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2725 min_keyframes: 3,
2726 min_translation_meters: 1.0,
2727 bias_release: Some(BiasReleaseSchedule {
2728 min_keyframes: 5,
2729 min_translation_meters: 3.0,
2730 }),
2731 ..MotionBasedViInitializerConfig::default()
2732 });
2733 let gravity = init.config().gravity_world;
2734 for i in 0..3 {
2735 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2736 }
2737 let mut map = build_constant_velocity_map(3);
2738 let seed = synthetic_seed();
2739 let factors = vec![
2740 no_acceleration_factor(1, 2, 1.0, gravity),
2741 no_acceleration_factor(2, 3, 1.0, gravity),
2742 ];
2743 init.try_initialize(&mut map, &factors, &seed)
2744 .expect("Stage A must fire");
2745 assert!(init.velocity_stage_result().is_some());
2746
2747 init.reset();
2748 assert!(
2749 init.velocity_stage_result().is_none(),
2750 "reset() must clear the cached velocity stage"
2751 );
2752 match init.status() {
2753 MotionBasedViInitializationStatus::Waiting {
2754 velocity_stage_completed,
2755 ..
2756 } => assert!(!velocity_stage_completed),
2757 other => panic!("expected Waiting after reset, got {other:?}"),
2758 }
2759 }
2760
2761 mod gravity_velocity_alignment {
2770 use super::*;
2771
2772 #[test]
2773 fn recovers_off_axis_gravity_and_velocities_from_a_consistent_window() {
2774 let true_gravity = Vector3::new(6.54, -3.27, 6.54); let velocity = Vector3::new(1.2, -0.7, 0.3);
2783 let map = build_map_at_velocity(5, 1.0, velocity);
2784 let ids: Vec<u64> = (1..=5).collect();
2785 let factors = vec![
2786 no_acceleration_factor(1, 2, 1.0, true_gravity),
2787 no_acceleration_factor(2, 3, 1.0, true_gravity),
2788 no_acceleration_factor(3, 4, 1.0, true_gravity),
2789 no_acceleration_factor(4, 5, 1.0, true_gravity),
2790 ];
2791 let alignment = estimate_gravity_and_velocities(
2792 &map,
2793 &ids,
2794 &factors,
2795 Vector3::zeros(),
2796 Vector3::zeros(),
2797 9.81,
2798 )
2799 .expect("well-conditioned, exactly-consistent window must align");
2800 assert!(
2801 (alignment.gravity_world - true_gravity).norm() < 1.0e-6,
2802 "g_est = {:?}",
2803 alignment.gravity_world
2804 );
2805 assert!(
2806 (alignment.raw_gravity_norm - 9.81).abs() < 1.0e-6,
2807 "raw_gravity_norm = {}",
2808 alignment.raw_gravity_norm
2809 );
2810 for (kf_id, v) in &alignment.velocities {
2811 assert!(
2812 (v - velocity).norm() < 1.0e-6,
2813 "kf {kf_id}: v_est = {v:?}, expected {velocity:?}"
2814 );
2815 }
2816 }
2817
2818 #[test]
2819 fn degenerate_window_with_a_single_factor_returns_none() {
2820 let velocity = Vector3::new(1.0, 0.0, 0.0);
2827 let map = build_map_at_velocity(2, 1.0, velocity);
2828 let ids: Vec<u64> = vec![1, 2];
2829 let factors = vec![no_acceleration_factor(
2830 1,
2831 2,
2832 1.0,
2833 Vector3::new(0.0, 9.81, 0.0),
2834 )];
2835 let alignment = estimate_gravity_and_velocities(
2836 &map,
2837 &ids,
2838 &factors,
2839 Vector3::zeros(),
2840 Vector3::zeros(),
2841 9.81,
2842 );
2843 assert!(
2844 alignment.is_none(),
2845 "a single-factor window must be reported degenerate"
2846 );
2847 }
2848
2849 #[test]
2850 fn norm_constrained_refinement_pins_the_magnitude_when_raw_solve_drifts() {
2851 let true_gravity = Vector3::new(6.54, -3.27, 6.54); let velocity = Vector3::new(1.2, -0.7, 0.3);
2860 let map = build_map_at_velocity(4, 1.0, velocity);
2861 let ids: Vec<u64> = (1..=4).collect();
2862 let mut factors = vec![
2863 no_acceleration_factor(1, 2, 1.0, true_gravity),
2864 no_acceleration_factor(2, 3, 1.0, true_gravity),
2865 no_acceleration_factor(3, 4, 1.0, true_gravity),
2866 ];
2867 factors[1].delta.delta_velocity += Vector3::new(0.35, -0.2, 0.15);
2868
2869 let alignment = estimate_gravity_and_velocities(
2870 &map,
2871 &ids,
2872 &factors,
2873 Vector3::zeros(),
2874 Vector3::zeros(),
2875 9.81,
2876 )
2877 .expect("a mild inconsistency must still be solvable");
2878 assert!(
2879 (alignment.raw_gravity_norm - 9.81).abs() > 1.0e-6,
2880 "fixture must actually perturb the unconstrained solve off the true magnitude, raw = {}",
2881 alignment.raw_gravity_norm
2882 );
2883 assert!(
2884 (alignment.gravity_world.norm() - 9.81).abs() < 1.0e-9,
2885 "the constrained estimate must be pinned to the expected magnitude, got {}",
2886 alignment.gravity_world.norm()
2887 );
2888 assert!(
2889 alignment.mean_residual_after > 0.0,
2890 "an inconsistent window must leave a nonzero residual"
2891 );
2892 }
2893 }
2894
2895 mod estimate_gravity_initializer {
2898 use super::*;
2899
2900 #[test]
2901 fn recovers_from_rotated_true_gravity_where_the_legacy_path_rejects() {
2902 let true_gravity = Vector3::new(0.0, 0.0, 9.81);
2910 let assumed_gravity = Vector3::new(0.0, 9.81, 0.0);
2911 let factors = vec![
2912 no_acceleration_factor_with_assumed_gravity(
2913 1,
2914 2,
2915 1.0,
2916 true_gravity,
2917 assumed_gravity,
2918 ),
2919 no_acceleration_factor_with_assumed_gravity(
2920 2,
2921 3,
2922 1.0,
2923 true_gravity,
2924 assumed_gravity,
2925 ),
2926 no_acceleration_factor_with_assumed_gravity(
2927 3,
2928 4,
2929 1.0,
2930 true_gravity,
2931 assumed_gravity,
2932 ),
2933 no_acceleration_factor_with_assumed_gravity(
2934 4,
2935 5,
2936 1.0,
2937 true_gravity,
2938 assumed_gravity,
2939 ),
2940 ];
2941 let seed = synthetic_seed();
2942
2943 let mut probe = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2949 min_keyframes: 3,
2950 min_translation_meters: 1.0,
2951 gravity_world: assumed_gravity,
2952 ..MotionBasedViInitializerConfig::default()
2953 });
2954 for i in 0..5 {
2955 probe.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2956 }
2957 let mut probe_map = build_constant_velocity_map(5);
2958 let probe_residual = probe
2959 .try_initialize(&mut probe_map, &factors, &seed)
2960 .expect("legacy solve still converges; only the gate is missing here")
2961 .final_cost_breakdown
2962 .imu_velocity_residual_rms_mps
2963 .expect("IMU factors produce a velocity residual");
2964 assert!(
2965 probe_residual > 0.5,
2966 "a 90-degree gravity misalignment should leave a substantial residual, got {probe_residual}"
2967 );
2968 let gate = probe_residual * 0.5;
2969
2970 let mut legacy = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2973 min_keyframes: 3,
2974 min_translation_meters: 1.0,
2975 gravity_world: assumed_gravity,
2976 max_final_imu_velocity_residual_rms_mps: Some(gate),
2977 ..MotionBasedViInitializerConfig::default()
2978 });
2979 for i in 0..5 {
2980 legacy.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2981 }
2982 let mut legacy_map = build_constant_velocity_map(5);
2983 let err = legacy
2984 .try_initialize(&mut legacy_map, &factors, &seed)
2985 .expect_err(
2986 "misaligned gravity assumption must be rejected by the raw-residual gate",
2987 );
2988 assert!(
2989 matches!(
2990 err,
2991 MotionBasedViRejectionReason::ImuRawResidualOutOfRange { .. }
2992 ),
2993 "unexpected rejection: {err:?}"
2994 );
2995
2996 let mut estimated = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2999 min_keyframes: 3,
3000 min_translation_meters: 1.0,
3001 gravity_world: assumed_gravity,
3002 estimate_gravity: true,
3003 max_final_imu_velocity_residual_rms_mps: Some(gate),
3004 ..MotionBasedViInitializerConfig::default()
3005 });
3006 for i in 0..5 {
3007 estimated.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3008 }
3009 let mut estimated_map = build_constant_velocity_map(5);
3010 let result = estimated
3011 .try_initialize(&mut estimated_map, &factors, &seed)
3012 .expect("gravity estimation must recover enough to clear the same gate");
3013 let g_est = result
3014 .estimated_gravity_world
3015 .expect("estimate_gravity=true must report the recovered vector");
3016 assert!(
3017 (g_est - true_gravity).norm() < 0.05,
3018 "recovered gravity {g_est:?} should match the true {true_gravity:?}"
3019 );
3020 }
3021
3022 #[test]
3023 fn norm_gate_rejects_an_implausible_recovered_magnitude() {
3024 let true_gravity = Vector3::new(0.0, 0.0, 3.0);
3031 let assumed_gravity = Vector3::new(0.0, 9.81, 0.0);
3032 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3033 min_keyframes: 3,
3034 min_translation_meters: 1.0,
3035 gravity_world: assumed_gravity,
3036 estimate_gravity: true,
3037 ..MotionBasedViInitializerConfig::default()
3038 });
3039 for i in 0..3 {
3040 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3041 }
3042 let mut map = build_constant_velocity_map(3);
3043 let seed = synthetic_seed();
3044 let factors = vec![
3045 no_acceleration_factor_with_assumed_gravity(
3046 1,
3047 2,
3048 1.0,
3049 true_gravity,
3050 assumed_gravity,
3051 ),
3052 no_acceleration_factor_with_assumed_gravity(
3053 2,
3054 3,
3055 1.0,
3056 true_gravity,
3057 assumed_gravity,
3058 ),
3059 ];
3060 let err = init
3061 .try_initialize(&mut map, &factors, &seed)
3062 .expect_err("implausible recovered magnitude must be rejected");
3063 match err {
3064 MotionBasedViRejectionReason::GravityEstimateOutOfRange {
3065 raw_norm_mps2,
3066 expected_mps2,
3067 max_deviation_ratio,
3068 } => {
3069 assert!(
3070 (raw_norm_mps2 - 3.0).abs() < 1.0e-6,
3071 "raw_norm_mps2 = {raw_norm_mps2}"
3072 );
3073 assert!((expected_mps2 - 9.81).abs() < 1.0e-9);
3074 assert!((max_deviation_ratio - 0.3).abs() < 1.0e-9);
3075 }
3076 other => panic!("expected GravityEstimateOutOfRange, got {other:?}"),
3077 }
3078 }
3079
3080 #[test]
3081 fn degenerate_when_no_factors_connect_the_window() {
3082 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3083 min_keyframes: 3,
3084 min_translation_meters: 1.0,
3085 estimate_gravity: true,
3086 ..MotionBasedViInitializerConfig::default()
3087 });
3088 for i in 0..3 {
3089 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3090 }
3091 let mut map = build_constant_velocity_map(3);
3092 let seed = synthetic_seed();
3093 let err = init
3094 .try_initialize(&mut map, &[], &seed)
3095 .expect_err("no factors means the alignment cannot condition at all");
3096 assert!(matches!(
3097 err,
3098 MotionBasedViRejectionReason::GravityEstimateDegenerate
3099 ));
3100 }
3101
3102 #[test]
3103 fn composes_with_staged_bias_release_stage_a() {
3104 let true_gravity = Vector3::new(0.0, 0.0, 9.81);
3110 let assumed_gravity = Vector3::new(0.0, 9.81, 0.0);
3111 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3112 min_keyframes: 3,
3113 min_translation_meters: 1.0,
3114 gravity_world: assumed_gravity,
3115 estimate_gravity: true,
3116 bias_release: Some(BiasReleaseSchedule {
3117 min_keyframes: 5,
3118 min_translation_meters: 3.0,
3119 }),
3120 ..MotionBasedViInitializerConfig::default()
3121 });
3122 for i in 0..3 {
3123 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3124 }
3125 let mut map = build_constant_velocity_map(3);
3126 let seed = synthetic_seed();
3127 let factors = vec![
3128 no_acceleration_factor_with_assumed_gravity(
3129 1,
3130 2,
3131 1.0,
3132 true_gravity,
3133 assumed_gravity,
3134 ),
3135 no_acceleration_factor_with_assumed_gravity(
3136 2,
3137 3,
3138 1.0,
3139 true_gravity,
3140 assumed_gravity,
3141 ),
3142 ];
3143 let result = init
3144 .try_initialize(&mut map, &factors, &seed)
3145 .expect("Stage A must fire even with gravity estimation enabled")
3146 .clone();
3147 assert!(!result.bias_released, "Stage A must not release bias");
3148 let g_est = result
3149 .estimated_gravity_world
3150 .expect("estimate must be reported on a Stage A result too");
3151 assert!(
3152 (g_est - true_gravity).norm() < 0.05,
3153 "recovered gravity {g_est:?} should match the true {true_gravity:?}"
3154 );
3155 for state in result.keyframe_states.values() {
3156 assert!(
3157 (state.bias_gyro - seed.bias_gyro).norm() < 1.0e-9,
3158 "Stage A must not move gyro bias off the seed even with gravity estimation"
3159 );
3160 assert!(
3161 (state.bias_acc - seed.bias_acc).norm() < 1.0e-9,
3162 "Stage A must not move accel bias off the seed even with gravity estimation"
3163 );
3164 }
3165 }
3166 }
3167
3168 mod gyro_bias_alignment {
3183 use super::*;
3184 use crate::imu_preintegration::ImuPreintegrator;
3185
3186 fn real_integrated_factors_with_constant_gyro_bias(
3194 bias_gyro_true: Vector3<f64>,
3195 steps: usize,
3196 dt: f64,
3197 ) -> Vec<ImuPreintegrationFactor> {
3198 [(1u64, 2u64), (2, 3)]
3199 .into_iter()
3200 .map(|(from_id, to_id)| {
3201 let mut pre =
3202 ImuPreintegrator::new_with_bias(Vector3::zeros(), Vector3::zeros());
3203 for _ in 0..steps {
3204 pre.integrate_sample(bias_gyro_true, Vector3::new(0.0, 9.81, 0.0), dt);
3205 }
3206 ImuPreintegrationFactor {
3207 keyframe_id_from: from_id,
3208 keyframe_id_to: to_id,
3209 delta: pre.delta(),
3210 gravity_world: Vector3::new(0.0, 9.81, 0.0),
3211 weight_position: 1.0,
3212 weight_velocity: 1.0,
3213 weight_rotation: 1.0,
3214 }
3215 })
3216 .collect()
3217 }
3218
3219 #[test]
3220 fn recovers_a_known_constant_bias_through_the_real_preintegrator() {
3221 let bias_gyro_true = Vector3::new(0.0005, -0.0003, 0.0002);
3222 let factors =
3223 real_integrated_factors_with_constant_gyro_bias(bias_gyro_true, 20, 0.001);
3224 let map = build_constant_velocity_map(3);
3225 let ids: Vec<u64> = vec![1, 2, 3];
3226
3227 let alignment = estimate_gyro_bias(&map, &ids, &factors, Vector3::zeros())
3228 .expect("well-conditioned window must align");
3229 assert!(
3230 (alignment.bias_gyro - bias_gyro_true).norm() < 1.0e-6,
3231 "b_g_est = {:?}, b_g_true = {:?}",
3232 alignment.bias_gyro,
3233 bias_gyro_true
3234 );
3235 assert!(
3236 alignment.rotation_residual_rms_before > 0.0,
3237 "an uncorrected constant bias must leave a nonzero residual"
3238 );
3239 assert!(
3240 alignment.rotation_residual_rms_after
3241 < alignment.rotation_residual_rms_before * 1.0e-3,
3242 "rms_before={}, rms_after={}",
3243 alignment.rotation_residual_rms_before,
3244 alignment.rotation_residual_rms_after
3245 );
3246 }
3247
3248 #[test]
3249 fn degenerate_window_with_a_single_factor_returns_none() {
3250 let factors = real_integrated_factors_with_constant_gyro_bias(
3251 Vector3::new(0.001, 0.0, 0.0),
3252 20,
3253 0.001,
3254 );
3255 let single_factor = vec![factors[0].clone()];
3256 let map = build_constant_velocity_map(2);
3257 let ids: Vec<u64> = vec![1, 2];
3258 assert!(
3259 estimate_gyro_bias(&map, &ids, &single_factor, Vector3::zeros()).is_none(),
3260 "a single-factor window must be reported degenerate"
3261 );
3262 }
3263
3264 #[test]
3265 fn real_preintegrator_regression_gyro_bias_then_gravity_recovery() {
3266 let true_gravity = Vector3::new(6.54, -3.27, 6.54); let velocity = Vector3::new(1.2, -0.7, 0.3);
3276 let bias_gyro_true = Vector3::new(0.0005, -0.0003, 0.0002);
3277 let dt_step = 0.001;
3278 let steps = 20;
3279 let window = (steps as f64) * dt_step;
3280 let map = build_map_at_velocity(5, window, velocity);
3281 let ids: Vec<u64> = (1..=5).collect();
3282 let mut factors = Vec::new();
3283 for (from_id, to_id) in [(1u64, 2u64), (2, 3), (3, 4), (4, 5)] {
3284 let mut pre = ImuPreintegrator::new_with_bias(Vector3::zeros(), Vector3::zeros());
3285 for _ in 0..steps {
3286 pre.integrate_sample(bias_gyro_true, -true_gravity, dt_step);
3287 }
3288 factors.push(ImuPreintegrationFactor {
3289 keyframe_id_from: from_id,
3290 keyframe_id_to: to_id,
3291 delta: pre.delta(),
3292 gravity_world: true_gravity,
3293 weight_position: 1.0,
3294 weight_velocity: 1.0,
3295 weight_rotation: 1.0,
3296 });
3297 }
3298
3299 let gyro_alignment = estimate_gyro_bias(&map, &ids, &factors, Vector3::zeros())
3300 .expect("well-conditioned window must align");
3301 assert!(
3302 (gyro_alignment.bias_gyro - bias_gyro_true).norm() < 1.0e-6,
3303 "b_g_est = {:?}",
3304 gyro_alignment.bias_gyro
3305 );
3306
3307 let gravity_alignment = estimate_gravity_and_velocities(
3308 &map,
3309 &ids,
3310 &factors,
3311 gyro_alignment.bias_gyro,
3312 Vector3::zeros(),
3313 9.81,
3314 )
3315 .expect("gravity alignment must still condition well after gyro-bias correction");
3316 assert!(
3317 (gravity_alignment.gravity_world - true_gravity).norm() < 1.0e-4,
3318 "g_est = {:?}",
3319 gravity_alignment.gravity_world
3320 );
3321 }
3322 }
3323
3324 mod estimate_gyro_bias_initializer {
3327 use super::*;
3328
3329 fn no_acceleration_factor_with_gyro_bias(
3340 from_id: u64,
3341 to_id: u64,
3342 delta_t: f64,
3343 gravity: Vector3<f64>,
3344 bias_gyro_true: Vector3<f64>,
3345 ) -> ImuPreintegrationFactor {
3346 let mut delta = ImuPreintegratedDelta::identity();
3347 delta.delta_time = delta_t;
3348 delta.delta_velocity = -gravity * delta_t;
3349 delta.delta_position = -0.5 * gravity * delta_t * delta_t;
3350 delta.delta_rotation =
3351 SO3::from_quaternion(UnitQuaternion::from_scaled_axis(bias_gyro_true * delta_t));
3352 delta.j_rotation_bg = Matrix3::identity() * (-delta_t);
3353 ImuPreintegrationFactor {
3354 keyframe_id_from: from_id,
3355 keyframe_id_to: to_id,
3356 delta,
3357 gravity_world: gravity,
3358 weight_position: 1.0,
3359 weight_velocity: 1.0,
3360 weight_rotation: 1.0,
3361 }
3362 }
3363
3364 fn no_acceleration_factor_with_assumed_gravity_and_gyro_bias(
3369 from_id: u64,
3370 to_id: u64,
3371 delta_t: f64,
3372 true_gravity: Vector3<f64>,
3373 assumed_gravity: Vector3<f64>,
3374 bias_gyro_true: Vector3<f64>,
3375 ) -> ImuPreintegrationFactor {
3376 let mut delta = ImuPreintegratedDelta::identity();
3377 delta.delta_time = delta_t;
3378 delta.delta_velocity = -true_gravity * delta_t;
3379 delta.delta_position = -0.5 * true_gravity * delta_t * delta_t;
3380 delta.delta_rotation =
3381 SO3::from_quaternion(UnitQuaternion::from_scaled_axis(bias_gyro_true * delta_t));
3382 delta.j_rotation_bg = Matrix3::identity() * (-delta_t);
3383 ImuPreintegrationFactor {
3384 keyframe_id_from: from_id,
3385 keyframe_id_to: to_id,
3386 delta,
3387 gravity_world: assumed_gravity,
3388 weight_position: 1.0,
3389 weight_velocity: 1.0,
3390 weight_rotation: 1.0,
3391 }
3392 }
3393
3394 #[test]
3395 fn recovers_from_gyro_bias_where_the_legacy_bias_fixed_path_rejects() {
3396 let gravity = Vector3::new(0.0, 9.81, 0.0);
3403 let bias_gyro_true = Vector3::new(0.05, -0.03, 0.02); let delta_t = 0.15; let factors = vec![
3406 no_acceleration_factor_with_gyro_bias(1, 2, delta_t, gravity, bias_gyro_true),
3407 no_acceleration_factor_with_gyro_bias(2, 3, delta_t, gravity, bias_gyro_true),
3408 ];
3409 let schedule = BiasReleaseSchedule {
3410 min_keyframes: 5,
3411 min_translation_meters: 3.0,
3412 };
3413 let seed = synthetic_seed();
3414
3415 let mut probe = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3421 min_keyframes: 3,
3422 min_translation_meters: 1.0,
3423 gravity_world: gravity,
3424 bias_release: Some(schedule),
3425 ..MotionBasedViInitializerConfig::default()
3426 });
3427 for i in 0..3 {
3428 probe.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3429 }
3430 let mut probe_map = build_constant_velocity_map(3);
3431 let probe_residual = probe
3432 .try_initialize(&mut probe_map, &factors, &seed)
3433 .expect("bias-fixed Stage A still converges; only the gate is missing here")
3434 .final_cost_breakdown
3435 .imu_rotation_residual_rms_rad
3436 .expect("IMU factors produce a rotation residual");
3437 assert!(
3438 probe_residual > 0.0,
3439 "an uncompensated gyro bias should leave a nonzero rotation residual, got {probe_residual}"
3440 );
3441 let gate = probe_residual * 0.5;
3442
3443 let mut legacy = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3444 min_keyframes: 3,
3445 min_translation_meters: 1.0,
3446 gravity_world: gravity,
3447 bias_release: Some(schedule),
3448 max_final_imu_rotation_residual_rms_rad: Some(gate),
3449 ..MotionBasedViInitializerConfig::default()
3450 });
3451 for i in 0..3 {
3452 legacy.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3453 }
3454 let mut legacy_map = build_constant_velocity_map(3);
3455 let err = legacy
3456 .try_initialize(&mut legacy_map, &factors, &seed)
3457 .expect_err("bias-fixed Stage A must be rejected by the rotation-residual gate");
3458 assert!(
3459 matches!(
3460 err,
3461 MotionBasedViRejectionReason::ImuRawResidualOutOfRange { .. }
3462 ),
3463 "unexpected rejection: {err:?}"
3464 );
3465
3466 let mut estimated = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3467 min_keyframes: 3,
3468 min_translation_meters: 1.0,
3469 gravity_world: gravity,
3470 bias_release: Some(schedule),
3471 max_final_imu_rotation_residual_rms_rad: Some(gate),
3472 estimate_gyro_bias: true,
3473 ..MotionBasedViInitializerConfig::default()
3474 });
3475 for i in 0..3 {
3476 estimated.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3477 }
3478 let mut estimated_map = build_constant_velocity_map(3);
3479 let result = estimated
3480 .try_initialize(&mut estimated_map, &factors, &seed)
3481 .expect("gyro-bias estimation must clear the same gate")
3482 .clone();
3483 assert!(
3484 !result.bias_released,
3485 "still Stage A — the schedule's release gate is not met"
3486 );
3487 let b_g_est = result
3488 .estimated_gyro_bias
3489 .expect("estimate_gyro_bias=true must report the recovered vector");
3490 assert!(
3491 (b_g_est - bias_gyro_true).norm() < 1.0e-6,
3492 "recovered bias {b_g_est:?} should match the true {bias_gyro_true:?}"
3493 );
3494 for state in result.keyframe_states.values() {
3495 assert!(
3496 (state.bias_gyro - bias_gyro_true).norm() < 1.0e-9,
3497 "Stage A must fix gyro bias at the ESTIMATE, not the raw seed"
3498 );
3499 assert!(
3500 (state.bias_acc - seed.bias_acc).norm() < 1.0e-9,
3501 "Stage A must leave accel bias at the seed"
3502 );
3503 }
3504 }
3505
3506 #[test]
3507 fn degenerate_when_no_factors_connect_the_window() {
3508 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3509 min_keyframes: 3,
3510 min_translation_meters: 1.0,
3511 estimate_gyro_bias: true,
3512 ..MotionBasedViInitializerConfig::default()
3513 });
3514 for i in 0..3 {
3515 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3516 }
3517 let mut map = build_constant_velocity_map(3);
3518 let seed = synthetic_seed();
3519 let err = init
3520 .try_initialize(&mut map, &[], &seed)
3521 .expect_err("no factors means the alignment cannot condition at all");
3522 assert!(matches!(
3523 err,
3524 MotionBasedViRejectionReason::GyroBiasEstimateDegenerate
3525 ));
3526 }
3527
3528 #[test]
3529 fn composes_with_gravity_estimation_and_staged_bias_release_stage_a() {
3530 let true_gravity = Vector3::new(0.0, 0.0, 9.81);
3531 let assumed_gravity = Vector3::new(0.0, 9.81, 0.0);
3532 let bias_gyro_true = Vector3::new(0.05, -0.03, 0.02);
3533 let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3534 min_keyframes: 3,
3535 min_translation_meters: 1.0,
3536 gravity_world: assumed_gravity,
3537 estimate_gravity: true,
3538 estimate_gyro_bias: true,
3539 bias_release: Some(BiasReleaseSchedule {
3540 min_keyframes: 5,
3541 min_translation_meters: 3.0,
3542 }),
3543 ..MotionBasedViInitializerConfig::default()
3544 });
3545 for i in 0..3 {
3546 init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3547 }
3548 let mut map = build_constant_velocity_map(3);
3549 let seed = synthetic_seed();
3550 let factors = vec![
3551 no_acceleration_factor_with_assumed_gravity_and_gyro_bias(
3552 1,
3553 2,
3554 0.15,
3555 true_gravity,
3556 assumed_gravity,
3557 bias_gyro_true,
3558 ),
3559 no_acceleration_factor_with_assumed_gravity_and_gyro_bias(
3560 2,
3561 3,
3562 0.15,
3563 true_gravity,
3564 assumed_gravity,
3565 bias_gyro_true,
3566 ),
3567 ];
3568 let result = init
3569 .try_initialize(&mut map, &factors, &seed)
3570 .expect("Stage A must fire with both estimations enabled")
3571 .clone();
3572 assert!(!result.bias_released, "Stage A must not release bias");
3573 let g_est = result
3574 .estimated_gravity_world
3575 .expect("gravity estimate must be reported alongside the gyro-bias estimate");
3576 assert!(
3577 (g_est - true_gravity).norm() < 0.05,
3578 "recovered gravity {g_est:?} should match the true {true_gravity:?}"
3579 );
3580 let b_g_est = result
3581 .estimated_gyro_bias
3582 .expect("gyro-bias estimate must be reported alongside the gravity estimate");
3583 assert!(
3584 (b_g_est - bias_gyro_true).norm() < 1.0e-6,
3585 "recovered bias {b_g_est:?} should match the true {bias_gyro_true:?}"
3586 );
3587 for state in result.keyframe_states.values() {
3588 assert!(
3589 (state.bias_gyro - bias_gyro_true).norm() < 1.0e-9,
3590 "Stage A must fix gyro bias at the ESTIMATE"
3591 );
3592 }
3593 }
3594 }
3595}