Skip to main content

visloc_slam/
loop_closure.rs

1//! Loop-closure detection and geometric verification: candidate scan,
2//! essential-matrix / PnP / hybrid verifiers, and constraint construction.
3
4use 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    /// `true` while the candidate has not been rejected by an explicit
37    /// verifier. When [`verify_loop_closure_candidates`] runs, this becomes
38    /// `LoopClosureVerification::verified`.
39    pub geometrically_verified: bool,
40    /// Optional verifier output. `Some` when [`verify_loop_closure_candidates`]
41    /// (or another caller) has explicitly run a [`LoopClosureVerifier`] over
42    /// the candidate; `None` when only the shared-landmark heuristic has
43    /// produced the candidate.
44    pub verification: Option<LoopClosureVerification>,
45    /// Query keypoint index paired with an older-map landmark id by the
46    /// appearance PnP correspondence builder. Empty for other sources.
47    pub pnp_query_landmark_pairs: Vec<(usize, u64)>,
48}
49
50/// Configuration thresholds for [`EssentialMatrixLoopClosureVerifier`].
51#[derive(Debug, Clone, Copy, PartialEq)]
52pub struct LoopClosureVerifierConfig {
53    /// Minimum number of inliers an essential-matrix RANSAC fit must produce
54    /// for the candidate to be accepted.
55    pub min_inliers: usize,
56    /// Minimum inlier ratio (inliers / supplied correspondences) for
57    /// acceptance.
58    pub min_inlier_ratio: f64,
59    /// Maximum allowed mean Sampson distance, in normalized image-plane units
60    /// (multiply by focal length to convert to pixels).
61    pub max_mean_sampson_error: f64,
62    /// Translation scale applied when recovering the relative pose. Two-view
63    /// geometry leaves translation up to scale; this default is what
64    /// [`LoopClosureVerification::relative_pose`] uses unless callers wrap
65    /// the verifier with their own scale source. Defaults to `1.0`.
66    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/// Reason a [`LoopClosureVerification`] rejected a candidate.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum LoopClosureVerificationFailureReason {
83    /// Fewer correspondences than the verifier's minimum requirement.
84    InsufficientCorrespondences,
85    /// The essential-matrix RANSAC failed to find a consensus.
86    EssentialEstimationFailed,
87    /// The RANSAC produced fewer inliers than `min_inliers`.
88    TooFewInliers,
89    /// The inlier ratio fell below `min_inlier_ratio`.
90    LowInlierRatio,
91    /// Mean Sampson error exceeded `max_mean_sampson_error`.
92    HighSampsonError,
93    /// The hybrid verifier ran both backends successfully, but the recovered
94    /// essential-matrix and PnP relative poses disagreed beyond the configured
95    /// translation-direction or rotation tolerances.
96    PoseDisagreement,
97}
98
99/// Output of running a [`LoopClosureVerifier`] on a candidate.
100#[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    /// Mean Sampson distance reported by an essential-matrix verifier (in
107    /// normalized image-plane units). `0.0` and uninformative for
108    /// PnP-based verifiers; check [`Self::mean_reprojection_error_px`] in
109    /// that case.
110    pub mean_sampson_error: f64,
111    pub score: f64,
112    pub failure_reason: Option<LoopClosureVerificationFailureReason>,
113    /// Recovered relative pose (older keyframe → current frame) when the
114    /// underlying RANSAC converged. `Some` even for non-`verified` cases as
115    /// long as a pose was recovered; consult `verified` and `failure_reason`
116    /// before consuming. For essential-matrix verifiers the translation is
117    /// scaled by [`LoopClosureVerifierConfig::default_translation_scale`];
118    /// for PnP verifiers it is in metric units (the keyframe pose carries
119    /// the world scale).
120    pub relative_pose: Option<SE3>,
121    /// Mean reprojection error (in pixels) reported by a PnP-based verifier.
122    /// `None` for essential-matrix verifiers.
123    pub mean_reprojection_error_px: Option<f64>,
124}
125
126/// Trait for a loop-closure candidate verifier. Concrete implementations
127/// receive 2D-2D correspondences in pixel coordinates between the older
128/// keyframe (`previous_xy`) and the current/query frame (`current_xy`) plus
129/// the shared camera intrinsics.
130pub trait LoopClosureVerifier {
131    fn verify(
132        &self,
133        correspondences: &[TwoViewCorrespondence],
134        camera: &Camera,
135    ) -> LoopClosureVerification;
136
137    /// Confidence-aware variant: when `weights[i]` is high, correspondence
138    /// `i` is preferred during RANSAC sampling (PROSAC-style). Default
139    /// implementation falls back to the unweighted `verify` so existing
140    /// implementors don't need to change. Verifiers backed by RANSAC can
141    /// override to thread weights into `EssentialRansac::estimate_with_weights`.
142    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/// Geometric verifier that runs the classical essential-matrix RANSAC from
154/// `visloc-vision::two_view` on the supplied correspondences and reports
155/// inlier statistics, mean Sampson error, and a combined score.
156#[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/// Configuration thresholds for [`PnPLoopClosureVerifier`].
275#[derive(Debug, Clone, Copy, PartialEq)]
276pub struct PnPLoopClosureVerifierConfig {
277    /// Minimum number of PnP RANSAC inliers an accepted candidate must
278    /// produce.
279    pub min_inliers: usize,
280    /// Minimum inlier ratio (inliers / supplied 2D-3D correspondences).
281    pub min_inlier_ratio: f64,
282    /// Maximum allowed mean reprojection error (in pixels) for inliers.
283    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/// PnP-based loop-closure verifier. Reuses the project's [`PnPRansac`] to
297/// re-localize the current frame against landmarks observed by the candidate
298/// keyframe; if the recovered absolute pose has enough inliers and a small
299/// reprojection error, the candidate is accepted and the relative pose
300/// (older keyframe → current frame) is filled into
301/// [`LoopClosureVerification::relative_pose`].
302///
303/// Compared with [`EssentialMatrixLoopClosureVerifier`], this verifier:
304///
305/// - operates on 2D-3D correspondences instead of 2D-2D, so it checks the
306///   candidate against the actual 3D map structure rather than two-view
307///   geometry alone;
308/// - returns metric translations (the keyframe pose carries the world scale),
309///   so callers do not need to plug in a separate `default_translation_scale`;
310/// - is preferable when the older keyframe has sufficient triangulated
311///   landmarks visible from the current frame, which is the common case for
312///   in-map loop closures.
313#[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    /// Run PnP RANSAC on `correspondences` and turn the report into a
328    /// [`LoopClosureVerification`]. `keyframe_pose` is the older keyframe's
329    /// stored `world_to_camera` SE3; the recovered current-frame pose is
330    /// composed with its inverse to populate `relative_pose`.
331    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    /// Run PnP RANSAC with optional confidence-weighted sampling. This keeps the
342    /// same acceptance thresholds as [`Self::verify`] but lets matchers such as
343    /// LightGlue bias RANSAC toward high-confidence correspondences.
344    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    /// PnP verification plus indices into `correspondences` selected as
356    /// RANSAC inliers. Used by Sim3 loop estimation to avoid reintroducing
357    /// descriptor outliers already rejected by PnP.
358    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
467/// Build 2D-3D correspondences for a loop-closure candidate by intersecting
468/// the current frame's tracking inliers with the older keyframe's observed
469/// landmarks. Each shared landmark contributes one entry pairing the current
470/// frame's pixel observation with the landmark's world position.
471pub 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
506/// Build pixel-space two-view correspondences for a loop-closure candidate
507/// from the current frame's tracking inliers and an older keyframe's
508/// observations. Each shared landmark id contributes one correspondence
509/// `(keyframe_xy, current_xy)`.
510pub 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/// Pose-graph-style constraint between two keyframes derived from a verified
541/// loop-closure candidate. This is intentionally a lightweight data type — no
542/// solver lives in this crate yet — so downstream optimization layers can
543/// adopt it without committing to a specific backend.
544///
545/// `relative_pose` represents the rigid transform that takes a point in
546/// `from_keyframe_id`'s camera frame to `to_keyframe_id`'s camera frame, with
547/// the translation scaled by the verifier's
548/// [`LoopClosureVerifierConfig::default_translation_scale`] (or whatever
549/// scale the caller chose to apply before constructing the constraint).
550#[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    /// Builds a constraint from a verified candidate. Returns `None` when the
563    /// candidate has no verifier output, when the verifier rejected it, or
564    /// when no relative pose was recovered.
565    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    /// Lift this loop-closure edge into a [`PairwisePoseFactor`] so it can be
585    /// added to a [`BundleAdjustment`] alongside reprojection residuals.
586    ///
587    /// The relative pose `T_rel = T_to · T_fromⁱ` (the constraint's
588    /// `relative_pose`) is used verbatim as the BA measurement; `weight` is
589    /// `1 / σ²` for an isotropic SE(3) measurement noise σ. A robust default is
590    /// to scale from the verifier's inlier count, e.g.
591    /// `weight = (inlier_count as f64) * base_weight`, but the choice is left
592    /// to the caller because verifier output differs by backend (essential
593    /// matrix vs PnP vs hybrid).
594    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
606/// Convenience helper that builds a constraint per verified candidate. Keeps
607/// the same ordering as the input slice and silently drops candidates that
608/// were not verified or lack a recovered relative pose.
609pub 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
618/// Convert a slice of verified [`LoopClosureConstraint`]s into BA-ready
619/// [`PairwisePoseFactor`]s, all sharing the same scalar `weight`. Convenience
620/// wrapper for the common case where every loop edge is treated as
621/// equally-informative. For per-edge weighting (e.g. scaling by
622/// `inlier_count`), call [`LoopClosureConstraint::to_pairwise_pose_factor`]
623/// directly.
624pub 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
634/// Run `verify_one` on every candidate whose `matched_keyframe_id` still
635/// resolves in `map`. Candidates without a matching keyframe are silently
636/// skipped (the matched keyframe may have been deleted between candidate
637/// generation and verification). When `verify_one` returns `Some`, the
638/// candidate is mutated in place: `geometrically_verified` is set to
639/// `LoopClosureVerification::verified` and `verification` is set to the
640/// returned struct. `None` skips writing.
641///
642/// This is the shared iteration shell between
643/// [`verify_loop_closure_candidates`],
644/// [`verify_loop_closure_candidates_pnp`], and
645/// [`verify_loop_closure_candidates_hybrid`]. Each public wrapper supplies a
646/// closure that builds correspondences and calls its backend; this helper
647/// owns the candidate iteration and write-back so the public API stays
648/// uniform when new backends are added.
649fn 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
668/// Run `verifier` on every supplied candidate, mutating each
669/// [`LoopClosureCandidate`] in place: `verification` is set to the verifier
670/// output and `geometrically_verified` is replaced with
671/// `LoopClosureVerification::verified`. Candidates whose matched keyframe is
672/// no longer in `map` are left untouched.
673pub 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
694/// Run a PnP-based [`PnPLoopClosureVerifier`] on every supplied candidate.
695/// For each candidate this builds 2D-3D correspondences via
696/// [`correspondences_2d3d_for_loop_candidate`], runs PnP RANSAC on them, and
697/// updates `verification` and `geometrically_verified` in place.
698/// Candidates whose matched keyframe is no longer in `map`, or whose stored
699/// keyframe pose is missing, are left untouched.
700pub 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/// Configuration for [`HybridLoopClosureVerifier`]: maximum allowed
724/// disagreement between the essential-matrix and PnP recovered poses before
725/// the hybrid verifier rejects the candidate as inconsistent.
726#[derive(Debug, Clone, Copy, PartialEq)]
727pub struct HybridLoopClosureVerifierConfig {
728    /// Maximum allowed angle (in radians) between the essential and PnP
729    /// translation directions. Compared on unit vectors so essential's
730    /// scale-up-to-translation ambiguity does not trigger spurious failures.
731    pub max_translation_direction_disagreement_rad: f64,
732    /// Maximum allowed rotation angle between the essential and PnP rotation
733    /// components.
734    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/// Loop-closure verifier that consults both the essential-matrix and PnP
747/// backends and reports a consensus decision: the candidate is accepted iff
748/// both verifiers accept it AND their recovered relative poses agree to
749/// within the configured rotation / translation-direction tolerances. This
750/// catches ambiguity where a 2D-2D essential fit looks plausible but
751/// disagrees with the 3D map structure (or vice versa).
752///
753/// The combined [`LoopClosureVerification`] uses the PnP relative pose
754/// (metric, no scale parameter), the minimum of both verifiers' inlier
755/// counts (conservative), and reports both `mean_sampson_error` and
756/// `mean_reprojection_error_px`. When either backend rejects, the failure
757/// reason is propagated; if both pass but the poses disagree the failure
758/// reason is [`LoopClosureVerificationFailureReason::PoseDisagreement`].
759#[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
783/// Run a [`HybridLoopClosureVerifier`] on every supplied candidate. For each
784/// candidate this builds both 2D-2D and 2D-3D correspondences, runs the two
785/// backends in turn, combines them into a consensus
786/// [`LoopClosureVerification`], and writes the result back into
787/// `verification` / `geometrically_verified` in place. Candidates whose
788/// matched keyframe is no longer in `map` or whose stored keyframe pose is
789/// missing are left untouched.
790pub 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/// One keyframe's appearance in a pairwise loop-closure scan: the frame id is
826/// what the produced [`LoopClosureCandidate`] uses for `query_frame_id` /
827/// `matched_keyframe_id`. The keypoint and descriptor slices are typically
828/// borrowed from a [`FeatureSet`] (see [`PairwiseKeyframeView::from_features`]).
829#[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/// Configuration for [`scan_pairwise_loop_closures`].
847#[derive(Debug, Clone, Copy, PartialEq)]
848pub struct PairwiseLoopClosureScannerConfig {
849    /// Minimum frame-id gap between two keyframes for a pair to be eligible.
850    /// Pairs `(i, j)` with `keyframes[j].frame_id - keyframes[i].frame_id <
851    /// min_keyframe_id_gap` are skipped, so adjacent keyframes (which share
852    /// most of their tracks) are never confused for loops.
853    pub min_keyframe_id_gap: u64,
854    /// Minimum number of descriptor matches a pair needs before its
855    /// correspondences are even handed to the verifier. Cheap reject for
856    /// keyframes whose appearance has no overlap.
857    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
869/// Walk every keyframe pair `(i, j)` with `i < j` and a sufficient frame-id
870/// gap, brute-force match descriptors, and run the verifier on the resulting
871/// 2D-2D correspondences. Returns one [`LoopClosureCandidate`] per accepted
872/// pair, with `verification` populated and `geometrically_verified = true`.
873/// Rejected pairs are dropped (vs the `verify_loop_closure_candidates_*`
874/// helpers which mutate caller-supplied candidates in place); this routine is
875/// meant for the "I have a list of keyframes and want loop *detection*, not
876/// just verification" case.
877///
878/// `query_frame_id` is the later keyframe and `matched_keyframe_id` is the
879/// earlier one — the same convention `LoopClosureConstraint` builders use.
880/// `shared_landmark_count` and `keyframe_observation_count` are filled with
881/// inlier and total-match counts respectively (no map is consulted), so the
882/// candidate is ready for [`LoopClosureConstraint::from_verified_candidate`].
883pub 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    // Inherit the minimum (conservative) inlier count and ratio so the
964    // combined diagnostics never overstate either backend's evidence.
965    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    // Both verified — check pose agreement.
997    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}