1use std::collections::{HashMap, HashSet};
35
36use nalgebra::{Matrix6, Point2, Point3, Vector6};
37use rayon::prelude::*;
38
39use visloc_core::geometry::{Pose, SE3};
40use visloc_core::types::Camera;
41use visloc_vision::features::FeatureSet;
42use visloc_vision::matching::{BruteForceMatcher, DescriptorMatch, Matcher};
43use visloc_vision::place_recognition::{cosine_similarity, vlad, Vocabulary};
44use visloc_vision::pnp::Correspondence2D3D;
45use visloc_vision::ransac::PnPRansac;
46use visloc_vision::stereo_vo::StereoFeature;
47use visloc_vision::two_view::TwoViewCorrespondence;
48
49use crate::gnc::{GncConfig, AUTO_SCALE_K};
50use crate::{
51 relative_world_to_camera, BaConfig, BaObservation, BaStereoObservation, BundleAdjustment,
52 EssentialMatrixLoopClosureVerifier, LinearSolver, LoopClosureConstraint,
53 LoopClosureVerificationFailureReason, PnPLoopClosureVerifier, PnPLoopClosureVerifierConfig,
54 PoseGraph, PoseGraphEdgeKind, PoseGraphError, PoseGraphGncResult, PoseGraphSe3Config,
55 RobustKernel,
56};
57
58#[derive(Debug, Clone)]
60pub struct VoLoopClosureConfig {
61 pub vocab_k: usize,
63 pub vocab_iterations: usize,
65 pub vocab_seed: u64,
67 pub vocab_descriptor_stride: usize,
71 pub vocab_max_pool: Option<usize>,
78 pub min_frame_gap: usize,
81 pub min_path_length: Option<f64>,
93 pub min_similarity: f32,
95 pub max_candidates_per_frame: usize,
98 pub max_verifications: Option<usize>,
104 pub match_ratio: Option<f32>,
106 pub verifier: PnPLoopClosureVerifierConfig,
108 pub ransac: PnPRansac,
110 pub pnp_essential_inlier_filter: bool,
116 pub pnp_confidence_weighted_sampling: bool,
120 pub se3: PoseGraphSe3Config,
122 pub gnc: GncConfig,
124 pub refine_loops_two_view: bool,
136 pub loop_edge_information: bool,
151}
152
153impl Default for VoLoopClosureConfig {
154 fn default() -> Self {
155 Self {
156 vocab_k: 64,
157 vocab_iterations: 10,
158 vocab_seed: 0xC0FFEE,
159 vocab_descriptor_stride: 4,
160 vocab_max_pool: Some(60_000),
161 min_frame_gap: 50,
162 min_path_length: Some(5.0),
163 min_similarity: 0.20,
164 max_candidates_per_frame: 3,
165 max_verifications: Some(400),
166 match_ratio: Some(0.8),
167 verifier: PnPLoopClosureVerifierConfig::default(),
168 ransac: PnPRansac::default(),
169 pnp_essential_inlier_filter: false,
170 pnp_confidence_weighted_sampling: false,
171 se3: PoseGraphSe3Config {
172 robust_kernel: RobustKernel::None,
173 linear_solver: LinearSolver::Sparse,
174 ..PoseGraphSe3Config::default()
175 },
176 gnc: GncConfig {
177 auto_scale: Some(AUTO_SCALE_K),
178 ..GncConfig::default()
179 },
180 refine_loops_two_view: false,
181 loop_edge_information: false,
182 }
183 }
184}
185
186#[derive(Debug, Clone, Copy, PartialEq)]
189pub struct LoopCandidatePair {
190 pub older: usize,
192 pub newer: usize,
194 pub similarity: f32,
196}
197
198#[derive(Debug, Clone, PartialEq)]
203pub struct LoopCandidateVerificationDiagnostic {
204 pub older: usize,
206 pub newer: usize,
208 pub similarity: f32,
210 pub attempted: bool,
212 pub match_count: usize,
214 pub match_source: String,
217 pub pnp_correspondence_count: usize,
220 pub pnp_unfiltered_correspondence_count: usize,
223 pub pnp_filter: String,
226 pub pnp_weighted_sampling: bool,
228 pub pnp_weight_policy: String,
232 pub pnp_weight_confidence_count: usize,
234 pub pnp_weight_confidence_spread: f32,
237 pub essential_correspondence_count: usize,
239 pub essential_verified: bool,
241 pub essential_failure_reason: Option<String>,
243 pub essential_inlier_count: usize,
245 pub essential_inlier_ratio: f64,
247 pub essential_mean_sampson_error: f64,
249 pub essential_score: f64,
251 pub essential_has_relative_pose: bool,
253 pub verified: bool,
255 pub failure_reason: Option<String>,
258 pub inlier_count: usize,
260 pub inlier_ratio: f64,
262 pub mean_sampson_error: f64,
265 pub mean_reprojection_error_px: Option<f64>,
267 pub score: f64,
269 pub has_relative_pose: bool,
271}
272
273impl LoopCandidateVerificationDiagnostic {
274 fn not_attempted(candidate: &LoopCandidatePair) -> Self {
275 Self {
276 older: candidate.older,
277 newer: candidate.newer,
278 similarity: candidate.similarity,
279 attempted: false,
280 match_count: 0,
281 match_source: "not_run".to_string(),
282 pnp_correspondence_count: 0,
283 pnp_unfiltered_correspondence_count: 0,
284 pnp_filter: "not_run".to_string(),
285 pnp_weighted_sampling: false,
286 pnp_weight_policy: "not_run".to_string(),
287 pnp_weight_confidence_count: 0,
288 pnp_weight_confidence_spread: 0.0,
289 essential_correspondence_count: 0,
290 essential_verified: false,
291 essential_failure_reason: Some("not_attempted".to_string()),
292 essential_inlier_count: 0,
293 essential_inlier_ratio: 0.0,
294 essential_mean_sampson_error: 0.0,
295 essential_score: 0.0,
296 essential_has_relative_pose: false,
297 verified: false,
298 failure_reason: Some("not_attempted".to_string()),
299 inlier_count: 0,
300 inlier_ratio: 0.0,
301 mean_sampson_error: 0.0,
302 mean_reprojection_error_px: None,
303 score: 0.0,
304 has_relative_pose: false,
305 }
306 }
307}
308
309#[derive(Debug, Clone)]
311pub struct VoLoopClosureResult {
312 pub refined_poses: Vec<Pose>,
315 pub loop_constraints: Vec<LoopClosureConstraint>,
317 pub candidate_pairs: Vec<LoopCandidatePair>,
321 pub verification_diagnostics: Vec<LoopCandidateVerificationDiagnostic>,
324 pub candidate_count: usize,
326 pub gnc: Option<PoseGraphGncResult>,
329}
330
331impl VoLoopClosureResult {
332 pub fn verified_count(&self) -> usize {
334 self.loop_constraints.len()
335 }
336}
337
338#[derive(Debug, Clone, PartialEq, Eq)]
340pub enum VoLoopClosureError {
341 InputLengthMismatch,
343 TooFewFrames(usize),
345 VocabularyBuildFailed,
347 PoseGraph(PoseGraphError),
349}
350
351impl std::fmt::Display for VoLoopClosureError {
352 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
353 match self {
354 Self::InputLengthMismatch => write!(
355 f,
356 "poses, left_features, and stereo_per_frame must have equal length"
357 ),
358 Self::TooFewFrames(n) => write!(f, "need at least 2 frames, got {n}"),
359 Self::VocabularyBuildFailed => write!(
360 f,
361 "VLAD vocabulary construction failed (too few or zero-dimension descriptors)"
362 ),
363 Self::PoseGraph(err) => write!(f, "pose-graph optimization failed: {err:?}"),
364 }
365 }
366}
367
368impl std::error::Error for VoLoopClosureError {}
369
370impl From<PoseGraphError> for VoLoopClosureError {
371 fn from(err: PoseGraphError) -> Self {
372 Self::PoseGraph(err)
373 }
374}
375
376fn compute_frame_globals(
379 left_features: &[FeatureSet],
380 config: &VoLoopClosureConfig,
381) -> Result<Vec<Vec<f32>>, VoLoopClosureError> {
382 let stride = config.vocab_descriptor_stride.max(1);
383 let mut pool: Vec<&[f32]> = Vec::new();
384 for features in left_features {
385 for descriptor in features.descriptors.iter().step_by(stride) {
386 pool.push(descriptor.as_slice());
387 }
388 }
389 if let Some(cap) = config.vocab_max_pool {
393 if cap > 0 && pool.len() > cap {
394 let step = pool.len() as f64 / cap as f64;
395 pool = (0..cap).map(|i| pool[(i as f64 * step) as usize]).collect();
396 }
397 }
398 let vocab = Vocabulary::build(
399 &pool,
400 config.vocab_k,
401 config.vocab_iterations,
402 config.vocab_seed,
403 )
404 .ok_or(VoLoopClosureError::VocabularyBuildFailed)?;
405
406 Ok(left_features
409 .par_iter()
410 .map(|features| vlad(&features.descriptors, &vocab))
411 .collect())
412}
413
414pub fn detect_loop_candidates(
423 globals: &[Vec<f32>],
424 min_frame_gap: usize,
425 min_similarity: f32,
426 max_candidates_per_frame: usize,
427) -> Vec<LoopCandidatePair> {
428 if min_frame_gap == 0 || max_candidates_per_frame == 0 {
429 return Vec::new();
430 }
431 (min_frame_gap..globals.len())
436 .into_par_iter()
437 .flat_map_iter(|newer| {
438 let last_older = newer - min_frame_gap;
439 let mut scored: Vec<(usize, f32)> = (0..=last_older)
440 .map(|older| (older, cosine_similarity(&globals[newer], &globals[older])))
441 .filter(|&(_, similarity)| similarity >= min_similarity)
442 .collect();
443 scored.sort_by(|a, b| {
444 b.1.partial_cmp(&a.1)
445 .unwrap_or(std::cmp::Ordering::Equal)
446 .then(a.0.cmp(&b.0))
447 });
448 scored
449 .into_iter()
450 .take(max_candidates_per_frame)
451 .map(move |(older, similarity)| LoopCandidatePair {
452 older,
453 newer,
454 similarity,
455 })
456 .collect::<Vec<_>>()
457 })
458 .collect()
459}
460
461#[derive(Debug, Clone, Copy)]
472struct LoopBaCorrespondence {
473 older_xy: Point2<f64>,
474 older_point_cam: Point3<f64>,
475 disparity: f64,
476 newer_xy: Point2<f64>,
477}
478
479#[derive(Debug, Clone)]
480struct PnpLoopCorrespondenceEntry {
481 two_view_index: usize,
482 correspondence: Correspondence2D3D,
483 ba_correspondence: LoopBaCorrespondence,
484}
485
486#[derive(Debug, Clone)]
487struct LoopCandidateVerificationOutcome {
488 diagnostic: LoopCandidateVerificationDiagnostic,
489 verified: Option<(LoopClosureConstraint, Vec<LoopBaCorrespondence>)>,
490}
491
492#[derive(Debug, Clone, PartialEq)]
493struct PnpWeightPolicy {
494 weights: Option<Vec<f32>>,
495 label: &'static str,
496 confidence_count: usize,
497 confidence_spread: f32,
498}
499
500fn select_pnp_confidence_weights(
501 requested: bool,
502 entries: &[PnpLoopCorrespondenceEntry],
503 min_confidence_count: usize,
504) -> PnpWeightPolicy {
505 if !requested {
506 return PnpWeightPolicy {
507 weights: None,
508 label: "disabled",
509 confidence_count: 0,
510 confidence_spread: 0.0,
511 };
512 }
513
514 let mut confidence_count = 0usize;
515 let mut min_confidence = f32::INFINITY;
516 let mut max_confidence = 0.0f32;
517 for entry in entries {
518 if let Some(confidence) = entry.correspondence.confidence {
519 if confidence.is_finite() && confidence > 0.0 {
520 confidence_count += 1;
521 min_confidence = min_confidence.min(confidence);
522 max_confidence = max_confidence.max(confidence);
523 }
524 }
525 }
526 if confidence_count == 0 {
527 return PnpWeightPolicy {
528 weights: None,
529 label: "missing_confidence",
530 confidence_count,
531 confidence_spread: 0.0,
532 };
533 }
534
535 let confidence_spread = if min_confidence.is_finite() && min_confidence > 0.0 {
536 max_confidence / min_confidence
537 } else {
538 0.0
539 };
540 let required = min_confidence_count.max(4);
541 if confidence_count < required {
542 return PnpWeightPolicy {
543 weights: None,
544 label: "insufficient_confidence",
545 confidence_count,
546 confidence_spread,
547 };
548 }
549 if confidence_spread < 1.05 {
554 return PnpWeightPolicy {
555 weights: None,
556 label: "low_confidence_spread",
557 confidence_count,
558 confidence_spread,
559 };
560 }
561
562 PnpWeightPolicy {
563 weights: Some(
564 entries
565 .iter()
566 .map(|entry| {
567 entry
568 .correspondence
569 .confidence
570 .filter(|value| value.is_finite() && *value > 0.0)
571 .unwrap_or(min_confidence)
572 })
573 .collect(),
574 ),
575 label: "enabled",
576 confidence_count,
577 confidence_spread,
578 }
579}
580
581#[derive(Debug, Clone)]
582struct EssentialLoopVerificationDiagnostic {
583 correspondence_count: usize,
584 verified: bool,
585 failure_reason: Option<LoopClosureVerificationFailureReason>,
586 inlier_count: usize,
587 inlier_ratio: f64,
588 mean_sampson_error: f64,
589 score: f64,
590 has_relative_pose: bool,
591 inliers: Vec<usize>,
592}
593
594fn verify_loop_candidate_essential(
595 verifier: &EssentialMatrixLoopClosureVerifier,
596 correspondences: &[TwoViewCorrespondence],
597 weights: Option<&[f32]>,
598 camera: &Camera,
599) -> EssentialLoopVerificationDiagnostic {
600 let correspondence_count = correspondences.len();
601 let minimum = verifier
602 .estimator
603 .ransac
604 .estimator
605 .min_correspondences
606 .max(verifier.config.min_inliers);
607 if correspondence_count < minimum {
608 return EssentialLoopVerificationDiagnostic {
609 correspondence_count,
610 verified: false,
611 failure_reason: Some(LoopClosureVerificationFailureReason::InsufficientCorrespondences),
612 inlier_count: 0,
613 inlier_ratio: 0.0,
614 mean_sampson_error: f64::INFINITY,
615 score: 0.0,
616 has_relative_pose: false,
617 inliers: Vec::new(),
618 };
619 }
620
621 let relative_pose = match weights {
622 Some(w) if w.len() == correspondences.len() => {
623 verifier.estimator.estimate_with_scale_and_weights(
624 correspondences,
625 camera,
626 verifier.config.default_translation_scale,
627 w,
628 )
629 }
630 _ => verifier.estimator.estimate_with_scale(
631 correspondences,
632 camera,
633 verifier.config.default_translation_scale,
634 ),
635 };
636 let Some(relative_pose) = relative_pose else {
637 return EssentialLoopVerificationDiagnostic {
638 correspondence_count,
639 verified: false,
640 failure_reason: Some(LoopClosureVerificationFailureReason::EssentialEstimationFailed),
641 inlier_count: 0,
642 inlier_ratio: 0.0,
643 mean_sampson_error: f64::INFINITY,
644 score: 0.0,
645 has_relative_pose: false,
646 inliers: Vec::new(),
647 };
648 };
649
650 let inlier_count = relative_pose.inliers.len();
651 let inlier_ratio = inlier_count as f64 / correspondence_count as f64;
652 let mean_sampson = relative_pose.mean_sampson_error;
653 let mut failure_reason = None;
654 if inlier_count < verifier.config.min_inliers {
655 failure_reason = Some(LoopClosureVerificationFailureReason::TooFewInliers);
656 } else if inlier_ratio < verifier.config.min_inlier_ratio {
657 failure_reason = Some(LoopClosureVerificationFailureReason::LowInlierRatio);
658 } else if mean_sampson > verifier.config.max_mean_sampson_error {
659 failure_reason = Some(LoopClosureVerificationFailureReason::HighSampsonError);
660 }
661 let inlier_volume = inlier_ratio * inlier_count as f64;
662 let denominator = mean_sampson.max(1.0e-6);
663 let score = if denominator.is_finite() {
664 inlier_volume / denominator
665 } else {
666 inlier_volume
667 };
668
669 EssentialLoopVerificationDiagnostic {
670 correspondence_count,
671 verified: failure_reason.is_none(),
672 failure_reason,
673 inlier_count,
674 inlier_ratio,
675 mean_sampson_error: mean_sampson,
676 score,
677 has_relative_pose: true,
678 inliers: relative_pose.inliers,
679 }
680}
681
682fn verification_failure_label(reason: LoopClosureVerificationFailureReason) -> String {
683 format!("{reason:?}")
684}
685
686#[allow(clippy::too_many_arguments)]
693fn verify_loop_candidate(
694 camera: &Camera,
695 poses: &[Pose],
696 left_features: &[FeatureSet],
697 stereo_per_frame: &[Vec<StereoFeature>],
698 candidate: &LoopCandidatePair,
699 matcher: &BruteForceMatcher,
700 verifier: &PnPLoopClosureVerifier,
701 essential_verifier: &EssentialMatrixLoopClosureVerifier,
702 pnp_essential_inlier_filter: bool,
703 pnp_confidence_weighted_sampling: bool,
704 external_matches: Option<&[DescriptorMatch]>,
705) -> LoopCandidateVerificationOutcome {
706 let older = candidate.older;
707 let newer = candidate.newer;
708 let older_pose = &poses[older];
709 let camera_to_world = older_pose.camera_to_world();
710
711 let mut stereo_by_index: HashMap<usize, (Point3<f64>, f64)> = HashMap::new();
716 for stereo in &stereo_per_frame[older] {
717 stereo_by_index.insert(stereo.left_index, (stereo.point_cam, stereo.disparity));
718 }
719
720 let owned_matches;
721 let (matches, match_source): (&[DescriptorMatch], &str) = match external_matches {
722 Some(matches) => (matches, "external"),
723 None => {
724 owned_matches = matcher.match_descriptors(
725 &left_features[newer].descriptors,
726 &left_features[older].descriptors,
727 );
728 (&owned_matches, "bruteforce")
729 }
730 };
731 let mut pnp_entries = Vec::with_capacity(matches.len());
732 let mut two_view_correspondences = Vec::with_capacity(matches.len());
733 let mut weights = Vec::with_capacity(matches.len());
734 let mut any_confidence = false;
735 for descriptor_match in matches {
736 let Some(&point2d) = left_features[newer]
737 .keypoints
738 .get(descriptor_match.query_index)
739 else {
740 continue;
741 };
742 let Some(&older_xy) = left_features[older]
743 .keypoints
744 .get(descriptor_match.train_index)
745 else {
746 continue;
747 };
748 let two_view_index = two_view_correspondences.len();
749 two_view_correspondences.push(TwoViewCorrespondence {
750 previous_xy: older_xy,
751 current_xy: point2d,
752 });
753 if let Some(confidence) = descriptor_match.confidence {
754 any_confidence = true;
755 weights.push(confidence);
756 } else {
757 weights.push(1.0);
758 }
759 let Some(&(point_cam, disparity)) = stereo_by_index.get(&descriptor_match.train_index)
760 else {
761 continue;
762 };
763 pnp_entries.push(PnpLoopCorrespondenceEntry {
764 two_view_index,
765 correspondence: Correspondence2D3D {
766 point2d,
767 point3d: camera_to_world.transform_point(&point_cam),
768 confidence: descriptor_match.confidence,
769 },
770 ba_correspondence: LoopBaCorrespondence {
771 older_xy,
772 older_point_cam: point_cam,
773 disparity,
774 newer_xy: point2d,
775 },
776 });
777 }
778
779 let weights_slice = if any_confidence {
780 Some(weights.as_slice())
781 } else {
782 None
783 };
784 let essential_verification = verify_loop_candidate_essential(
785 essential_verifier,
786 &two_view_correspondences,
787 weights_slice,
788 camera,
789 );
790 let pnp_unfiltered_correspondence_count = pnp_entries.len();
791 let (pnp_filter, filtered_entries): (&str, Vec<PnpLoopCorrespondenceEntry>) =
792 if pnp_essential_inlier_filter {
793 if essential_verification.verified {
794 let inlier_set: HashSet<usize> =
795 essential_verification.inliers.iter().copied().collect();
796 (
797 "essential_inliers",
798 pnp_entries
799 .iter()
800 .filter(|entry| inlier_set.contains(&entry.two_view_index))
801 .cloned()
802 .collect(),
803 )
804 } else {
805 ("essential_unverified", pnp_entries)
806 }
807 } else {
808 ("none", pnp_entries)
809 };
810 let correspondences: Vec<Correspondence2D3D> = filtered_entries
811 .iter()
812 .map(|entry| entry.correspondence.clone())
813 .collect();
814 let ba_correspondences: Vec<LoopBaCorrespondence> = filtered_entries
815 .iter()
816 .map(|entry| entry.ba_correspondence)
817 .collect();
818 let pnp_weight_policy = select_pnp_confidence_weights(
819 pnp_confidence_weighted_sampling,
820 &filtered_entries,
821 verifier.config.min_inliers,
822 );
823 let verification = verifier.verify_with_weights(
824 &correspondences,
825 older_pose,
826 camera,
827 pnp_weight_policy.weights.as_deref(),
828 );
829 let has_relative_pose = verification.relative_pose.is_some();
830 let mut diagnostic = LoopCandidateVerificationDiagnostic {
831 older,
832 newer,
833 similarity: candidate.similarity,
834 attempted: true,
835 match_count: matches.len(),
836 match_source: match_source.to_string(),
837 pnp_correspondence_count: correspondences.len(),
838 pnp_unfiltered_correspondence_count,
839 pnp_filter: pnp_filter.to_string(),
840 pnp_weighted_sampling: pnp_weight_policy.weights.is_some(),
841 pnp_weight_policy: pnp_weight_policy.label.to_string(),
842 pnp_weight_confidence_count: pnp_weight_policy.confidence_count,
843 pnp_weight_confidence_spread: pnp_weight_policy.confidence_spread,
844 essential_correspondence_count: essential_verification.correspondence_count,
845 essential_verified: essential_verification.verified,
846 essential_failure_reason: essential_verification
847 .failure_reason
848 .map(verification_failure_label),
849 essential_inlier_count: essential_verification.inlier_count,
850 essential_inlier_ratio: essential_verification.inlier_ratio,
851 essential_mean_sampson_error: essential_verification.mean_sampson_error,
852 essential_score: essential_verification.score,
853 essential_has_relative_pose: essential_verification.has_relative_pose,
854 verified: false,
855 failure_reason: verification.failure_reason.map(verification_failure_label),
856 inlier_count: verification.inlier_count,
857 inlier_ratio: verification.inlier_ratio,
858 mean_sampson_error: verification.mean_sampson_error,
859 mean_reprojection_error_px: verification.mean_reprojection_error_px,
860 score: verification.score,
861 has_relative_pose,
862 };
863 if !verification.verified {
864 return LoopCandidateVerificationOutcome {
865 diagnostic,
866 verified: None,
867 };
868 }
869 let Some(relative_pose) = verification.relative_pose.clone() else {
870 diagnostic.failure_reason = Some("missing_relative_pose".to_string());
871 return LoopCandidateVerificationOutcome {
872 diagnostic,
873 verified: None,
874 };
875 };
876 diagnostic.verified = true;
877 diagnostic.failure_reason = None;
878 LoopCandidateVerificationOutcome {
879 diagnostic,
880 verified: Some((
881 LoopClosureConstraint {
882 from_keyframe_id: older as u64,
883 to_keyframe_id: newer as u64,
884 relative_pose,
885 inlier_count: verification.inlier_count,
886 inlier_ratio: verification.inlier_ratio,
887 mean_sampson_error: verification.mean_sampson_error,
888 score: verification.score,
889 },
890 ba_correspondences,
891 )),
892 }
893}
894
895fn refine_loop_relative_two_view(
915 camera: &Camera,
916 relative_pose: &SE3,
917 correspondences: &[LoopBaCorrespondence],
918) -> Option<SE3> {
919 const MIN_CORRESPONDENCES: usize = 8;
920 const REPROJ_INLIER_PX: f64 = 4.0;
924 const MAX_TRANSLATION_DELTA_M: f64 = 2.0;
927 const MAX_ROTATION_DELTA_RAD: f64 = 0.30;
928
929 let (fx, _, _, _) = camera.intrinsics()?;
930
931 let mut ba = BundleAdjustment::new(camera.clone());
932 ba.add_pose(0, Pose::identity());
933 ba.fix_pose(0);
934 ba.add_pose(
935 1,
936 Pose {
937 world_to_camera: relative_pose.clone(),
938 },
939 );
940
941 let mut baseline: Option<f64> = None;
942 let mut used = 0usize;
943 for corr in correspondences {
944 if corr.disparity <= 0.0 || corr.older_point_cam.z <= 0.0 {
945 continue;
946 }
947 let newer_cam = relative_pose.transform_point(&corr.older_point_cam);
950 let Some(predicted) = camera.project(&newer_cam) else {
951 continue;
952 };
953 if (predicted - corr.newer_xy).norm() > REPROJ_INLIER_PX {
954 continue;
955 }
956 baseline.get_or_insert(corr.disparity * corr.older_point_cam.z / fx);
959
960 let id = used as u64;
961 ba.add_landmark(id, corr.older_point_cam);
962 ba.add_stereo_observation(BaStereoObservation {
963 keyframe_id: 0,
964 landmark_id: id,
965 xy: corr.older_xy,
966 u_right: corr.older_xy.x - corr.disparity,
967 });
968 ba.add_observation(BaObservation {
969 keyframe_id: 1,
970 landmark_id: id,
971 xy: corr.newer_xy,
972 });
973 used += 1;
974 }
975
976 if used < MIN_CORRESPONDENCES {
977 return None;
978 }
979 ba.set_stereo_baseline(baseline?);
980
981 let config = BaConfig {
982 max_iterations: 12,
983 robust_kernel: RobustKernel::Huber { delta: 3.0 },
984 linear_solver: LinearSolver::Dense,
985 ..BaConfig::default()
986 };
987 ba.optimize(&config).ok()?;
988
989 let refined = ba.poses.get(&1)?.world_to_camera.clone();
990
991 let delta = refined.compose(&relative_pose.inverse());
994 if delta.translation.norm() > MAX_TRANSLATION_DELTA_M
995 || delta.rotation.angle() > MAX_ROTATION_DELTA_RAD
996 {
997 return None;
998 }
999 Some(refined)
1000}
1001
1002fn loop_edge_information(
1023 camera: &Camera,
1024 relative_pose: &SE3,
1025 correspondences: &[LoopBaCorrespondence],
1026 inlier_count: usize,
1027) -> Option<Matrix6<f64>> {
1028 const REPROJ_INLIER_PX: f64 = 4.0;
1031 const EPS: f64 = 1e-4;
1032 const MIN_CORRESPONDENCES: usize = 8;
1033
1034 let mut h = Matrix6::<f64>::zeros();
1035 let mut used = 0usize;
1036 for corr in correspondences {
1037 if corr.disparity <= 0.0 || corr.older_point_cam.z <= 0.0 {
1038 continue;
1039 }
1040 let base_cam = relative_pose.transform_point(&corr.older_point_cam);
1041 let Some(predicted) = camera.project(&base_cam) else {
1042 continue;
1043 };
1044 if (predicted - corr.newer_xy).norm() > REPROJ_INLIER_PX {
1045 continue;
1046 }
1047 let mut jac = nalgebra::Matrix2x6::<f64>::zeros();
1049 let mut ok = true;
1050 for k in 0..6 {
1051 let mut xi = Vector6::zeros();
1052 xi[k] = EPS;
1053 let perturbed = relative_pose.compose(&SE3::exp(&xi));
1054 let Some(proj) = camera.project(&perturbed.transform_point(&corr.older_point_cam))
1055 else {
1056 ok = false;
1057 break;
1058 };
1059 jac[(0, k)] = (proj.x - predicted.x) / EPS;
1060 jac[(1, k)] = (proj.y - predicted.y) / EPS;
1061 }
1062 if !ok {
1063 continue;
1064 }
1065 h += jac.transpose() * jac;
1066 used += 1;
1067 }
1068
1069 if used < MIN_CORRESPONDENCES {
1070 return None;
1071 }
1072 let trace = h.diagonal().sum();
1073 if !trace.is_finite() || trace <= 0.0 {
1074 return None;
1075 }
1076 let weight = (inlier_count as f64).max(1.0);
1079 let mut omega = h * (6.0 * weight / trace);
1080 let ridge = 1e-3 * weight;
1082 for d in 0..6 {
1083 omega[(d, d)] += ridge;
1084 }
1085 Some(omega)
1086}
1087
1088fn cumulative_path_length(poses: &[Pose]) -> Vec<f64> {
1092 let mut cum = vec![0.0; poses.len()];
1093 for i in 1..poses.len() {
1094 let step = (poses[i].camera_center_world().coords
1095 - poses[i - 1].camera_center_world().coords)
1096 .norm();
1097 cum[i] = cum[i - 1] + step;
1098 }
1099 cum
1100}
1101
1102pub fn close_loops_on_vo_trajectory(
1110 camera: &Camera,
1111 poses: &[Pose],
1112 left_features: &[FeatureSet],
1113 stereo_per_frame: &[Vec<StereoFeature>],
1114 config: &VoLoopClosureConfig,
1115) -> Result<VoLoopClosureResult, VoLoopClosureError> {
1116 let globals = compute_frame_globals(left_features, config)?;
1117 close_loops_on_vo_trajectory_with_globals(
1118 camera,
1119 poses,
1120 left_features,
1121 stereo_per_frame,
1122 &globals,
1123 config,
1124 )
1125}
1126
1127pub fn close_loops_on_vo_trajectory_with_loop_matches(
1133 camera: &Camera,
1134 poses: &[Pose],
1135 left_features: &[FeatureSet],
1136 stereo_per_frame: &[Vec<StereoFeature>],
1137 loop_matches: &HashMap<(usize, usize), Vec<DescriptorMatch>>,
1138 config: &VoLoopClosureConfig,
1139) -> Result<VoLoopClosureResult, VoLoopClosureError> {
1140 let globals = compute_frame_globals(left_features, config)?;
1141 close_loops_on_vo_trajectory_with_globals_impl(
1142 camera,
1143 poses,
1144 left_features,
1145 stereo_per_frame,
1146 &globals,
1147 Some(loop_matches),
1148 config,
1149 )
1150}
1151
1152pub fn close_loops_on_vo_trajectory_with_globals(
1171 camera: &Camera,
1172 poses: &[Pose],
1173 left_features: &[FeatureSet],
1174 stereo_per_frame: &[Vec<StereoFeature>],
1175 globals: &[Vec<f32>],
1176 config: &VoLoopClosureConfig,
1177) -> Result<VoLoopClosureResult, VoLoopClosureError> {
1178 close_loops_on_vo_trajectory_with_globals_impl(
1179 camera,
1180 poses,
1181 left_features,
1182 stereo_per_frame,
1183 globals,
1184 None,
1185 config,
1186 )
1187}
1188
1189pub fn close_loops_on_vo_trajectory_with_globals_and_loop_matches(
1195 camera: &Camera,
1196 poses: &[Pose],
1197 left_features: &[FeatureSet],
1198 stereo_per_frame: &[Vec<StereoFeature>],
1199 globals: &[Vec<f32>],
1200 loop_matches: &HashMap<(usize, usize), Vec<DescriptorMatch>>,
1201 config: &VoLoopClosureConfig,
1202) -> Result<VoLoopClosureResult, VoLoopClosureError> {
1203 close_loops_on_vo_trajectory_with_globals_impl(
1204 camera,
1205 poses,
1206 left_features,
1207 stereo_per_frame,
1208 globals,
1209 Some(loop_matches),
1210 config,
1211 )
1212}
1213
1214fn close_loops_on_vo_trajectory_with_globals_impl(
1215 camera: &Camera,
1216 poses: &[Pose],
1217 left_features: &[FeatureSet],
1218 stereo_per_frame: &[Vec<StereoFeature>],
1219 globals: &[Vec<f32>],
1220 loop_matches: Option<&HashMap<(usize, usize), Vec<DescriptorMatch>>>,
1221 config: &VoLoopClosureConfig,
1222) -> Result<VoLoopClosureResult, VoLoopClosureError> {
1223 let n = poses.len();
1224 if left_features.len() != n || stereo_per_frame.len() != n || globals.len() != n {
1225 return Err(VoLoopClosureError::InputLengthMismatch);
1226 }
1227 if n < 2 {
1228 return Err(VoLoopClosureError::TooFewFrames(n));
1229 }
1230
1231 let mut candidates = detect_loop_candidates(
1232 globals,
1233 config.min_frame_gap,
1234 config.min_similarity,
1235 config.max_candidates_per_frame,
1236 );
1237
1238 if let Some(min_path) = config.min_path_length {
1242 if min_path > 0.0 {
1243 let cum = cumulative_path_length(poses);
1244 candidates.retain(|c| cum[c.newer] - cum[c.older] >= min_path);
1245 }
1246 }
1247
1248 let matcher = BruteForceMatcher {
1249 ratio: config.match_ratio,
1250 };
1251 let verifier = PnPLoopClosureVerifier::new(config.ransac, config.verifier);
1252 let essential_verifier = EssentialMatrixLoopClosureVerifier::default();
1253
1254 let mut to_verify: Vec<&LoopCandidatePair> = candidates.iter().collect();
1257 to_verify.sort_by(|a, b| {
1258 b.similarity
1259 .partial_cmp(&a.similarity)
1260 .unwrap_or(std::cmp::Ordering::Equal)
1261 });
1262 if let Some(cap) = config.max_verifications {
1263 to_verify.truncate(cap);
1264 }
1265
1266 let outcomes: Vec<LoopCandidateVerificationOutcome> = to_verify
1272 .par_iter()
1273 .map(|candidate| {
1274 verify_loop_candidate(
1275 camera,
1276 poses,
1277 left_features,
1278 stereo_per_frame,
1279 candidate,
1280 &matcher,
1281 &verifier,
1282 &essential_verifier,
1283 config.pnp_essential_inlier_filter,
1284 config.pnp_confidence_weighted_sampling,
1285 loop_matches
1286 .and_then(|matches| matches.get(&(candidate.older, candidate.newer)))
1287 .map(Vec::as_slice),
1288 )
1289 })
1290 .collect();
1291 let mut verified: Vec<(LoopClosureConstraint, Vec<LoopBaCorrespondence>)> = Vec::new();
1292 let mut diagnostics_by_pair: HashMap<(usize, usize), LoopCandidateVerificationDiagnostic> =
1293 HashMap::with_capacity(outcomes.len());
1294 for outcome in outcomes {
1295 let diagnostic = outcome.diagnostic;
1296 if let Some(verified_loop) = outcome.verified {
1297 verified.push(verified_loop);
1298 }
1299 diagnostics_by_pair.insert((diagnostic.older, diagnostic.newer), diagnostic);
1300 }
1301 let verification_diagnostics: Vec<LoopCandidateVerificationDiagnostic> = candidates
1302 .iter()
1303 .map(|candidate| {
1304 diagnostics_by_pair
1305 .remove(&(candidate.older, candidate.newer))
1306 .unwrap_or_else(|| LoopCandidateVerificationDiagnostic::not_attempted(candidate))
1307 })
1308 .collect();
1309
1310 let refined: Vec<(LoopClosureConstraint, Option<Matrix6<f64>>)> = verified
1317 .par_iter()
1318 .map(|(constraint, corrs)| {
1319 let mut constraint = constraint.clone();
1320 if config.refine_loops_two_view {
1321 if let Some(refined) =
1322 refine_loop_relative_two_view(camera, &constraint.relative_pose, corrs)
1323 {
1324 constraint.relative_pose = refined;
1325 }
1326 }
1327 let information = if config.loop_edge_information {
1328 loop_edge_information(
1329 camera,
1330 &constraint.relative_pose,
1331 corrs,
1332 constraint.inlier_count,
1333 )
1334 } else {
1335 None
1336 };
1337 (constraint, information)
1338 })
1339 .collect();
1340
1341 let loop_constraints: Vec<LoopClosureConstraint> =
1342 refined.iter().map(|(c, _)| c.clone()).collect();
1343
1344 if loop_constraints.is_empty() {
1345 return Ok(VoLoopClosureResult {
1346 refined_poses: poses.to_vec(),
1347 loop_constraints,
1348 candidate_pairs: candidates.clone(),
1349 verification_diagnostics,
1350 candidate_count: candidates.len(),
1351 gnc: None,
1352 });
1353 }
1354
1355 let mut graph = PoseGraph::new();
1356 for (index, pose) in poses.iter().enumerate() {
1357 graph.add_pose(index as u64, pose.clone());
1358 }
1359 graph.anchor(0);
1360 for index in 0..n - 1 {
1361 graph.add_sequential_edge(
1362 index as u64,
1363 (index + 1) as u64,
1364 relative_world_to_camera(&poses[index], &poses[index + 1]),
1365 );
1366 }
1367 for (constraint, information) in &refined {
1368 match information {
1369 Some(omega) => graph.add_edge_with_information(
1370 constraint.from_keyframe_id,
1371 constraint.to_keyframe_id,
1372 constraint.relative_pose.clone(),
1373 PoseGraphEdgeKind::LoopClosure,
1374 *omega,
1375 ),
1376 None => graph.add_loop_closure_constraint(constraint),
1377 }
1378 }
1379
1380 let gnc = graph.optimize_se3_gnc(&config.se3, &config.gnc)?;
1381
1382 let refined_poses = (0..n)
1383 .map(|index| {
1384 graph
1385 .poses
1386 .get(&(index as u64))
1387 .cloned()
1388 .unwrap_or_else(|| poses[index].clone())
1389 })
1390 .collect();
1391
1392 Ok(VoLoopClosureResult {
1393 refined_poses,
1394 loop_constraints,
1395 candidate_pairs: candidates.clone(),
1396 verification_diagnostics,
1397 candidate_count: candidates.len(),
1398 gnc: Some(gnc),
1399 })
1400}
1401
1402#[cfg(test)]
1403mod tests {
1404 use super::*;
1405 use nalgebra::{Point2, UnitQuaternion, Vector3};
1406 use visloc_core::geometry::SE3;
1407
1408 fn camera() -> Camera {
1409 Camera::pinhole(0, 1280, 480, 600.0, 600.0, 640.0, 240.0)
1410 }
1411
1412 fn pnp_entry(confidence: Option<f32>) -> PnpLoopCorrespondenceEntry {
1413 let xy = Point2::new(10.0, 20.0);
1414 let point = Point3::new(0.1, 0.2, 3.0);
1415 PnpLoopCorrespondenceEntry {
1416 two_view_index: 0,
1417 correspondence: Correspondence2D3D {
1418 point2d: xy,
1419 point3d: point,
1420 confidence,
1421 },
1422 ba_correspondence: LoopBaCorrespondence {
1423 older_xy: xy,
1424 older_point_cam: point,
1425 disparity: 10.0,
1426 newer_xy: xy,
1427 },
1428 }
1429 }
1430
1431 #[test]
1432 fn pnp_confidence_weight_policy_uses_weights_only_with_real_signal() {
1433 let strong = [0.2, 0.9, 0.4, 0.8, 0.3, 0.7, 0.5, 0.6]
1434 .into_iter()
1435 .map(|confidence| pnp_entry(Some(confidence)))
1436 .collect::<Vec<_>>();
1437 let policy = select_pnp_confidence_weights(true, &strong, 8);
1438 assert_eq!(policy.label, "enabled");
1439 assert_eq!(policy.confidence_count, 8);
1440 assert!(policy.confidence_spread > 4.0);
1441 assert_eq!(policy.weights.as_ref().map(Vec::len), Some(strong.len()));
1442
1443 let uniform = vec![pnp_entry(Some(0.5)); 8];
1444 let policy = select_pnp_confidence_weights(true, &uniform, 8);
1445 assert_eq!(policy.label, "low_confidence_spread");
1446 assert!(policy.weights.is_none());
1447
1448 let missing = vec![pnp_entry(None); 8];
1449 let policy = select_pnp_confidence_weights(true, &missing, 8);
1450 assert_eq!(policy.label, "missing_confidence");
1451 assert!(policy.weights.is_none());
1452
1453 let insufficient = vec![
1454 pnp_entry(Some(0.1)),
1455 pnp_entry(Some(0.9)),
1456 pnp_entry(Some(0.4)),
1457 ];
1458 let policy = select_pnp_confidence_weights(true, &insufficient, 8);
1459 assert_eq!(policy.label, "insufficient_confidence");
1460 assert_eq!(policy.confidence_count, 3);
1461 assert!(policy.weights.is_none());
1462
1463 let disabled = select_pnp_confidence_weights(false, &strong, 8);
1464 assert_eq!(disabled.label, "disabled");
1465 assert!(disabled.weights.is_none());
1466 }
1467
1468 fn descriptor_for(id: usize, dim: usize) -> Vec<f32> {
1474 let mut d = vec![0.0f32; dim];
1475 let phase = id as f32 * 0.618_034;
1476 for (j, slot) in d.iter_mut().enumerate() {
1477 *slot = ((phase + j as f32 * 0.27).sin() * 0.5 + 0.5)
1478 + ((id * 13 + j * 7) % 5) as f32 * 0.05;
1479 }
1480 let norm: f32 = d.iter().map(|x| x * x).sum::<f32>().sqrt();
1481 if norm > 0.0 {
1482 for slot in d.iter_mut() {
1483 *slot /= norm;
1484 }
1485 }
1486 d
1487 }
1488
1489 fn observe(
1493 camera: &Camera,
1494 true_pose: &Pose,
1495 landmarks: &[(usize, Point3<f64>)],
1496 desc_dim: usize,
1497 ) -> (FeatureSet, Vec<StereoFeature>) {
1498 let mut keypoints = Vec::new();
1499 let mut descriptors = Vec::new();
1500 let mut stereo = Vec::new();
1501 for (id, world) in landmarks {
1502 let point_cam = true_pose.transform_world_point(world);
1503 if point_cam.z <= 0.5 {
1504 continue;
1505 }
1506 let Some(pixel) = camera.project(&point_cam) else {
1507 continue;
1508 };
1509 if pixel.x < 0.0
1510 || pixel.x >= camera.width as f64
1511 || pixel.y < 0.0
1512 || pixel.y >= camera.height as f64
1513 {
1514 continue;
1515 }
1516 let index = keypoints.len();
1517 keypoints.push(Point2::new(pixel.x, pixel.y));
1518 descriptors.push(descriptor_for(*id, desc_dim));
1519 stereo.push(StereoFeature {
1520 left_index: index,
1521 right_index: index,
1522 disparity: 600.0 * 0.5 / point_cam.z,
1523 point_cam,
1524 });
1525 }
1526 (FeatureSet::new(keypoints, descriptors).unwrap(), stereo)
1527 }
1528
1529 fn pose_at(translation: Vector3<f64>, yaw: f64) -> Pose {
1530 let rotation = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), yaw);
1533 let world_to_camera_rot = rotation.inverse();
1534 let translation = world_to_camera_rot * (-translation);
1535 Pose::from_world_to_camera(world_to_camera_rot, translation)
1536 }
1537
1538 fn ate_rmse(estimate: &[Pose], truth: &[Pose]) -> f64 {
1539 let sum: f64 = estimate
1540 .iter()
1541 .zip(truth)
1542 .map(|(e, t)| {
1543 (e.camera_center_world().coords - t.camera_center_world().coords).norm_squared()
1544 })
1545 .sum();
1546 (sum / estimate.len() as f64).sqrt()
1547 }
1548
1549 #[test]
1550 fn closes_a_synthetic_square_loop() {
1551 let camera = camera();
1552 let desc_dim = 16;
1553
1554 let n = 41;
1558 let mut centers = Vec::with_capacity(n);
1559 let mut angles = Vec::with_capacity(n);
1560 for i in 0..n {
1561 let t = i as f64 / (n - 1) as f64; let angle = t * std::f64::consts::TAU;
1563 let radius = 6.0;
1564 centers.push(Vector3::new(
1565 radius * angle.sin(),
1566 0.0,
1567 radius * (1.0 - angle.cos()),
1568 ));
1569 angles.push(angle);
1570 }
1571 let true_poses: Vec<Pose> = centers
1572 .iter()
1573 .zip(&angles)
1574 .map(|(c, &a)| pose_at(*c, a))
1575 .collect();
1576
1577 let mut landmarks = Vec::new();
1580 for k in 0..160 {
1581 let a = k as f64 / 160.0 * std::f64::consts::TAU;
1582 let r = 9.0;
1583 landmarks.push((
1584 k,
1585 Point3::new(
1586 r * a.sin(),
1587 (k % 5) as f64 * 0.3 - 0.6,
1588 r * (1.0 - a.cos()) + 3.0,
1589 ),
1590 ));
1591 }
1592
1593 let mut left_features = Vec::with_capacity(n);
1594 let mut stereo_per_frame = Vec::with_capacity(n);
1595 for true_pose in &true_poses {
1596 let (features, stereo) = observe(&camera, true_pose, &landmarks, desc_dim);
1597 left_features.push(features);
1598 stereo_per_frame.push(stereo);
1599 }
1600
1601 let mut vo_poses = Vec::with_capacity(n);
1607 vo_poses.push(true_poses[0].clone());
1608 let delta = SE3 {
1609 rotation: UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.012),
1610 translation: Vector3::new(0.0, 0.0, 0.03),
1611 };
1612 for i in 1..n {
1613 let true_rel = relative_world_to_camera(&true_poses[i - 1], &true_poses[i]);
1614 let drifted_rel = delta.compose(&true_rel);
1615 let prev = vo_poses[i - 1].world_to_camera.clone();
1616 vo_poses.push(Pose {
1617 world_to_camera: drifted_rel.compose(&prev),
1618 });
1619 }
1620
1621 let config = VoLoopClosureConfig {
1622 min_frame_gap: 20,
1623 min_similarity: 0.1,
1624 max_candidates_per_frame: 5,
1625 vocab_k: 24,
1626 vocab_descriptor_stride: 1,
1627 ..VoLoopClosureConfig::default()
1628 };
1629
1630 let result = close_loops_on_vo_trajectory(
1631 &camera,
1632 &vo_poses,
1633 &left_features,
1634 &stereo_per_frame,
1635 &config,
1636 )
1637 .expect("loop closure runs");
1638
1639 assert!(
1640 result.verified_count() >= 1,
1641 "expected at least one verified loop, got {} (candidates {})",
1642 result.verified_count(),
1643 result.candidate_count
1644 );
1645 assert_eq!(result.candidate_pairs.len(), result.candidate_count);
1646 assert_eq!(
1647 result.verification_diagnostics.len(),
1648 result.candidate_count
1649 );
1650 assert_eq!(
1651 result
1652 .verification_diagnostics
1653 .iter()
1654 .filter(|diagnostic| diagnostic.verified)
1655 .count(),
1656 result.verified_count()
1657 );
1658
1659 let before = ate_rmse(&vo_poses, &true_poses);
1660 let after = ate_rmse(&result.refined_poses, &true_poses);
1661 assert!(
1662 after < before,
1663 "PGO should reduce ATE: before {before:.3} m, after {after:.3} m"
1664 );
1665 }
1666
1667 #[test]
1668 fn no_loop_returns_input_unchanged() {
1669 let camera = camera();
1670 let desc_dim = 16;
1671 let n = 10;
1672 let mut poses = Vec::new();
1673 let mut left_features = Vec::new();
1674 let mut stereo_per_frame = Vec::new();
1675 let landmarks: Vec<(usize, Point3<f64>)> = (0..40)
1676 .map(|k| {
1677 (
1678 k,
1679 Point3::new((k % 7) as f64 - 3.0, (k % 3) as f64 - 1.0, 8.0),
1680 )
1681 })
1682 .collect();
1683 for i in 0..n {
1684 let pose = pose_at(Vector3::new(0.0, 0.0, i as f64 * 2.0), 0.0);
1685 let (features, stereo) = observe(&camera, &pose, &landmarks, desc_dim);
1686 poses.push(pose);
1687 left_features.push(features);
1688 stereo_per_frame.push(stereo);
1689 }
1690 let config = VoLoopClosureConfig {
1692 min_frame_gap: 8,
1693 min_similarity: 0.99,
1694 vocab_k: 12,
1695 vocab_descriptor_stride: 1,
1696 ..VoLoopClosureConfig::default()
1697 };
1698 let result = close_loops_on_vo_trajectory(
1699 &camera,
1700 &poses,
1701 &left_features,
1702 &stereo_per_frame,
1703 &config,
1704 )
1705 .expect("runs");
1706 assert_eq!(result.verified_count(), 0);
1707 assert!(result.gnc.is_none());
1708 assert_eq!(result.refined_poses.len(), n);
1709 assert_eq!(result.candidate_pairs.len(), result.candidate_count);
1710 assert_eq!(
1711 result.verification_diagnostics.len(),
1712 result.candidate_count
1713 );
1714 assert!(result
1715 .verification_diagnostics
1716 .iter()
1717 .all(|diagnostic| !diagnostic.verified));
1718 }
1719
1720 #[test]
1727 fn two_view_refinement_corrects_noisy_depth_loop_edge() {
1728 let camera = camera();
1729 let (fx, _, _, _) = camera.intrinsics().unwrap();
1730 let baseline = 0.5;
1731
1732 let r_true = SE3 {
1734 rotation: UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.05),
1735 translation: Vector3::new(0.4, 0.0, 0.3),
1736 };
1737
1738 let mut corrs = Vec::new();
1743 for k in 0..60usize {
1744 let gx = ((k % 7) as f64 - 3.0) * 0.8;
1745 let gy = ((k % 5) as f64 - 2.0) * 0.6;
1746 let gz = 4.0 + (k % 11) as f64 * 0.5;
1747 let true_point = Point3::new(gx, gy, gz);
1748
1749 let Some(older_xy) = camera.project(&true_point) else {
1750 continue;
1751 };
1752 let newer_cam = r_true.transform_point(&true_point);
1753 let Some(newer_xy) = camera.project(&newer_cam) else {
1754 continue;
1755 };
1756 if older_xy.x < 0.0
1757 || older_xy.x >= camera.width as f64
1758 || newer_xy.x < 0.0
1759 || newer_xy.x >= camera.width as f64
1760 {
1761 continue;
1762 }
1763
1764 let noise = ((k as f64 * 0.61803398).fract() - 0.5) * 0.24;
1769 let noisy_point = true_point * (1.0 + noise);
1770 let disparity = fx * baseline / noisy_point.z;
1771
1772 corrs.push(LoopBaCorrespondence {
1773 older_xy,
1774 older_point_cam: noisy_point,
1775 disparity,
1776 newer_xy,
1777 });
1778 }
1779 assert!(corrs.len() >= 8, "need enough correspondences for the BA");
1780
1781 let r_seed = SE3 {
1785 rotation: r_true.rotation * UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.02),
1786 translation: r_true.translation + Vector3::new(0.04, 0.02, -0.03),
1787 };
1788 let mut pnp_ba = BundleAdjustment::new(camera.clone());
1789 pnp_ba.add_pose(0, Pose::identity());
1790 pnp_ba.fix_pose(0);
1791 pnp_ba.add_pose(
1792 1,
1793 Pose {
1794 world_to_camera: r_seed,
1795 },
1796 );
1797 for (id, corr) in corrs.iter().enumerate() {
1798 pnp_ba.add_landmark(id as u64, corr.older_point_cam);
1799 pnp_ba.fix_landmark(id as u64);
1800 pnp_ba.add_observation(BaObservation {
1801 keyframe_id: 1,
1802 landmark_id: id as u64,
1803 xy: corr.newer_xy,
1804 });
1805 }
1806 pnp_ba
1807 .optimize(&BaConfig {
1808 max_iterations: 20,
1809 ..BaConfig::default()
1810 })
1811 .expect("PnP-analog BA converges");
1812 let r_pnp = pnp_ba.poses.get(&1).unwrap().world_to_camera.clone();
1813
1814 let edge_error = |edge: &SE3| -> f64 {
1815 let d = edge.compose(&r_true.inverse());
1816 d.translation.norm() + d.rotation.angle()
1817 };
1818
1819 let refined = refine_loop_relative_two_view(&camera, &r_pnp, &corrs)
1820 .expect("two-view refinement succeeds");
1821
1822 let before = edge_error(&r_pnp);
1823 let after = edge_error(&refined);
1824 assert!(
1825 after < before,
1826 "two-view BA should pull the loop edge toward truth: PnP {before:.4}, BA {after:.4}"
1827 );
1828 }
1829
1830 #[test]
1833 fn two_view_refinement_keeps_a_clean_loop_edge() {
1834 let camera = camera();
1835 let (fx, _, _, _) = camera.intrinsics().unwrap();
1836 let baseline = 0.5;
1837 let r_true = SE3 {
1838 rotation: UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.03),
1839 translation: Vector3::new(0.3, 0.0, 0.2),
1840 };
1841 let mut corrs = Vec::new();
1842 for k in 0..60usize {
1843 let true_point = Point3::new(
1844 ((k % 7) as f64 - 3.0) * 0.8,
1845 ((k % 5) as f64 - 2.0) * 0.6,
1846 4.0 + (k % 11) as f64 * 0.5,
1847 );
1848 let (Some(older_xy), newer) = (
1849 camera.project(&true_point),
1850 camera.project(&r_true.transform_point(&true_point)),
1851 ) else {
1852 continue;
1853 };
1854 let Some(newer_xy) = newer else { continue };
1855 corrs.push(LoopBaCorrespondence {
1856 older_xy,
1857 older_point_cam: true_point,
1858 disparity: fx * baseline / true_point.z,
1859 newer_xy,
1860 });
1861 }
1862 let refined =
1863 refine_loop_relative_two_view(&camera, &r_true, &corrs).expect("refinement succeeds");
1864 let d = refined.compose(&r_true.inverse());
1865 assert!(
1866 d.translation.norm() < 0.02 && d.rotation.angle() < 0.01,
1867 "clean edge should stay put: dt {:.4} dr {:.4}",
1868 d.translation.norm(),
1869 d.rotation.angle()
1870 );
1871 }
1872
1873 #[test]
1879 fn loop_edge_information_is_spd_calibrated_and_anisotropic() {
1880 let camera = camera();
1881 let (fx, _, _, _) = camera.intrinsics().unwrap();
1882 let baseline = 0.5;
1883 let r_true = SE3 {
1884 rotation: UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.05),
1885 translation: Vector3::new(0.4, 0.0, 0.3),
1886 };
1887
1888 let mut corrs = Vec::new();
1889 for k in 0..60usize {
1890 let gx = ((k % 7) as f64 - 3.0) * 0.8;
1891 let gy = ((k % 5) as f64 - 2.0) * 0.6;
1892 let gz = 4.0 + (k % 11) as f64 * 0.5;
1893 let point = Point3::new(gx, gy, gz);
1894 let (Some(older_xy), newer) = (
1895 camera.project(&point),
1896 camera.project(&r_true.transform_point(&point)),
1897 ) else {
1898 continue;
1899 };
1900 let Some(newer_xy) = newer else { continue };
1901 if older_xy.x < 0.0
1902 || older_xy.x >= camera.width as f64
1903 || newer_xy.x < 0.0
1904 || newer_xy.x >= camera.width as f64
1905 {
1906 continue;
1907 }
1908 corrs.push(LoopBaCorrespondence {
1909 older_xy,
1910 older_point_cam: point,
1911 disparity: fx * baseline / point.z,
1912 newer_xy,
1913 });
1914 }
1915 assert!(corrs.len() >= 8, "need enough correspondences");
1916
1917 let inlier_count = 137usize;
1918 let omega = loop_edge_information(&camera, &r_true, &corrs, inlier_count)
1919 .expect("information matrix");
1920
1921 let asym = (omega - omega.transpose()).amax();
1923 assert!(asym < 1e-9, "Omega must be symmetric, got asymmetry {asym}");
1924
1925 let trace = omega.diagonal().sum();
1927 let target = 6.0 * inlier_count as f64;
1928 assert!(
1929 (trace - target).abs() < 0.01 * target,
1930 "trace {trace} should match 6·inlier_count {target}"
1931 );
1932
1933 let eigenvalues = omega.symmetric_eigenvalues();
1935 let min_eig = eigenvalues.min();
1936 let max_eig = eigenvalues.max();
1937 assert!(min_eig > 0.0, "Omega must be SPD, min eigenvalue {min_eig}");
1938 assert!(
1939 max_eig / min_eig > 1.5,
1940 "expected anisotropy, eigenvalue ratio {}",
1941 max_eig / min_eig
1942 );
1943 }
1944}