Skip to main content

visloc_vision/
stereo_vo.rs

1//! Rectified-stereo VO frontend primitives.
2//!
3//! These helpers turn left/right [`FeatureSet`]s into metric 3D points in the
4//! left camera's frame (via [`triangulate_stereo_features`]) and stitch
5//! consecutive triangulations into a relative-pose hypothesis (via
6//! [`build_stereo_temporal_correspondences`] + a caller-supplied PnP RANSAC).
7//! Compared with monocular VO the recovered pose is in metric units — the
8//! baseline anchors scale on every frame, so there is no per-pair scale
9//! ambiguity to resolve later.
10//!
11//! The frontend is split so callers can plug in alternative feature
12//! extractors and matchers, keep their own per-frame caches, or skip the PnP
13//! step when they only need the triangulations themselves.
14
15use std::collections::HashMap;
16
17use nalgebra::{DMatrix, DVector, Matrix3, Point2, Point3, UnitQuaternion, Vector3};
18use rand::rngs::SmallRng;
19use rand::seq::SliceRandom;
20use rand::SeedableRng;
21use visloc_core::geometry::Pose;
22use visloc_core::types::Camera;
23
24use crate::features::{
25    CornerFeatureConfig, CornerFeatureError, CornerFeatureExtractor, FeatureExtractor, FeatureSet,
26    GrayscaleImage,
27};
28use crate::matching::{BruteForceMatcher, DescriptorMatch, Matcher};
29use crate::pnp::Correspondence2D3D;
30use crate::ransac::{PnPRansac, RobustPoseEstimator};
31use crate::stereo::triangulate_stereo_pixel;
32
33/// One triangulated stereo feature, anchored to its descriptor index in the
34/// left [`FeatureSet`].
35#[derive(Debug, Clone, PartialEq)]
36pub struct StereoFeature {
37    /// Index of the keypoint in the left [`FeatureSet`].
38    pub left_index: usize,
39    /// Index of the keypoint in the right [`FeatureSet`].
40    pub right_index: usize,
41    /// Disparity `u_l − u_r` (always positive, in pixels).
42    pub disparity: f64,
43    /// 3D point in the left camera's frame, in metric units derived from
44    /// `baseline`.
45    pub point_cam: Point3<f64>,
46}
47
48/// Runtime policy for the lower stereo-depth gate.
49///
50/// [`StereoDepthGate::Fixed`] preserves the historical
51/// [`StereoFeatureConfig::min_depth_m`] behavior. The adaptive policy keeps
52/// that fixed path available for A/B runs while letting production-style
53/// frontends choose a per-frame lower bound from the observed stereo-depth
54/// distribution.
55#[derive(Debug, Clone, Copy, PartialEq)]
56pub enum StereoDepthGate {
57    Fixed,
58    Adaptive(StereoAdaptiveDepthGateConfig),
59}
60
61impl StereoDepthGate {
62    pub const fn fixed() -> Self {
63        Self::Fixed
64    }
65
66    pub fn adaptive() -> Self {
67        Self::Adaptive(StereoAdaptiveDepthGateConfig::default())
68    }
69}
70
71impl Default for StereoDepthGate {
72    fn default() -> Self {
73        Self::Adaptive(StereoAdaptiveDepthGateConfig::default())
74    }
75}
76
77/// Configuration for [`StereoDepthGate::Adaptive`].
78#[derive(Debug, Clone, Copy, PartialEq)]
79pub struct StereoAdaptiveDepthGateConfig {
80    /// Minimum number of geometrically plausible stereo candidates required
81    /// before the adaptive policy replaces the fixed lower-depth gate.
82    pub min_candidate_count: usize,
83    /// Lower quantile of the per-frame depth distribution used as the scene
84    /// scale anchor. Values near 0.2 ignore sparse near-field outliers while
85    /// still following close-approach scenes.
86    pub depth_quantile: f64,
87    /// Multiplier applied to `depth_quantile` before bounding. Values below
88    /// one keep points slightly nearer than the robust scene-scale anchor.
89    pub depth_quantile_scale: f64,
90    /// Absolute safety floor for the effective lower-depth gate.
91    pub min_depth_floor_m: f64,
92    /// Absolute safety ceiling for the effective lower-depth gate. This keeps
93    /// automotive/hall-scale scenes close to the historical 3 m behavior.
94    pub max_adaptive_min_depth_m: f64,
95    /// Assumed 1-sigma disparity noise. Combined with
96    /// `max_relative_depth_uncertainty` to reject far-field samples whose
97    /// stereo depth is dominated by disparity noise.
98    pub disparity_noise_px: f64,
99    /// Maximum accepted relative depth uncertainty implied by disparity noise:
100    /// `sigma_z / z ~= sigma_disparity / disparity`.
101    pub max_relative_depth_uncertainty: f64,
102    /// Fractional hysteresis band around the previous effective gate. Proposed
103    /// updates inside this band keep the prior gate to prevent frame-to-frame
104    /// threshold chatter.
105    pub hysteresis_ratio: f64,
106}
107
108impl Default for StereoAdaptiveDepthGateConfig {
109    fn default() -> Self {
110        Self {
111            min_candidate_count: 20,
112            depth_quantile: 0.20,
113            depth_quantile_scale: 0.85,
114            min_depth_floor_m: 0.35,
115            max_adaptive_min_depth_m: 3.0,
116            disparity_noise_px: 0.5,
117            max_relative_depth_uncertainty: 0.5,
118            hysteresis_ratio: 0.15,
119        }
120    }
121}
122
123/// Stateful memory for adaptive stereo-depth gating.
124#[derive(Debug, Clone, Copy, PartialEq, Default)]
125pub struct StereoDepthGateState {
126    effective_min_depth_m: Option<f64>,
127}
128
129impl StereoDepthGateState {
130    pub const fn reset(&mut self) {
131        self.effective_min_depth_m = None;
132    }
133
134    pub const fn effective_min_depth_m(&self) -> Option<f64> {
135        self.effective_min_depth_m
136    }
137}
138
139/// Per-frame diagnostics emitted by the stereo-depth gate.
140#[derive(Debug, Clone, Copy, PartialEq)]
141pub struct StereoDepthGateDiagnostics {
142    pub adaptive: bool,
143    pub candidate_count: usize,
144    pub accepted_count: usize,
145    pub effective_min_depth_m: f64,
146    pub effective_max_depth_m: f64,
147    pub depth_quantile_m: Option<f64>,
148    pub disparity_uncertainty_min_px: Option<f64>,
149}
150
151/// Configuration for [`triangulate_stereo_features`]. Defaults are tuned for
152/// rectified KITTI imagery.
153#[derive(Debug, Clone, Copy, PartialEq)]
154pub struct StereoFeatureConfig {
155    /// Minimum acceptable disparity (`u_l − u_r`) in pixels. Sub-threshold
156    /// matches indicate either a far-field point (numerically unstable) or
157    /// a wrong correspondence (e.g., a sky pixel). Set on the same scale
158    /// as the descriptor matcher's expected sub-pixel accuracy.
159    pub min_disparity_px: f64,
160    /// Maximum allowed `|v_l − v_r|` row residual in pixels. A non-zero
161    /// row residual on rectified imagery means the match is wrong (or the
162    /// rectification is imperfect); reject so triangulation does not blend
163    /// in a Y-direction error.
164    pub max_row_residual_px: f64,
165    /// Fixed-policy minimum `Z` (depth) accepted in the left camera's frame,
166    /// and the adaptive-policy fallback before enough candidates establish a
167    /// scene scale. Points nearer than this disappear behind / below the
168    /// camera within one frame on a moving vehicle; on room-scale datasets the
169    /// adaptive gate can lower the effective value without changing this A/B
170    /// baseline.
171    pub min_depth_m: f64,
172    /// Maximum `Z` (depth) accepted in the left camera's frame. KITTI sky
173    /// pixels triangulate to `Z ≫ 100 m` because their disparity is at the
174    /// matcher's noise floor — those points are useless for downstream
175    /// pose estimation and inflate landmark counts.
176    pub max_depth_m: f64,
177    /// Lower-depth gate policy. Set to [`StereoDepthGate::Fixed`] to reproduce
178    /// the historical `min_depth_m` behavior exactly.
179    pub depth_gate: StereoDepthGate,
180    /// Lowe's ratio threshold for the row-restricted L↔R descriptor search.
181    /// `Some(0.85)` keeps matches whose best-distance / second-best-distance
182    /// in the same row band is strictly below the threshold. `None`
183    /// disables the ratio check (every left keypoint with a band candidate
184    /// is matched).
185    pub ratio: Option<f64>,
186}
187
188impl Default for StereoFeatureConfig {
189    fn default() -> Self {
190        Self {
191            min_disparity_px: 1.0,
192            max_row_residual_px: 1.5,
193            min_depth_m: 3.0,
194            max_depth_m: 80.0,
195            depth_gate: StereoDepthGate::default(),
196            ratio: Some(0.85),
197        }
198    }
199}
200
201/// Match the left and right [`FeatureSet`]s using the rectified-stereo
202/// epipolar constraint and triangulate every accepted correspondence into a
203/// metric 3D point. Returns one [`StereoFeature`] per match that passes the
204/// [`StereoFeatureConfig`] gates.
205///
206/// Unlike a plain descriptor matcher, this routine restricts each left
207/// keypoint's right-image search to the same row band (`|v_l − v_r| ≤
208/// max_row_residual_px`) and to positive disparity (`u_r < u_l`). Without
209/// the row gate, patch descriptors on KITTI-like imagery routinely match
210/// across rows and produce 3D points consistent with the left view but
211/// wildly wrong in 3D space — those points then poison the downstream PnP.
212/// The gated matcher also runs Lowe's ratio test on the within-band best /
213/// second-best descriptor distance.
214///
215/// The returned points live in the left-camera frame (positive `Z` ahead of
216/// the camera). `baseline` is the rectified-stereo baseline magnitude in
217/// metric units (same units the points come out in).
218pub fn triangulate_stereo_features(
219    left: &FeatureSet,
220    right: &FeatureSet,
221    camera: &Camera,
222    baseline: f64,
223    config: &StereoFeatureConfig,
224) -> Vec<StereoFeature> {
225    triangulate_stereo_features_with_depth_state(left, right, camera, baseline, config, None)
226        .features
227}
228
229fn triangulate_stereo_features_with_depth_state(
230    left: &FeatureSet,
231    right: &FeatureSet,
232    camera: &Camera,
233    baseline: f64,
234    config: &StereoFeatureConfig,
235    state: Option<&mut StereoDepthGateState>,
236) -> StereoDepthGateOutcome {
237    if left.is_empty() || right.is_empty() {
238        return empty_stereo_depth_gate_outcome(config);
239    }
240    let mut candidates: Vec<StereoFeature> = Vec::with_capacity(left.len() / 2);
241    for (l_idx, l_kp) in left.keypoints.iter().enumerate() {
242        let l_desc = &left.descriptors[l_idx];
243        // Row-restricted descriptor search: only consider right keypoints
244        // sharing the left's image row (within max_row_residual_px) and
245        // with positive disparity (u_r < u_l).
246        let mut best: Option<(usize, f64)> = None;
247        let mut second_best: Option<f64> = None;
248        for (r_idx, r_kp) in right.keypoints.iter().enumerate() {
249            if (l_kp.y - r_kp.y).abs() > config.max_row_residual_px {
250                continue;
251            }
252            let disparity = l_kp.x - r_kp.x;
253            if disparity < config.min_disparity_px {
254                continue;
255            }
256            let r_desc = &right.descriptors[r_idx];
257            let dist = descriptor_distance(l_desc, r_desc);
258            match best {
259                None => best = Some((r_idx, dist)),
260                Some((_, b_dist)) if dist < b_dist => {
261                    second_best = Some(b_dist);
262                    best = Some((r_idx, dist));
263                }
264                Some(_) => {
265                    if second_best.is_none_or(|s| dist < s) {
266                        second_best = Some(dist);
267                    }
268                }
269            }
270        }
271        let Some((r_idx, b_dist)) = best else {
272            continue;
273        };
274        // Lowe's ratio test (rectified-stereo variant: only if a runner-up
275        // exists in the same band).
276        if let (Some(s), Some(ratio)) = (second_best, config.ratio) {
277            if s > 0.0 && b_dist / s > ratio {
278                continue;
279            }
280        } else {
281            // Suppress unused-variable warning when ratio is disabled.
282            let _ = b_dist;
283        }
284        let r_kp = right.keypoints[r_idx];
285        let disparity = l_kp.x - r_kp.x;
286        let Some(point) = triangulate_stereo_pixel(
287            camera,
288            baseline,
289            (l_kp.x, l_kp.y),
290            (r_kp.x, r_kp.y),
291            config.min_disparity_px,
292        ) else {
293            continue;
294        };
295        if !point.coords.iter().all(|v| v.is_finite()) {
296            continue;
297        }
298        candidates.push(StereoFeature {
299            left_index: l_idx,
300            right_index: r_idx,
301            disparity,
302            point_cam: point,
303        });
304    }
305    apply_stereo_depth_gate(candidates, config, state)
306}
307
308/// Triangulate explicit rectified-stereo matches into metric 3D points.
309///
310/// This is the file-backed / learned-frontend companion to
311/// [`triangulate_stereo_features`]. It trusts the caller's matcher
312/// (SuperPoint+LightGlue, ONNX, a remote service, etc.) for candidate
313/// association, then applies the same stereo geometry gates: positive
314/// disparity, row residual, finite 3D point, and depth range.
315pub fn triangulate_stereo_feature_matches(
316    left: &FeatureSet,
317    right: &FeatureSet,
318    matches: &[DescriptorMatch],
319    camera: &Camera,
320    baseline: f64,
321    config: &StereoFeatureConfig,
322) -> Vec<StereoFeature> {
323    triangulate_stereo_feature_matches_with_depth_state(
324        left, right, matches, camera, baseline, config, None,
325    )
326    .features
327}
328
329fn triangulate_stereo_feature_matches_with_depth_state(
330    left: &FeatureSet,
331    right: &FeatureSet,
332    matches: &[DescriptorMatch],
333    camera: &Camera,
334    baseline: f64,
335    config: &StereoFeatureConfig,
336    state: Option<&mut StereoDepthGateState>,
337) -> StereoDepthGateOutcome {
338    if left.is_empty() || right.is_empty() || matches.is_empty() {
339        return empty_stereo_depth_gate_outcome(config);
340    }
341
342    let mut candidates = Vec::with_capacity(matches.len());
343    for descriptor_match in matches {
344        let Some(l_kp) = left.keypoints.get(descriptor_match.query_index) else {
345            continue;
346        };
347        let Some(r_kp) = right.keypoints.get(descriptor_match.train_index) else {
348            continue;
349        };
350        if (l_kp.y - r_kp.y).abs() > config.max_row_residual_px {
351            continue;
352        }
353        let disparity = l_kp.x - r_kp.x;
354        if disparity < config.min_disparity_px {
355            continue;
356        }
357        let Some(point) = triangulate_stereo_pixel(
358            camera,
359            baseline,
360            (l_kp.x, l_kp.y),
361            (r_kp.x, r_kp.y),
362            config.min_disparity_px,
363        ) else {
364            continue;
365        };
366        if !point.coords.iter().all(|v| v.is_finite()) {
367            continue;
368        }
369        candidates.push(StereoFeature {
370            left_index: descriptor_match.query_index,
371            right_index: descriptor_match.train_index,
372            disparity,
373            point_cam: point,
374        });
375    }
376    apply_stereo_depth_gate(candidates, config, state)
377}
378
379struct StereoDepthGateOutcome {
380    features: Vec<StereoFeature>,
381    diagnostics: StereoDepthGateDiagnostics,
382}
383
384const fn empty_stereo_depth_gate_outcome(config: &StereoFeatureConfig) -> StereoDepthGateOutcome {
385    StereoDepthGateOutcome {
386        features: Vec::new(),
387        diagnostics: StereoDepthGateDiagnostics {
388            adaptive: false,
389            candidate_count: 0,
390            accepted_count: 0,
391            effective_min_depth_m: config.min_depth_m,
392            effective_max_depth_m: config.max_depth_m,
393            depth_quantile_m: None,
394            disparity_uncertainty_min_px: None,
395        },
396    }
397}
398
399fn apply_stereo_depth_gate(
400    candidates: Vec<StereoFeature>,
401    config: &StereoFeatureConfig,
402    state: Option<&mut StereoDepthGateState>,
403) -> StereoDepthGateOutcome {
404    match config.depth_gate {
405        StereoDepthGate::Fixed => apply_fixed_stereo_depth_gate(candidates, config),
406        StereoDepthGate::Adaptive(adaptive) => {
407            apply_adaptive_stereo_depth_gate(candidates, config, adaptive, state)
408        }
409    }
410}
411
412fn apply_fixed_stereo_depth_gate(
413    candidates: Vec<StereoFeature>,
414    config: &StereoFeatureConfig,
415) -> StereoDepthGateOutcome {
416    let candidate_count = candidates.len();
417    let features: Vec<_> = candidates
418        .into_iter()
419        .filter(|feature| {
420            feature.point_cam.z >= config.min_depth_m && feature.point_cam.z <= config.max_depth_m
421        })
422        .collect();
423    let accepted_count = features.len();
424    StereoDepthGateOutcome {
425        features,
426        diagnostics: StereoDepthGateDiagnostics {
427            adaptive: false,
428            candidate_count,
429            accepted_count,
430            effective_min_depth_m: config.min_depth_m,
431            effective_max_depth_m: config.max_depth_m,
432            depth_quantile_m: None,
433            disparity_uncertainty_min_px: None,
434        },
435    }
436}
437
438fn apply_adaptive_stereo_depth_gate(
439    candidates: Vec<StereoFeature>,
440    config: &StereoFeatureConfig,
441    adaptive: StereoAdaptiveDepthGateConfig,
442    state: Option<&mut StereoDepthGateState>,
443) -> StereoDepthGateOutcome {
444    let candidate_count = candidates.len();
445    let uncertainty_min_disparity_px = adaptive_uncertainty_min_disparity_px(config, &adaptive);
446    let bounded_depths: Vec<f64> = candidates
447        .iter()
448        .filter(|feature| {
449            stereo_candidate_passes_safety_gates(feature, config, uncertainty_min_disparity_px)
450        })
451        .map(|feature| feature.point_cam.z)
452        .collect();
453    let depth_quantile_m = if bounded_depths.len() >= adaptive.min_candidate_count {
454        robust_quantile(&bounded_depths, adaptive.depth_quantile)
455    } else {
456        None
457    };
458    let previous_effective_min_depth_m = state
459        .as_ref()
460        .and_then(|state| state.effective_min_depth_m());
461    let raw_effective_min_depth_m = depth_quantile_m
462        .map(|depth| {
463            let max_effective_min_depth_m = adaptive
464                .max_adaptive_min_depth_m
465                .min(config.max_depth_m)
466                .max(adaptive.min_depth_floor_m);
467            (depth * adaptive.depth_quantile_scale)
468                .clamp(adaptive.min_depth_floor_m, max_effective_min_depth_m)
469        })
470        .or(previous_effective_min_depth_m)
471        .unwrap_or(config.min_depth_m);
472    let effective_min_depth_m = apply_depth_hysteresis(raw_effective_min_depth_m, adaptive, state);
473
474    let features: Vec<_> = candidates
475        .into_iter()
476        .filter(|feature| {
477            stereo_candidate_passes_safety_gates(feature, config, uncertainty_min_disparity_px)
478                && feature.point_cam.z >= effective_min_depth_m
479        })
480        .collect();
481    let accepted_count = features.len();
482    StereoDepthGateOutcome {
483        features,
484        diagnostics: StereoDepthGateDiagnostics {
485            adaptive: depth_quantile_m.is_some(),
486            candidate_count,
487            accepted_count,
488            effective_min_depth_m,
489            effective_max_depth_m: config.max_depth_m,
490            depth_quantile_m,
491            disparity_uncertainty_min_px: Some(uncertainty_min_disparity_px),
492        },
493    }
494}
495
496fn adaptive_uncertainty_min_disparity_px(
497    config: &StereoFeatureConfig,
498    adaptive: &StereoAdaptiveDepthGateConfig,
499) -> f64 {
500    let uncertainty_floor = if adaptive.disparity_noise_px.is_finite()
501        && adaptive.disparity_noise_px > 0.0
502        && adaptive.max_relative_depth_uncertainty.is_finite()
503        && adaptive.max_relative_depth_uncertainty > 0.0
504    {
505        adaptive.disparity_noise_px / adaptive.max_relative_depth_uncertainty
506    } else {
507        config.min_disparity_px
508    };
509    config.min_disparity_px.max(uncertainty_floor)
510}
511
512fn stereo_candidate_passes_safety_gates(
513    feature: &StereoFeature,
514    config: &StereoFeatureConfig,
515    uncertainty_min_disparity_px: f64,
516) -> bool {
517    feature.point_cam.z.is_finite()
518        && feature.point_cam.z > 0.0
519        && feature.point_cam.z <= config.max_depth_m
520        && feature.disparity >= uncertainty_min_disparity_px
521}
522
523fn robust_quantile(values: &[f64], quantile: f64) -> Option<f64> {
524    let mut sorted: Vec<f64> = values.iter().copied().filter(|v| v.is_finite()).collect();
525    if sorted.is_empty() {
526        return None;
527    }
528    sorted.sort_by(|a, b| a.total_cmp(b));
529    let q = quantile.clamp(0.0, 1.0);
530    let rank = ((sorted.len() - 1) as f64 * q).round() as usize;
531    sorted.get(rank).copied()
532}
533
534fn apply_depth_hysteresis(
535    proposed_min_depth_m: f64,
536    adaptive: StereoAdaptiveDepthGateConfig,
537    state: Option<&mut StereoDepthGateState>,
538) -> f64 {
539    let Some(state) = state else {
540        return proposed_min_depth_m;
541    };
542    let Some(previous) = state.effective_min_depth_m else {
543        state.effective_min_depth_m = Some(proposed_min_depth_m);
544        return proposed_min_depth_m;
545    };
546    let ratio = adaptive.hysteresis_ratio.clamp(0.0, 0.95);
547    let lower = previous * (1.0 - ratio);
548    let upper = previous * (1.0 + ratio);
549    let effective = if proposed_min_depth_m >= lower && proposed_min_depth_m <= upper {
550        previous
551    } else {
552        proposed_min_depth_m
553    };
554    state.effective_min_depth_m = Some(effective);
555    effective
556}
557
558/// One pair of metric 3D points (frame `a` and frame `b`) believed to be the
559/// same physical scene point. Used by [`estimate_relative_pose_kabsch_ransac`].
560#[derive(Debug, Clone, PartialEq)]
561pub struct StereoPairCorrespondence {
562    pub a: Point3<f64>,
563    pub b: Point3<f64>,
564    /// Optional temporal-match confidence. Deep matchers such as
565    /// `MutualSoftmaxMatcher` populate this so Kabsch RANSAC can sample
566    /// high-confidence 3D-3D pairs first; classical matchers leave it `None`.
567    pub confidence: Option<f32>,
568}
569
570/// Configuration for [`estimate_relative_pose_kabsch_ransac`].
571#[derive(Debug, Clone, Copy, PartialEq)]
572pub struct KabschRansacConfig {
573    pub iterations: usize,
574    /// Maximum allowed `|X_b − (R·X_a + t)|` per inlier (in metric units).
575    pub inlier_threshold_m: f64,
576    /// Minimum number of inliers for a pose to be accepted. Below this, the
577    /// estimator returns `None`.
578    pub min_inliers: usize,
579    /// Discard correspondences with `Z` (in either frame) above this. Stereo
580    /// noise scales as `Z² · σ_disp / (fx · b)`, so far-field samples are
581    /// unreliable for the metric pose recovery.
582    pub max_depth_m: f64,
583    pub seed: u64,
584}
585
586impl Default for KabschRansacConfig {
587    fn default() -> Self {
588        Self {
589            iterations: 256,
590            inlier_threshold_m: 0.30,
591            min_inliers: 12,
592            max_depth_m: 25.0,
593            seed: 7,
594        }
595    }
596}
597
598/// Output of [`estimate_relative_pose_kabsch_ransac`].
599#[derive(Debug, Clone, PartialEq)]
600pub struct KabschRansacReport {
601    /// `T_a_to_b`: applies as `X_b = relative · X_a` for any matched scene
602    /// point, with `world_to_camera.translation` carrying metric scale.
603    pub relative_pose: Pose,
604    /// Indices into the original `correspondences` slice that fit the
605    /// recovered pose within [`KabschRansacConfig::inlier_threshold_m`].
606    pub inliers: Vec<usize>,
607    pub mean_residual_m: f64,
608}
609
610#[derive(Debug, Clone, Copy, PartialEq, Eq)]
611pub enum StereoRelativePoseSource {
612    Pnp,
613    PnpFallback,
614    Kabsch,
615    KabschFallback,
616}
617
618#[derive(Debug, Clone, PartialEq)]
619pub struct StereoVoPairDiagnostics {
620    pub from_frame: usize,
621    pub to_frame: usize,
622    pub source: StereoRelativePoseSource,
623    pub temporal_match_count: usize,
624    pub temporal_row_gate_px: Option<f64>,
625    pub temporal_confidence_gate: Option<f32>,
626    pub pnp_correspondence_count: usize,
627    pub stereo_pair_correspondence_count: usize,
628    pub inlier_count: usize,
629    pub raw_translation_m: f64,
630    pub raw_rotation_deg: f64,
631    pub translation_m: f64,
632    pub rotation_deg: f64,
633    pub motion_scale_rescued: bool,
634    pub stereo_vertical_aligned: bool,
635    pub translation_direction_rescued: bool,
636    pub rotation_spike_rescued: bool,
637    pub rotation_vector_rescued: bool,
638    pub pnp_mean_reprojection_error_px: Option<f64>,
639    pub kabsch_mean_residual_m: Option<f64>,
640}
641
642/// 3D-3D Kabsch (Procrustes) registration with RANSAC.
643///
644/// Robust to the forward-motion degeneracy that breaks essential-matrix VO
645/// on driving sequences. Each correspondence supplies the same physical
646/// point's metric coordinates in two frames; the metric translation
647/// magnitude is recovered directly from the data with no scale ambiguity.
648///
649/// Three correspondences are the minimum sample (one solves a 3D-3D
650/// alignment up to a one-DoF reflection that the cheirality picker
651/// resolves). 256 iterations find a clean inlier set even when the input
652/// has 50 % outliers.
653pub fn estimate_relative_pose_kabsch_ransac(
654    correspondences: &[StereoPairCorrespondence],
655    config: &KabschRansacConfig,
656) -> Option<KabschRansacReport> {
657    // Pre-filter to within-depth correspondences (stereo accuracy
658    // degrades as Z²).
659    let usable: Vec<usize> = (0..correspondences.len())
660        .filter(|&i| {
661            let c = &correspondences[i];
662            c.a.z > 0.0 && c.b.z > 0.0 && c.a.z <= config.max_depth_m && c.b.z <= config.max_depth_m
663        })
664        .collect();
665    if usable.len() < 3.max(config.min_inliers) {
666        return None;
667    }
668    let mut rng = SmallRng::seed_from_u64(config.seed);
669    let has_confidence = usable.iter().any(|&i| {
670        correspondences[i]
671            .confidence
672            .is_some_and(|w| w.is_finite() && w > 0.0)
673    });
674    let mut ranked = usable.clone();
675    if has_confidence {
676        ranked.sort_by(|&left, &right| {
677            let l = correspondences[left].confidence.unwrap_or(0.0);
678            let r = correspondences[right].confidence.unwrap_or(0.0);
679            r.total_cmp(&l)
680        });
681    }
682    let mut indices = usable;
683    let mut best: Option<(Pose, Vec<usize>, f64)> = None;
684    let threshold_sq = config.inlier_threshold_m * config.inlier_threshold_m;
685    for iter in 0..config.iterations {
686        let sample_indices: Vec<usize> = if has_confidence {
687            let span = ranked.len().saturating_sub(3);
688            let subset_len = 3 + (span * (iter + 1) / config.iterations.max(1));
689            ranked[..subset_len]
690                .choose_multiple(&mut rng, 3)
691                .copied()
692                .collect()
693        } else {
694            indices.shuffle(&mut rng);
695            indices.iter().take(3).copied().collect()
696        };
697        let sample: Vec<&StereoPairCorrespondence> = sample_indices
698            .iter()
699            .map(|&i| &correspondences[i])
700            .collect();
701        let Some(pose) = kabsch_3pt(&sample) else {
702            continue;
703        };
704        let (inliers, sse) = score_pose_3d3d(&pose, correspondences, threshold_sq);
705        let better = best.as_ref().is_none_or(|(_, b_inliers, b_sse)| {
706            inliers.len() > b_inliers.len() || (inliers.len() == b_inliers.len() && sse < *b_sse)
707        });
708        if better {
709            best = Some((pose, inliers, sse));
710        }
711    }
712    let (_, best_inliers, _) = best?;
713    if best_inliers.len() < config.min_inliers {
714        return None;
715    }
716    // Refine on the full inlier set (Kabsch on N≥3 is the closed-form
717    // least-squares solution, no iteration needed).
718    let inlier_corrs: Vec<&StereoPairCorrespondence> =
719        best_inliers.iter().map(|&i| &correspondences[i]).collect();
720    let refined = kabsch_n(&inlier_corrs)?;
721    let (final_inliers, sse) = score_pose_3d3d(&refined, correspondences, threshold_sq);
722    let mean_residual_m = if final_inliers.is_empty() {
723        f64::INFINITY
724    } else {
725        (sse / final_inliers.len() as f64).sqrt()
726    };
727    Some(KabschRansacReport {
728        relative_pose: refined,
729        inliers: final_inliers,
730        mean_residual_m,
731    })
732}
733
734fn kabsch_3pt(samples: &[&StereoPairCorrespondence]) -> Option<Pose> {
735    if samples.len() < 3 {
736        return None;
737    }
738    kabsch_n(samples)
739}
740
741/// Closed-form Kabsch / Procrustes least-squares pose from N matched 3D
742/// pairs. Returns `T_a_to_b` such that `X_b ≈ R·X_a + t`.
743fn kabsch_n(samples: &[&StereoPairCorrespondence]) -> Option<Pose> {
744    let n = samples.len();
745    if n < 3 {
746        return None;
747    }
748    let mut centroid_a = Vector3::<f64>::zeros();
749    let mut centroid_b = Vector3::<f64>::zeros();
750    for c in samples {
751        centroid_a += c.a.coords;
752        centroid_b += c.b.coords;
753    }
754    centroid_a /= n as f64;
755    centroid_b /= n as f64;
756    let mut h = Matrix3::<f64>::zeros();
757    for c in samples {
758        let a = c.a.coords - centroid_a;
759        let b = c.b.coords - centroid_b;
760        h += a * b.transpose();
761    }
762    let svd = h.try_svd(true, true, f64::EPSILON * 5.0, 10_000)?;
763    let u = svd.u?;
764    let v_t = svd.v_t?;
765    let v = v_t.transpose();
766    let mut s = Matrix3::<f64>::identity();
767    let det = (v * u.transpose()).determinant();
768    if det < 0.0 {
769        s[(2, 2)] = -1.0;
770    }
771    let r_mat = v * s * u.transpose();
772    let translation = centroid_b - r_mat * centroid_a;
773    let rotation = rotation_from_orthonormal(&r_mat);
774    Some(Pose::from_world_to_camera(rotation, translation))
775}
776
777/// `UnitQuaternion::from_matrix(r_mat)` without its hang on a half-turn
778/// RANSAC hypothesis; see [`visloc_core::geometry::rotation_from_matrix`].
779fn rotation_from_orthonormal(r_mat: &Matrix3<f64>) -> UnitQuaternion<f64> {
780    visloc_core::geometry::rotation_from_matrix(r_mat)
781}
782
783fn score_pose_3d3d(
784    pose: &Pose,
785    correspondences: &[StereoPairCorrespondence],
786    threshold_sq: f64,
787) -> (Vec<usize>, f64) {
788    let r_mat = pose
789        .world_to_camera
790        .rotation
791        .to_rotation_matrix()
792        .into_inner();
793    let t = pose.world_to_camera.translation;
794    let mut inliers = Vec::new();
795    let mut sse = 0.0;
796    for (i, c) in correspondences.iter().enumerate() {
797        let predicted = r_mat * c.a.coords + t;
798        let residual = c.b.coords - predicted;
799        let err_sq = residual.dot(&residual);
800        if err_sq <= threshold_sq {
801            inliers.push(i);
802            sse += err_sq;
803        }
804    }
805    (inliers, sse)
806}
807
808/// Build [`StereoPairCorrespondence`]s by joining the per-frame
809/// triangulations on temporal descriptor matches: each match links a left
810/// keypoint at frame `a` to a left keypoint at frame `b`; if both have a
811/// stereo triangulation the pair contributes one 3D-3D correspondence.
812pub fn stereo_pair_correspondences(
813    a_features: &[StereoFeature],
814    b_features: &[StereoFeature],
815    temporal_matches: &[DescriptorMatch],
816) -> Vec<StereoPairCorrespondence> {
817    if a_features.is_empty() || b_features.is_empty() || temporal_matches.is_empty() {
818        return Vec::new();
819    }
820    let a_lookup: HashMap<usize, &StereoFeature> =
821        a_features.iter().map(|f| (f.left_index, f)).collect();
822    let b_lookup: HashMap<usize, &StereoFeature> =
823        b_features.iter().map(|f| (f.left_index, f)).collect();
824    let mut out: Vec<StereoPairCorrespondence> = Vec::with_capacity(temporal_matches.len());
825    for m in temporal_matches {
826        let (Some(sa), Some(sb)) = (a_lookup.get(&m.query_index), b_lookup.get(&m.train_index))
827        else {
828            continue;
829        };
830        out.push(StereoPairCorrespondence {
831            a: sa.point_cam,
832            b: sb.point_cam,
833            confidence: m.confidence,
834        });
835    }
836    out
837}
838
839/// One observation contributed by a multi-frame [`StereoTrack`].
840#[derive(Debug, Clone, PartialEq)]
841pub struct StereoTrackObservation {
842    pub frame_index: usize,
843    pub left_index: usize,
844    pub right_index: usize,
845}
846
847/// One multi-frame stereo track: a single landmark's world-frame position
848/// (anchored from the seed frame's stereo triangulation, lifted into world
849/// using the seed frame's pose) plus its observations across one or more
850/// frames. Produced by [`extend_stereo_tracks_via_projection`].
851#[derive(Debug, Clone, PartialEq)]
852pub struct StereoTrack {
853    pub landmark_world: Point3<f64>,
854    pub observations: Vec<StereoTrackObservation>,
855}
856
857/// Configuration for [`extend_stereo_tracks_via_projection`]. Defaults are
858/// tuned for KITTI-scale per-frame motion (~1 m/frame at stride 1, ~7 m/frame
859/// at stride 8) and the project's `CornerFeatureExtractor` descriptor scale.
860#[derive(Debug, Clone, Copy, PartialEq)]
861pub struct TrackExtensionConfig {
862    /// Maximum image-pixel distance from the projected landmark within
863    /// which to look for a matching keypoint at the next frame. Has to be
864    /// generous enough to cover VO pose noise + reprojection error from
865    /// per-frame stereo-triangulation inaccuracy, but small enough to keep
866    /// the descriptor search discriminative — `25 px` works on KITTI 00.
867    pub search_radius_px: f64,
868    /// Lowe's ratio test on the within-radius descriptor search. The best
869    /// match's descriptor distance must be below this fraction of the
870    /// second best's, otherwise the track ends.
871    pub ratio: f64,
872    /// Tracks may extend by this many frames past their seed before being
873    /// force-cut. Without a cap, tracks that follow distant landmarks can
874    /// span ~all frames at the cost of a quadratic match. `30` is a
875    /// reasonable upper bound for stride-1 KITTI windows.
876    pub max_extension: usize,
877    /// Each `(frame, left_kp_index)` is consumed by at most one track —
878    /// once a feature has been added to a longer track its later
879    /// re-seeding as a new track is suppressed. Set `false` to allow
880    /// overlapping tracks (rarely useful).
881    pub deduplicate: bool,
882}
883
884impl Default for TrackExtensionConfig {
885    fn default() -> Self {
886        Self {
887            search_radius_px: 25.0,
888            ratio: 0.8,
889            max_extension: 30,
890            deduplicate: true,
891        }
892    }
893}
894
895/// Build multi-frame stereo tracks by projecting each frame's stereo
896/// triangulations forward through subsequent VO poses and searching for
897/// descriptor-matching stereo features near the predicted pixel.
898///
899/// Why projection-guided rather than chained brute-force matching: KITTI's
900/// per-frame motion takes individual features out of the camera's FOV
901/// quickly (≤ 4 frames at stride 8), and the brute-force matcher between
902/// `left_i ↔ left_(i+1)` does not transitively reuse the same `left_(i+1)`
903/// keypoint across `(i → i+1)` and `(i+1 → i+2)`. Projecting the landmark
904/// through the next pose narrows the search to a small image patch and
905/// allows the same physical point to be re-identified across many frames,
906/// which is what gives the bundle adjuster the long-baseline constraints
907/// needed to attack rotation drift.
908pub fn extend_stereo_tracks_via_projection(
909    poses: &[Pose],
910    left_features: &[FeatureSet],
911    stereo_per_frame: &[Vec<StereoFeature>],
912    camera: &Camera,
913    config: &TrackExtensionConfig,
914) -> Vec<StereoTrack> {
915    let n = poses.len();
916    if n < 2 || left_features.len() < n || stereo_per_frame.len() < n {
917        return Vec::new();
918    }
919    // Per-frame: index every stereo triangulation by its left keypoint id
920    // so projection-based extension can ask "is there a stereo feature at
921    // keypoint k of frame j?" in O(1).
922    let stereo_lookup: Vec<HashMap<usize, &StereoFeature>> = stereo_per_frame
923        .iter()
924        .map(|sf| sf.iter().map(|f| (f.left_index, f)).collect())
925        .collect();
926    let mut consumed: Vec<std::collections::HashSet<usize>> =
927        (0..n).map(|_| std::collections::HashSet::new()).collect();
928    let mut out: Vec<StereoTrack> = Vec::new();
929
930    for seed_frame in 0..n - 1 {
931        let pose_seed = &poses[seed_frame];
932        let r_inv = pose_seed.world_to_camera.rotation.inverse();
933        let t_seed = pose_seed.world_to_camera.translation;
934        for stereo in &stereo_per_frame[seed_frame] {
935            if config.deduplicate && consumed[seed_frame].contains(&stereo.left_index) {
936                continue;
937            }
938            let landmark_w =
939                nalgebra::Point3::from(r_inv.transform_vector(&(stereo.point_cam.coords - t_seed)));
940            let descriptor = left_features[seed_frame].descriptors[stereo.left_index].clone();
941            let mut observations: Vec<StereoTrackObservation> = vec![StereoTrackObservation {
942                frame_index: seed_frame,
943                left_index: stereo.left_index,
944                right_index: stereo.right_index,
945            }];
946            let extension_cap = (seed_frame + config.max_extension).min(n - 1);
947            for next_frame in seed_frame + 1..=extension_cap {
948                let pose_next = &poses[next_frame];
949                let xc = pose_next.transform_world_point(&landmark_w);
950                if xc.z <= 0.0 {
951                    break;
952                }
953                let Some(predicted) = camera.project(&xc) else {
954                    break;
955                };
956                if predicted.x < 0.0
957                    || predicted.x >= camera.width as f64
958                    || predicted.y < 0.0
959                    || predicted.y >= camera.height as f64
960                {
961                    break;
962                }
963                // Within-radius descriptor search constrained to keypoints
964                // that have a stereo triangulation (otherwise the
965                // landmark's BA observation is incomplete and the track
966                // cannot contribute a stereo residual).
967                let mut best: Option<(usize, f64)> = None;
968                let mut second_best: Option<f64> = None;
969                let radius_sq = config.search_radius_px * config.search_radius_px;
970                for (kp_idx, kp) in left_features[next_frame].keypoints.iter().enumerate() {
971                    let dx = kp.x - predicted.x;
972                    let dy = kp.y - predicted.y;
973                    if dx * dx + dy * dy > radius_sq {
974                        continue;
975                    }
976                    if !stereo_lookup[next_frame].contains_key(&kp_idx) {
977                        continue;
978                    }
979                    if config.deduplicate && consumed[next_frame].contains(&kp_idx) {
980                        continue;
981                    }
982                    let dist = descriptor_distance(
983                        &descriptor,
984                        &left_features[next_frame].descriptors[kp_idx],
985                    );
986                    match best {
987                        None => best = Some((kp_idx, dist)),
988                        Some((_, b_dist)) if dist < b_dist => {
989                            second_best = Some(b_dist);
990                            best = Some((kp_idx, dist));
991                        }
992                        Some(_) => {
993                            if second_best.is_none_or(|s| dist < s) {
994                                second_best = Some(dist);
995                            }
996                        }
997                    }
998                }
999                let Some((kp_idx, b_dist)) = best else {
1000                    break;
1001                };
1002                if let Some(s) = second_best {
1003                    if s > 0.0 && b_dist / s > config.ratio {
1004                        break;
1005                    }
1006                }
1007                let stereo_next = stereo_lookup[next_frame][&kp_idx];
1008                observations.push(StereoTrackObservation {
1009                    frame_index: next_frame,
1010                    left_index: kp_idx,
1011                    right_index: stereo_next.right_index,
1012                });
1013            }
1014            if observations.len() >= 2 {
1015                if config.deduplicate {
1016                    for obs in &observations {
1017                        consumed[obs.frame_index].insert(obs.left_index);
1018                    }
1019                }
1020                out.push(StereoTrack {
1021                    landmark_world: landmark_w,
1022                    observations,
1023                });
1024            }
1025        }
1026    }
1027    out
1028}
1029
1030fn descriptor_distance(a: &[f32], b: &[f32]) -> f64 {
1031    let mut sum = 0.0;
1032    let len = a.len().min(b.len());
1033    for i in 0..len {
1034        let d = (a[i] - b[i]) as f64;
1035        sum += d * d;
1036    }
1037    sum
1038}
1039
1040/// Build 2D-3D correspondences for PnP between two consecutive frames, using
1041/// frame-`a`'s stereo triangulations and frame-`b`'s left features.
1042///
1043/// `temporal_matches` is the descriptor matcher's output of `left_a → left_b`.
1044/// Only matches whose query keypoint also has a triangulated stereo feature
1045/// in `a_features` are kept; the resulting [`Correspondence2D3D`] pairs the
1046/// 3D point (in `a`'s left-camera frame) with the 2D pixel in `b`'s left
1047/// image.
1048///
1049/// The PnP solver then recovers `T_a_to_b` directly: feed the result into
1050/// `PnPRansac::estimate` with `b_left`'s keypoints as the 2D side.
1051pub fn build_stereo_temporal_correspondences(
1052    a_features: &[StereoFeature],
1053    b_left: &FeatureSet,
1054    temporal_matches: &[crate::matching::DescriptorMatch],
1055) -> Vec<Correspondence2D3D> {
1056    if a_features.is_empty() || b_left.is_empty() || temporal_matches.is_empty() {
1057        return Vec::new();
1058    }
1059    // Index a_features by their left-keypoint index for O(1) lookup.
1060    let mut a_by_left_idx: HashMap<usize, &StereoFeature> =
1061        HashMap::with_capacity(a_features.len());
1062    for f in a_features {
1063        a_by_left_idx.insert(f.left_index, f);
1064    }
1065    let mut out: Vec<Correspondence2D3D> = Vec::with_capacity(temporal_matches.len());
1066    for m in temporal_matches {
1067        let Some(stereo) = a_by_left_idx.get(&m.query_index) else {
1068            continue;
1069        };
1070        let b_kp = b_left.keypoints[m.train_index];
1071        out.push(Correspondence2D3D {
1072            point2d: b_kp,
1073            point3d: stereo.point_cam,
1074            confidence: m.confidence,
1075        });
1076    }
1077    out
1078}
1079
1080#[derive(Debug, Clone, PartialEq)]
1081struct PnpSelectedReport {
1082    pose: Pose,
1083    inlier_count: usize,
1084    mean_reprojection_error: f64,
1085    correspondence_count: usize,
1086}
1087
1088#[derive(Debug, Clone, Copy, PartialEq)]
1089struct PnpFullScore {
1090    inlier_count: usize,
1091    mean_error: f64,
1092}
1093
1094#[derive(Debug, Clone, Copy, PartialEq)]
1095struct Pose3d3dScore {
1096    inlier_count: usize,
1097    mean_residual_m: f64,
1098}
1099
1100// Each parameter is an independent PnP/depth-hypothesis knob; positional args
1101// stay closer to the math than an ad-hoc bundling struct would.
1102#[allow(clippy::too_many_arguments)]
1103fn estimate_pnp_with_depth_hypotheses(
1104    pnp: &PnPRansac,
1105    all_corrs: &[Correspondence2D3D],
1106    camera: &Camera,
1107    min_inliers: usize,
1108    primary_max_depth_m: Option<f64>,
1109    depth_hypotheses_m: &[f64],
1110    adaptive_depth_hypothesis_m: Option<f64>,
1111    adaptive_depth_min_primary_inlier_ratio: f64,
1112) -> Option<PnpSelectedReport> {
1113    let primary_depth = primary_max_depth_m.filter(|d| d.is_finite() && *d > 0.0);
1114    let mut best: Option<PnpSelectedReport> = None;
1115    let mut best_score: Option<PnpFullScore> = None;
1116
1117    update_best_pnp_depth_candidate(
1118        pnp,
1119        all_corrs,
1120        camera,
1121        min_inliers,
1122        primary_depth,
1123        &mut best,
1124        &mut best_score,
1125    );
1126
1127    let mut candidate_depths = pnp_candidate_depths(primary_max_depth_m, depth_hypotheses_m);
1128    if depth_hypotheses_m.is_empty()
1129        && should_try_adaptive_pnp_depth(
1130            best_score.as_ref(),
1131            all_corrs.len(),
1132            adaptive_depth_min_primary_inlier_ratio,
1133        )
1134    {
1135        if let Some(adaptive_depth_m) =
1136            adaptive_depth_hypothesis_m.filter(|d| d.is_finite() && *d > 0.0)
1137        {
1138            let candidate = Some(adaptive_depth_m);
1139            if !candidate_depths
1140                .iter()
1141                .any(|existing| same_optional_depth(*existing, candidate))
1142            {
1143                candidate_depths.push(candidate);
1144            }
1145        }
1146    }
1147
1148    for max_depth_m in candidate_depths {
1149        if same_optional_depth(max_depth_m, primary_depth) {
1150            continue;
1151        }
1152        update_best_pnp_depth_candidate(
1153            pnp,
1154            all_corrs,
1155            camera,
1156            min_inliers,
1157            max_depth_m,
1158            &mut best,
1159            &mut best_score,
1160        );
1161    }
1162    best
1163}
1164
1165fn update_best_pnp_depth_candidate(
1166    pnp: &PnPRansac,
1167    all_corrs: &[Correspondence2D3D],
1168    camera: &Camera,
1169    min_inliers: usize,
1170    max_depth_m: Option<f64>,
1171    best: &mut Option<PnpSelectedReport>,
1172    best_score: &mut Option<PnpFullScore>,
1173) {
1174    let corrs = pnp_correspondences_for_depth(all_corrs, max_depth_m);
1175    let weights: Vec<f32> = corrs.iter().map(|c| c.confidence.unwrap_or(0.0)).collect();
1176    let Some(report) = estimate_pnp_candidate(pnp, &corrs, camera, &weights) else {
1177        return;
1178    };
1179    if report.inliers.len() < min_inliers {
1180        return;
1181    }
1182    let full_score = score_pnp_pose_on_correspondences(
1183        &report.pose,
1184        all_corrs,
1185        camera,
1186        pnp.reprojection_threshold,
1187    );
1188    if full_score.inlier_count < min_inliers {
1189        return;
1190    }
1191    let better = best_score
1192        .as_ref()
1193        .is_none_or(|score| is_pnp_candidate_better(&full_score, score));
1194    if better {
1195        *best_score = Some(full_score);
1196        *best = Some(PnpSelectedReport {
1197            pose: report.pose,
1198            inlier_count: full_score.inlier_count,
1199            mean_reprojection_error: full_score.mean_error,
1200            correspondence_count: corrs.len(),
1201        });
1202    }
1203}
1204
1205fn should_try_adaptive_pnp_depth(
1206    primary_score: Option<&PnpFullScore>,
1207    total_correspondences: usize,
1208    min_primary_inlier_ratio: f64,
1209) -> bool {
1210    if total_correspondences == 0
1211        || !min_primary_inlier_ratio.is_finite()
1212        || min_primary_inlier_ratio <= 0.0
1213    {
1214        return false;
1215    }
1216    let Some(primary_score) = primary_score else {
1217        return true;
1218    };
1219    let primary_ratio = primary_score.inlier_count as f64 / total_correspondences as f64;
1220    primary_ratio < min_primary_inlier_ratio
1221}
1222
1223fn pnp_candidate_depths(
1224    primary_max_depth_m: Option<f64>,
1225    depth_hypotheses_m: &[f64],
1226) -> Vec<Option<f64>> {
1227    let mut depths = Vec::new();
1228    depths.push(primary_max_depth_m.filter(|d| d.is_finite() && *d > 0.0));
1229    for &depth in depth_hypotheses_m {
1230        if !depth.is_finite() || depth <= 0.0 {
1231            continue;
1232        }
1233        let candidate = Some(depth);
1234        if !depths
1235            .iter()
1236            .any(|existing| same_optional_depth(*existing, candidate))
1237        {
1238            depths.push(candidate);
1239        }
1240    }
1241    depths
1242}
1243
1244fn same_optional_depth(a: Option<f64>, b: Option<f64>) -> bool {
1245    match (a, b) {
1246        (None, None) => true,
1247        (Some(a), Some(b)) => (a - b).abs() <= 1.0e-9,
1248        _ => false,
1249    }
1250}
1251
1252fn pnp_correspondences_for_depth(
1253    all_corrs: &[Correspondence2D3D],
1254    max_depth_m: Option<f64>,
1255) -> Vec<Correspondence2D3D> {
1256    match max_depth_m {
1257        Some(max_depth_m) => all_corrs
1258            .iter()
1259            .filter(|corr| corr.point3d.z <= max_depth_m)
1260            .cloned()
1261            .collect(),
1262        None => all_corrs.to_vec(),
1263    }
1264}
1265
1266fn estimate_pnp_candidate(
1267    pnp: &PnPRansac,
1268    corrs: &[Correspondence2D3D],
1269    camera: &Camera,
1270    weights: &[f32],
1271) -> Option<crate::ransac::RansacReport> {
1272    if weights.iter().any(|w| w.is_finite() && *w > 0.0) {
1273        pnp.estimate_with_weights(corrs, camera, weights)
1274    } else {
1275        pnp.estimate(corrs, camera)
1276    }
1277}
1278
1279fn score_pnp_pose_on_correspondences(
1280    pose: &Pose,
1281    corrs: &[Correspondence2D3D],
1282    camera: &Camera,
1283    threshold_px: f64,
1284) -> PnpFullScore {
1285    let mut inlier_count = 0usize;
1286    let mut error_sum = 0.0;
1287    for corr in corrs {
1288        let projected_point = pose.transform_world_point(&corr.point3d);
1289        let Some(projected) = camera.project(&projected_point) else {
1290            continue;
1291        };
1292        let err = (projected - corr.point2d).norm();
1293        if err <= threshold_px {
1294            inlier_count += 1;
1295            error_sum += err;
1296        }
1297    }
1298    let mean_error = if inlier_count == 0 {
1299        f64::INFINITY
1300    } else {
1301        error_sum / inlier_count as f64
1302    };
1303    PnpFullScore {
1304        inlier_count,
1305        mean_error,
1306    }
1307}
1308
1309fn is_pnp_candidate_better(candidate: &PnpFullScore, baseline: &PnpFullScore) -> bool {
1310    candidate.inlier_count > baseline.inlier_count
1311        || (candidate.inlier_count == baseline.inlier_count
1312            && candidate.mean_error + 1.0e-9 < baseline.mean_error)
1313}
1314
1315fn score_pose_on_stereo_pairs(
1316    pose: &Pose,
1317    correspondences: &[StereoPairCorrespondence],
1318    inlier_threshold_m: f64,
1319) -> Pose3d3dScore {
1320    if correspondences.is_empty() || !inlier_threshold_m.is_finite() || inlier_threshold_m <= 0.0 {
1321        return Pose3d3dScore {
1322            inlier_count: 0,
1323            mean_residual_m: f64::INFINITY,
1324        };
1325    }
1326    let (inliers, sse) = score_pose_3d3d(pose, correspondences, inlier_threshold_m.powi(2));
1327    let mean_residual_m = if inliers.is_empty() {
1328        f64::INFINITY
1329    } else {
1330        (sse / inliers.len() as f64).sqrt()
1331    };
1332    Pose3d3dScore {
1333        inlier_count: inliers.len(),
1334        mean_residual_m,
1335    }
1336}
1337
1338fn should_try_kabsch_challenger(
1339    pnp_report: &PnpSelectedReport,
1340    config: &StereoVoFrontendConfig,
1341) -> bool {
1342    if pnp_report.correspondence_count == 0 {
1343        return true;
1344    }
1345    if !config.pnp_kabsch_challenge_max_inlier_ratio.is_finite()
1346        || config.pnp_kabsch_challenge_max_inlier_ratio <= 0.0
1347    {
1348        return false;
1349    }
1350    let ratio = pnp_report.inlier_count as f64 / pnp_report.correspondence_count as f64;
1351    ratio < config.pnp_kabsch_challenge_max_inlier_ratio
1352}
1353
1354fn is_kabsch_challenger_better(
1355    kabsch_report: &KabschRansacReport,
1356    pnp_stereo_score: Pose3d3dScore,
1357    config: &StereoVoFrontendConfig,
1358) -> bool {
1359    if kabsch_report.inliers.len()
1360        < pnp_stereo_score
1361            .inlier_count
1362            .saturating_add(config.pnp_kabsch_challenge_min_3d_inlier_gain)
1363    {
1364        return false;
1365    }
1366    if !pnp_stereo_score.mean_residual_m.is_finite() {
1367        return true;
1368    }
1369    kabsch_report.mean_residual_m
1370        <= pnp_stereo_score.mean_residual_m * config.pnp_kabsch_challenge_max_residual_ratio
1371}
1372
1373fn filter_temporal_matches_by_row_delta(
1374    a_left: &FeatureSet,
1375    b_left: &FeatureSet,
1376    temporal_matches: &[DescriptorMatch],
1377    max_row_delta_px: f64,
1378) -> Vec<DescriptorMatch> {
1379    if !max_row_delta_px.is_finite() || max_row_delta_px <= 0.0 {
1380        return temporal_matches.to_vec();
1381    }
1382    temporal_matches
1383        .iter()
1384        .filter(|m| {
1385            let Some(a_kp) = a_left.keypoints.get(m.query_index) else {
1386                return false;
1387            };
1388            let Some(b_kp) = b_left.keypoints.get(m.train_index) else {
1389                return false;
1390            };
1391            (a_kp.y - b_kp.y).abs() <= max_row_delta_px
1392        })
1393        .cloned()
1394        .collect()
1395}
1396
1397fn filter_temporal_matches_by_confidence(
1398    temporal_matches: &[DescriptorMatch],
1399    min_confidence: f32,
1400) -> Vec<DescriptorMatch> {
1401    if !min_confidence.is_finite() || min_confidence <= 0.0 {
1402        return temporal_matches.to_vec();
1403    }
1404    if !temporal_matches
1405        .iter()
1406        .any(|m| m.confidence.is_some_and(|c| c.is_finite()))
1407    {
1408        return temporal_matches.to_vec();
1409    }
1410    temporal_matches
1411        .iter()
1412        .filter(|m| {
1413            m.confidence
1414                .is_some_and(|confidence| confidence.is_finite() && confidence >= min_confidence)
1415        })
1416        .cloned()
1417        .collect()
1418}
1419
1420fn effective_temporal_max_row_delta_px(
1421    translation_history_m: &[f64],
1422    config: &StereoVoFrontendConfig,
1423) -> Option<f64> {
1424    if let Some(max_row_delta_px) = config.temporal_max_row_delta_px {
1425        return finite_positive(max_row_delta_px);
1426    }
1427    let auto_max = finite_positive(config.temporal_auto_max_row_delta_px?)?;
1428    if translation_history_m.len() < config.temporal_auto_min_history {
1429        return None;
1430    }
1431    let recent_median =
1432        recent_translation_median(translation_history_m, config.temporal_auto_min_history)?;
1433    if recent_median >= config.temporal_auto_min_median_translation_m {
1434        Some(auto_max)
1435    } else {
1436        None
1437    }
1438}
1439
1440fn effective_temporal_min_confidence(
1441    translation_history_m: &[f64],
1442    rotation_history_deg: &[f64],
1443    config: &StereoVoFrontendConfig,
1444) -> Option<f32> {
1445    let min_confidence = config.temporal_auto_min_confidence?;
1446    if !min_confidence.is_finite() || min_confidence <= 0.0 {
1447        return None;
1448    }
1449    if translation_history_m.len() < config.temporal_auto_confidence_min_history {
1450        return None;
1451    }
1452    let recent_translation_median = recent_translation_median(
1453        translation_history_m,
1454        config.temporal_auto_confidence_min_history,
1455    )?;
1456    let max_rotation_deg = config
1457        .temporal_auto_confidence_max_median_rotation_deg
1458        .and_then(finite_positive);
1459    let needs_rotation_median = max_rotation_deg.is_some()
1460        || config
1461            .temporal_auto_confidence_curve_min_median_translation_m
1462            .and_then(finite_positive)
1463            .is_some()
1464        || config
1465            .temporal_auto_confidence_curve_min_median_rotation_deg
1466            .and_then(finite_positive)
1467            .is_some();
1468    let recent_rotation_median = if needs_rotation_median {
1469        if rotation_history_deg.len() < config.temporal_auto_confidence_min_history {
1470            return None;
1471        }
1472        Some(recent_positive_median(
1473            rotation_history_deg,
1474            config.temporal_auto_confidence_min_history,
1475        )?)
1476    } else {
1477        None
1478    };
1479    if recent_translation_median >= config.temporal_auto_confidence_min_median_translation_m
1480        && max_rotation_deg
1481            .is_none_or(|max| recent_rotation_median.is_some_and(|rotation| rotation <= max))
1482    {
1483        return Some(min_confidence);
1484    }
1485    let curve_min_translation_m = config
1486        .temporal_auto_confidence_curve_min_median_translation_m
1487        .and_then(finite_positive)?;
1488    let curve_min_rotation_deg = config
1489        .temporal_auto_confidence_curve_min_median_rotation_deg
1490        .and_then(finite_positive)?;
1491    if recent_translation_median < curve_min_translation_m {
1492        return None;
1493    }
1494    let recent_rotation_median = recent_rotation_median?;
1495    if recent_rotation_median < curve_min_rotation_deg {
1496        return None;
1497    }
1498    if max_rotation_deg.is_some_and(|max| recent_rotation_median > max) {
1499        return None;
1500    }
1501    Some(min_confidence)
1502}
1503
1504fn finite_positive(value: f64) -> Option<f64> {
1505    if value.is_finite() && value > 0.0 {
1506        Some(value)
1507    } else {
1508        None
1509    }
1510}
1511
1512#[derive(Debug, Clone, PartialEq)]
1513struct StereoPoseObservation {
1514    point_prev: Point3<f64>,
1515    left_px: Point2<f64>,
1516    right_px: Point2<f64>,
1517}
1518
1519// Stereo-temporal observation inputs (prev/current stereo, left/right features,
1520// matches, camera) are passed positionally to mirror `stereo_pose_observations`.
1521#[allow(clippy::too_many_arguments)]
1522fn refine_relative_pose_with_current_stereo(
1523    initial_pose: &Pose,
1524    prev_stereo: &[StereoFeature],
1525    current_stereo: &[StereoFeature],
1526    current_left: &FeatureSet,
1527    current_right: &FeatureSet,
1528    temporal_matches: &[DescriptorMatch],
1529    camera: &Camera,
1530    baseline: f64,
1531    max_initial_left_error_px: f64,
1532) -> Option<Pose> {
1533    let observations = stereo_pose_observations(
1534        initial_pose,
1535        prev_stereo,
1536        current_stereo,
1537        current_left,
1538        current_right,
1539        temporal_matches,
1540        camera,
1541        max_initial_left_error_px,
1542    );
1543    if observations.len() < 12 {
1544        return None;
1545    }
1546    refine_pose_stereo_reprojection(initial_pose, &observations, camera, baseline)
1547}
1548
1549// Stereo-temporal observation inputs are passed positionally; bundling them
1550// would not group more cohesively than this single call site.
1551#[allow(clippy::too_many_arguments)]
1552fn stereo_pose_observations(
1553    initial_pose: &Pose,
1554    prev_stereo: &[StereoFeature],
1555    current_stereo: &[StereoFeature],
1556    current_left: &FeatureSet,
1557    current_right: &FeatureSet,
1558    temporal_matches: &[DescriptorMatch],
1559    camera: &Camera,
1560    max_initial_left_error_px: f64,
1561) -> Vec<StereoPoseObservation> {
1562    let prev_lookup: HashMap<usize, &StereoFeature> =
1563        prev_stereo.iter().map(|f| (f.left_index, f)).collect();
1564    let current_lookup: HashMap<usize, &StereoFeature> =
1565        current_stereo.iter().map(|f| (f.left_index, f)).collect();
1566    let mut observations = Vec::new();
1567    for m in temporal_matches {
1568        let (Some(prev), Some(curr)) = (
1569            prev_lookup.get(&m.query_index),
1570            current_lookup.get(&m.train_index),
1571        ) else {
1572            continue;
1573        };
1574        let left_px = current_left.keypoints[m.train_index];
1575        let right_px = current_right.keypoints[curr.right_index];
1576        let Some(projected) = camera.project(&initial_pose.transform_world_point(&prev.point_cam))
1577        else {
1578            continue;
1579        };
1580        if (projected - left_px).norm() > max_initial_left_error_px {
1581            continue;
1582        }
1583        observations.push(StereoPoseObservation {
1584            point_prev: prev.point_cam,
1585            left_px,
1586            right_px,
1587        });
1588    }
1589    observations
1590}
1591
1592fn refine_pose_stereo_reprojection(
1593    initial_pose: &Pose,
1594    observations: &[StereoPoseObservation],
1595    camera: &Camera,
1596    baseline: f64,
1597) -> Option<Pose> {
1598    let mut pose = initial_pose.clone();
1599    let mut best_error =
1600        stereo_reprojection_mean_squared_error(&pose, observations, camera, baseline)?;
1601    for _ in 0..6 {
1602        let residual = stereo_reprojection_residual(&pose, observations, camera, baseline)?;
1603        let jacobian = stereo_translation_jacobian(&pose, observations, camera, baseline, 1.0e-6)?;
1604        let j_t = jacobian.transpose();
1605        let mut hessian = &j_t * &jacobian;
1606        for diagonal in 0..hessian.nrows().min(hessian.ncols()) {
1607            hessian[(diagonal, diagonal)] += 1.0e-5;
1608        }
1609        let gradient = &j_t * residual;
1610        let step = hessian.lu().solve(&(-gradient))?;
1611        if !step.iter().all(|value| value.is_finite()) {
1612            return Some(pose);
1613        }
1614        let candidate = perturb_stereo_translation(&pose, &step);
1615        let Some(candidate_error) =
1616            stereo_reprojection_mean_squared_error(&candidate, observations, camera, baseline)
1617        else {
1618            break;
1619        };
1620        if candidate_error + 1.0e-9 >= best_error {
1621            break;
1622        }
1623        pose = candidate;
1624        best_error = candidate_error;
1625    }
1626    Some(pose)
1627}
1628
1629fn stereo_reprojection_mean_squared_error(
1630    pose: &Pose,
1631    observations: &[StereoPoseObservation],
1632    camera: &Camera,
1633    baseline: f64,
1634) -> Option<f64> {
1635    let residual = stereo_reprojection_residual(pose, observations, camera, baseline)?;
1636    Some(residual.norm_squared() / observations.len() as f64)
1637}
1638
1639fn stereo_reprojection_residual(
1640    pose: &Pose,
1641    observations: &[StereoPoseObservation],
1642    camera: &Camera,
1643    baseline: f64,
1644) -> Option<DVector<f64>> {
1645    let mut residual = DVector::<f64>::zeros(observations.len() * 4);
1646    for (index, obs) in observations.iter().enumerate() {
1647        let point_left = pose.transform_world_point(&obs.point_prev);
1648        let left_projected = camera.project(&point_left)?;
1649        let right_projected = camera.project(&Point3::new(
1650            point_left.x - baseline,
1651            point_left.y,
1652            point_left.z,
1653        ))?;
1654        let offset = index * 4;
1655        residual[offset] = left_projected.x - obs.left_px.x;
1656        residual[offset + 1] = left_projected.y - obs.left_px.y;
1657        residual[offset + 2] = right_projected.x - obs.right_px.x;
1658        residual[offset + 3] = right_projected.y - obs.right_px.y;
1659    }
1660    Some(residual)
1661}
1662
1663fn stereo_translation_jacobian(
1664    pose: &Pose,
1665    observations: &[StereoPoseObservation],
1666    camera: &Camera,
1667    baseline: f64,
1668    epsilon: f64,
1669) -> Option<DMatrix<f64>> {
1670    let base = stereo_reprojection_residual(pose, observations, camera, baseline)?;
1671    let mut jacobian = DMatrix::<f64>::zeros(base.len(), 3);
1672    for parameter_index in 0..3 {
1673        let mut delta = DVector::<f64>::zeros(3);
1674        delta[parameter_index] = epsilon;
1675        let perturbed_pose = perturb_stereo_translation(pose, &delta);
1676        let perturbed =
1677            stereo_reprojection_residual(&perturbed_pose, observations, camera, baseline)?;
1678        let column = (perturbed - &base) / epsilon;
1679        jacobian.set_column(parameter_index, &column);
1680    }
1681    Some(jacobian)
1682}
1683
1684fn perturb_stereo_translation(pose: &Pose, delta: &DVector<f64>) -> Pose {
1685    let translation_delta = Vector3::new(delta[0], delta[1], delta[2]);
1686    Pose::from_world_to_camera(
1687        pose.world_to_camera.rotation,
1688        pose.world_to_camera.translation + translation_delta,
1689    )
1690}
1691
1692/// Configuration for [`StereoVoFrontend`]. Defaults are tuned for KITTI-
1693/// scale rectified stereo with the project's `CornerFeatureExtractor`
1694/// patch descriptors at radius 9; tighter `kabsch.inlier_threshold_m` /
1695/// looser `stereo.max_depth_m` may be appropriate for sequences with
1696/// faster motion or longer-range structure.
1697#[derive(Debug, Clone, PartialEq)]
1698pub struct StereoVoFrontendConfig {
1699    pub feature: CornerFeatureConfig,
1700    pub stereo: StereoFeatureConfig,
1701    pub kabsch: KabschRansacConfig,
1702    /// Pixel threshold for the 2D-3D PnP RANSAC reprojection inlier test.
1703    /// Lower values reject descriptor-consistent but geometrically loose
1704    /// matches; higher values are more tolerant when features are noisy.
1705    pub pnp_reprojection_threshold_px: f64,
1706    /// Minimum accepted 2D-3D PnP inlier count. If PnP recovers fewer
1707    /// inliers, the frontend treats it as a failed primary estimate and
1708    /// falls back to the 3D-3D Kabsch path when available.
1709    pub pnp_min_inliers: usize,
1710    /// Optional maximum depth for 3D points passed into consecutive-frame
1711    /// PnP. Stereo depth noise grows quadratically with distance, so
1712    /// dropping very far landmarks can reduce rotation drift on driving
1713    /// sequences. `None` keeps every triangulated point accepted by the
1714    /// stereo frontend.
1715    pub pnp_max_depth_m: Option<f64>,
1716    /// Optional extra max-depth hypotheses for PnP. When populated, the
1717    /// frontend estimates PnP once with the primary `pnp_max_depth_m` setting
1718    /// and once for each extra depth cap, then selects the pose that scores
1719    /// best when reprojected against the full uncapped correspondence set.
1720    /// This lets far-field pruning act as a candidate generator without
1721    /// making a depth-capped pose eligible when it loses global consensus.
1722    pub pnp_depth_hypotheses_m: Vec<f64>,
1723    /// Optional automatic PnP max-depth candidate. Unlike
1724    /// `pnp_depth_hypotheses_m`, this candidate is tried only when the
1725    /// primary uncapped/depth-capped PnP estimate has weak consensus.
1726    pub pnp_adaptive_depth_hypothesis_m: Option<f64>,
1727    /// Primary PnP inlier ratio below which the adaptive depth candidate is
1728    /// evaluated. This is intentionally conservative so clean short windows
1729    /// keep the primary path unchanged.
1730    pub pnp_adaptive_depth_min_primary_inlier_ratio: f64,
1731    /// Number of prior relative-motion estimates required before the frontend
1732    /// can rescue a collapsed translation magnitude from recent motion scale.
1733    pub motion_scale_rescue_min_history: usize,
1734    /// Minimum recent median translation required before motion-scale rescue
1735    /// is considered. This keeps slow urban windows on the raw estimator path.
1736    pub motion_scale_rescue_min_median_translation_m: f64,
1737    /// Trigger rescue when the current translation magnitude is below this
1738    /// fraction of the recent median and the pose consensus is weak.
1739    pub motion_scale_rescue_min_translation_ratio: f64,
1740    /// Trigger rescue when the current translation magnitude is above this
1741    /// multiple of the recent median and the pose consensus is weak.
1742    pub motion_scale_rescue_max_translation_ratio: f64,
1743    /// Percentile of the recent translation history used as the replacement
1744    /// scale once motion-scale rescue triggers. Values above the median make
1745    /// the fast-motion guard less laggy on accelerating driving sequences.
1746    pub motion_scale_rescue_target_percentile: f64,
1747    /// Maximum PnP inlier ratio eligible for motion-scale rescue. Keeping
1748    /// this slightly above one lets the fast-motion scale guard smooth clean
1749    /// but laggy PnP pairs, while the median-translation gate keeps slow
1750    /// urban windows on the raw estimator path.
1751    pub motion_scale_rescue_max_pnp_inlier_ratio: f64,
1752    /// Release a motion-scale rescue that has rescued a whole history window
1753    /// (`motion_scale_rescue_min_history` pairs) in a row. The rescue judges
1754    /// each step against the recent rescued steps. After a full window of
1755    /// rescues that history holds only the rescue's own outputs, so a real,
1756    /// sustained slowdown locks in: every slower step counts as "collapsed"
1757    /// and is scaled back up to the old speed, for good (KITTI odometry 09:
1758    /// 1,312 pairs in a row; raw drive 2011_09_30_0020: 307). On release the
1759    /// streak's entries in the rescue's history are replaced by the
1760    /// estimator's raw step lengths and the current step is kept as
1761    /// estimated, so the median follows the real speed again. On by
1762    /// default. The short streaks the rescue exists for (at most 17 pairs on
1763    /// KITTI 01's highway slice) never reach it.
1764    pub motion_scale_rescue_release_full_window: bool,
1765    /// Number of prior relative-motion estimates required before translation
1766    /// direction rescue can clamp a weak-consensus lateral outlier.
1767    pub translation_direction_rescue_min_history: usize,
1768    /// Minimum recent median translation required before translation direction
1769    /// rescue is considered.
1770    pub translation_direction_rescue_min_median_translation_m: f64,
1771    /// Trigger translation direction rescue when the current translation vector
1772    /// deviates from the recent average direction by more than this angle.
1773    pub translation_direction_rescue_max_angle_deg: f64,
1774    /// Maximum PnP inlier ratio still considered weak enough for translation
1775    /// direction rescue. Kabsch fallbacks are considered weak.
1776    pub translation_direction_rescue_max_pnp_inlier_ratio: f64,
1777    /// Number of prior relative-motion estimates required before rotation
1778    /// spike rescue can clamp an implausibly large weak-consensus rotation.
1779    pub rotation_spike_rescue_min_history: usize,
1780    /// Minimum recent median translation required before rotation spike rescue
1781    /// is considered.
1782    pub rotation_spike_rescue_min_median_translation_m: f64,
1783    /// Minimum current relative-rotation angle before rotation spike rescue can
1784    /// trigger, even if the recent-median ratio is exceeded.
1785    pub rotation_spike_rescue_min_angle_deg: f64,
1786    /// Trigger rotation spike rescue when the current rotation angle exceeds
1787    /// this multiple of the recent median rotation angle.
1788    pub rotation_spike_rescue_max_angle_ratio: f64,
1789    /// Maximum PnP inlier ratio still considered weak enough for rotation
1790    /// spike rescue. Kabsch fallbacks are considered weak.
1791    pub rotation_spike_rescue_max_pnp_inlier_ratio: f64,
1792    /// Number of prior relative-motion estimates required before weak
1793    /// rotations can be clamped to the recent scaled-axis trend.
1794    pub rotation_vector_rescue_min_history: usize,
1795    /// Minimum recent median translation required before rotation-vector
1796    /// rescue is considered.
1797    pub rotation_vector_rescue_min_median_translation_m: f64,
1798    /// Trigger rotation-vector rescue when the current scaled-axis rotation
1799    /// differs from the recent average scaled-axis rotation by more than this
1800    /// angle.
1801    pub rotation_vector_rescue_max_delta_deg: f64,
1802    /// Maximum PnP inlier ratio still considered weak enough for
1803    /// rotation-vector rescue. Kabsch fallbacks are considered weak.
1804    pub rotation_vector_rescue_max_pnp_inlier_ratio: f64,
1805    /// Minimum PnP RANSAC trials before the high-consensus early-stop guard
1806    /// can terminate the search. This only applies when
1807    /// `pnp_early_stop_inlier_ratio` is `Some`.
1808    pub pnp_early_stop_min_iterations: usize,
1809    /// Optional high-consensus early-stop ratio for consecutive-frame PnP.
1810    /// KITTI-like stereo pairs often reach a very large inlier set quickly;
1811    /// stopping after that point avoids pathological long frames while
1812    /// preserving the full budget for lower-consensus pairs.
1813    pub pnp_early_stop_inlier_ratio: Option<f64>,
1814    /// When PnP technically succeeds but has a very low inlier ratio, also
1815    /// estimate a 3D-3D Kabsch pose and let it challenge the PnP pose.
1816    /// This targets highway windows where a small descriptor-consistent PnP
1817    /// consensus can carry a rotation/translation outlier even though the
1818    /// stereo pair set contains a stronger metric alignment.
1819    pub pnp_kabsch_challenge_max_inlier_ratio: f64,
1820    /// Minimum 3D-3D inlier-count gain required before the weak-PnP Kabsch
1821    /// challenger can replace PnP.
1822    pub pnp_kabsch_challenge_min_3d_inlier_gain: usize,
1823    /// Required residual improvement for the Kabsch challenger relative to
1824    /// scoring the PnP pose on the same 3D-3D stereo pairs.
1825    pub pnp_kabsch_challenge_max_residual_ratio: f64,
1826    /// If enabled, refine only the selected relative pose translation
1827    /// against current-frame left and right stereo reprojection residuals
1828    /// for temporal matches that have stereo triangulations in both frames.
1829    /// Rotation stays anchored to PnP/Kabsch so current-frame stereo
1830    /// disparity noise cannot pull the orientation estimate around.
1831    pub stereo_pose_refinement: bool,
1832    /// If enabled, align only the selected relative pose's vertical
1833    /// translation component against matched stereo 3D pairs. This keeps
1834    /// PnP's rotation and forward/lateral translation while using the
1835    /// current stereo triangulation as a robust vertical residual check.
1836    pub stereo_vertical_alignment: bool,
1837    /// Minimum matched stereo 3D pairs required before vertical-only
1838    /// alignment can run.
1839    pub stereo_vertical_alignment_min_pairs: usize,
1840    /// Maximum absolute per-pair vertical correction in meters.
1841    pub stereo_vertical_alignment_max_correction_m: f64,
1842    /// Number of prior relative-motion estimates required before automatic
1843    /// stereo pose refinement can run without the explicit
1844    /// `stereo_pose_refinement` override.
1845    pub stereo_pose_refinement_auto_min_history: usize,
1846    /// Minimum recent median translation required before automatic stereo
1847    /// pose refinement is considered.
1848    pub stereo_pose_refinement_auto_min_median_translation_m: f64,
1849    /// Maximum PnP inlier ratio eligible for automatic stereo pose
1850    /// refinement once the recent motion is fast enough. Kabsch fallbacks are
1851    /// considered eligible by construction.
1852    pub stereo_pose_refinement_auto_max_pnp_inlier_ratio: f64,
1853    /// Consecutive-frame relative-pose source. `PnpThenKabsch` preserves
1854    /// the default 2D-3D PnP path and uses 3D-3D Kabsch only as a fallback;
1855    /// `KabschThenPnp` is useful for driving/stereo ablations where metric
1856    /// 3D-3D alignment may reduce forward-motion PnP drift.
1857    pub relative_pose_mode: StereoRelativePoseMode,
1858    /// Lowe's ratio for the per-pair temporal `left_i ↔ left_(i+1)`
1859    /// descriptor matcher. Native to the project's `BruteForceMatcher`
1860    /// (`f32`), kept here as `Option<f32>` to avoid a lossy cast at
1861    /// every `process_pair`.
1862    pub temporal_ratio: Option<f32>,
1863    /// Optional row-motion gate for consecutive-frame temporal matches.
1864    /// Rectified automotive stereo has limited vertical frame-to-frame
1865    /// motion; setting this can remove descriptor-consistent but implausible
1866    /// temporal matches before PnP/Kabsch. `None` preserves unconstrained
1867    /// temporal matching.
1868    pub temporal_max_row_delta_px: Option<f64>,
1869    /// Optional automatic row-motion gate for faster recent motion. Unlike
1870    /// `temporal_max_row_delta_px`, this only activates after enough prior
1871    /// relative translations have been integrated and their recent median is
1872    /// above `temporal_auto_min_median_translation_m`.
1873    pub temporal_auto_max_row_delta_px: Option<f64>,
1874    pub temporal_auto_min_history: usize,
1875    pub temporal_auto_min_median_translation_m: f64,
1876    /// Optional automatic confidence floor for consecutive-frame temporal
1877    /// matches during faster recent motion. Matchers without confidence
1878    /// metadata are left unchanged, so this only affects deep-style matchers
1879    /// such as [`crate::matching::MutualSoftmaxMatcher`].
1880    pub temporal_auto_min_confidence: Option<f32>,
1881    pub temporal_auto_confidence_min_history: usize,
1882    pub temporal_auto_confidence_min_median_translation_m: f64,
1883    pub temporal_auto_confidence_curve_min_median_translation_m: Option<f64>,
1884    pub temporal_auto_confidence_curve_min_median_rotation_deg: Option<f64>,
1885    pub temporal_auto_confidence_max_median_rotation_deg: Option<f64>,
1886}
1887
1888impl Default for StereoVoFrontendConfig {
1889    fn default() -> Self {
1890        Self {
1891            feature: CornerFeatureConfig {
1892                max_features: 1500,
1893                min_score: 0.02,
1894                descriptor_radius: 9,
1895            },
1896            stereo: StereoFeatureConfig {
1897                min_disparity_px: 1.0,
1898                max_row_residual_px: 2.0,
1899                min_depth_m: 3.0,
1900                max_depth_m: 80.0,
1901                depth_gate: StereoDepthGate::default(),
1902                ratio: Some(0.85),
1903            },
1904            kabsch: KabschRansacConfig {
1905                iterations: 4000,
1906                inlier_threshold_m: 2.0,
1907                min_inliers: 8,
1908                max_depth_m: 30.0,
1909                seed: 7,
1910            },
1911            pnp_reprojection_threshold_px: 3.32,
1912            pnp_min_inliers: 12,
1913            pnp_max_depth_m: None,
1914            pnp_depth_hypotheses_m: Vec::new(),
1915            pnp_adaptive_depth_hypothesis_m: Some(60.0),
1916            pnp_adaptive_depth_min_primary_inlier_ratio: 0.65,
1917            motion_scale_rescue_min_history: 20,
1918            motion_scale_rescue_min_median_translation_m: 1.5,
1919            motion_scale_rescue_min_translation_ratio: 0.97,
1920            motion_scale_rescue_max_translation_ratio: 1.6,
1921            motion_scale_rescue_target_percentile: 0.75,
1922            motion_scale_rescue_max_pnp_inlier_ratio: 1.05,
1923            motion_scale_rescue_release_full_window: true,
1924            translation_direction_rescue_min_history: 20,
1925            translation_direction_rescue_min_median_translation_m: 1.5,
1926            translation_direction_rescue_max_angle_deg: 10.0,
1927            translation_direction_rescue_max_pnp_inlier_ratio: 0.45,
1928            rotation_spike_rescue_min_history: 20,
1929            rotation_spike_rescue_min_median_translation_m: 1.5,
1930            rotation_spike_rescue_min_angle_deg: 1.0,
1931            rotation_spike_rescue_max_angle_ratio: 3.0,
1932            rotation_spike_rescue_max_pnp_inlier_ratio: 0.45,
1933            rotation_vector_rescue_min_history: 20,
1934            rotation_vector_rescue_min_median_translation_m: 1.5,
1935            rotation_vector_rescue_max_delta_deg: 0.4,
1936            rotation_vector_rescue_max_pnp_inlier_ratio: 0.45,
1937            pnp_early_stop_min_iterations: 100,
1938            pnp_early_stop_inlier_ratio: Some(0.85),
1939            pnp_kabsch_challenge_max_inlier_ratio: 0.0,
1940            pnp_kabsch_challenge_min_3d_inlier_gain: 8,
1941            pnp_kabsch_challenge_max_residual_ratio: 0.85,
1942            stereo_pose_refinement: false,
1943            stereo_vertical_alignment: false,
1944            stereo_vertical_alignment_min_pairs: 80,
1945            stereo_vertical_alignment_max_correction_m: 0.25,
1946            stereo_pose_refinement_auto_min_history: 20,
1947            stereo_pose_refinement_auto_min_median_translation_m: 1.5,
1948            stereo_pose_refinement_auto_max_pnp_inlier_ratio: 1.0,
1949            relative_pose_mode: StereoRelativePoseMode::PnpThenKabsch,
1950            temporal_ratio: Some(0.9),
1951            temporal_max_row_delta_px: None,
1952            temporal_auto_max_row_delta_px: None,
1953            temporal_auto_min_history: 20,
1954            temporal_auto_min_median_translation_m: 1.05,
1955            temporal_auto_min_confidence: Some(0.20),
1956            temporal_auto_confidence_min_history: 20,
1957            temporal_auto_confidence_min_median_translation_m: 1.45,
1958            temporal_auto_confidence_curve_min_median_translation_m: Some(0.95),
1959            temporal_auto_confidence_curve_min_median_rotation_deg: Some(0.26),
1960            temporal_auto_confidence_max_median_rotation_deg: Some(0.45),
1961        }
1962    }
1963}
1964
1965#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1966pub enum StereoRelativePoseMode {
1967    PnpThenKabsch,
1968    KabschThenPnp,
1969}
1970
1971/// Errors returned by [`StereoVoFrontend::process_pair`]. The feature
1972/// extractor's error is type-erased into a `Box<dyn Error>` so the same
1973/// `StereoVoError` type accepts any [`FeatureExtractor`] implementation
1974/// (classical `CornerFeatureExtractor`, learned `HogLikeFeatureExtractor`,
1975/// or a future ONNX-backed deep head).
1976#[derive(Debug)]
1977pub enum StereoVoError {
1978    Feature(Box<dyn std::error::Error + Send + Sync>),
1979    KabschFailed {
1980        pair_index: usize,
1981        correspondence_count: usize,
1982        min_inliers: usize,
1983    },
1984}
1985
1986impl From<CornerFeatureError> for StereoVoError {
1987    fn from(value: CornerFeatureError) -> Self {
1988        StereoVoError::Feature(Box::new(value))
1989    }
1990}
1991
1992impl std::fmt::Display for StereoVoError {
1993    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1994        match self {
1995            StereoVoError::Feature(e) => write!(f, "feature extraction failed: {e}"),
1996            StereoVoError::KabschFailed {
1997                pair_index,
1998                correspondence_count,
1999                min_inliers,
2000            } => write!(
2001                f,
2002                "relative-pose RANSAC failed at pair {pair_index}→{}: {correspondence_count} \
2003                 correspondences (need ≥{min_inliers} inliers)",
2004                pair_index + 1,
2005            ),
2006        }
2007    }
2008}
2009
2010impl std::error::Error for StereoVoError {}
2011
2012/// Stateful rectified-stereo VO frontend. Each `process_pair` call extracts
2013/// features in both eyes, triangulates them, matches the previous frame's
2014/// left features against the new frame's, and recovers the relative pose via
2015/// 2D-3D PnP RANSAC with a 3D-3D Kabsch fallback. The first call seeds the
2016/// world frame at identity; subsequent calls compose the recovered relative
2017/// pose into the running world-frame trajectory.
2018///
2019/// Per-frame state (FeatureSets, stereo triangulations, world-frame poses)
2020/// is exposed via the public fields so a downstream BA orchestrator can
2021/// build multi-frame tracks across the trajectory and refine without
2022/// re-running the front-end.
2023#[derive(Debug)]
2024pub struct StereoVoFrontend<E = CornerFeatureExtractor, M = BruteForceMatcher>
2025where
2026    E: FeatureExtractor<Image = GrayscaleImage>,
2027    M: Matcher,
2028{
2029    pub camera: Camera,
2030    pub baseline: f64,
2031    pub config: StereoVoFrontendConfig,
2032
2033    extractor: E,
2034    matcher: M,
2035    depth_gate_state: StereoDepthGateState,
2036
2037    /// World-frame pose for every processed frame, beginning with the
2038    /// identity pose at the seed frame.
2039    pub poses: Vec<Pose>,
2040    pub left_features: Vec<FeatureSet>,
2041    pub right_features: Vec<FeatureSet>,
2042    pub stereo_per_frame: Vec<Vec<StereoFeature>>,
2043    /// Per-pair Kabsch translation magnitude in metric units (one entry
2044    /// per call after the first). Used by track-extension callers to
2045    /// adapt the projection search radius to the observed motion.
2046    pub per_pair_translation_m: Vec<f64>,
2047    /// Per-pair translation magnitudes before any frontend rescue (the
2048    /// estimator's own step lengths).
2049    pub per_pair_raw_translation_m: Vec<f64>,
2050    motion_scale_rescue: MotionScaleRescue,
2051    /// Per-pair relative translation vectors in the current camera frame,
2052    /// after any guarded frontend rescues have been applied.
2053    pub per_pair_translation_vectors: Vec<Vector3<f64>>,
2054    /// Per-pair relative-rotation magnitudes in degrees, after any guarded
2055    /// frontend rescues have been applied.
2056    pub per_pair_rotation_deg: Vec<f64>,
2057    /// Per-pair relative-rotation scaled-axis vectors in radians, after any
2058    /// guarded frontend rescues have been applied.
2059    pub per_pair_rotation_vectors: Vec<Vector3<f64>>,
2060    /// Per-pair relative-pose RANSAC inlier counts.
2061    pub kabsch_inlier_counts: Vec<usize>,
2062    /// Per-pair relative-pose diagnostics, including which estimator was
2063    /// actually selected. Kept separate from `kabsch_inlier_counts` because
2064    /// the latter is a legacy name used by existing examples.
2065    pub pair_diagnostics: Vec<StereoVoPairDiagnostics>,
2066    /// Per-frame lower-depth gate diagnostics. One entry is appended for
2067    /// every processed stereo frame, including the seed frame.
2068    pub stereo_depth_gate_diagnostics: Vec<StereoDepthGateDiagnostics>,
2069    /// Per-pair temporal matches actually used (after row-gate and
2070    /// confidence filters). One entry per pose pair, i.e. `poses.len() - 1`
2071    /// entries after the seed frame. Captured so downstream multi-frame BA
2072    /// refiners (e.g. `visloc_slam::refine_stereo_vo_with_ba`) can be driven
2073    /// online without re-running the matcher.
2074    pub temporal_matches_per_pair: Vec<Vec<DescriptorMatch>>,
2075}
2076
2077impl StereoVoFrontend<CornerFeatureExtractor, BruteForceMatcher> {
2078    /// Build the classical Corner + brute-force frontend that the original
2079    /// stereo VO demos use. Equivalent to
2080    /// `new_with(camera, baseline, config, CornerFeatureExtractor::new(...),
2081    /// BruteForceMatcher { ratio: config.temporal_ratio })`.
2082    pub fn new(camera: Camera, baseline: f64, config: StereoVoFrontendConfig) -> Self {
2083        let extractor = CornerFeatureExtractor::new(config.feature.clone());
2084        let matcher = BruteForceMatcher {
2085            ratio: config.temporal_ratio,
2086        };
2087        Self::new_with(camera, baseline, config, extractor, matcher)
2088    }
2089}
2090
2091impl<E, M> StereoVoFrontend<E, M>
2092where
2093    E: FeatureExtractor<Image = GrayscaleImage>,
2094    E::Error: std::error::Error + Send + Sync + 'static,
2095    M: Matcher,
2096{
2097    /// Build a stereo VO frontend with caller-provided feature extractor
2098    /// and matcher. Use this constructor to plug in a deep frontend
2099    /// (`HogLikeFeatureExtractor` + `MutualSoftmaxMatcher`) or a future
2100    /// ONNX-backed learned head — the rest of the pipeline (stereo
2101    /// triangulation, Kabsch RANSAC, world-frame composition) is shared.
2102    pub fn new_with(
2103        camera: Camera,
2104        baseline: f64,
2105        config: StereoVoFrontendConfig,
2106        extractor: E,
2107        matcher: M,
2108    ) -> Self {
2109        Self {
2110            camera,
2111            baseline,
2112            config,
2113            extractor,
2114            matcher,
2115            depth_gate_state: StereoDepthGateState::default(),
2116            poses: Vec::new(),
2117            left_features: Vec::new(),
2118            right_features: Vec::new(),
2119            stereo_per_frame: Vec::new(),
2120            per_pair_translation_m: Vec::new(),
2121            per_pair_raw_translation_m: Vec::new(),
2122            motion_scale_rescue: MotionScaleRescue::default(),
2123            per_pair_translation_vectors: Vec::new(),
2124            per_pair_rotation_deg: Vec::new(),
2125            per_pair_rotation_vectors: Vec::new(),
2126            kabsch_inlier_counts: Vec::new(),
2127            pair_diagnostics: Vec::new(),
2128            stereo_depth_gate_diagnostics: Vec::new(),
2129            temporal_matches_per_pair: Vec::new(),
2130        }
2131    }
2132
2133    /// Number of frames processed so far.
2134    pub fn frame_count(&self) -> usize {
2135        self.poses.len()
2136    }
2137
2138    /// Process a rectified stereo pair. The first call seeds the world
2139    /// frame at identity; each subsequent call extends the trajectory
2140    /// with one new pose and returns it.
2141    pub fn process_pair(
2142        &mut self,
2143        left: &GrayscaleImage,
2144        right: &GrayscaleImage,
2145    ) -> Result<Pose, StereoVoError> {
2146        let left_features = self
2147            .extractor
2148            .extract(left)
2149            .map_err(|e| StereoVoError::Feature(Box::new(e)))?;
2150        let right_features = self
2151            .extractor
2152            .extract(right)
2153            .map_err(|e| StereoVoError::Feature(Box::new(e)))?;
2154        self.process_feature_pair(left_features, right_features)
2155    }
2156
2157    /// Process caller-provided left/right features using the frontend's
2158    /// configured descriptor matcher for stereo-temporal association.
2159    ///
2160    /// This is useful when feature extraction lives outside the frontend but
2161    /// descriptor matching should still use the Rust matcher.
2162    pub fn process_feature_pair(
2163        &mut self,
2164        left_features: FeatureSet,
2165        right_features: FeatureSet,
2166    ) -> Result<Pose, StereoVoError> {
2167        self.process_feature_pair_with_matches(left_features, right_features, None, None)
2168    }
2169
2170    /// Process caller-provided left/right features and optional explicit
2171    /// matches.
2172    ///
2173    /// `stereo_matches` are interpreted as `left.query_index -> right.train_index`.
2174    /// `temporal_matches` are interpreted as
2175    /// `previous_left.query_index -> current_left.train_index`. When either
2176    /// argument is `None`, the frontend falls back to its configured internal
2177    /// matcher for that association.
2178    pub fn process_feature_pair_with_matches(
2179        &mut self,
2180        left_features: FeatureSet,
2181        right_features: FeatureSet,
2182        stereo_matches: Option<&[DescriptorMatch]>,
2183        temporal_matches: Option<&[DescriptorMatch]>,
2184    ) -> Result<Pose, StereoVoError> {
2185        let stereo_outcome = if let Some(stereo_matches) = stereo_matches {
2186            triangulate_stereo_feature_matches_with_depth_state(
2187                &left_features,
2188                &right_features,
2189                stereo_matches,
2190                &self.camera,
2191                self.baseline,
2192                &self.config.stereo,
2193                Some(&mut self.depth_gate_state),
2194            )
2195        } else {
2196            triangulate_stereo_features_with_depth_state(
2197                &left_features,
2198                &right_features,
2199                &self.camera,
2200                self.baseline,
2201                &self.config.stereo,
2202                Some(&mut self.depth_gate_state),
2203            )
2204        };
2205        let stereo_depth_gate_diagnostics = stereo_outcome.diagnostics;
2206        let stereo = stereo_outcome.features;
2207
2208        let new_pose = if let (Some(prev_left), Some(prev_stereo)) =
2209            (self.left_features.last(), self.stereo_per_frame.last())
2210        {
2211            let temporal_matches_raw = temporal_matches.map_or_else(
2212                || {
2213                    self.matcher
2214                        .match_descriptors(&prev_left.descriptors, &left_features.descriptors)
2215                },
2216                |matches| matches.to_vec(),
2217            );
2218            let temporal_row_gate_px =
2219                effective_temporal_max_row_delta_px(&self.per_pair_translation_m, &self.config);
2220            let temporal_confidence_gate = effective_temporal_min_confidence(
2221                &self.per_pair_translation_m,
2222                &self.per_pair_rotation_deg,
2223                &self.config,
2224            );
2225            let temporal_matches = if let Some(max_row_delta_px) = temporal_row_gate_px {
2226                filter_temporal_matches_by_row_delta(
2227                    prev_left,
2228                    &left_features,
2229                    &temporal_matches_raw,
2230                    max_row_delta_px,
2231                )
2232            } else {
2233                temporal_matches_raw
2234            };
2235            let temporal_matches = if let Some(min_confidence) = temporal_confidence_gate {
2236                filter_temporal_matches_by_confidence(&temporal_matches, min_confidence)
2237            } else {
2238                temporal_matches
2239            };
2240            let pnp_corrs_all = build_stereo_temporal_correspondences(
2241                prev_stereo,
2242                &left_features,
2243                &temporal_matches,
2244            );
2245            let pnp = PnPRansac {
2246                iterations: self.config.kabsch.iterations,
2247                reprojection_threshold: self.config.pnp_reprojection_threshold_px,
2248                seed: self.config.kabsch.seed,
2249                early_stop_min_iterations: self.config.pnp_early_stop_min_iterations,
2250                early_stop_inlier_ratio: self.config.pnp_early_stop_inlier_ratio,
2251                ..PnPRansac::default()
2252            };
2253            let pnp_report = estimate_pnp_with_depth_hypotheses(
2254                &pnp,
2255                &pnp_corrs_all,
2256                &self.camera,
2257                self.config.pnp_min_inliers,
2258                self.config.pnp_max_depth_m,
2259                &self.config.pnp_depth_hypotheses_m,
2260                self.config.pnp_adaptive_depth_hypothesis_m,
2261                self.config.pnp_adaptive_depth_min_primary_inlier_ratio,
2262            );
2263            let pair_corrs = stereo_pair_correspondences(prev_stereo, &stereo, &temporal_matches);
2264            let (
2265                mut relative_pose,
2266                inlier_count,
2267                source,
2268                pnp_mean_reprojection_error_px,
2269                kabsch_mean_residual_m,
2270            ) = match self.config.relative_pose_mode {
2271                StereoRelativePoseMode::PnpThenKabsch => {
2272                    if let Some(report) = &pnp_report {
2273                        let kabsch_challenger =
2274                            if should_try_kabsch_challenger(report, &self.config) {
2275                                estimate_relative_pose_kabsch_ransac(
2276                                    &pair_corrs,
2277                                    &self.config.kabsch,
2278                                )
2279                            } else {
2280                                None
2281                            };
2282                        if let Some(kabsch_report) = &kabsch_challenger {
2283                            let pnp_stereo_score = score_pose_on_stereo_pairs(
2284                                &report.pose,
2285                                &pair_corrs,
2286                                self.config.kabsch.inlier_threshold_m,
2287                            );
2288                            if is_kabsch_challenger_better(
2289                                kabsch_report,
2290                                pnp_stereo_score,
2291                                &self.config,
2292                            ) {
2293                                (
2294                                    kabsch_report.relative_pose.clone(),
2295                                    kabsch_report.inliers.len(),
2296                                    StereoRelativePoseSource::Kabsch,
2297                                    Some(report.mean_reprojection_error),
2298                                    Some(kabsch_report.mean_residual_m),
2299                                )
2300                            } else {
2301                                (
2302                                    report.pose.clone(),
2303                                    report.inlier_count,
2304                                    StereoRelativePoseSource::Pnp,
2305                                    Some(report.mean_reprojection_error),
2306                                    kabsch_challenger.as_ref().map(|r| r.mean_residual_m),
2307                                )
2308                            }
2309                        } else {
2310                            (
2311                                report.pose.clone(),
2312                                report.inlier_count,
2313                                StereoRelativePoseSource::Pnp,
2314                                Some(report.mean_reprojection_error),
2315                                None,
2316                            )
2317                        }
2318                    } else {
2319                        let kabsch_report =
2320                            estimate_relative_pose_kabsch_ransac(&pair_corrs, &self.config.kabsch);
2321                        let report =
2322                            kabsch_report
2323                                .as_ref()
2324                                .ok_or_else(|| StereoVoError::KabschFailed {
2325                                    pair_index: self.poses.len() - 1,
2326                                    correspondence_count: pair_corrs.len().max(pnp_corrs_all.len()),
2327                                    min_inliers: self.config.kabsch.min_inliers,
2328                                })?;
2329                        (
2330                            report.relative_pose.clone(),
2331                            report.inliers.len(),
2332                            StereoRelativePoseSource::KabschFallback,
2333                            pnp_report.as_ref().map(|r| r.mean_reprojection_error),
2334                            Some(report.mean_residual_m),
2335                        )
2336                    }
2337                }
2338                StereoRelativePoseMode::KabschThenPnp => {
2339                    let kabsch_report =
2340                        estimate_relative_pose_kabsch_ransac(&pair_corrs, &self.config.kabsch);
2341                    if let Some(report) = &kabsch_report {
2342                        (
2343                            report.relative_pose.clone(),
2344                            report.inliers.len(),
2345                            StereoRelativePoseSource::Kabsch,
2346                            pnp_report.as_ref().map(|r| r.mean_reprojection_error),
2347                            Some(report.mean_residual_m),
2348                        )
2349                    } else {
2350                        let report =
2351                            pnp_report
2352                                .as_ref()
2353                                .ok_or_else(|| StereoVoError::KabschFailed {
2354                                    pair_index: self.poses.len() - 1,
2355                                    correspondence_count: pair_corrs.len().max(pnp_corrs_all.len()),
2356                                    min_inliers: self.config.kabsch.min_inliers,
2357                                })?;
2358                        (
2359                            report.pose.clone(),
2360                            report.inlier_count,
2361                            StereoRelativePoseSource::PnpFallback,
2362                            Some(report.mean_reprojection_error),
2363                            kabsch_report.as_ref().map(|r| r.mean_residual_m),
2364                        )
2365                    }
2366                }
2367            };
2368            if should_refine_current_stereo_pose(
2369                &self.per_pair_translation_m,
2370                pnp_report.as_ref(),
2371                source,
2372                &self.config,
2373            ) {
2374                if let Some(refined) = refine_relative_pose_with_current_stereo(
2375                    &relative_pose,
2376                    prev_stereo,
2377                    &stereo,
2378                    &left_features,
2379                    &right_features,
2380                    &temporal_matches,
2381                    &self.camera,
2382                    self.baseline,
2383                    self.config.pnp_reprojection_threshold_px * 2.0,
2384                ) {
2385                    relative_pose = refined;
2386                }
2387            }
2388            let raw_translation_m = relative_pose.world_to_camera.translation.norm();
2389            let raw_rotation_deg = relative_rotation_angle_deg(&relative_pose);
2390            let stereo_vertical_aligned = align_vertical_translation_to_stereo_pairs(
2391                &mut relative_pose,
2392                prev_stereo,
2393                &stereo,
2394                prev_left,
2395                &left_features,
2396                &temporal_matches,
2397                &self.camera,
2398                &self.config,
2399            );
2400            let motion_scale_rescued = self.motion_scale_rescue.apply(
2401                &mut relative_pose,
2402                pnp_report.as_ref(),
2403                source,
2404                &self.config,
2405            );
2406            let translation_direction_rescued = rescue_translation_direction(
2407                &mut relative_pose,
2408                &self.per_pair_translation_m,
2409                &self.per_pair_translation_vectors,
2410                pnp_report.as_ref(),
2411                source,
2412                &self.config,
2413            );
2414            let rotation_spike_rescued = rescue_rotation_spike(
2415                &mut relative_pose,
2416                &self.per_pair_translation_m,
2417                &self.per_pair_rotation_deg,
2418                pnp_report.as_ref(),
2419                source,
2420                &self.config,
2421            );
2422            let rotation_vector_rescued = rescue_rotation_vector(
2423                &mut relative_pose,
2424                &self.per_pair_translation_m,
2425                &self.per_pair_rotation_vectors,
2426                pnp_report.as_ref(),
2427                source,
2428                &self.config,
2429            );
2430            self.kabsch_inlier_counts.push(inlier_count);
2431            let translation_m = relative_pose.world_to_camera.translation.norm();
2432            let rotation_deg = relative_rotation_angle_deg(&relative_pose);
2433            let rotation_vector = relative_pose.world_to_camera.rotation.scaled_axis();
2434            self.per_pair_translation_m.push(translation_m);
2435            self.per_pair_raw_translation_m.push(raw_translation_m);
2436            self.motion_scale_rescue
2437                .record(raw_translation_m, translation_m);
2438            self.per_pair_translation_vectors
2439                .push(relative_pose.world_to_camera.translation);
2440            self.per_pair_rotation_deg.push(rotation_deg);
2441            self.per_pair_rotation_vectors.push(rotation_vector);
2442            self.temporal_matches_per_pair
2443                .push(temporal_matches.clone());
2444            self.pair_diagnostics.push(StereoVoPairDiagnostics {
2445                from_frame: self.poses.len() - 1,
2446                to_frame: self.poses.len(),
2447                source,
2448                temporal_match_count: temporal_matches.len(),
2449                temporal_row_gate_px,
2450                temporal_confidence_gate,
2451                pnp_correspondence_count: pnp_report
2452                    .as_ref()
2453                    .map_or_else(|| pnp_corrs_all.len(), |report| report.correspondence_count),
2454                stereo_pair_correspondence_count: pair_corrs.len(),
2455                inlier_count,
2456                raw_translation_m,
2457                raw_rotation_deg,
2458                translation_m,
2459                rotation_deg,
2460                motion_scale_rescued,
2461                stereo_vertical_aligned,
2462                translation_direction_rescued,
2463                rotation_spike_rescued,
2464                rotation_vector_rescued,
2465                pnp_mean_reprojection_error_px,
2466                kabsch_mean_residual_m,
2467            });
2468            let relative = relative_pose.world_to_camera;
2469            let last = self.poses.last().unwrap();
2470            Pose {
2471                world_to_camera: relative.compose(&last.world_to_camera),
2472            }
2473        } else {
2474            Pose::identity()
2475        };
2476
2477        self.poses.push(new_pose.clone());
2478        self.left_features.push(left_features);
2479        self.right_features.push(right_features);
2480        self.stereo_per_frame.push(stereo);
2481        self.stereo_depth_gate_diagnostics
2482            .push(stereo_depth_gate_diagnostics);
2483        Ok(new_pose)
2484    }
2485
2486    /// Adaptive projection-track search radius in pixels: scales with the
2487    /// observed median per-pair translation, with a 20 px floor that
2488    /// covers KITTI's patch-descriptor confusion band even when motion is
2489    /// small. Returns 25 px when no pairs have been processed yet.
2490    pub fn adaptive_track_search_radius_px(&self) -> f64 {
2491        if self.per_pair_translation_m.is_empty() {
2492            return 25.0;
2493        }
2494        let mut sorted = self.per_pair_translation_m.clone();
2495        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
2496        let median = sorted[sorted.len() / 2];
2497        (12.0 + 2.0 * median).clamp(20.0, 35.0)
2498    }
2499
2500    /// Sum of consecutive camera-center deltas in the recovered trajectory
2501    /// (in metric units).
2502    pub fn trajectory_length_m(&self) -> f64 {
2503        let centers: Vec<_> = self.poses.iter().map(|p| p.camera_center_world()).collect();
2504        centers.windows(2).map(|w| (w[1] - w[0]).norm()).sum()
2505    }
2506}
2507
2508/// The motion-scale rescue's own history: the step lengths it judges
2509/// against (the rescued ones, except a released streak, whose entries are
2510/// the raw ones) and its current run of consecutive rescues
2511/// ([`StereoVoFrontendConfig::motion_scale_rescue_release_full_window`]).
2512#[derive(Debug, Clone, Default)]
2513struct MotionScaleRescue {
2514    history_m: Vec<f64>,
2515    raw_m: Vec<f64>,
2516    streak: usize,
2517}
2518
2519impl MotionScaleRescue {
2520    /// Rescues `relative_pose`'s translation magnitude if it collapsed (or
2521    /// inflated) against the history, unless the rescue has just rescued a
2522    /// whole window in a row: then the streak is released instead and the
2523    /// pose is kept. Returns whether the pose was rescued.
2524    fn apply(
2525        &mut self,
2526        relative_pose: &mut Pose,
2527        pnp_report: Option<&PnpSelectedReport>,
2528        source: StereoRelativePoseSource,
2529        config: &StereoVoFrontendConfig,
2530    ) -> bool {
2531        let window = config.motion_scale_rescue_min_history;
2532        let rescued = if config.motion_scale_rescue_release_full_window
2533            && window > 0
2534            && self.streak >= window
2535        {
2536            // The window holds only the rescue's own outputs: hand the
2537            // streak back to the estimator's raw step lengths.
2538            let start = self.history_m.len() - self.streak;
2539            self.history_m[start..].copy_from_slice(&self.raw_m[start..]);
2540            false
2541        } else {
2542            rescue_collapsed_motion_scale(
2543                relative_pose,
2544                &self.history_m,
2545                pnp_report,
2546                source,
2547                config,
2548            )
2549        };
2550        self.streak = if rescued { self.streak + 1 } else { 0 };
2551        rescued
2552    }
2553
2554    /// Records the pair's raw step length and the one it ended with.
2555    fn record(&mut self, raw_m: f64, final_m: f64) {
2556        self.raw_m.push(raw_m);
2557        self.history_m.push(final_m);
2558    }
2559}
2560
2561fn rescue_collapsed_motion_scale(
2562    relative_pose: &mut Pose,
2563    translation_history_m: &[f64],
2564    pnp_report: Option<&PnpSelectedReport>,
2565    source: StereoRelativePoseSource,
2566    config: &StereoVoFrontendConfig,
2567) -> bool {
2568    if translation_history_m.len() < config.motion_scale_rescue_min_history {
2569        return false;
2570    }
2571    let Some(recent_median) = recent_translation_median(
2572        translation_history_m,
2573        config.motion_scale_rescue_min_history,
2574    ) else {
2575        return false;
2576    };
2577    if recent_median < config.motion_scale_rescue_min_median_translation_m {
2578        return false;
2579    }
2580    let current = relative_pose.world_to_camera.translation.norm();
2581    if !current.is_finite() || current <= 1.0e-9 {
2582        return false;
2583    }
2584    let collapsed = current < recent_median * config.motion_scale_rescue_min_translation_ratio;
2585    let inflated = current > recent_median * config.motion_scale_rescue_max_translation_ratio;
2586    if !collapsed && !inflated {
2587        return false;
2588    }
2589    if !is_weak_motion_scale_consensus(
2590        pnp_report,
2591        source,
2592        config.motion_scale_rescue_max_pnp_inlier_ratio,
2593    ) {
2594        return false;
2595    }
2596    let target_scale = recent_positive_percentile(
2597        translation_history_m,
2598        config.motion_scale_rescue_min_history,
2599        config.motion_scale_rescue_target_percentile,
2600    )
2601    .filter(|target| target.is_finite() && *target > 0.0)
2602    .unwrap_or(recent_median);
2603    relative_pose.world_to_camera.translation *= target_scale / current;
2604    true
2605}
2606
2607fn rescue_rotation_spike(
2608    relative_pose: &mut Pose,
2609    translation_history_m: &[f64],
2610    rotation_history_deg: &[f64],
2611    pnp_report: Option<&PnpSelectedReport>,
2612    source: StereoRelativePoseSource,
2613    config: &StereoVoFrontendConfig,
2614) -> bool {
2615    if translation_history_m.len() < config.rotation_spike_rescue_min_history
2616        || rotation_history_deg.len() < config.rotation_spike_rescue_min_history
2617    {
2618        return false;
2619    }
2620    let Some(recent_translation_median) = recent_translation_median(
2621        translation_history_m,
2622        config.rotation_spike_rescue_min_history,
2623    ) else {
2624        return false;
2625    };
2626    if recent_translation_median < config.rotation_spike_rescue_min_median_translation_m {
2627        return false;
2628    }
2629    if !is_weak_motion_scale_consensus(
2630        pnp_report,
2631        source,
2632        config.rotation_spike_rescue_max_pnp_inlier_ratio,
2633    ) {
2634        return false;
2635    }
2636    let Some(recent_rotation_median) = recent_positive_median(
2637        rotation_history_deg,
2638        config.rotation_spike_rescue_min_history,
2639    ) else {
2640        return false;
2641    };
2642    let current_deg = relative_rotation_angle_deg(relative_pose);
2643    if !current_deg.is_finite()
2644        || current_deg < config.rotation_spike_rescue_min_angle_deg
2645        || current_deg < recent_rotation_median * config.rotation_spike_rescue_max_angle_ratio
2646    {
2647        return false;
2648    }
2649    let scaled_axis = relative_pose.world_to_camera.rotation.scaled_axis();
2650    let current_rad = scaled_axis.norm();
2651    if !current_rad.is_finite() || current_rad <= 1.0e-12 {
2652        return false;
2653    }
2654    let target_deg = recent_rotation_median.max(1.0e-6);
2655    let target_axis = scaled_axis * (target_deg.to_radians() / current_rad);
2656    relative_pose.world_to_camera.rotation = UnitQuaternion::from_scaled_axis(target_axis);
2657    true
2658}
2659
2660fn rescue_rotation_vector(
2661    relative_pose: &mut Pose,
2662    translation_history_m: &[f64],
2663    rotation_vector_history: &[Vector3<f64>],
2664    pnp_report: Option<&PnpSelectedReport>,
2665    source: StereoRelativePoseSource,
2666    config: &StereoVoFrontendConfig,
2667) -> bool {
2668    if translation_history_m.len() < config.rotation_vector_rescue_min_history
2669        || rotation_vector_history.len() < config.rotation_vector_rescue_min_history
2670    {
2671        return false;
2672    }
2673    let Some(recent_translation_median) = recent_translation_median(
2674        translation_history_m,
2675        config.rotation_vector_rescue_min_history,
2676    ) else {
2677        return false;
2678    };
2679    if recent_translation_median < config.rotation_vector_rescue_min_median_translation_m {
2680        return false;
2681    }
2682    if !is_weak_motion_scale_consensus(
2683        pnp_report,
2684        source,
2685        config.rotation_vector_rescue_max_pnp_inlier_ratio,
2686    ) {
2687        return false;
2688    }
2689    let Some(recent_vector) = recent_rotation_vector(
2690        rotation_vector_history,
2691        config.rotation_vector_rescue_min_history,
2692    ) else {
2693        return false;
2694    };
2695    let current_vector = relative_pose.world_to_camera.rotation.scaled_axis();
2696    if !current_vector.iter().all(|v| v.is_finite()) {
2697        return false;
2698    }
2699    let delta_deg = (current_vector - recent_vector).norm().to_degrees();
2700    if !delta_deg.is_finite() || delta_deg <= config.rotation_vector_rescue_max_delta_deg {
2701        return false;
2702    }
2703    relative_pose.world_to_camera.rotation = UnitQuaternion::from_scaled_axis(recent_vector);
2704    true
2705}
2706
2707fn rescue_translation_direction(
2708    relative_pose: &mut Pose,
2709    translation_history_m: &[f64],
2710    translation_vector_history: &[Vector3<f64>],
2711    pnp_report: Option<&PnpSelectedReport>,
2712    source: StereoRelativePoseSource,
2713    config: &StereoVoFrontendConfig,
2714) -> bool {
2715    if translation_history_m.len() < config.translation_direction_rescue_min_history
2716        || translation_vector_history.len() < config.translation_direction_rescue_min_history
2717    {
2718        return false;
2719    }
2720    let Some(recent_translation_median) = recent_translation_median(
2721        translation_history_m,
2722        config.translation_direction_rescue_min_history,
2723    ) else {
2724        return false;
2725    };
2726    if recent_translation_median < config.translation_direction_rescue_min_median_translation_m {
2727        return false;
2728    }
2729    if !is_weak_motion_scale_consensus(
2730        pnp_report,
2731        source,
2732        config.translation_direction_rescue_max_pnp_inlier_ratio,
2733    ) {
2734        return false;
2735    }
2736    let current = relative_pose.world_to_camera.translation;
2737    let current_norm = current.norm();
2738    if !current_norm.is_finite() || current_norm <= 1.0e-9 {
2739        return false;
2740    }
2741    let Some(recent_direction) = recent_translation_direction(
2742        translation_vector_history,
2743        config.translation_direction_rescue_min_history,
2744    ) else {
2745        return false;
2746    };
2747    let current_direction = current / current_norm;
2748    let cos_angle = current_direction.dot(&recent_direction).clamp(-1.0, 1.0);
2749    let angle_deg = cos_angle.acos().to_degrees();
2750    if !angle_deg.is_finite() || angle_deg <= config.translation_direction_rescue_max_angle_deg {
2751        return false;
2752    }
2753    relative_pose.world_to_camera.translation = recent_direction * current_norm;
2754    true
2755}
2756
2757// Stereo-pair alignment inputs plus the frontend config; canonical positional
2758// signature shared in spirit with the other stereo-temporal helpers above.
2759#[allow(clippy::too_many_arguments)]
2760fn align_vertical_translation_to_stereo_pairs(
2761    relative_pose: &mut Pose,
2762    prev_stereo: &[StereoFeature],
2763    current_stereo: &[StereoFeature],
2764    prev_left: &FeatureSet,
2765    current_left: &FeatureSet,
2766    temporal_matches: &[DescriptorMatch],
2767    camera: &Camera,
2768    config: &StereoVoFrontendConfig,
2769) -> bool {
2770    if !config.stereo_vertical_alignment
2771        || temporal_matches.len() < config.stereo_vertical_alignment_min_pairs
2772        || !config
2773            .stereo_vertical_alignment_max_correction_m
2774            .is_finite()
2775        || config.stereo_vertical_alignment_max_correction_m <= 0.0
2776    {
2777        return false;
2778    }
2779    let rotation = relative_pose.world_to_camera.rotation;
2780    let current_ty = relative_pose.world_to_camera.translation.y;
2781    let prev_lookup: HashMap<usize, &StereoFeature> =
2782        prev_stereo.iter().map(|f| (f.left_index, f)).collect();
2783    let current_lookup: HashMap<usize, &StereoFeature> =
2784        current_stereo.iter().map(|f| (f.left_index, f)).collect();
2785    let lower_row = camera.height as f64 * 0.55;
2786    let mut residuals = Vec::with_capacity(temporal_matches.len());
2787    for m in temporal_matches {
2788        let (Some(prev), Some(curr)) = (
2789            prev_lookup.get(&m.query_index),
2790            current_lookup.get(&m.train_index),
2791        ) else {
2792            continue;
2793        };
2794        let (Some(prev_kp), Some(curr_kp)) = (
2795            prev_left.keypoints.get(m.query_index),
2796            current_left.keypoints.get(m.train_index),
2797        ) else {
2798            continue;
2799        };
2800        if prev_kp.y < lower_row || curr_kp.y < lower_row {
2801            continue;
2802        }
2803        if prev.point_cam.z > 45.0
2804            || curr.point_cam.z > 45.0
2805            || prev.point_cam.y < -0.5
2806            || curr.point_cam.y < -0.5
2807            || !prev.point_cam.coords.iter().all(|v| v.is_finite())
2808            || !curr.point_cam.coords.iter().all(|v| v.is_finite())
2809        {
2810            continue;
2811        }
2812        let rotated = rotation.transform_point(&prev.point_cam);
2813        let residual_y = curr.point_cam.y - (rotated.y + current_ty);
2814        if residual_y.is_finite() {
2815            residuals.push(residual_y);
2816        }
2817    }
2818    if residuals.len() < config.stereo_vertical_alignment_min_pairs {
2819        return false;
2820    }
2821    align_vertical_translation_from_residuals(
2822        relative_pose,
2823        residuals,
2824        config.stereo_vertical_alignment_max_correction_m,
2825    )
2826}
2827
2828fn align_vertical_translation_from_residuals(
2829    relative_pose: &mut Pose,
2830    mut residuals: Vec<f64>,
2831    max_correction_m: f64,
2832) -> bool {
2833    residuals.sort_by(|a, b| a.partial_cmp(b).unwrap());
2834    let correction = residuals[residuals.len() / 2].clamp(-max_correction_m, max_correction_m);
2835    if correction.abs() <= 1.0e-6 {
2836        return false;
2837    }
2838    relative_pose.world_to_camera.translation.y += correction;
2839    true
2840}
2841
2842fn should_refine_current_stereo_pose(
2843    translation_history_m: &[f64],
2844    pnp_report: Option<&PnpSelectedReport>,
2845    source: StereoRelativePoseSource,
2846    config: &StereoVoFrontendConfig,
2847) -> bool {
2848    if config.stereo_pose_refinement {
2849        return true;
2850    }
2851    if translation_history_m.len() < config.stereo_pose_refinement_auto_min_history {
2852        return false;
2853    }
2854    let Some(recent_median) = recent_translation_median(
2855        translation_history_m,
2856        config.stereo_pose_refinement_auto_min_history,
2857    ) else {
2858        return false;
2859    };
2860    if recent_median < config.stereo_pose_refinement_auto_min_median_translation_m {
2861        return false;
2862    }
2863    is_weak_motion_scale_consensus(
2864        pnp_report,
2865        source,
2866        config.stereo_pose_refinement_auto_max_pnp_inlier_ratio,
2867    )
2868}
2869
2870fn recent_translation_median(history: &[f64], window: usize) -> Option<f64> {
2871    recent_positive_median(history, window)
2872}
2873
2874fn recent_positive_median(history: &[f64], window: usize) -> Option<f64> {
2875    recent_positive_percentile(history, window, 0.5)
2876}
2877
2878fn recent_positive_percentile(history: &[f64], window: usize, percentile: f64) -> Option<f64> {
2879    if history.is_empty() || window == 0 {
2880        return None;
2881    }
2882    let start = history.len().saturating_sub(window);
2883    let mut values = history[start..]
2884        .iter()
2885        .copied()
2886        .filter(|v| v.is_finite() && *v > 0.0)
2887        .collect::<Vec<_>>();
2888    if values.is_empty() {
2889        return None;
2890    }
2891    values.sort_by(|a, b| a.partial_cmp(b).unwrap());
2892    let clamped = if percentile.is_finite() {
2893        percentile.clamp(0.0, 1.0)
2894    } else {
2895        0.5
2896    };
2897    let index = ((values.len() - 1) as f64 * clamped).round() as usize;
2898    Some(values[index])
2899}
2900
2901fn relative_rotation_angle_deg(relative_pose: &Pose) -> f64 {
2902    relative_pose.world_to_camera.rotation.angle().to_degrees()
2903}
2904
2905fn recent_translation_direction(history: &[Vector3<f64>], window: usize) -> Option<Vector3<f64>> {
2906    if history.is_empty() || window == 0 {
2907        return None;
2908    }
2909    let start = history.len().saturating_sub(window);
2910    let mut sum = Vector3::zeros();
2911    let mut count = 0usize;
2912    for t in &history[start..] {
2913        let norm = t.norm();
2914        if norm.is_finite() && norm > 1.0e-9 {
2915            sum += *t / norm;
2916            count += 1;
2917        }
2918    }
2919    if count == 0 {
2920        return None;
2921    }
2922    let norm = sum.norm();
2923    if !norm.is_finite() || norm <= 1.0e-9 {
2924        return None;
2925    }
2926    Some(sum / norm)
2927}
2928
2929fn recent_rotation_vector(history: &[Vector3<f64>], window: usize) -> Option<Vector3<f64>> {
2930    if history.is_empty() || window == 0 {
2931        return None;
2932    }
2933    let start = history.len().saturating_sub(window);
2934    let mut sum = Vector3::zeros();
2935    let mut count = 0usize;
2936    for v in &history[start..] {
2937        if v.iter().all(|x| x.is_finite()) {
2938            sum += *v;
2939            count += 1;
2940        }
2941    }
2942    if count == 0 {
2943        return None;
2944    }
2945    let mean = sum / count as f64;
2946    if mean.iter().all(|v| v.is_finite()) {
2947        Some(mean)
2948    } else {
2949        None
2950    }
2951}
2952
2953fn is_weak_motion_scale_consensus(
2954    pnp_report: Option<&PnpSelectedReport>,
2955    source: StereoRelativePoseSource,
2956    max_pnp_inlier_ratio: f64,
2957) -> bool {
2958    if source != StereoRelativePoseSource::Pnp {
2959        return true;
2960    }
2961    let Some(report) = pnp_report else {
2962        return true;
2963    };
2964    if report.correspondence_count == 0 {
2965        return true;
2966    }
2967    let ratio = report.inlier_count as f64 / report.correspondence_count as f64;
2968    ratio < max_pnp_inlier_ratio
2969}
2970
2971#[cfg(test)]
2972// Tests build large `*Config` fixtures by tweaking a handful of fields off
2973// `Default::default()`; field-by-field assignment reads more clearly than a
2974// struct-update literal here and keeps each gate's relevant knobs together.
2975#[allow(clippy::field_reassign_with_default)]
2976mod tests {
2977    use super::*;
2978    use crate::features::FeatureSet;
2979    use crate::matching::{BruteForceMatcher, DescriptorMatch, Matcher};
2980    use nalgebra::{Point2, UnitQuaternion, Vector3};
2981    use visloc_core::geometry::{Pose, SE3};
2982
2983    fn camera() -> Camera {
2984        Camera::pinhole(1, 1241, 376, 718.856, 718.856, 607.193, 185.216)
2985    }
2986
2987    #[test]
2988    fn default_rescue_config_keeps_adopted_guardrails() {
2989        let config = StereoVoFrontendConfig::default();
2990        assert!(matches!(
2991            config.stereo.depth_gate,
2992            StereoDepthGate::Adaptive(_)
2993        ));
2994        assert_eq!(config.motion_scale_rescue_min_history, 20);
2995        assert_eq!(config.motion_scale_rescue_min_median_translation_m, 1.5);
2996        assert_eq!(config.motion_scale_rescue_min_translation_ratio, 0.97);
2997        assert_eq!(config.motion_scale_rescue_max_translation_ratio, 1.6);
2998        assert_eq!(config.motion_scale_rescue_target_percentile, 0.75);
2999        assert_eq!(config.motion_scale_rescue_max_pnp_inlier_ratio, 1.05);
3000        assert_eq!(config.translation_direction_rescue_min_history, 20);
3001        assert_eq!(
3002            config.translation_direction_rescue_min_median_translation_m,
3003            1.5
3004        );
3005        assert_eq!(config.translation_direction_rescue_max_angle_deg, 10.0);
3006        assert_eq!(
3007            config.translation_direction_rescue_max_pnp_inlier_ratio,
3008            0.45
3009        );
3010        assert_eq!(config.rotation_spike_rescue_min_history, 20);
3011        assert_eq!(config.rotation_spike_rescue_min_angle_deg, 1.0);
3012        assert_eq!(config.rotation_spike_rescue_max_angle_ratio, 3.0);
3013        assert_eq!(config.rotation_vector_rescue_min_history, 20);
3014        assert_eq!(config.rotation_vector_rescue_max_delta_deg, 0.4);
3015        assert_eq!(config.rotation_vector_rescue_max_pnp_inlier_ratio, 0.45);
3016        assert_eq!(config.pnp_kabsch_challenge_max_inlier_ratio, 0.0);
3017        assert_eq!(config.pnp_kabsch_challenge_min_3d_inlier_gain, 8);
3018        assert_eq!(config.pnp_kabsch_challenge_max_residual_ratio, 0.85);
3019        assert!(!config.stereo_vertical_alignment);
3020        assert_eq!(config.stereo_vertical_alignment_min_pairs, 80);
3021        assert_eq!(config.stereo_vertical_alignment_max_correction_m, 0.25);
3022        assert_eq!(config.stereo_pose_refinement_auto_min_history, 20);
3023        assert_eq!(config.stereo_pose_refinement_auto_max_pnp_inlier_ratio, 1.0);
3024        assert_eq!(config.temporal_max_row_delta_px, None);
3025        assert_eq!(config.temporal_auto_max_row_delta_px, None);
3026        assert_eq!(config.temporal_auto_min_history, 20);
3027        assert_eq!(config.temporal_auto_min_median_translation_m, 1.05);
3028        assert_eq!(config.temporal_auto_min_confidence, Some(0.20));
3029        assert_eq!(config.temporal_auto_confidence_min_history, 20);
3030        assert_eq!(
3031            config.temporal_auto_confidence_min_median_translation_m,
3032            1.45
3033        );
3034        assert_eq!(
3035            config.temporal_auto_confidence_curve_min_median_translation_m,
3036            Some(0.95)
3037        );
3038        assert_eq!(
3039            config.temporal_auto_confidence_curve_min_median_rotation_deg,
3040            Some(0.26)
3041        );
3042        assert_eq!(
3043            config.temporal_auto_confidence_max_median_rotation_deg,
3044            Some(0.45)
3045        );
3046    }
3047
3048    #[test]
3049    fn fixed_depth_gate_preserves_legacy_min_depth_behavior() {
3050        let camera = camera();
3051        let baseline = 0.5;
3052        let (left, right) = stereo_feature_sets_for_depths(&camera, baseline, &[1.5, 1.7, 2.0]);
3053        let stereo = triangulate_stereo_features(
3054            &left,
3055            &right,
3056            &camera,
3057            baseline,
3058            &StereoFeatureConfig {
3059                depth_gate: StereoDepthGate::fixed(),
3060                ratio: None,
3061                ..StereoFeatureConfig::default()
3062            },
3063        );
3064        assert!(
3065            stereo.is_empty(),
3066            "fixed 3 m min-depth gate should reject room-scale points"
3067        );
3068    }
3069
3070    #[test]
3071    fn adaptive_depth_gate_lowers_min_depth_for_room_scale_frames() {
3072        let camera = camera();
3073        let baseline = 0.5;
3074        let depths: Vec<f64> = (0..30).map(|i| 1.5 + (i as f64) * 0.02).collect();
3075        let (left, right) = stereo_feature_sets_for_depths(&camera, baseline, &depths);
3076        let mut state = StereoDepthGateState::default();
3077        let outcome = triangulate_stereo_features_with_depth_state(
3078            &left,
3079            &right,
3080            &camera,
3081            baseline,
3082            &StereoFeatureConfig {
3083                ratio: None,
3084                ..StereoFeatureConfig::default()
3085            },
3086            Some(&mut state),
3087        );
3088
3089        assert!(outcome.diagnostics.adaptive);
3090        assert!(
3091            outcome.diagnostics.effective_min_depth_m < 3.0,
3092            "room-scale effective min depth should drop below the legacy 3 m gate, got {}",
3093            outcome.diagnostics.effective_min_depth_m
3094        );
3095        assert_eq!(outcome.features.len(), depths.len());
3096    }
3097
3098    #[test]
3099    fn adaptive_depth_gate_keeps_far_scene_floor_against_near_outlier() {
3100        let camera = camera();
3101        let baseline = 0.5;
3102        let mut depths = vec![0.8];
3103        depths.extend((0..29).map(|i| 12.0 + (i as f64) * 0.1));
3104        let (left, right) = stereo_feature_sets_for_depths(&camera, baseline, &depths);
3105        let outcome = triangulate_stereo_features_with_depth_state(
3106            &left,
3107            &right,
3108            &camera,
3109            baseline,
3110            &StereoFeatureConfig {
3111                ratio: None,
3112                ..StereoFeatureConfig::default()
3113            },
3114            None,
3115        );
3116
3117        assert!(outcome.diagnostics.adaptive);
3118        assert_eq!(outcome.diagnostics.effective_min_depth_m, 3.0);
3119        assert_eq!(outcome.features.len(), depths.len() - 1);
3120        assert!(
3121            outcome
3122                .features
3123                .iter()
3124                .all(|feature| feature.point_cam.z >= 3.0),
3125            "near outlier should not pass the hall-scale adaptive gate"
3126        );
3127    }
3128
3129    #[test]
3130    fn adaptive_depth_gate_hysteresis_keeps_small_updates_stable() {
3131        let camera = camera();
3132        let baseline = 0.5;
3133        let far_depths: Vec<f64> = (0..30).map(|i| 12.0 + (i as f64) * 0.1).collect();
3134        let (far_left, far_right) = stereo_feature_sets_for_depths(&camera, baseline, &far_depths);
3135        let mid_depths: Vec<f64> = (0..30).map(|i| 3.35 + (i as f64) * 0.01).collect();
3136        let (mid_left, mid_right) = stereo_feature_sets_for_depths(&camera, baseline, &mid_depths);
3137        let mut state = StereoDepthGateState::default();
3138        let config = StereoFeatureConfig {
3139            ratio: None,
3140            ..StereoFeatureConfig::default()
3141        };
3142
3143        let first = triangulate_stereo_features_with_depth_state(
3144            &far_left,
3145            &far_right,
3146            &camera,
3147            baseline,
3148            &config,
3149            Some(&mut state),
3150        );
3151        let second = triangulate_stereo_features_with_depth_state(
3152            &mid_left,
3153            &mid_right,
3154            &camera,
3155            baseline,
3156            &config,
3157            Some(&mut state),
3158        );
3159
3160        assert_eq!(first.diagnostics.effective_min_depth_m, 3.0);
3161        assert_eq!(
3162            second.diagnostics.effective_min_depth_m, 3.0,
3163            "mid-scale proposal is inside the hysteresis band and should keep the prior gate"
3164        );
3165    }
3166
3167    #[test]
3168    fn temporal_row_gate_prefers_explicit_override() {
3169        let mut config = StereoVoFrontendConfig::default();
3170        config.temporal_max_row_delta_px = Some(4.0);
3171        config.temporal_auto_max_row_delta_px = Some(8.0);
3172        config.temporal_auto_min_history = 3;
3173        config.temporal_auto_min_median_translation_m = 10.0;
3174        assert_eq!(
3175            effective_temporal_max_row_delta_px(&[0.1, 0.2, 0.3], &config),
3176            Some(4.0)
3177        );
3178    }
3179
3180    #[test]
3181    fn temporal_row_gate_activates_only_for_fast_recent_motion() {
3182        let mut config = StereoVoFrontendConfig::default();
3183        config.temporal_max_row_delta_px = None;
3184        config.temporal_auto_max_row_delta_px = Some(8.0);
3185        config.temporal_auto_min_history = 3;
3186        config.temporal_auto_min_median_translation_m = 0.9;
3187
3188        assert_eq!(
3189            effective_temporal_max_row_delta_px(&[0.8, 0.85], &config),
3190            None
3191        );
3192        assert_eq!(
3193            effective_temporal_max_row_delta_px(&[0.7, 0.8, 0.85], &config),
3194            None
3195        );
3196        assert_eq!(
3197            effective_temporal_max_row_delta_px(&[0.7, 0.95, 1.1], &config),
3198            Some(8.0)
3199        );
3200    }
3201
3202    #[test]
3203    fn temporal_confidence_gate_activates_only_for_fast_recent_motion() {
3204        let mut config = StereoVoFrontendConfig::default();
3205        config.temporal_auto_min_confidence = Some(0.20);
3206        config.temporal_auto_confidence_min_history = 3;
3207        config.temporal_auto_confidence_min_median_translation_m = 0.8;
3208
3209        assert_eq!(
3210            effective_temporal_min_confidence(&[0.7, 0.75], &[0.2, 0.2], &config),
3211            None
3212        );
3213        assert_eq!(
3214            effective_temporal_min_confidence(&[0.65, 0.7, 0.75], &[0.2, 0.2, 0.2], &config),
3215            None
3216        );
3217        assert_eq!(
3218            effective_temporal_min_confidence(&[0.7, 0.85, 0.9], &[0.2, 0.2, 0.2], &config),
3219            Some(0.20)
3220        );
3221        assert_eq!(
3222            effective_temporal_min_confidence(&[0.7, 0.85, 0.9], &[0.6, 0.7, 0.8], &config),
3223            None
3224        );
3225    }
3226
3227    #[test]
3228    fn temporal_confidence_gate_activates_for_medium_curved_motion() {
3229        let mut config = StereoVoFrontendConfig::default();
3230        config.temporal_auto_min_confidence = Some(0.20);
3231        config.temporal_auto_confidence_min_history = 3;
3232        config.temporal_auto_confidence_min_median_translation_m = 1.5;
3233        config.temporal_auto_confidence_curve_min_median_translation_m = Some(0.9);
3234        config.temporal_auto_confidence_curve_min_median_rotation_deg = Some(0.18);
3235        config.temporal_auto_confidence_max_median_rotation_deg = Some(0.45);
3236
3237        assert_eq!(
3238            effective_temporal_min_confidence(&[0.8, 0.95, 1.0], &[0.15, 0.16, 0.17], &config),
3239            None
3240        );
3241        assert_eq!(
3242            effective_temporal_min_confidence(&[0.8, 0.95, 1.0], &[0.18, 0.22, 0.24], &config),
3243            Some(0.20)
3244        );
3245        assert_eq!(
3246            effective_temporal_min_confidence(&[0.8, 0.95, 1.0], &[0.4, 0.5, 0.6], &config),
3247            None
3248        );
3249    }
3250
3251    #[test]
3252    fn temporal_confidence_filter_preserves_matchers_without_confidence() {
3253        let matches = vec![
3254            DescriptorMatch {
3255                query_index: 0,
3256                train_index: 1,
3257                distance: 0.1,
3258                second_best_distance: None,
3259                ratio: None,
3260                confidence: None,
3261            },
3262            DescriptorMatch {
3263                query_index: 2,
3264                train_index: 3,
3265                distance: 0.2,
3266                second_best_distance: None,
3267                ratio: None,
3268                confidence: None,
3269            },
3270        ];
3271
3272        assert_eq!(
3273            filter_temporal_matches_by_confidence(&matches, 0.20),
3274            matches
3275        );
3276    }
3277
3278    #[test]
3279    fn temporal_confidence_filter_drops_low_confidence_deep_matches() {
3280        let matches = vec![
3281            DescriptorMatch {
3282                query_index: 0,
3283                train_index: 1,
3284                distance: 0.1,
3285                second_best_distance: None,
3286                ratio: None,
3287                confidence: Some(0.19),
3288            },
3289            DescriptorMatch {
3290                query_index: 2,
3291                train_index: 3,
3292                distance: 0.2,
3293                second_best_distance: None,
3294                ratio: None,
3295                confidence: Some(0.20),
3296            },
3297        ];
3298
3299        let filtered = filter_temporal_matches_by_confidence(&matches, 0.20);
3300
3301        assert_eq!(filtered.len(), 1);
3302        assert_eq!(filtered[0].query_index, 2);
3303    }
3304
3305    #[test]
3306    fn stereo_vertical_alignment_uses_median_y_residual_only() {
3307        let mut config = StereoVoFrontendConfig::default();
3308        config.stereo_vertical_alignment = true;
3309        config.stereo_vertical_alignment_min_pairs = 3;
3310        config.stereo_vertical_alignment_max_correction_m = 0.25;
3311        let mut pose = Pose {
3312            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.5, 0.0, -1.0)),
3313        };
3314        assert!(align_vertical_translation_from_residuals(
3315            &mut pose,
3316            vec![0.2, 0.2, 0.2],
3317            config.stereo_vertical_alignment_max_correction_m,
3318        ));
3319        assert!((pose.world_to_camera.translation.x - 0.5).abs() < 1.0e-12);
3320        assert!((pose.world_to_camera.translation.y - 0.2).abs() < 1.0e-12);
3321        assert!((pose.world_to_camera.translation.z + 1.0).abs() < 1.0e-12);
3322    }
3323
3324    #[test]
3325    fn stereo_vertical_alignment_clamps_large_corrections() {
3326        let mut config = StereoVoFrontendConfig::default();
3327        config.stereo_vertical_alignment = true;
3328        config.stereo_vertical_alignment_min_pairs = 3;
3329        config.stereo_vertical_alignment_max_correction_m = 0.25;
3330        let mut pose = Pose {
3331            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::zeros()),
3332        };
3333        assert!(align_vertical_translation_from_residuals(
3334            &mut pose,
3335            vec![1.0, 1.0, 1.0],
3336            config.stereo_vertical_alignment_max_correction_m,
3337        ));
3338        assert!((pose.world_to_camera.translation.y - 0.25).abs() < 1.0e-12);
3339    }
3340
3341    #[test]
3342    fn weak_pnp_triggers_kabsch_challenger_only_below_ratio_gate() {
3343        let mut config = StereoVoFrontendConfig::default();
3344        config.pnp_kabsch_challenge_max_inlier_ratio = 0.20;
3345        let weak = PnpSelectedReport {
3346            pose: Pose::identity(),
3347            inlier_count: 19,
3348            correspondence_count: 100,
3349            mean_reprojection_error: 1.0,
3350        };
3351        let strong = PnpSelectedReport {
3352            inlier_count: 20,
3353            ..weak.clone()
3354        };
3355
3356        assert!(should_try_kabsch_challenger(&weak, &config));
3357        assert!(!should_try_kabsch_challenger(&strong, &config));
3358    }
3359
3360    #[test]
3361    fn kabsch_challenger_needs_inlier_gain_and_residual_gain() {
3362        let config = StereoVoFrontendConfig::default();
3363        let pnp_score = Pose3d3dScore {
3364            inlier_count: 20,
3365            mean_residual_m: 1.0,
3366        };
3367        let better = KabschRansacReport {
3368            relative_pose: Pose::identity(),
3369            inliers: (0..30).collect(),
3370            mean_residual_m: 0.7,
3371        };
3372        let too_few_extra_inliers = KabschRansacReport {
3373            inliers: (0..27).collect(),
3374            ..better.clone()
3375        };
3376        let too_noisy = KabschRansacReport {
3377            mean_residual_m: 0.9,
3378            ..better.clone()
3379        };
3380
3381        assert!(is_kabsch_challenger_better(&better, pnp_score, &config));
3382        assert!(!is_kabsch_challenger_better(
3383            &too_few_extra_inliers,
3384            pnp_score,
3385            &config
3386        ));
3387        assert!(!is_kabsch_challenger_better(&too_noisy, pnp_score, &config));
3388    }
3389
3390    /// Project a world-frame point through `pose` and the camera. Used by
3391    /// the round-trip test below.
3392    fn project(camera: &Camera, pose: &Pose, x_world: &Point3<f64>) -> Point2<f64> {
3393        let xc = pose.transform_world_point(x_world);
3394        camera.project(&xc).expect("point in front of camera")
3395    }
3396
3397    /// Build a synthetic FeatureSet at the given pixel locations. Each
3398    /// keypoint gets a 1-D descriptor encoding its `landmark id`, so a
3399    /// brute-force matcher can recover the unique correspondence.
3400    fn synthetic_feature_set(keypoints: &[(usize, Point2<f64>)]) -> FeatureSet {
3401        let kps: Vec<Point2<f64>> = keypoints.iter().map(|(_, p)| *p).collect();
3402        let descriptors: Vec<Vec<f32>> = keypoints.iter().map(|(id, _)| vec![*id as f32]).collect();
3403        FeatureSet::new(kps, descriptors).expect("synthetic FeatureSet")
3404    }
3405
3406    fn stereo_feature_sets_for_depths(
3407        camera: &Camera,
3408        baseline: f64,
3409        depths: &[f64],
3410    ) -> (FeatureSet, FeatureSet) {
3411        let (fx, _, _, _) = camera.intrinsics().unwrap();
3412        let pose = Pose::identity();
3413        let mut left_kps = Vec::with_capacity(depths.len());
3414        let mut right_kps = Vec::with_capacity(depths.len());
3415        for (id, depth) in depths.iter().copied().enumerate() {
3416            let x = ((id % 7) as f64 - 3.0) * 0.04;
3417            let y = ((id / 7) as f64 - 2.0) * 0.03;
3418            let point = Point3::new(x, y, depth);
3419            let left = project(camera, &pose, &point);
3420            let right = Point2::new(left.x - fx * baseline / depth, left.y);
3421            left_kps.push((id, left));
3422            right_kps.push((id, right));
3423        }
3424        (
3425            synthetic_feature_set(&left_kps),
3426            synthetic_feature_set(&right_kps),
3427        )
3428    }
3429
3430    fn descriptor_match(query_index: usize, train_index: usize) -> DescriptorMatch {
3431        DescriptorMatch {
3432            query_index,
3433            train_index,
3434            distance: 0.0,
3435            second_best_distance: None,
3436            ratio: None,
3437            confidence: Some(0.95),
3438        }
3439    }
3440
3441    #[test]
3442    fn triangulate_stereo_features_round_trips_metric_points() {
3443        let camera = camera();
3444        let baseline = 0.537150888;
3445        let (fx, _, _, _) = camera.intrinsics().unwrap();
3446        // Choose a few world-frame points in front of the camera.
3447        let truth: Vec<(usize, Point3<f64>)> = vec![
3448            (0, Point3::new(-1.5, 0.2, 12.0)),
3449            (1, Point3::new(0.5, -0.4, 8.0)),
3450            (2, Point3::new(2.0, 0.0, 25.0)),
3451            (3, Point3::new(-0.5, 0.5, 5.0)),
3452        ];
3453        let pose = Pose::identity();
3454        let mut left_kps: Vec<(usize, Point2<f64>)> = Vec::new();
3455        let mut right_kps: Vec<(usize, Point2<f64>)> = Vec::new();
3456        for (id, p) in &truth {
3457            let l = project(&camera, &pose, p);
3458            // Right pixel: apply `u_r = u_l − fx · b / Z`, same row.
3459            let right = Point2::new(l.x - fx * baseline / p.z, l.y);
3460            left_kps.push((*id, l));
3461            right_kps.push((*id, right));
3462        }
3463        let left = synthetic_feature_set(&left_kps);
3464        let right = synthetic_feature_set(&right_kps);
3465        let stereo = triangulate_stereo_features(
3466            &left,
3467            &right,
3468            &camera,
3469            baseline,
3470            &StereoFeatureConfig {
3471                ratio: None,
3472                ..StereoFeatureConfig::default()
3473            },
3474        );
3475        assert_eq!(stereo.len(), truth.len());
3476        for f in &stereo {
3477            // The "id" field is the same for left and right since we made
3478            // the descriptor encode it; verify the matcher actually paired
3479            // by id and that the recovered point matches truth.
3480            let id = left.descriptors[f.left_index][0] as usize;
3481            let expected = truth.iter().find(|(i, _)| *i == id).unwrap().1;
3482            let err = (f.point_cam - expected).norm();
3483            assert!(err < 1.0e-9, "stereo triangulation error {err} for id {id}");
3484        }
3485    }
3486
3487    #[test]
3488    fn triangulate_stereo_features_rejects_row_mismatched_pairs() {
3489        let camera = camera();
3490        let baseline = 0.5;
3491        // Row mismatch by 5 px should be rejected (default max 1.5 px).
3492        let left = synthetic_feature_set(&[(0, Point2::new(700.0, 200.0))]);
3493        let right = synthetic_feature_set(&[(0, Point2::new(680.0, 205.0))]);
3494        let stereo = triangulate_stereo_features(
3495            &left,
3496            &right,
3497            &camera,
3498            baseline,
3499            &StereoFeatureConfig {
3500                ratio: None,
3501                ..StereoFeatureConfig::default()
3502            },
3503        );
3504        assert!(stereo.is_empty(), "row-mismatched pair must be rejected");
3505    }
3506
3507    #[test]
3508    fn triangulate_stereo_features_rejects_far_field_points() {
3509        let camera = camera();
3510        let baseline = 0.5;
3511        // Disparity = 0.4 < default 1.0 px threshold.
3512        let left = synthetic_feature_set(&[(0, Point2::new(700.0, 200.0))]);
3513        let right = synthetic_feature_set(&[(0, Point2::new(699.6, 200.0))]);
3514        let stereo = triangulate_stereo_features(
3515            &left,
3516            &right,
3517            &camera,
3518            baseline,
3519            &StereoFeatureConfig {
3520                ratio: None,
3521                ..StereoFeatureConfig::default()
3522            },
3523        );
3524        assert!(
3525            stereo.is_empty(),
3526            "sub-threshold disparity must be rejected"
3527        );
3528    }
3529
3530    #[test]
3531    fn triangulate_stereo_feature_matches_uses_explicit_pairs() {
3532        let camera = camera();
3533        let baseline = 0.5;
3534        let left = FeatureSet::new(vec![Point2::new(700.0, 200.0)], vec![vec![0.0]]).unwrap();
3535        let right = FeatureSet::new(
3536            vec![Point2::new(699.0, 210.0), Point2::new(670.0, 200.0)],
3537            vec![vec![0.0], vec![0.0]],
3538        )
3539        .unwrap();
3540        let matches = vec![descriptor_match(0, 1), descriptor_match(0, 0)];
3541
3542        let stereo = triangulate_stereo_feature_matches(
3543            &left,
3544            &right,
3545            &matches,
3546            &camera,
3547            baseline,
3548            &StereoFeatureConfig {
3549                ratio: None,
3550                ..StereoFeatureConfig::default()
3551            },
3552        );
3553
3554        assert_eq!(stereo.len(), 1);
3555        assert_eq!(stereo[0].left_index, 0);
3556        assert_eq!(stereo[0].right_index, 1);
3557        assert!((stereo[0].disparity - 30.0).abs() < 1.0e-9);
3558    }
3559
3560    #[test]
3561    fn build_stereo_temporal_correspondences_links_3d_with_b_pixels() {
3562        // Three triangulated stereo features in frame A, and a temporal
3563        // matcher that pairs each one with a known frame-B pixel.
3564        let a_features = vec![
3565            StereoFeature {
3566                left_index: 5,
3567                right_index: 6,
3568                disparity: 10.0,
3569                point_cam: Point3::new(0.0, 0.0, 5.0),
3570            },
3571            StereoFeature {
3572                left_index: 7,
3573                right_index: 8,
3574                disparity: 5.0,
3575                point_cam: Point3::new(1.0, 0.5, 10.0),
3576            },
3577            StereoFeature {
3578                left_index: 9,
3579                right_index: 10,
3580                disparity: 4.0,
3581                point_cam: Point3::new(-2.0, 0.5, 15.0),
3582            },
3583        ];
3584        let b_left = synthetic_feature_set(&[
3585            (0, Point2::new(100.0, 100.0)),
3586            (1, Point2::new(200.0, 200.0)),
3587            (2, Point2::new(300.0, 300.0)),
3588        ]);
3589        let temporal_matches = vec![
3590            DescriptorMatch {
3591                query_index: 5,
3592                train_index: 0,
3593                distance: 0.1,
3594                second_best_distance: None,
3595                ratio: None,
3596                confidence: None,
3597            },
3598            DescriptorMatch {
3599                query_index: 7,
3600                train_index: 1,
3601                distance: 0.1,
3602                second_best_distance: None,
3603                ratio: None,
3604                confidence: None,
3605            },
3606            // This match's query index has no triangulation in A → drop.
3607            DescriptorMatch {
3608                query_index: 99,
3609                train_index: 2,
3610                distance: 0.1,
3611                second_best_distance: None,
3612                ratio: None,
3613                confidence: None,
3614            },
3615        ];
3616        let pairs = build_stereo_temporal_correspondences(&a_features, &b_left, &temporal_matches);
3617        assert_eq!(pairs.len(), 2);
3618        assert_eq!(pairs[0].point2d, Point2::new(100.0, 100.0));
3619        assert_eq!(pairs[0].point3d, Point3::new(0.0, 0.0, 5.0));
3620        assert_eq!(pairs[1].point2d, Point2::new(200.0, 200.0));
3621        assert_eq!(pairs[1].point3d, Point3::new(1.0, 0.5, 10.0));
3622    }
3623
3624    #[test]
3625    fn adaptive_pnp_depth_triggers_only_on_weak_primary_consensus() {
3626        assert!(!should_try_adaptive_pnp_depth(
3627            Some(&PnpFullScore {
3628                inlier_count: 65,
3629                mean_error: 1.0,
3630            }),
3631            100,
3632            0.65,
3633        ));
3634        assert!(should_try_adaptive_pnp_depth(
3635            Some(&PnpFullScore {
3636                inlier_count: 64,
3637                mean_error: 1.0,
3638            }),
3639            100,
3640            0.65,
3641        ));
3642        assert!(should_try_adaptive_pnp_depth(None, 100, 0.65));
3643        assert!(!should_try_adaptive_pnp_depth(None, 0, 0.65));
3644        assert!(!should_try_adaptive_pnp_depth(
3645            Some(&PnpFullScore {
3646                inlier_count: 1,
3647                mean_error: 1.0,
3648            }),
3649            100,
3650            f64::NAN,
3651        ));
3652    }
3653
3654    /// A vehicle that cruises at 2 m/frame, then slows to 1 m/frame, through
3655    /// the motion-scale rescue with the default settings (every PnP pose
3656    /// counts as weak consensus). Returns the steps the frontend keeps.
3657    fn decelerate_through_rescue(release: bool) -> Vec<f64> {
3658        let config = StereoVoFrontendConfig {
3659            motion_scale_rescue_release_full_window: release,
3660            ..StereoVoFrontendConfig::default()
3661        };
3662        let mut rescue = MotionScaleRescue::default();
3663        (0..160)
3664            .map(|frame| {
3665                let step = match frame {
3666                    0..40 => 2.0,
3667                    40..60 => 2.0 - 0.05 * f64::from(frame - 39),
3668                    _ => 1.0,
3669                };
3670                let mut pose = Pose {
3671                    world_to_camera: SE3::new(
3672                        UnitQuaternion::identity(),
3673                        Vector3::new(0.0, 0.0, step),
3674                    ),
3675                };
3676                rescue.apply(&mut pose, None, StereoRelativePoseSource::Pnp, &config);
3677                let kept = pose.world_to_camera.translation.norm();
3678                rescue.record(step, kept);
3679                kept
3680            })
3681            .collect()
3682    }
3683
3684    #[test]
3685    fn rotation_from_orthonormal_matches_from_matrix_and_survives_the_half_turn() {
3686        // An ordinary rotation: bit-identical to nalgebra's unbounded call.
3687        let ordinary = UnitQuaternion::from_euler_angles(0.3, -0.2, 1.1)
3688            .to_rotation_matrix()
3689            .into_inner();
3690        let expected = UnitQuaternion::from_matrix(&ordinary);
3691        let actual = rotation_from_orthonormal(&ordinary);
3692        assert_eq!(actual.coords.as_slice(), expected.coords.as_slice());
3693
3694        // The half turn KITTI 01 produced at pair ~326 (column-major). The
3695        // unbounded projection cycles forever on it; capped, it does not
3696        // converge, and the matrix itself is returned.
3697        let half_turn = Matrix3::from_column_slice(&[
3698            -0.9954361201834596,
3699            0.0954302396208945,
3700            0.0,
3701            0.09543023962089417,
3702            0.9954361201834596,
3703            0.0,
3704            0.0,
3705            0.0,
3706            -1.0,
3707        ]);
3708        let capped = nalgebra::Rotation3::from_matrix_eps(
3709            &half_turn,
3710            f64::EPSILON,
3711            visloc_core::geometry::ROTATION_FROM_MATRIX_MAX_ITERATIONS,
3712            nalgebra::Rotation3::identity(),
3713        );
3714        assert!((capped.matrix() - half_turn).norm() > 1.0e-6);
3715        let rotation = rotation_from_orthonormal(&half_turn);
3716        assert!((rotation.to_rotation_matrix().into_inner() - half_turn).norm() < 1.0e-12);
3717    }
3718
3719    #[test]
3720    fn motion_scale_rescue_releases_after_a_full_window_of_rescues() {
3721        // Without the release the rescued steps keep the median at the old
3722        // speed and every slower step is scaled back up, for good.
3723        let locked = decelerate_through_rescue(false);
3724        assert!(locked[60..].iter().all(|&step| step > 1.9), "{locked:?}");
3725        // With it the streak ends after one window (20 pairs), the history
3726        // takes the raw steps, and the rescue stays off at the new speed.
3727        let released = decelerate_through_rescue(true);
3728        let first_kept = (40..160)
3729            .find(|&frame| (released[frame] - 1.0).abs() < 1e-12)
3730            .expect("the rescue never released");
3731        assert!(first_kept <= 62, "released only at frame {first_kept}");
3732        assert!(
3733            released[first_kept..]
3734                .iter()
3735                .all(|&step| (step - 1.0).abs() < 1e-12),
3736            "{released:?}"
3737        );
3738        // A single collapsed step during the cruise is still rescued.
3739        let mut rescue = MotionScaleRescue::default();
3740        let config = StereoVoFrontendConfig::default();
3741        for _ in 0..30 {
3742            rescue.record(2.0, 2.0);
3743        }
3744        let mut collapsed = Pose {
3745            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.5)),
3746        };
3747        assert!(rescue.apply(&mut collapsed, None, StereoRelativePoseSource::Pnp, &config));
3748        assert!((collapsed.world_to_camera.translation.norm() - 2.0).abs() < 1e-12);
3749    }
3750
3751    #[test]
3752    fn motion_scale_rescue_requires_fast_history_and_weak_consensus() {
3753        let mut config = StereoVoFrontendConfig::default();
3754        config.motion_scale_rescue_min_history = 4;
3755        config.motion_scale_rescue_min_median_translation_m = 1.5;
3756        config.motion_scale_rescue_min_translation_ratio = 0.35;
3757        config.motion_scale_rescue_max_translation_ratio = 1.6;
3758        config.motion_scale_rescue_max_pnp_inlier_ratio = 0.25;
3759
3760        let history = [2.2, 2.5, 2.7, 2.6];
3761        let mut pose = Pose {
3762            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.1, 0.0, 0.0)),
3763        };
3764        assert!(rescue_collapsed_motion_scale(
3765            &mut pose,
3766            &history,
3767            None,
3768            StereoRelativePoseSource::KabschFallback,
3769            &config,
3770        ));
3771        assert!((pose.world_to_camera.translation.norm() - 2.6).abs() < 1.0e-9);
3772
3773        let slow_history = [0.6, 0.7, 0.8, 0.7];
3774        let mut slow_pose = Pose {
3775            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.1, 0.0, 0.0)),
3776        };
3777        assert!(!rescue_collapsed_motion_scale(
3778            &mut slow_pose,
3779            &slow_history,
3780            None,
3781            StereoRelativePoseSource::KabschFallback,
3782            &config,
3783        ));
3784
3785        let strong_report = PnpSelectedReport {
3786            pose: Pose::identity(),
3787            inlier_count: 80,
3788            correspondence_count: 100,
3789            mean_reprojection_error: 1.0,
3790        };
3791        let mut strong_pose = Pose {
3792            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.1, 0.0, 0.0)),
3793        };
3794        assert!(!rescue_collapsed_motion_scale(
3795            &mut strong_pose,
3796            &history,
3797            Some(&strong_report),
3798            StereoRelativePoseSource::Pnp,
3799            &config,
3800        ));
3801
3802        let weak_report = PnpSelectedReport {
3803            pose: Pose::identity(),
3804            inlier_count: 20,
3805            correspondence_count: 100,
3806            mean_reprojection_error: 1.0,
3807        };
3808        let mut inflated_pose = Pose {
3809            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(5.0, 0.0, 0.0)),
3810        };
3811        assert!(rescue_collapsed_motion_scale(
3812            &mut inflated_pose,
3813            &history,
3814            Some(&weak_report),
3815            StereoRelativePoseSource::Pnp,
3816            &config,
3817        ));
3818        assert!((inflated_pose.world_to_camera.translation.norm() - 2.6).abs() < 1.0e-9);
3819    }
3820
3821    #[test]
3822    fn motion_scale_rescue_uses_configured_target_percentile() {
3823        let mut config = StereoVoFrontendConfig::default();
3824        config.motion_scale_rescue_min_history = 5;
3825        config.motion_scale_rescue_min_median_translation_m = 1.5;
3826        config.motion_scale_rescue_min_translation_ratio = 0.65;
3827        config.motion_scale_rescue_target_percentile = 0.75;
3828
3829        let history = [2.0, 2.1, 2.2, 2.8, 3.0];
3830        let mut pose = Pose {
3831            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(1.0, 0.0, 0.0)),
3832        };
3833        assert!(rescue_collapsed_motion_scale(
3834            &mut pose,
3835            &history,
3836            None,
3837            StereoRelativePoseSource::KabschFallback,
3838            &config,
3839        ));
3840        assert!((pose.world_to_camera.translation.norm() - 2.8).abs() < 1.0e-9);
3841    }
3842
3843    #[test]
3844    fn stereo_pose_refinement_auto_requires_fast_history_and_weak_consensus() {
3845        let mut config = StereoVoFrontendConfig::default();
3846        config.stereo_pose_refinement = false;
3847        config.stereo_pose_refinement_auto_min_history = 4;
3848        config.stereo_pose_refinement_auto_min_median_translation_m = 1.5;
3849        config.stereo_pose_refinement_auto_max_pnp_inlier_ratio = 0.65;
3850        let history = [1.9, 2.0, 2.1, 2.2];
3851        let weak_report = PnpSelectedReport {
3852            pose: Pose::identity(),
3853            inlier_count: 12,
3854            correspondence_count: 40,
3855            mean_reprojection_error: 1.0,
3856        };
3857        assert!(should_refine_current_stereo_pose(
3858            &history,
3859            Some(&weak_report),
3860            StereoRelativePoseSource::Pnp,
3861            &config,
3862        ));
3863
3864        let strong_report = PnpSelectedReport {
3865            pose: Pose::identity(),
3866            inlier_count: 32,
3867            correspondence_count: 40,
3868            mean_reprojection_error: 1.0,
3869        };
3870        assert!(!should_refine_current_stereo_pose(
3871            &history,
3872            Some(&strong_report),
3873            StereoRelativePoseSource::Pnp,
3874            &config,
3875        ));
3876        assert!(!should_refine_current_stereo_pose(
3877            &[0.6, 0.7, 0.8, 0.9],
3878            Some(&weak_report),
3879            StereoRelativePoseSource::Pnp,
3880            &config,
3881        ));
3882        assert!(should_refine_current_stereo_pose(
3883            &history,
3884            Some(&strong_report),
3885            StereoRelativePoseSource::KabschFallback,
3886            &config,
3887        ));
3888
3889        config.stereo_pose_refinement = true;
3890        assert!(should_refine_current_stereo_pose(
3891            &[],
3892            Some(&strong_report),
3893            StereoRelativePoseSource::Pnp,
3894            &config,
3895        ));
3896    }
3897
3898    #[test]
3899    fn translation_direction_rescue_requires_fast_history_and_weak_consensus() {
3900        let mut config = StereoVoFrontendConfig::default();
3901        config.translation_direction_rescue_min_history = 4;
3902        config.translation_direction_rescue_min_median_translation_m = 1.5;
3903        config.translation_direction_rescue_max_angle_deg = 12.0;
3904        config.translation_direction_rescue_max_pnp_inlier_ratio = 0.45;
3905        let translation_history = [2.1, 2.2, 2.3, 2.4];
3906        let direction_history = [
3907            Vector3::new(0.0, 0.0, 2.1),
3908            Vector3::new(0.02, 0.0, 2.2),
3909            Vector3::new(-0.01, 0.0, 2.3),
3910            Vector3::new(0.0, 0.0, 2.4),
3911        ];
3912        let weak_report = PnpSelectedReport {
3913            pose: Pose::identity(),
3914            inlier_count: 10,
3915            correspondence_count: 40,
3916            mean_reprojection_error: 1.0,
3917        };
3918        let mut pose = Pose {
3919            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(1.2, 0.0, 2.0)),
3920        };
3921        let original_norm = pose.world_to_camera.translation.norm();
3922        assert!(rescue_translation_direction(
3923            &mut pose,
3924            &translation_history,
3925            &direction_history,
3926            Some(&weak_report),
3927            StereoRelativePoseSource::Pnp,
3928            &config,
3929        ));
3930        assert!((pose.world_to_camera.translation.norm() - original_norm).abs() < 1.0e-9);
3931        assert!(pose.world_to_camera.translation.x.abs() < 0.02);
3932        assert!(pose.world_to_camera.translation.z > 0.0);
3933
3934        let strong_report = PnpSelectedReport {
3935            pose: Pose::identity(),
3936            inlier_count: 30,
3937            correspondence_count: 40,
3938            mean_reprojection_error: 1.0,
3939        };
3940        let mut strong_pose = Pose {
3941            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(1.2, 0.0, 2.0)),
3942        };
3943        assert!(!rescue_translation_direction(
3944            &mut strong_pose,
3945            &translation_history,
3946            &direction_history,
3947            Some(&strong_report),
3948            StereoRelativePoseSource::Pnp,
3949            &config,
3950        ));
3951
3952        let mut slow_pose = Pose {
3953            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(1.2, 0.0, 2.0)),
3954        };
3955        assert!(!rescue_translation_direction(
3956            &mut slow_pose,
3957            &[0.7, 0.8, 0.9, 0.8],
3958            &direction_history,
3959            Some(&weak_report),
3960            StereoRelativePoseSource::Pnp,
3961            &config,
3962        ));
3963
3964        let mut aligned_pose = Pose {
3965            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.1, 0.0, 2.0)),
3966        };
3967        assert!(!rescue_translation_direction(
3968            &mut aligned_pose,
3969            &translation_history,
3970            &direction_history,
3971            Some(&weak_report),
3972            StereoRelativePoseSource::Pnp,
3973            &config,
3974        ));
3975    }
3976
3977    #[test]
3978    fn translation_direction_rescue_requires_vector_history_window() {
3979        let mut config = StereoVoFrontendConfig::default();
3980        config.translation_direction_rescue_min_history = 4;
3981        config.translation_direction_rescue_min_median_translation_m = 1.5;
3982        config.translation_direction_rescue_max_angle_deg = 10.0;
3983        let translation_history = [2.1, 2.2, 2.3, 2.4];
3984        let short_direction_history = [
3985            Vector3::new(0.0, 0.0, 2.1),
3986            Vector3::new(0.0, 0.0, 2.2),
3987            Vector3::new(0.0, 0.0, 2.3),
3988        ];
3989        let mut pose = Pose {
3990            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(1.2, 0.0, 2.0)),
3991        };
3992        let before = pose.world_to_camera.translation;
3993
3994        assert!(!rescue_translation_direction(
3995            &mut pose,
3996            &translation_history,
3997            &short_direction_history,
3998            None,
3999            StereoRelativePoseSource::KabschFallback,
4000            &config,
4001        ));
4002        assert_eq!(pose.world_to_camera.translation, before);
4003    }
4004
4005    #[test]
4006    fn translation_direction_rescue_handles_kabsch_fallback_without_pnp_report() {
4007        let mut config = StereoVoFrontendConfig::default();
4008        config.translation_direction_rescue_min_history = 4;
4009        config.translation_direction_rescue_min_median_translation_m = 1.5;
4010        config.translation_direction_rescue_max_angle_deg = 10.0;
4011        let translation_history = [2.1, 2.2, 2.3, 2.4];
4012        let direction_history = [
4013            Vector3::new(0.0, 0.0, 2.1),
4014            Vector3::new(0.0, 0.0, 2.2),
4015            Vector3::new(0.0, 0.0, 2.3),
4016            Vector3::new(0.0, 0.0, 2.4),
4017        ];
4018        let mut pose = Pose {
4019            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(-1.5, 0.0, 1.5)),
4020        };
4021        let original_norm = pose.world_to_camera.translation.norm();
4022
4023        assert!(rescue_translation_direction(
4024            &mut pose,
4025            &translation_history,
4026            &direction_history,
4027            None,
4028            StereoRelativePoseSource::KabschFallback,
4029            &config,
4030        ));
4031        assert!((pose.world_to_camera.translation.norm() - original_norm).abs() < 1.0e-9);
4032        assert!(pose.world_to_camera.translation.x.abs() < 1.0e-9);
4033        assert!((pose.world_to_camera.translation.z - original_norm).abs() < 1.0e-9);
4034    }
4035
4036    #[test]
4037    fn translation_direction_rescue_clamps_backward_outlier_but_keeps_magnitude() {
4038        let mut config = StereoVoFrontendConfig::default();
4039        config.translation_direction_rescue_min_history = 4;
4040        config.translation_direction_rescue_min_median_translation_m = 1.5;
4041        config.translation_direction_rescue_max_angle_deg = 10.0;
4042        let translation_history = [2.1, 2.2, 2.3, 2.4];
4043        let direction_history = [
4044            Vector3::new(0.0, 0.0, 2.1),
4045            Vector3::new(0.0, 0.0, 2.2),
4046            Vector3::new(0.0, 0.0, 2.3),
4047            Vector3::new(0.0, 0.0, 2.4),
4048        ];
4049        let weak_report = PnpSelectedReport {
4050            pose: Pose::identity(),
4051            inlier_count: 10,
4052            correspondence_count: 40,
4053            mean_reprojection_error: 1.0,
4054        };
4055        let mut pose = Pose {
4056            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, -2.4)),
4057        };
4058
4059        assert!(rescue_translation_direction(
4060            &mut pose,
4061            &translation_history,
4062            &direction_history,
4063            Some(&weak_report),
4064            StereoRelativePoseSource::Pnp,
4065            &config,
4066        ));
4067        assert!(pose.world_to_camera.translation.x.abs() < 1.0e-9);
4068        assert!(pose.world_to_camera.translation.y.abs() < 1.0e-9);
4069        assert!((pose.world_to_camera.translation.z - 2.4).abs() < 1.0e-9);
4070    }
4071
4072    #[test]
4073    fn recent_translation_direction_uses_recent_window_and_ignores_bad_vectors() {
4074        let history = [
4075            Vector3::new(3.0, 0.0, 0.0),
4076            Vector3::new(f64::NAN, 0.0, 0.0),
4077            Vector3::zeros(),
4078            Vector3::new(0.0, 0.0, 2.0),
4079            Vector3::new(0.0, 0.0, 3.0),
4080        ];
4081        let direction = recent_translation_direction(&history, 4).expect("recent direction");
4082        assert!(direction.x.abs() < 1.0e-9);
4083        assert!(direction.y.abs() < 1.0e-9);
4084        assert!((direction.z - 1.0).abs() < 1.0e-9);
4085
4086        assert!(recent_translation_direction(
4087            &[Vector3::new(1.0, 0.0, 0.0), Vector3::new(-1.0, 0.0, 0.0)],
4088            2,
4089        )
4090        .is_none());
4091        assert!(recent_translation_direction(&history, 0).is_none());
4092    }
4093
4094    #[test]
4095    fn rotation_spike_rescue_requires_fast_history_and_weak_consensus() {
4096        let mut config = StereoVoFrontendConfig::default();
4097        config.rotation_spike_rescue_min_history = 4;
4098        config.rotation_spike_rescue_min_median_translation_m = 1.5;
4099        config.rotation_spike_rescue_min_angle_deg = 1.0;
4100        config.rotation_spike_rescue_max_angle_ratio = 3.0;
4101        config.rotation_spike_rescue_max_pnp_inlier_ratio = 0.45;
4102        let translation_history = [2.1, 2.2, 2.3, 2.4];
4103        let rotation_history = [0.2, 0.3, 0.4, 0.3];
4104        let weak_report = PnpSelectedReport {
4105            pose: Pose::identity(),
4106            inlier_count: 10,
4107            correspondence_count: 40,
4108            mean_reprojection_error: 1.0,
4109        };
4110        let mut pose = Pose {
4111            world_to_camera: SE3::new(
4112                UnitQuaternion::from_euler_angles(0.0, 0.0, 3.0_f64.to_radians()),
4113                Vector3::new(2.0, 0.0, 0.0),
4114            ),
4115        };
4116        assert!(rescue_rotation_spike(
4117            &mut pose,
4118            &translation_history,
4119            &rotation_history,
4120            Some(&weak_report),
4121            StereoRelativePoseSource::Pnp,
4122            &config,
4123        ));
4124        assert!((relative_rotation_angle_deg(&pose) - 0.3).abs() < 1.0e-9);
4125
4126        let strong_report = PnpSelectedReport {
4127            pose: Pose::identity(),
4128            inlier_count: 30,
4129            correspondence_count: 40,
4130            mean_reprojection_error: 1.0,
4131        };
4132        let mut strong_pose = Pose {
4133            world_to_camera: SE3::new(
4134                UnitQuaternion::from_euler_angles(0.0, 0.0, 3.0_f64.to_radians()),
4135                Vector3::new(2.0, 0.0, 0.0),
4136            ),
4137        };
4138        assert!(!rescue_rotation_spike(
4139            &mut strong_pose,
4140            &translation_history,
4141            &rotation_history,
4142            Some(&strong_report),
4143            StereoRelativePoseSource::Pnp,
4144            &config,
4145        ));
4146
4147        let mut slow_pose = Pose {
4148            world_to_camera: SE3::new(
4149                UnitQuaternion::from_euler_angles(0.0, 0.0, 3.0_f64.to_radians()),
4150                Vector3::new(2.0, 0.0, 0.0),
4151            ),
4152        };
4153        assert!(!rescue_rotation_spike(
4154            &mut slow_pose,
4155            &[0.7, 0.8, 0.9, 0.8],
4156            &rotation_history,
4157            Some(&weak_report),
4158            StereoRelativePoseSource::Pnp,
4159            &config,
4160        ));
4161    }
4162
4163    #[test]
4164    fn rotation_vector_rescue_clamps_weak_rotation_to_recent_trend() {
4165        let mut config = StereoVoFrontendConfig::default();
4166        config.rotation_vector_rescue_min_history = 4;
4167        config.rotation_vector_rescue_min_median_translation_m = 1.5;
4168        config.rotation_vector_rescue_max_delta_deg = 0.4;
4169        config.rotation_vector_rescue_max_pnp_inlier_ratio = 0.45;
4170        let translation_history = [2.1, 2.2, 2.3, 2.4];
4171        let rotation_history = [
4172            Vector3::new(0.0, 0.0, 0.2_f64.to_radians()),
4173            Vector3::new(0.0, 0.0, 0.3_f64.to_radians()),
4174            Vector3::new(0.0, 0.0, 0.4_f64.to_radians()),
4175            Vector3::new(0.0, 0.0, 0.3_f64.to_radians()),
4176        ];
4177        let weak_report = PnpSelectedReport {
4178            pose: Pose::identity(),
4179            inlier_count: 10,
4180            correspondence_count: 40,
4181            mean_reprojection_error: 1.0,
4182        };
4183        let mut pose = Pose {
4184            world_to_camera: SE3::new(
4185                UnitQuaternion::from_euler_angles(0.0, 0.0, 1.1_f64.to_radians()),
4186                Vector3::new(2.0, 0.0, 0.0),
4187            ),
4188        };
4189
4190        assert!(rescue_rotation_vector(
4191            &mut pose,
4192            &translation_history,
4193            &rotation_history,
4194            Some(&weak_report),
4195            StereoRelativePoseSource::Pnp,
4196            &config,
4197        ));
4198        assert!((relative_rotation_angle_deg(&pose) - 0.3).abs() < 1.0e-9);
4199    }
4200
4201    #[test]
4202    fn rotation_vector_rescue_requires_fast_history_and_weak_consensus() {
4203        let mut config = StereoVoFrontendConfig::default();
4204        config.rotation_vector_rescue_min_history = 4;
4205        config.rotation_vector_rescue_min_median_translation_m = 1.5;
4206        config.rotation_vector_rescue_max_delta_deg = 0.4;
4207        config.rotation_vector_rescue_max_pnp_inlier_ratio = 0.45;
4208        let translation_history = [2.1, 2.2, 2.3, 2.4];
4209        let rotation_history = [
4210            Vector3::new(0.0, 0.0, 0.2_f64.to_radians()),
4211            Vector3::new(0.0, 0.0, 0.3_f64.to_radians()),
4212            Vector3::new(0.0, 0.0, 0.4_f64.to_radians()),
4213            Vector3::new(0.0, 0.0, 0.3_f64.to_radians()),
4214        ];
4215        let strong_report = PnpSelectedReport {
4216            pose: Pose::identity(),
4217            inlier_count: 30,
4218            correspondence_count: 40,
4219            mean_reprojection_error: 1.0,
4220        };
4221        let mut strong_pose = Pose {
4222            world_to_camera: SE3::new(
4223                UnitQuaternion::from_euler_angles(0.0, 0.0, 1.1_f64.to_radians()),
4224                Vector3::new(2.0, 0.0, 0.0),
4225            ),
4226        };
4227        assert!(!rescue_rotation_vector(
4228            &mut strong_pose,
4229            &translation_history,
4230            &rotation_history,
4231            Some(&strong_report),
4232            StereoRelativePoseSource::Pnp,
4233            &config,
4234        ));
4235
4236        let weak_report = PnpSelectedReport {
4237            pose: Pose::identity(),
4238            inlier_count: 10,
4239            correspondence_count: 40,
4240            mean_reprojection_error: 1.0,
4241        };
4242        let mut slow_pose = Pose {
4243            world_to_camera: SE3::new(
4244                UnitQuaternion::from_euler_angles(0.0, 0.0, 1.1_f64.to_radians()),
4245                Vector3::new(2.0, 0.0, 0.0),
4246            ),
4247        };
4248        assert!(!rescue_rotation_vector(
4249            &mut slow_pose,
4250            &[0.7, 0.8, 0.9, 0.8],
4251            &rotation_history,
4252            Some(&weak_report),
4253            StereoRelativePoseSource::Pnp,
4254            &config,
4255        ));
4256    }
4257
4258    /// 3D-3D Kabsch round-trip: synthesize matched 3D points in two
4259    /// frames with known relative pose plus 3 outliers, run RANSAC,
4260    /// confirm pose recovery and outlier rejection.
4261    #[test]
4262    fn kabsch_ransac_recovers_metric_pose_and_rejects_outliers() {
4263        let r = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.1)
4264            * UnitQuaternion::from_axis_angle(&Vector3::x_axis(), -0.05);
4265        let truth_t = Vector3::new(0.3, -0.05, 1.5);
4266        let r_mat = r.to_rotation_matrix().into_inner();
4267        let inliers: Vec<Point3<f64>> = vec![
4268            Point3::new(-1.0, 0.0, 8.0),
4269            Point3::new(1.5, 0.5, 12.0),
4270            Point3::new(0.0, -0.3, 6.0),
4271            Point3::new(2.0, 0.5, 15.0),
4272            Point3::new(-2.5, -0.4, 10.0),
4273            Point3::new(0.5, 0.6, 5.0),
4274            Point3::new(-1.5, 0.2, 9.0),
4275            Point3::new(1.0, -0.2, 7.0),
4276            Point3::new(-0.5, 0.0, 11.0),
4277            Point3::new(2.5, -0.5, 14.0),
4278            Point3::new(-2.0, 0.4, 8.5),
4279            Point3::new(0.0, 0.5, 6.5),
4280        ];
4281        let mut corrs: Vec<StereoPairCorrespondence> = inliers
4282            .iter()
4283            .map(|p| StereoPairCorrespondence {
4284                a: *p,
4285                b: Point3::from(r_mat * p.coords + truth_t),
4286                confidence: None,
4287            })
4288            .collect();
4289        // Three gross outliers (random offsets).
4290        corrs.push(StereoPairCorrespondence {
4291            a: Point3::new(0.0, 0.0, 10.0),
4292            b: Point3::new(8.0, 0.0, 4.0),
4293            confidence: None,
4294        });
4295        corrs.push(StereoPairCorrespondence {
4296            a: Point3::new(1.0, 0.0, 12.0),
4297            b: Point3::new(-4.0, 0.0, 6.0),
4298            confidence: None,
4299        });
4300        corrs.push(StereoPairCorrespondence {
4301            a: Point3::new(0.5, 0.5, 9.0),
4302            b: Point3::new(0.5, -3.5, 3.0),
4303            confidence: None,
4304        });
4305        let report = estimate_relative_pose_kabsch_ransac(&corrs, &KabschRansacConfig::default())
4306            .expect("Kabsch RANSAC must succeed on mostly-inlier data");
4307        let recovered_t = report.relative_pose.world_to_camera.translation;
4308        assert!(
4309            (recovered_t - truth_t).norm() < 1.0e-6,
4310            "translation err {:?}",
4311            recovered_t,
4312        );
4313        let recovered_r = report
4314            .relative_pose
4315            .world_to_camera
4316            .rotation
4317            .to_rotation_matrix()
4318            .into_inner();
4319        assert!(
4320            (recovered_r - r_mat).norm() < 1.0e-6,
4321            "rotation err {:?}",
4322            recovered_r,
4323        );
4324        // All 12 inliers should be recovered, the 3 outliers rejected.
4325        assert!(
4326            report.inliers.len() >= 12,
4327            "should keep all inliers: {}",
4328            report.inliers.len()
4329        );
4330        assert!(report.inliers.len() <= 12, "should reject outliers");
4331    }
4332
4333    /// `StereoVoFrontend` round-trip on a synthetic 4-frame KITTI-like
4334    /// stereo sequence. Verifies that (a) the first frame seeds at
4335    /// identity, (b) the last frame's recovered camera center matches
4336    /// truth in metric units, and (c) the per-call state collections
4337    /// stay in lockstep.
4338    #[test]
4339    fn stereo_vo_frontend_recovers_synthetic_metric_trajectory() {
4340        // Pack a synthetic image so CornerFeatureExtractor returns
4341        // exactly the keypoints / descriptors we want — i.e., construct
4342        // a frontend that doesn't actually depend on the FAST detector.
4343        // Simpler path: use the lower-level helpers directly to validate
4344        // the frontend's state-tracking is correct on synthesized inputs.
4345        let camera = camera();
4346        let baseline = 0.537150888;
4347        let (fx, _, _, _) = camera.intrinsics().unwrap();
4348        let landmarks: Vec<Point3<f64>> = vec![
4349            Point3::new(-2.0, 0.5, 12.0),
4350            Point3::new(1.5, -0.3, 9.0),
4351            Point3::new(0.0, 0.0, 18.0),
4352            Point3::new(-1.0, 0.6, 7.0),
4353            Point3::new(2.0, 0.0, 14.0),
4354            Point3::new(-3.0, -0.2, 11.0),
4355        ];
4356        let mut poses_truth: Vec<Pose> = Vec::new();
4357        for i in 0..3 {
4358            let r = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.03 * i as f64);
4359            let center = Vector3::new(0.05 * i as f64, 0.0, 1.2 * i as f64);
4360            poses_truth.push(Pose::from_world_to_camera(
4361                r,
4362                -(r.transform_vector(&center)),
4363            ));
4364        }
4365        let mut frontend = StereoVoFrontend::new(
4366            camera.clone(),
4367            baseline,
4368            StereoVoFrontendConfig {
4369                kabsch: KabschRansacConfig {
4370                    iterations: 64,
4371                    inlier_threshold_m: 0.01,
4372                    min_inliers: 4,
4373                    max_depth_m: 30.0,
4374                    seed: 7,
4375                },
4376                ..StereoVoFrontendConfig::default()
4377            },
4378        );
4379        // Inject synthetic state directly: skip the image-extractor
4380        // path (which the test doesn't aim to exercise) and validate
4381        // only the per-pair Kabsch + composition logic.
4382        for pose in &poses_truth {
4383            let mut kps: Vec<Point2<f64>> = Vec::new();
4384            let mut descs: Vec<Vec<f32>> = Vec::new();
4385            let mut sf: Vec<StereoFeature> = Vec::new();
4386            for (id, p) in landmarks.iter().enumerate() {
4387                let xc = pose.transform_world_point(p);
4388                let l = camera.project(&xc).unwrap();
4389                let u_r = l.x - fx * baseline / xc.z;
4390                let kp_idx = kps.len();
4391                kps.push(l);
4392                descs.push(vec![id as f32]);
4393                sf.push(StereoFeature {
4394                    left_index: kp_idx,
4395                    right_index: kp_idx,
4396                    disparity: l.x - u_r,
4397                    point_cam: Point3::from(xc.coords),
4398                });
4399            }
4400            let lf = FeatureSet::new(kps.clone(), descs.clone()).unwrap();
4401            let rf = FeatureSet::new(kps, descs).unwrap();
4402            // Manually advance frontend state, mimicking process_pair
4403            // without invoking the FAST extractor on a synthetic image.
4404            let new_pose = if let (Some(prev_left), Some(prev_stereo)) = (
4405                frontend.left_features.last(),
4406                frontend.stereo_per_frame.last(),
4407            ) {
4408                let temporal_matches = frontend
4409                    .matcher
4410                    .match_descriptors(&prev_left.descriptors, &lf.descriptors);
4411                let pair_corrs = stereo_pair_correspondences(prev_stereo, &sf, &temporal_matches);
4412                let report =
4413                    estimate_relative_pose_kabsch_ransac(&pair_corrs, &frontend.config.kabsch)
4414                        .expect("kabsch should succeed on synthetic data");
4415                frontend.kabsch_inlier_counts.push(report.inliers.len());
4416                frontend
4417                    .per_pair_translation_m
4418                    .push(report.relative_pose.world_to_camera.translation.norm());
4419                frontend
4420                    .per_pair_translation_vectors
4421                    .push(report.relative_pose.world_to_camera.translation);
4422                let relative = report.relative_pose.world_to_camera.clone();
4423                let last = frontend.poses.last().unwrap();
4424                Pose {
4425                    world_to_camera: relative.compose(&last.world_to_camera),
4426                }
4427            } else {
4428                Pose::identity()
4429            };
4430            frontend.poses.push(new_pose);
4431            frontend.left_features.push(lf);
4432            frontend.right_features.push(rf);
4433            frontend.stereo_per_frame.push(sf);
4434        }
4435        assert_eq!(frontend.frame_count(), 3);
4436        assert_eq!(frontend.left_features.len(), 3);
4437        assert_eq!(frontend.stereo_per_frame.len(), 3);
4438        assert_eq!(frontend.per_pair_translation_m.len(), 2);
4439        assert_eq!(frontend.per_pair_translation_vectors.len(), 2);
4440        assert_eq!(frontend.kabsch_inlier_counts.len(), 2);
4441        for (magnitude, vector) in frontend
4442            .per_pair_translation_m
4443            .iter()
4444            .zip(frontend.per_pair_translation_vectors.iter())
4445        {
4446            assert!((vector.norm() - magnitude).abs() < 1.0e-9);
4447        }
4448        // Frame 0 should be identity, last-frame center should match truth.
4449        let center_0 = frontend.poses[0].camera_center_world();
4450        assert!(center_0.coords.norm() < 1.0e-9);
4451        let recovered_last = frontend.poses[2].camera_center_world();
4452        let truth_last = -poses_truth[2]
4453            .world_to_camera
4454            .rotation
4455            .inverse()
4456            .transform_vector(&poses_truth[2].world_to_camera.translation);
4457        assert!(
4458            (recovered_last.coords - truth_last).norm() < 1.0e-6,
4459            "recovered {recovered_last:?} truth {truth_last:?}",
4460        );
4461        // Trajectory length should be ≈ sum of per-pair translations.
4462        let len_traj = frontend.trajectory_length_m();
4463        let len_pairs: f64 = frontend.per_pair_translation_m.iter().sum();
4464        assert!((len_traj - len_pairs).abs() < 1.0e-6);
4465        // Adaptive search radius respects the floor.
4466        assert!(frontend.adaptive_track_search_radius_px() >= 20.0);
4467    }
4468
4469    #[test]
4470    fn stereo_vo_frontend_accepts_external_features_and_matches() {
4471        let camera = camera();
4472        let baseline = 0.537150888;
4473        let (fx, _, _, _) = camera.intrinsics().unwrap();
4474        let landmarks: Vec<Point3<f64>> = vec![
4475            Point3::new(-2.0, 0.5, 12.0),
4476            Point3::new(1.5, -0.3, 9.0),
4477            Point3::new(0.0, 0.0, 18.0),
4478            Point3::new(-1.0, 0.6, 7.0),
4479            Point3::new(2.0, 0.0, 14.0),
4480            Point3::new(-3.0, -0.2, 11.0),
4481        ];
4482        let mut poses_truth: Vec<Pose> = Vec::new();
4483        for i in 0..3 {
4484            let r = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.03 * i as f64);
4485            let center = Vector3::new(0.05 * i as f64, 0.0, 1.2 * i as f64);
4486            poses_truth.push(Pose::from_world_to_camera(
4487                r,
4488                -(r.transform_vector(&center)),
4489            ));
4490        }
4491        let mut frontend = StereoVoFrontend::new(
4492            camera.clone(),
4493            baseline,
4494            StereoVoFrontendConfig {
4495                kabsch: KabschRansacConfig {
4496                    iterations: 64,
4497                    inlier_threshold_m: 0.01,
4498                    min_inliers: 4,
4499                    max_depth_m: 30.0,
4500                    seed: 7,
4501                },
4502                relative_pose_mode: StereoRelativePoseMode::KabschThenPnp,
4503                ..StereoVoFrontendConfig::default()
4504            },
4505        );
4506
4507        for (frame_index, pose) in poses_truth.iter().enumerate() {
4508            let mut left_keypoints = Vec::new();
4509            let mut right_keypoints = Vec::new();
4510            let mut left_descriptors = Vec::new();
4511            let mut right_descriptors = Vec::new();
4512            let mut stereo_matches = Vec::new();
4513
4514            for (id, point_world) in landmarks.iter().enumerate() {
4515                let point_cam = pose.transform_world_point(point_world);
4516                let left = camera.project(&point_cam).unwrap();
4517                let right = Point2::new(left.x - fx * baseline / point_cam.z, left.y);
4518                left_keypoints.push(left);
4519                right_keypoints.push(right);
4520                // All descriptors are deliberately identical. The explicit
4521                // LightGlue-style matches below, not the internal matcher,
4522                // are what make this sequence trackable.
4523                left_descriptors.push(vec![0.0]);
4524                right_descriptors.push(vec![0.0]);
4525                stereo_matches.push(descriptor_match(id, id));
4526            }
4527
4528            let left_features = FeatureSet::new(left_keypoints, left_descriptors).unwrap();
4529            let right_features = FeatureSet::new(right_keypoints, right_descriptors).unwrap();
4530            let temporal_matches = if frame_index == 0 {
4531                None
4532            } else {
4533                Some(
4534                    (0..landmarks.len())
4535                        .map(|id| descriptor_match(id, id))
4536                        .collect::<Vec<_>>(),
4537                )
4538            };
4539
4540            frontend
4541                .process_feature_pair_with_matches(
4542                    left_features,
4543                    right_features,
4544                    Some(&stereo_matches),
4545                    temporal_matches.as_deref(),
4546                )
4547                .unwrap();
4548        }
4549
4550        assert_eq!(frontend.frame_count(), 3);
4551        assert_eq!(frontend.stereo_per_frame[0].len(), landmarks.len());
4552        assert_eq!(frontend.pair_diagnostics.len(), 2);
4553        for diagnostics in &frontend.pair_diagnostics {
4554            assert_eq!(diagnostics.source, StereoRelativePoseSource::Kabsch);
4555            assert_eq!(diagnostics.temporal_match_count, landmarks.len());
4556            assert_eq!(
4557                diagnostics.stereo_pair_correspondence_count,
4558                landmarks.len()
4559            );
4560        }
4561        let recovered_last = frontend.poses[2].camera_center_world();
4562        let truth_last = -poses_truth[2]
4563            .world_to_camera
4564            .rotation
4565            .inverse()
4566            .transform_vector(&poses_truth[2].world_to_camera.translation);
4567        assert!(
4568            (recovered_last.coords - truth_last).norm() < 1.0e-6,
4569            "recovered {recovered_last:?} truth {truth_last:?}",
4570        );
4571    }
4572
4573    /// Projection-guided extension: synthesize a 4-frame world-frame
4574    /// trajectory plus 5 fixed world-frame landmarks. Each frame's
4575    /// FeatureSet contains the projected pixels (left + right with
4576    /// rectified-stereo offset). Run extension, confirm tracks span all
4577    /// 4 frames and consume each (frame, kp) at most once.
4578    #[test]
4579    fn extend_stereo_tracks_via_projection_finds_long_chains() {
4580        let camera = camera();
4581        let baseline = 0.537150888;
4582        let (fx, _, _, _) = camera.intrinsics().unwrap();
4583        let landmarks: Vec<Point3<f64>> = vec![
4584            Point3::new(-2.0, 0.5, 12.0),
4585            Point3::new(1.5, -0.3, 9.0),
4586            Point3::new(0.0, 0.0, 18.0),
4587            Point3::new(-1.0, 0.6, 7.0),
4588            Point3::new(2.0, 0.0, 14.0),
4589        ];
4590        // Forward camera motion of 0.8 m / frame, slight yaw rotation.
4591        let mut poses: Vec<Pose> = Vec::new();
4592        for i in 0..4 {
4593            let r = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.02 * i as f64);
4594            let center = Vector3::new(0.0, 0.0, 0.8 * i as f64);
4595            let t = -(r.transform_vector(&center));
4596            poses.push(Pose::from_world_to_camera(r, t));
4597        }
4598        // Build per-frame FeatureSets and stereo features.
4599        let mut left_features: Vec<FeatureSet> = Vec::new();
4600        let mut stereo_per_frame: Vec<Vec<StereoFeature>> = Vec::new();
4601        for pose in &poses {
4602            let mut kps: Vec<Point2<f64>> = Vec::new();
4603            let mut descs: Vec<Vec<f32>> = Vec::new();
4604            let mut sf: Vec<StereoFeature> = Vec::new();
4605            for (id, p) in landmarks.iter().enumerate() {
4606                let xc = pose.transform_world_point(p);
4607                let l = camera.project(&xc).unwrap();
4608                let u_r = l.x - fx * baseline / xc.z;
4609                let kp_idx = kps.len();
4610                kps.push(l);
4611                descs.push(vec![id as f32]);
4612                sf.push(StereoFeature {
4613                    left_index: kp_idx,
4614                    right_index: kp_idx,
4615                    disparity: l.x - u_r,
4616                    point_cam: Point3::from(xc.coords),
4617                });
4618            }
4619            left_features.push(FeatureSet::new(kps, descs).unwrap());
4620            stereo_per_frame.push(sf);
4621        }
4622        let tracks = extend_stereo_tracks_via_projection(
4623            &poses,
4624            &left_features,
4625            &stereo_per_frame,
4626            &camera,
4627            &TrackExtensionConfig::default(),
4628        );
4629        // Each landmark should produce exactly one 4-frame track (with
4630        // deduplication on, the same physical point isn't re-seeded).
4631        assert_eq!(tracks.len(), 5, "got {} tracks", tracks.len());
4632        for track in &tracks {
4633            assert_eq!(track.observations.len(), 4, "track len {:?}", track);
4634        }
4635    }
4636
4637    /// End-to-end PnP round-trip: synthesize a metric scene, triangulate
4638    /// stereo features at frame A, build correspondences against frame B
4639    /// (with a known relative pose), run PnP, and verify the recovered
4640    /// pose matches truth in metric units.
4641    #[test]
4642    fn stereo_vo_pnp_round_trips_metric_relative_pose() {
4643        use crate::pnp::{DltPnP, PoseEstimator};
4644        let camera = camera();
4645        let baseline = 0.5;
4646        let (fx, _, _, _) = camera.intrinsics().unwrap();
4647        let truth_t_a_to_b = Vector3::new(0.4, 0.0, 1.2);
4648        let r = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.05);
4649        let pose_a = Pose::identity();
4650        let pose_b = Pose::from_world_to_camera(r, -(r.transform_vector(&truth_t_a_to_b)));
4651
4652        let world_points: Vec<Point3<f64>> = vec![
4653            Point3::new(-1.0, -0.3, 6.0),
4654            Point3::new(1.0, 0.3, 8.0),
4655            Point3::new(0.0, 0.0, 10.0),
4656            Point3::new(-1.5, 0.2, 4.0),
4657            Point3::new(2.0, -0.5, 12.0),
4658            Point3::new(0.5, 0.6, 5.5),
4659        ];
4660        let mut left_a: Vec<(usize, Point2<f64>)> = Vec::new();
4661        let mut right_a: Vec<(usize, Point2<f64>)> = Vec::new();
4662        let mut left_b: Vec<(usize, Point2<f64>)> = Vec::new();
4663        for (id, p) in world_points.iter().enumerate() {
4664            let xa = pose_a.transform_world_point(p);
4665            let xb = pose_b.transform_world_point(p);
4666            let la = camera.project(&xa).unwrap();
4667            let lb = camera.project(&xb).unwrap();
4668            let ra = Point2::new(la.x - fx * baseline / xa.z, la.y);
4669            left_a.push((id, la));
4670            right_a.push((id, ra));
4671            left_b.push((id, lb));
4672        }
4673        let left_a_fs = synthetic_feature_set(&left_a);
4674        let right_a_fs = synthetic_feature_set(&right_a);
4675        let left_b_fs = synthetic_feature_set(&left_b);
4676        let stereo_a = triangulate_stereo_features(
4677            &left_a_fs,
4678            &right_a_fs,
4679            &camera,
4680            baseline,
4681            &StereoFeatureConfig {
4682                ratio: None,
4683                ..StereoFeatureConfig::default()
4684            },
4685        );
4686        let matcher = BruteForceMatcher { ratio: None };
4687        let temporal_matches =
4688            matcher.match_descriptors(&left_a_fs.descriptors, &left_b_fs.descriptors);
4689        let corrs = build_stereo_temporal_correspondences(&stereo_a, &left_b_fs, &temporal_matches);
4690        assert_eq!(corrs.len(), world_points.len());
4691        let estimator = DltPnP::default();
4692        let recovered = estimator
4693            .estimate_pose(&corrs, &camera)
4694            .expect("DLT must succeed on noise-free input");
4695        // PnP recovers T_a_to_b directly because the 3D points were given
4696        // in frame-a's camera frame and the 2D pixels are in frame-b.
4697        let recovered_center = recovered.camera_center_world();
4698        let truth_center = -(pose_b
4699            .world_to_camera
4700            .rotation
4701            .inverse()
4702            .transform_vector(&pose_b.world_to_camera.translation));
4703        let err = (recovered_center.coords - truth_center).norm();
4704        assert!(
4705            err < 1.0e-9,
4706            "stereo VO PnP center error {err}: recovered {recovered_center:?} truth {truth_center:?}"
4707        );
4708    }
4709}