Skip to main content

visloc_slam/
vo_loop_closure.rs

1//! Loop-closure pose-graph optimization for an open stereo-VO trajectory.
2//!
3//! A streaming stereo-VO frontend (classical or learned) produces a
4//! drift-accumulating *open* trajectory: only the first pose is gauge-fixed and
5//! nothing ties a revisited place back to its earlier observation. On a loopy
6//! sequence (KITTI seq00 revisits frame 86 around frame 1561, and closes the
7//! grand loop near frame 4404) the accumulated drift is exactly what a loop
8//! closure removes — and dense global bundle adjustment provably cannot, because
9//! a loop-free reprojection-minimum just deforms the trajectory without a
10//! constraint pulling the revisit back.
11//!
12//! This module is the glue that turns the per-frame VO products — poses, left
13//! [`FeatureSet`]s, and per-frame stereo depth ([`StereoFeature`]) — into a
14//! [`PoseGraph`] and runs the robust GNC SE(3) optimizer:
15//!
16//! 1. **Appearance** — a VLAD global descriptor per frame, from a k-means
17//!    vocabulary pooled over (subsampled) left descriptors.
18//! 2. **Proposal** — for each frame, the most similar earlier frames beyond a
19//!    temporal gap, above a cosine-similarity floor.
20//! 3. **Verification** — brute-force descriptor matching between the two frames'
21//!    left features, lifted to 2D-3D via the older frame's stereo depth, then
22//!    [`PnPLoopClosureVerifier`]. PnP yields a *metric* relative pose, so no
23//!    separate scale source is needed.
24//! 4. **Optimization** — sequential odometry edges (from the VO poses) plus the
25//!    verified loop edges, anchored at frame 0, solved with [`PoseGraph::optimize_se3_gnc`]
26//!    so a surviving spurious loop is down-weighted rather than trusted.
27//!
28//! The map-bound online-SLAM helpers ([`crate::verify_loop_closure_candidates_pnp`])
29//! require a [`crate::VisualMap`]/[`crate::Keyframe`] that the file-backed VO path
30//! never builds; this module reuses the same map-free primitives
31//! ([`PnPLoopClosureVerifier::verify`], [`LoopClosureConstraint`], [`PoseGraph`])
32//! over raw feature sets instead.
33
34use 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/// Configuration for [`close_loops_on_vo_trajectory`].
59#[derive(Debug, Clone)]
60pub struct VoLoopClosureConfig {
61    /// Visual-word count for the VLAD vocabulary (k-means centroids).
62    pub vocab_k: usize,
63    /// Lloyd iterations for vocabulary construction.
64    pub vocab_iterations: usize,
65    /// Deterministic seed for vocabulary k-means++ seeding.
66    pub vocab_seed: u64,
67    /// Keep every `vocab_descriptor_stride`-th left descriptor when pooling for
68    /// vocabulary construction (`1` = use all; larger keeps k-means tractable on
69    /// thousand-frame sequences).
70    pub vocab_descriptor_stride: usize,
71    /// Optional hard cap on the pooled descriptor count fed to k-means, applied
72    /// after striding by evenly sub-sampling the pool. k-means is
73    /// `O(pool · k · dim · iters)`, so without a cap a 4500-frame sequence pools
74    /// millions of descriptors and vocabulary construction alone runs for the
75    /// better part of an hour. A few tens of thousands of descriptors already
76    /// seed a stable `k=64` vocabulary. `None` uses the full strided pool.
77    pub vocab_max_pool: Option<usize>,
78    /// Minimum temporal gap (in frames) between the two frames of a loop
79    /// candidate. A cheap floor; the portable gate is `min_path_length`.
80    pub min_frame_gap: usize,
81    /// Optional minimum accumulated VO path length (metres travelled along the
82    /// trajectory) between a candidate's two frames. This is the *frame-rate-
83    /// and speed-independent* loop gate: a loop only corrects drift if drift had
84    /// room to accumulate between the revisit and its original observation, and
85    /// drift grows with distance travelled — not with frame index. A small
86    /// frame gap during slow motion (e.g. a hovering UAV at 20 Hz) travels
87    /// almost nothing and yields odometry-consistent "loops" that contribute no
88    /// correction; gating on path length rejects them without per-dataset
89    /// frame-gap tuning. `None` disables the gate (frame gap only). Measured on
90    /// EuRoC MH_03: frame-gap 30 alone left ATE unchanged (2.46 m), while a few
91    /// metres of required travel recovers the genuine long-range revisits.
92    pub min_path_length: Option<f64>,
93    /// Minimum VLAD cosine similarity for a frame pair to become a candidate.
94    pub min_similarity: f32,
95    /// Keep at most this many earlier frames per query frame as candidates
96    /// (strongest similarity first).
97    pub max_candidates_per_frame: usize,
98    /// Optional global cap on how many candidates reach PnP verification, taken
99    /// in descending appearance similarity. Bounds the cost of the dominant
100    /// stage — per-pair brute-force descriptor matching is `O(N_kp² · dim)` — on
101    /// long sequences where appearance alone proposes thousands of (mostly
102    /// redundant) pairs. `None` verifies every candidate.
103    pub max_verifications: Option<usize>,
104    /// Lowe-ratio for the loop-pair descriptor matcher.
105    pub match_ratio: Option<f32>,
106    /// PnP loop-closure verifier thresholds.
107    pub verifier: PnPLoopClosureVerifierConfig,
108    /// PnP RANSAC backend used by the verifier.
109    pub ransac: PnPRansac,
110    /// Before PnP, optionally retain only correspondences that are also
111    /// essential-matrix inliers under the same loop-pair match set. This is an
112    /// opt-in diagnostic/policy lever for long-baseline loop candidates where
113    /// 2D-2D geometry is strong but stereo-lifted 2D-3D correspondences are
114    /// noisy. `false` keeps the historical PnP input unchanged.
115    pub pnp_essential_inlier_filter: bool,
116    /// Bias loop PnP RANSAC sampling by descriptor-match confidence when
117    /// enough finite positive confidences are available and their spread is
118    /// meaningful. `false` keeps historical uniform sampling.
119    pub pnp_confidence_weighted_sampling: bool,
120    /// SE(3) pose-graph solver configuration.
121    pub se3: PoseGraphSe3Config,
122    /// GNC robust-optimization configuration.
123    pub gnc: GncConfig,
124    /// Refine each verified loop's relative pose with a local two-view bundle
125    /// adjustment *before* it enters the pose graph. See
126    /// `refine_loop_relative_two_view` for the rationale: PnP minimises
127    /// reprojection in the newer frame only while holding the older frame's
128    /// stereo-depth points fixed, so their triangulation error biases the loop
129    /// edge; a 2-view BA (older pose fixed, newer pose + shared landmarks free,
130    /// the older stereo disparity a *soft* metric anchor) lets the points refine
131    /// to satisfy reprojection in both frames and recovers a metrically better
132    /// grounded relative pose. Strictly local — it touches only each loop's two
133    /// frames, never the rest of the trajectory; the global drift distribution
134    /// stays with the SE(3) PGO. `false` reproduces the PnP-only loop edges.
135    pub refine_loops_two_view: bool,
136    /// Give each loop-closure edge an anisotropic 6×6 information matrix `Ω`
137    /// derived from the loop's own reprojection geometry, instead of the default
138    /// isotropic scalar weight (`inlier_count`). PnP/2-view BA constrain a loop
139    /// edge tightly in rotation and the lateral image directions but only weakly
140    /// along the optical axis (depth), yet the scalar weight pulls all six DOF
141    /// equally — so the SE(3) PGO smears each loop correction isotropically over
142    /// the cycle rather than routing it into the directions the loop actually
143    /// observes. `loop_edge_information` recovers `Ω` as the reprojection
144    /// Hessian `Σ JᵀJ` (in the solver's `[ρ; ω]` SE(3)-tangent convention) and
145    /// **trace-normalises it to the same total weight `inlier_count`**, so this
146    /// changes *only* the directional distribution of each loop's pull, not the
147    /// calibrated loop-vs-odometry ratio. This is the ORB-SLAM Essential-Graph
148    /// per-edge information that the isotropic edges omit. `false` keeps the
149    /// scalar-weight loop edges.
150    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/// An appearance-proposed loop candidate (older revisited frame ← newer query
187/// frame), before geometric verification.
188#[derive(Debug, Clone, Copy, PartialEq)]
189pub struct LoopCandidatePair {
190    /// Earlier (revisited) frame index.
191    pub older: usize,
192    /// Later (query) frame index. Always `older + min_frame_gap <= newer`.
193    pub newer: usize,
194    /// VLAD cosine similarity that proposed the pair.
195    pub similarity: f32,
196}
197
198/// Geometry-verification diagnostics for one appearance-proposed loop
199/// candidate. This is intended for benchmark artifacts and failure analysis:
200/// it records candidates that were never attempted because of
201/// `max_verifications` as well as candidates rejected by PnP.
202#[derive(Debug, Clone, PartialEq)]
203pub struct LoopCandidateVerificationDiagnostic {
204    /// Earlier (revisited) frame index.
205    pub older: usize,
206    /// Later (query) frame index.
207    pub newer: usize,
208    /// Appearance similarity that proposed the pair.
209    pub similarity: f32,
210    /// Whether the expensive descriptor-match + PnP verifier was run.
211    pub attempted: bool,
212    /// Raw left-descriptor match count between the newer and older frames.
213    pub match_count: usize,
214    /// Matcher source used for the row (`bruteforce`, `external`, or
215    /// `not_run`).
216    pub match_source: String,
217    /// Matches that survived the older-frame stereo-depth lookup and were
218    /// supplied to PnP as 2D-3D correspondences.
219    pub pnp_correspondence_count: usize,
220    /// Stereo-lifted 2D-3D correspondences before optional essential-inlier
221    /// filtering.
222    pub pnp_unfiltered_correspondence_count: usize,
223    /// PnP input policy used (`none`, `essential_inliers`, or
224    /// `essential_unverified`).
225    pub pnp_filter: String,
226    /// Whether PnP RANSAC used descriptor-match confidence for sampling.
227    pub pnp_weighted_sampling: bool,
228    /// Confidence-weight policy decision (`disabled`, `enabled`,
229    /// `missing_confidence`, `insufficient_confidence`, or
230    /// `low_confidence_spread`).
231    pub pnp_weight_policy: String,
232    /// Number of PnP correspondences with finite positive confidence values.
233    pub pnp_weight_confidence_count: usize,
234    /// Ratio `max(confidence) / min(confidence)` across valid confidence
235    /// values. `0.0` when no finite positive confidences are present.
236    pub pnp_weight_confidence_spread: f32,
237    /// 2D-2D correspondences supplied to essential-matrix verification.
238    pub essential_correspondence_count: usize,
239    /// Whether the same match set passed essential-matrix verification.
240    pub essential_verified: bool,
241    /// Essential-matrix verifier rejection label.
242    pub essential_failure_reason: Option<String>,
243    /// Essential-matrix RANSAC inlier count.
244    pub essential_inlier_count: usize,
245    /// Essential-matrix RANSAC inlier ratio.
246    pub essential_inlier_ratio: f64,
247    /// Essential-matrix mean Sampson error in normalized image-plane units.
248    pub essential_mean_sampson_error: f64,
249    /// Essential-matrix verifier score.
250    pub essential_score: f64,
251    /// Whether essential-matrix verification recovered a relative pose.
252    pub essential_has_relative_pose: bool,
253    /// True only when the candidate produced a loop constraint consumed by PGO.
254    pub verified: bool,
255    /// Rejection label. Existing verifier failures use their enum debug name;
256    /// VO-path-specific failures use short snake_case labels.
257    pub failure_reason: Option<String>,
258    /// PnP inlier count reported by the verifier.
259    pub inlier_count: usize,
260    /// PnP inlier ratio reported by the verifier.
261    pub inlier_ratio: f64,
262    /// Mean Sampson error from essential-matrix verifiers. For the current PnP
263    /// path this is usually `0.0`; prefer `mean_reprojection_error_px`.
264    pub mean_sampson_error: f64,
265    /// Mean reprojection error in pixels for PnP verification.
266    pub mean_reprojection_error_px: Option<f64>,
267    /// Verifier score, useful for ranking accepted and near-miss candidates.
268    pub score: f64,
269    /// Whether the verifier recovered a relative pose at all.
270    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/// Output of [`close_loops_on_vo_trajectory`].
310#[derive(Debug, Clone)]
311pub struct VoLoopClosureResult {
312    /// Trajectory after loop-closure PGO, in input frame order. Equal to the
313    /// input poses when no loop was verified.
314    pub refined_poses: Vec<Pose>,
315    /// Verified metric loop constraints fed into the pose graph.
316    pub loop_constraints: Vec<LoopClosureConstraint>,
317    /// Appearance-proposed loop candidates after temporal/path-length gates and
318    /// before geometric verification. This is the retrieval-stage artifact used
319    /// to measure recall@K independently of PnP/PGO.
320    pub candidate_pairs: Vec<LoopCandidatePair>,
321    /// Per-candidate geometry-verification diagnostics, ordered like
322    /// `candidate_pairs`.
323    pub verification_diagnostics: Vec<LoopCandidateVerificationDiagnostic>,
324    /// Appearance-proposed candidate count (pre-verification).
325    pub candidate_count: usize,
326    /// GNC solver report. `None` when no loop was verified (PGO is skipped and
327    /// the trajectory is returned unchanged).
328    pub gnc: Option<PoseGraphGncResult>,
329}
330
331impl VoLoopClosureResult {
332    /// Number of verified loop constraints.
333    pub fn verified_count(&self) -> usize {
334        self.loop_constraints.len()
335    }
336}
337
338/// Error returned by [`close_loops_on_vo_trajectory`].
339#[derive(Debug, Clone, PartialEq, Eq)]
340pub enum VoLoopClosureError {
341    /// `poses`, `left_features`, and `stereo_per_frame` disagree in length.
342    InputLengthMismatch,
343    /// Fewer than two frames — nothing to close.
344    TooFewFrames(usize),
345    /// k-means vocabulary construction failed (too few / zero-dim descriptors).
346    VocabularyBuildFailed,
347    /// The pose-graph solver failed.
348    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
376/// Build a VLAD global descriptor per frame from a k-means vocabulary pooled
377/// over (subsampled) left descriptors.
378fn 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    // Cap the k-means pool independent of sequence length: k-means is
390    // O(pool · k · dim · iters), so a multi-thousand-frame sequence would
391    // otherwise spend tens of minutes here. Evenly sub-sample to the cap.
392    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    // VLAD per frame is independent → parallelize (each is a full nearest-
407    // centroid pass over that frame's descriptors). `collect` preserves order.
408    Ok(left_features
409        .par_iter()
410        .map(|features| vlad(&features.descriptors, &vocab))
411        .collect())
412}
413
414/// Propose loop candidates by gap-constrained appearance retrieval: for each
415/// query frame, its strongest earlier matches beyond `min_frame_gap` whose
416/// cosine similarity clears `min_similarity`.
417///
418/// Unlike a full mutual-NN over one set (which collapses to the identity
419/// diagonal), this scans only the strictly-earlier prefix and leaves the
420/// false-positive rejection to PnP verification + GNC, mirroring the standard
421/// appearance-then-geometry loop-detection pipeline.
422pub 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    // Each query frame scans its earlier prefix independently — the O(N²·dim)
432    // retrieval is the dominant cost on long sequences, so parallelize across
433    // query frames. `flat_map_iter` over an indexed range keeps the output
434    // order deterministic.
435    (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/// One matched loop correspondence carried out of verification so a local
462/// two-view bundle adjustment can re-grind the loop edge. All quantities are in
463/// the *older* frame's camera coordinates (where that frame's stereo depth lives)
464/// plus the newer frame's pixel observation:
465/// - `older_xy` / `disparity`: the older left-image pixel and its rectified-stereo
466///   disparity (`u_l - u_r`), the soft metric anchor on the landmark.
467/// - `older_point_cam`: the landmark triangulated from that disparity, the BA's
468///   initial 3D point (in older-camera coordinates).
469/// - `newer_xy`: the same physical point's pixel in the newer frame, the cross-view
470///   reprojection target that refines the relative pose.
471#[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    // Weighted sampling only helps when the matcher is actually expressing a
550    // preference. Near-uniform scores add nondeterministic ordering pressure
551    // without useful signal, so keep those candidates on the historical uniform
552    // path.
553    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/// Geometrically verify one candidate pair. Matches the newer frame's left
687/// descriptors against the older frame's, lifts the older keypoints to world
688/// 3D via the older frame's stereo depth and pose, and runs PnP. Returns a
689/// metric loop constraint (`older -> newer`) when the verifier accepts it,
690/// paired with the matched correspondences (in older-camera coordinates) for an
691/// optional two-view refinement of the loop edge.
692#[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    // older left-keypoint index -> (camera-frame point, disparity) for keypoints
712    // with a valid stereo depth. The camera-frame point lifts to world for PnP;
713    // it is also kept in camera frame (with the disparity) so a two-view BA can
714    // re-anchor the loop without re-deriving the stereo geometry.
715    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
895/// Re-grind one verified loop's relative pose with a local two-view bundle
896/// adjustment, returning the refined `older -> newer` transform (or `None` to
897/// keep the PnP estimate).
898///
899/// PnP estimates the loop edge by minimising reprojection in the *newer* frame
900/// while holding the older frame's stereo-depth points fixed, so any error in
901/// the older disparity triangulation passes straight into the edge. This sets up
902/// a minimal BA in the older camera frame:
903/// - the older pose is the fixed gauge (identity);
904/// - the newer pose starts at the PnP relative pose and is free;
905/// - each shared landmark starts at its older stereo point and is free, anchored
906///   *softly* by an older rectified-stereo observation (so its depth can move to
907///   satisfy the newer-frame reprojection instead of being frozen at the noisy
908///   disparity), and observed by a newer monocular reprojection.
909///
910/// The older stereo residuals keep the metric scale well-posed, so the refined
911/// relative pose stays metric. The optimisation is local to the two frames and
912/// is rejected (returns `None`) if it wanders implausibly far from the PnP edge,
913/// leaving the global drift distribution to the SE(3) PGO.
914fn 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    // Drop a correspondence whose newer-frame reprojection under the PnP edge is
921    // already grossly off — it is a descriptor-match outlier the verifier's
922    // RANSAC rejected, and a free monocular residual would only bias the BA.
923    const REPROJ_INLIER_PX: f64 = 4.0;
924    // Reject a refinement that moved the loop edge implausibly far (the BA
925    // diverged or latched onto a bad configuration); keep the PnP edge instead.
926    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        // Reproject the older point into the newer frame under the PnP edge and
948        // gate on the pixel error (outlier rejection consistent with the edge).
949        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        // All correspondences share one rectified-stereo baseline; recover it
957        // from the disparity geometry (disparity = fx * baseline / z).
958        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    // Sanity-gate the refinement against the PnP edge: a large jump means the BA
992    // diverged, so fall back to the PnP estimate.
993    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
1002/// Anisotropic 6×6 information matrix `Ω` for a verified loop edge, in the SE(3)
1003/// pose-graph's `[ρ; ω]` (translation-first) right-perturbation tangent — the
1004/// exact convention [`PoseGraph::assemble_se3_system`] folds into `rᵀ Ω r`.
1005///
1006/// `Ω` is the reprojection Hessian of the loop measurement: with the older
1007/// landmarks fixed (the PnP assumption), the cost that determined the
1008/// `older → newer` relative pose `T` is `C(T) = Σ ‖π(T · Xᵢ) − uᵢ‖²`, and its
1009/// Hessian at the estimate is the information of the estimate. Parameterising
1010/// `T(ξ) = T · exp(ξ)` (right perturbation, matching the PGO residual
1011/// `r = log(measurementᵀ · predicted) = ξ`), each correspondence contributes
1012/// `Jᵢᵀ Jᵢ` with `Jᵢ = ∂π(T · exp(ξ) · Xᵢ)/∂ξ |₀` (2×6, finite-differenced).
1013///
1014/// The raw Hessian's *scale* (∝ `fx²/σ_px² · #inliers`) would dwarf the
1015/// scalar-weighted odometry edges and over-pull the loop, so `Ω` is
1016/// **trace-normalised to `6 · inlier_count`** — its mean eigenvalue equals the
1017/// scalar weight [`PoseGraph::add_loop_closure_constraint`] would have used.
1018/// Only the *direction* of the loop's pull changes (the well-observed rotation /
1019/// lateral axes up, the weak depth axis down); the calibrated loop-vs-odometry
1020/// magnitude is preserved. A small ridge keeps `Ω` positive-definite when the
1021/// shared landmarks are near-degenerate (collinear / coplanar).
1022fn loop_edge_information(
1023    camera: &Camera,
1024    relative_pose: &SE3,
1025    correspondences: &[LoopBaCorrespondence],
1026    inlier_count: usize,
1027) -> Option<Matrix6<f64>> {
1028    // Same inlier gate as the two-view refinement: ignore descriptor-match
1029    // outliers whose reprojection is already grossly off under the loop edge.
1030    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        // 2×6 reprojection Jacobian w.r.t. a right perturbation of the edge.
1048        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    // Trace-normalise so mean(eigenvalues) == inlier_count (the scalar weight),
1077    // isolating anisotropy from the loop-vs-odometry magnitude.
1078    let weight = (inlier_count as f64).max(1.0);
1079    let mut omega = h * (6.0 * weight / trace);
1080    // Ridge for strict positive-definiteness on near-degenerate geometry.
1081    let ridge = 1e-3 * weight;
1082    for d in 0..6 {
1083        omega[(d, d)] += ridge;
1084    }
1085    Some(omega)
1086}
1087
1088/// Accumulated trajectory length up to each frame: `cum[0] = 0`,
1089/// `cum[i] = cum[i-1] + ‖center_i − center_{i-1}‖`. The arc length between two
1090/// frames `a ≤ b` is `cum[b] − cum[a]`.
1091fn 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
1102/// Close loops on an open stereo-VO trajectory and return the globally
1103/// consistent poses.
1104///
1105/// `poses[i]` is frame `i`'s `world_to_camera`; `left_features[i]` and
1106/// `stereo_per_frame[i]` are the same products the BA refiner consumes
1107/// ([`crate::refine_stereo_vo_with_ba`]). When no loop survives verification the
1108/// trajectory is returned unchanged (`gnc == None`).
1109pub 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
1127/// Like [`close_loops_on_vo_trajectory`], but use caller-supplied descriptor
1128/// matches for selected loop candidates. The key is `(older, newer)` and the
1129/// match convention is `query_index = newer left feature`,
1130/// `train_index = older left feature`. Candidates without an entry fall back to
1131/// the built-in brute-force descriptor matcher.
1132pub 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
1152/// Like [`close_loops_on_vo_trajectory`] but with the per-frame *global
1153/// descriptors* supplied by the caller instead of computed internally as a
1154/// k-means VLAD over the local SuperPoint descriptors.
1155///
1156/// Appearance retrieval only needs one L2-comparable vector per frame; its
1157/// *source* is orthogonal to the geometric verification + PGO that follow. This
1158/// entry point lets a caller drive retrieval with a **learned** global
1159/// descriptor — e.g. an EigenPlaces / CosPlace embedding from
1160/// `GlobalDescriptorOnnxExtractor` (in `visloc-vision`)
1161/// — which is the same "learned front-end is the lever" substitution that
1162/// SuperPoint and LightGlue applied to the local stages. `globals[i]` is frame
1163/// `i`'s descriptor (any fixed dimension, the same for every frame); they need
1164/// not be unit-norm (`cosine_similarity` normalises), though learned VPR heads
1165/// already emit L2-normalised vectors.
1166///
1167/// Everything downstream of candidate proposal — path-length gating, PnP
1168/// verification, optional two-view BA, GNC SE(3) PGO — is identical to the VLAD
1169/// path.
1170pub 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
1189/// Like [`close_loops_on_vo_trajectory_with_globals`], but use caller-supplied
1190/// descriptor matches for selected loop candidates. The key is `(older, newer)`
1191/// and the match convention is `query_index = newer left feature`,
1192/// `train_index = older left feature`. Candidates without an entry fall back to
1193/// the built-in brute-force descriptor matcher.
1194pub 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    // Path-length gate: keep only candidates whose two frames are separated by
1239    // enough accumulated travel for drift to have built up. Speed-/frame-rate-
1240    // independent, so it needs no per-dataset frame-gap tuning.
1241    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    // Verify in descending appearance similarity so a `max_verifications` cap
1255    // spends the (expensive) geometric stage on the most promising pairs first.
1256    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    // Each candidate's geometric check (a brute-force descriptor match +
1267    // PnP RANSAC, O(N_kp²·dim)) is independent and is the other dominant cost,
1268    // so verify in parallel. The PnP RANSAC seed is fixed, so results are
1269    // thread-count-independent; `collect` preserves the (similarity-sorted)
1270    // order so the pose graph's edge order is deterministic.
1271    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    // Optionally re-grind each loop edge with a local two-view BA (older pose
1311    // fixed, newer pose + shared landmarks free) before it enters the pose
1312    // graph, and optionally derive its anisotropic information matrix `Ω` from
1313    // the loop's reprojection geometry. Independent per loop, so process in
1314    // parallel; the two-view refine falls back to the PnP edge when rejected,
1315    // and `Ω` is `None` when the lever is off or the geometry is degenerate.
1316    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    /// A landmark's descriptor: a deterministic, *continuous* per-id vector so
1469    /// the same physical point matches across frames, while no k-means centroid
1470    /// sits exactly on it (which would collapse the VLAD residual to zero, an
1471    /// artifact of sparse one-hot synthetic descriptors that real 256-d
1472    /// SuperPoint vectors never exhibit).
1473    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    /// Build a frame's `FeatureSet` + stereo depth by projecting the visible
1490    /// landmarks through the *true* pose, so PnP recovers the true geometry
1491    /// regardless of how drifted the VO estimate is.
1492    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        // world_to_camera: rotate then translate. Build from a camera-center +
1531        // orientation so the geometry is easy to reason about.
1532        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        // A circular loop of 41 frames returning to the start; landmarks scattered
1555        // ahead so each frame sees a stable subset, and frame 0 / frame 40 (same
1556        // place) re-see the same landmarks for the loop match.
1557        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; // 0..1 around the loop
1562            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        // Landmarks on a ring slightly outside the path so they stay in front of
1578        // the camera as it goes around.
1579        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        // Drifted VO estimate: integrate the *true* frame-to-frame motions with a
1602        // small systematic per-step error (slight yaw + forward bias) injected
1603        // into each relative pose. Error accumulates, so the trajectory spirals
1604        // open and the endpoint no longer coincides with the start — exactly the
1605        // drift a loop closure removes (a linear position offset would not).
1606        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        // Straight line, no revisits: huge min_gap so nothing is proposed.
1691        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    /// The two-view loop refinement recovers a loop edge biased by *noisy older
1721    /// stereo depth*. PnP holds the older points fixed at their (corrupted)
1722    /// disparity depth and fits the newer pose to them, so its edge inherits the
1723    /// depth error; the 2-view BA lets the points slide off the soft stereo
1724    /// anchor to satisfy the true newer-frame reprojection and drives the edge
1725    /// back toward ground truth.
1726    #[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        // Ground-truth loop edge: a modest forward/lateral translation + yaw.
1733        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        // A spread of landmarks in front of the older camera (its frame == world
1739        // here). Per-point unbiased depth noise corrupts the older stereo depth
1740        // (and hence the disparity), but the newer-frame pixel is the projection
1741        // of the TRUE point, so reprojection alone identifies the true geometry.
1742        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            // Deterministic per-point depth noise in ~[-12%, +12%]; scaling the
1765            // camera-frame point along its ray changes depth while keeping the
1766            // older pixel (and so the older stereo observation stays self-
1767            // consistent at the noisy depth, exactly as a real disparity error).
1768            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        // The PnP edge: minimise newer-frame reprojection holding the (noisy)
1782        // older points FIXED — exactly what PnP does — seeded from a slightly
1783        // perturbed truth. Its edge inherits the depth bias.
1784        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    /// With consistent (noise-free) geometry the refinement is a no-op-quality
1831    /// fixed point: it neither diverges nor degrades an already-correct edge.
1832    #[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    /// The loop-edge information matrix is symmetric positive-definite, calibrated
1874    /// to the same total weight the isotropic edge would have used (trace ≈
1875    /// 6·inlier_count), and *genuinely anisotropic* — a scaled identity would
1876    /// defeat the purpose, so the reprojection geometry must produce distinct
1877    /// eigenvalues (well-observed rotation/lateral axes up, weak depth axis down).
1878    #[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        // Symmetric.
1922        let asym = (omega - omega.transpose()).amax();
1923        assert!(asym < 1e-9, "Omega must be symmetric, got asymmetry {asym}");
1924
1925        // Trace-calibrated to ~6·inlier_count (a tiny PD ridge aside).
1926        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        // Positive-definite, and genuinely anisotropic (not a scaled identity).
1934        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}