1use super::*;
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct LoopClosureConfig {
8 pub enabled: bool,
9 pub min_frame_id_gap: u64,
10 pub min_shared_landmarks: usize,
11 pub min_shared_landmark_ratio_percent: u8,
12 pub max_candidates: usize,
13}
14
15impl Default for LoopClosureConfig {
16 fn default() -> Self {
17 Self {
18 enabled: true,
19 min_frame_id_gap: 5,
20 min_shared_landmarks: 12,
21 min_shared_landmark_ratio_percent: 40,
22 max_candidates: 5,
23 }
24 }
25}
26
27#[derive(Debug, Clone, PartialEq)]
28pub struct LoopClosureCandidate {
29 pub query_frame_id: u64,
30 pub matched_keyframe_id: u64,
31 pub shared_landmark_count: usize,
32 pub query_inlier_count: usize,
33 pub keyframe_observation_count: usize,
34 pub shared_landmark_ratio: f64,
35 pub score: f64,
36 pub geometrically_verified: bool,
40 pub verification: Option<LoopClosureVerification>,
45 pub pnp_query_landmark_pairs: Vec<(usize, u64)>,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq)]
52pub struct LoopClosureVerifierConfig {
53 pub min_inliers: usize,
56 pub min_inlier_ratio: f64,
59 pub max_mean_sampson_error: f64,
62 pub default_translation_scale: f64,
67}
68
69impl Default for LoopClosureVerifierConfig {
70 fn default() -> Self {
71 Self {
72 min_inliers: 8,
73 min_inlier_ratio: 0.5,
74 max_mean_sampson_error: 5.0e-3,
75 default_translation_scale: 1.0,
76 }
77 }
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum LoopClosureVerificationFailureReason {
83 InsufficientCorrespondences,
85 EssentialEstimationFailed,
87 TooFewInliers,
89 LowInlierRatio,
91 HighSampsonError,
93 PoseDisagreement,
97}
98
99#[derive(Debug, Clone, PartialEq)]
101pub struct LoopClosureVerification {
102 pub verified: bool,
103 pub correspondence_count: usize,
104 pub inlier_count: usize,
105 pub inlier_ratio: f64,
106 pub mean_sampson_error: f64,
111 pub score: f64,
112 pub failure_reason: Option<LoopClosureVerificationFailureReason>,
113 pub relative_pose: Option<SE3>,
121 pub mean_reprojection_error_px: Option<f64>,
124}
125
126pub trait LoopClosureVerifier {
131 fn verify(
132 &self,
133 correspondences: &[TwoViewCorrespondence],
134 camera: &Camera,
135 ) -> LoopClosureVerification;
136
137 fn verify_with_weights(
143 &self,
144 correspondences: &[TwoViewCorrespondence],
145 weights: Option<&[f32]>,
146 camera: &Camera,
147 ) -> LoopClosureVerification {
148 let _ = weights;
149 self.verify(correspondences, camera)
150 }
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Default)]
157pub struct EssentialMatrixLoopClosureVerifier {
158 pub estimator: RelativePoseEstimator<EightPointEssentialMatrixEstimator>,
159 pub config: LoopClosureVerifierConfig,
160}
161
162impl EssentialMatrixLoopClosureVerifier {
163 pub const fn new(
164 estimator: RelativePoseEstimator<EightPointEssentialMatrixEstimator>,
165 config: LoopClosureVerifierConfig,
166 ) -> Self {
167 Self { estimator, config }
168 }
169}
170
171impl LoopClosureVerifier for EssentialMatrixLoopClosureVerifier {
172 fn verify(
173 &self,
174 correspondences: &[TwoViewCorrespondence],
175 camera: &Camera,
176 ) -> LoopClosureVerification {
177 self.verify_with_weights(correspondences, None, camera)
178 }
179
180 fn verify_with_weights(
181 &self,
182 correspondences: &[TwoViewCorrespondence],
183 weights: Option<&[f32]>,
184 camera: &Camera,
185 ) -> LoopClosureVerification {
186 let correspondence_count = correspondences.len();
187 let minimum = self
188 .estimator
189 .ransac
190 .estimator
191 .min_correspondences
192 .max(self.config.min_inliers);
193 if correspondence_count < minimum {
194 return LoopClosureVerification {
195 verified: false,
196 correspondence_count,
197 inlier_count: 0,
198 inlier_ratio: 0.0,
199 mean_sampson_error: f64::INFINITY,
200 score: 0.0,
201 failure_reason: Some(
202 LoopClosureVerificationFailureReason::InsufficientCorrespondences,
203 ),
204 relative_pose: None,
205 mean_reprojection_error_px: None,
206 };
207 }
208
209 let relative_pose = match weights {
210 Some(w) if w.len() == correspondences.len() => {
211 self.estimator.estimate_with_scale_and_weights(
212 correspondences,
213 camera,
214 self.config.default_translation_scale,
215 w,
216 )
217 }
218 _ => self.estimator.estimate_with_scale(
219 correspondences,
220 camera,
221 self.config.default_translation_scale,
222 ),
223 };
224 let Some(relative_pose) = relative_pose else {
225 return LoopClosureVerification {
226 verified: false,
227 correspondence_count,
228 inlier_count: 0,
229 inlier_ratio: 0.0,
230 mean_sampson_error: f64::INFINITY,
231 score: 0.0,
232 failure_reason: Some(
233 LoopClosureVerificationFailureReason::EssentialEstimationFailed,
234 ),
235 relative_pose: None,
236 mean_reprojection_error_px: None,
237 };
238 };
239
240 let inlier_count = relative_pose.inliers.len();
241 let inlier_ratio = inlier_count as f64 / correspondence_count as f64;
242 let mean_sampson = relative_pose.mean_sampson_error;
243
244 let mut failure_reason = None;
245 if inlier_count < self.config.min_inliers {
246 failure_reason = Some(LoopClosureVerificationFailureReason::TooFewInliers);
247 } else if inlier_ratio < self.config.min_inlier_ratio {
248 failure_reason = Some(LoopClosureVerificationFailureReason::LowInlierRatio);
249 } else if mean_sampson > self.config.max_mean_sampson_error {
250 failure_reason = Some(LoopClosureVerificationFailureReason::HighSampsonError);
251 }
252 let verified = failure_reason.is_none();
253 let inlier_volume = inlier_ratio * inlier_count as f64;
254 let denominator = mean_sampson.max(1.0e-6);
255 let score = if denominator.is_finite() {
256 inlier_volume / denominator
257 } else {
258 inlier_volume
259 };
260 LoopClosureVerification {
261 verified,
262 correspondence_count,
263 inlier_count,
264 inlier_ratio,
265 mean_sampson_error: mean_sampson,
266 score,
267 failure_reason,
268 relative_pose: Some(relative_pose.previous_to_current),
269 mean_reprojection_error_px: None,
270 }
271 }
272}
273
274#[derive(Debug, Clone, Copy, PartialEq)]
276pub struct PnPLoopClosureVerifierConfig {
277 pub min_inliers: usize,
280 pub min_inlier_ratio: f64,
282 pub max_mean_reprojection_error_px: f64,
284}
285
286impl Default for PnPLoopClosureVerifierConfig {
287 fn default() -> Self {
288 Self {
289 min_inliers: 8,
290 min_inlier_ratio: 0.5,
291 max_mean_reprojection_error_px: 4.0,
292 }
293 }
294}
295
296#[derive(Debug, Clone, Copy, PartialEq, Default)]
314pub struct PnPLoopClosureVerifier<R = PnPRansac> {
315 pub ransac: R,
316 pub config: PnPLoopClosureVerifierConfig,
317}
318
319impl<R> PnPLoopClosureVerifier<R>
320where
321 R: RobustPoseEstimator,
322{
323 pub const fn new(ransac: R, config: PnPLoopClosureVerifierConfig) -> Self {
324 Self { ransac, config }
325 }
326
327 pub fn verify(
332 &self,
333 correspondences: &[Correspondence2D3D],
334 keyframe_pose: &Pose,
335 camera: &Camera,
336 ) -> LoopClosureVerification {
337 self.verify_impl(correspondences, keyframe_pose, camera, None)
338 .0
339 }
340
341 pub fn verify_with_weights(
345 &self,
346 correspondences: &[Correspondence2D3D],
347 keyframe_pose: &Pose,
348 camera: &Camera,
349 weights: Option<&[f32]>,
350 ) -> LoopClosureVerification {
351 self.verify_impl(correspondences, keyframe_pose, camera, weights)
352 .0
353 }
354
355 pub fn verify_with_inlier_indices(
359 &self,
360 correspondences: &[Correspondence2D3D],
361 keyframe_pose: &Pose,
362 camera: &Camera,
363 ) -> (LoopClosureVerification, Vec<usize>) {
364 self.verify_impl(correspondences, keyframe_pose, camera, None)
365 }
366
367 fn verify_impl(
368 &self,
369 correspondences: &[Correspondence2D3D],
370 keyframe_pose: &Pose,
371 camera: &Camera,
372 weights: Option<&[f32]>,
373 ) -> (LoopClosureVerification, Vec<usize>) {
374 let correspondence_count = correspondences.len();
375 if correspondence_count < self.config.min_inliers {
376 return (
377 LoopClosureVerification {
378 verified: false,
379 correspondence_count,
380 inlier_count: 0,
381 inlier_ratio: 0.0,
382 mean_sampson_error: 0.0,
383 score: 0.0,
384 failure_reason: Some(
385 LoopClosureVerificationFailureReason::InsufficientCorrespondences,
386 ),
387 relative_pose: None,
388 mean_reprojection_error_px: None,
389 },
390 Vec::new(),
391 );
392 }
393
394 let report = match weights {
395 Some(weights)
396 if weights.len() == correspondence_count
397 && weights
398 .iter()
399 .any(|value| value.is_finite() && *value > 0.0) =>
400 {
401 self.ransac
402 .estimate_with_weights(correspondences, camera, weights)
403 }
404 _ => self.ransac.estimate(correspondences, camera),
405 };
406 let Some(report) = report else {
407 return (
408 LoopClosureVerification {
409 verified: false,
410 correspondence_count,
411 inlier_count: 0,
412 inlier_ratio: 0.0,
413 mean_sampson_error: 0.0,
414 score: 0.0,
415 failure_reason: Some(
416 LoopClosureVerificationFailureReason::EssentialEstimationFailed,
417 ),
418 relative_pose: None,
419 mean_reprojection_error_px: None,
420 },
421 Vec::new(),
422 );
423 };
424
425 let inlier_count = report.inliers.len();
426 let inlier_ratio = inlier_count as f64 / correspondence_count as f64;
427 let mean_reprojection_error_px = report.mean_reprojection_error;
428
429 let mut failure_reason = None;
430 if inlier_count < self.config.min_inliers {
431 failure_reason = Some(LoopClosureVerificationFailureReason::TooFewInliers);
432 } else if inlier_ratio < self.config.min_inlier_ratio {
433 failure_reason = Some(LoopClosureVerificationFailureReason::LowInlierRatio);
434 } else if mean_reprojection_error_px > self.config.max_mean_reprojection_error_px {
435 failure_reason = Some(LoopClosureVerificationFailureReason::HighSampsonError);
436 }
437 let verified = failure_reason.is_none();
438 let inlier_volume = inlier_ratio * inlier_count as f64;
439 let denominator = mean_reprojection_error_px.max(1.0e-6);
440 let score = if denominator.is_finite() {
441 inlier_volume / denominator
442 } else {
443 inlier_volume
444 };
445 let relative_pose = report
446 .pose
447 .world_to_camera
448 .compose(&keyframe_pose.world_to_camera.inverse());
449 let inlier_indices = report.inliers;
450 (
451 LoopClosureVerification {
452 verified,
453 correspondence_count,
454 inlier_count,
455 inlier_ratio,
456 mean_sampson_error: 0.0,
457 score,
458 failure_reason,
459 relative_pose: Some(relative_pose),
460 mean_reprojection_error_px: Some(mean_reprojection_error_px),
461 },
462 inlier_indices,
463 )
464 }
465}
466
467pub fn correspondences_2d3d_for_loop_candidate(
472 current_frame: &Frame,
473 current_inlier_query_indices: &[usize],
474 current_inlier_landmark_ids: &[u64],
475 keyframe: &Keyframe,
476 map: &VisualMap,
477) -> Vec<Correspondence2D3D> {
478 let keyframe_landmark_ids: HashSet<u64> = keyframe
479 .observations
480 .iter()
481 .map(|observation| observation.landmark_id)
482 .collect();
483 let mut correspondences = Vec::new();
484 for (query_index, landmark_id) in current_inlier_query_indices
485 .iter()
486 .zip(current_inlier_landmark_ids.iter())
487 {
488 if !keyframe_landmark_ids.contains(landmark_id) {
489 continue;
490 }
491 let Some(landmark) = map.landmarks.get(landmark_id) else {
492 continue;
493 };
494 let Some(query_xy) = current_frame.keypoints.get(*query_index) else {
495 continue;
496 };
497 correspondences.push(Correspondence2D3D {
498 point2d: *query_xy,
499 point3d: landmark.position,
500 confidence: None,
501 });
502 }
503 correspondences
504}
505
506pub fn correspondences_for_loop_candidate(
511 current_frame: &Frame,
512 current_inlier_query_indices: &[usize],
513 current_inlier_landmark_ids: &[u64],
514 keyframe: &Keyframe,
515) -> Vec<TwoViewCorrespondence> {
516 let keyframe_lookup: HashMap<u64, Point2<f64>> = keyframe
517 .observations
518 .iter()
519 .map(|observation| (observation.landmark_id, observation.xy))
520 .collect();
521 let mut correspondences = Vec::new();
522 for (query_index, landmark_id) in current_inlier_query_indices
523 .iter()
524 .zip(current_inlier_landmark_ids.iter())
525 {
526 let Some(keyframe_xy) = keyframe_lookup.get(landmark_id) else {
527 continue;
528 };
529 let Some(query_xy) = current_frame.keypoints.get(*query_index) else {
530 continue;
531 };
532 correspondences.push(TwoViewCorrespondence {
533 previous_xy: *keyframe_xy,
534 current_xy: *query_xy,
535 });
536 }
537 correspondences
538}
539
540#[derive(Debug, Clone, PartialEq)]
551pub struct LoopClosureConstraint {
552 pub from_keyframe_id: u64,
553 pub to_keyframe_id: u64,
554 pub relative_pose: SE3,
555 pub inlier_count: usize,
556 pub inlier_ratio: f64,
557 pub mean_sampson_error: f64,
558 pub score: f64,
559}
560
561impl LoopClosureConstraint {
562 pub fn from_verified_candidate(
566 candidate: &LoopClosureCandidate,
567 ) -> Option<LoopClosureConstraint> {
568 let verification = candidate.verification.as_ref()?;
569 if !verification.verified {
570 return None;
571 }
572 let relative_pose = verification.relative_pose.clone()?;
573 Some(LoopClosureConstraint {
574 from_keyframe_id: candidate.matched_keyframe_id,
575 to_keyframe_id: candidate.query_frame_id,
576 relative_pose,
577 inlier_count: verification.inlier_count,
578 inlier_ratio: verification.inlier_ratio,
579 mean_sampson_error: verification.mean_sampson_error,
580 score: verification.score,
581 })
582 }
583
584 pub fn to_pairwise_pose_factor(&self, weight: f64) -> PairwisePoseFactor {
595 PairwisePoseFactor {
596 keyframe_id_from: self.from_keyframe_id,
597 keyframe_id_to: self.to_keyframe_id,
598 measurement: Pose {
599 world_to_camera: self.relative_pose.clone(),
600 },
601 weight,
602 }
603 }
604}
605
606pub fn loop_closure_constraints_from_candidates(
610 candidates: &[LoopClosureCandidate],
611) -> Vec<LoopClosureConstraint> {
612 candidates
613 .iter()
614 .filter_map(LoopClosureConstraint::from_verified_candidate)
615 .collect()
616}
617
618pub fn pairwise_pose_factors_from_loop_closures(
625 constraints: &[LoopClosureConstraint],
626 weight: f64,
627) -> Vec<PairwisePoseFactor> {
628 constraints
629 .iter()
630 .map(|c| c.to_pairwise_pose_factor(weight))
631 .collect()
632}
633
634fn verify_each_candidate<F>(
650 candidates: &mut [LoopClosureCandidate],
651 map: &VisualMap,
652 mut verify_one: F,
653) where
654 F: FnMut(&Keyframe) -> Option<LoopClosureVerification>,
655{
656 for candidate in candidates.iter_mut() {
657 let Some(keyframe) = map.keyframes.get(&candidate.matched_keyframe_id) else {
658 continue;
659 };
660 let Some(verification) = verify_one(keyframe) else {
661 continue;
662 };
663 candidate.geometrically_verified = verification.verified;
664 candidate.verification = Some(verification);
665 }
666}
667
668pub fn verify_loop_closure_candidates<V>(
674 candidates: &mut [LoopClosureCandidate],
675 current_frame: &Frame,
676 tracking: &TrackingResult,
677 map: &VisualMap,
678 camera: &Camera,
679 verifier: &V,
680) where
681 V: LoopClosureVerifier,
682{
683 verify_each_candidate(candidates, map, |keyframe| {
684 let correspondences = correspondences_for_loop_candidate(
685 current_frame,
686 &tracking.localization.inlier_query_indices,
687 &tracking.localization.inlier_landmark_ids,
688 keyframe,
689 );
690 Some(verifier.verify(&correspondences, camera))
691 });
692}
693
694pub fn verify_loop_closure_candidates_pnp<R>(
701 candidates: &mut [LoopClosureCandidate],
702 current_frame: &Frame,
703 tracking: &TrackingResult,
704 map: &VisualMap,
705 camera: &Camera,
706 verifier: &PnPLoopClosureVerifier<R>,
707) where
708 R: RobustPoseEstimator,
709{
710 verify_each_candidate(candidates, map, |keyframe| {
711 let keyframe_pose = keyframe.frame.pose.as_ref()?;
712 let correspondences = correspondences_2d3d_for_loop_candidate(
713 current_frame,
714 &tracking.localization.inlier_query_indices,
715 &tracking.localization.inlier_landmark_ids,
716 keyframe,
717 map,
718 );
719 Some(verifier.verify(&correspondences, keyframe_pose, camera))
720 });
721}
722
723#[derive(Debug, Clone, Copy, PartialEq)]
727pub struct HybridLoopClosureVerifierConfig {
728 pub max_translation_direction_disagreement_rad: f64,
732 pub max_rotation_disagreement_rad: f64,
735}
736
737impl Default for HybridLoopClosureVerifierConfig {
738 fn default() -> Self {
739 Self {
740 max_translation_direction_disagreement_rad: 0.20,
741 max_rotation_disagreement_rad: 0.20,
742 }
743 }
744}
745
746#[derive(Debug, Clone, Copy, PartialEq, Default)]
760pub struct HybridLoopClosureVerifier<R = PnPRansac> {
761 pub essential: EssentialMatrixLoopClosureVerifier,
762 pub pnp: PnPLoopClosureVerifier<R>,
763 pub config: HybridLoopClosureVerifierConfig,
764}
765
766impl<R> HybridLoopClosureVerifier<R>
767where
768 R: RobustPoseEstimator,
769{
770 pub const fn new(
771 essential: EssentialMatrixLoopClosureVerifier,
772 pnp: PnPLoopClosureVerifier<R>,
773 config: HybridLoopClosureVerifierConfig,
774 ) -> Self {
775 Self {
776 essential,
777 pnp,
778 config,
779 }
780 }
781}
782
783pub fn verify_loop_closure_candidates_hybrid<R>(
791 candidates: &mut [LoopClosureCandidate],
792 current_frame: &Frame,
793 tracking: &TrackingResult,
794 map: &VisualMap,
795 camera: &Camera,
796 verifier: &HybridLoopClosureVerifier<R>,
797) where
798 R: RobustPoseEstimator,
799{
800 verify_each_candidate(candidates, map, |keyframe| {
801 let keyframe_pose = keyframe.frame.pose.as_ref()?;
802 let two_view = correspondences_for_loop_candidate(
803 current_frame,
804 &tracking.localization.inlier_query_indices,
805 &tracking.localization.inlier_landmark_ids,
806 keyframe,
807 );
808 let pnp_corrs = correspondences_2d3d_for_loop_candidate(
809 current_frame,
810 &tracking.localization.inlier_query_indices,
811 &tracking.localization.inlier_landmark_ids,
812 keyframe,
813 map,
814 );
815 let essential_v = verifier.essential.verify(&two_view, camera);
816 let pnp_v = verifier.pnp.verify(&pnp_corrs, keyframe_pose, camera);
817 Some(combine_hybrid_verifications(
818 &essential_v,
819 &pnp_v,
820 &verifier.config,
821 ))
822 });
823}
824
825#[derive(Debug, Clone, Copy)]
830pub struct PairwiseKeyframeView<'a> {
831 pub frame_id: u64,
832 pub keypoints: &'a [Point2<f64>],
833 pub descriptors: &'a [Vec<f32>],
834}
835
836impl<'a> PairwiseKeyframeView<'a> {
837 pub fn from_features(frame_id: u64, features: &'a FeatureSet) -> Self {
838 Self {
839 frame_id,
840 keypoints: &features.keypoints,
841 descriptors: &features.descriptors,
842 }
843 }
844}
845
846#[derive(Debug, Clone, Copy, PartialEq)]
848pub struct PairwiseLoopClosureScannerConfig {
849 pub min_keyframe_id_gap: u64,
854 pub min_matches: usize,
858}
859
860impl Default for PairwiseLoopClosureScannerConfig {
861 fn default() -> Self {
862 Self {
863 min_keyframe_id_gap: 20,
864 min_matches: 30,
865 }
866 }
867}
868
869pub fn scan_pairwise_loop_closures<M, V>(
884 keyframes: &[PairwiseKeyframeView],
885 matcher: &M,
886 verifier: &V,
887 camera: &Camera,
888 config: &PairwiseLoopClosureScannerConfig,
889) -> Vec<LoopClosureCandidate>
890where
891 M: Matcher,
892 V: LoopClosureVerifier,
893{
894 let mut out = Vec::new();
895 for i in 0..keyframes.len() {
896 for j in (i + 1)..keyframes.len() {
897 let from = &keyframes[i];
898 let to = &keyframes[j];
899 let gap = to.frame_id.saturating_sub(from.frame_id);
900 if gap < config.min_keyframe_id_gap {
901 continue;
902 }
903 let matches = matcher.match_descriptors(from.descriptors, to.descriptors);
904 if matches.len() < config.min_matches {
905 continue;
906 }
907 let mut correspondences: Vec<TwoViewCorrespondence> = Vec::with_capacity(matches.len());
908 let mut weights: Vec<f32> = Vec::with_capacity(matches.len());
909 let mut any_confidence = false;
910 for m in &matches {
911 let Some(prev) = from.keypoints.get(m.query_index) else {
912 continue;
913 };
914 let Some(curr) = to.keypoints.get(m.train_index) else {
915 continue;
916 };
917 correspondences.push(TwoViewCorrespondence {
918 previous_xy: *prev,
919 current_xy: *curr,
920 });
921 if let Some(c) = m.confidence {
922 any_confidence = true;
923 weights.push(c);
924 } else {
925 weights.push(1.0);
926 }
927 }
928 if correspondences.len() < config.min_matches {
929 continue;
930 }
931 let weights_slice = if any_confidence {
932 Some(weights.as_slice())
933 } else {
934 None
935 };
936 let verification =
937 verifier.verify_with_weights(&correspondences, weights_slice, camera);
938 if !verification.verified {
939 continue;
940 }
941 out.push(LoopClosureCandidate {
942 query_frame_id: to.frame_id,
943 matched_keyframe_id: from.frame_id,
944 shared_landmark_count: verification.inlier_count,
945 query_inlier_count: verification.inlier_count,
946 keyframe_observation_count: matches.len(),
947 shared_landmark_ratio: verification.inlier_ratio,
948 score: verification.score,
949 geometrically_verified: true,
950 verification: Some(verification),
951 pnp_query_landmark_pairs: Vec::new(),
952 });
953 }
954 }
955 out
956}
957
958fn combine_hybrid_verifications(
959 essential: &LoopClosureVerification,
960 pnp: &LoopClosureVerification,
961 config: &HybridLoopClosureVerifierConfig,
962) -> LoopClosureVerification {
963 let inlier_count = essential.inlier_count.min(pnp.inlier_count);
966 let inlier_ratio = essential.inlier_ratio.min(pnp.inlier_ratio);
967 let correspondence_count = essential.correspondence_count.min(pnp.correspondence_count);
968 let score = essential.score.min(pnp.score);
969
970 if !essential.verified {
971 return LoopClosureVerification {
972 verified: false,
973 correspondence_count,
974 inlier_count,
975 inlier_ratio,
976 mean_sampson_error: essential.mean_sampson_error,
977 score,
978 failure_reason: essential.failure_reason,
979 relative_pose: pnp.relative_pose.clone(),
980 mean_reprojection_error_px: pnp.mean_reprojection_error_px,
981 };
982 }
983 if !pnp.verified {
984 return LoopClosureVerification {
985 verified: false,
986 correspondence_count,
987 inlier_count,
988 inlier_ratio,
989 mean_sampson_error: essential.mean_sampson_error,
990 score,
991 failure_reason: pnp.failure_reason,
992 relative_pose: pnp.relative_pose.clone(),
993 mean_reprojection_error_px: pnp.mean_reprojection_error_px,
994 };
995 }
996 let (Some(ess_pose), Some(pnp_pose)) =
998 (essential.relative_pose.as_ref(), pnp.relative_pose.as_ref())
999 else {
1000 return LoopClosureVerification {
1001 verified: false,
1002 correspondence_count,
1003 inlier_count,
1004 inlier_ratio,
1005 mean_sampson_error: essential.mean_sampson_error,
1006 score,
1007 failure_reason: Some(LoopClosureVerificationFailureReason::PoseDisagreement),
1008 relative_pose: pnp.relative_pose.clone(),
1009 mean_reprojection_error_px: pnp.mean_reprojection_error_px,
1010 };
1011 };
1012
1013 let direction_disagreement =
1014 translation_direction_disagreement_rad(&ess_pose.translation, &pnp_pose.translation);
1015 let rotation_disagreement = ess_pose.rotation.rotation_to(&pnp_pose.rotation).angle();
1016 let agreement_ok = direction_disagreement <= config.max_translation_direction_disagreement_rad
1017 && rotation_disagreement <= config.max_rotation_disagreement_rad;
1018
1019 let failure_reason = if agreement_ok {
1020 None
1021 } else {
1022 Some(LoopClosureVerificationFailureReason::PoseDisagreement)
1023 };
1024 LoopClosureVerification {
1025 verified: agreement_ok,
1026 correspondence_count,
1027 inlier_count,
1028 inlier_ratio,
1029 mean_sampson_error: essential.mean_sampson_error,
1030 score,
1031 failure_reason,
1032 relative_pose: Some(pnp_pose.clone()),
1033 mean_reprojection_error_px: pnp.mean_reprojection_error_px,
1034 }
1035}
1036
1037fn translation_direction_disagreement_rad(
1038 a: &nalgebra::Vector3<f64>,
1039 b: &nalgebra::Vector3<f64>,
1040) -> f64 {
1041 let na = a.norm();
1042 let nb = b.norm();
1043 if na < 1.0e-9 || nb < 1.0e-9 {
1044 return 0.0;
1045 }
1046 let dir_a = a / na;
1047 let dir_b = b / nb;
1048 dir_a.dot(&dir_b).clamp(-1.0, 1.0).acos()
1049}
1050
1051pub(crate) fn detect_loop_closure_candidates(
1052 frame: &Frame,
1053 tracking: &TrackingResult,
1054 map: &VisualMap,
1055 config: &LoopClosureConfig,
1056) -> Vec<LoopClosureCandidate> {
1057 if !config.enabled || !tracking.localization.success {
1058 return Vec::new();
1059 }
1060
1061 let query_landmarks = tracking
1062 .localization
1063 .inlier_landmark_ids
1064 .iter()
1065 .copied()
1066 .collect::<HashSet<_>>();
1067 if query_landmarks.is_empty() {
1068 return Vec::new();
1069 }
1070
1071 let mut candidates = map
1072 .keyframes
1073 .values()
1074 .filter_map(|keyframe| {
1075 if frame.id.abs_diff(keyframe.frame.id) < config.min_frame_id_gap {
1076 return None;
1077 }
1078
1079 let keyframe_landmarks = keyframe
1080 .observations
1081 .iter()
1082 .map(|observation| observation.landmark_id)
1083 .collect::<HashSet<_>>();
1084 if keyframe_landmarks.is_empty() {
1085 return None;
1086 }
1087
1088 let shared_landmark_count = query_landmarks.intersection(&keyframe_landmarks).count();
1089 if shared_landmark_count < config.min_shared_landmarks {
1090 return None;
1091 }
1092
1093 let denominator = query_landmarks.len().min(keyframe_landmarks.len());
1094 let shared_landmark_ratio = shared_landmark_count as f64 / denominator as f64;
1095 let required_ratio = f64::from(config.min_shared_landmark_ratio_percent) / 100.0;
1096 if shared_landmark_ratio < required_ratio {
1097 return None;
1098 }
1099
1100 let score = shared_landmark_ratio * shared_landmark_count as f64;
1101 Some(LoopClosureCandidate {
1102 query_frame_id: frame.id,
1103 matched_keyframe_id: keyframe.frame.id,
1104 shared_landmark_count,
1105 query_inlier_count: query_landmarks.len(),
1106 keyframe_observation_count: keyframe_landmarks.len(),
1107 shared_landmark_ratio,
1108 score,
1109 geometrically_verified: true,
1110 verification: None,
1111 pnp_query_landmark_pairs: Vec::new(),
1112 })
1113 })
1114 .collect::<Vec<_>>();
1115
1116 candidates.sort_by(|a, b| {
1117 b.score
1118 .partial_cmp(&a.score)
1119 .unwrap_or(std::cmp::Ordering::Equal)
1120 .then_with(|| b.shared_landmark_count.cmp(&a.shared_landmark_count))
1121 .then_with(|| a.matched_keyframe_id.cmp(&b.matched_keyframe_id))
1122 });
1123 candidates.truncate(config.max_candidates);
1124 candidates
1125}