1use super::loop_pose_information::estimate_loop_pose_information;
5pub use super::loop_pose_information::{
6 LoopPoseInformationConfig, LoopPoseInformationDiagnostic, LoopPoseInformationFailure,
7 LoopPoseInformationFailureCounts,
8};
9use super::*;
10use crate::imu_preintegration::ImuNoiseModel;
11use std::time::Instant;
12
13#[derive(Debug, Clone, PartialEq)]
14pub struct OnlineSlamConfig {
15 pub apply_map_updates: bool,
16 pub loop_closure: LoopClosureConfig,
17 pub imu: Option<OnlineSlamImuConfig>,
25 pub local_vi_ba: Option<OnlineSlamLocalBaConfig>,
36 pub covisibility_local_ba: Option<OnlineSlamCovisibilityLocalBaConfig>,
44 pub sparse_factor_graph: Option<SparseFactorGraphConfig>,
50 pub vi_init: Option<OnlineSlamViInitConfig>,
61 pub vi_motion_init: Option<OnlineSlamMotionViInitConfig>,
73 pub keep_pre_promotion_imu_factors: bool,
90 pub pose_graph_refinement: Option<OnlineSlamLoopClosureRefinementConfig>,
103 pub relocalization: Option<OnlineSlamRelocalizationConfig>,
114}
115
116impl OnlineSlamConfig {
117 pub fn validate(&self) -> Result<(), OnlineSlamConfigError> {
122 if let Some(vi_init) = &self.vi_init {
123 let Some(imu) = &self.imu else {
124 return Err(OnlineSlamConfigError::ViInitRequiresImu);
125 };
126 if (vi_init.initializer.gravity_world - imu.gravity_world).norm() > 1.0e-12 {
127 return Err(OnlineSlamConfigError::GravityMismatch {
128 imu_gravity_world: imu.gravity_world,
129 vi_init_gravity_world: vi_init.initializer.gravity_world,
130 });
131 }
132 }
133 if let Some(motion) = &self.vi_motion_init {
134 if self.imu.is_none() {
135 return Err(OnlineSlamConfigError::MotionViInitRequiresImu);
136 }
137 if self.vi_init.is_none() {
138 return Err(OnlineSlamConfigError::MotionViInitRequiresStaticViInit);
139 }
140 if (motion.allow_after_static_give_up
141 || motion.allow_from_configured_bias_before_static)
142 && self.vi_init.as_ref().is_some_and(|static_config| {
143 static_config.on_persistent_rejection != ViInitFallback::KeepExistingSeed
144 })
145 {
146 return Err(OnlineSlamConfigError::MotionViInitAfterGiveUpRequiresKeepExistingSeed);
147 }
148 if let Some(imu) = &self.imu {
149 if (motion.initializer.gravity_world - imu.gravity_world).norm() > 1.0e-12 {
150 return Err(OnlineSlamConfigError::MotionGravityMismatch {
151 imu_gravity_world: imu.gravity_world,
152 motion_gravity_world: motion.initializer.gravity_world,
153 });
154 }
155 }
156 if self.vi_init.as_ref().is_some_and(|static_config| {
157 motion.initializer.body_to_camera != static_config.body_to_camera
158 }) {
159 return Err(OnlineSlamConfigError::MotionExtrinsicMismatch);
160 }
161 }
162 if self.local_vi_ba.as_ref().is_some_and(|local| {
163 self.vi_init
164 .as_ref()
165 .is_some_and(|static_config| local.body_to_camera != static_config.body_to_camera)
166 }) {
167 return Err(OnlineSlamConfigError::LocalViBaExtrinsicMismatch);
168 }
169 if self.local_vi_ba.as_ref().is_some_and(|local| {
170 let invalid = |(gyro, accel): (f64, f64)| {
171 !gyro.is_finite() || gyro <= 0.0 || !accel.is_finite() || accel <= 0.0
172 };
173 local.bias_random_walk_weights.is_some_and(invalid)
174 || local.bias_random_walk_noise_densities.is_some_and(invalid)
175 }) {
176 return Err(OnlineSlamConfigError::InvalidLocalViBaBiasRandomWalkWeights);
177 }
178 if self
179 .sparse_factor_graph
180 .as_ref()
181 .is_some_and(|config| !config.is_valid())
182 {
183 return Err(OnlineSlamConfigError::InvalidSparseFactorGraphConfig);
184 }
185 Ok(())
186 }
187}
188
189impl Default for OnlineSlamConfig {
190 fn default() -> Self {
191 Self {
192 apply_map_updates: true,
193 loop_closure: LoopClosureConfig::default(),
194 imu: None,
195 local_vi_ba: None,
196 covisibility_local_ba: None,
197 sparse_factor_graph: None,
198 vi_init: None,
199 vi_motion_init: None,
200 keep_pre_promotion_imu_factors: false,
201 pose_graph_refinement: None,
202 relocalization: None,
203 }
204 }
205}
206
207#[derive(Debug, Clone, PartialEq)]
210pub struct OnlineSlamCovisibilityLocalBaConfig {
211 pub min_keyframes: usize,
215 pub max_keyframes: Option<usize>,
219 pub motion_vi_raw_residual_activation: Option<MotionViRawResidualActivationConfig>,
225 pub max_seed_landmarks_for_activation: Option<usize>,
229 pub trigger_every_new_keyframes: usize,
232 pub max_outlier_observation_ratio: Option<f64>,
237 pub max_behind_camera_landmark_ratio: Option<f64>,
245 pub min_fixed_to_optimized_ratio: Option<f64>,
255 pub max_pose_translation_correction_m: Option<f64>,
258 pub max_pose_rotation_correction_rad: Option<f64>,
261 pub ba: CovisibilityLocalBaConfig,
264}
265
266#[derive(Debug, Clone, Copy, PartialEq)]
267pub struct MotionViRawResidualActivationConfig {
268 pub max_rotation_residual_rms_rad: f64,
269 pub max_velocity_residual_rms_mps: f64,
270 pub max_position_residual_rms_meters: f64,
271}
272
273impl Default for OnlineSlamCovisibilityLocalBaConfig {
274 fn default() -> Self {
275 Self {
276 min_keyframes: 2,
277 max_keyframes: None,
278 motion_vi_raw_residual_activation: None,
279 max_seed_landmarks_for_activation: None,
280 trigger_every_new_keyframes: 1,
281 max_outlier_observation_ratio: None,
282 max_behind_camera_landmark_ratio: None,
283 min_fixed_to_optimized_ratio: None,
284 max_pose_translation_correction_m: None,
285 max_pose_rotation_correction_rad: None,
286 ba: CovisibilityLocalBaConfig::default(),
287 }
288 }
289}
290
291#[derive(Debug, Clone, PartialEq)]
296pub struct OnlineSlamCovisibilityLocalBaStats {
297 pub active_keyframe_id: u64,
298 pub map_keyframe_count: usize,
299 pub factor_graph_neighbor_count: Option<usize>,
302 pub elapsed_ms: f64,
303 pub success: bool,
304 pub error: Option<CovisibilityLocalBaError>,
305 pub selection: Option<CovisibilityLocalBaSelection>,
306 pub ba_result: Option<BaResult>,
307 pub mean_reprojection_before_px: Option<f64>,
308 pub mean_reprojection_after_px: Option<f64>,
309 pub max_pose_translation_correction_m: Option<f64>,
310 pub max_pose_rotation_correction_rad: Option<f64>,
311 pub updated_keyframe_count: usize,
312 pub updated_landmark_count: usize,
313 pub outlier_observation_count: usize,
314 pub observation_count: usize,
315 pub outlier_observation_ratio: Option<f64>,
316 pub quality_gate_rejected: bool,
317 pub pose_correction_gate_rejected: bool,
318 pub removed_observation_count: usize,
319}
320
321#[derive(Debug, Clone, PartialEq)]
332pub struct OnlineSlamRelocalizationConfig {
333 pub min_inliers: usize,
338 pub min_inlier_ratio: f64,
340 pub max_mean_reprojection_error: Option<f64>,
344 pub pose_prior_candidate_radius_meters: Option<f64>,
358 pub recent_keyframe_window: Option<usize>,
370 pub covisibility_local_map: Option<OnlineSlamRelocalizationCovisibilityConfig>,
379 pub appearance_retrieval_map: Option<OnlineSlamRelocalizationAppearanceConfig>,
389 pub max_translation_from_imu_prediction_meters: Option<f64>,
402 pub attempt_interval_frames: u64,
408 pub max_consecutive_failed_attempts: Option<u64>,
414 pub max_translation_per_frame_from_last_success_meters: Option<f64>,
423 pub min_inlier_depth_median_ratio_to_last_success: Option<f64>,
429 pub max_inlier_depth_median_ratio_to_last_success: Option<f64>,
435 pub confirmation_required_recoveries: usize,
440 pub confirmation_max_translation_per_frame_meters: Option<f64>,
446}
447
448impl Default for OnlineSlamRelocalizationConfig {
449 fn default() -> Self {
450 Self {
451 min_inliers: 20,
452 min_inlier_ratio: 0.3,
453 max_mean_reprojection_error: Some(8.0),
454 pose_prior_candidate_radius_meters: None,
455 recent_keyframe_window: None,
456 covisibility_local_map: None,
457 appearance_retrieval_map: None,
458 max_translation_from_imu_prediction_meters: None,
459 attempt_interval_frames: 1,
460 max_consecutive_failed_attempts: None,
461 max_translation_per_frame_from_last_success_meters: None,
462 min_inlier_depth_median_ratio_to_last_success: None,
463 max_inlier_depth_median_ratio_to_last_success: None,
464 confirmation_required_recoveries: 1,
465 confirmation_max_translation_per_frame_meters: None,
466 }
467 }
468}
469
470#[derive(Debug, Clone, PartialEq, Eq)]
471pub struct OnlineSlamRelocalizationCovisibilityConfig {
472 pub max_neighbor_keyframes: Option<usize>,
476 pub min_shared_landmarks: usize,
479 pub min_local_map_landmarks: usize,
482 pub fallback_to_broader_store_on_failure: bool,
489 pub broader_store_retry_interval_frames: u64,
494 pub compare_broader_store_on_success: bool,
499}
500
501impl Default for OnlineSlamRelocalizationCovisibilityConfig {
502 fn default() -> Self {
503 Self {
504 max_neighbor_keyframes: Some(10),
505 min_shared_landmarks: 15,
506 min_local_map_landmarks: 30,
507 fallback_to_broader_store_on_failure: true,
508 broader_store_retry_interval_frames: 10,
509 compare_broader_store_on_success: false,
510 }
511 }
512}
513
514#[derive(Debug, Clone, PartialEq)]
515pub struct OnlineSlamRelocalizationAppearanceConfig {
516 pub max_keyframes: usize,
519 pub candidate_log_limit: Option<usize>,
525 pub min_similarity: f32,
528 pub exclude_recent_frame_gap: u64,
532 pub min_local_map_landmarks: usize,
535 pub fallback_to_broader_store_on_failure: bool,
538 pub broader_store_retry_interval_frames: u64,
542 pub compare_broader_store_on_success: bool,
546}
547
548impl Default for OnlineSlamRelocalizationAppearanceConfig {
549 fn default() -> Self {
550 Self {
551 max_keyframes: 5,
552 candidate_log_limit: None,
553 min_similarity: 0.2,
554 exclude_recent_frame_gap: 30,
555 min_local_map_landmarks: 30,
556 fallback_to_broader_store_on_failure: true,
557 broader_store_retry_interval_frames: 10,
558 compare_broader_store_on_success: false,
559 }
560 }
561}
562
563#[derive(Debug, Clone, PartialEq)]
564pub struct OnlineSlamRelocalizationPendingConfirmation {
565 pub frame_id: u64,
566 pub pose: Pose,
567 pub count: usize,
568}
569
570#[derive(Debug, Clone)]
577pub struct OnlineSlamRelocalizationState {
578 pub config: OnlineSlamRelocalizationConfig,
579 pub localizer: LocalizationPipeline,
580 pub trigger_count: u64,
581 pub success_count: u64,
582 pub consecutive_failed_attempts: u64,
583 pub budget_skip_count: u64,
584 pub last_attempt_frame_id: Option<u64>,
585 pub last_broader_descriptor_store_retry_frame_id: Option<u64>,
586 pub last_success_frame_id: Option<u64>,
587 pub pending_confirmation: Option<OnlineSlamRelocalizationPendingConfirmation>,
588}
589
590impl PartialEq for OnlineSlamRelocalizationState {
591 fn eq(&self, other: &Self) -> bool {
592 self.config == other.config
597 && self.trigger_count == other.trigger_count
598 && self.success_count == other.success_count
599 && self.consecutive_failed_attempts == other.consecutive_failed_attempts
600 && self.budget_skip_count == other.budget_skip_count
601 && self.last_attempt_frame_id == other.last_attempt_frame_id
602 && self.last_broader_descriptor_store_retry_frame_id
603 == other.last_broader_descriptor_store_retry_frame_id
604 && self.last_success_frame_id == other.last_success_frame_id
605 && self.pending_confirmation == other.pending_confirmation
606 }
607}
608
609impl OnlineSlamRelocalizationState {
610 fn new(config: OnlineSlamRelocalizationConfig) -> Self {
611 Self {
612 config,
613 localizer: LocalizationPipeline::default(),
614 trigger_count: 0,
615 success_count: 0,
616 consecutive_failed_attempts: 0,
617 budget_skip_count: 0,
618 last_attempt_frame_id: None,
619 last_broader_descriptor_store_retry_frame_id: None,
620 last_success_frame_id: None,
621 pending_confirmation: None,
622 }
623 }
624
625 const fn reset(&mut self) {
626 self.trigger_count = 0;
627 self.success_count = 0;
628 self.consecutive_failed_attempts = 0;
629 self.budget_skip_count = 0;
630 self.last_attempt_frame_id = None;
631 self.last_broader_descriptor_store_retry_frame_id = None;
632 self.last_success_frame_id = None;
633 self.pending_confirmation = None;
634 }
635}
636
637#[derive(Debug, Clone, Copy, PartialEq)]
640pub struct OnlineSlamRelocalizationAppearanceCandidate {
641 pub keyframe_id: u64,
642 pub similarity: f32,
643}
644
645#[derive(Debug, Clone, PartialEq, Default)]
651pub struct OnlineSlamRelocalizationStats {
652 pub attempted: bool,
654 pub localization_success: bool,
658 pub succeeded: bool,
661 pub inlier_count: usize,
664 pub inlier_ratio: f64,
666 pub correspondence_count: usize,
668 pub mean_reprojection_error: Option<f64>,
670 pub translation_from_last_success_meters: Option<f64>,
673 pub translation_per_frame_from_last_success_meters: Option<f64>,
678 pub inlier_depth_median_meters: Option<f64>,
681 pub last_success_inlier_depth_median_meters: Option<f64>,
684 pub inlier_depth_median_ratio_to_last_success: Option<f64>,
687 pub passed_acceptance_gates: bool,
691 pub confirmation_count: usize,
694 pub confirmation_required_count: usize,
697 pub confirmation_translation_per_frame_from_previous_meters: Option<f64>,
701 pub descriptor_store_landmark_count: usize,
705 pub covisibility_local_descriptor_store_landmark_count: Option<usize>,
708 pub appearance_descriptor_store_landmark_count: Option<usize>,
711 pub broader_descriptor_store_landmark_count: Option<usize>,
714 pub tried_covisibility_local_descriptor_store: bool,
717 pub used_covisibility_local_descriptor_store: bool,
720 pub tried_appearance_descriptor_store: bool,
723 pub used_appearance_descriptor_store: bool,
726 pub tried_broader_descriptor_store_fallback: bool,
729 pub broader_descriptor_store_retry_skipped_by_interval: bool,
732 pub used_broader_descriptor_store_fallback: bool,
735 pub covisibility_reference_keyframe_id: Option<u64>,
738 pub appearance_candidate_keyframe_count: usize,
741 pub appearance_best_similarity: Option<f32>,
743 pub appearance_best_keyframe_id: Option<u64>,
745 pub appearance_candidates: Vec<OnlineSlamRelocalizationAppearanceCandidate>,
749}
750
751fn median_positive_depth_for_landmarks(
752 map: &VisualMap,
753 pose: &Pose,
754 landmark_ids: &[u64],
755) -> Option<f64> {
756 let mut depths: Vec<f64> = landmark_ids
757 .iter()
758 .filter_map(|landmark_id| map.landmarks.get(landmark_id))
759 .map(|landmark| pose.transform_world_point(&landmark.position).z)
760 .filter(|depth| depth.is_finite() && *depth > 0.0)
761 .collect();
762 if depths.is_empty() {
763 return None;
764 }
765 depths.sort_by(|left, right| left.total_cmp(right));
766 let mid = depths.len() / 2;
767 if depths.len().is_multiple_of(2) {
768 Some((depths[mid - 1] + depths[mid]) * 0.5)
769 } else {
770 Some(depths[mid])
771 }
772}
773
774fn relocalization_pick_covisibility_reference_keyframe(
775 map: &VisualMap,
776 last_id: u64,
777) -> Option<u64> {
778 if map.keyframes.contains_key(&last_id) {
779 return Some(last_id);
780 }
781 let mut best: Option<u64> = None;
782 for keyframe_id in map.keyframes.keys() {
783 if *keyframe_id > last_id {
784 continue;
785 }
786 match best {
787 None => best = Some(*keyframe_id),
788 Some(current) if *keyframe_id > current => best = Some(*keyframe_id),
789 _ => {}
790 }
791 }
792 best
793}
794
795fn relocalization_covisibility_descriptor_store(
796 map: &VisualMap,
797 reference_keyframe_id: u64,
798 config: &OnlineSlamRelocalizationCovisibilityConfig,
799) -> Option<visloc_core::types::LandmarkDescriptorStore> {
800 let reference_keyframe = map.keyframes.get(&reference_keyframe_id)?;
801 let reference_landmarks: std::collections::HashSet<u64> = reference_keyframe
802 .observations
803 .iter()
804 .map(|observation| observation.landmark_id)
805 .collect();
806 if reference_landmarks.is_empty() {
807 return None;
808 }
809
810 let mut local_landmarks = reference_landmarks.clone();
811 let mut shared_counts: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();
812 for landmark_id in &reference_landmarks {
813 let Some(landmark) = map.landmarks.get(landmark_id) else {
814 continue;
815 };
816 for observation in &landmark.observations {
817 let keyframe_id = observation.frame_id;
818 if keyframe_id == reference_keyframe_id || !map.keyframes.contains_key(&keyframe_id) {
819 continue;
820 }
821 *shared_counts.entry(keyframe_id).or_insert(0) += 1;
822 }
823 }
824
825 let mut ranked_neighbors: Vec<(u64, usize)> = shared_counts
826 .into_iter()
827 .filter(|(_, count)| *count >= config.min_shared_landmarks)
828 .collect();
829 ranked_neighbors.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0)));
830 if let Some(cap) = config.max_neighbor_keyframes {
831 ranked_neighbors.truncate(cap);
832 }
833
834 for (keyframe_id, _) in ranked_neighbors {
835 if let Some(keyframe) = map.keyframes.get(&keyframe_id) {
836 for observation in &keyframe.observations {
837 local_landmarks.insert(observation.landmark_id);
838 }
839 }
840 }
841
842 let mut local_landmark_ids: Vec<u64> = local_landmarks.into_iter().collect();
843 local_landmark_ids.sort_unstable();
844 let mut store = visloc_core::types::LandmarkDescriptorStore::new();
845 for landmark_id in local_landmark_ids {
846 if let Some(descriptor) = map
847 .landmarks
848 .get(&landmark_id)
849 .and_then(|landmark| landmark.descriptor.as_ref())
850 {
851 store.insert(landmark_id, descriptor.clone());
852 }
853 }
854 if store.len() < config.min_local_map_landmarks {
855 return None;
856 }
857 Some(store)
858}
859
860struct RelocalizationAppearanceDescriptorStore {
861 store: visloc_core::types::LandmarkDescriptorStore,
862 candidate_keyframe_count: usize,
863 best_keyframe_id: Option<u64>,
864 best_similarity: Option<f32>,
865 candidates: Vec<OnlineSlamRelocalizationAppearanceCandidate>,
866}
867
868#[derive(Debug, Clone, Copy, PartialEq, Eq)]
869enum RelocalizationDescriptorStoreKind {
870 Broader,
871 CovisibilityLocal,
872 AppearanceRetrieval,
873}
874
875pub(crate) fn relocalization_mean_descriptor(descriptors: &[Vec<f32>]) -> Option<Vec<f32>> {
876 let first = descriptors.first()?;
877 if first.is_empty()
878 || descriptors
879 .iter()
880 .any(|descriptor| descriptor.len() != first.len())
881 {
882 return None;
883 }
884 let mut mean = vec![0.0_f32; first.len()];
885 for descriptor in descriptors {
886 for (acc, value) in mean.iter_mut().zip(descriptor) {
887 *acc += *value;
888 }
889 }
890 let inv_count = 1.0_f32 / descriptors.len() as f32;
891 let mut norm = 0.0_f32;
892 for value in &mut mean {
893 *value *= inv_count;
894 norm += *value * *value;
895 }
896 let norm = norm.sqrt();
897 if norm <= 1.0e-12 {
898 return None;
899 }
900 for value in &mut mean {
901 *value /= norm;
902 }
903 Some(mean)
904}
905
906pub(crate) fn relocalization_descriptor_cosine(left: &[f32], right: &[f32]) -> f32 {
907 if left.len() != right.len() || left.is_empty() {
908 return 0.0;
909 }
910 let dot: f32 = left.iter().zip(right).map(|(l, r)| l * r).sum();
911 let left_norm = left.iter().map(|v| v * v).sum::<f32>().sqrt();
912 let right_norm = right.iter().map(|v| v * v).sum::<f32>().sqrt();
913 if left_norm <= 1.0e-12 || right_norm <= 1.0e-12 {
914 0.0
915 } else {
916 dot / (left_norm * right_norm)
917 }
918}
919
920fn relocalization_appearance_descriptor_store(
921 map: &VisualMap,
922 frame: &Frame,
923 config: &OnlineSlamRelocalizationAppearanceConfig,
924) -> Option<RelocalizationAppearanceDescriptorStore> {
925 let query_descriptor = relocalization_mean_descriptor(&frame.descriptors)?;
926 let mut ranked_keyframes: Vec<(u64, f32)> = Vec::new();
927 for (keyframe_id, keyframe) in &map.keyframes {
928 if *keyframe_id >= frame.id {
929 continue;
930 }
931 if frame.id.saturating_sub(*keyframe_id) < config.exclude_recent_frame_gap {
932 continue;
933 }
934 let Some(keyframe_descriptor) = relocalization_mean_descriptor(&keyframe.frame.descriptors)
935 else {
936 continue;
937 };
938 let similarity = relocalization_descriptor_cosine(&query_descriptor, &keyframe_descriptor);
939 if similarity >= config.min_similarity {
940 ranked_keyframes.push((*keyframe_id, similarity));
941 }
942 }
943 ranked_keyframes.sort_by(|left, right| {
944 right
945 .1
946 .partial_cmp(&left.1)
947 .unwrap_or(std::cmp::Ordering::Equal)
948 .then_with(|| left.0.cmp(&right.0))
949 });
950 let candidate_keyframe_count = ranked_keyframes.len();
951 let best_keyframe_id = ranked_keyframes
952 .first()
953 .map(|(keyframe_id, _)| *keyframe_id);
954 let best_similarity = ranked_keyframes.first().map(|(_, similarity)| *similarity);
955 let recovery_keyframe_count = config.max_keyframes.max(1);
956 let log_keyframe_count = config
957 .candidate_log_limit
958 .unwrap_or(recovery_keyframe_count)
959 .max(1);
960 let candidates: Vec<OnlineSlamRelocalizationAppearanceCandidate> = ranked_keyframes
961 .iter()
962 .take(log_keyframe_count)
963 .map(
964 |(keyframe_id, similarity)| OnlineSlamRelocalizationAppearanceCandidate {
965 keyframe_id: *keyframe_id,
966 similarity: *similarity,
967 },
968 )
969 .collect();
970
971 let mut landmark_ids = std::collections::HashSet::new();
972 for (keyframe_id, _) in ranked_keyframes.iter().take(recovery_keyframe_count) {
973 if let Some(keyframe) = map.keyframes.get(keyframe_id) {
974 for observation in &keyframe.observations {
975 landmark_ids.insert(observation.landmark_id);
976 }
977 }
978 }
979 let mut landmark_ids: Vec<u64> = landmark_ids.into_iter().collect();
980 landmark_ids.sort_unstable();
981 let mut store = visloc_core::types::LandmarkDescriptorStore::new();
982 for landmark_id in landmark_ids {
983 if let Some(descriptor) = map
984 .landmarks
985 .get(&landmark_id)
986 .and_then(|landmark| landmark.descriptor.as_ref())
987 {
988 store.insert(landmark_id, descriptor.clone());
989 }
990 }
991 if store.len() < config.min_local_map_landmarks {
992 return None;
993 }
994 Some(RelocalizationAppearanceDescriptorStore {
995 store,
996 candidate_keyframe_count,
997 best_keyframe_id,
998 best_similarity,
999 candidates,
1000 })
1001}
1002
1003pub fn appearance_loop_candidate_descriptor_store(
1011 map: &VisualMap,
1012 keyframe: &Keyframe,
1013) -> Option<visloc_core::types::LandmarkDescriptorStore> {
1014 let mut landmark_ids: Vec<u64> = keyframe
1015 .observations
1016 .iter()
1017 .map(|observation| observation.landmark_id)
1018 .collect();
1019 landmark_ids.sort_unstable();
1020 landmark_ids.dedup();
1021 if landmark_ids.is_empty() {
1022 return None;
1023 }
1024 let mut store = visloc_core::types::LandmarkDescriptorStore::new();
1025 for landmark_id in landmark_ids {
1026 if let Some(descriptor) = map
1027 .landmarks
1028 .get(&landmark_id)
1029 .and_then(|landmark| landmark.descriptor.as_ref())
1030 {
1031 store.insert(landmark_id, descriptor.clone());
1032 }
1033 }
1034 Some(store)
1035}
1036
1037fn keyframes_ranked_by_covisibility(
1038 map: &VisualMap,
1039 seed_keyframe_id: u64,
1040 min_shared_landmarks: usize,
1041 max_keyframes: usize,
1042) -> Vec<u64> {
1043 let Some(seed) = map.keyframes.get(&seed_keyframe_id) else {
1044 return Vec::new();
1045 };
1046 let seed_landmarks: std::collections::HashSet<_> = seed
1047 .observations
1048 .iter()
1049 .map(|observation| observation.landmark_id)
1050 .collect();
1051 let mut ranked: Vec<(u64, usize)> = map
1052 .keyframes
1053 .iter()
1054 .filter(|(keyframe_id, _)| **keyframe_id != seed_keyframe_id)
1055 .filter_map(|(keyframe_id, keyframe)| {
1056 let shared = keyframe
1057 .observations
1058 .iter()
1059 .filter(|observation| seed_landmarks.contains(&observation.landmark_id))
1060 .count();
1061 (shared >= min_shared_landmarks.max(1)).then_some((*keyframe_id, shared))
1062 })
1063 .collect();
1064 ranked.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0)));
1065 ranked.truncate(max_keyframes);
1066 ranked
1067 .into_iter()
1068 .map(|(keyframe_id, _)| keyframe_id)
1069 .collect()
1070}
1071
1072fn appearance_loop_region_descriptor_store(
1073 map: &VisualMap,
1074 keyframe_ids: &[u64],
1075) -> visloc_core::types::LandmarkDescriptorStore {
1076 let mut landmark_ids = std::collections::BTreeSet::new();
1077 for keyframe_id in keyframe_ids {
1078 if let Some(keyframe) = map.keyframes.get(keyframe_id) {
1079 landmark_ids.extend(
1080 keyframe
1081 .observations
1082 .iter()
1083 .map(|observation| observation.landmark_id),
1084 );
1085 }
1086 }
1087 let mut store = visloc_core::types::LandmarkDescriptorStore::new();
1088 for landmark_id in landmark_ids {
1089 if let Some(descriptor) = map
1090 .landmarks
1091 .get(&landmark_id)
1092 .and_then(|landmark| landmark.descriptor.as_ref())
1093 {
1094 store.insert(landmark_id, descriptor.clone());
1095 }
1096 }
1097 store
1098}
1099
1100fn rank_appearance_loop_candidate_keyframes(
1107 descriptor_cache: &HashMap<u64, Vec<f32>>,
1108 frame_id: u64,
1109 query_descriptor: &[f32],
1110 min_similarity: f32,
1111 min_keyframe_id_gap: u64,
1112) -> Vec<(u64, f32)> {
1113 let mut ranked: Vec<(u64, f32)> = descriptor_cache
1114 .iter()
1115 .filter(|(&keyframe_id, _)| {
1116 keyframe_id < frame_id && frame_id.saturating_sub(keyframe_id) >= min_keyframe_id_gap
1117 })
1118 .map(|(&keyframe_id, descriptor)| {
1119 (
1120 keyframe_id,
1121 relocalization_descriptor_cosine(query_descriptor, descriptor),
1122 )
1123 })
1124 .filter(|(_, similarity)| *similarity >= min_similarity)
1125 .collect();
1126 ranked.sort_by(|left, right| {
1127 right
1128 .1
1129 .partial_cmp(&left.1)
1130 .unwrap_or(std::cmp::Ordering::Equal)
1131 .then_with(|| left.0.cmp(&right.0))
1132 });
1133 ranked
1134}
1135
1136#[derive(Debug, Clone, PartialEq, Default)]
1168pub struct AppearanceLoopCandidateBuildResult {
1169 pub candidates: Vec<LoopClosureCandidate>,
1170 pub connected_region_rejected_count: usize,
1171 pub pnp_verified_count: usize,
1172 pub projection_rejected_count: usize,
1173 pub covisibility_rejected_count: usize,
1174 pub diagnostics: Vec<AppearanceLoopCandidateDiagnostic>,
1175}
1176
1177#[derive(Debug, Clone, PartialEq)]
1181pub struct AppearanceLoopCandidateDiagnostic {
1182 pub query_frame_id: u64,
1183 pub matched_keyframe_id: u64,
1184 pub appearance_similarity: f32,
1185 pub matched_region_keyframe_count: usize,
1186 pub matched_region_landmark_count: usize,
1187 pub primary_correspondence_count: usize,
1188 pub primary_inlier_count: usize,
1189 pub projection_attempted: bool,
1190 pub projection_correspondence_count: usize,
1191 pub projection_inlier_count: usize,
1192 pub projection_accepted: bool,
1193 pub current_covisible_keyframe_count: usize,
1194 pub neighbor_pnp_verified_count: usize,
1195 pub consistent_keyframe_count: usize,
1196 pub minimum_translation_disagreement_meters: Option<f64>,
1197 pub minimum_rotation_disagreement_radians: Option<f64>,
1198 pub accepted: bool,
1199}
1200
1201pub fn build_appearance_loop_candidates(
1202 map: &VisualMap,
1203 frame: &Frame,
1204 descriptor_cache: &HashMap<u64, Vec<f32>>,
1205 config: &LoopAppearanceCandidateConfig,
1206 camera: &Camera,
1207) -> Vec<LoopClosureCandidate> {
1208 build_appearance_loop_candidates_with_diagnostics(map, frame, descriptor_cache, config, camera)
1209 .candidates
1210}
1211
1212pub fn build_appearance_loop_candidates_with_diagnostics(
1213 map: &VisualMap,
1214 frame: &Frame,
1215 descriptor_cache: &HashMap<u64, Vec<f32>>,
1216 config: &LoopAppearanceCandidateConfig,
1217 camera: &Camera,
1218) -> AppearanceLoopCandidateBuildResult {
1219 let Some(query_descriptor) = relocalization_mean_descriptor(&frame.descriptors) else {
1220 return AppearanceLoopCandidateBuildResult::default();
1221 };
1222 let mut ranked = rank_appearance_loop_candidate_keyframes(
1223 descriptor_cache,
1224 frame.id,
1225 &query_descriptor,
1226 config.min_similarity,
1227 config.min_keyframe_id_gap,
1228 );
1229 ranked.truncate(config.max_candidates_per_frame.max(1));
1230
1231 let query = visloc_core::types::QueryImage::from_frame(frame, camera.clone());
1232 let matcher = visloc_vision::matching::BruteForceMatcher::default();
1233 let correspondence_builder = visloc_localization::CorrespondenceBuilder::new(matcher);
1234 let verifier = PnPLoopClosureVerifier {
1235 ransac: PnPRansac::default(),
1236 config: config.pnp_verifier,
1237 };
1238
1239 let mut result = AppearanceLoopCandidateBuildResult::default();
1240 let current_connected_keyframes: std::collections::HashSet<u64> =
1241 keyframes_ranked_by_covisibility(
1242 map,
1243 frame.id,
1244 config.covisibility_min_shared_landmarks,
1245 usize::MAX,
1246 )
1247 .into_iter()
1248 .chain(std::iter::once(frame.id))
1249 .collect();
1250 for (keyframe_id, similarity) in ranked {
1251 let Some(keyframe) = map.keyframes.get(&keyframe_id) else {
1252 continue;
1253 };
1254 let Some(keyframe_pose) = keyframe.frame.pose.as_ref() else {
1255 continue;
1256 };
1257 let mut matched_region_keyframe_ids = vec![keyframe_id];
1258 matched_region_keyframe_ids.extend(keyframes_ranked_by_covisibility(
1259 map,
1260 keyframe_id,
1261 config.covisibility_min_shared_landmarks,
1262 config.covisibility_max_keyframes,
1263 ));
1264 if matched_region_keyframe_ids
1265 .iter()
1266 .any(|keyframe_id| current_connected_keyframes.contains(keyframe_id))
1267 {
1268 result.connected_region_rejected_count += 1;
1269 continue;
1270 }
1271 let store = appearance_loop_region_descriptor_store(map, &matched_region_keyframe_ids);
1272 if store.len() < config.min_candidate_landmark_count {
1273 continue;
1274 }
1275 let Ok(mut correspondence_set) = correspondence_builder.build(&query, map, &store) else {
1276 continue;
1277 };
1278 let (mut verification, mut pnp_inlier_indices) = verifier.verify_with_inlier_indices(
1279 &correspondence_set.correspondences,
1280 keyframe_pose,
1281 camera,
1282 );
1283 if !verification.verified {
1284 continue;
1285 }
1286 result.pnp_verified_count += 1;
1287 let primary_correspondence_count = verification.correspondence_count;
1288 let primary_inlier_count = verification.inlier_count;
1289 let mut projection_attempted = false;
1290 let mut projection_correspondence_count = 0usize;
1291 let mut projection_inlier_count = 0usize;
1292 let mut projection_accepted = false;
1293 if let Some(search_radius_px) = config.projection_search_radius_px {
1294 projection_attempted = true;
1295 if let Some(primary_relative_pose) = verification.relative_pose.as_ref() {
1296 let recovered_current_pose = Pose {
1297 world_to_camera: primary_relative_pose.compose(&keyframe_pose.world_to_camera),
1298 };
1299 let projection_builder = visloc_localization::ProjectionCorrespondenceBuilder::new(
1300 visloc_vision::matching::BruteForceMatcher::default(),
1301 );
1302 if let Ok(projected_set) = projection_builder.build_with_pose_prior(
1303 &query,
1304 map,
1305 &store,
1306 &recovered_current_pose,
1307 search_radius_px,
1308 ) {
1309 projection_correspondence_count = projected_set.correspondences.len();
1310 if projection_correspondence_count >= config.min_projection_correspondence_count
1311 {
1312 let (projected_verification, projected_inlier_indices) = verifier
1313 .verify_with_inlier_indices(
1314 &projected_set.correspondences,
1315 keyframe_pose,
1316 camera,
1317 );
1318 projection_inlier_count = projected_verification.inlier_count;
1319 if projected_verification.verified {
1320 projection_accepted = true;
1321 correspondence_set = projected_set;
1322 verification = projected_verification;
1323 pnp_inlier_indices = projected_inlier_indices;
1324 }
1325 }
1326 }
1327 }
1328 }
1329 let required_verifications = config.min_covisible_keyframe_verifications.max(1);
1330 let mut region_verifications = 1usize;
1331 let current_covisible_keyframe_ids = keyframes_ranked_by_covisibility(
1332 map,
1333 frame.id,
1334 config.covisibility_min_shared_landmarks,
1335 config.covisibility_max_keyframes,
1336 );
1337 let mut diagnostic = AppearanceLoopCandidateDiagnostic {
1338 query_frame_id: frame.id,
1339 matched_keyframe_id: keyframe_id,
1340 appearance_similarity: similarity,
1341 matched_region_keyframe_count: matched_region_keyframe_ids.len(),
1342 matched_region_landmark_count: store.len(),
1343 primary_correspondence_count,
1344 primary_inlier_count,
1345 projection_attempted,
1346 projection_correspondence_count,
1347 projection_inlier_count,
1348 projection_accepted,
1349 current_covisible_keyframe_count: current_covisible_keyframe_ids.len(),
1350 neighbor_pnp_verified_count: 0,
1351 consistent_keyframe_count: 1,
1352 minimum_translation_disagreement_meters: None,
1353 minimum_rotation_disagreement_radians: None,
1354 accepted: false,
1355 };
1356 if projection_attempted && !projection_accepted {
1357 result.projection_rejected_count += 1;
1358 result.diagnostics.push(diagnostic);
1359 continue;
1360 }
1361 if required_verifications > 1 {
1362 let Some(primary_relative_pose) = verification.relative_pose.as_ref() else {
1363 result.covisibility_rejected_count += 1;
1364 result.diagnostics.push(diagnostic);
1365 continue;
1366 };
1367 let Some(current_pose) = map
1368 .keyframes
1369 .get(&frame.id)
1370 .and_then(|keyframe| keyframe.frame.pose.as_ref())
1371 else {
1372 result.covisibility_rejected_count += 1;
1373 result.diagnostics.push(diagnostic);
1374 continue;
1375 };
1376 for current_neighbor_id in current_covisible_keyframe_ids {
1377 let Some(current_neighbor) = map.keyframes.get(¤t_neighbor_id) else {
1378 continue;
1379 };
1380 let neighbor_query = visloc_core::types::QueryImage::from_frame(
1381 ¤t_neighbor.frame,
1382 camera.clone(),
1383 );
1384 let Ok(neighbor_correspondences) =
1385 correspondence_builder.build(&neighbor_query, map, &store)
1386 else {
1387 continue;
1388 };
1389 let neighbor_verification = verifier.verify(
1390 &neighbor_correspondences.correspondences,
1391 keyframe_pose,
1392 camera,
1393 );
1394 if neighbor_verification.verified {
1395 diagnostic.neighbor_pnp_verified_count += 1;
1396 let Some(neighbor_relative_pose) = neighbor_verification.relative_pose.as_ref()
1397 else {
1398 continue;
1399 };
1400 let Some(neighbor_pose) = current_neighbor.frame.pose.as_ref() else {
1401 continue;
1402 };
1403 let current_to_neighbor = relative_world_to_camera(current_pose, neighbor_pose);
1404 let expected_neighbor_relative =
1405 current_to_neighbor.compose(primary_relative_pose);
1406 let disagreement =
1407 neighbor_relative_pose.compose(&expected_neighbor_relative.inverse());
1408 let translation_disagreement = disagreement.translation.norm();
1409 let rotation_disagreement = disagreement.rotation.angle();
1410 diagnostic.minimum_translation_disagreement_meters = Some(
1411 diagnostic
1412 .minimum_translation_disagreement_meters
1413 .map_or(translation_disagreement, |value| {
1414 value.min(translation_disagreement)
1415 }),
1416 );
1417 diagnostic.minimum_rotation_disagreement_radians = Some(
1418 diagnostic
1419 .minimum_rotation_disagreement_radians
1420 .map_or(rotation_disagreement, |value| {
1421 value.min(rotation_disagreement)
1422 }),
1423 );
1424 if translation_disagreement
1425 <= config.max_covisibility_translation_disagreement_meters
1426 && rotation_disagreement
1427 <= config.max_covisibility_rotation_disagreement_radians
1428 {
1429 region_verifications += 1;
1430 diagnostic.consistent_keyframe_count = region_verifications;
1431 }
1432 if region_verifications >= required_verifications {
1433 break;
1434 }
1435 }
1436 }
1437 }
1438 if region_verifications < required_verifications {
1439 result.covisibility_rejected_count += 1;
1440 result.diagnostics.push(diagnostic);
1441 continue;
1442 }
1443 diagnostic.accepted = true;
1444 result.diagnostics.push(diagnostic);
1445 result.candidates.push(LoopClosureCandidate {
1446 query_frame_id: frame.id,
1447 matched_keyframe_id: keyframe_id,
1448 shared_landmark_count: verification.inlier_count,
1449 query_inlier_count: verification.inlier_count,
1450 keyframe_observation_count: correspondence_set.candidate_landmark_count,
1451 shared_landmark_ratio: verification.inlier_ratio,
1452 score: f64::from(similarity) * verification.score,
1453 geometrically_verified: true,
1454 verification: Some(verification),
1455 pnp_query_landmark_pairs: pnp_inlier_indices
1456 .into_iter()
1457 .filter_map(|index| {
1458 Some((
1459 *correspondence_set.query_indices.get(index)?,
1460 *correspondence_set.landmark_ids.get(index)?,
1461 ))
1462 })
1463 .collect(),
1464 });
1465 }
1466 result
1467}
1468
1469fn appearance_regions_overlap(
1470 map: &VisualMap,
1471 left_keyframe_id: u64,
1472 right_keyframe_id: u64,
1473 config: &LoopAppearanceCandidateConfig,
1474) -> bool {
1475 if left_keyframe_id == right_keyframe_id {
1476 return true;
1477 }
1478 let mut left_region = keyframes_ranked_by_covisibility(
1479 map,
1480 left_keyframe_id,
1481 config.covisibility_min_shared_landmarks,
1482 config.covisibility_max_keyframes,
1483 );
1484 left_region.push(left_keyframe_id);
1485 let right_region: std::collections::HashSet<u64> = keyframes_ranked_by_covisibility(
1486 map,
1487 right_keyframe_id,
1488 config.covisibility_min_shared_landmarks,
1489 config.covisibility_max_keyframes,
1490 )
1491 .into_iter()
1492 .chain(std::iter::once(right_keyframe_id))
1493 .collect();
1494 left_region
1495 .iter()
1496 .any(|keyframe_id| right_region.contains(keyframe_id))
1497}
1498
1499#[derive(Debug, Clone, PartialEq, Default)]
1500struct AppearancePendingProjectionResult {
1501 attempted: bool,
1502 search_radius_px: Option<f64>,
1503 correspondence_count: usize,
1504 inlier_count: usize,
1505 candidate: Option<LoopClosureCandidate>,
1506}
1507
1508fn verify_pending_appearance_region_by_projection(
1514 map: &VisualMap,
1515 frame: &Frame,
1516 camera: &Camera,
1517 config: &LoopAppearanceCandidateConfig,
1518 pending: &AppearancePendingRegion,
1519) -> AppearancePendingProjectionResult {
1520 let Some(search_radius_px) = config.projection_search_radius_px else {
1521 return AppearancePendingProjectionResult::default();
1522 };
1523 let Some(root_keyframe) = map.keyframes.get(&pending.root_keyframe_id) else {
1524 return AppearancePendingProjectionResult::default();
1525 };
1526 let Some(root_pose) = root_keyframe.frame.pose.as_ref() else {
1527 return AppearancePendingProjectionResult::default();
1528 };
1529 let Some(last_current_pose) = map
1530 .keyframes
1531 .get(&pending.last_current_keyframe_id)
1532 .and_then(|keyframe| keyframe.frame.pose.as_ref())
1533 else {
1534 return AppearancePendingProjectionResult::default();
1535 };
1536 let Some(current_pose) = map
1537 .keyframes
1538 .get(&frame.id)
1539 .and_then(|keyframe| keyframe.frame.pose.as_ref())
1540 else {
1541 return AppearancePendingProjectionResult::default();
1542 };
1543
1544 let mut region_keyframe_ids = vec![pending.root_keyframe_id];
1545 region_keyframe_ids.extend(keyframes_ranked_by_covisibility(
1546 map,
1547 pending.root_keyframe_id,
1548 config.covisibility_min_shared_landmarks,
1549 config.covisibility_max_keyframes,
1550 ));
1551 let store = appearance_loop_region_descriptor_store(map, ®ion_keyframe_ids);
1552 if store.len() < config.min_candidate_landmark_count {
1553 return AppearancePendingProjectionResult::default();
1554 }
1555
1556 let last_to_current = relative_world_to_camera(last_current_pose, current_pose);
1557 let predicted_root_to_current = last_to_current.compose(&pending.root_to_last_current);
1558 let predicted_current_pose = Pose {
1559 world_to_camera: predicted_root_to_current.compose(&root_pose.world_to_camera),
1560 };
1561 let query = visloc_core::types::QueryImage::from_frame(frame, camera.clone());
1562 let mut result = AppearancePendingProjectionResult {
1563 attempted: true,
1564 ..AppearancePendingProjectionResult::default()
1565 };
1566 let verifier = PnPLoopClosureVerifier {
1567 ransac: PnPRansac::default(),
1568 config: config.pnp_verifier,
1569 };
1570 let mut radii = [
1571 (search_radius_px / 3.0).max(1.0),
1572 (search_radius_px * 2.0 / 3.0).max(1.0),
1573 search_radius_px,
1574 ];
1575 radii.sort_by(f64::total_cmp);
1576 let mut previous_radius: Option<f64> = None;
1577 let mut best_ratio = -1.0_f64;
1578 for radius in radii {
1579 if previous_radius.is_some_and(|previous| (radius - previous).abs() <= f64::EPSILON) {
1580 continue;
1581 }
1582 previous_radius = Some(radius);
1583 let projection_builder = visloc_localization::ProjectionCorrespondenceBuilder::new(
1584 visloc_vision::matching::BruteForceMatcher::default(),
1585 );
1586 let Ok(correspondence_set) = projection_builder.build_with_pose_prior(
1587 &query,
1588 map,
1589 &store,
1590 &predicted_current_pose,
1591 radius,
1592 ) else {
1593 continue;
1594 };
1595 let correspondence_count = correspondence_set.correspondences.len();
1596 if correspondence_count < config.min_projection_correspondence_count {
1597 if result.search_radius_px.is_none() {
1598 result.search_radius_px = Some(radius);
1599 result.correspondence_count = correspondence_count;
1600 }
1601 continue;
1602 }
1603 let (verification, pnp_inlier_indices) = verifier.verify_with_inlier_indices(
1604 &correspondence_set.correspondences,
1605 root_pose,
1606 camera,
1607 );
1608 let ratio = if correspondence_count == 0 {
1609 0.0
1610 } else {
1611 verification.inlier_count as f64 / correspondence_count as f64
1612 };
1613 if ratio > best_ratio
1614 || (ratio == best_ratio && verification.inlier_count > result.inlier_count)
1615 {
1616 best_ratio = ratio;
1617 result.search_radius_px = Some(radius);
1618 result.correspondence_count = correspondence_count;
1619 result.inlier_count = verification.inlier_count;
1620 }
1621 if !verification.verified {
1622 continue;
1623 }
1624 result.search_radius_px = Some(radius);
1625 result.correspondence_count = correspondence_count;
1626 result.inlier_count = verification.inlier_count;
1627 result.candidate = Some(LoopClosureCandidate {
1628 query_frame_id: frame.id,
1629 matched_keyframe_id: pending.root_keyframe_id,
1630 shared_landmark_count: verification.inlier_count,
1631 query_inlier_count: verification.inlier_count,
1632 keyframe_observation_count: correspondence_set.candidate_landmark_count,
1633 shared_landmark_ratio: verification.inlier_ratio,
1634 score: verification.score,
1635 geometrically_verified: true,
1636 verification: Some(verification),
1637 pnp_query_landmark_pairs: pnp_inlier_indices
1638 .into_iter()
1639 .filter_map(|index| {
1640 Some((
1641 *correspondence_set.query_indices.get(index)?,
1642 *correspondence_set.landmark_ids.get(index)?,
1643 ))
1644 })
1645 .collect(),
1646 });
1647 break;
1648 }
1649 result
1650}
1651
1652fn confirm_appearance_region_across_keyframes(
1653 map: &VisualMap,
1654 current_keyframe_id: u64,
1655 candidates: Vec<LoopClosureCandidate>,
1656 config: &LoopAppearanceCandidateConfig,
1657 pending: &mut Option<AppearancePendingRegion>,
1658) -> (Vec<LoopClosureCandidate>, bool, bool) {
1659 let required = config.region_confirmation_required_keyframes.max(1);
1660 if required == 1 {
1661 *pending = None;
1662 return (candidates, false, false);
1663 }
1664
1665 let Some(current_pose) = map
1666 .keyframes
1667 .get(¤t_keyframe_id)
1668 .and_then(|keyframe| keyframe.frame.pose.as_ref())
1669 else {
1670 *pending = None;
1671 return (Vec::new(), false, false);
1672 };
1673
1674 if pending.is_none() {
1675 let Some(candidate) = candidates
1676 .into_iter()
1677 .max_by(|left, right| left.score.total_cmp(&right.score))
1678 else {
1679 return (Vec::new(), false, false);
1680 };
1681 let Some(relative_pose) = candidate
1682 .verification
1683 .as_ref()
1684 .and_then(|verification| verification.relative_pose.clone())
1685 else {
1686 return (Vec::new(), false, false);
1687 };
1688 *pending = Some(AppearancePendingRegion {
1689 root_keyframe_id: candidate.matched_keyframe_id,
1690 last_current_keyframe_id: current_keyframe_id,
1691 root_to_last_current: relative_pose,
1692 confirmation_count: 1,
1693 miss_count: 0,
1694 });
1695 return (Vec::new(), true, false);
1696 }
1697
1698 let state = pending.as_mut().expect("pending region checked above");
1699 let matching_candidate = candidates.into_iter().find(|candidate| {
1700 appearance_regions_overlap(
1701 map,
1702 state.root_keyframe_id,
1703 candidate.matched_keyframe_id,
1704 config,
1705 )
1706 });
1707 let Some(candidate) = matching_candidate else {
1708 state.miss_count += 1;
1709 if state.miss_count >= config.region_confirmation_max_misses.max(1) {
1710 *pending = None;
1711 }
1712 return (Vec::new(), true, false);
1713 };
1714
1715 let recovered_candidate_to_current = candidate
1716 .verification
1717 .as_ref()
1718 .and_then(|verification| verification.relative_pose.as_ref());
1719 let root_pose = map
1720 .keyframes
1721 .get(&state.root_keyframe_id)
1722 .and_then(|keyframe| keyframe.frame.pose.as_ref());
1723 let candidate_pose = map
1724 .keyframes
1725 .get(&candidate.matched_keyframe_id)
1726 .and_then(|keyframe| keyframe.frame.pose.as_ref());
1727 let last_current_pose = map
1728 .keyframes
1729 .get(&state.last_current_keyframe_id)
1730 .and_then(|keyframe| keyframe.frame.pose.as_ref());
1731 let Some((recovered_candidate_to_current, root_pose, candidate_pose, last_current_pose)) =
1732 recovered_candidate_to_current
1733 .zip(root_pose)
1734 .zip(candidate_pose)
1735 .zip(last_current_pose)
1736 .map(|(((a, b), c), d)| (a, b, c, d))
1737 else {
1738 *pending = None;
1739 return (Vec::new(), false, false);
1740 };
1741
1742 let root_to_candidate = relative_world_to_camera(root_pose, candidate_pose);
1743 let recovered_root_to_current = recovered_candidate_to_current.compose(&root_to_candidate);
1744 let last_to_current = relative_world_to_camera(last_current_pose, current_pose);
1745 let predicted_root_to_current = last_to_current.compose(&state.root_to_last_current);
1746 let disagreement = recovered_root_to_current.compose(&predicted_root_to_current.inverse());
1747 let consistent = disagreement.translation.norm()
1748 <= config.max_covisibility_translation_disagreement_meters
1749 && disagreement.rotation.angle() <= config.max_covisibility_rotation_disagreement_radians;
1750 if !consistent {
1751 state.miss_count += 1;
1752 if state.miss_count >= config.region_confirmation_max_misses.max(1) {
1753 *pending = None;
1754 }
1755 return (Vec::new(), true, false);
1756 }
1757
1758 state.confirmation_count += 1;
1759 state.miss_count = 0;
1760 state.last_current_keyframe_id = current_keyframe_id;
1761 state.root_to_last_current = recovered_root_to_current;
1762 if state.confirmation_count < required {
1763 return (Vec::new(), true, false);
1764 }
1765 *pending = None;
1766 (vec![candidate], false, true)
1767}
1768
1769fn relocalization_recent_keyframe_descriptor_store(
1770 map: &VisualMap,
1771 recent_keyframe_window: Option<usize>,
1772) -> visloc_core::types::LandmarkDescriptorStore {
1773 match recent_keyframe_window {
1774 Some(window) if window > 0 => {
1775 let mut keyframe_ids: Vec<u64> = map.keyframes.keys().copied().collect();
1776 keyframe_ids.sort();
1777 let start = keyframe_ids.len().saturating_sub(window);
1778 let mut active_landmark_ids: std::collections::HashSet<u64> =
1779 std::collections::HashSet::new();
1780 for keyframe_id in &keyframe_ids[start..] {
1781 if let Some(keyframe) = map.keyframes.get(keyframe_id) {
1782 for observation in &keyframe.observations {
1783 active_landmark_ids.insert(observation.landmark_id);
1784 }
1785 }
1786 }
1787 let mut store = visloc_core::types::LandmarkDescriptorStore::new();
1788 let mut landmark_ids: Vec<u64> = active_landmark_ids.into_iter().collect();
1789 landmark_ids.sort_unstable();
1790 for landmark_id in landmark_ids {
1791 if let Some(descriptor) = map
1792 .landmarks
1793 .get(&landmark_id)
1794 .and_then(|landmark| landmark.descriptor.as_ref())
1795 {
1796 store.insert(landmark_id, descriptor.clone());
1797 }
1798 }
1799 store
1800 }
1801 _ => visloc_core::types::LandmarkDescriptorStore::from_visual_map(map),
1802 }
1803}
1804
1805fn relocalization_result_has_better_score(
1806 candidate: &visloc_core::types::LocalizationResult,
1807 incumbent: &visloc_core::types::LocalizationResult,
1808) -> bool {
1809 candidate.inlier_count > incumbent.inlier_count
1810 || (candidate.inlier_count == incumbent.inlier_count
1811 && match (candidate.reprojection_error, incumbent.reprojection_error) {
1812 (Some(candidate_error), Some(incumbent_error)) => candidate_error < incumbent_error,
1813 (Some(_), None) => true,
1814 _ => false,
1815 })
1816}
1817
1818#[derive(Debug, Clone, PartialEq, Default)]
1842pub enum LoopRefinementVerifier {
1843 #[default]
1844 EssentialMatrix,
1845 Pnp(PnPLoopClosureVerifierConfig),
1846}
1847
1848#[derive(Debug, Clone, Default, PartialEq)]
1903pub enum LoopRefinementSolver {
1904 #[default]
1905 Se3,
1906 Sim3(Sim3PoseGraphConfig),
1907}
1908
1909#[derive(Debug, Clone, PartialEq)]
1934pub struct LoopAppearanceCandidateConfig {
1935 pub min_keyframe_id_gap: u64,
1940 pub max_candidates_per_frame: usize,
1943 pub min_similarity: f32,
1946 pub min_candidate_landmark_count: usize,
1951 pub covisibility_max_keyframes: usize,
1954 pub covisibility_min_shared_landmarks: usize,
1956 pub min_covisible_keyframe_verifications: usize,
1959 pub max_covisibility_translation_disagreement_meters: f64,
1962 pub max_covisibility_rotation_disagreement_radians: f64,
1964 pub region_confirmation_required_keyframes: usize,
1967 pub region_confirmation_max_misses: usize,
1969 pub projection_search_radius_px: Option<f64>,
1974 pub min_projection_correspondence_count: usize,
1979 pub pnp_verifier: PnPLoopClosureVerifierConfig,
1985}
1986
1987impl Default for LoopAppearanceCandidateConfig {
1988 fn default() -> Self {
1989 Self {
1990 min_keyframe_id_gap: 150,
1991 max_candidates_per_frame: 3,
1992 min_similarity: 0.2,
1993 min_candidate_landmark_count: 30,
1994 covisibility_max_keyframes: 10,
1995 covisibility_min_shared_landmarks: 10,
1996 min_covisible_keyframe_verifications: 3,
1997 max_covisibility_translation_disagreement_meters: 0.5,
1998 max_covisibility_rotation_disagreement_radians: 0.2,
1999 region_confirmation_required_keyframes: 3,
2000 region_confirmation_max_misses: 2,
2001 projection_search_radius_px: None,
2002 min_projection_correspondence_count: 50,
2003 pnp_verifier: PnPLoopClosureVerifierConfig {
2004 min_inliers: 30,
2005 min_inlier_ratio: 0.5,
2006 max_mean_reprojection_error_px: 4.0,
2007 },
2008 }
2009 }
2010}
2011
2012#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2015pub enum LoopClosureCandidateSource {
2016 SharedLandmark,
2020 Appearance,
2023}
2024
2025#[derive(Debug, Clone, PartialEq)]
2034pub struct OnlineSlamAdmittedLoopConstraint {
2035 pub from_keyframe_id: u64,
2036 pub to_keyframe_id: u64,
2037 pub inlier_count: usize,
2038 pub translation_norm_m: f64,
2039 pub relative_pose: SE3,
2040 pub source: LoopClosureCandidateSource,
2041}
2042
2043#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2046pub enum OnlineSlamLoopConstraintRejectionReason {
2047 Pcm,
2048 Covariance,
2049 PoseInformation,
2052}
2053
2054#[derive(Debug, Clone, PartialEq)]
2058pub struct OnlineSlamRejectedLoopConstraint {
2059 pub from_keyframe_id: u64,
2060 pub to_keyframe_id: u64,
2061 pub inlier_count: usize,
2062 pub translation_norm_m: f64,
2063 pub relative_pose: SE3,
2064 pub source: LoopClosureCandidateSource,
2065 pub reason: OnlineSlamLoopConstraintRejectionReason,
2066}
2067
2068#[derive(Debug, Clone, PartialEq)]
2079pub struct OnlineSlamLoopClosureRefinementConfig {
2080 pub camera: Camera,
2085 pub verifier_config: LoopClosureVerifierConfig,
2091 pub verifier: LoopRefinementVerifier,
2096 pub pose_graph_config: PoseGraphSe3Config,
2101 pub fixed_loop_edge_weight: Option<f64>,
2109 pub loop_pose_information: Option<LoopPoseInformationConfig>,
2119 pub gnc: Option<gnc::GncConfig>,
2134 pub pcm: Option<pcm::PcmConfig>,
2147 pub covariance_gate: Option<f64>,
2161 pub pcm_batch_rescreen: bool,
2182 pub marginalization_window: Option<usize>,
2195 pub marginalization_sparsify: bool,
2203 pub trigger_every_new_constraints: usize,
2208 pub appearance_candidates: Option<LoopAppearanceCandidateConfig>,
2220 pub fuse_loop_observations: bool,
2230 pub loop_welding_ba: Option<CovisibilityLocalBaConfig>,
2235 pub propagate_corrections: bool,
2259 pub solver: LoopRefinementSolver,
2265}
2266
2267impl OnlineSlamLoopClosureRefinementConfig {
2268 pub fn recovered_factor_sink(camera: Camera) -> Self {
2271 Self {
2272 camera,
2273 verifier_config: LoopClosureVerifierConfig::default(),
2274 verifier: LoopRefinementVerifier::EssentialMatrix,
2275 pose_graph_config: PoseGraphSe3Config::default(),
2276 fixed_loop_edge_weight: None,
2277 loop_pose_information: None,
2278 gnc: None,
2279 pcm: None,
2280 covariance_gate: None,
2281 pcm_batch_rescreen: false,
2282 marginalization_window: None,
2283 marginalization_sparsify: false,
2284 trigger_every_new_constraints: usize::MAX,
2285 appearance_candidates: None,
2286 fuse_loop_observations: false,
2287 loop_welding_ba: None,
2288 propagate_corrections: false,
2289 solver: LoopRefinementSolver::Se3,
2290 }
2291 }
2292}
2293
2294#[derive(Debug, Clone, PartialEq)]
2298pub struct OnlineSlamLoopClosureRefinementState {
2299 pub config: OnlineSlamLoopClosureRefinementConfig,
2300 pub graph: PoseGraph,
2305 pub sim3_graph: Option<Sim3PoseGraph>,
2313 pub keyframe_order: Vec<u64>,
2317 pub verified_constraints: Vec<LoopClosureConstraint>,
2322 loop_pose_information: HashMap<(u64, u64), Matrix6<f64>>,
2325 pub pcm_deferred: Vec<LoopClosureConstraint>,
2331 pub pending_since_last_trigger: usize,
2334 pub trigger_count: u64,
2339 pub appearance_descriptor_cache: HashMap<u64, Vec<f32>>,
2347 appearance_pending_region: Option<AppearancePendingRegion>,
2348 pending_loop_observation_fusions: Vec<PendingLoopObservationFusion>,
2349}
2350
2351#[derive(Debug, Clone, PartialEq)]
2352struct PendingLoopObservationFusion {
2353 from_keyframe_id: u64,
2354 query_keyframe_id: u64,
2355 relative_pose: SE3,
2356 pairs: Vec<(usize, u64)>,
2357}
2358
2359#[derive(Debug, Clone, PartialEq)]
2360struct AppearancePendingRegion {
2361 root_keyframe_id: u64,
2362 last_current_keyframe_id: u64,
2363 root_to_last_current: SE3,
2364 confirmation_count: usize,
2365 miss_count: usize,
2366}
2367
2368impl OnlineSlamLoopClosureRefinementState {
2369 fn new(config: OnlineSlamLoopClosureRefinementConfig) -> Self {
2370 let sim3_graph =
2371 matches!(config.solver, LoopRefinementSolver::Sim3(_)).then(Sim3PoseGraph::new);
2372 Self {
2373 config,
2374 graph: PoseGraph::new(),
2375 sim3_graph,
2376 keyframe_order: Vec::new(),
2377 verified_constraints: Vec::new(),
2378 loop_pose_information: HashMap::new(),
2379 pcm_deferred: Vec::new(),
2380 pending_since_last_trigger: 0,
2381 trigger_count: 0,
2382 appearance_descriptor_cache: HashMap::new(),
2383 appearance_pending_region: None,
2384 pending_loop_observation_fusions: Vec::new(),
2385 }
2386 }
2387
2388 fn reset(&mut self) {
2389 self.appearance_descriptor_cache.clear();
2390 self.appearance_pending_region = None;
2391 self.pending_loop_observation_fusions.clear();
2392 self.graph = PoseGraph::new();
2393 self.sim3_graph =
2394 matches!(self.config.solver, LoopRefinementSolver::Sim3(_)).then(Sim3PoseGraph::new);
2395 self.keyframe_order.clear();
2396 self.verified_constraints.clear();
2397 self.loop_pose_information.clear();
2398 self.pcm_deferred.clear();
2399 self.pending_since_last_trigger = 0;
2400 self.trigger_count = 0;
2401 }
2402}
2403
2404#[derive(Debug, Clone, PartialEq, Default)]
2409pub struct OnlineSlamLoopClosureRefinementStats {
2410 pub verified_candidate_count: usize,
2413 pub accepted_count: usize,
2419 pub pose_graph_result: Option<PoseGraphSe3Result>,
2424 pub gnc_result: Option<PoseGraphGncResult>,
2430 pub sim3_pose_graph_result: Option<Sim3PoseGraphResult>,
2436 pub sim3_scale_spread: Option<(f64, f64)>,
2443 pub loop_closures_rejected: usize,
2448 pub loop_closures_pcm_rejected: usize,
2452 pub loop_closures_covariance_rejected: usize,
2457 pub loop_closures_pose_information_rejected: usize,
2460 pub loop_closures_with_pose_information: usize,
2463 pub loop_pose_information_diagnostics: Vec<LoopPoseInformationDiagnostic>,
2466 pub loop_pose_information_failures: LoopPoseInformationFailureCounts,
2470 pub sequential_edges_with_pose_information: usize,
2473 pub sequential_pose_information_fallbacks: usize,
2476 pub sequential_pose_information_diagnostics: Vec<LoopPoseInformationDiagnostic>,
2477 pub sequential_pose_information_failures: LoopPoseInformationFailureCounts,
2479 pub loop_closures_pcm_promoted: usize,
2484 pub loop_closures_pcm_evicted: usize,
2489 pub keyframes_updated: usize,
2493 pub poses_marginalized: Vec<u64>,
2497 pub appearance_candidate_count: usize,
2502 pub appearance_ranked_candidate_count: usize,
2505 pub appearance_connected_region_rejected_count: usize,
2508 pub appearance_pnp_verified_count: usize,
2510 pub appearance_projection_rejected_count: usize,
2513 pub appearance_covisibility_rejected_count: usize,
2515 pub appearance_pending_projection_attempted_count: usize,
2517 pub appearance_pending_projection_verified_count: usize,
2519 pub appearance_pending_projection_correspondence_count: usize,
2522 pub appearance_pending_projection_inlier_count: usize,
2524 pub appearance_pending_projection_search_radius_px: Option<f64>,
2526 pub appearance_candidate_diagnostics: Vec<AppearanceLoopCandidateDiagnostic>,
2528 pub appearance_region_confirmation_waiting: bool,
2530 pub appearance_region_confirmed_count: usize,
2532 pub appearance_scale_estimation_failed_count: usize,
2535 pub appearance_scale_insufficient_points_count: usize,
2536 pub appearance_scale_insufficient_matches_count: usize,
2537 pub appearance_scale_no_consensus_count: usize,
2538 pub appearance_near_unit_scale_count: usize,
2541 pub appearance_accepted_count: usize,
2545 pub loop_fusion_pairs_considered: usize,
2548 pub loop_fusion_observations_inserted: usize,
2550 pub loop_fusion_observations_reassigned: usize,
2553 pub loop_fusion_pairs_robust_rejected: usize,
2556 pub loop_fusion_pairs_reprojection_rejected: usize,
2559 pub loop_fusion_pairs_skipped: usize,
2562 pub loop_welding_ba_attempted: bool,
2563 pub loop_welding_ba_succeeded: bool,
2564 pub loop_welding_ba_mean_reprojection_before_px: Option<f64>,
2565 pub loop_welding_ba_mean_reprojection_after_px: Option<f64>,
2566 pub loop_welding_initial_translation_meters: Option<f64>,
2567 pub loop_welding_initial_rotation_radians: Option<f64>,
2568 pub loop_welding_ba_updated_keyframes: usize,
2569 pub loop_welding_ba_updated_landmarks: usize,
2570 pub loop_welding_ba_rejected_or_failed: bool,
2571 pub loop_welding_post_pgo_attempted: bool,
2572 pub loop_welding_post_pgo_succeeded: bool,
2573 pub loop_welding_post_pgo_mean_reprojection_px: Option<f64>,
2574 pub loop_welding_post_ba_error: Option<CovisibilityLocalBaError>,
2575 pub loop_welding_post_ba_behind_camera_ratio: Option<f64>,
2576 pub admitted_constraints: Vec<OnlineSlamAdmittedLoopConstraint>,
2583 pub rejected_constraints: Vec<OnlineSlamRejectedLoopConstraint>,
2587 pub landmarks_moved: usize,
2593 pub max_landmark_displacement_meters: Option<f64>,
2596 pub mean_landmark_displacement_meters: Option<f64>,
2599 pub tracker_correction_applied: bool,
2605}
2606
2607#[derive(Debug, Clone, PartialEq)]
2615pub struct OnlineSlamImuConfig {
2616 pub gravity_world: Vector3<f64>,
2617 pub bias_gyro: Vector3<f64>,
2618 pub bias_acc: Vector3<f64>,
2619 pub weight_position: f64,
2620 pub weight_velocity: f64,
2621 pub weight_rotation: f64,
2622 pub noise_model: Option<ImuNoiseModel>,
2626}
2627
2628impl Default for OnlineSlamImuConfig {
2629 fn default() -> Self {
2630 Self {
2631 gravity_world: Vector3::new(0.0, 9.81, 0.0),
2632 bias_gyro: Vector3::zeros(),
2633 bias_acc: Vector3::zeros(),
2634 weight_position: 1.0,
2635 weight_velocity: 1.0,
2636 weight_rotation: 1.0,
2637 noise_model: None,
2638 }
2639 }
2640}
2641
2642#[derive(Debug, Clone, PartialEq)]
2648pub struct OnlineSlamImuState {
2649 pub config: OnlineSlamImuConfig,
2650 pub preintegrator: ImuPreintegrator,
2651 pub last_keyframe_id: Option<u64>,
2652 pub pending_factor: Option<ImuPreintegrationFactor>,
2653}
2654
2655impl OnlineSlamImuState {
2656 fn new(config: OnlineSlamImuConfig) -> Self {
2657 let preintegrator = config
2658 .noise_model
2659 .and_then(|noise| {
2660 ImuPreintegrator::new_with_bias_and_noise(config.bias_gyro, config.bias_acc, noise)
2661 })
2662 .unwrap_or_else(|| ImuPreintegrator::new_with_bias(config.bias_gyro, config.bias_acc));
2663 Self {
2664 config,
2665 preintegrator,
2666 last_keyframe_id: None,
2667 pending_factor: None,
2668 }
2669 }
2670
2671 fn reset(&mut self) {
2672 self.preintegrator = self
2673 .config
2674 .noise_model
2675 .and_then(|noise| {
2676 ImuPreintegrator::new_with_bias_and_noise(
2677 self.config.bias_gyro,
2678 self.config.bias_acc,
2679 noise,
2680 )
2681 })
2682 .unwrap_or_else(|| {
2683 ImuPreintegrator::new_with_bias(self.config.bias_gyro, self.config.bias_acc)
2684 });
2685 self.last_keyframe_id = None;
2686 self.pending_factor = None;
2687 }
2688
2689 fn reset_preintegrator_with_bias(&mut self, bias_gyro: Vector3<f64>, bias_acc: Vector3<f64>) {
2690 self.config.bias_gyro = bias_gyro;
2691 self.config.bias_acc = bias_acc;
2692 self.preintegrator = self
2693 .config
2694 .noise_model
2695 .and_then(|noise| ImuPreintegrator::new_with_bias_and_noise(bias_gyro, bias_acc, noise))
2696 .unwrap_or_else(|| ImuPreintegrator::new_with_bias(bias_gyro, bias_acc));
2697 self.pending_factor = None;
2698 }
2699}
2700
2701#[derive(Debug, Clone, PartialEq)]
2702pub struct OnlineSlamPipeline<T, M> {
2703 pub map: VisualMap,
2704 pub tracker: T,
2705 pub mapper: M,
2706 pub config: OnlineSlamConfig,
2707 pub imu_state: Option<OnlineSlamImuState>,
2711 pub local_vi_ba_state: Option<OnlineSlamLocalBaState>,
2715 pub sparse_factor_graph_state: Option<SparseFactorGraph>,
2718 vi_init_state: Option<OnlineSlamViInitState>,
2724 vi_motion_init_state: Option<OnlineSlamMotionViInitState>,
2732 pub pose_graph_state: Option<OnlineSlamLoopClosureRefinementState>,
2737 pub relocalization_state: Option<OnlineSlamRelocalizationState>,
2743}
2744
2745impl Default
2746 for OnlineSlamPipeline<
2747 Tracker<LocalizationPipeline, ConstantPoseMotionModel>,
2748 LocalMappingPipeline<SimpleKeyframePolicy, LinearTriangulator>,
2749 >
2750{
2751 fn default() -> Self {
2752 Self {
2753 map: VisualMap::new(),
2754 tracker: Tracker::new(LocalizationPipeline::default(), TrackingConfig::default()),
2755 mapper: LocalMappingPipeline::default(),
2756 config: OnlineSlamConfig::default(),
2757 imu_state: None,
2758 local_vi_ba_state: None,
2759 sparse_factor_graph_state: None,
2760 vi_init_state: None,
2761 vi_motion_init_state: None,
2762 pose_graph_state: None,
2763 relocalization_state: None,
2764 }
2765 }
2766}
2767
2768impl<T, M> OnlineSlamPipeline<T, M> {
2769 pub fn new(map: VisualMap, tracker: T, mapper: M, config: OnlineSlamConfig) -> Self {
2776 if let Err(err) = config.validate() {
2777 panic!("OnlineSlamPipeline::new: invalid config: {err}");
2778 }
2779 let imu_state = config.imu.clone().map(OnlineSlamImuState::new);
2780 let local_vi_ba_state = config.local_vi_ba.clone().map(OnlineSlamLocalBaState::new);
2781 let mut sparse_factor_graph_state = config
2782 .sparse_factor_graph
2783 .clone()
2784 .map(SparseFactorGraph::new);
2785 if let Some(graph) = sparse_factor_graph_state.as_mut() {
2786 let mut existing_keyframe_ids = map.keyframes.keys().copied().collect::<Vec<_>>();
2787 existing_keyframe_ids.sort_unstable();
2788 for keyframe_id in existing_keyframe_ids {
2789 graph.update_from_map(&map, keyframe_id);
2790 }
2791 }
2792 let vi_init_state = config.vi_init.clone().map(OnlineSlamViInitState::new);
2793 let vi_motion_init_state = config
2794 .vi_motion_init
2795 .clone()
2796 .map(OnlineSlamMotionViInitState::new);
2797 let pose_graph_state = config
2798 .pose_graph_refinement
2799 .clone()
2800 .map(OnlineSlamLoopClosureRefinementState::new);
2801 let relocalization_state = config
2802 .relocalization
2803 .clone()
2804 .map(OnlineSlamRelocalizationState::new);
2805 Self {
2806 map,
2807 tracker,
2808 mapper,
2809 config,
2810 imu_state,
2811 local_vi_ba_state,
2812 sparse_factor_graph_state,
2813 vi_init_state,
2814 vi_motion_init_state,
2815 pose_graph_state,
2816 relocalization_state,
2817 }
2818 }
2819
2820 pub fn vi_initialization_status(&self) -> ViInitializationStatus {
2824 match &self.vi_init_state {
2825 None => ViInitializationStatus::Disabled,
2826 Some(state) => state.snapshot(),
2827 }
2828 }
2829
2830 pub fn motion_vi_initialization_status(&self) -> MotionViInitializationStatus {
2835 match &self.vi_motion_init_state {
2836 None => MotionViInitializationStatus::Disabled,
2837 Some(state) => state.snapshot(),
2838 }
2839 }
2840
2841 pub fn push_imu_measurement(&mut self, gyro: Vector3<f64>, accel: Vector3<f64>, dt: f64) {
2847 if dt <= 0.0 || !dt.is_finite() {
2848 return;
2849 }
2850 if let Some(state) = self.imu_state.as_mut() {
2851 state.preintegrator.integrate_sample(gyro, accel, dt);
2852 }
2853 if let Some(state) = self.vi_init_state.as_mut() {
2858 if state.is_active() {
2859 state.initializer.push_sample(gyro, accel, dt);
2860 state.samples_buffered += 1;
2861 state.buffered_duration_seconds += dt;
2862 }
2863 }
2864 }
2865
2866 pub fn push_vi_initialization_measurement(
2873 &mut self,
2874 gyro: Vector3<f64>,
2875 accel: Vector3<f64>,
2876 dt: f64,
2877 ) {
2878 if dt <= 0.0 || !dt.is_finite() {
2879 return;
2880 }
2881 if let Some(state) = self.vi_init_state.as_mut() {
2882 if state.is_active() {
2883 state.initializer.push_sample(gyro, accel, dt);
2884 state.samples_buffered += 1;
2885 state.buffered_duration_seconds += dt;
2886 }
2887 }
2888 }
2889
2890 pub fn take_pending_imu_factor(&mut self) -> Option<ImuPreintegrationFactor> {
2899 self.imu_state
2900 .as_mut()
2901 .and_then(|s| s.pending_factor.take())
2902 }
2903
2904 pub const fn map(&self) -> &VisualMap {
2905 &self.map
2906 }
2907
2908 pub const fn map_mut(&mut self) -> &mut VisualMap {
2909 &mut self.map
2910 }
2911
2912 pub fn sync_sparse_factor_graph_keyframe(
2917 &mut self,
2918 keyframe_id: u64,
2919 ) -> Option<SparseFactorGraphUpdateStats> {
2920 if !self.map.keyframes.contains_key(&keyframe_id) {
2921 return None;
2922 }
2923 self.sparse_factor_graph_state
2924 .as_mut()
2925 .map(|graph| graph.update_from_map(&self.map, keyframe_id))
2926 }
2927
2928 pub fn scan_appearance_loops<Mat, V>(
2942 &self,
2943 matcher: &Mat,
2944 verifier: &V,
2945 camera: &Camera,
2946 settings: &AppearanceLoopScannerSettings,
2947 ) -> Vec<LoopClosureCandidate>
2948 where
2949 Mat: Matcher,
2950 V: LoopClosureVerifier,
2951 {
2952 let mut kfs: Vec<(&u64, &Keyframe)> = self.map.keyframes.iter().collect();
2954 kfs.sort_by_key(|(id, _)| *id);
2955 let views: Vec<PairwiseKeyframeView> = kfs
2956 .iter()
2957 .map(|(_, kf)| PairwiseKeyframeView {
2958 frame_id: kf.frame.id,
2959 keypoints: &kf.frame.keypoints,
2960 descriptors: &kf.frame.descriptors,
2961 })
2962 .collect();
2963 scan_pairwise_loop_closures(
2964 &views,
2965 matcher,
2966 verifier,
2967 camera,
2968 &PairwiseLoopClosureScannerConfig {
2969 min_keyframe_id_gap: settings.min_keyframe_id_gap,
2970 min_matches: settings.min_matches,
2971 },
2972 )
2973 }
2974}
2975
2976#[derive(Debug, Clone, Copy, PartialEq)]
2983pub struct AppearanceLoopScannerSettings {
2984 pub min_keyframe_id_gap: u64,
2989 pub min_matches: usize,
2992}
2993
2994impl Default for AppearanceLoopScannerSettings {
2995 fn default() -> Self {
2996 Self {
2997 min_keyframe_id_gap: 30,
2998 min_matches: 30,
2999 }
3000 }
3001}
3002
3003impl<P, Motion, K, Tri> OnlineSlamPipeline<Tracker<P, Motion>, LocalMappingPipeline<K, Tri>>
3004where
3005 P: FrameLocalizer,
3006 Motion: MotionModel,
3007 K: KeyframePolicy,
3008 Tri: Triangulator,
3009{
3010 pub fn process_frame<I>(&mut self, frame: &Frame, candidates: I) -> OnlineSlamResult
3011 where
3012 I: IntoIterator<Item = LandmarkCandidate>,
3013 {
3014 self.process_frame_with_metric_points(frame, candidates, &HashMap::new())
3015 }
3016
3017 pub fn process_frame_with_metric_points<I>(
3022 &mut self,
3023 frame: &Frame,
3024 candidates: I,
3025 metric_points_camera: &HashMap<usize, Point3<f64>>,
3026 ) -> OnlineSlamResult
3027 where
3028 I: IntoIterator<Item = LandmarkCandidate>,
3029 {
3030 let mut tracking = self.tracker.track_frame(frame, &self.map);
3031 let relocalization_stats = self.maybe_run_relocalization(frame, &mut tracking);
3038 let mut mapping = None;
3039 let mut applied_update = None;
3040 let mut loop_closure_candidates =
3041 detect_loop_closure_candidates(frame, &tracking, &self.map, &self.config.loop_closure);
3042
3043 if tracking.localization.success {
3044 let keyframe = keyframe_from_tracking_result(frame, &tracking);
3045 let mapping_result = self
3046 .mapper
3047 .process_keyframe(&self.map, &tracking, keyframe, candidates);
3048 if self.config.apply_map_updates && mapping_result.staged_update_validation.is_valid() {
3049 if let Ok(applied) = mapping_result.staged_update.clone().apply_to(&mut self.map) {
3050 if applied.keyframe_count > 0 {
3051 record_tracking_observation_confidences(&mut self.map, frame.id, &tracking);
3052 }
3053 applied_update = Some(applied);
3054 }
3055 }
3056 mapping = Some(mapping_result);
3057 }
3058
3059 let imu_factor = self.stage_imu_factor_on_new_keyframe(frame, applied_update.as_ref());
3067 let vi_init = self.run_vi_init_step(frame, applied_update.as_ref());
3073 let just_promoted_vi_init =
3074 matches!(vi_init, Some(ViInitializationEvent::Succeeded { .. }));
3075 let vi_motion_init =
3081 self.run_motion_vi_init_step(frame, applied_update.as_ref(), imu_factor.as_ref());
3082 let mut local_vi_ba = self.maybe_run_local_vi_ba(imu_factor.clone());
3083 let run_at_promotion = self
3091 .config
3092 .local_vi_ba
3093 .as_ref()
3094 .is_some_and(|c| c.run_at_vi_init_promotion);
3095 if just_promoted_vi_init && run_at_promotion && local_vi_ba.is_none() {
3096 if let Some(state) = self.local_vi_ba_state.as_mut() {
3097 local_vi_ba = crate::online_slam_vi_ba::run_local_vi_ba(&mut self.map, state);
3098 }
3099 }
3100 let sparse_factor_graph =
3101 self.maybe_update_sparse_factor_graph(frame.id, applied_update.as_ref());
3102 let covisibility_local_ba =
3107 self.maybe_run_covisibility_local_ba(frame, applied_update.as_ref());
3108
3109 let pose_graph_refinement = self.maybe_run_loop_closure_refinement(
3114 frame,
3115 &tracking,
3116 applied_update.as_ref(),
3117 &mut loop_closure_candidates,
3118 metric_points_camera,
3119 );
3120 if self
3121 .local_vi_ba_state
3122 .as_ref()
3123 .is_some_and(|s| !s.pending_recovered_pose_factors.is_empty())
3124 {
3125 let injected = self.maybe_inject_recovered_factors();
3126 if let Some(ref mut stats) = local_vi_ba.as_mut() {
3127 stats.recovered_marginal_factors_injected = injected;
3128 }
3129 }
3130
3131 OnlineSlamResult {
3132 tracking,
3133 mapping,
3134 applied_update,
3135 loop_closure_candidates,
3136 imu_factor,
3137 local_vi_ba,
3138 sparse_factor_graph,
3139 map_keyframe_count: self.map.keyframes.len(),
3140 map_landmark_count: self.map.landmarks.len(),
3141 vi_init,
3142 vi_motion_init,
3143 covisibility_local_ba,
3144 pose_graph_refinement,
3145 relocalization: relocalization_stats,
3146 }
3147 }
3148
3149 fn maybe_update_sparse_factor_graph(
3150 &mut self,
3151 frame_id: u64,
3152 applied_update: Option<&AppliedMapUpdate>,
3153 ) -> Option<SparseFactorGraphUpdateStats> {
3154 applied_update.filter(|update| update.keyframe_count > 0)?;
3155 self.sync_sparse_factor_graph_keyframe(frame_id)
3156 }
3157
3158 fn maybe_run_relocalization(
3170 &mut self,
3171 frame: &Frame,
3172 tracking: &mut TrackingResult,
3173 ) -> Option<OnlineSlamRelocalizationStats> {
3174 let state = self.relocalization_state.as_mut()?;
3175 if tracking.localization.success {
3176 state.consecutive_failed_attempts = 0;
3177 state.pending_confirmation = None;
3178 return None;
3179 }
3180 if state
3181 .config
3182 .max_consecutive_failed_attempts
3183 .is_some_and(|max| state.consecutive_failed_attempts >= max)
3184 {
3185 state.budget_skip_count = state.budget_skip_count.saturating_add(1);
3186 return None;
3187 }
3188 let attempt_interval_frames = state.config.attempt_interval_frames.max(1);
3189 if let Some(last_attempt_frame_id) = state.last_attempt_frame_id {
3190 if frame.id.saturating_sub(last_attempt_frame_id) < attempt_interval_frames {
3191 return None;
3192 }
3193 }
3194 state.trigger_count += 1;
3195 state.last_attempt_frame_id = Some(frame.id);
3196 let (recovered, mut stats, accept, tried_broader_descriptor_store) = {
3197 let pose_prior = if state.config.pose_prior_candidate_radius_meters.is_some() {
3198 self.tracker.pose_prior_for_frame(frame)
3199 } else {
3200 None
3201 };
3202 let candidate_radius = state.config.pose_prior_candidate_radius_meters;
3203 let localize_with_store =
3204 |descriptor_store: &visloc_core::types::LandmarkDescriptorStore| {
3205 if pose_prior.is_some() {
3206 state
3207 .localizer
3208 .localize_frame_with_pose_prior_warm_start_and_descriptor_store(
3209 frame,
3210 &self.map,
3211 descriptor_store,
3212 pose_prior.as_ref(),
3213 candidate_radius,
3214 )
3215 } else {
3216 state.localizer.localize_frame_with_descriptor_store(
3217 frame,
3218 &self.map,
3219 descriptor_store,
3220 )
3221 }
3222 };
3223 let build_attempt_stats =
3224 |recovered: &visloc_core::types::LocalizationResult,
3225 descriptor_store_landmark_count: usize,
3226 covisibility_local_descriptor_store_landmark_count: Option<usize>,
3227 appearance_descriptor_store_landmark_count: Option<usize>,
3228 broader_descriptor_store_landmark_count: Option<usize>,
3229 tried_covisibility_local_descriptor_store: bool,
3230 used_covisibility_local_descriptor_store: bool,
3231 tried_appearance_descriptor_store: bool,
3232 used_appearance_descriptor_store: bool,
3233 tried_broader_descriptor_store_fallback: bool,
3234 broader_descriptor_store_retry_skipped_by_interval: bool,
3235 used_broader_descriptor_store_fallback: bool,
3236 covisibility_reference_keyframe_id: Option<u64>,
3237 appearance_candidate_keyframe_count: usize,
3238 appearance_best_similarity: Option<f32>,
3239 appearance_best_keyframe_id: Option<u64>,
3240 appearance_candidates: Vec<OnlineSlamRelocalizationAppearanceCandidate>| {
3241 let mut stats = OnlineSlamRelocalizationStats {
3242 attempted: true,
3243 localization_success: recovered.success,
3244 succeeded: false,
3245 inlier_count: recovered.inlier_count,
3246 inlier_ratio: recovered.inlier_ratio,
3247 correspondence_count: recovered.correspondence_count,
3248 mean_reprojection_error: recovered.reprojection_error,
3249 translation_from_last_success_meters: None,
3250 translation_per_frame_from_last_success_meters: None,
3251 inlier_depth_median_meters: None,
3252 last_success_inlier_depth_median_meters: None,
3253 inlier_depth_median_ratio_to_last_success: None,
3254 passed_acceptance_gates: false,
3255 confirmation_count: 0,
3256 confirmation_required_count: state
3257 .config
3258 .confirmation_required_recoveries
3259 .max(1),
3260 confirmation_translation_per_frame_from_previous_meters: None,
3261 descriptor_store_landmark_count,
3262 covisibility_local_descriptor_store_landmark_count,
3263 appearance_descriptor_store_landmark_count,
3264 broader_descriptor_store_landmark_count,
3265 tried_covisibility_local_descriptor_store,
3266 used_covisibility_local_descriptor_store,
3267 tried_appearance_descriptor_store,
3268 used_appearance_descriptor_store,
3269 tried_broader_descriptor_store_fallback,
3270 broader_descriptor_store_retry_skipped_by_interval,
3271 used_broader_descriptor_store_fallback,
3272 covisibility_reference_keyframe_id,
3273 appearance_candidate_keyframe_count,
3274 appearance_best_similarity,
3275 appearance_best_keyframe_id,
3276 appearance_candidates,
3277 };
3278 if let (Some(last_pose), Some(recovered_pose)) =
3279 (self.tracker.last_successful_pose(), recovered.pose.as_ref())
3280 {
3281 let translation = (recovered_pose.camera_center_world()
3282 - last_pose.camera_center_world())
3283 .norm();
3284 stats.translation_from_last_success_meters = Some(translation);
3285 if let Some(last_frame_id) = self.tracker.last_successful_frame_id() {
3286 let frame_gap = frame.id.saturating_sub(last_frame_id).max(1) as f64;
3287 stats.translation_per_frame_from_last_success_meters =
3288 Some(translation / frame_gap);
3289 }
3290 stats.inlier_depth_median_meters = median_positive_depth_for_landmarks(
3291 &self.map,
3292 recovered_pose,
3293 &recovered.inlier_landmark_ids,
3294 );
3295 stats.last_success_inlier_depth_median_meters =
3296 median_positive_depth_for_landmarks(
3297 &self.map,
3298 last_pose,
3299 &recovered.inlier_landmark_ids,
3300 );
3301 if let (Some(recovered_depth), Some(last_depth)) = (
3302 stats.inlier_depth_median_meters,
3303 stats.last_success_inlier_depth_median_meters,
3304 ) {
3305 if last_depth > 0.0 {
3306 stats.inlier_depth_median_ratio_to_last_success =
3307 Some(recovered_depth / last_depth);
3308 }
3309 }
3310 }
3311 let basic_accept = recovered.success
3312 && recovered.inlier_count >= state.config.min_inliers
3313 && recovered.inlier_ratio >= state.config.min_inlier_ratio
3314 && match (
3315 state.config.max_mean_reprojection_error,
3316 recovered.reprojection_error,
3317 ) {
3318 (Some(max), Some(actual)) => actual <= max,
3319 (Some(_), None) => false,
3320 (None, _) => true,
3321 };
3322 let imu_accept = if let Some(max_dist) =
3323 state.config.max_translation_from_imu_prediction_meters
3324 {
3325 match (
3326 self.tracker.pose_prior_for_frame(frame),
3327 recovered.pose.as_ref(),
3328 ) {
3329 (Some(predicted), Some(recovered_pose)) => {
3330 let predicted_centre =
3331 predicted.world_to_camera.inverse().translation;
3332 let recovered_centre =
3333 recovered_pose.world_to_camera.inverse().translation;
3334 (recovered_centre - predicted_centre).norm() <= max_dist
3335 }
3336 _ => true,
3337 }
3338 } else {
3339 true
3340 };
3341 let continuity_accept = match (
3342 state
3343 .config
3344 .max_translation_per_frame_from_last_success_meters,
3345 stats.translation_per_frame_from_last_success_meters,
3346 ) {
3347 (Some(max), Some(actual)) => actual <= max,
3348 (Some(_), None) => true,
3349 (None, _) => true,
3350 };
3351 let depth_ratio_accept = match stats.inlier_depth_median_ratio_to_last_success {
3352 Some(ratio) => {
3353 state
3354 .config
3355 .min_inlier_depth_median_ratio_to_last_success
3356 .is_none_or(|min| ratio >= min)
3357 && state
3358 .config
3359 .max_inlier_depth_median_ratio_to_last_success
3360 .is_none_or(|max| ratio <= max)
3361 }
3362 None => true,
3363 };
3364 let accept =
3365 basic_accept && imu_accept && continuity_accept && depth_ratio_accept;
3366 stats.passed_acceptance_gates = accept;
3367 (stats, accept)
3368 };
3369
3370 let mut broader_descriptor_store =
3371 Some(relocalization_recent_keyframe_descriptor_store(
3372 &self.map,
3373 state.config.recent_keyframe_window,
3374 ));
3375 let appearance_store =
3376 state
3377 .config
3378 .appearance_retrieval_map
3379 .as_ref()
3380 .and_then(|appearance_config| {
3381 relocalization_appearance_descriptor_store(
3382 &self.map,
3383 frame,
3384 appearance_config,
3385 )
3386 });
3387 let covis_store =
3388 state
3389 .config
3390 .covisibility_local_map
3391 .as_ref()
3392 .and_then(|covis_config| {
3393 self.tracker
3394 .last_successful_frame_id()
3395 .and_then(|last_id| {
3396 relocalization_pick_covisibility_reference_keyframe(
3397 &self.map, last_id,
3398 )
3399 })
3400 .and_then(|reference_id| {
3401 relocalization_covisibility_descriptor_store(
3402 &self.map,
3403 reference_id,
3404 covis_config,
3405 )
3406 .map(|store| (reference_id, store))
3407 })
3408 });
3409 let (
3410 initial_descriptor_store,
3411 initial_store_kind,
3412 reference_keyframe_id,
3413 appearance_candidate_keyframe_count,
3414 appearance_best_similarity,
3415 appearance_best_keyframe_id,
3416 appearance_candidates,
3417 ) = if let Some(appearance) = appearance_store {
3418 (
3419 appearance.store,
3420 RelocalizationDescriptorStoreKind::AppearanceRetrieval,
3421 None,
3422 appearance.candidate_keyframe_count,
3423 appearance.best_similarity,
3424 appearance.best_keyframe_id,
3425 appearance.candidates,
3426 )
3427 } else if let Some((reference_keyframe_id, store)) = covis_store {
3428 (
3429 store,
3430 RelocalizationDescriptorStoreKind::CovisibilityLocal,
3431 Some(reference_keyframe_id),
3432 0,
3433 None,
3434 None,
3435 Vec::new(),
3436 )
3437 } else {
3438 (
3439 broader_descriptor_store
3440 .take()
3441 .expect("broader descriptor store was built"),
3442 RelocalizationDescriptorStoreKind::Broader,
3443 None,
3444 0,
3445 None,
3446 None,
3447 Vec::new(),
3448 )
3449 };
3450 let fallback_to_broader_store_on_failure = match initial_store_kind {
3451 RelocalizationDescriptorStoreKind::AppearanceRetrieval => state
3452 .config
3453 .appearance_retrieval_map
3454 .as_ref()
3455 .is_some_and(|config| config.fallback_to_broader_store_on_failure),
3456 RelocalizationDescriptorStoreKind::CovisibilityLocal => state
3457 .config
3458 .covisibility_local_map
3459 .as_ref()
3460 .is_some_and(|config| config.fallback_to_broader_store_on_failure),
3461 RelocalizationDescriptorStoreKind::Broader => false,
3462 };
3463 let compare_broader_store_on_success = match initial_store_kind {
3464 RelocalizationDescriptorStoreKind::AppearanceRetrieval => state
3465 .config
3466 .appearance_retrieval_map
3467 .as_ref()
3468 .is_some_and(|config| config.compare_broader_store_on_success),
3469 RelocalizationDescriptorStoreKind::CovisibilityLocal => state
3470 .config
3471 .covisibility_local_map
3472 .as_ref()
3473 .is_some_and(|config| config.compare_broader_store_on_success),
3474 RelocalizationDescriptorStoreKind::Broader => false,
3475 };
3476 let broader_store_retry_interval_frames = match initial_store_kind {
3477 RelocalizationDescriptorStoreKind::AppearanceRetrieval => state
3478 .config
3479 .appearance_retrieval_map
3480 .as_ref()
3481 .map_or(1, |config| {
3482 config.broader_store_retry_interval_frames.max(1)
3483 }),
3484 RelocalizationDescriptorStoreKind::CovisibilityLocal => state
3485 .config
3486 .covisibility_local_map
3487 .as_ref()
3488 .map_or(1, |config| {
3489 config.broader_store_retry_interval_frames.max(1)
3490 }),
3491 RelocalizationDescriptorStoreKind::Broader => 1,
3492 };
3493 let broader_retry_interval_allows = state
3494 .last_broader_descriptor_store_retry_frame_id
3495 .is_none_or(|last_frame_id| {
3496 frame.id.saturating_sub(last_frame_id) >= broader_store_retry_interval_frames
3497 });
3498 let initial_is_covisibility =
3499 initial_store_kind == RelocalizationDescriptorStoreKind::CovisibilityLocal;
3500 let initial_is_appearance =
3501 initial_store_kind == RelocalizationDescriptorStoreKind::AppearanceRetrieval;
3502 let initial_is_narrow =
3503 initial_store_kind != RelocalizationDescriptorStoreKind::Broader;
3504 let covisibility_local_descriptor_store_landmark_count =
3505 initial_is_covisibility.then_some(initial_descriptor_store.len());
3506 let appearance_descriptor_store_landmark_count =
3507 initial_is_appearance.then_some(initial_descriptor_store.len());
3508 let mut recovered = localize_with_store(&initial_descriptor_store);
3509 let (mut stats, mut accept) = build_attempt_stats(
3510 &recovered,
3511 initial_descriptor_store.len(),
3512 covisibility_local_descriptor_store_landmark_count,
3513 appearance_descriptor_store_landmark_count,
3514 None,
3515 initial_is_covisibility,
3516 initial_is_covisibility,
3517 initial_is_appearance,
3518 initial_is_appearance,
3519 false,
3520 false,
3521 false,
3522 reference_keyframe_id,
3523 appearance_candidate_keyframe_count,
3524 appearance_best_similarity,
3525 appearance_best_keyframe_id,
3526 appearance_candidates.clone(),
3527 );
3528 let wants_broader_retry = initial_is_narrow
3529 && ((!accept && fallback_to_broader_store_on_failure)
3530 || (accept && compare_broader_store_on_success));
3531 let should_try_broader = wants_broader_retry && broader_retry_interval_allows;
3532 if wants_broader_retry && !broader_retry_interval_allows {
3533 stats.broader_descriptor_store_retry_skipped_by_interval = true;
3534 }
3535 if should_try_broader {
3536 let broader_store = broader_descriptor_store.take().unwrap_or_else(|| {
3537 relocalization_recent_keyframe_descriptor_store(
3538 &self.map,
3539 state.config.recent_keyframe_window,
3540 )
3541 });
3542 let broader_store_len = broader_store.len();
3543 let broader_recovered = localize_with_store(&broader_store);
3544 let (broader_stats, broader_accept) = build_attempt_stats(
3545 &broader_recovered,
3546 broader_store_len,
3547 covisibility_local_descriptor_store_landmark_count,
3548 appearance_descriptor_store_landmark_count,
3549 Some(broader_store_len),
3550 initial_is_covisibility,
3551 false,
3552 initial_is_appearance,
3553 false,
3554 true,
3555 false,
3556 true,
3557 reference_keyframe_id,
3558 appearance_candidate_keyframe_count,
3559 appearance_best_similarity,
3560 appearance_best_keyframe_id,
3561 appearance_candidates,
3562 );
3563 stats.tried_broader_descriptor_store_fallback = true;
3564 stats.broader_descriptor_store_landmark_count = Some(broader_store_len);
3565 let use_broader = if !accept {
3566 true
3567 } else {
3568 broader_accept
3569 && relocalization_result_has_better_score(&broader_recovered, &recovered)
3570 };
3571 if use_broader {
3572 recovered = broader_recovered;
3573 stats = broader_stats;
3574 accept = broader_accept;
3575 }
3576 }
3577 (recovered, stats, accept, should_try_broader)
3578 };
3579 if tried_broader_descriptor_store {
3580 state.last_broader_descriptor_store_retry_frame_id = Some(frame.id);
3581 }
3582 if !accept {
3583 state.consecutive_failed_attempts = state.consecutive_failed_attempts.saturating_add(1);
3584 state.pending_confirmation = None;
3585 return Some(stats);
3586 }
3587 let confirmation_required = state.config.confirmation_required_recoveries.max(1);
3588 stats.confirmation_required_count = confirmation_required;
3589 if confirmation_required > 1 {
3590 let Some(recovered_pose) = recovered.pose.as_ref() else {
3591 state.consecutive_failed_attempts =
3592 state.consecutive_failed_attempts.saturating_add(1);
3593 state.pending_confirmation = None;
3594 stats.passed_acceptance_gates = false;
3595 return Some(stats);
3596 };
3597 let mut confirmation_count = 1usize;
3598 if let Some(pending) = state.pending_confirmation.as_ref() {
3599 let translation = (recovered_pose.camera_center_world()
3600 - pending.pose.camera_center_world())
3601 .norm();
3602 let frame_gap = frame.id.saturating_sub(pending.frame_id).max(1) as f64;
3603 let translation_per_frame = translation / frame_gap;
3604 stats.confirmation_translation_per_frame_from_previous_meters =
3605 Some(translation_per_frame);
3606 let chain_is_consistent = state
3607 .config
3608 .confirmation_max_translation_per_frame_meters
3609 .is_none_or(|max| translation_per_frame <= max);
3610 if chain_is_consistent {
3611 confirmation_count = pending.count.saturating_add(1);
3612 }
3613 }
3614 stats.confirmation_count = confirmation_count;
3615 if confirmation_count < confirmation_required {
3616 state.pending_confirmation = Some(OnlineSlamRelocalizationPendingConfirmation {
3617 frame_id: frame.id,
3618 pose: recovered_pose.clone(),
3619 count: confirmation_count,
3620 });
3621 return Some(stats);
3622 }
3623 state.pending_confirmation = None;
3624 } else {
3625 stats.confirmation_count = 1;
3626 state.pending_confirmation = None;
3627 }
3628 let recovered_tracking = TrackingResult {
3629 frame_id: frame.id,
3630 state: visloc_tracking::TrackingState::Tracking,
3631 event: visloc_tracking::TrackingEvent::Relocalized,
3632 successive_failures: 0,
3633 pose_prior: tracking.pose_prior.clone(),
3634 used_pose_prior: tracking.used_pose_prior,
3635 used_external_localization_prior: tracking.used_external_localization_prior,
3636 external_localization_prior_radius: tracking.external_localization_prior_radius,
3637 tracking_failure_reason: None,
3638 map_landmark_count: tracking.map_landmark_count,
3639 map_stats: tracking.map_stats,
3640 localization: recovered,
3641 covisibility_local_map_size: tracking.covisibility_local_map_size,
3642 };
3643 self.tracker
3644 .accept_relocalization_result(recovered_tracking.clone());
3645 state.success_count += 1;
3646 state.consecutive_failed_attempts = 0;
3647 state.last_success_frame_id = Some(frame.id);
3648 stats.succeeded = true;
3649 *tracking = recovered_tracking;
3650 Some(stats)
3651 }
3652
3653 fn maybe_run_loop_closure_refinement(
3667 &mut self,
3668 frame: &Frame,
3669 tracking: &TrackingResult,
3670 applied_update: Option<&AppliedMapUpdate>,
3671 loop_closure_candidates: &mut [LoopClosureCandidate],
3672 metric_points_camera: &HashMap<usize, Point3<f64>>,
3673 ) -> Option<OnlineSlamLoopClosureRefinementStats> {
3674 let state = self.pose_graph_state.as_mut()?;
3675 applied_update?;
3681 let new_keyframe_id = frame.id;
3682 let new_pose = self
3685 .map
3686 .keyframes
3687 .get(&new_keyframe_id)
3688 .and_then(|kf| kf.frame.pose.clone())?;
3689 let mut stats = OnlineSlamLoopClosureRefinementStats::default();
3690
3691 let prev_keyframe_id = state.keyframe_order.last().copied();
3695 state.graph.add_pose(new_keyframe_id, new_pose.clone());
3696 if let Some(sim3_graph) = state.sim3_graph.as_mut() {
3697 sim3_graph.add_pose(
3698 new_keyframe_id,
3699 sim3_at_unit_scale(&new_pose.world_to_camera),
3700 );
3701 }
3702 if state.keyframe_order.is_empty() {
3703 state.graph.anchor(new_keyframe_id);
3704 if let Some(sim3_graph) = state.sim3_graph.as_mut() {
3705 sim3_graph.anchor(new_keyframe_id);
3706 }
3707 } else if let Some(prev_id) = prev_keyframe_id {
3708 if let Some(prev_pose) = state.graph.poses.get(&prev_id).cloned() {
3709 let relative = relative_world_to_camera(&prev_pose, &new_pose);
3710 if let Some(sim3_graph) = state.sim3_graph.as_mut() {
3711 sim3_graph.add_edge(
3717 prev_id,
3718 new_keyframe_id,
3719 sim3_at_unit_scale(&relative),
3720 1.0,
3721 );
3722 }
3723 let sequential_information =
3724 state
3725 .config
3726 .loop_pose_information
3727 .map(|information_config| {
3728 if !matches!(state.config.solver, LoopRefinementSolver::Se3) {
3729 return Err(LoopPoseInformationFailure::UnsupportedSolver);
3730 }
3731 let pnp_inliers: Vec<(usize, u64)> = tracking
3732 .localization
3733 .inlier_query_indices
3734 .iter()
3735 .copied()
3736 .zip(tracking.localization.inlier_landmark_ids.iter().copied())
3737 .collect();
3738 let measurement = LoopClosureConstraint {
3739 from_keyframe_id: prev_id,
3740 to_keyframe_id: new_keyframe_id,
3741 relative_pose: relative.clone(),
3742 inlier_count: pnp_inliers.len(),
3743 inlier_ratio: 1.0,
3744 mean_sampson_error: 0.0,
3745 score: pnp_inliers.len() as f64,
3746 };
3747 estimate_loop_pose_information(
3748 &self.map,
3749 frame,
3750 &state.config.camera,
3751 &measurement,
3752 &pnp_inliers,
3753 information_config,
3754 )
3755 });
3756 if let Some(Ok((information, diagnostic))) = sequential_information {
3757 state.graph.add_edge_with_information(
3758 prev_id,
3759 new_keyframe_id,
3760 relative,
3761 PoseGraphEdgeKind::Sequential,
3762 information,
3763 );
3764 stats.sequential_edges_with_pose_information += 1;
3765 stats
3766 .sequential_pose_information_diagnostics
3767 .push(diagnostic);
3768 } else {
3769 state
3770 .graph
3771 .add_sequential_edge(prev_id, new_keyframe_id, relative);
3772 if state.config.loop_pose_information.is_some() {
3773 stats.sequential_pose_information_fallbacks += 1;
3774 }
3775 if let Some(Err(reason)) = sequential_information {
3776 stats.sequential_pose_information_failures.record(reason);
3777 }
3778 }
3779 }
3780 }
3781 state.keyframe_order.push(new_keyframe_id);
3782
3783 if state.config.appearance_candidates.is_some() {
3788 if let Some(mean_descriptor) = relocalization_mean_descriptor(&frame.descriptors) {
3789 state
3790 .appearance_descriptor_cache
3791 .insert(new_keyframe_id, mean_descriptor);
3792 }
3793 }
3794
3795 if !loop_closure_candidates.is_empty() {
3803 stats.verified_candidate_count = loop_closure_candidates.len();
3804 match &state.config.verifier {
3805 LoopRefinementVerifier::EssentialMatrix => {
3806 let verifier = EssentialMatrixLoopClosureVerifier {
3807 config: state.config.verifier_config,
3808 ..Default::default()
3809 };
3810 verify_loop_closure_candidates(
3811 loop_closure_candidates,
3812 frame,
3813 tracking,
3814 &self.map,
3815 &state.config.camera,
3816 &verifier,
3817 );
3818 }
3819 LoopRefinementVerifier::Pnp(pnp_config) => {
3820 let verifier = PnPLoopClosureVerifier {
3821 ransac: PnPRansac::default(),
3822 config: *pnp_config,
3823 };
3824 verify_loop_closure_candidates_pnp(
3825 loop_closure_candidates,
3826 frame,
3827 tracking,
3828 &self.map,
3829 &state.config.camera,
3830 &verifier,
3831 );
3832 }
3833 }
3834 }
3835
3836 let appearance_candidates: Vec<LoopClosureCandidate> = if let Some(appearance_config) =
3843 state.config.appearance_candidates.clone()
3844 {
3845 stats.appearance_ranked_candidate_count =
3846 relocalization_mean_descriptor(&frame.descriptors).map_or(0, |descriptor| {
3847 rank_appearance_loop_candidate_keyframes(
3848 &state.appearance_descriptor_cache,
3849 frame.id,
3850 &descriptor,
3851 appearance_config.min_similarity,
3852 appearance_config.min_keyframe_id_gap,
3853 )
3854 .len()
3855 .min(appearance_config.max_candidates_per_frame.max(1))
3856 });
3857 let mut builder_config = appearance_config.clone();
3858 builder_config.min_covisible_keyframe_verifications = 1;
3862 let built = build_appearance_loop_candidates_with_diagnostics(
3863 &self.map,
3864 frame,
3865 &state.appearance_descriptor_cache,
3866 &builder_config,
3867 &state.config.camera,
3868 );
3869 stats.appearance_connected_region_rejected_count =
3870 built.connected_region_rejected_count;
3871 stats.appearance_pnp_verified_count = built.pnp_verified_count;
3872 stats.appearance_projection_rejected_count = built.projection_rejected_count;
3873 stats.appearance_covisibility_rejected_count = built.covisibility_rejected_count;
3874 let mut candidates = built.candidates;
3875 let pending_needs_projection =
3876 state
3877 .appearance_pending_region
3878 .as_ref()
3879 .is_some_and(|pending| {
3880 !candidates.iter().any(|candidate| {
3881 appearance_regions_overlap(
3882 &self.map,
3883 pending.root_keyframe_id,
3884 candidate.matched_keyframe_id,
3885 &appearance_config,
3886 )
3887 })
3888 });
3889 if pending_needs_projection {
3890 let projected = verify_pending_appearance_region_by_projection(
3891 &self.map,
3892 frame,
3893 &state.config.camera,
3894 &appearance_config,
3895 state
3896 .appearance_pending_region
3897 .as_ref()
3898 .expect("pending projection was requested"),
3899 );
3900 stats.appearance_pending_projection_attempted_count =
3901 usize::from(projected.attempted);
3902 stats.appearance_pending_projection_verified_count =
3903 usize::from(projected.candidate.is_some());
3904 stats.appearance_pending_projection_correspondence_count =
3905 projected.correspondence_count;
3906 stats.appearance_pending_projection_inlier_count = projected.inlier_count;
3907 stats.appearance_pending_projection_search_radius_px = projected.search_radius_px;
3908 if let Some(candidate) = projected.candidate {
3909 candidates.push(candidate);
3910 }
3911 }
3912 stats.appearance_candidate_count = candidates.len();
3913 stats.appearance_candidate_diagnostics = built.diagnostics;
3914 let (confirmed, waiting, just_confirmed) = confirm_appearance_region_across_keyframes(
3915 &self.map,
3916 frame.id,
3917 candidates,
3918 &appearance_config,
3919 &mut state.appearance_pending_region,
3920 );
3921 stats.appearance_region_confirmation_waiting = waiting;
3922 stats.appearance_region_confirmed_count = usize::from(just_confirmed);
3923 confirmed
3924 } else {
3925 Vec::new()
3926 };
3927
3928 if !loop_closure_candidates.is_empty() || !appearance_candidates.is_empty() {
3929 let pcm_cfg = state.config.pcm;
3934 let odometry: BTreeMap<u64, SE3> = if pcm_cfg.is_some() {
3935 state
3936 .graph
3937 .poses
3938 .iter()
3939 .map(|(id, p)| (*id, p.world_to_camera.clone()))
3940 .collect()
3941 } else {
3942 BTreeMap::new()
3943 };
3944 let mut admitted: Vec<pcm::LoopMeasurement> = if pcm_cfg.is_some() {
3945 state
3946 .verified_constraints
3947 .iter()
3948 .map(loop_measurement_of)
3949 .collect()
3950 } else {
3951 Vec::new()
3952 };
3953
3954 let tagged_candidates = loop_closure_candidates
3958 .iter()
3959 .map(|candidate| (candidate, LoopClosureCandidateSource::SharedLandmark))
3960 .chain(
3961 appearance_candidates
3962 .iter()
3963 .map(|candidate| (candidate, LoopClosureCandidateSource::Appearance)),
3964 );
3965
3966 for (candidate, source) in tagged_candidates {
3967 let Some(constraint) = LoopClosureConstraint::from_verified_candidate(candidate)
3968 else {
3969 continue;
3970 };
3971 if !state.graph.poses.contains_key(&constraint.from_keyframe_id) {
3975 continue;
3976 }
3977 let measured_sim3_scale =
3978 if matches!(state.config.solver, LoopRefinementSolver::Sim3(_))
3979 && source == LoopClosureCandidateSource::Appearance
3980 {
3981 let scale = match estimate_loop_sim3_scale_3d3d(
3982 &self.map,
3983 constraint.from_keyframe_id,
3984 constraint.to_keyframe_id,
3985 &candidate.pnp_query_landmark_pairs,
3986 metric_points_camera,
3987 ) {
3988 Ok(scale) => scale,
3989 Err(reason) => {
3990 stats.appearance_scale_estimation_failed_count += 1;
3991 match reason {
3992 Sim3ScaleEstimationFailure::InsufficientPoints => {
3993 stats.appearance_scale_insufficient_points_count += 1;
3994 }
3995 Sim3ScaleEstimationFailure::InsufficientMatches => {
3996 stats.appearance_scale_insufficient_matches_count += 1;
3997 }
3998 Sim3ScaleEstimationFailure::NoConsensus => {
3999 stats.appearance_scale_no_consensus_count += 1;
4000 }
4001 }
4002 continue;
4006 }
4007 };
4008 if (scale - 1.0).abs() < 0.05 {
4009 stats.appearance_near_unit_scale_count += 1;
4010 continue;
4014 }
4015 Some(scale)
4016 } else {
4017 None
4018 };
4019 let loop_information =
4020 if let Some(information_config) = state.config.loop_pose_information {
4021 let estimate = if matches!(state.config.solver, LoopRefinementSolver::Se3) {
4024 estimate_loop_pose_information(
4025 &self.map,
4026 frame,
4027 &state.config.camera,
4028 &constraint,
4029 &candidate.pnp_query_landmark_pairs,
4030 information_config,
4031 )
4032 } else {
4033 Err(LoopPoseInformationFailure::UnsupportedSolver)
4034 };
4035 let (mut information, diagnostic) = match estimate {
4036 Ok(estimate) => estimate,
4037 Err(reason) => {
4038 stats.loop_pose_information_failures.record(reason);
4039 stats.loop_closures_pose_information_rejected += 1;
4040 stats
4041 .rejected_constraints
4042 .push(OnlineSlamRejectedLoopConstraint {
4043 from_keyframe_id: constraint.from_keyframe_id,
4044 to_keyframe_id: constraint.to_keyframe_id,
4045 inlier_count: constraint.inlier_count,
4046 translation_norm_m: constraint.relative_pose.translation.norm(),
4047 relative_pose: constraint.relative_pose.clone(),
4048 source,
4049 reason: OnlineSlamLoopConstraintRejectionReason::PoseInformation,
4050 });
4051 continue;
4052 }
4053 };
4054 information =
4058 apply_loop_edge_scale(information, information_config.loop_edge_scale);
4059 stats.loop_pose_information_diagnostics.push(diagnostic);
4060 state.loop_pose_information.insert(
4061 (constraint.from_keyframe_id, constraint.to_keyframe_id),
4062 information,
4063 );
4064 Some(information)
4065 } else {
4066 None
4067 };
4068 let pcm_measurement = pcm_cfg.as_ref().map(|cfg| {
4071 let m = loop_measurement_of(&constraint);
4072 (pcm_admits_loop(&m, &admitted, &odometry, cfg), m)
4073 });
4074 if let Some((false, _)) = pcm_measurement {
4075 stats.loop_closures_pcm_rejected += 1;
4076 stats
4077 .rejected_constraints
4078 .push(OnlineSlamRejectedLoopConstraint {
4079 from_keyframe_id: constraint.from_keyframe_id,
4080 to_keyframe_id: constraint.to_keyframe_id,
4081 inlier_count: constraint.inlier_count,
4082 translation_norm_m: constraint.relative_pose.translation.norm(),
4083 relative_pose: constraint.relative_pose.clone(),
4084 source,
4085 reason: OnlineSlamLoopConstraintRejectionReason::Pcm,
4086 });
4087 if state.config.pcm_batch_rescreen {
4090 state.pcm_deferred.push(constraint);
4091 }
4092 continue;
4093 }
4094 if let Some(threshold) = state.config.covariance_gate {
4095 if !covariance_gate_admits(&state.graph, &constraint, threshold) {
4096 stats.loop_closures_covariance_rejected += 1;
4097 stats
4098 .rejected_constraints
4099 .push(OnlineSlamRejectedLoopConstraint {
4100 from_keyframe_id: constraint.from_keyframe_id,
4101 to_keyframe_id: constraint.to_keyframe_id,
4102 inlier_count: constraint.inlier_count,
4103 translation_norm_m: constraint.relative_pose.translation.norm(),
4104 relative_pose: constraint.relative_pose.clone(),
4105 source,
4106 reason: OnlineSlamLoopConstraintRejectionReason::Covariance,
4107 });
4108 continue;
4109 }
4110 }
4111 if let Some((_, m)) = pcm_measurement {
4112 admitted.push(m);
4113 }
4114 let loop_edge_weight = state
4115 .config
4116 .fixed_loop_edge_weight
4117 .filter(|weight| weight.is_finite() && *weight > 0.0)
4118 .unwrap_or_else(|| (constraint.inlier_count as f64).max(1.0));
4119 if let Some(information) = loop_information {
4120 state.graph.add_edge_with_information(
4121 constraint.from_keyframe_id,
4122 constraint.to_keyframe_id,
4123 constraint.relative_pose.clone(),
4124 PoseGraphEdgeKind::LoopClosure,
4125 information,
4126 );
4127 stats.loop_closures_with_pose_information += 1;
4128 } else {
4129 state
4130 .graph
4131 .add_loop_closure_constraint_with_weight(&constraint, loop_edge_weight);
4132 }
4133 if let Some(sim3_graph) = state.sim3_graph.as_mut() {
4134 sim3_graph.add_edge(
4135 constraint.from_keyframe_id,
4136 constraint.to_keyframe_id,
4137 Sim3::new(
4138 constraint.relative_pose.rotation,
4139 constraint.relative_pose.translation,
4140 measured_sim3_scale.unwrap_or(1.0),
4141 ),
4142 loop_edge_weight,
4143 );
4144 }
4145 stats
4146 .admitted_constraints
4147 .push(OnlineSlamAdmittedLoopConstraint {
4148 from_keyframe_id: constraint.from_keyframe_id,
4149 to_keyframe_id: constraint.to_keyframe_id,
4150 inlier_count: constraint.inlier_count,
4151 translation_norm_m: constraint.relative_pose.translation.norm(),
4152 relative_pose: constraint.relative_pose.clone(),
4153 source,
4154 });
4155 if source == LoopClosureCandidateSource::Appearance {
4156 stats.appearance_accepted_count += 1;
4157 if state.config.fuse_loop_observations {
4158 state
4159 .pending_loop_observation_fusions
4160 .push(PendingLoopObservationFusion {
4161 from_keyframe_id: constraint.from_keyframe_id,
4162 query_keyframe_id: constraint.to_keyframe_id,
4163 relative_pose: constraint.relative_pose.clone(),
4164 pairs: candidate.pnp_query_landmark_pairs.clone(),
4165 });
4166 }
4167 }
4168 state.verified_constraints.push(constraint);
4169 state.pending_since_last_trigger += 1;
4170 stats.accepted_count += 1;
4171 }
4172
4173 if state.config.pcm_batch_rescreen {
4180 if let Some(cfg) = pcm_cfg {
4181 let (promoted, evicted) = pcm_batch_reconcile(
4182 &mut state.graph,
4183 &mut state.verified_constraints,
4184 &mut state.pcm_deferred,
4185 &odometry,
4186 &cfg,
4187 state.config.fixed_loop_edge_weight,
4188 );
4189 stats.loop_closures_pcm_promoted = promoted;
4190 stats.loop_closures_pcm_evicted = evicted;
4191 for edge in &mut state.graph.edges {
4195 if edge.kind != PoseGraphEdgeKind::LoopClosure || edge.information.is_some()
4196 {
4197 continue;
4198 }
4199 if let Some(information) = state
4200 .loop_pose_information
4201 .get(&(edge.from, edge.to))
4202 .copied()
4203 {
4204 edge.information = Some(information);
4205 stats.loop_closures_with_pose_information += 1;
4206 }
4207 }
4208 state.pending_since_last_trigger += promoted + evicted;
4210 }
4211 }
4212 }
4213
4214 let trigger_threshold = state.config.trigger_every_new_constraints.max(1);
4218 if state.pending_since_last_trigger >= trigger_threshold {
4219 let pgo_config = state.config.pose_graph_config.clone();
4220 let sim3_solver_config = match &state.config.solver {
4221 LoopRefinementSolver::Sim3(cfg) => Some(cfg.clone()),
4222 LoopRefinementSolver::Se3 => None,
4223 };
4224 let pre_solve_sim3_nodes = state.sim3_graph.as_ref().map(|graph| graph.poses.clone());
4230 state.pending_since_last_trigger = 0;
4231 state.trigger_count += 1;
4232 let solved = if let Some(sim3_config) = sim3_solver_config {
4242 match state
4243 .sim3_graph
4244 .get_or_insert_with(Sim3PoseGraph::new)
4245 .optimize(&sim3_config)
4246 {
4247 Ok(result) => {
4248 stats.sim3_scale_spread =
4249 state.sim3_graph.as_ref().and_then(sim3_pose_scale_spread);
4250 stats.sim3_pose_graph_result = Some(result);
4251 true
4252 }
4253 Err(_) => false,
4254 }
4255 } else if let Some(gnc_config) = state.config.gnc {
4256 match state.graph.optimize_se3_gnc(&pgo_config, &gnc_config) {
4257 Ok(result) => {
4258 stats.loop_closures_rejected = state
4262 .graph
4263 .edges
4264 .iter()
4265 .zip(&result.edge_weights)
4266 .filter(|(edge, &w)| {
4267 edge.kind == PoseGraphEdgeKind::LoopClosure && w < 0.5
4268 })
4269 .count();
4270 stats.gnc_result = Some(result);
4271 true
4272 }
4273 Err(_) => false,
4274 }
4275 } else {
4276 match state.graph.optimize_se3_iterative(&pgo_config) {
4277 Ok(result) => {
4278 stats.pose_graph_result = Some(result);
4279 true
4280 }
4281 Err(_) => false,
4282 }
4283 };
4284 if solved && matches!(state.config.solver, LoopRefinementSolver::Sim3(_)) {
4285 let mut updated = 0usize;
4296 let mut corrections: HashMap<u64, Sim3> = HashMap::new();
4297 let solved_nodes: Vec<(u64, Sim3)> = state
4298 .sim3_graph
4299 .as_ref()
4300 .map(|graph| graph.poses.iter().map(|(id, s)| (*id, s.clone())).collect())
4301 .unwrap_or_default();
4302 for (id, siw_new) in &solved_nodes {
4303 let Some(keyframe) = self.map.keyframes.get_mut(id) else {
4304 continue;
4305 };
4306 let new_pose = Pose {
4307 world_to_camera: SE3::new(
4308 siw_new.rotation,
4309 siw_new.translation / siw_new.scale,
4310 ),
4311 };
4312 if state.config.propagate_corrections {
4313 if let Some(siw_old) = pre_solve_sim3_nodes
4314 .as_ref()
4315 .and_then(|nodes| nodes.get(id))
4316 {
4317 corrections.insert(*id, siw_new.inverse().compose(siw_old));
4318 }
4319 }
4320 keyframe.frame.pose = Some(new_pose.clone());
4321 state.graph.poses.insert(*id, new_pose);
4322 updated += 1;
4323 }
4324 stats.keyframes_updated = updated;
4325
4326 if state.config.propagate_corrections && !corrections.is_empty() {
4327 let (moved, max_displacement, mean_displacement) =
4334 propagate_pose_graph_corrections_sim3(&mut self.map, &corrections);
4335 stats.landmarks_moved = moved;
4336 stats.max_landmark_displacement_meters = max_displacement;
4337 stats.mean_landmark_displacement_meters = mean_displacement;
4338
4339 if let Some((_, last_correction)) =
4345 corrections.iter().max_by_key(|(id, _)| **id)
4346 {
4347 self.tracker
4348 .apply_similarity_pose_correction(last_correction);
4349 stats.tracker_correction_applied = true;
4350 }
4351 }
4352 } else if solved {
4356 let mut updated = 0usize;
4366 let mut corrections: HashMap<u64, SE3> = HashMap::new();
4367 for (id, pose) in state.graph.poses.iter() {
4368 if let Some(keyframe) = self.map.keyframes.get_mut(id) {
4369 if state.config.propagate_corrections {
4370 if let Some(old_pose) = keyframe.frame.pose.as_ref() {
4371 let correction = pose
4372 .world_to_camera
4373 .inverse()
4374 .compose(&old_pose.world_to_camera);
4375 corrections.insert(*id, correction);
4376 }
4377 }
4378 keyframe.frame.pose = Some(pose.clone());
4379 updated += 1;
4380 }
4381 }
4382 stats.keyframes_updated = updated;
4383
4384 if state.config.propagate_corrections && !corrections.is_empty() {
4385 let (moved, max_displacement, mean_displacement) =
4391 propagate_pose_graph_corrections(&mut self.map, &corrections);
4392 stats.landmarks_moved = moved;
4393 stats.max_landmark_displacement_meters = max_displacement;
4394 stats.mean_landmark_displacement_meters = mean_displacement;
4395
4396 if let Some((_, last_correction)) =
4405 corrections.iter().max_by_key(|(id, _)| **id)
4406 {
4407 self.tracker.apply_pose_correction(last_correction);
4408 stats.tracker_correction_applied = true;
4409 }
4410 }
4411
4412 if let Some(window) = state.config.marginalization_window {
4417 let result = if state.config.marginalization_sparsify {
4418 state.graph.marginalize_oldest_sparsified(window)
4419 } else {
4420 state.graph.marginalize_oldest(window)
4421 };
4422 if let Ok(removed) = result {
4423 stats.poses_marginalized = removed;
4424 }
4425 }
4426 }
4427
4428 if solved {
4429 let max_reprojection_error_px = state
4430 .config
4431 .appearance_candidates
4432 .as_ref()
4433 .map_or(4.0, |config| {
4434 config.pnp_verifier.max_mean_reprojection_error_px
4435 });
4436 for pending in std::mem::take(&mut state.pending_loop_observation_fusions) {
4437 let edge_is_still_admitted = state
4438 .graph
4439 .edges
4440 .iter()
4441 .enumerate()
4442 .find(|(_, edge)| {
4443 edge.kind == PoseGraphEdgeKind::LoopClosure
4444 && edge.from == pending.from_keyframe_id
4445 && edge.to == pending.query_keyframe_id
4446 })
4447 .is_some_and(|(index, _)| {
4448 stats
4449 .gnc_result
4450 .as_ref()
4451 .and_then(|result| result.edge_weights.get(index))
4452 .is_none_or(|weight| *weight >= 0.5)
4453 });
4454 if !edge_is_still_admitted {
4455 stats.loop_fusion_pairs_considered += pending.pairs.len();
4456 stats.loop_fusion_pairs_skipped += pending.pairs.len();
4457 stats.loop_fusion_pairs_robust_rejected += pending.pairs.len();
4458 continue;
4459 }
4460 if let Some(welding_config) = state.config.loop_welding_ba.clone() {
4461 stats.loop_welding_ba_attempted = true;
4467 let active_pose_before = self
4468 .map
4469 .keyframes
4470 .get(&pending.query_keyframe_id)
4471 .and_then(|keyframe| keyframe.frame.pose.clone());
4472 let live_map_before_welding = self.map.clone();
4473 let graph_before_welding = state.graph.clone();
4474 let mut candidate_map = live_map_before_welding.clone();
4475 let Some(correction) = correct_loop_welding_region(
4476 &mut candidate_map,
4477 pending.from_keyframe_id,
4478 pending.query_keyframe_id,
4479 &pending.relative_pose,
4480 &welding_config,
4481 ) else {
4482 stats.loop_fusion_pairs_considered += pending.pairs.len();
4483 stats.loop_fusion_pairs_skipped += pending.pairs.len();
4484 stats.loop_welding_ba_rejected_or_failed = true;
4485 continue;
4486 };
4487 stats.loop_welding_initial_translation_meters = Some(
4488 stats
4489 .loop_welding_initial_translation_meters
4490 .map_or(correction.translation_meters, |value| {
4491 value.max(correction.translation_meters)
4492 }),
4493 );
4494 stats.loop_welding_initial_rotation_radians = Some(
4495 stats
4496 .loop_welding_initial_rotation_radians
4497 .map_or(correction.rotation_radians, |value| {
4498 value.max(correction.rotation_radians)
4499 }),
4500 );
4501 let (max_welding_translation, max_welding_rotation) = state
4502 .config
4503 .appearance_candidates
4504 .as_ref()
4505 .map_or((0.5, 0.2), |config| {
4506 (
4507 config.max_covisibility_translation_disagreement_meters,
4508 config.max_covisibility_rotation_disagreement_radians,
4509 )
4510 });
4511 if correction.translation_meters > max_welding_translation
4512 || correction.rotation_radians > max_welding_rotation
4513 {
4514 stats.loop_fusion_pairs_considered += pending.pairs.len();
4515 stats.loop_fusion_pairs_skipped += pending.pairs.len();
4516 stats.loop_welding_ba_rejected_or_failed = true;
4517 continue;
4518 }
4519 let mut corrected_ids = correction.keyframe_ids;
4520 let fusion = fuse_loop_observations(
4521 &mut candidate_map,
4522 &state.config.camera,
4523 pending.query_keyframe_id,
4524 &pending.pairs,
4525 max_reprojection_error_px,
4526 );
4527 stats.loop_fusion_pairs_considered += fusion.pairs_considered;
4528 stats.loop_fusion_pairs_skipped += fusion.pairs_skipped;
4529 stats.loop_fusion_pairs_reprojection_rejected +=
4530 fusion.reprojection_rejected;
4531 if fusion.observations_inserted == 0 {
4532 stats.loop_welding_ba_rejected_or_failed = true;
4533 continue;
4534 }
4535 let rotations_before_ba: HashMap<u64, UnitQuaternion<f64>> = candidate_map
4536 .keyframes
4537 .iter()
4538 .filter_map(|(id, keyframe)| {
4539 keyframe
4540 .frame
4541 .pose
4542 .as_ref()
4543 .map(|pose| (*id, pose.world_to_camera.rotation))
4544 })
4545 .collect();
4546
4547 match refine_visual_map_with_covisibility_ba(
4548 &mut candidate_map,
4549 pending.query_keyframe_id,
4550 &welding_config,
4551 ) {
4552 Ok(result) => {
4553 for id in &result.selection.optimized_keyframe_ids {
4560 let (Some(rotation), Some(pose)) = (
4561 rotations_before_ba.get(id),
4562 candidate_map
4563 .keyframes
4564 .get_mut(id)
4565 .and_then(|keyframe| keyframe.frame.pose.as_mut()),
4566 ) else {
4567 continue;
4568 };
4569 let center = pose.camera_center_world();
4570 pose.world_to_camera.rotation = *rotation;
4571 pose.world_to_camera.translation =
4572 -(rotation.transform_vector(¢er.coords));
4573 }
4574 let anchored_reprojection = mean_selected_reprojection_px(
4575 &candidate_map,
4576 &result.selection,
4577 );
4578 stats.loop_welding_ba_mean_reprojection_before_px =
4579 Some(result.mean_reprojection_before_px);
4580 stats.loop_welding_ba_mean_reprojection_after_px =
4581 anchored_reprojection;
4582 if !anchored_reprojection.is_some_and(|error| {
4583 error.is_finite()
4584 && error <= result.mean_reprojection_before_px + 1.0e-9
4585 }) || !candidate_map.validate().is_valid()
4586 {
4587 stats.loop_welding_ba_rejected_or_failed = true;
4588 continue;
4589 }
4590 corrected_ids.extend(
4591 result.selection.optimized_keyframe_ids.iter().copied(),
4592 );
4593 corrected_ids.sort_unstable();
4594 corrected_ids.dedup();
4595 self.map = candidate_map;
4596 for id in corrected_ids {
4597 if let Some(pose) = self
4598 .map
4599 .keyframes
4600 .get(&id)
4601 .and_then(|keyframe| keyframe.frame.pose.clone())
4602 {
4603 if state.graph.poses.contains_key(&id) {
4604 state.graph.poses.insert(id, pose);
4605 }
4606 }
4607 }
4608 stats.loop_welding_post_pgo_attempted = true;
4609 let (
4610 post_pgo_succeeded,
4611 post_pgo_reprojection,
4612 post_ba_error,
4613 post_ba_behind_camera_ratio,
4614 ) = if matches!(state.config.solver, LoopRefinementSolver::Se3) {
4615 refine_pose_graph_after_welding(
4616 &mut self.map,
4617 &mut state.graph,
4618 &pgo_config,
4619 state.config.gnc.as_ref(),
4620 pending.query_keyframe_id,
4621 &welding_config,
4622 result.mean_reprojection_before_px,
4623 )
4624 } else {
4625 (false, None, None, None)
4626 };
4627 stats.loop_welding_post_pgo_mean_reprojection_px =
4628 post_pgo_reprojection;
4629 stats.loop_welding_post_ba_error = post_ba_error;
4630 stats.loop_welding_post_ba_behind_camera_ratio =
4631 post_ba_behind_camera_ratio;
4632 if !post_pgo_succeeded {
4633 self.map = live_map_before_welding;
4634 state.graph = graph_before_welding;
4635 stats.loop_welding_ba_rejected_or_failed = true;
4636 continue;
4637 }
4638 stats.loop_welding_post_pgo_succeeded = true;
4639 stats.loop_welding_ba_updated_keyframes +=
4640 result.updated_keyframe_count;
4641 stats.loop_welding_ba_updated_landmarks +=
4642 result.updated_landmark_count;
4643 if let (Some(old_pose), Some(new_pose)) = (
4644 active_pose_before,
4645 self.map
4646 .keyframes
4647 .get(&pending.query_keyframe_id)
4648 .and_then(|keyframe| keyframe.frame.pose.clone()),
4649 ) {
4650 let correction = new_pose
4651 .world_to_camera
4652 .inverse()
4653 .compose(&old_pose.world_to_camera);
4654 self.tracker.apply_pose_correction(&correction);
4655 stats.tracker_correction_applied = true;
4656 }
4657 stats.loop_fusion_observations_inserted +=
4658 fusion.observations_inserted;
4659 stats.loop_fusion_observations_reassigned +=
4660 fusion.observations_reassigned;
4661 stats.loop_welding_ba_succeeded = true;
4662 }
4663 Err(_) => stats.loop_welding_ba_rejected_or_failed = true,
4664 }
4665 } else {
4666 let fusion = fuse_loop_observations(
4667 &mut self.map,
4668 &state.config.camera,
4669 pending.query_keyframe_id,
4670 &pending.pairs,
4671 max_reprojection_error_px,
4672 );
4673 stats.loop_fusion_pairs_considered += fusion.pairs_considered;
4674 stats.loop_fusion_observations_inserted += fusion.observations_inserted;
4675 stats.loop_fusion_observations_reassigned += fusion.observations_reassigned;
4676 stats.loop_fusion_pairs_skipped += fusion.pairs_skipped;
4677 stats.loop_fusion_pairs_reprojection_rejected +=
4678 fusion.reprojection_rejected;
4679 }
4680 }
4681 }
4682 }
4683
4684 Some(stats)
4685 }
4686
4687 fn vi_initialization_pending(&self) -> bool {
4727 self.vi_init_state.as_ref().is_some_and(|static_state| {
4728 let static_not_done = static_state.completed.is_none();
4730 if !static_not_done {
4731 return false;
4732 }
4733 let static_gave_up = static_state.gave_up.is_some();
4739 match self.vi_motion_init_state.as_ref() {
4740 None => {
4741 !static_gave_up
4743 }
4744 Some(motion_state) => {
4745 if motion_state.completed.is_some() || motion_state.velocity_stage_fired() {
4746 false
4748 } else {
4749 true
4751 }
4752 }
4753 }
4754 })
4755 }
4756
4757 fn maybe_run_local_vi_ba(
4758 &mut self,
4759 new_factor: Option<ImuPreintegrationFactor>,
4760 ) -> Option<OnlineSlamLocalBaStats> {
4761 let vi_initialization_pending = self.vi_initialization_pending();
4762 let state = self.local_vi_ba_state.as_mut()?;
4763 let factor = new_factor?;
4764 let should_trigger = state.register_new_factor(factor);
4765 if !should_trigger || vi_initialization_pending {
4766 return None;
4767 }
4768 crate::online_slam_vi_ba::run_local_vi_ba(&mut self.map, state)
4769 }
4770
4771 fn maybe_inject_recovered_factors(&mut self) -> usize {
4781 let vi_ba_state = match self.local_vi_ba_state.as_mut() {
4782 Some(s) => s,
4783 None => return 0,
4784 };
4785 if !vi_ba_state.config.use_sqrt_window_marginalization {
4786 return 0;
4787 }
4788 let pending = std::mem::take(&mut vi_ba_state.pending_recovered_pose_factors);
4789 if pending.is_empty() {
4790 return 0;
4791 }
4792 let pg_state = match self.pose_graph_state.as_mut() {
4793 Some(s) => s,
4794 None => {
4795 vi_ba_state.pending_recovered_pose_factors = pending;
4796 return 0;
4797 }
4798 };
4799 let mut injected = 0usize;
4800 let mut retry = Vec::new();
4801 for (id_i, id_j, f) in pending {
4802 let pose_i = Self::pose_graph_pose_or_map(&self.map, pg_state, id_i);
4803 let pose_j = Self::pose_graph_pose_or_map(&self.map, pg_state, id_j);
4804 let (pose_i, pose_j) = match (pose_i, pose_j) {
4805 (Some(pi), Some(pj)) => (pi, pj),
4806 _ => {
4807 retry.push((id_i, id_j, f));
4808 continue;
4809 }
4810 };
4811 let relative = relative_world_to_camera(&pose_i, &pose_j);
4812 if f.omega_relative.nrows() != 6 || f.omega_relative.ncols() != 6 {
4813 continue;
4814 }
4815 let mut information = nalgebra::Matrix6::<f64>::zeros();
4816 for row in 0..6 {
4817 for col in 0..6 {
4818 information[(row, col)] = f.omega_relative[(row, col)];
4819 }
4820 }
4821 pg_state.graph.add_edge_with_information(
4822 id_i,
4823 id_j,
4824 relative,
4825 PoseGraphEdgeKind::Sequential,
4826 information,
4827 );
4828 injected += 1;
4829 }
4830 vi_ba_state.pending_recovered_pose_factors = retry;
4831 injected
4832 }
4833
4834 fn pose_graph_pose_or_map(
4835 map: &VisualMap,
4836 pg_state: &mut OnlineSlamLoopClosureRefinementState,
4837 keyframe_id: u64,
4838 ) -> Option<Pose> {
4839 if let Some(pose) = pg_state.graph.poses.get(&keyframe_id) {
4840 return Some(pose.clone());
4841 }
4842 let pose = map.keyframes.get(&keyframe_id)?.frame.pose.clone()?;
4843 pg_state.graph.add_pose(keyframe_id, pose.clone());
4844 Some(pose)
4845 }
4846
4847 fn maybe_run_covisibility_local_ba(
4853 &mut self,
4854 frame: &Frame,
4855 applied_update: Option<&AppliedMapUpdate>,
4856 ) -> Option<OnlineSlamCovisibilityLocalBaStats> {
4857 let config = self.config.covisibility_local_ba.clone()?;
4858 let added_new_keyframe = applied_update.is_some_and(|a| a.keyframe_count > 0);
4859 if !added_new_keyframe {
4860 return None;
4861 }
4862
4863 if let Some(activation) = config.motion_vi_raw_residual_activation {
4864 let motion_state = self.vi_motion_init_state.as_ref()?;
4865 if motion_state.completed.is_some()
4866 || !motion_state.last_rejection.as_ref().is_some_and(|reason| {
4867 motion_vi_raw_residual_activation_satisfied(activation, reason)
4868 })
4869 {
4870 return None;
4871 }
4872 }
4873 if let Some(maximum) = config.max_seed_landmarks_for_activation {
4874 let seed_support = self
4875 .map
4876 .keyframes
4877 .values()
4878 .min_by_key(|keyframe| keyframe.frame.id)
4879 .map(|keyframe| keyframe.observations.len());
4880 if seed_support.is_none_or(|support| support > maximum) {
4881 return None;
4882 }
4883 }
4884
4885 let map_keyframe_count = self.map.keyframes.len();
4886 if map_keyframe_count < config.min_keyframes.max(1) {
4887 return None;
4888 }
4889 if config
4890 .max_keyframes
4891 .is_some_and(|maximum| map_keyframe_count > maximum)
4892 {
4893 return None;
4894 }
4895
4896 let trigger_every = config.trigger_every_new_keyframes.max(1);
4897 if !map_keyframe_count.is_multiple_of(trigger_every) {
4898 return None;
4899 }
4900
4901 let started = Instant::now();
4902 let conditioning_gate_active = config.max_outlier_observation_ratio.is_some()
4909 || config.max_behind_camera_landmark_ratio.is_some()
4910 || config.min_fixed_to_optimized_ratio.is_some()
4911 || config.max_pose_translation_correction_m.is_some()
4912 || config.max_pose_rotation_correction_rad.is_some();
4913 let factor_neighbor_allowlist = self
4914 .sparse_factor_graph_state
4915 .as_ref()
4916 .map(|graph| graph.active_neighbor_keyframe_ids(frame.id));
4917 let result = if conditioning_gate_active {
4918 let mut candidate_map = self.map.clone();
4919 let result = refine_visual_map_with_covisibility_ba_and_neighbor_allowlist(
4920 &mut candidate_map,
4921 frame.id,
4922 &config.ba,
4923 factor_neighbor_allowlist.as_ref(),
4924 );
4925 if let Ok(ref result) = result {
4926 let outlier_ratio = outlier_observation_ratio(
4927 result.outlier_observation_count,
4928 result.selection.observation_count,
4929 );
4930 let make_rejection =
4931 |error: CovisibilityLocalBaError, quality_gate_rejected: bool| {
4932 let pose_correction_gate_rejected = matches!(
4933 error,
4934 CovisibilityLocalBaError::PoseCorrectionGateRejected { .. }
4935 );
4936 OnlineSlamCovisibilityLocalBaStats {
4937 active_keyframe_id: frame.id,
4938 map_keyframe_count,
4939 factor_graph_neighbor_count: factor_neighbor_allowlist
4940 .as_ref()
4941 .map(|neighbors| neighbors.len()),
4942 elapsed_ms: started.elapsed().as_secs_f64() * 1000.0,
4943 success: false,
4944 error: Some(error),
4945 selection: Some(result.selection.clone()),
4946 ba_result: Some(result.ba_result.clone()),
4947 mean_reprojection_before_px: Some(result.mean_reprojection_before_px),
4948 mean_reprojection_after_px: Some(result.mean_reprojection_after_px),
4949 max_pose_translation_correction_m: Some(
4950 result.max_pose_translation_correction_m,
4951 ),
4952 max_pose_rotation_correction_rad: Some(
4953 result.max_pose_rotation_correction_rad,
4954 ),
4955 updated_keyframe_count: 0,
4956 updated_landmark_count: 0,
4957 outlier_observation_count: result.outlier_observation_count,
4958 observation_count: result.selection.observation_count,
4959 outlier_observation_ratio: outlier_ratio,
4960 quality_gate_rejected,
4961 pose_correction_gate_rejected,
4962 removed_observation_count: 0,
4963 }
4964 };
4965
4966 let optimized_keyframe_count = result.selection.optimized_keyframe_ids.len();
4967 let fixed_keyframe_count = result.selection.fixed_keyframe_ids.len();
4968
4969 let translation_exceeded = config
4970 .max_pose_translation_correction_m
4971 .is_some_and(|limit| result.max_pose_translation_correction_m > limit);
4972 let rotation_exceeded = config
4973 .max_pose_rotation_correction_rad
4974 .is_some_and(|limit| result.max_pose_rotation_correction_rad > limit);
4975 if translation_exceeded || rotation_exceeded {
4976 return Some(make_rejection(
4977 CovisibilityLocalBaError::PoseCorrectionGateRejected {
4978 translation_correction_m: result.max_pose_translation_correction_m,
4979 rotation_correction_rad: result.max_pose_rotation_correction_rad,
4980 max_translation_correction_m: config.max_pose_translation_correction_m,
4981 max_rotation_correction_rad: config.max_pose_rotation_correction_rad,
4982 },
4983 false,
4984 ));
4985 }
4986
4987 if let Some(min_ratio) = config.min_fixed_to_optimized_ratio {
4989 if !fixed_to_optimized_ratio_satisfied(
4990 optimized_keyframe_count,
4991 fixed_keyframe_count,
4992 min_ratio,
4993 ) {
4994 return Some(make_rejection(
4995 CovisibilityLocalBaError::FixedSupportRatioRejected {
4996 optimized_keyframe_count,
4997 fixed_keyframe_count,
4998 required_fixed_keyframes: required_fixed_keyframes(
4999 optimized_keyframe_count,
5000 min_ratio,
5001 ),
5002 min_fixed_to_optimized_ratio: min_ratio,
5003 },
5004 false,
5005 ));
5006 }
5007 }
5008
5009 if let Some(max_behind) = config.max_behind_camera_landmark_ratio {
5011 let behind_ratio =
5012 behind_camera_optimized_landmark_ratio(&candidate_map, &result.selection)
5013 .unwrap_or(0.0);
5014 if behind_ratio > max_behind {
5015 return Some(make_rejection(
5016 CovisibilityLocalBaError::BehindCameraGateRejected {
5017 behind_camera_landmark_ratio: behind_ratio,
5018 max_behind_camera_landmark_ratio: max_behind,
5019 },
5020 false,
5021 ));
5022 }
5023 }
5024
5025 if let Some(max_ratio) = config.max_outlier_observation_ratio {
5027 if outlier_ratio.unwrap_or(0.0) > max_ratio {
5028 return Some(make_rejection(
5029 CovisibilityLocalBaError::QualityGateRejected {
5030 outlier_observation_count: result.outlier_observation_count,
5031 observation_count: result.selection.observation_count,
5032 max_outlier_observation_ratio: max_ratio,
5033 },
5034 true,
5035 ));
5036 }
5037 }
5038
5039 self.map = candidate_map;
5040 }
5041 result
5042 } else {
5043 refine_visual_map_with_covisibility_ba_and_neighbor_allowlist(
5044 &mut self.map,
5045 frame.id,
5046 &config.ba,
5047 factor_neighbor_allowlist.as_ref(),
5048 )
5049 };
5050 let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
5051
5052 match result {
5053 Ok(result) => {
5054 let observation_count = result.selection.observation_count;
5055 Some(OnlineSlamCovisibilityLocalBaStats {
5056 active_keyframe_id: frame.id,
5057 map_keyframe_count,
5058 factor_graph_neighbor_count: factor_neighbor_allowlist
5059 .as_ref()
5060 .map(|neighbors| neighbors.len()),
5061 elapsed_ms,
5062 success: true,
5063 error: None,
5064 selection: Some(result.selection),
5065 ba_result: Some(result.ba_result),
5066 mean_reprojection_before_px: Some(result.mean_reprojection_before_px),
5067 mean_reprojection_after_px: Some(result.mean_reprojection_after_px),
5068 max_pose_translation_correction_m: Some(
5069 result.max_pose_translation_correction_m,
5070 ),
5071 max_pose_rotation_correction_rad: Some(result.max_pose_rotation_correction_rad),
5072 updated_keyframe_count: result.updated_keyframe_count,
5073 updated_landmark_count: result.updated_landmark_count,
5074 outlier_observation_count: result.outlier_observation_count,
5075 observation_count,
5076 outlier_observation_ratio: outlier_observation_ratio(
5077 result.outlier_observation_count,
5078 observation_count,
5079 ),
5080 quality_gate_rejected: false,
5081 pose_correction_gate_rejected: false,
5082 removed_observation_count: result.removed_observation_count,
5083 })
5084 }
5085 Err(error) => Some(OnlineSlamCovisibilityLocalBaStats {
5086 active_keyframe_id: frame.id,
5087 map_keyframe_count,
5088 factor_graph_neighbor_count: factor_neighbor_allowlist
5089 .as_ref()
5090 .map(|neighbors| neighbors.len()),
5091 elapsed_ms,
5092 success: false,
5093 error: Some(error),
5094 selection: None,
5095 ba_result: None,
5096 mean_reprojection_before_px: None,
5097 mean_reprojection_after_px: None,
5098 max_pose_translation_correction_m: None,
5099 max_pose_rotation_correction_rad: None,
5100 updated_keyframe_count: 0,
5101 updated_landmark_count: 0,
5102 outlier_observation_count: 0,
5103 observation_count: 0,
5104 outlier_observation_ratio: None,
5105 quality_gate_rejected: false,
5106 pose_correction_gate_rejected: false,
5107 removed_observation_count: 0,
5108 }),
5109 }
5110 }
5111
5112 fn stage_imu_factor_on_new_keyframe(
5113 &mut self,
5114 frame: &Frame,
5115 applied_update: Option<&AppliedMapUpdate>,
5116 ) -> Option<ImuPreintegrationFactor> {
5117 let state = self.imu_state.as_mut()?;
5118 let added_new_keyframe = applied_update.is_some_and(|a| a.keyframe_count > 0);
5119 if !added_new_keyframe {
5120 return None;
5121 }
5122 let new_keyframe_id = frame.id;
5123 let factor = match state.last_keyframe_id {
5124 Some(prev_id) if prev_id != new_keyframe_id => {
5125 let delta = state.preintegrator.delta();
5126 let factor = ImuPreintegrationFactor {
5127 keyframe_id_from: prev_id,
5128 keyframe_id_to: new_keyframe_id,
5129 delta,
5130 gravity_world: state.config.gravity_world,
5131 weight_position: state.config.weight_position,
5132 weight_velocity: state.config.weight_velocity,
5133 weight_rotation: state.config.weight_rotation,
5134 };
5135 state.preintegrator.reset();
5136 Some(factor)
5137 }
5138 _ => None,
5139 };
5140 state.last_keyframe_id = Some(new_keyframe_id);
5141
5142 if let Some(vi) = self.vi_init_state.as_mut() {
5155 if vi.is_active() {
5156 if factor.is_some() {
5157 vi.discarded_stale_factor_count += 1;
5158 }
5159 if !self.config.keep_pre_promotion_imu_factors {
5160 state.pending_factor = None;
5161 return None;
5162 }
5163 }
5164 }
5165
5166 state.pending_factor = factor.clone();
5167 factor
5168 }
5169
5170 fn run_vi_init_step(
5176 &mut self,
5177 frame: &Frame,
5178 applied_update: Option<&AppliedMapUpdate>,
5179 ) -> Option<ViInitializationEvent> {
5180 if self.vi_init_state.as_ref().is_none_or(|s| !s.is_active()) {
5183 return None;
5184 }
5185 let added_new_keyframe = applied_update.is_some_and(|a| a.keyframe_count > 0);
5186 let try_on_every_frame = self
5187 .vi_init_state
5188 .as_ref()
5189 .is_some_and(|s| s.config.try_initialize_on_every_frame);
5190 if !added_new_keyframe && !try_on_every_frame {
5191 return None;
5192 }
5193
5194 let try_result = {
5197 let state = self.vi_init_state.as_ref().unwrap();
5198 state.initializer.try_initialize()
5199 };
5200
5201 match try_result {
5202 Ok(result) => {
5203 let binding_keyframe_id = if added_new_keyframe {
5212 Some(frame.id)
5213 } else {
5214 self.map.keyframes.keys().copied().max()
5215 };
5216 Some(self.promote_vi_init_result(binding_keyframe_id, result))
5217 }
5218 Err(reason) => {
5219 let vi = self.vi_init_state.as_mut().unwrap();
5223 vi.last_rejection = Some(reason.clone());
5224 if vi.cap_exceeded() {
5225 Some(self.apply_vi_init_fallback(reason))
5226 } else {
5227 Some(ViInitializationEvent::StillBuffering { reason })
5228 }
5229 }
5230 }
5231 }
5232
5233 fn promote_vi_init_result(
5245 &mut self,
5246 binding_keyframe_id: Option<u64>,
5247 result: VisualInertialInitializationResult,
5248 ) -> ViInitializationEvent {
5249 let bias_gyro = result.bias_gyro;
5250 let bias_acc = result.bias_acc;
5251 let seed_rotation = result.initial_rotation_body_to_world;
5252
5253 if let Some(imu) = self.imu_state.as_mut() {
5255 imu.reset_preintegrator_with_bias(bias_gyro, bias_acc);
5256 }
5257 if let Some(imu_cfg) = self.config.imu.as_mut() {
5258 imu_cfg.bias_gyro = bias_gyro;
5259 imu_cfg.bias_acc = bias_acc;
5260 }
5261
5262 let seed_first_keyframe_rotation = self
5269 .vi_init_state
5270 .as_ref()
5271 .is_some_and(|s| s.config.seed_first_keyframe_rotation);
5272 let body_to_camera = self
5273 .vi_init_state
5274 .as_ref()
5275 .map_or_else(SE3::identity, |s| s.config.body_to_camera.clone());
5276 if seed_first_keyframe_rotation {
5277 if let Some(first_keyframe_id) = binding_keyframe_id {
5278 if let Some(keyframe) = self.map.keyframes.get_mut(&first_keyframe_id) {
5279 if let Some(pose) = keyframe.frame.pose.as_mut() {
5280 let r_wb = seed_rotation;
5281 let r_bc = body_to_camera.rotation;
5282 let r_wc = r_wb * r_bc;
5283 let r_cw_new = r_wc.inverse();
5284 let camera_center_world = -(pose.world_to_camera.rotation.inverse()
5285 * pose.world_to_camera.translation);
5286 let t_cw_new = -(r_cw_new * camera_center_world);
5287 *pose =
5288 visloc_core::geometry::Pose::from_world_to_camera(r_cw_new, t_cw_new);
5289 }
5290 }
5291 }
5292 }
5293
5294 if let Some(local) = self.local_vi_ba_state.as_mut() {
5296 if let Some(first_keyframe_id) = binding_keyframe_id {
5297 local
5298 .keyframe_state
5299 .entry(first_keyframe_id)
5300 .or_insert_with(|| crate::online_slam_vi_ba::KeyframeImuState {
5301 velocity_world: Vector3::zeros(),
5302 bias_gyro,
5303 bias_acc,
5304 });
5305 }
5306 local.config.bias_gyro_init = bias_gyro;
5309 local.config.bias_acc_init = bias_acc;
5310 }
5311 if let Some(local_cfg) = self.config.local_vi_ba.as_mut() {
5312 local_cfg.bias_gyro_init = bias_gyro;
5313 local_cfg.bias_acc_init = bias_acc;
5314 }
5315
5316 let discarded_stale_factor_count;
5318 {
5319 let vi = self.vi_init_state.as_mut().unwrap();
5320 vi.completed = Some(result.clone());
5321 discarded_stale_factor_count = vi.discarded_stale_factor_count;
5322 }
5323
5324 ViInitializationEvent::Succeeded {
5325 result,
5326 first_keyframe_id: binding_keyframe_id,
5327 discarded_stale_factor_count,
5328 }
5329 }
5330
5331 fn apply_vi_init_fallback(
5334 &mut self,
5335 last_reason: StationaryRejectionReason,
5336 ) -> ViInitializationEvent {
5337 let fallback = self
5338 .vi_init_state
5339 .as_ref()
5340 .map_or(ViInitFallback::KeepExistingSeed, |s| {
5341 s.config.on_persistent_rejection
5342 });
5343 match fallback {
5344 ViInitFallback::KeepExistingSeed => {
5345 }
5348 ViInitFallback::DisableImuStage => {
5349 self.imu_state = None;
5350 self.local_vi_ba_state = None;
5351 self.config.imu = None;
5352 self.config.local_vi_ba = None;
5353 }
5354 }
5355 if let Some(vi) = self.vi_init_state.as_mut() {
5356 vi.gave_up = Some(last_reason.clone());
5357 }
5358 ViInitializationEvent::GaveUp {
5359 last_reason,
5360 fallback,
5361 }
5362 }
5363
5364 fn run_motion_vi_init_step(
5386 &mut self,
5387 frame: &Frame,
5388 applied_update: Option<&AppliedMapUpdate>,
5389 new_imu_factor: Option<&ImuPreintegrationFactor>,
5390 ) -> Option<MotionViInitializationEvent> {
5391 let added_new_keyframe = applied_update.is_some_and(|a| a.keyframe_count > 0);
5392 if !added_new_keyframe {
5393 return None;
5394 }
5395 if self
5396 .vi_motion_init_state
5397 .as_ref()
5398 .is_none_or(|s| !s.is_active())
5399 {
5400 return None;
5401 }
5402 let static_bias_seed = self
5408 .vi_init_state
5409 .as_ref()
5410 .and_then(|state| state.completed.as_ref())
5411 .map(|seed| (seed.bias_gyro, seed.bias_acc));
5412 let allow_after_give_up = self
5413 .vi_motion_init_state
5414 .as_ref()
5415 .is_some_and(|state| state.config.allow_after_static_give_up);
5416 let allow_from_configured_bias_before_static = self
5417 .vi_motion_init_state
5418 .as_ref()
5419 .is_some_and(|state| state.config.allow_from_configured_bias_before_static);
5420 let static_gave_up = self
5421 .vi_init_state
5422 .as_ref()
5423 .is_some_and(|state| state.gave_up.is_some());
5424 let (bias_gyro_seed, bias_acc_seed) = if let Some(seed) = static_bias_seed {
5425 seed
5426 } else if allow_from_configured_bias_before_static
5427 || (allow_after_give_up && static_gave_up)
5428 {
5429 let imu = self.imu_state.as_ref()?;
5430 (imu.config.bias_gyro, imu.config.bias_acc)
5431 } else {
5432 return None;
5433 };
5434
5435 let camera_center = self
5437 .map
5438 .keyframes
5439 .get(&frame.id)
5440 .and_then(|kf| kf.frame.pose.as_ref().map(|p| p.camera_center_world()))?;
5441 {
5442 let state = self.vi_motion_init_state.as_mut().unwrap();
5443 if let Some(factor) = new_imu_factor {
5444 state.push_factor(factor.clone());
5445 }
5446 state.initializer.register_keyframe(frame.id, camera_center);
5447 }
5448
5449 let factors_snapshot: Vec<ImuPreintegrationFactor> = self
5455 .vi_motion_init_state
5456 .as_ref()
5457 .map(|s| s.factor_history.iter().cloned().collect())
5458 .unwrap_or_default();
5459 let outcome = {
5460 let state = self.vi_motion_init_state.as_mut().unwrap();
5461 match state.initializer.try_initialize_with_bias_seed(
5462 &mut self.map,
5463 &factors_snapshot,
5464 bias_gyro_seed,
5465 bias_acc_seed,
5466 ) {
5467 Ok(r) => Ok(r.clone()),
5468 Err(reason) => {
5469 state.last_rejection = Some(reason.clone());
5470 Err(reason)
5471 }
5472 }
5473 };
5474 match outcome {
5475 Ok(result) => Some(self.promote_motion_vi_init_result(result)),
5476 Err(reason) => Some(MotionViInitializationEvent::StillWaiting { reason }),
5477 }
5478 }
5479
5480 fn promote_motion_vi_init_result(
5494 &mut self,
5495 result: MotionBasedViInitializationResult,
5496 ) -> MotionViInitializationEvent {
5497 let mirror_local = self
5498 .vi_motion_init_state
5499 .as_ref()
5500 .is_none_or(|s| s.config.mirror_into_local_vi_ba);
5501 let mirror_imu = self
5502 .vi_motion_init_state
5503 .as_ref()
5504 .is_none_or(|s| s.config.mirror_into_imu_state);
5505
5506 if mirror_local {
5508 if let Some(local) = self.local_vi_ba_state.as_mut() {
5509 for (kf_id, refined) in &result.keyframe_states {
5510 local.keyframe_state.insert(*kf_id, refined.clone());
5511 }
5512 }
5513 }
5514
5515 if mirror_imu {
5520 if let Some((_, latest)) = result.keyframe_states.iter().next_back() {
5521 let bg = latest.bias_gyro;
5522 let ba = latest.bias_acc;
5523 if let Some(imu) = self.imu_state.as_mut() {
5524 imu.reset_preintegrator_with_bias(bg, ba);
5525 }
5526 if let Some(imu_cfg) = self.config.imu.as_mut() {
5527 imu_cfg.bias_gyro = bg;
5528 imu_cfg.bias_acc = ba;
5529 }
5530 if let Some(local) = self.local_vi_ba_state.as_mut() {
5531 local.config.bias_gyro_init = bg;
5532 local.config.bias_acc_init = ba;
5533 }
5534 if let Some(local_cfg) = self.config.local_vi_ba.as_mut() {
5535 local_cfg.bias_gyro_init = bg;
5536 local_cfg.bias_acc_init = ba;
5537 }
5538 }
5539 }
5540
5541 if let Some(g) = result.estimated_gravity_world {
5580 if let Some(imu) = self.imu_state.as_mut() {
5581 imu.config.gravity_world = g;
5582 }
5583 if let Some(imu_cfg) = self.config.imu.as_mut() {
5584 imu_cfg.gravity_world = g;
5585 }
5586 if let Some(local) = self.local_vi_ba_state.as_mut() {
5587 local.config.gravity_world = g;
5588 }
5589 if let Some(local_cfg) = self.config.local_vi_ba.as_mut() {
5590 local_cfg.gravity_world = g;
5591 }
5592 if let Some(state) = self.vi_motion_init_state.as_mut() {
5593 state.initializer.set_gravity_world(g);
5594 }
5595 if let Some(motion_cfg) = self.config.vi_motion_init.as_mut() {
5596 motion_cfg.initializer.gravity_world = g;
5597 }
5598 if let Some(vi_init_cfg) = self.config.vi_init.as_mut() {
5599 vi_init_cfg.initializer.gravity_world = g;
5600 }
5601 }
5602
5603 if let Some(state) = self.vi_motion_init_state.as_mut() {
5611 if result.bias_released {
5612 state.completed = Some(result.clone());
5613 }
5614 state.last_rejection = None;
5615 }
5616
5617 MotionViInitializationEvent::Succeeded { result }
5618 }
5619
5620 pub fn reset_sequence_state(&mut self) {
5621 self.tracker.reset();
5622 self.mapper.reset();
5623 if let Some(state) = self.imu_state.as_mut() {
5624 state.reset();
5625 }
5626 if let Some(state) = self.local_vi_ba_state.as_mut() {
5627 state.reset();
5628 }
5629 if let Some(state) = self.vi_init_state.as_mut() {
5630 state.reset();
5631 }
5632 if let Some(state) = self.vi_motion_init_state.as_mut() {
5633 state.reset();
5634 }
5635 if let Some(state) = self.pose_graph_state.as_mut() {
5636 state.reset();
5637 }
5638 if let Some(state) = self.relocalization_state.as_mut() {
5639 state.reset();
5640 }
5641 }
5642}
5643
5644fn motion_vi_raw_residual_activation_satisfied(
5645 config: MotionViRawResidualActivationConfig,
5646 reason: &MotionBasedViRejectionReason,
5647) -> bool {
5648 let MotionBasedViRejectionReason::ImuRawResidualOutOfRange {
5649 rotation_residual_rms_rad: Some(rotation),
5650 velocity_residual_rms_mps: Some(velocity),
5651 position_residual_rms_meters: Some(position),
5652 ..
5653 } = reason
5654 else {
5655 return false;
5656 };
5657 config.max_rotation_residual_rms_rad.is_finite()
5658 && config.max_rotation_residual_rms_rad > 0.0
5659 && config.max_velocity_residual_rms_mps.is_finite()
5660 && config.max_velocity_residual_rms_mps > 0.0
5661 && config.max_position_residual_rms_meters.is_finite()
5662 && config.max_position_residual_rms_meters > 0.0
5663 && rotation.is_finite()
5664 && velocity.is_finite()
5665 && position.is_finite()
5666 && *rotation <= config.max_rotation_residual_rms_rad
5667 && *velocity <= config.max_velocity_residual_rms_mps
5668 && *position <= config.max_position_residual_rms_meters
5669}
5670
5671#[cfg(test)]
5672mod motion_vi_raw_residual_activation_tests {
5673 use super::*;
5674
5675 fn raw_rejection(rotation: f64, velocity: f64, position: f64) -> MotionBasedViRejectionReason {
5676 MotionBasedViRejectionReason::ImuRawResidualOutOfRange {
5677 rotation_residual_rms_rad: Some(rotation),
5678 velocity_residual_rms_mps: Some(velocity),
5679 position_residual_rms_meters: Some(position),
5680 max_rotation_residual_rms_rad: Some(0.01),
5681 max_velocity_residual_rms_mps: Some(0.25),
5682 max_position_residual_rms_meters: Some(0.08),
5683 }
5684 }
5685
5686 #[test]
5687 fn activates_only_for_complete_near_conditioned_raw_residuals() {
5688 let config = MotionViRawResidualActivationConfig {
5689 max_rotation_residual_rms_rad: 0.03,
5690 max_velocity_residual_rms_mps: 0.6,
5691 max_position_residual_rms_meters: 0.15,
5692 };
5693 assert!(motion_vi_raw_residual_activation_satisfied(
5694 config,
5695 &raw_rejection(0.02, 0.46, 0.12)
5696 ));
5697 assert!(!motion_vi_raw_residual_activation_satisfied(
5698 config,
5699 &raw_rejection(0.038, 0.46, 0.12)
5700 ));
5701 assert!(!motion_vi_raw_residual_activation_satisfied(
5702 config,
5703 &MotionBasedViRejectionReason::InsufficientKeyframes { have: 5, need: 10 }
5704 ));
5705 }
5706}
5707
5708#[cfg(test)]
5715mod bias_release_promotion_tests {
5716 use super::*;
5717
5718 fn zero_cost_breakdown() -> crate::bundle::BaCostBreakdown {
5719 crate::bundle::BaCostBreakdown {
5720 total: 0.0,
5721 visual: 0.0,
5722 imu: 0.0,
5723 bias_random_walk: 0.0,
5724 navigation_prior: 0.0,
5725 other_structural: 0.0,
5726 imu_normalized_squared_residual_per_dof: None,
5727 imu_rotation_residual_rms_rad: None,
5728 imu_velocity_residual_rms_mps: None,
5729 imu_position_residual_rms_meters: None,
5730 }
5731 }
5732
5733 fn fake_result(
5738 kf_id: u64,
5739 velocity: Vector3<f64>,
5740 bias_released: bool,
5741 ) -> MotionBasedViInitializationResult {
5742 let mut keyframe_states = BTreeMap::new();
5743 keyframe_states.insert(
5744 kf_id,
5745 KeyframeImuState {
5746 velocity_world: velocity,
5747 bias_gyro: Vector3::zeros(),
5748 bias_acc: Vector3::zeros(),
5749 },
5750 );
5751 MotionBasedViInitializationResult {
5752 keyframe_states,
5753 keyframe_ids: vec![kf_id],
5754 imu_factors_used: 1,
5755 scale: 1.0,
5756 scale_history: Vec::new(),
5757 viba2_iterations_run: 0,
5758 trigger_translation_meters: 2.0,
5759 ba_result: BaResult {
5760 initial_cost: 1.0,
5761 final_cost: 0.5,
5762 iterations: Vec::new(),
5763 converged: true,
5764 },
5765 initial_cost_breakdown: zero_cost_breakdown(),
5766 final_cost_breakdown: zero_cost_breakdown(),
5767 bias_released,
5768 estimated_gravity_world: None,
5769 estimated_gyro_bias: None,
5770 }
5771 }
5772
5773 fn minimal_pipeline_with_motion_vi_state(
5774 ) -> OnlineSlamPipeline<Tracker<LocalizationPipeline>, LocalMappingPipeline> {
5775 let mut slam = OnlineSlamPipeline::new(
5776 VisualMap::new(),
5777 Tracker::new(LocalizationPipeline::default(), TrackingConfig::default()),
5778 LocalMappingPipeline::default(),
5779 OnlineSlamConfig::default(),
5780 );
5781 slam.local_vi_ba_state = Some(OnlineSlamLocalBaState::new(
5782 OnlineSlamLocalBaConfig::default(),
5783 ));
5784 slam.vi_motion_init_state = Some(OnlineSlamMotionViInitState::new(
5785 OnlineSlamMotionViInitConfig::default(),
5786 ));
5787 slam
5788 }
5789
5790 #[test]
5791 fn stage_a_mirrors_velocity_but_leaves_stage_active_then_stage_b_completes_it() {
5792 let mut slam = minimal_pipeline_with_motion_vi_state();
5793
5794 let stage_a = fake_result(1, Vector3::new(1.0, 0.0, 0.0), false);
5796 match slam.promote_motion_vi_init_result(stage_a) {
5797 MotionViInitializationEvent::Succeeded { result } => assert!(!result.bias_released),
5798 other => panic!("expected Succeeded, got {other:?}"),
5799 }
5800 let mirrored_after_stage_a = slam
5801 .local_vi_ba_state
5802 .as_ref()
5803 .expect("configured above")
5804 .keyframe_state
5805 .get(&1)
5806 .expect("Stage A must mirror velocity into local_vi_ba_state")
5807 .velocity_world;
5808 assert!((mirrored_after_stage_a - Vector3::new(1.0, 0.0, 0.0)).norm() < 1.0e-12);
5809 let motion_state = slam
5810 .vi_motion_init_state
5811 .as_ref()
5812 .expect("configured above");
5813 assert!(
5814 motion_state.completed.is_none(),
5815 "Stage A must NOT mark the motion-VI stage completed"
5816 );
5817 assert!(
5818 motion_state.is_active(),
5819 "Stage A must leave the motion-VI stage active"
5820 );
5821
5822 let stage_b = fake_result(1, Vector3::new(2.0, 0.0, 0.0), true);
5825 match slam.promote_motion_vi_init_result(stage_b) {
5826 MotionViInitializationEvent::Succeeded { result } => assert!(result.bias_released),
5827 other => panic!("expected Succeeded, got {other:?}"),
5828 }
5829 let mirrored_after_stage_b = slam
5830 .local_vi_ba_state
5831 .as_ref()
5832 .expect("configured above")
5833 .keyframe_state
5834 .get(&1)
5835 .expect("Stage B must mirror velocity into local_vi_ba_state")
5836 .velocity_world;
5837 assert!((mirrored_after_stage_b - Vector3::new(2.0, 0.0, 0.0)).norm() < 1.0e-12);
5838 let motion_state = slam
5839 .vi_motion_init_state
5840 .as_ref()
5841 .expect("configured above");
5842 assert!(
5843 motion_state.completed.is_some(),
5844 "Stage B must mark the motion-VI stage completed (terminal)"
5845 );
5846 assert!(
5847 !motion_state.is_active(),
5848 "Stage B must leave the motion-VI stage inactive (terminal)"
5849 );
5850 }
5851
5852 #[test]
5863 fn estimated_gravity_mirrors_into_every_documented_sink() {
5864 let mut slam = minimal_pipeline_with_motion_vi_state();
5865 slam.imu_state = Some(OnlineSlamImuState::new(OnlineSlamImuConfig::default()));
5866 slam.config.imu = Some(OnlineSlamImuConfig::default());
5867 slam.config.local_vi_ba = Some(OnlineSlamLocalBaConfig::default());
5868 slam.config.vi_motion_init = Some(OnlineSlamMotionViInitConfig::default());
5869 slam.config.vi_init = Some(OnlineSlamViInitConfig::default());
5870
5871 let original_gravity = OnlineSlamImuConfig::default().gravity_world;
5872 let new_gravity = Vector3::new(0.0, 0.0, 9.81);
5873 assert!(
5874 (original_gravity - new_gravity).norm() > 1.0,
5875 "fixture must actually move the gravity assumption"
5876 );
5877
5878 let mut result = fake_result(1, Vector3::zeros(), true);
5879 result.estimated_gravity_world = Some(new_gravity);
5880 match slam.promote_motion_vi_init_result(result) {
5881 MotionViInitializationEvent::Succeeded { result } => {
5882 assert_eq!(result.estimated_gravity_world, Some(new_gravity));
5883 }
5884 other => panic!("expected Succeeded, got {other:?}"),
5885 }
5886
5887 assert!(
5888 (slam.imu_state.as_ref().unwrap().config.gravity_world - new_gravity).norm() < 1.0e-12,
5889 "sink (1): imu_state.config.gravity_world must mirror the estimate"
5890 );
5891 assert!(
5892 (slam.config.imu.as_ref().unwrap().gravity_world - new_gravity).norm() < 1.0e-12,
5893 "sink (2): config.imu.gravity_world must mirror the estimate"
5894 );
5895 assert!(
5896 (slam
5897 .local_vi_ba_state
5898 .as_ref()
5899 .unwrap()
5900 .config
5901 .gravity_world
5902 - new_gravity)
5903 .norm()
5904 < 1.0e-12,
5905 "sink (3): local_vi_ba_state.config.gravity_world must mirror the estimate"
5906 );
5907 assert!(
5908 (slam.config.local_vi_ba.as_ref().unwrap().gravity_world - new_gravity).norm()
5909 < 1.0e-12,
5910 "sink (4): config.local_vi_ba.gravity_world must mirror the estimate"
5911 );
5912 assert!(
5913 (slam
5914 .vi_motion_init_state
5915 .as_ref()
5916 .unwrap()
5917 .initializer
5918 .config()
5919 .gravity_world
5920 - new_gravity)
5921 .norm()
5922 < 1.0e-12,
5923 "sink (5): the motion initializer's own config must mirror the estimate"
5924 );
5925 assert!(
5926 (slam
5927 .config
5928 .vi_motion_init
5929 .as_ref()
5930 .unwrap()
5931 .initializer
5932 .gravity_world
5933 - new_gravity)
5934 .norm()
5935 < 1.0e-12,
5936 "sink (6): config.vi_motion_init.initializer.gravity_world must mirror the estimate"
5937 );
5938 assert!(
5939 (slam
5940 .config
5941 .vi_init
5942 .as_ref()
5943 .unwrap()
5944 .initializer
5945 .gravity_world
5946 - new_gravity)
5947 .norm()
5948 < 1.0e-12,
5949 "sink (7): config.vi_init.initializer.gravity_world must mirror the estimate"
5950 );
5951 }
5952
5953 #[test]
5972 fn gravity_mirror_keeps_config_reconstructible_after_rebootstrap() {
5973 let seed_gravity = OnlineSlamImuConfig::default().gravity_world;
5979
5980 let vi_init_config = OnlineSlamViInitConfig {
5981 initializer: VisualInertialInitializerConfig {
5982 gravity_world: seed_gravity,
5983 ..VisualInertialInitializerConfig::default()
5984 },
5985 ..OnlineSlamViInitConfig::default()
5986 };
5987
5988 let motion_config = OnlineSlamMotionViInitConfig {
5989 initializer: MotionBasedViInitializerConfig {
5990 gravity_world: seed_gravity,
5991 ..MotionBasedViInitializerConfig::default()
5992 },
5993 ..OnlineSlamMotionViInitConfig::default()
5994 };
5995
5996 let config = OnlineSlamConfig {
5997 imu: Some(OnlineSlamImuConfig::default()),
5998 local_vi_ba: Some(OnlineSlamLocalBaConfig::default()),
5999 vi_init: Some(vi_init_config),
6000 vi_motion_init: Some(motion_config),
6001 ..OnlineSlamConfig::default()
6002 };
6003
6004 let mut slam = OnlineSlamPipeline::new(
6007 VisualMap::new(),
6008 Tracker::new(LocalizationPipeline::default(), TrackingConfig::default()),
6009 LocalMappingPipeline::default(),
6010 config,
6011 );
6012
6013 let estimated_gravity = Vector3::new(0.1678, 9.3632, 2.9222);
6014 assert!(
6015 (estimated_gravity - seed_gravity).norm() > 1.0,
6016 "fixture must actually move the gravity assumption"
6017 );
6018 let mut result = fake_result(1, Vector3::zeros(), true);
6019 result.estimated_gravity_world = Some(estimated_gravity);
6020 match slam.promote_motion_vi_init_result(result) {
6021 MotionViInitializationEvent::Succeeded { result } => {
6022 assert_eq!(result.estimated_gravity_world, Some(estimated_gravity));
6023 }
6024 other => panic!("expected Succeeded, got {other:?}"),
6025 }
6026
6027 assert_eq!(
6030 slam.config.imu.as_ref().unwrap().gravity_world,
6031 estimated_gravity
6032 );
6033 assert_eq!(
6034 slam.config
6035 .vi_init
6036 .as_ref()
6037 .unwrap()
6038 .initializer
6039 .gravity_world,
6040 estimated_gravity
6041 );
6042 assert_eq!(
6043 slam.config
6044 .vi_motion_init
6045 .as_ref()
6046 .unwrap()
6047 .initializer
6048 .gravity_world,
6049 estimated_gravity
6050 );
6051 assert!(slam.config.validate().is_ok());
6052
6053 let _rebuilt = OnlineSlamPipeline::new(
6056 VisualMap::new(),
6057 Tracker::new(LocalizationPipeline::default(), TrackingConfig::default()),
6058 LocalMappingPipeline::default(),
6059 slam.config.clone(),
6060 );
6061 }
6062
6063 #[test]
6068 fn no_estimated_gravity_leaves_every_sink_untouched() {
6069 let mut slam = minimal_pipeline_with_motion_vi_state();
6070 slam.imu_state = Some(OnlineSlamImuState::new(OnlineSlamImuConfig::default()));
6071 slam.config.imu = Some(OnlineSlamImuConfig::default());
6072 let original_gravity = OnlineSlamImuConfig::default().gravity_world;
6073
6074 let result = fake_result(1, Vector3::zeros(), true);
6075 assert!(result.estimated_gravity_world.is_none());
6076 slam.promote_motion_vi_init_result(result);
6077
6078 assert_eq!(
6079 slam.imu_state.as_ref().unwrap().config.gravity_world,
6080 original_gravity
6081 );
6082 assert_eq!(
6083 slam.config.imu.as_ref().unwrap().gravity_world,
6084 original_gravity
6085 );
6086 }
6087
6088 #[test]
6097 fn stage_a_promotion_unblocks_vi_initialization_pending() {
6098 let mut slam = minimal_pipeline_with_motion_vi_state();
6099 slam.vi_init_state = Some(OnlineSlamViInitState::new(OnlineSlamViInitConfig::default()));
6100
6101 assert!(
6103 slam.vi_initialization_pending(),
6104 "with no Stage A fired and static init incomplete, local VI-BA must stay gated"
6105 );
6106
6107 let stage_a = fake_result(1, Vector3::new(1.0, 0.0, 0.0), false);
6118 slam.vi_motion_init_state
6119 .as_mut()
6120 .expect("configured above")
6121 .initializer
6122 .set_velocity_stage_result_for_test(stage_a.clone());
6123 match slam.promote_motion_vi_init_result(stage_a) {
6124 MotionViInitializationEvent::Succeeded { result } => assert!(!result.bias_released),
6125 other => panic!("expected Succeeded, got {other:?}"),
6126 }
6127 let motion_state = slam
6128 .vi_motion_init_state
6129 .as_ref()
6130 .expect("configured above");
6131 assert!(
6132 motion_state.completed.is_none(),
6133 "Stage A must NOT mark the motion-VI stage completed"
6134 );
6135 assert!(
6136 motion_state.velocity_stage_fired(),
6137 "Stage A must be visible via velocity_stage_fired()"
6138 );
6139
6140 assert!(
6141 !slam.vi_initialization_pending(),
6142 "a Stage A promotion must unblock vi_initialization_pending even though the \
6143 motion-VI stage remains non-terminal"
6144 );
6145 }
6146
6147 #[test]
6152 fn no_stage_a_and_incomplete_static_init_keeps_vi_initialization_pending() {
6153 let mut slam = minimal_pipeline_with_motion_vi_state();
6154 slam.vi_init_state = Some(OnlineSlamViInitState::new(OnlineSlamViInitConfig::default()));
6155
6156 assert!(
6157 slam.vi_initialization_pending(),
6158 "static init incomplete + motion-VI stage never fired must stay pending"
6159 );
6160
6161 assert!(slam
6164 .vi_motion_init_state
6165 .as_ref()
6166 .unwrap()
6167 .completed
6168 .is_none());
6169 assert!(!slam
6170 .vi_motion_init_state
6171 .as_ref()
6172 .unwrap()
6173 .velocity_stage_fired());
6174 assert!(slam.vi_initialization_pending());
6175 }
6176}
6177
6178#[derive(Debug, Clone, PartialEq)]
6179pub struct OnlineSlamResult {
6180 pub tracking: TrackingResult,
6181 pub mapping: Option<LocalMappingResult>,
6182 pub applied_update: Option<AppliedMapUpdate>,
6183 pub loop_closure_candidates: Vec<LoopClosureCandidate>,
6184 pub imu_factor: Option<ImuPreintegrationFactor>,
6191 pub local_vi_ba: Option<OnlineSlamLocalBaStats>,
6197 pub sparse_factor_graph: Option<SparseFactorGraphUpdateStats>,
6200 pub covisibility_local_ba: Option<OnlineSlamCovisibilityLocalBaStats>,
6207 pub map_keyframe_count: usize,
6208 pub map_landmark_count: usize,
6209 pub vi_init: Option<ViInitializationEvent>,
6217 pub vi_motion_init: Option<MotionViInitializationEvent>,
6225 pub pose_graph_refinement: Option<OnlineSlamLoopClosureRefinementStats>,
6233 pub relocalization: Option<OnlineSlamRelocalizationStats>,
6241}
6242
6243impl OnlineSlamResult {
6244 pub const fn tracking_succeeded(&self) -> bool {
6245 self.tracking.localization.success
6246 }
6247
6248 pub const fn map_was_updated(&self) -> bool {
6249 self.applied_update.is_some()
6250 }
6251
6252 pub fn has_loop_closure_candidate(&self) -> bool {
6253 !self.loop_closure_candidates.is_empty()
6254 }
6255}
6256
6257fn propagate_pose_graph_corrections(
6287 map: &mut VisualMap,
6288 corrections: &HashMap<u64, SE3>,
6289) -> (usize, Option<f64>, Option<f64>) {
6290 let mut anchor_keyframe_of_landmark: HashMap<u64, u64> = HashMap::new();
6291 let mut keyframe_ids: Vec<u64> = map.keyframes.keys().copied().collect();
6292 keyframe_ids.sort_unstable();
6293 for keyframe_id in keyframe_ids {
6294 let Some(keyframe) = map.keyframes.get(&keyframe_id) else {
6295 continue;
6296 };
6297 for observation in &keyframe.observations {
6298 anchor_keyframe_of_landmark
6299 .entry(observation.landmark_id)
6300 .or_insert(keyframe_id);
6301 }
6302 }
6303
6304 let mut moved = 0usize;
6305 let mut max_displacement = 0.0_f64;
6306 let mut sum_displacement = 0.0_f64;
6307 for (landmark_id, anchor_keyframe_id) in &anchor_keyframe_of_landmark {
6308 let Some(correction) = corrections.get(anchor_keyframe_id) else {
6309 continue;
6310 };
6311 let Some(landmark) = map.landmarks.get_mut(landmark_id) else {
6312 continue;
6313 };
6314 let old_position = landmark.position;
6315 landmark.position = correction.transform_point(&old_position);
6316 let displacement = (landmark.position - old_position).norm();
6317 if let Some(covariance) = map.landmark_position_covariances.get_mut(landmark_id) {
6318 let rotation = correction.rotation.to_rotation_matrix().into_inner();
6319 *covariance = rotation * *covariance * rotation.transpose();
6320 }
6321 moved += 1;
6322 sum_displacement += displacement;
6323 if displacement > max_displacement {
6324 max_displacement = displacement;
6325 }
6326 }
6327
6328 if moved == 0 {
6329 (0, None, None)
6330 } else {
6331 (
6332 moved,
6333 Some(max_displacement),
6334 Some(sum_displacement / moved as f64),
6335 )
6336 }
6337}
6338
6339const fn sim3_at_unit_scale(se3: &SE3) -> Sim3 {
6345 Sim3::new(se3.rotation, se3.translation, 1.0)
6346}
6347
6348#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6354enum Sim3ScaleEstimationFailure {
6355 InsufficientPoints,
6356 InsufficientMatches,
6357 NoConsensus,
6358}
6359
6360fn estimate_loop_sim3_scale_3d3d(
6361 map: &VisualMap,
6362 from_keyframe_id: u64,
6363 to_keyframe_id: u64,
6364 pnp_query_landmark_pairs: &[(usize, u64)],
6365 metric_points_camera: &HashMap<usize, Point3<f64>>,
6366) -> Result<f64, Sim3ScaleEstimationFailure> {
6367 let from = map
6368 .keyframes
6369 .get(&from_keyframe_id)
6370 .ok_or(Sim3ScaleEstimationFailure::InsufficientPoints)?;
6371 let to = map
6372 .keyframes
6373 .get(&to_keyframe_id)
6374 .ok_or(Sim3ScaleEstimationFailure::InsufficientPoints)?;
6375 let from_pose = from
6376 .frame
6377 .pose
6378 .as_ref()
6379 .ok_or(Sim3ScaleEstimationFailure::InsufficientPoints)?;
6380 let to_pose = to
6381 .frame
6382 .pose
6383 .as_ref()
6384 .ok_or(Sim3ScaleEstimationFailure::InsufficientPoints)?;
6385
6386 let collect = |keyframe: &Keyframe, pose: &Pose, prefer_frame_descriptor: bool| {
6387 keyframe
6388 .observations
6389 .iter()
6390 .filter_map(|observation| {
6391 let landmark = map.landmarks.get(&observation.landmark_id)?;
6392 let frame_descriptor = || {
6398 keyframe
6399 .frame
6400 .descriptors
6401 .get(observation.keypoint_index)
6402 .cloned()
6403 };
6404 let descriptor = if prefer_frame_descriptor {
6405 frame_descriptor().or_else(|| landmark.descriptor.clone())
6406 } else {
6407 landmark.descriptor.clone().or_else(frame_descriptor)
6408 }?;
6409 Some((
6410 observation.landmark_id,
6411 descriptor,
6412 pose.transform_world_point(&landmark.position),
6413 ))
6414 })
6415 .collect::<Vec<_>>()
6416 };
6417 let from_points = collect(from, from_pose, false);
6421 let to_points = collect(to, to_pose, true);
6422 if from_points.len() < 4 || to_points.len() < 4 {
6423 return Err(Sim3ScaleEstimationFailure::InsufficientPoints);
6424 }
6425 let mut matched = Vec::new();
6426 if pnp_query_landmark_pairs.is_empty() {
6427 let from_descriptors: Vec<Vec<f32>> =
6428 from_points.iter().map(|(_, d, _)| d.clone()).collect();
6429 let to_descriptors: Vec<Vec<f32>> = to_points.iter().map(|(_, d, _)| d.clone()).collect();
6430 let matcher = visloc_vision::matching::BruteForceMatcher::default();
6431 let forward = matcher.match_descriptors(&from_descriptors, &to_descriptors);
6432 let reverse = matcher.match_descriptors(&to_descriptors, &from_descriptors);
6433 for m in forward {
6434 let reciprocal = reverse
6435 .iter()
6436 .any(|r| r.query_index == m.train_index && r.train_index == m.query_index);
6437 if reciprocal && from_points[m.query_index].0 != to_points[m.train_index].0 {
6438 matched.push((from_points[m.query_index].2, to_points[m.train_index].2));
6439 }
6440 }
6441 } else if !metric_points_camera.is_empty() {
6442 for &(query_index, old_landmark_id) in pnp_query_landmark_pairs {
6443 let Some(current_point) = metric_points_camera.get(&query_index) else {
6444 continue;
6445 };
6446 let Some(old_landmark) = map.landmarks.get(&old_landmark_id) else {
6447 continue;
6448 };
6449 matched.push((
6450 from_pose.transform_world_point(&old_landmark.position),
6451 *current_point,
6452 ));
6453 }
6454 } else {
6455 let current_landmark_by_keypoint: HashMap<usize, u64> = to
6456 .observations
6457 .iter()
6458 .map(|observation| (observation.keypoint_index, observation.landmark_id))
6459 .collect();
6460 for &(query_index, old_landmark_id) in pnp_query_landmark_pairs {
6461 let Some(¤t_landmark_id) = current_landmark_by_keypoint.get(&query_index) else {
6462 continue;
6463 };
6464 if current_landmark_id == old_landmark_id {
6465 continue;
6466 }
6467 let Some(old_landmark) = map.landmarks.get(&old_landmark_id) else {
6468 continue;
6469 };
6470 let Some(current_landmark) = map.landmarks.get(¤t_landmark_id) else {
6471 continue;
6472 };
6473 matched.push((
6474 from_pose.transform_world_point(&old_landmark.position),
6475 to_pose.transform_world_point(¤t_landmark.position),
6476 ));
6477 }
6478 }
6479 if matched.len() < 6 {
6480 return Err(Sim3ScaleEstimationFailure::InsufficientMatches);
6481 }
6482
6483 let mut scene_distances = Vec::new();
6487 for i in 0..matched.len() {
6488 for j in (i + 1)..matched.len() {
6489 scene_distances.push((matched[i].1 - matched[j].1).norm());
6490 }
6491 }
6492 scene_distances.sort_by(f64::total_cmp);
6493 let scene_scale = scene_distances[scene_distances.len() / 2];
6494 let inlier_threshold = (scene_scale * 0.10).clamp(0.05, 1.0);
6500
6501 let mut best_inliers = Vec::new();
6502 let mut best_rmse = f64::INFINITY;
6503 let mut hypotheses = 0usize;
6504 'triplets: for i in 0..matched.len() - 2 {
6505 for j in (i + 1)..matched.len() - 1 {
6506 for k in (j + 1)..matched.len() {
6507 if hypotheses >= 256 {
6508 break 'triplets;
6509 }
6510 hypotheses += 1;
6511 let source = [matched[i].0, matched[j].0, matched[k].0];
6512 let target = [matched[i].1, matched[j].1, matched[k].1];
6513 let Some(model) =
6514 visloc_tracking::umeyama_similarity_transform(&source, &target, true)
6515 else {
6516 continue;
6517 };
6518 if !model.scale.is_finite() || !(0.5..=2.0).contains(&model.scale) {
6519 continue;
6520 }
6521 let mut inliers = Vec::new();
6522 let mut squared_error = 0.0;
6523 for (index, (from_point, to_point)) in matched.iter().enumerate() {
6524 let error = (model.apply(from_point) - to_point).norm();
6525 if error <= inlier_threshold {
6526 inliers.push(index);
6527 squared_error += error * error;
6528 }
6529 }
6530 let rmse = if inliers.is_empty() {
6531 f64::INFINITY
6532 } else {
6533 (squared_error / inliers.len() as f64).sqrt()
6534 };
6535 if inliers.len() > best_inliers.len()
6536 || (inliers.len() == best_inliers.len() && rmse < best_rmse)
6537 {
6538 best_inliers = inliers;
6539 best_rmse = rmse;
6540 }
6541 }
6542 }
6543 }
6544 let min_inliers = 6usize.max(matched.len().div_ceil(2));
6545 if best_inliers.len() < min_inliers || best_rmse > inlier_threshold * 0.75 {
6546 return Err(Sim3ScaleEstimationFailure::NoConsensus);
6547 }
6548 let source: Vec<Point3<f64>> = best_inliers.iter().map(|&i| matched[i].0).collect();
6549 let target: Vec<Point3<f64>> = best_inliers.iter().map(|&i| matched[i].1).collect();
6550 let refined = visloc_tracking::umeyama_similarity_transform(&source, &target, true)
6551 .ok_or(Sim3ScaleEstimationFailure::NoConsensus)?;
6552 (refined.scale.is_finite() && (0.5..=2.0).contains(&refined.scale))
6553 .then_some(refined.scale)
6554 .ok_or(Sim3ScaleEstimationFailure::NoConsensus)
6555}
6556
6557fn sim3_pose_scale_spread(graph: &Sim3PoseGraph) -> Option<(f64, f64)> {
6561 let mut scales = graph.poses.values().map(|pose| pose.scale);
6562 let first = scales.next()?;
6563 let (min, max) = scales.fold((first, first), |(min, max), scale| {
6564 (min.min(scale), max.max(scale))
6565 });
6566 Some((min, max))
6567}
6568
6569fn propagate_pose_graph_corrections_sim3(
6588 map: &mut VisualMap,
6589 corrections: &HashMap<u64, Sim3>,
6590) -> (usize, Option<f64>, Option<f64>) {
6591 let mut anchor_keyframe_of_landmark: HashMap<u64, u64> = HashMap::new();
6592 let mut keyframe_ids: Vec<u64> = map.keyframes.keys().copied().collect();
6593 keyframe_ids.sort_unstable();
6594 for keyframe_id in keyframe_ids {
6595 let Some(keyframe) = map.keyframes.get(&keyframe_id) else {
6596 continue;
6597 };
6598 for observation in &keyframe.observations {
6599 anchor_keyframe_of_landmark
6600 .entry(observation.landmark_id)
6601 .or_insert(keyframe_id);
6602 }
6603 }
6604
6605 let mut moved = 0usize;
6606 let mut max_displacement = 0.0_f64;
6607 let mut sum_displacement = 0.0_f64;
6608 for (landmark_id, anchor_keyframe_id) in &anchor_keyframe_of_landmark {
6609 let Some(correction) = corrections.get(anchor_keyframe_id) else {
6610 continue;
6611 };
6612 let Some(landmark) = map.landmarks.get_mut(landmark_id) else {
6613 continue;
6614 };
6615 let old_position = landmark.position;
6616 landmark.position = correction.transform_point(&old_position);
6617 let displacement = (landmark.position - old_position).norm();
6618 if let Some(covariance) = map.landmark_position_covariances.get_mut(landmark_id) {
6619 let rotation = correction.rotation.to_rotation_matrix().into_inner();
6620 *covariance = rotation * *covariance * rotation.transpose() * correction.scale.powi(2);
6621 }
6622 moved += 1;
6623 sum_displacement += displacement;
6624 if displacement > max_displacement {
6625 max_displacement = displacement;
6626 }
6627 }
6628
6629 if moved == 0 {
6630 (0, None, None)
6631 } else {
6632 (
6633 moved,
6634 Some(max_displacement),
6635 Some(sum_displacement / moved as f64),
6636 )
6637 }
6638}
6639
6640fn apply_loop_edge_scale(information: Matrix6<f64>, loop_edge_scale: f64) -> Matrix6<f64> {
6641 information * loop_edge_scale
6642}
6643
6644#[cfg(test)]
6645#[allow(clippy::items_after_test_module)]
6646mod sim3_scale_estimation_tests {
6647 use super::*;
6648 use nalgebra::{Point2, Point3};
6649 use visloc_core::types::Landmark;
6650
6651 #[test]
6652 fn bias_promotion_reset_preserves_preintegration_noise_model() {
6653 let noise = ImuNoiseModel {
6654 gyroscope_noise_density: 1.0e-3,
6655 accelerometer_noise_density: 2.0e-2,
6656 };
6657 let mut state = OnlineSlamImuState::new(OnlineSlamImuConfig {
6658 noise_model: Some(noise),
6659 ..OnlineSlamImuConfig::default()
6660 });
6661 let bias_gyro = Vector3::new(0.01, -0.02, 0.03);
6662 let bias_acc = Vector3::new(0.1, -0.2, 0.3);
6663 state.reset_preintegrator_with_bias(bias_gyro, bias_acc);
6664 state
6665 .preintegrator
6666 .integrate_sample(Vector3::zeros(), Vector3::new(0.0, 0.0, 9.81), 0.01);
6667 let delta = state.preintegrator.delta();
6668 assert_eq!(delta.bias_gyro_linearisation, bias_gyro);
6669 assert_eq!(delta.bias_acc_linearisation, bias_acc);
6670 assert!(delta.covariance.trace() > 0.0);
6671 }
6672
6673 #[test]
6674 fn loop_edge_scale_preserves_information_anisotropy() {
6675 let information = Matrix6::from_diagonal(&nalgebra::SVector::<f64, 6>::new(
6676 1.0, 2.0, 4.0, 8.0, 16.0, 32.0,
6677 ));
6678 let scaled = apply_loop_edge_scale(information, 0.1);
6679 assert!((scaled - information * 0.1).norm() < 1.0e-15);
6680 assert!((scaled[(5, 5)] / scaled[(0, 0)] - 32.0).abs() < 1.0e-15);
6681 }
6682
6683 #[test]
6684 fn loop_observation_fusion_reassigns_both_map_indices_idempotently() {
6685 let mut map = VisualMap::new();
6686 map.cameras
6687 .insert(1, Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0));
6688 let mut old_frame = Frame::new(10, 1);
6689 old_frame.pose = Some(Pose::identity());
6690 old_frame.keypoints.push(Point2::new(320.0, 240.0));
6691 let old_observation = Observation {
6692 frame_id: 10,
6693 landmark_id: 1,
6694 keypoint_index: 0,
6695 xy: old_frame.keypoints[0],
6696 };
6697 map.keyframes.insert(
6698 10,
6699 Keyframe {
6700 frame: old_frame,
6701 observations: vec![old_observation.clone()],
6702 },
6703 );
6704 let mut frame = Frame::new(20, 1);
6705 frame.pose = Some(Pose::identity());
6706 frame.keypoints.push(Point2::new(320.0, 240.0));
6707 let previous = Observation {
6708 frame_id: 20,
6709 landmark_id: 2,
6710 keypoint_index: 0,
6711 xy: frame.keypoints[0],
6712 };
6713 map.keyframes.insert(
6714 20,
6715 Keyframe {
6716 frame,
6717 observations: vec![previous.clone()],
6718 },
6719 );
6720 let mut old_landmark = Landmark::new(1, Point3::new(0.0, 0.0, 5.0));
6721 old_landmark.observations.push(old_observation);
6722 map.landmarks.insert(1, old_landmark);
6723 let mut duplicate = Landmark::new(2, Point3::new(0.1, 0.0, 5.0));
6724 duplicate.observations.push(previous);
6725 map.landmarks.insert(2, duplicate);
6726
6727 let camera = map.cameras[&1].clone();
6728 let first = fuse_loop_observations(&mut map, &camera, 20, &[(0, 1)], 4.0);
6729 assert_eq!(
6730 first,
6731 LoopObservationFusionStats {
6732 pairs_considered: 1,
6733 observations_inserted: 1,
6734 observations_reassigned: 1,
6735 pairs_skipped: 0,
6736 reprojection_rejected: 0,
6737 }
6738 );
6739 assert_eq!(map.keyframes[&20].observations[0].landmark_id, 1);
6740 assert_eq!(map.landmarks[&1].observations.len(), 2);
6741 assert!(map.landmarks[&2].observations.is_empty());
6742 assert!(map.validate().is_valid());
6743
6744 let selection = select_covisibility_local_ba_window(
6745 &map,
6746 20,
6747 &CovisibilityLocalBaConfig {
6748 max_neighbor_keyframes: 1,
6749 min_shared_landmarks: 1,
6750 max_boundary_keyframes: 0,
6751 min_boundary_observations: 1,
6752 min_observations_per_landmark: 2,
6753 min_active_observations: 1,
6754 ..CovisibilityLocalBaConfig::default()
6755 },
6756 )
6757 .expect("fused loop observation should connect both welding regions");
6758 assert_eq!(selection.optimized_keyframe_ids, vec![20, 10]);
6759 assert_eq!(selection.landmark_ids, vec![1]);
6760
6761 let second = fuse_loop_observations(&mut map, &camera, 20, &[(0, 1)], 4.0);
6762 assert_eq!(second.pairs_considered, 1);
6763 assert_eq!(second.observations_inserted, 0);
6764 assert_eq!(second.observations_reassigned, 0);
6765 assert_eq!(second.pairs_skipped, 0);
6766 assert_eq!(map.keyframes[&20].observations.len(), 1);
6767 assert_eq!(map.landmarks[&1].observations.len(), 2);
6768
6769 map.keyframes
6770 .get_mut(&20)
6771 .unwrap()
6772 .frame
6773 .keypoints
6774 .push(Point2::new(100.0, 100.0));
6775 map.landmarks
6776 .insert(3, Landmark::new(3, Point3::new(0.0, 0.0, 5.0)));
6777 let rejected = fuse_loop_observations(&mut map, &camera, 20, &[(1, 3)], 4.0);
6778 assert_eq!(rejected.pairs_considered, 1);
6779 assert_eq!(rejected.observations_inserted, 0);
6780 assert_eq!(rejected.pairs_skipped, 1);
6781 assert_eq!(rejected.reprojection_rejected, 1);
6782 assert!(map.keyframes[&20]
6783 .observations
6784 .iter()
6785 .all(|observation| observation.keypoint_index != 1));
6786 }
6787
6788 #[test]
6789 fn loop_welding_region_correction_preserves_local_reprojection() {
6790 let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
6791 let mut map = VisualMap::new();
6792 map.cameras.insert(1, camera.clone());
6793
6794 let mut matched = Frame::new(10, 1);
6795 matched.pose = Some(Pose::identity());
6796 map.keyframes.insert(
6797 10,
6798 Keyframe {
6799 frame: matched,
6800 observations: Vec::new(),
6801 },
6802 );
6803
6804 let drifted_pose = Pose::from_world_to_camera(
6805 nalgebra::UnitQuaternion::identity(),
6806 Vector3::new(1.0, 0.0, 0.0),
6807 );
6808 let local_point = Point3::new(0.0, 0.0, 5.0);
6809 let local_xy = camera
6810 .project(&drifted_pose.transform_world_point(&local_point))
6811 .unwrap();
6812 let mut local_landmark = Landmark::new(2, local_point);
6813 for id in [20_u64, 21_u64] {
6814 let mut frame = Frame::new(id, 1);
6815 frame.pose = Some(drifted_pose.clone());
6816 frame.keypoints.push(local_xy);
6817 let observation = Observation {
6818 frame_id: id,
6819 landmark_id: 2,
6820 keypoint_index: 0,
6821 xy: local_xy,
6822 };
6823 map.keyframes.insert(
6824 id,
6825 Keyframe {
6826 frame,
6827 observations: vec![observation.clone()],
6828 },
6829 );
6830 local_landmark.observations.push(observation);
6831 }
6832 map.landmarks.insert(2, local_landmark);
6833
6834 let corrected = correct_loop_welding_region(
6835 &mut map,
6836 10,
6837 20,
6838 &SE3::identity(),
6839 &CovisibilityLocalBaConfig {
6840 max_neighbor_keyframes: 1,
6841 min_shared_landmarks: 1,
6842 max_boundary_keyframes: 0,
6843 min_boundary_observations: 1,
6844 min_observations_per_landmark: 2,
6845 min_active_observations: 1,
6846 ..CovisibilityLocalBaConfig::default()
6847 },
6848 )
6849 .unwrap();
6850
6851 assert_eq!(corrected.keyframe_ids, vec![20, 21]);
6852 assert!((corrected.translation_meters - 1.0).abs() < 1.0e-9);
6853 assert!(corrected.rotation_radians < 1.0e-9);
6854 for id in corrected.keyframe_ids {
6855 let pose = map.keyframes[&id].frame.pose.as_ref().unwrap();
6856 let projected = camera
6857 .project(&pose.transform_world_point(&map.landmarks[&2].position))
6858 .unwrap();
6859 assert!((projected - local_xy).norm() < 1.0e-9);
6860 }
6861 assert!(
6862 map.keyframes[&20]
6863 .frame
6864 .pose
6865 .as_ref()
6866 .unwrap()
6867 .world_to_camera
6868 .translation
6869 .norm()
6870 < 1.0e-9
6871 );
6872 assert!((map.landmarks[&2].position - Point3::new(1.0, 0.0, 5.0)).norm() < 1.0e-9);
6873 }
6874
6875 fn covariance_propagation_map() -> VisualMap {
6876 let mut map = VisualMap::new();
6877 map.landmarks
6878 .insert(1, Landmark::new(1, Point3::new(1.0, 0.0, 2.0)));
6879 map.landmark_position_covariances.insert(
6880 1,
6881 nalgebra::Matrix3::from_diagonal(&Vector3::new(1.0, 4.0, 9.0)),
6882 );
6883 let frame = Frame::new(10, 1);
6884 map.keyframes.insert(
6885 10,
6886 Keyframe {
6887 frame,
6888 observations: vec![Observation {
6889 frame_id: 10,
6890 landmark_id: 1,
6891 keypoint_index: 0,
6892 xy: Point2::new(0.0, 0.0),
6893 }],
6894 },
6895 );
6896 map
6897 }
6898
6899 #[test]
6900 fn se3_landmark_propagation_rotates_position_covariance() {
6901 let mut map = covariance_propagation_map();
6902 let correction = SE3::new(
6903 nalgebra::UnitQuaternion::from_axis_angle(
6904 &Vector3::z_axis(),
6905 std::f64::consts::FRAC_PI_2,
6906 ),
6907 Vector3::new(0.5, 0.0, 0.0),
6908 );
6909 propagate_pose_graph_corrections(&mut map, &HashMap::from([(10, correction)]));
6910 let covariance = map.landmark_position_covariances.get(&1).unwrap();
6911 let expected = nalgebra::Matrix3::from_diagonal(&Vector3::new(4.0, 1.0, 9.0));
6912 assert!((*covariance - expected).norm() < 1.0e-10);
6913 }
6914
6915 #[test]
6916 fn sim3_landmark_propagation_rotates_and_scales_position_covariance() {
6917 let mut map = covariance_propagation_map();
6918 let correction = Sim3::new(nalgebra::UnitQuaternion::identity(), Vector3::zeros(), 2.0);
6919 propagate_pose_graph_corrections_sim3(&mut map, &HashMap::from([(10, correction)]));
6920 let covariance = map.landmark_position_covariances.get(&1).unwrap();
6921 let expected = nalgebra::Matrix3::from_diagonal(&Vector3::new(4.0, 16.0, 36.0));
6922 assert!((*covariance - expected).norm() < 1.0e-10);
6923 }
6924
6925 fn verified_appearance_candidate(query_frame_id: u64) -> LoopClosureCandidate {
6926 verified_appearance_candidate_with_pose(query_frame_id, 10, SE3::identity())
6927 }
6928
6929 fn verified_appearance_candidate_with_pose(
6930 query_frame_id: u64,
6931 matched_keyframe_id: u64,
6932 relative_pose: SE3,
6933 ) -> LoopClosureCandidate {
6934 LoopClosureCandidate {
6935 query_frame_id,
6936 matched_keyframe_id,
6937 shared_landmark_count: 40,
6938 query_inlier_count: 40,
6939 keyframe_observation_count: 40,
6940 shared_landmark_ratio: 1.0,
6941 score: 10.0,
6942 geometrically_verified: true,
6943 verification: Some(LoopClosureVerification {
6944 verified: true,
6945 correspondence_count: 40,
6946 inlier_count: 40,
6947 inlier_ratio: 1.0,
6948 mean_sampson_error: 0.0,
6949 score: 10.0,
6950 failure_reason: None,
6951 relative_pose: Some(relative_pose),
6952 mean_reprojection_error_px: Some(0.0),
6953 }),
6954 pnp_query_landmark_pairs: Vec::new(),
6955 }
6956 }
6957
6958 #[test]
6959 fn pending_appearance_region_is_carried_by_projection_without_retrieval() {
6960 use nalgebra::{UnitQuaternion, Vector3};
6961
6962 let camera = Camera::pinhole(1, 640, 480, 420.0, 415.0, 320.0, 240.0);
6963 let mut map = VisualMap::new();
6964 map.cameras.insert(camera.id, camera.clone());
6965 let mut root_frame = Frame::new(10, camera.id);
6966 root_frame.pose = Some(Pose::identity());
6967 let mut root_observations = Vec::new();
6968 let mut current_frame = Frame::new(110, camera.id);
6969 let current_pose =
6970 Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.05, -0.02, 0.01));
6971 current_frame.pose = Some(current_pose.clone());
6972
6973 for index in 0..64usize {
6974 let row = index / 8;
6975 let column = index % 8;
6976 let point = Point3::new(
6977 (column as f64 - 3.5) * 0.22,
6978 (row as f64 - 3.5) * 0.18,
6979 4.0 + (index % 7) as f64 * 0.35,
6980 );
6981 let mut descriptor = vec![0.0_f32; 64];
6982 descriptor[index] = 1.0;
6983 let landmark_id = index as u64 + 1;
6984 let mut landmark = Landmark::new(landmark_id, point);
6985 landmark.descriptor = Some(descriptor.clone());
6986 let root_xy = camera.project(&point).unwrap();
6987 let observation = Observation {
6988 frame_id: root_frame.id,
6989 landmark_id,
6990 keypoint_index: index,
6991 xy: root_xy,
6992 };
6993 root_frame.keypoints.push(root_xy);
6994 root_frame.descriptors.push(descriptor.clone());
6995 root_observations.push(observation.clone());
6996 landmark.observations.push(observation);
6997 current_frame.keypoints.push(
6998 camera
6999 .project(¤t_pose.transform_world_point(&point))
7000 .unwrap(),
7001 );
7002 current_frame.descriptors.push(descriptor);
7003 map.landmarks.insert(landmark_id, landmark);
7004 }
7005 map.keyframes.insert(
7006 root_frame.id,
7007 Keyframe {
7008 frame: root_frame,
7009 observations: root_observations,
7010 },
7011 );
7012 let mut last_frame = Frame::new(100, camera.id);
7013 last_frame.pose = Some(Pose::identity());
7014 map.keyframes.insert(
7015 last_frame.id,
7016 Keyframe {
7017 frame: last_frame,
7018 observations: Vec::new(),
7019 },
7020 );
7021 map.keyframes.insert(
7022 current_frame.id,
7023 Keyframe {
7024 frame: current_frame.clone(),
7025 observations: Vec::new(),
7026 },
7027 );
7028 let pending = AppearancePendingRegion {
7029 root_keyframe_id: 10,
7030 last_current_keyframe_id: 100,
7031 root_to_last_current: SE3::identity(),
7032 confirmation_count: 1,
7033 miss_count: 0,
7034 };
7035 let config = LoopAppearanceCandidateConfig {
7036 min_candidate_landmark_count: 30,
7037 min_projection_correspondence_count: 50,
7038 projection_search_radius_px: Some(15.0),
7039 ..LoopAppearanceCandidateConfig::default()
7040 };
7041
7042 let result = verify_pending_appearance_region_by_projection(
7043 &map,
7044 ¤t_frame,
7045 &camera,
7046 &config,
7047 &pending,
7048 );
7049
7050 assert!(result.attempted);
7051 assert!(result.correspondence_count >= 50);
7052 assert!(result.inlier_count >= config.pnp_verifier.min_inliers);
7053 let candidate = result.candidate.expect("projection carry should verify");
7054 assert_eq!(candidate.matched_keyframe_id, 10);
7055 assert_eq!(candidate.query_frame_id, 110);
7056 assert!(candidate.pnp_query_landmark_pairs.len() >= config.pnp_verifier.min_inliers);
7057 }
7058
7059 #[test]
7060 fn confirms_the_same_appearance_region_across_three_keyframes() {
7061 let mut map = VisualMap::new();
7062 for frame_id in [10, 100, 110, 120] {
7063 let mut frame = Frame::new(frame_id, 1);
7064 frame.pose = Some(Pose::identity());
7065 map.keyframes.insert(
7066 frame_id,
7067 Keyframe {
7068 frame,
7069 observations: Vec::new(),
7070 },
7071 );
7072 }
7073 let config = LoopAppearanceCandidateConfig {
7074 region_confirmation_required_keyframes: 3,
7075 ..LoopAppearanceCandidateConfig::default()
7076 };
7077 let mut pending = None;
7078
7079 let (first, waiting, confirmed) = confirm_appearance_region_across_keyframes(
7080 &map,
7081 100,
7082 vec![verified_appearance_candidate(100)],
7083 &config,
7084 &mut pending,
7085 );
7086 assert!(first.is_empty() && waiting && !confirmed);
7087 let (second, waiting, confirmed) = confirm_appearance_region_across_keyframes(
7088 &map,
7089 110,
7090 vec![verified_appearance_candidate(110)],
7091 &config,
7092 &mut pending,
7093 );
7094 assert!(second.is_empty() && waiting && !confirmed);
7095 let (third, waiting, confirmed) = confirm_appearance_region_across_keyframes(
7096 &map,
7097 120,
7098 vec![verified_appearance_candidate(120)],
7099 &config,
7100 &mut pending,
7101 );
7102 assert_eq!(third.len(), 1);
7103 assert!(!waiting && confirmed);
7104 assert!(pending.is_none());
7105 }
7106
7107 #[test]
7108 fn confirms_overlapping_region_with_nontrivial_pose_composition() {
7109 use nalgebra::{UnitQuaternion, Vector3};
7110 use visloc_core::types::Observation;
7111
7112 let pose = |x: f64| {
7113 Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(x, 0.0, 0.0))
7114 };
7115 let observation = |frame_id| Observation {
7116 frame_id,
7117 landmark_id: 7,
7118 keypoint_index: 0,
7119 xy: Point2::origin(),
7120 };
7121 let mut map = VisualMap::new();
7122 for (frame_id, x) in [(10, 0.0), (20, 1.0), (100, 10.0), (110, 11.0), (120, 12.0)] {
7123 let mut frame = Frame::new(frame_id, 1);
7124 frame.pose = Some(pose(x));
7125 let observations = if matches!(frame_id, 10 | 20) {
7126 vec![observation(frame_id)]
7127 } else {
7128 Vec::new()
7129 };
7130 map.keyframes.insert(
7131 frame_id,
7132 Keyframe {
7133 frame,
7134 observations,
7135 },
7136 );
7137 }
7138 let config = LoopAppearanceCandidateConfig {
7139 covisibility_min_shared_landmarks: 1,
7140 region_confirmation_required_keyframes: 3,
7141 ..LoopAppearanceCandidateConfig::default()
7142 };
7143 let mut pending = None;
7144
7145 let first_edge = SE3::new(UnitQuaternion::identity(), Vector3::new(10.0, 0.0, 0.0));
7146 let second_edge = SE3::new(UnitQuaternion::identity(), Vector3::new(10.0, 0.0, 0.0));
7147 let third_edge = SE3::new(UnitQuaternion::identity(), Vector3::new(12.0, 0.0, 0.0));
7148 let (first, waiting, confirmed) = confirm_appearance_region_across_keyframes(
7149 &map,
7150 100,
7151 vec![verified_appearance_candidate_with_pose(100, 10, first_edge)],
7152 &config,
7153 &mut pending,
7154 );
7155 assert!(first.is_empty() && waiting && !confirmed);
7156 let (second, waiting, confirmed) = confirm_appearance_region_across_keyframes(
7157 &map,
7158 110,
7159 vec![verified_appearance_candidate_with_pose(
7160 110,
7161 20,
7162 second_edge,
7163 )],
7164 &config,
7165 &mut pending,
7166 );
7167 assert!(second.is_empty() && waiting && !confirmed);
7168 let (third, waiting, confirmed) = confirm_appearance_region_across_keyframes(
7169 &map,
7170 120,
7171 vec![verified_appearance_candidate_with_pose(120, 10, third_edge)],
7172 &config,
7173 &mut pending,
7174 );
7175 assert_eq!(third.len(), 1);
7176 assert_eq!(third[0].matched_keyframe_id, 10);
7177 assert!(!waiting && confirmed);
7178 assert!(pending.is_none());
7179 }
7180
7181 #[test]
7182 fn recovers_scale_from_duplicate_landmark_regions() {
7183 let mut map = VisualMap::new();
7184 let mut from_frame = Frame::new(10, 1);
7185 let mut to_frame = Frame::new(20, 1);
7186 from_frame.pose = Some(Pose::identity());
7187 to_frame.pose = Some(Pose::identity());
7188 let mut from_observations = Vec::new();
7189 let mut to_observations = Vec::new();
7190 let points = [
7191 Point3::new(0.0, 0.0, 4.0),
7192 Point3::new(1.0, 0.0, 4.2),
7193 Point3::new(0.0, 1.0, 4.4),
7194 Point3::new(1.0, 1.0, 4.8),
7195 Point3::new(-0.5, 0.3, 5.0),
7196 Point3::new(0.4, -0.7, 5.3),
7197 Point3::new(1.2, 0.6, 5.6),
7198 Point3::new(-0.8, -0.4, 4.6),
7199 ];
7200 for (index, point) in points.into_iter().enumerate() {
7201 let descriptor = vec![index as f32, 1.0, -(index as f32)];
7202 from_frame.descriptors.push(descriptor.clone());
7203 to_frame.descriptors.push(descriptor.clone());
7204 let from_id = index as u64 + 1;
7205 let to_id = index as u64 + 101;
7206 let mut from_landmark = Landmark::new(from_id, point);
7207 if index % 2 == 0 {
7208 from_landmark.descriptor = Some(descriptor.clone());
7209 }
7210 let transformed = if index < 6 {
7211 point.coords * 1.7 + Vector3::new(2.0, -1.0, 0.5)
7212 } else {
7213 Vector3::new(20.0 + index as f64, -15.0, 2.0)
7214 };
7215 let mut to_landmark = Landmark::new(to_id, Point3::from(transformed));
7216 to_landmark.descriptor = Some(vec![100.0 + index as f32, -50.0, 25.0]);
7219 map.landmarks.insert(from_id, from_landmark);
7220 map.landmarks.insert(to_id, to_landmark);
7221 from_observations.push(Observation {
7222 frame_id: 10,
7223 landmark_id: from_id,
7224 keypoint_index: index,
7225 xy: Point2::origin(),
7226 });
7227 to_observations.push(Observation {
7228 frame_id: 20,
7229 landmark_id: to_id,
7230 keypoint_index: index,
7231 xy: Point2::origin(),
7232 });
7233 }
7234 map.keyframes.insert(
7235 10,
7236 Keyframe {
7237 frame: from_frame,
7238 observations: from_observations,
7239 },
7240 );
7241 map.keyframes.insert(
7242 20,
7243 Keyframe {
7244 frame: to_frame,
7245 observations: to_observations,
7246 },
7247 );
7248
7249 let pnp_pairs: Vec<(usize, u64)> = (0..points.len())
7250 .map(|index| (index, index as u64 + 1))
7251 .collect();
7252 let scale =
7253 estimate_loop_sim3_scale_3d3d(&map, 10, 20, &pnp_pairs, &HashMap::new()).unwrap();
7254 assert!((scale - 1.7).abs() < 1.0e-9, "scale={scale}");
7255 }
7256}
7257
7258fn outlier_observation_ratio(outlier_count: usize, observation_count: usize) -> Option<f64> {
7259 if observation_count == 0 {
7260 None
7261 } else {
7262 Some(outlier_count as f64 / observation_count as f64)
7263 }
7264}
7265
7266#[derive(Debug, Clone, PartialEq)]
7273struct LoopWeldingRegionCorrection {
7274 keyframe_ids: Vec<u64>,
7275 translation_meters: f64,
7276 rotation_radians: f64,
7277}
7278
7279fn refine_pose_graph_after_welding(
7285 map: &mut VisualMap,
7286 graph: &mut PoseGraph,
7287 config: &PoseGraphSe3Config,
7288 gnc: Option<&gnc::GncConfig>,
7289 active_keyframe_id: u64,
7290 welding_config: &CovisibilityLocalBaConfig,
7291 max_mean_reprojection_px: f64,
7292) -> (
7293 bool,
7294 Option<f64>,
7295 Option<CovisibilityLocalBaError>,
7296 Option<f64>,
7297) {
7298 let original_map = map.clone();
7299 let original_graph = graph.clone();
7300 let mut post_config = config.clone();
7301 post_config.chordal_init = false;
7304 let solved = if let Some(gnc) = gnc {
7305 graph.optimize_se3_gnc(&post_config, gnc).is_ok()
7306 } else {
7307 graph.optimize_se3_iterative(&post_config).is_ok()
7308 };
7309 if !solved {
7310 *map = original_map;
7311 *graph = original_graph;
7312 return (false, None, None, None);
7313 }
7314
7315 let mut corrections = HashMap::new();
7316 for (id, new_pose) in &graph.poses {
7317 let Some(old_pose) = map
7318 .keyframes
7319 .get(id)
7320 .and_then(|keyframe| keyframe.frame.pose.as_ref())
7321 else {
7322 continue;
7323 };
7324 corrections.insert(
7325 *id,
7326 new_pose
7327 .world_to_camera
7328 .inverse()
7329 .compose(&old_pose.world_to_camera),
7330 );
7331 }
7332 for (id, new_pose) in &graph.poses {
7333 if let Some(keyframe) = map.keyframes.get_mut(id) {
7334 keyframe.frame.pose = Some(new_pose.clone());
7335 }
7336 }
7337 propagate_pose_graph_corrections(map, &corrections);
7338 let mut post_welding_config = welding_config.clone();
7344 post_welding_config.ba_config.max_iterations =
7345 post_welding_config.ba_config.max_iterations.max(20);
7346 post_welding_config.ba_config.robust_kernel = RobustKernel::Huber { delta: 5.0 };
7351 let post_ba =
7352 match refine_visual_map_with_covisibility_ba(map, active_keyframe_id, &post_welding_config)
7353 {
7354 Ok(result) => result,
7355 Err(error) => {
7356 *map = original_map;
7357 *graph = original_graph;
7358 return (false, None, Some(error), None);
7359 }
7360 };
7361 for id in &post_ba.selection.optimized_keyframe_ids {
7362 if let Some(pose) = map
7363 .keyframes
7364 .get(id)
7365 .and_then(|keyframe| keyframe.frame.pose.clone())
7366 {
7367 if graph.poses.contains_key(id) {
7368 graph.poses.insert(*id, pose);
7369 }
7370 }
7371 }
7372 let mean_reprojection = mean_selected_reprojection_px(map, &post_ba.selection);
7373 let behind_camera_ratio = behind_camera_optimized_landmark_ratio(map, &post_ba.selection);
7374 let reprojection_ok = mean_reprojection
7375 .is_some_and(|error| error.is_finite() && error <= max_mean_reprojection_px + 1.0e-9);
7376 let behind_camera_ok = behind_camera_ratio.is_some_and(|ratio| ratio <= 0.01);
7377 if !reprojection_ok || !behind_camera_ok || !map.validate().is_valid() {
7378 *map = original_map;
7379 *graph = original_graph;
7380 return (false, mean_reprojection, None, behind_camera_ratio);
7381 }
7382 (true, mean_reprojection, None, behind_camera_ratio)
7383}
7384
7385fn correct_loop_welding_region(
7386 map: &mut VisualMap,
7387 matched_keyframe_id: u64,
7388 query_keyframe_id: u64,
7389 matched_to_query: &SE3,
7390 config: &CovisibilityLocalBaConfig,
7391) -> Option<LoopWeldingRegionCorrection> {
7392 if matched_keyframe_id == query_keyframe_id {
7393 return None;
7394 }
7395 let matched_pose = map
7396 .keyframes
7397 .get(&matched_keyframe_id)?
7398 .frame
7399 .pose
7400 .as_ref()?
7401 .clone();
7402 let query_pose = map
7403 .keyframes
7404 .get(&query_keyframe_id)?
7405 .frame
7406 .pose
7407 .as_ref()?
7408 .clone();
7409 let selection = select_covisibility_local_ba_window(map, query_keyframe_id, config).ok()?;
7410
7411 let desired_query_world_to_camera = matched_to_query.compose(&matched_pose.world_to_camera);
7412 let world_correction = desired_query_world_to_camera
7413 .inverse()
7414 .compose(&query_pose.world_to_camera);
7415 if !world_correction
7416 .translation
7417 .iter()
7418 .all(|value| value.is_finite())
7419 {
7420 return None;
7421 }
7422
7423 let mut corrected_keyframe_ids = selection.optimized_keyframe_ids.clone();
7424 corrected_keyframe_ids.extend(selection.fixed_keyframe_ids.iter().copied());
7425 corrected_keyframe_ids.retain(|id| *id != matched_keyframe_id);
7426 corrected_keyframe_ids.sort_unstable();
7427 corrected_keyframe_ids.dedup();
7428 if !corrected_keyframe_ids.contains(&query_keyframe_id) {
7429 return None;
7430 }
7431 let inverse_correction = world_correction.inverse();
7432 for id in &corrected_keyframe_ids {
7433 let pose = map.keyframes.get_mut(id)?.frame.pose.as_mut()?;
7434 pose.world_to_camera = pose.world_to_camera.compose(&inverse_correction);
7435 }
7436
7437 let rotation = world_correction.rotation.to_rotation_matrix().into_inner();
7438 for landmark_id in selection.landmark_ids {
7439 let landmark = map.landmarks.get_mut(&landmark_id)?;
7440 landmark.position = world_correction.transform_point(&landmark.position);
7441 if let Some(covariance) = map.landmark_position_covariances.get_mut(&landmark_id) {
7442 *covariance = rotation * *covariance * rotation.transpose();
7443 }
7444 }
7445 Some(LoopWeldingRegionCorrection {
7446 keyframe_ids: corrected_keyframe_ids,
7447 translation_meters: world_correction.translation.norm(),
7448 rotation_radians: world_correction.rotation.angle(),
7449 })
7450}
7451
7452#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
7453struct LoopObservationFusionStats {
7454 pairs_considered: usize,
7455 observations_inserted: usize,
7456 observations_reassigned: usize,
7457 pairs_skipped: usize,
7458 reprojection_rejected: usize,
7459}
7460
7461fn fuse_loop_observations(
7467 map: &mut VisualMap,
7468 camera: &Camera,
7469 query_keyframe_id: u64,
7470 pairs: &[(usize, u64)],
7471 max_reprojection_error_px: f64,
7472) -> LoopObservationFusionStats {
7473 let mut stats = LoopObservationFusionStats::default();
7474 for &(keypoint_index, loop_landmark_id) in pairs {
7475 stats.pairs_considered += 1;
7476 let Some(keyframe) = map.keyframes.get(&query_keyframe_id) else {
7477 stats.pairs_skipped += 1;
7478 continue;
7479 };
7480 let Some(&xy) = keyframe.frame.keypoints.get(keypoint_index) else {
7481 stats.pairs_skipped += 1;
7482 continue;
7483 };
7484 let Some(loop_landmark) = map.landmarks.get(&loop_landmark_id) else {
7485 stats.pairs_skipped += 1;
7486 continue;
7487 };
7488 let Some(query_pose) = keyframe.frame.pose.as_ref() else {
7489 stats.pairs_skipped += 1;
7490 continue;
7491 };
7492 let Some(predicted) =
7493 camera.project(&query_pose.transform_world_point(&loop_landmark.position))
7494 else {
7495 stats.pairs_skipped += 1;
7496 stats.reprojection_rejected += 1;
7497 continue;
7498 };
7499 if !max_reprojection_error_px.is_finite()
7500 || max_reprojection_error_px <= 0.0
7501 || (predicted - xy).norm() > max_reprojection_error_px
7502 {
7503 stats.pairs_skipped += 1;
7504 stats.reprojection_rejected += 1;
7505 continue;
7506 }
7507
7508 let existing = keyframe
7509 .observations
7510 .iter()
7511 .find(|observation| observation.keypoint_index == keypoint_index)
7512 .cloned();
7513 if existing
7514 .as_ref()
7515 .is_some_and(|observation| observation.landmark_id == loop_landmark_id)
7516 {
7517 continue;
7518 }
7519 if map.landmarks[&loop_landmark_id]
7523 .observations
7524 .iter()
7525 .any(|observation| {
7526 observation.frame_id == query_keyframe_id
7527 && observation.keypoint_index != keypoint_index
7528 })
7529 {
7530 stats.pairs_skipped += 1;
7531 continue;
7532 }
7533
7534 let observation = Observation {
7535 frame_id: query_keyframe_id,
7536 landmark_id: loop_landmark_id,
7537 keypoint_index,
7538 xy,
7539 };
7540 let keyframe = map
7541 .keyframes
7542 .get_mut(&query_keyframe_id)
7543 .expect("query keyframe existence checked above");
7544 keyframe
7545 .observations
7546 .retain(|candidate| candidate.keypoint_index != keypoint_index);
7547 keyframe.observations.push(observation.clone());
7548
7549 if let Some(previous) = existing {
7550 if previous.landmark_id != loop_landmark_id {
7551 map.remove_observation_confidence(&previous);
7555 if let Some(previous_landmark) = map.landmarks.get_mut(&previous.landmark_id) {
7556 previous_landmark.observations.retain(|candidate| {
7557 !(candidate.frame_id == query_keyframe_id
7558 && candidate.keypoint_index == keypoint_index)
7559 });
7560 }
7561 let loop_stereo_exists = map.stereo_observations.iter().any(|stereo| {
7562 stereo.frame_id == query_keyframe_id && stereo.landmark_id == loop_landmark_id
7563 });
7564 if loop_stereo_exists {
7565 map.stereo_observations.retain(|stereo| {
7566 !(stereo.frame_id == query_keyframe_id
7567 && stereo.landmark_id == previous.landmark_id)
7568 });
7569 } else if let Some(stereo) = map.stereo_observations.iter_mut().find(|stereo| {
7570 stereo.frame_id == query_keyframe_id
7571 && stereo.landmark_id == previous.landmark_id
7572 }) {
7573 stereo.landmark_id = loop_landmark_id;
7574 }
7575 stats.observations_reassigned += 1;
7576 }
7577 }
7578 let loop_landmark = map
7579 .landmarks
7580 .get_mut(&loop_landmark_id)
7581 .expect("loop landmark existence checked above");
7582 loop_landmark.observations.retain(|candidate| {
7583 !(candidate.frame_id == query_keyframe_id && candidate.keypoint_index == keypoint_index)
7584 });
7585 loop_landmark.observations.push(observation);
7586 stats.observations_inserted += 1;
7587 }
7588 stats
7589}
7590
7591fn keyframe_from_tracking_result(frame: &Frame, tracking: &TrackingResult) -> Keyframe {
7592 let mut frame = frame.clone();
7593 frame.pose = tracking.localization.pose.clone();
7594
7595 let observations = tracking
7596 .localization
7597 .inlier_query_indices
7598 .iter()
7599 .zip(tracking.localization.inlier_landmark_ids.iter())
7600 .filter_map(|(keypoint_index, landmark_id)| {
7601 frame.keypoints.get(*keypoint_index).map(|xy| Observation {
7602 frame_id: frame.id,
7603 landmark_id: *landmark_id,
7604 keypoint_index: *keypoint_index,
7605 xy: *xy,
7606 })
7607 })
7608 .collect();
7609
7610 Keyframe {
7611 frame,
7612 observations,
7613 }
7614}
7615
7616fn record_tracking_observation_confidences(
7621 map: &mut VisualMap,
7622 frame_id: u64,
7623 tracking: &TrackingResult,
7624) -> usize {
7625 let accepted = tracking
7626 .localization
7627 .inlier_query_indices
7628 .iter()
7629 .copied()
7630 .zip(tracking.localization.inlier_landmark_ids.iter().copied())
7631 .zip(tracking.localization.inlier_confidences.iter().copied())
7632 .filter_map(|((keypoint_index, landmark_id), confidence)| {
7633 confidence.map(|confidence| (keypoint_index, landmark_id, confidence))
7634 })
7635 .collect::<Vec<_>>();
7636
7637 let Some(keyframe) = map.keyframes.get(&frame_id) else {
7638 return 0;
7639 };
7640 let observations = keyframe.observations.clone();
7641 let mut recorded = 0usize;
7642 for (keypoint_index, landmark_id, confidence) in accepted {
7643 let Some(observation) = observations.iter().find(|observation| {
7644 observation.keypoint_index == keypoint_index && observation.landmark_id == landmark_id
7645 }) else {
7646 continue;
7647 };
7648 if map.set_observation_confidence(observation, confidence) {
7649 recorded += 1;
7650 }
7651 }
7652 recorded
7653}
7654
7655#[cfg(test)]
7656mod observation_confidence_transfer_tests {
7657 use super::*;
7658 use nalgebra::Point2;
7659 use visloc_core::types::{LocalizationResult, LocalizationSuccess};
7660 use visloc_localization::MapProviderStats;
7661 use visloc_tracking::{TrackingEvent, TrackingState};
7662
7663 #[test]
7664 fn accepted_keyframe_keeps_frontend_inlier_confidence() {
7665 let mut frame = Frame::new(7, 1);
7666 frame.keypoints.push(Point2::new(12.0, 34.0));
7667 let localization = LocalizationResult::success(LocalizationSuccess {
7668 pose: Pose::identity(),
7669 candidate_landmark_count: 1,
7670 match_count: 1,
7671 correspondence_count: 1,
7672 inliers: vec![0],
7673 inlier_query_indices: vec![0],
7674 inlier_landmark_ids: vec![42],
7675 inlier_confidences: vec![Some(0.3)],
7676 inlier_reprojection_errors: vec![0.0],
7677 mean_reprojection_error: 0.0,
7678 median_reprojection_error: 0.0,
7679 max_reprojection_error: 0.0,
7680 });
7681 let tracking = TrackingResult {
7682 frame_id: frame.id,
7683 state: TrackingState::Tracking,
7684 event: TrackingEvent::Tracked,
7685 successive_failures: 0,
7686 pose_prior: None,
7687 used_pose_prior: false,
7688 used_external_localization_prior: false,
7689 external_localization_prior_radius: None,
7690 tracking_failure_reason: None,
7691 map_landmark_count: 1,
7692 map_stats: MapProviderStats::default(),
7693 localization,
7694 covisibility_local_map_size: None,
7695 };
7696 let keyframe = keyframe_from_tracking_result(&frame, &tracking);
7697 let observation = keyframe.observations[0].clone();
7698 let mut map = VisualMap::new();
7699 map.keyframes.insert(frame.id, keyframe);
7700
7701 assert_eq!(
7702 record_tracking_observation_confidences(&mut map, frame.id, &tracking),
7703 1
7704 );
7705 assert_eq!(map.observation_confidence(&observation), Some(0.3));
7706 }
7707}