Skip to main content

visloc_slam/
stereo_vo_ba.rs

1//! Multi-frame stereo bundle adjustment for stereo VO trajectories.
2//!
3//! Per-pair PnP underestimates absolute vertical motion on slope-following
4//! sequences (e.g. KITTI seq08): the road follows the camera, so road-surface
5//! stereo features yield `Δy_cam ≈ 0` between frames even when the camera
6//! actually rises in world coordinates. Multi-view BA breaks this ambiguity
7//! by requiring a single 3D landmark to explain its observations across many
8//! frames — features that genuinely persist must obey rigid-body motion, and
9//! the long-baseline geometry constrains the camera trajectory's vertical
10//! component that pairwise stereo cannot.
11//!
12//! This module builds forward feature tracks from per-pair temporal matches,
13//! initialises landmarks from the first stereo observation in each track, and
14//! runs Schur-complement BA over all poses (with pose 0 fixed) plus all
15//! long-tracked landmarks. The robust Huber kernel down-weights tracks that
16//! cannot be explained as a rigid-body landmark (e.g. road texture matches
17//! that "follow" the camera through pitched motion).
18
19use std::collections::HashMap;
20
21use nalgebra::{DMatrix, Point2, Point3, Vector3, Vector6};
22use visloc_core::geometry::Pose;
23use visloc_core::types::Camera;
24use visloc_vision::features::FeatureSet;
25use visloc_vision::matching::DescriptorMatch;
26use visloc_vision::stereo_vo::StereoFeature;
27
28use crate::imu_preintegration::{ImuPreintegrationFactor, ImuPreintegrator};
29use crate::{
30    BaConfig, BaError, BaResult, BaStereoObservation, BiasRandomWalkFactor, BundleAdjustment,
31    GravityPrior, LinearSolver, PerPoseGravityPrior, PositionPrior, RobustKernel,
32};
33
34/// Single body-frame IMU sample for a stereo-VO BA inter-keyframe window.
35/// `dt` is the time elapsed since the previous sample (or since the
36/// window start for the first sample). `gyro` and `accel` are body-frame;
37/// gravity is *not* pre-subtracted from `accel` — the BA-side IMU factor
38/// handles gravity compensation through [`StereoVoBaImuInput::gravity_world`].
39#[derive(Debug, Clone, PartialEq)]
40pub struct StereoVoBaImuSample {
41    /// Time step in seconds (must be `> 0`).
42    pub dt: f64,
43    /// Body-frame gyroscope reading (rad / s).
44    pub gyro: Vector3<f64>,
45    /// Body-frame accelerometer reading (m / s²), gravity *not* removed.
46    pub accel: Vector3<f64>,
47}
48
49/// IMU input wired into a stereo-VO BA refinement. The caller supplies
50/// `n_frames − 1` sample windows: `windows[i]` covers the integration
51/// interval from keyframe `i` to keyframe `i + 1`. The refiner pre-
52/// integrates each window with [`ImuPreintegrator::new_with_bias`] at
53/// the initial bias linearisation point, registers a velocity / bias
54/// state per keyframe, and pushes an [`ImuPreintegrationFactor`] for
55/// every non-empty window. When `bias_random_walk_weight` is `Some(w)`,
56/// every consecutive bias pair is also tied with a
57/// [`BiasRandomWalkFactor`] of weight `w`.
58#[derive(Debug, Clone, PartialEq)]
59pub struct StereoVoBaImuInput {
60    /// `n_frames − 1` body-frame sample windows. An empty window (no
61    /// samples) means "no IMU factor between those two keyframes" — the
62    /// pair contributes neither velocity nor bias state, and any
63    /// random-walk factor that would have referenced them is skipped.
64    pub windows: Vec<Vec<StereoVoBaImuSample>>,
65    /// World-frame gravity vector applied by every IMU factor. KITTI
66    /// y-down convention: `(0, 9.81, 0)`. Pass `Vector3::zeros()` for
67    /// gravity-free pre-integration (e.g. zero-g simulation tests).
68    pub gravity_world: Vector3<f64>,
69    /// Initial gyro bias linearisation point shared by every window.
70    pub bias_gyro_init: Vector3<f64>,
71    /// Initial accel bias linearisation point shared by every window.
72    pub bias_acc_init: Vector3<f64>,
73    /// 3-vector position residual weight `1/σ_p²` on every factor.
74    pub weight_position: f64,
75    /// 3-vector velocity residual weight `1/σ_v²` on every factor.
76    pub weight_velocity: f64,
77    /// 3-vector rotation residual weight `1/σ_R²` on every factor.
78    pub weight_rotation: f64,
79    /// When `Some(w)`, a [`BiasRandomWalkFactor`] is added between every
80    /// pair of consecutive bias slots with weight `w` on
81    /// `‖b_j − b_i‖²`. `None` disables the random-walk tie.
82    pub bias_random_walk_weight: Option<f64>,
83    /// When `true`, the first IMU-active keyframe's bias is held fixed
84    /// at its initial value (gauge choice for an otherwise drift-free
85    /// random walk).
86    pub fix_first_bias: bool,
87    /// When `true`, the first IMU-active keyframe's velocity is held
88    /// fixed at its initial value. Pose 0 is always fixed for the BA
89    /// gauge but velocity is an independent 3-DoF — pin it when a
90    /// measured initial velocity is available.
91    pub fix_first_velocity: bool,
92}
93
94impl StereoVoBaImuInput {
95    /// Convenience constructor with weights, zero initial biases, no
96    /// random-walk tie, gauge-fixed first bias, free first velocity.
97    pub fn new(
98        windows: Vec<Vec<StereoVoBaImuSample>>,
99        gravity_world: Vector3<f64>,
100        weight_position: f64,
101        weight_velocity: f64,
102        weight_rotation: f64,
103    ) -> Self {
104        Self {
105            windows,
106            gravity_world,
107            bias_gyro_init: Vector3::zeros(),
108            bias_acc_init: Vector3::zeros(),
109            weight_position,
110            weight_velocity,
111            weight_rotation,
112            bias_random_walk_weight: None,
113            fix_first_bias: true,
114            fix_first_velocity: false,
115        }
116    }
117}
118
119/// Refined IMU state from a BA solve that included
120/// [`StereoVoBaImuInput`]. The vectors are indexed by keyframe id (so
121/// entry `i` corresponds to `initial_poses[i]`). Keyframes that did not
122/// participate in any IMU factor have their velocity left at the
123/// build-time initial value and their bias at the input
124/// `bias_*_init`.
125#[derive(Debug, Clone, PartialEq)]
126pub struct StereoVoBaImuRefinement {
127    /// World-frame velocity refined per keyframe.
128    pub refined_velocities: Vec<Vector3<f64>>,
129    /// Refined gyro bias per keyframe.
130    pub refined_bias_gyro: Vec<Vector3<f64>>,
131    /// Refined accelerometer bias per keyframe.
132    pub refined_bias_acc: Vec<Vector3<f64>>,
133}
134
135/// Landmark initialisation strategy for [`refine_stereo_vo_with_ba`]. See
136/// [`StereoVoBaConfig::landmark_init`].
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
138pub enum LandmarkInit {
139    /// Triangulate the landmark from the first stereo observation in the
140    /// track, transformed to world via that frame's initial pose. Default
141    /// for backwards-compatibility.
142    #[default]
143    StereoSingleFrame,
144    /// Linear DLT over ALL stereo observations in the track (3 equations
145    /// per frame: `u_l`, `v_l`, `u_r`). Solved via SVD on a `(3n)×4`
146    /// matrix.
147    MultiViewDlt,
148}
149
150/// Configuration for [`refine_stereo_vo_with_ba`].
151#[derive(Debug, Clone, PartialEq)]
152pub struct StereoVoBaConfig {
153    /// Minimum number of frames a track must span before it contributes a
154    /// landmark to BA. Tracks shorter than this are dropped. The pairwise
155    /// PnP-only path already exercises 2-frame tracks; the value of BA is in
156    /// 3+ -frame tracks whose long baseline disambiguates ambiguous per-pair
157    /// solutions.
158    pub min_track_length: usize,
159    /// Maximum cam-frame depth (metres) accepted for the seed stereo
160    /// observation that initialises a landmark. Far-field points (large `Z`)
161    /// have very noisy initial 3D positions from stereo triangulation and
162    /// destabilise LM until refined.
163    pub max_initial_depth_m: f64,
164    /// Optional upper-row fraction (0..1) of the image. When set to `Some(r)`,
165    /// only tracks whose FIRST observation has a left-image row `v < r * h`
166    /// contribute landmarks. Tighter (smaller) values keep only above-horizon
167    /// scenery (sky / buildings / trees) and exclude road-surface features
168    /// that "follow" the camera through pitched motion on slope-following
169    /// sequences. `None` (default) accepts every track regardless of row.
170    pub max_seed_row_fraction: Option<f64>,
171    /// Optional per-track pre-BA residual gate. When `Some(threshold_px)`,
172    /// each candidate track's observations are projected against the initial
173    /// poses + initial landmark, and the track is dropped if any single
174    /// stereo residual exceeds `threshold_px` (Euclidean norm of the 3-vector
175    /// `(du_l, dv, du_r)`). This rejects "pseudo-tracks" where chained
176    /// temporal matches link slightly-different physical points — the
177    /// dominant failure mode that made naive global BA degrade the
178    /// trajectory on real KITTI sequences. Typical range `4.0..8.0`. `None`
179    /// (default) admits every track regardless of fit.
180    pub max_init_residual_px: Option<f64>,
181    /// Optional minimum temporal-match confidence (in `(0, 1]`) applied to
182    /// the temporal lookup before building forward tracks. Matches with
183    /// `confidence < min` (or unset confidence) are excluded from chaining.
184    /// Long chains of low-confidence matches were the second-largest source
185    /// of pseudo-tracks. `None` (default) lets every temporal match
186    /// contribute. A practical floor for SuperPoint/LightGlue is `0.8`.
187    pub min_temporal_confidence: Option<f32>,
188    /// Optional minimum number of tracks that must survive all filters
189    /// before BA actually runs. When fewer than this many tracks remain,
190    /// `refine_stereo_vo_with_ba` returns `Err(InsufficientTracks)` and the
191    /// caller is expected to keep the initial poses. The gate guards against
192    /// pathological sequences (low-feature highway, sparse texture) where
193    /// the filtered track set is too small to support stable BA — joint
194    /// optimisation in that regime tends to amplify whatever drift the
195    /// initial trajectory already has. `None` (default) runs BA whenever
196    /// there is at least one track.
197    pub min_track_count: Option<usize>,
198    /// Landmark initialisation strategy.
199    ///
200    /// `StereoSingleFrame` (legacy default) triangulates from the first
201    /// stereo observation in the track, transformed to world via that
202    /// frame's initial pose. Simple and fast, but for long tracks the
203    /// initial 3D position is biased by the per-frame stereo depth noise
204    /// and inflates the pre-BA residual.
205    ///
206    /// `MultiViewDlt` solves a linear DLT over ALL stereo observations in
207    /// the track (3 equations per frame: `u_l`, `v_l`, `u_r`). Smaller
208    /// initial residuals → tighter `max_init_residual_px` gates become
209    /// viable → cleaner BA convergence.
210    pub landmark_init: LandmarkInit,
211    /// Optional sliding-window size. When `Some(w)`, BA processes
212    /// overlapping `w`-frame windows instead of the entire trajectory at
213    /// once: window 0 covers poses `[0, w)`, window 1 covers
214    /// `[w-1, 2w-1)`, etc., so each window shares its first pose with the
215    /// previous window's last pose. Within each window the first pose is
216    /// fixed (the global gauge for window 0, the previously-refined
217    /// boundary pose for subsequent windows), and only tracks confined to
218    /// that window contribute observations. `None` (default) is global
219    /// joint BA over all frames.
220    pub window_size: Option<usize>,
221    /// Optional level-world gravity prior. When `Some`, every non-anchor
222    /// pose contributes a rotation-alignment residual `R_wc · g_world −
223    /// g_camera_observed` to the BA solve (see [`GravityPrior`]). Useful on
224    /// KITTI-style ground-vehicle sequences where the world frame is level
225    /// and pitch / roll drift is the dominant rotational failure mode. In
226    /// sliding-window mode the prior is applied to every window. `None`
227    /// (default) runs BA without a gravity constraint.
228    pub gravity_prior: Option<GravityPrior>,
229    /// Optional absolute camera-centre prior. Use axis weights to constrain
230    /// only the observable components needed by the experiment, e.g.
231    /// `(0, w, 0)` for KITTI y/height or `(0, w, w)` for y+z grade priors.
232    /// In sliding-window mode observations are remapped to each local window.
233    pub position_prior: Option<PositionPrior>,
234    /// Optional per-keyframe gravity prior. Each observation constrains
235    /// `R_wc · g_world ≈ g_camera_observed` at the named frame. This is
236    /// the online-friendly companion to [`Self::gravity_prior`] — the
237    /// observation can be sourced per-frame from an accelerometer
238    /// sample (rotated into the camera frame via the body→camera
239    /// extrinsic), so a deployed VIO can use exactly the same prior
240    /// path the BA exercises here. In sliding-window mode observations
241    /// are remapped to each local window. `None` (default) runs BA
242    /// without per-keyframe gravity constraints.
243    pub per_pose_gravity_prior: Option<PerPoseGravityPrior>,
244    /// Optional inter-keyframe IMU input. When `Some`, every inter-frame
245    /// window in [`StereoVoBaImuInput::windows`] is pre-integrated and an
246    /// [`ImuPreintegrationFactor`] is added to BA. Velocity and bias
247    /// state are registered for every keyframe that participates. Not
248    /// compatible with [`Self::window_size`] (the sliding window slices
249    /// poses but not IMU samples). `None` (default) runs visual-only BA.
250    pub imu_input: Option<StereoVoBaImuInput>,
251    /// Number of leading poses to hold fixed as the gauge / map anchor. The
252    /// default `1` fixes only pose 0 (the classic single-anchor window BA). A
253    /// larger value fixes a *prefix* of poses: used by the streaming wrapper to
254    /// run a "local map" BA over an extended backward window whose old frames are
255    /// fixed (they anchor long-baseline landmarks) while only the recent frames
256    /// are optimised — the fixed-keyframe local BA pattern. Values are clamped to
257    /// `[1, n_frames-1]`.
258    pub fix_pose_prefix: usize,
259    /// Underlying BA solver config. Defaults to sparse Cholesky + Huber
260    /// kernel sized to a 3 px reprojection residual norm.
261    pub ba_config: BaConfig,
262}
263
264impl Default for StereoVoBaConfig {
265    fn default() -> Self {
266        Self {
267            min_track_length: 3,
268            max_initial_depth_m: 60.0,
269            max_seed_row_fraction: None,
270            max_init_residual_px: None,
271            min_temporal_confidence: None,
272            min_track_count: None,
273            landmark_init: LandmarkInit::StereoSingleFrame,
274            window_size: None,
275            gravity_prior: None,
276            position_prior: None,
277            per_pose_gravity_prior: None,
278            imu_input: None,
279            fix_pose_prefix: 1,
280            ba_config: BaConfig {
281                max_iterations: 12,
282                robust_kernel: RobustKernel::Huber { delta: 3.0 },
283                linear_solver: LinearSolver::Sparse,
284                ..BaConfig::default()
285            },
286        }
287    }
288}
289
290/// Result of [`refine_stereo_vo_with_ba`].
291#[derive(Debug, Clone, PartialEq)]
292pub struct StereoVoBaRefinement {
293    /// Refined `world_to_camera` pose per frame (same length as the input
294    /// `initial_poses`). Pose 0 is unchanged (it is fixed as the anchor).
295    pub refined_poses: Vec<Pose>,
296    /// LM iteration trace and final cost from the BA solve.
297    pub ba_result: BaResult,
298    /// Number of multi-frame tracks that contributed landmarks to BA.
299    pub track_count: usize,
300    /// Number of `BaStereoObservation`s added across all tracks.
301    pub observation_count: usize,
302    /// Refined IMU state when [`StereoVoBaConfig::imu_input`] was set.
303    /// `None` when the BA solve ran visual-only.
304    pub imu_refinement: Option<StereoVoBaImuRefinement>,
305}
306
307/// Refine a stereo VO trajectory with multi-frame stereo bundle adjustment.
308///
309/// Build forward feature tracks by chaining `temporal_matches` across frames,
310/// initialise each long track's landmark from its first valid stereo
311/// observation, then run Schur-complement BA over all `initial_poses` (with
312/// pose 0 fixed) plus all long-tracked landmarks. The metric scale is
313/// anchored by the rectified-stereo baseline; no extra gauge fixing is
314/// required.
315// Public entry point: the stereo rig (camera, baseline), the per-frame VO
316// sequence (poses, left/right features, stereo, temporal matches), and config.
317#[allow(clippy::too_many_arguments)]
318pub fn refine_stereo_vo_with_ba(
319    camera: &Camera,
320    baseline: f64,
321    initial_poses: &[Pose],
322    left_features: &[FeatureSet],
323    right_features: &[FeatureSet],
324    stereo_per_frame: &[Vec<StereoFeature>],
325    temporal_matches: &[Vec<DescriptorMatch>],
326    config: &StereoVoBaConfig,
327) -> Result<StereoVoBaRefinement, StereoVoBaError> {
328    let n_frames = initial_poses.len();
329    if n_frames < config.min_track_length || n_frames < 2 {
330        return Err(StereoVoBaError::TooFewFrames(n_frames));
331    }
332    if left_features.len() != n_frames
333        || right_features.len() != n_frames
334        || stereo_per_frame.len() != n_frames
335    {
336        return Err(StereoVoBaError::InputLengthMismatch);
337    }
338    if temporal_matches.len() != n_frames - 1 {
339        return Err(StereoVoBaError::InputLengthMismatch);
340    }
341    if let Some(imu) = &config.imu_input {
342        if imu.windows.len() != n_frames - 1 {
343            return Err(StereoVoBaError::InvalidImuInput {
344                reason: format!(
345                    "imu_input.windows.len()={} must equal initial_poses.len()-1={}",
346                    imu.windows.len(),
347                    n_frames - 1
348                ),
349            });
350        }
351        if config.window_size.is_some() {
352            return Err(StereoVoBaError::InvalidImuInput {
353                reason:
354                    "sliding-window BA (`window_size`) is not yet wired through the IMU factor stack"
355                        .to_string(),
356            });
357        }
358        for (i, samples) in imu.windows.iter().enumerate() {
359            for (k, s) in samples.iter().enumerate() {
360                if !(s.dt.is_finite() && s.dt > 0.0) {
361                    return Err(StereoVoBaError::InvalidImuInput {
362                        reason: format!("window[{i}] sample[{k}] has non-positive dt={}", s.dt),
363                    });
364                }
365            }
366        }
367    }
368
369    if let Some(w) = config.window_size {
370        if w < config.min_track_length || w < 2 {
371            return Err(StereoVoBaError::TooFewFrames(w));
372        }
373        // Sliding-window mode: refine overlapping windows of `w` frames each.
374        // Successive windows share one boundary pose so the trajectory stays
375        // continuous; that boundary pose, once refined, becomes the fixed
376        // gauge of the next window.
377        let mut refined = initial_poses.to_vec();
378        let mut total_tracks = 0usize;
379        let mut total_obs = 0usize;
380        let mut agg_initial_cost = 0.0;
381        let mut agg_final_cost = 0.0;
382        let mut all_iterations: Vec<crate::BaIterationStats> = Vec::new();
383        let mut converged_all = true;
384        let mut start = 0usize;
385        let mut sub_config = config.clone();
386        sub_config.window_size = None;
387        loop {
388            let end = (start + w).min(n_frames);
389            if end <= start + 1 {
390                break;
391            }
392            if end - start >= config.min_track_length {
393                sub_config.position_prior = config
394                    .position_prior
395                    .as_ref()
396                    .map(|prior| slice_position_prior_for_window(prior, start, end));
397                sub_config.per_pose_gravity_prior = config
398                    .per_pose_gravity_prior
399                    .as_ref()
400                    .map(|prior| slice_per_pose_gravity_prior_for_window(prior, start, end));
401                match refine_stereo_vo_with_ba(
402                    camera,
403                    baseline,
404                    &refined[start..end],
405                    &left_features[start..end],
406                    &right_features[start..end],
407                    &stereo_per_frame[start..end],
408                    &temporal_matches[start..end - 1],
409                    &sub_config,
410                ) {
411                    Ok(window_refinement) => {
412                        for (offset, p) in window_refinement.refined_poses.iter().enumerate() {
413                            refined[start + offset] = p.clone();
414                        }
415                        total_tracks += window_refinement.track_count;
416                        total_obs += window_refinement.observation_count;
417                        agg_initial_cost += window_refinement.ba_result.initial_cost;
418                        agg_final_cost += window_refinement.ba_result.final_cost;
419                        all_iterations.extend(window_refinement.ba_result.iterations);
420                        converged_all = converged_all && window_refinement.ba_result.converged;
421                    }
422                    Err(StereoVoBaError::InsufficientTracks { .. })
423                    | Err(StereoVoBaError::NoLongTracks) => {
424                        // Skip this window; carry initial poses through.
425                    }
426                    Err(e) => return Err(e),
427                }
428            }
429            if end >= n_frames {
430                break;
431            }
432            start = end - 1; // overlap by one boundary frame
433        }
434        if total_tracks == 0 {
435            return Err(StereoVoBaError::NoLongTracks);
436        }
437        return Ok(StereoVoBaRefinement {
438            refined_poses: refined,
439            ba_result: BaResult {
440                initial_cost: agg_initial_cost,
441                final_cost: agg_final_cost,
442                iterations: all_iterations,
443                converged: converged_all,
444            },
445            track_count: total_tracks,
446            observation_count: total_obs,
447            imu_refinement: None,
448        });
449    }
450
451    let stereo_lookup: Vec<HashMap<usize, &StereoFeature>> = stereo_per_frame
452        .iter()
453        .map(|stereo| stereo.iter().map(|f| (f.left_index, f)).collect())
454        .collect();
455
456    let temporal_lookup: Vec<HashMap<usize, usize>> = temporal_matches
457        .iter()
458        .map(|matches| {
459            matches
460                .iter()
461                .filter(|m| match config.min_temporal_confidence {
462                    Some(min) => m.confidence.is_some_and(|c| c.is_finite() && c >= min),
463                    None => true,
464                })
465                .map(|m| (m.query_index, m.train_index))
466                .collect()
467        })
468        .collect();
469
470    let tracks = build_forward_tracks(
471        n_frames,
472        left_features,
473        &temporal_lookup,
474        config.min_track_length,
475    );
476    if tracks.is_empty() {
477        return Err(StereoVoBaError::NoLongTracks);
478    }
479
480    let mut ba = BundleAdjustment::new(camera.clone());
481    ba.set_stereo_baseline(baseline);
482    if let Some(gravity) = config.gravity_prior.clone() {
483        ba.set_gravity_prior(gravity);
484    }
485    if let Some(position_prior) = config.position_prior.clone() {
486        ba.set_position_prior(position_prior);
487    }
488    if let Some(per_pose_gravity_prior) = config.per_pose_gravity_prior.clone() {
489        ba.set_per_pose_gravity_prior(per_pose_gravity_prior);
490    }
491    for (i, pose) in initial_poses.iter().enumerate() {
492        ba.add_pose(i as u64, pose.clone());
493    }
494    // Fix a leading prefix of poses as the gauge / local-map anchor (default 1 =
495    // fix pose 0 only). A larger prefix anchors long-baseline landmarks over an
496    // extended backward window while only the recent poses move.
497    let fixed_prefix = config
498        .fix_pose_prefix
499        .clamp(1, n_frames.saturating_sub(1).max(1));
500    for i in 0..fixed_prefix {
501        ba.fix_pose(i as u64);
502    }
503
504    // IMU factor / velocity / bias wiring. Pre-integrate every supplied
505    // window, register velocity & bias slots for each active keyframe,
506    // then push the factors. Velocities are initialised from the
507    // inter-keyframe pose-centre delta divided by the integrated time
508    // (a coarse but reasonable seed); biases start at the input
509    // linearisation point. Active keyframes are tracked so the
510    // refinement extraction can fall back cleanly for non-IMU frames.
511    let mut imu_active: Vec<bool> = vec![false; n_frames];
512    if let Some(imu) = &config.imu_input {
513        let bias_init = Vector6::from_iterator(
514            imu.bias_gyro_init
515                .iter()
516                .copied()
517                .chain(imu.bias_acc_init.iter().copied()),
518        );
519        for (window_index, samples) in imu.windows.iter().enumerate() {
520            if samples.is_empty() {
521                continue;
522            }
523            let from_id = window_index as u64;
524            let to_id = (window_index + 1) as u64;
525            let mut pre = ImuPreintegrator::new_with_bias(imu.bias_gyro_init, imu.bias_acc_init);
526            for s in samples {
527                pre.integrate_sample(s.gyro, s.accel, s.dt);
528            }
529            let delta = pre.delta();
530            // Seed velocities from the inter-keyframe world-frame centre
531            // delta, scaled by the integrated time. Only assign when the
532            // slot is not yet populated so multi-window keyframes use
533            // their first arriving seed and don't oscillate.
534            let dt_total = delta.delta_time;
535            let c_from = initial_poses[window_index].camera_center_world();
536            let c_to = initial_poses[window_index + 1].camera_center_world();
537            let v_seed = if dt_total > 0.0 {
538                (c_to - c_from) / dt_total
539            } else {
540                Vector3::zeros()
541            };
542            if !imu_active[window_index] {
543                ba.add_velocity(from_id, v_seed);
544                ba.add_bias(from_id, bias_init);
545                imu_active[window_index] = true;
546            }
547            if !imu_active[window_index + 1] {
548                ba.add_velocity(to_id, v_seed);
549                ba.add_bias(to_id, bias_init);
550                imu_active[window_index + 1] = true;
551            }
552            ba.add_imu_factor(ImuPreintegrationFactor {
553                keyframe_id_from: from_id,
554                keyframe_id_to: to_id,
555                delta,
556                gravity_world: imu.gravity_world,
557                weight_position: imu.weight_position,
558                weight_velocity: imu.weight_velocity,
559                weight_rotation: imu.weight_rotation,
560            });
561        }
562        // Optional random-walk tie between consecutive bias slots.
563        if let Some(rw_weight) = imu.bias_random_walk_weight {
564            for i in 0..(n_frames - 1) {
565                if imu_active[i] && imu_active[i + 1] {
566                    ba.add_bias_random_walk_factor(BiasRandomWalkFactor {
567                        keyframe_id_from: i as u64,
568                        keyframe_id_to: (i + 1) as u64,
569                        weight_gyro: rw_weight,
570                        weight_accel: rw_weight,
571                    });
572                }
573            }
574        }
575        // Gauge anchors: optionally fix the very first IMU-active slot.
576        if let Some(first_active) = imu_active.iter().position(|&a| a) {
577            if imu.fix_first_bias {
578                ba.fix_bias(first_active as u64);
579            }
580            if imu.fix_first_velocity {
581                ba.fix_velocity(first_active as u64);
582            }
583        }
584    }
585
586    let mut observation_count = 0usize;
587    let mut landmark_count = 0usize;
588    let mut next_landmark_id: u64 = 0;
589
590    let seed_row_threshold: Option<f64> = config
591        .max_seed_row_fraction
592        .map(|frac| (camera.height as f64) * frac);
593
594    let intrinsics_for_residual: Option<(f64, f64, f64, f64)> =
595        config.max_init_residual_px.and(camera.intrinsics());
596
597    for track in &tracks {
598        // Optional row-band filter: drop tracks whose first observation is
599        // outside the configured upper-image band. Road-surface features
600        // (lower image rows) genuinely violate rigid-body BA on slope
601        // sequences (KITTI seq08) so removing them is a structural fix.
602        if let Some(row_max) = seed_row_threshold {
603            let (first_frame, first_idx) = track[0];
604            let Some(first_kp) = left_features[first_frame].keypoints.get(first_idx) else {
605                continue;
606            };
607            if first_kp.y >= row_max {
608                continue;
609            }
610        }
611        let init_world = match config.landmark_init {
612            LandmarkInit::StereoSingleFrame => initial_landmark_world(
613                track,
614                &stereo_lookup,
615                initial_poses,
616                config.max_initial_depth_m,
617            ),
618            LandmarkInit::MultiViewDlt => initial_landmark_world_dlt(
619                track,
620                &stereo_lookup,
621                left_features,
622                right_features,
623                initial_poses,
624                camera,
625                baseline,
626                config.max_initial_depth_m,
627            )
628            .or_else(|| {
629                // DLT can fail on degenerate geometry (collinear cameras +
630                // far-field points). Fall back to the single-frame stereo
631                // init so the track still gets a chance at BA.
632                initial_landmark_world(
633                    track,
634                    &stereo_lookup,
635                    initial_poses,
636                    config.max_initial_depth_m,
637                )
638            }),
639        };
640        let Some(init_world) = init_world else {
641            continue;
642        };
643        // Build the candidate observation list first; only commit if the
644        // track has enough stereo-observed frames AND every per-observation
645        // initial residual stays below the configured pre-BA gate.
646        let mut candidate_obs: Vec<BaStereoObservation> = Vec::with_capacity(track.len());
647        let landmark_id = next_landmark_id;
648        let mut track_passes_residual_gate = true;
649        for &(frame, left_idx) in track {
650            let Some(left_kp) = left_features[frame].keypoints.get(left_idx) else {
651                continue;
652            };
653            let Some(stereo) = stereo_lookup[frame].get(&left_idx) else {
654                continue;
655            };
656            let Some(right_kp) = right_features[frame].keypoints.get(stereo.right_index) else {
657                continue;
658            };
659            if let (Some(threshold), Some((fx, fy, cx, cy))) =
660                (config.max_init_residual_px, intrinsics_for_residual)
661            {
662                // Predicted stereo projection of init_world from this frame's
663                // initial pose. Reject the entire track if any observation
664                // disagrees with the initial geometry by more than the gate.
665                let pose = &initial_poses[frame];
666                let xc = pose.transform_world_point(&init_world);
667                if xc.z <= 0.0 {
668                    track_passes_residual_gate = false;
669                    break;
670                }
671                let u_l_pred = fx * xc.x / xc.z + cx;
672                let v_pred = fy * xc.y / xc.z + cy;
673                let u_r_pred = u_l_pred - fx * baseline / xc.z;
674                let du_l = u_l_pred - left_kp.x;
675                let dv = v_pred - left_kp.y;
676                let du_r = u_r_pred - right_kp.x;
677                let residual_norm = (du_l * du_l + dv * dv + du_r * du_r).sqrt();
678                if !residual_norm.is_finite() || residual_norm > threshold {
679                    track_passes_residual_gate = false;
680                    break;
681                }
682            }
683            candidate_obs.push(BaStereoObservation {
684                keyframe_id: frame as u64,
685                landmark_id,
686                xy: Point2::new(left_kp.x, left_kp.y),
687                u_right: right_kp.x,
688            });
689        }
690        if !track_passes_residual_gate {
691            continue;
692        }
693        if candidate_obs.len() < config.min_track_length {
694            continue;
695        }
696        next_landmark_id += 1;
697        ba.add_landmark(landmark_id, init_world);
698        observation_count += candidate_obs.len();
699        for obs in candidate_obs {
700            ba.add_stereo_observation(obs);
701        }
702        landmark_count += 1;
703    }
704
705    if landmark_count == 0 {
706        return Err(StereoVoBaError::NoLongTracks);
707    }
708    if let Some(required) = config.min_track_count {
709        if landmark_count < required {
710            return Err(StereoVoBaError::InsufficientTracks {
711                count: landmark_count,
712                required,
713            });
714        }
715    }
716
717    let ba_result = ba
718        .optimize(&config.ba_config)
719        .map_err(StereoVoBaError::Ba)?;
720
721    let refined_poses: Vec<Pose> = (0..n_frames as u64)
722        .map(|i| {
723            ba.poses
724                .get(&i)
725                .cloned()
726                .unwrap_or_else(|| initial_poses[i as usize].clone())
727        })
728        .collect();
729
730    let imu_refinement = config.imu_input.as_ref().map(|imu| {
731        let mut velocities = vec![Vector3::zeros(); n_frames];
732        let mut bias_g = vec![imu.bias_gyro_init; n_frames];
733        let mut bias_a = vec![imu.bias_acc_init; n_frames];
734        for i in 0..n_frames as u64 {
735            if let Some(v) = ba.velocities.get(&i) {
736                velocities[i as usize] = *v;
737            }
738            if let Some(b) = ba.biases.get(&i) {
739                bias_g[i as usize] = b.fixed_rows::<3>(0).into();
740                bias_a[i as usize] = b.fixed_rows::<3>(3).into();
741            }
742        }
743        StereoVoBaImuRefinement {
744            refined_velocities: velocities,
745            refined_bias_gyro: bias_g,
746            refined_bias_acc: bias_a,
747        }
748    });
749
750    Ok(StereoVoBaRefinement {
751        refined_poses,
752        ba_result,
753        track_count: landmark_count,
754        observation_count,
755        imu_refinement,
756    })
757}
758
759/// A left-image observation track: `(frame, left_keypoint_index, pixel)` per view.
760type TrackObservations = Vec<(usize, usize, Point2<f64>)>;
761
762/// A single reconstructed 3D point with its full multi-view track.
763///
764/// Unlike the per-frame stereo lift used by the streaming VO (one landmark per
765/// frame, observed once), each `ReconstructedLandmark` is a *merged* track: the
766/// same physical point seen by every frame the forward-track chaining linked it
767/// to. This is the multi-view constraint that makes a global bundle adjustment
768/// tighten reprojection to sub-pixel — i.e. COLMAP-grade structure suitable for
769/// downstream novel-view synthesis (3DGS).
770#[derive(Debug, Clone, PartialEq)]
771pub struct ReconstructedLandmark {
772    /// Refined world-frame position after BA.
773    pub position: Point3<f64>,
774    /// Every left-image observation of this point: `(frame, left_keypoint_index, pixel)`.
775    pub observations: TrackObservations,
776}
777
778/// Output of [`reconstruct_stereo_vo_with_ba`]: a BA-grade sparse reconstruction
779/// (refined poses + merged multi-view landmark tracks) ready for COLMAP export.
780#[derive(Debug, Clone)]
781pub struct StereoVoReconstruction {
782    /// Refined `world_to_camera` pose per frame (pose 0 fixed as the anchor).
783    pub refined_poses: Vec<Pose>,
784    /// Merged multi-view landmark tracks (each observed by ≥ `min_track_length` frames).
785    pub landmarks: Vec<ReconstructedLandmark>,
786    /// LM iteration trace and final cost from the BA solve.
787    pub ba_result: BaResult,
788    /// Total left-image observations across all landmark tracks.
789    pub observation_count: usize,
790    /// Mean left-image reprojection error (px) before BA, over all observations.
791    pub mean_reproj_before_px: f64,
792    /// Mean left-image reprojection error (px) after BA — the structure-quality headline.
793    pub mean_reproj_after_px: f64,
794}
795
796/// Build a COLMAP-grade sparse reconstruction from a stereo VO trajectory.
797///
798/// Where [`refine_stereo_vo_with_ba`] runs the same global bundle adjustment but
799/// only returns the refined *poses* (discarding the structure), this entry point
800/// keeps the merged multi-view landmark tracks so they can be written out as a
801/// COLMAP model — every 3D point carries the full `TRACK[]` of frames that see
802/// it, which is exactly what a per-frame stereo lift lacks and what a downstream
803/// 3DGS optimizer needs to converge crisply.
804///
805/// Visual-only and global (no IMU, no sliding window): novel-view synthesis
806/// wants one joint solve over every pose and point. Metric scale is anchored by
807/// the rectified-stereo baseline; pose 0 is fixed as the gauge.
808#[allow(clippy::too_many_arguments)]
809pub fn reconstruct_stereo_vo_with_ba(
810    camera: &Camera,
811    baseline: f64,
812    initial_poses: &[Pose],
813    left_features: &[FeatureSet],
814    right_features: &[FeatureSet],
815    stereo_per_frame: &[Vec<StereoFeature>],
816    temporal_matches: &[Vec<DescriptorMatch>],
817    config: &StereoVoBaConfig,
818) -> Result<StereoVoReconstruction, StereoVoBaError> {
819    let n_frames = initial_poses.len();
820    if n_frames < config.min_track_length || n_frames < 2 {
821        return Err(StereoVoBaError::TooFewFrames(n_frames));
822    }
823    if left_features.len() != n_frames
824        || right_features.len() != n_frames
825        || stereo_per_frame.len() != n_frames
826        || temporal_matches.len() != n_frames - 1
827    {
828        return Err(StereoVoBaError::InputLengthMismatch);
829    }
830
831    let stereo_lookup: Vec<HashMap<usize, &StereoFeature>> = stereo_per_frame
832        .iter()
833        .map(|stereo| stereo.iter().map(|f| (f.left_index, f)).collect())
834        .collect();
835    let temporal_lookup: Vec<HashMap<usize, usize>> = temporal_matches
836        .iter()
837        .map(|matches| {
838            matches
839                .iter()
840                .filter(|m| match config.min_temporal_confidence {
841                    Some(min) => m.confidence.is_some_and(|c| c.is_finite() && c >= min),
842                    None => true,
843                })
844                .map(|m| (m.query_index, m.train_index))
845                .collect()
846        })
847        .collect();
848
849    let tracks = build_forward_tracks(
850        n_frames,
851        left_features,
852        &temporal_lookup,
853        config.min_track_length,
854    );
855    if tracks.is_empty() {
856        return Err(StereoVoBaError::NoLongTracks);
857    }
858
859    let mut ba = BundleAdjustment::new(camera.clone());
860    ba.set_stereo_baseline(baseline);
861    for (i, pose) in initial_poses.iter().enumerate() {
862        ba.add_pose(i as u64, pose.clone());
863    }
864    ba.fix_pose(0);
865
866    let seed_row_threshold: Option<f64> = config
867        .max_seed_row_fraction
868        .map(|frac| (camera.height as f64) * frac);
869    let intrinsics_for_residual: Option<(f64, f64, f64, f64)> =
870        config.max_init_residual_px.and(camera.intrinsics());
871
872    // Per accepted landmark, remember its left-image observations so we can
873    // emit the merged track once BA has refined the point.
874    let mut landmark_obs: Vec<(u64, TrackObservations)> = Vec::new();
875    let mut observation_count = 0usize;
876    let mut next_landmark_id: u64 = 0;
877
878    for track in &tracks {
879        if let Some(row_max) = seed_row_threshold {
880            let (first_frame, first_idx) = track[0];
881            let Some(first_kp) = left_features[first_frame].keypoints.get(first_idx) else {
882                continue;
883            };
884            if first_kp.y >= row_max {
885                continue;
886            }
887        }
888        let init_world = match config.landmark_init {
889            LandmarkInit::StereoSingleFrame => initial_landmark_world(
890                track,
891                &stereo_lookup,
892                initial_poses,
893                config.max_initial_depth_m,
894            ),
895            LandmarkInit::MultiViewDlt => initial_landmark_world_dlt(
896                track,
897                &stereo_lookup,
898                left_features,
899                right_features,
900                initial_poses,
901                camera,
902                baseline,
903                config.max_initial_depth_m,
904            )
905            .or_else(|| {
906                initial_landmark_world(
907                    track,
908                    &stereo_lookup,
909                    initial_poses,
910                    config.max_initial_depth_m,
911                )
912            }),
913        };
914        let Some(init_world) = init_world else {
915            continue;
916        };
917
918        let landmark_id = next_landmark_id;
919        let mut candidate_obs: Vec<BaStereoObservation> = Vec::with_capacity(track.len());
920        let mut track_obs: TrackObservations = Vec::with_capacity(track.len());
921        let mut track_passes_residual_gate = true;
922        for &(frame, left_idx) in track {
923            let Some(left_kp) = left_features[frame].keypoints.get(left_idx) else {
924                continue;
925            };
926            let Some(stereo) = stereo_lookup[frame].get(&left_idx) else {
927                continue;
928            };
929            let Some(right_kp) = right_features[frame].keypoints.get(stereo.right_index) else {
930                continue;
931            };
932            if let (Some(threshold), Some((fx, fy, cx, cy))) =
933                (config.max_init_residual_px, intrinsics_for_residual)
934            {
935                let pose = &initial_poses[frame];
936                let xc = pose.transform_world_point(&init_world);
937                if xc.z <= 0.0 {
938                    track_passes_residual_gate = false;
939                    break;
940                }
941                let u_l_pred = fx * xc.x / xc.z + cx;
942                let v_pred = fy * xc.y / xc.z + cy;
943                let u_r_pred = u_l_pred - fx * baseline / xc.z;
944                let du_l = u_l_pred - left_kp.x;
945                let dv = v_pred - left_kp.y;
946                let du_r = u_r_pred - right_kp.x;
947                let residual_norm = (du_l * du_l + dv * dv + du_r * du_r).sqrt();
948                if !residual_norm.is_finite() || residual_norm > threshold {
949                    track_passes_residual_gate = false;
950                    break;
951                }
952            }
953            let xy = Point2::new(left_kp.x, left_kp.y);
954            candidate_obs.push(BaStereoObservation {
955                keyframe_id: frame as u64,
956                landmark_id,
957                xy,
958                u_right: right_kp.x,
959            });
960            track_obs.push((frame, left_idx, xy));
961        }
962        if !track_passes_residual_gate || candidate_obs.len() < config.min_track_length {
963            continue;
964        }
965        next_landmark_id += 1;
966        ba.add_landmark(landmark_id, init_world);
967        observation_count += candidate_obs.len();
968        for obs in candidate_obs {
969            ba.add_stereo_observation(obs);
970        }
971        landmark_obs.push((landmark_id, track_obs));
972    }
973
974    if landmark_obs.is_empty() {
975        return Err(StereoVoBaError::NoLongTracks);
976    }
977    if let Some(required) = config.min_track_count {
978        if landmark_obs.len() < required {
979            return Err(StereoVoBaError::InsufficientTracks {
980                count: landmark_obs.len(),
981                required,
982            });
983        }
984    }
985
986    let mean_reproj_before_px = mean_left_reprojection_px(&ba);
987    let ba_result = ba
988        .optimize(&config.ba_config)
989        .map_err(StereoVoBaError::Ba)?;
990    let mean_reproj_after_px = mean_left_reprojection_px(&ba);
991
992    let refined_poses: Vec<Pose> = (0..n_frames as u64)
993        .map(|i| {
994            ba.poses
995                .get(&i)
996                .cloned()
997                .unwrap_or_else(|| initial_poses[i as usize].clone())
998        })
999        .collect();
1000
1001    let landmarks: Vec<ReconstructedLandmark> = landmark_obs
1002        .into_iter()
1003        .filter_map(|(id, observations)| {
1004            ba.landmarks.get(&id).map(|p| ReconstructedLandmark {
1005                position: *p,
1006                observations,
1007            })
1008        })
1009        .collect();
1010
1011    Ok(StereoVoReconstruction {
1012        refined_poses,
1013        landmarks,
1014        ba_result,
1015        observation_count,
1016        mean_reproj_before_px,
1017        mean_reproj_after_px,
1018    })
1019}
1020
1021/// Mean left-image reprojection error (px) over every stereo observation in a
1022/// BA problem, using the current pose/landmark estimates. The right-image term
1023/// is ignored so the figure is directly comparable to a monocular reprojection.
1024fn mean_left_reprojection_px(ba: &BundleAdjustment) -> f64 {
1025    let Some((fx, fy, cx, cy)) = ba.camera.intrinsics() else {
1026        return f64::NAN;
1027    };
1028    let mut sum = 0.0;
1029    let mut count = 0usize;
1030    for obs in &ba.stereo_observations {
1031        let (Some(pose), Some(point)) = (
1032            ba.poses.get(&obs.keyframe_id),
1033            ba.landmarks.get(&obs.landmark_id),
1034        ) else {
1035            continue;
1036        };
1037        let xc = pose.transform_world_point(point);
1038        if xc.z <= 0.0 {
1039            continue;
1040        }
1041        let u = fx * xc.x / xc.z + cx;
1042        let v = fy * xc.y / xc.z + cy;
1043        let du = u - obs.xy.x;
1044        let dv = v - obs.xy.y;
1045        sum += (du * du + dv * dv).sqrt();
1046        count += 1;
1047    }
1048    if count == 0 {
1049        f64::NAN
1050    } else {
1051        sum / count as f64
1052    }
1053}
1054
1055fn slice_position_prior_for_window(
1056    prior: &PositionPrior,
1057    start: usize,
1058    end: usize,
1059) -> PositionPrior {
1060    let mut out = PositionPrior::new();
1061    for obs in &prior.observations {
1062        let frame = obs.keyframe_id as usize;
1063        if frame >= start && frame < end {
1064            let mut local = obs.clone();
1065            local.keyframe_id = (frame - start) as u64;
1066            out.push(local);
1067        }
1068    }
1069    out
1070}
1071
1072fn slice_per_pose_gravity_prior_for_window(
1073    prior: &PerPoseGravityPrior,
1074    start: usize,
1075    end: usize,
1076) -> PerPoseGravityPrior {
1077    let mut out = PerPoseGravityPrior::new(prior.g_world, prior.weight);
1078    for obs in &prior.observations {
1079        let frame = obs.keyframe_id as usize;
1080        if frame >= start && frame < end {
1081            let mut local = obs.clone();
1082            local.keyframe_id = (frame - start) as u64;
1083            out.push(local);
1084        }
1085    }
1086    out
1087}
1088
1089fn build_forward_tracks(
1090    n_frames: usize,
1091    left_features: &[FeatureSet],
1092    temporal_lookup: &[HashMap<usize, usize>],
1093    min_track_length: usize,
1094) -> Vec<Vec<(usize, usize)>> {
1095    let mut visited: HashMap<(usize, usize), ()> = HashMap::new();
1096    let mut tracks: Vec<Vec<(usize, usize)>> = Vec::new();
1097    for (start_frame, start_features) in left_features.iter().enumerate().take(n_frames) {
1098        for start_idx in 0..start_features.keypoints.len() {
1099            if visited.contains_key(&(start_frame, start_idx)) {
1100                continue;
1101            }
1102            let mut track = vec![(start_frame, start_idx)];
1103            visited.insert((start_frame, start_idx), ());
1104            let mut curr_frame = start_frame;
1105            let mut curr_idx = start_idx;
1106            while curr_frame + 1 < n_frames {
1107                let Some(map) = temporal_lookup.get(curr_frame) else {
1108                    break;
1109                };
1110                let Some(&next_idx) = map.get(&curr_idx) else {
1111                    break;
1112                };
1113                if visited.contains_key(&(curr_frame + 1, next_idx)) {
1114                    break;
1115                }
1116                track.push((curr_frame + 1, next_idx));
1117                visited.insert((curr_frame + 1, next_idx), ());
1118                curr_frame += 1;
1119                curr_idx = next_idx;
1120            }
1121            if track.len() >= min_track_length {
1122                tracks.push(track);
1123            }
1124        }
1125    }
1126    tracks
1127}
1128
1129fn initial_landmark_world(
1130    track: &[(usize, usize)],
1131    stereo_lookup: &[HashMap<usize, &StereoFeature>],
1132    initial_poses: &[Pose],
1133    max_initial_depth_m: f64,
1134) -> Option<Point3<f64>> {
1135    for &(frame, left_idx) in track {
1136        let Some(stereo) = stereo_lookup[frame].get(&left_idx) else {
1137            continue;
1138        };
1139        if !stereo.point_cam.coords.iter().all(|v| v.is_finite()) {
1140            continue;
1141        }
1142        if stereo.point_cam.z <= 0.0 || stereo.point_cam.z > max_initial_depth_m {
1143            continue;
1144        }
1145        let pose = &initial_poses[frame];
1146        let world = pose.camera_to_world().transform_point(&stereo.point_cam);
1147        return Some(world);
1148    }
1149    None
1150}
1151
1152/// Linear DLT triangulation over all stereo observations in a track. Each
1153/// stereo-observed frame contributes 3 rows to `A * [X, 1]^T = 0`: two from
1154/// the left-image projection equations and one from the right-image `u_r`
1155/// (the rectified-stereo `v_r = v_l` row is redundant with the left row).
1156///
1157/// Returns `None` when the track has fewer than 2 stereo-observed frames
1158/// (DLT is under-constrained), the SVD fails, or the recovered point fails
1159/// cheirality / depth gates at the first observation's frame.
1160// Per-track DLT triangulation inputs: the track plus the shared BA frame data
1161// (stereo lookup, features, poses, rig). Passed positionally for one call site.
1162#[allow(clippy::too_many_arguments)]
1163fn initial_landmark_world_dlt(
1164    track: &[(usize, usize)],
1165    stereo_lookup: &[HashMap<usize, &StereoFeature>],
1166    left_features: &[FeatureSet],
1167    right_features: &[FeatureSet],
1168    initial_poses: &[Pose],
1169    camera: &Camera,
1170    baseline: f64,
1171    max_initial_depth_m: f64,
1172) -> Option<Point3<f64>> {
1173    let (fx, fy, cx, cy) = camera.intrinsics()?;
1174    let mut rows: Vec<[f64; 4]> = Vec::with_capacity(track.len() * 3);
1175    let mut first_pose_index: Option<usize> = None;
1176    for &(frame, left_idx) in track {
1177        let Some(left_kp) = left_features[frame].keypoints.get(left_idx) else {
1178            continue;
1179        };
1180        let Some(stereo) = stereo_lookup[frame].get(&left_idx) else {
1181            continue;
1182        };
1183        let Some(right_kp) = right_features[frame].keypoints.get(stereo.right_index) else {
1184            continue;
1185        };
1186        if first_pose_index.is_none() {
1187            first_pose_index = Some(frame);
1188        }
1189        let pose = &initial_poses[frame];
1190        let r = pose.world_to_camera.rotation.to_rotation_matrix();
1191        let r = r.matrix();
1192        let t = pose.world_to_camera.translation;
1193        // Left projection matrix rows: P_left = K_left * [R | t]
1194        let p0 = [
1195            fx * r[(0, 0)] + cx * r[(2, 0)],
1196            fx * r[(0, 1)] + cx * r[(2, 1)],
1197            fx * r[(0, 2)] + cx * r[(2, 2)],
1198            fx * t.x + cx * t.z,
1199        ];
1200        let p1 = [
1201            fy * r[(1, 0)] + cy * r[(2, 0)],
1202            fy * r[(1, 1)] + cy * r[(2, 1)],
1203            fy * r[(1, 2)] + cy * r[(2, 2)],
1204            fy * t.y + cy * t.z,
1205        ];
1206        let p2 = [r[(2, 0)], r[(2, 1)], r[(2, 2)], t.z];
1207        // u_l row: u_l * p2 - p0 = 0
1208        rows.push([
1209            left_kp.x * p2[0] - p0[0],
1210            left_kp.x * p2[1] - p0[1],
1211            left_kp.x * p2[2] - p0[2],
1212            left_kp.x * p2[3] - p0[3],
1213        ]);
1214        // v_l row: v_l * p2 - p1 = 0
1215        rows.push([
1216            left_kp.y * p2[0] - p1[0],
1217            left_kp.y * p2[1] - p1[1],
1218            left_kp.y * p2[2] - p1[2],
1219            left_kp.y * p2[3] - p1[3],
1220        ]);
1221        // Right cam shares R; its origin is at +baseline along the left cam's
1222        // x-axis. Thus the right-cam world_to_camera translation is
1223        // `t - [b, 0, 0]^T` in the left-cam frame. The right `u_r` projection
1224        // row uses the same K but the shifted translation:
1225        //   u_r * (p2_right - p0_right) = 0
1226        // where p2_right == p2 (z-row unchanged), and the right p0 has
1227        // `t_right_x = t.x - baseline` in column 3.
1228        let p0_right_col3 = fx * (t.x - baseline) + cx * t.z;
1229        let p0_right = [p0[0], p0[1], p0[2], p0_right_col3];
1230        rows.push([
1231            right_kp.x * p2[0] - p0_right[0],
1232            right_kp.x * p2[1] - p0_right[1],
1233            right_kp.x * p2[2] - p0_right[2],
1234            right_kp.x * p2[3] - p0_right[3],
1235        ]);
1236    }
1237    if rows.len() < 6 {
1238        // Need at least 2 stereo-observed frames (6 rows) for an
1239        // over-determined 4-unknown linear system.
1240        return None;
1241    }
1242    let first_frame = first_pose_index?;
1243    let n = rows.len();
1244    let mut a = DMatrix::<f64>::zeros(n, 4);
1245    for (i, row) in rows.iter().enumerate() {
1246        for j in 0..4 {
1247            a[(i, j)] = row[j];
1248        }
1249    }
1250    let svd = a.svd(false, true);
1251    let v_t = svd.v_t?;
1252    // Right singular vector for the smallest singular value (= last row of V^T).
1253    let solution = v_t.row(3);
1254    let w = solution[3];
1255    if !w.is_finite() || w.abs() < 1e-12 {
1256        return None;
1257    }
1258    let world = Point3::new(solution[0] / w, solution[1] / w, solution[2] / w);
1259    if !world.coords.iter().all(|v| v.is_finite()) {
1260        return None;
1261    }
1262    // Cheirality + depth gate at the first observation's frame.
1263    let p_cam = initial_poses[first_frame].transform_world_point(&world);
1264    if !p_cam.z.is_finite() || p_cam.z <= 0.0 || p_cam.z > max_initial_depth_m {
1265        return None;
1266    }
1267    Some(world)
1268}
1269
1270#[derive(Debug, Clone, PartialEq)]
1271pub enum StereoVoBaError {
1272    /// `initial_poses.len()` is less than the minimum required.
1273    TooFewFrames(usize),
1274    /// Per-frame slices have inconsistent lengths.
1275    InputLengthMismatch,
1276    /// No track of length `>= min_track_length` could be built from the
1277    /// supplied temporal matches.
1278    NoLongTracks,
1279    /// `config.min_track_count` was set and the filtered track set was
1280    /// below the gate. `count` is what survived; `required` is the gate.
1281    InsufficientTracks { count: usize, required: usize },
1282    /// `config.imu_input` was malformed (wrong number of windows, a
1283    /// non-positive sample dt, or incompatible with `window_size`).
1284    InvalidImuInput { reason: String },
1285    /// Underlying BA error.
1286    Ba(BaError),
1287}
1288
1289impl std::fmt::Display for StereoVoBaError {
1290    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1291        match self {
1292            StereoVoBaError::TooFewFrames(n) => {
1293                write!(
1294                    f,
1295                    "stereo VO BA: only {n} frames, need at least min_track_length"
1296                )
1297            }
1298            StereoVoBaError::InputLengthMismatch => {
1299                write!(
1300                    f,
1301                    "stereo VO BA: per-frame input slices have inconsistent lengths"
1302                )
1303            }
1304            StereoVoBaError::NoLongTracks => {
1305                write!(
1306                    f,
1307                    "stereo VO BA: no tracks of sufficient length built from temporal matches"
1308                )
1309            }
1310            StereoVoBaError::InsufficientTracks { count, required } => write!(
1311                f,
1312                "stereo VO BA: only {count} tracks survived filters, below min_track_count={required}"
1313            ),
1314            StereoVoBaError::InvalidImuInput { reason } => {
1315                write!(f, "stereo VO BA: invalid imu_input — {reason}")
1316            }
1317            StereoVoBaError::Ba(err) => write!(f, "stereo VO BA: {err}"),
1318        }
1319    }
1320}
1321
1322impl std::error::Error for StereoVoBaError {}
1323
1324/// Parse a plain-text per-window IMU sample file.
1325///
1326/// Each non-empty, non-comment line carries seven whitespace-separated
1327/// numbers `dt gyro_x gyro_y gyro_z accel_x accel_y accel_z`. Lines
1328/// starting with `#` are treated as comments. The returned samples
1329/// preserve file order so callers can hand them straight to
1330/// [`ImuPreintegrator::integrate_sample`] without resorting on time.
1331///
1332/// `dt` must be a positive finite number; a non-positive `dt` aborts
1333/// the parse with a descriptive error so callers don't silently feed
1334/// the BA an unintegrable window.
1335pub fn parse_stereo_vo_imu_samples_txt(text: &str) -> Result<Vec<StereoVoBaImuSample>, String> {
1336    let mut out = Vec::new();
1337    for (line_no, raw) in text.lines().enumerate() {
1338        let trimmed = raw.trim();
1339        if trimmed.is_empty() || trimmed.starts_with('#') {
1340            continue;
1341        }
1342        let nums: Vec<f64> = trimmed
1343            .split_whitespace()
1344            .map(|tok| {
1345                tok.parse::<f64>()
1346                    .map_err(|e| format!("line {}: cannot parse '{tok}': {e}", line_no + 1))
1347            })
1348            .collect::<Result<_, _>>()?;
1349        if nums.len() != 7 {
1350            return Err(format!(
1351                "line {}: expected 7 numbers (dt gyro accel), got {}",
1352                line_no + 1,
1353                nums.len()
1354            ));
1355        }
1356        let dt = nums[0];
1357        if !dt.is_finite() || dt <= 0.0 {
1358            return Err(format!(
1359                "line {}: dt must be a positive finite number, got {dt}",
1360                line_no + 1
1361            ));
1362        }
1363        out.push(StereoVoBaImuSample {
1364            dt,
1365            gyro: Vector3::new(nums[1], nums[2], nums[3]),
1366            accel: Vector3::new(nums[4], nums[5], nums[6]),
1367        });
1368    }
1369    Ok(out)
1370}
1371
1372/// Slice a globally-timestamped IMU stream into per-keyframe pre-integration
1373/// windows that match the [`StereoVoBaImuInput::windows`] layout.
1374///
1375/// Given monotonically non-decreasing IMU timestamps `imu_timestamps_ns` and
1376/// the matching gyro / accel readings (same length), plus keyframe timestamps
1377/// `keyframe_timestamps_ns` (length `K >= 2`), the function returns a vector
1378/// of `K - 1` windows. Window `i` collects every IMU sample whose timestamp
1379/// `t` satisfies `kf[i] < t <= kf[i+1]`, with each sample's `dt` equal to the
1380/// gap from the previous timestamp in the window (the first sample is anchored
1381/// to `kf[i]`). If the last sample in the window does not reach `kf[i+1]`, a
1382/// trailing zero-order-hold step is appended using the last sample's
1383/// gyro/accel so the integrated interval matches the inter-keyframe duration.
1384///
1385/// Windows with no IMU coverage are returned empty, which signals
1386/// [`refine_stereo_vo_with_ba`] to skip wiring an IMU factor for that segment.
1387pub fn slice_imu_samples_for_keyframes(
1388    imu_timestamps_ns: &[i128],
1389    imu_gyro: &[Vector3<f64>],
1390    imu_accel: &[Vector3<f64>],
1391    keyframe_timestamps_ns: &[i128],
1392) -> Result<Vec<Vec<StereoVoBaImuSample>>, String> {
1393    if imu_gyro.len() != imu_timestamps_ns.len() {
1394        return Err(format!(
1395            "IMU timestamp / gyro length mismatch: {} vs {}",
1396            imu_timestamps_ns.len(),
1397            imu_gyro.len()
1398        ));
1399    }
1400    if imu_accel.len() != imu_timestamps_ns.len() {
1401        return Err(format!(
1402            "IMU timestamp / accel length mismatch: {} vs {}",
1403            imu_timestamps_ns.len(),
1404            imu_accel.len()
1405        ));
1406    }
1407    if keyframe_timestamps_ns.len() < 2 {
1408        return Err(format!(
1409            "need at least 2 keyframe timestamps, got {}",
1410            keyframe_timestamps_ns.len()
1411        ));
1412    }
1413    for (idx, pair) in keyframe_timestamps_ns.windows(2).enumerate() {
1414        if pair[1] < pair[0] {
1415            return Err(format!(
1416                "keyframe timestamps are not monotonically non-decreasing at index {idx}"
1417            ));
1418        }
1419    }
1420    for (idx, pair) in imu_timestamps_ns.windows(2).enumerate() {
1421        if pair[1] < pair[0] {
1422            return Err(format!(
1423                "IMU timestamps are not monotonically non-decreasing at index {idx}"
1424            ));
1425        }
1426    }
1427
1428    let mut windows: Vec<Vec<StereoVoBaImuSample>> =
1429        Vec::with_capacity(keyframe_timestamps_ns.len() - 1);
1430    let mut cursor = 0usize;
1431    for pair in keyframe_timestamps_ns.windows(2) {
1432        let t_a = pair[0];
1433        let t_b = pair[1];
1434        let mut window: Vec<StereoVoBaImuSample> = Vec::new();
1435        let mut prev_t = t_a;
1436
1437        while cursor < imu_timestamps_ns.len() && imu_timestamps_ns[cursor] <= t_a {
1438            cursor += 1;
1439        }
1440        while cursor < imu_timestamps_ns.len() && imu_timestamps_ns[cursor] <= t_b {
1441            let t = imu_timestamps_ns[cursor];
1442            let dt = (t - prev_t) as f64 * 1e-9;
1443            if dt > 0.0 {
1444                window.push(StereoVoBaImuSample {
1445                    dt,
1446                    gyro: imu_gyro[cursor],
1447                    accel: imu_accel[cursor],
1448                });
1449            }
1450            prev_t = t;
1451            cursor += 1;
1452        }
1453        if prev_t < t_b {
1454            if let Some(last) = window.last() {
1455                let tail_dt = (t_b - prev_t) as f64 * 1e-9;
1456                if tail_dt > 0.0 {
1457                    let tail = StereoVoBaImuSample {
1458                        dt: tail_dt,
1459                        gyro: last.gyro,
1460                        accel: last.accel,
1461                    };
1462                    window.push(tail);
1463                }
1464            }
1465        }
1466        windows.push(window);
1467    }
1468
1469    Ok(windows)
1470}
1471
1472#[cfg(test)]
1473// Tests build large `*Config` fixtures by tweaking a handful of fields off
1474// `Default::default()`; field-by-field assignment reads more clearly than a
1475// struct-update literal here and keeps each gate's relevant knobs together.
1476#[allow(clippy::field_reassign_with_default)]
1477mod tests {
1478    use super::*;
1479    use nalgebra::{Point3, UnitQuaternion, Vector3};
1480    use visloc_core::geometry::SE3;
1481    use visloc_vision::features::FeatureSet;
1482
1483    fn kitti_camera() -> Camera {
1484        Camera::pinhole(0, 1241, 376, 718.856, 718.856, 607.193, 185.216)
1485    }
1486
1487    fn synthetic_landmark_grid() -> Vec<Point3<f64>> {
1488        // 12 stationary landmarks spread in front of the cameras at depths 8..30 m
1489        // and across the image (X in [-4, 4], Y in [-2, 2]).
1490        let mut out = Vec::new();
1491        for &x in &[-4.0, -2.0, 0.0, 2.0, 4.0] {
1492            for &y in &[-2.0, 0.0, 1.5] {
1493                for &z in &[10.0, 20.0] {
1494                    out.push(Point3::new(x, y, z));
1495                }
1496            }
1497        }
1498        out
1499    }
1500
1501    fn project_to_pixels(
1502        camera: &Camera,
1503        pose: &Pose,
1504        landmarks: &[Point3<f64>],
1505        baseline: f64,
1506    ) -> (FeatureSet, FeatureSet, Vec<StereoFeature>) {
1507        let (fx, fy, cx, cy) = camera.intrinsics().unwrap();
1508        let mut left_kp = Vec::new();
1509        let mut right_kp = Vec::new();
1510        let mut stereo = Vec::new();
1511        for (lm_idx, lm) in landmarks.iter().enumerate() {
1512            let p_cam = pose.transform_world_point(lm);
1513            if p_cam.z <= 0.5 {
1514                continue;
1515            }
1516            let u_l = fx * p_cam.x / p_cam.z + cx;
1517            let v = fy * p_cam.y / p_cam.z + cy;
1518            let u_r = u_l - fx * baseline / p_cam.z;
1519            let left_index = left_kp.len();
1520            let right_index = right_kp.len();
1521            left_kp.push(nalgebra::Point2::new(u_l, v));
1522            right_kp.push(nalgebra::Point2::new(u_r, v));
1523            stereo.push(StereoFeature {
1524                left_index,
1525                right_index,
1526                disparity: (u_l - u_r),
1527                point_cam: p_cam,
1528            });
1529            // Use lm_idx to make a unique descriptor so temporal matching is
1530            // straightforward (we don't actually use descriptors in BA tests).
1531            let _ = lm_idx;
1532        }
1533        let left_features = FeatureSet {
1534            keypoints: left_kp,
1535            descriptors: Vec::new(),
1536        };
1537        let right_features = FeatureSet {
1538            keypoints: right_kp,
1539            descriptors: Vec::new(),
1540        };
1541        (left_features, right_features, stereo)
1542    }
1543
1544    /// Multi-view DLT landmark init should produce a near-perfect 3D point
1545    /// when the input observations are noise-free synthetic projections.
1546    #[test]
1547    fn multi_view_dlt_recovers_synthetic_landmark() {
1548        use std::collections::HashMap;
1549
1550        let camera = kitti_camera();
1551        let baseline = 0.537;
1552        // Single landmark in front of the cameras.
1553        let truth = Point3::new(1.0, 0.5, 25.0);
1554        let poses = vec![
1555            Pose::identity(),
1556            Pose {
1557                world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, -1.0)),
1558            },
1559            Pose {
1560                world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, -2.0)),
1561            },
1562        ];
1563        let mut left_features = Vec::new();
1564        let mut right_features = Vec::new();
1565        let mut stereo_per_frame: Vec<Vec<StereoFeature>> = Vec::new();
1566        let (fx, fy, cx, cy) = camera.intrinsics().unwrap();
1567        for p in &poses {
1568            let cam = p.transform_world_point(&truth);
1569            let u_l = fx * cam.x / cam.z + cx;
1570            let v = fy * cam.y / cam.z + cy;
1571            let u_r = u_l - fx * baseline / cam.z;
1572            let left = FeatureSet {
1573                keypoints: vec![nalgebra::Point2::new(u_l, v)],
1574                descriptors: Vec::new(),
1575            };
1576            let right = FeatureSet {
1577                keypoints: vec![nalgebra::Point2::new(u_r, v)],
1578                descriptors: Vec::new(),
1579            };
1580            let stereo = StereoFeature {
1581                left_index: 0,
1582                right_index: 0,
1583                disparity: u_l - u_r,
1584                point_cam: cam,
1585            };
1586            left_features.push(left);
1587            right_features.push(right);
1588            stereo_per_frame.push(vec![stereo]);
1589        }
1590        let track: Vec<(usize, usize)> = vec![(0, 0), (1, 0), (2, 0)];
1591        let stereo_lookup: Vec<HashMap<usize, &StereoFeature>> = stereo_per_frame
1592            .iter()
1593            .map(|stereo| stereo.iter().map(|f| (f.left_index, f)).collect())
1594            .collect();
1595        let recovered = initial_landmark_world_dlt(
1596            &track,
1597            &stereo_lookup,
1598            &left_features,
1599            &right_features,
1600            &poses,
1601            &camera,
1602            baseline,
1603            80.0,
1604        )
1605        .expect("DLT should succeed on noise-free synthetic data");
1606        let err = (recovered - truth).norm();
1607        assert!(
1608            err < 1e-6,
1609            "multi-view DLT recovered point off by {err} for truth {truth:?}, got {recovered:?}"
1610        );
1611    }
1612
1613    /// On a synthetic, stationary scene the refined poses should match the
1614    /// initial (correct) poses to within solver tolerance.
1615    #[test]
1616    fn ba_keeps_correct_trajectory_stable() {
1617        let camera = kitti_camera();
1618        let baseline = 0.537;
1619        let landmarks = synthetic_landmark_grid();
1620
1621        // Three frames: forward motion only.
1622        let poses = vec![
1623            Pose::identity(),
1624            Pose {
1625                world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, -0.8)),
1626            },
1627            Pose {
1628                world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, -1.6)),
1629            },
1630        ];
1631
1632        let mut left = Vec::new();
1633        let mut right = Vec::new();
1634        let mut stereo = Vec::new();
1635        for p in &poses {
1636            let (l, r, s) = project_to_pixels(&camera, p, &landmarks, baseline);
1637            left.push(l);
1638            right.push(r);
1639            stereo.push(s);
1640        }
1641
1642        // Identity temporal matches: each frame's left feature i maps to the
1643        // next frame's left feature i (synthetic scene, no missing matches).
1644        let temporal_matches: Vec<Vec<DescriptorMatch>> = (0..poses.len() - 1)
1645            .map(|f| {
1646                let n = left[f].keypoints.len().min(left[f + 1].keypoints.len());
1647                (0..n)
1648                    .map(|i| DescriptorMatch {
1649                        query_index: i,
1650                        train_index: i,
1651                        distance: 0.0,
1652                        second_best_distance: None,
1653                        ratio: None,
1654                        confidence: Some(1.0),
1655                    })
1656                    .collect()
1657            })
1658            .collect();
1659
1660        let config = StereoVoBaConfig::default();
1661        let refinement = refine_stereo_vo_with_ba(
1662            &camera,
1663            baseline,
1664            &poses,
1665            &left,
1666            &right,
1667            &stereo,
1668            &temporal_matches,
1669            &config,
1670        )
1671        .expect("BA should succeed on synthetic scene");
1672
1673        assert!(refinement.track_count > 0);
1674        assert!(refinement.observation_count > 0);
1675        // Pose 0 is fixed.
1676        assert!(
1677            (refinement.refined_poses[0].world_to_camera.translation
1678                - poses[0].world_to_camera.translation)
1679                .norm()
1680                < 1e-9
1681        );
1682        // Other poses should remain close to the (correct) input.
1683        for (idx, (refined, original)) in refinement
1684            .refined_poses
1685            .iter()
1686            .zip(poses.iter())
1687            .enumerate()
1688        {
1689            let dt =
1690                (refined.world_to_camera.translation - original.world_to_camera.translation).norm();
1691            assert!(
1692                dt < 1e-3,
1693                "frame {idx} drifted {dt} from a known-correct initialisation"
1694            );
1695        }
1696    }
1697
1698    /// `reconstruct_stereo_vo_with_ba` returns merged multi-view tracks (each
1699    /// landmark observed by every frame it was chained through) and a global BA
1700    /// that does not worsen reprojection. On a noise-free synthetic scene the
1701    /// recovered landmark positions match truth and the tracks span all frames.
1702    #[test]
1703    fn reconstruct_emits_multiview_tracks_and_does_not_worsen_reprojection() {
1704        let camera = kitti_camera();
1705        let baseline = 0.537;
1706        let landmarks = synthetic_landmark_grid();
1707
1708        // Four frames of forward motion (truth).
1709        let poses: Vec<Pose> = (0..4)
1710            .map(|i| Pose {
1711                world_to_camera: SE3::new(
1712                    UnitQuaternion::identity(),
1713                    Vector3::new(0.0, 0.0, -0.8 * i as f64),
1714                ),
1715            })
1716            .collect();
1717
1718        let mut left = Vec::new();
1719        let mut right = Vec::new();
1720        let mut stereo = Vec::new();
1721        for p in &poses {
1722            let (l, r, s) = project_to_pixels(&camera, p, &landmarks, baseline);
1723            left.push(l);
1724            right.push(r);
1725            stereo.push(s);
1726        }
1727
1728        // Identity temporal matches: feature i → feature i in the next frame.
1729        let temporal_matches: Vec<Vec<DescriptorMatch>> = (0..poses.len() - 1)
1730            .map(|f| {
1731                let n = left[f].keypoints.len().min(left[f + 1].keypoints.len());
1732                (0..n)
1733                    .map(|i| DescriptorMatch {
1734                        query_index: i,
1735                        train_index: i,
1736                        distance: 0.0,
1737                        second_best_distance: None,
1738                        ratio: None,
1739                        confidence: Some(1.0),
1740                    })
1741                    .collect()
1742            })
1743            .collect();
1744
1745        let config = StereoVoBaConfig::default();
1746        let recon = reconstruct_stereo_vo_with_ba(
1747            &camera,
1748            baseline,
1749            &poses,
1750            &left,
1751            &right,
1752            &stereo,
1753            &temporal_matches,
1754            &config,
1755        )
1756        .expect("reconstruction should succeed on synthetic scene");
1757
1758        assert!(!recon.landmarks.is_empty(), "expected merged landmarks");
1759        assert_eq!(recon.refined_poses.len(), poses.len());
1760
1761        // The defining property vs the per-frame writer: each landmark carries a
1762        // multi-view track. With identity matches every grid point is seen by all
1763        // 4 frames, so at least one landmark must span > 1 frame, and total
1764        // observations must exceed the landmark count.
1765        let max_track = recon
1766            .landmarks
1767            .iter()
1768            .map(|l| l.observations.len())
1769            .max()
1770            .unwrap();
1771        assert!(
1772            max_track >= 3,
1773            "expected a multi-view track spanning ≥3 frames, got {max_track}"
1774        );
1775        assert!(recon.observation_count > recon.landmarks.len());
1776
1777        // Observations within a track must reference distinct frames in order.
1778        for l in &recon.landmarks {
1779            for w in l.observations.windows(2) {
1780                assert!(w[0].0 < w[1].0, "track frames must be strictly increasing");
1781            }
1782        }
1783
1784        // Global BA must not worsen reprojection on a consistent scene.
1785        assert!(
1786            recon.mean_reproj_after_px <= recon.mean_reproj_before_px + 1e-6,
1787            "BA worsened reprojection: {} -> {}",
1788            recon.mean_reproj_before_px,
1789            recon.mean_reproj_after_px,
1790        );
1791
1792        // Recovered landmark positions should match one of the truth grid points.
1793        for l in &recon.landmarks {
1794            let nearest = landmarks
1795                .iter()
1796                .map(|t| (t - l.position).norm())
1797                .fold(f64::INFINITY, f64::min);
1798            assert!(
1799                nearest < 1e-2,
1800                "reconstructed landmark {:?} not near any truth point (nearest {nearest})",
1801                l.position,
1802            );
1803        }
1804    }
1805
1806    /// `fix_pose_prefix > 1` holds a leading prefix of poses fixed (the
1807    /// fixed-keyframe local-map anchor) while still optimising the trailing
1808    /// poses: the prefix is bit-for-bit unchanged, and a drifted trailing pose is
1809    /// pulled back toward truth by the long-baseline landmarks the fixed prefix
1810    /// anchors.
1811    #[test]
1812    fn fix_pose_prefix_anchors_leading_poses() {
1813        let camera = kitti_camera();
1814        let baseline = 0.537;
1815        let landmarks = synthetic_landmark_grid();
1816
1817        // Five frames of forward motion (truth).
1818        let truth: Vec<Pose> = (0..5)
1819            .map(|i| Pose {
1820                world_to_camera: SE3::new(
1821                    UnitQuaternion::identity(),
1822                    Vector3::new(0.0, 0.0, -0.8 * i as f64),
1823                ),
1824            })
1825            .collect();
1826
1827        // Observations are projected from the TRUE poses.
1828        let mut left = Vec::new();
1829        let mut right = Vec::new();
1830        let mut stereo = Vec::new();
1831        for p in &truth {
1832            let (l, r, s) = project_to_pixels(&camera, p, &landmarks, baseline);
1833            left.push(l);
1834            right.push(r);
1835            stereo.push(s);
1836        }
1837        let temporal_matches: Vec<Vec<DescriptorMatch>> = (0..truth.len() - 1)
1838            .map(|f| {
1839                let n = left[f].keypoints.len().min(left[f + 1].keypoints.len());
1840                (0..n)
1841                    .map(|i| DescriptorMatch {
1842                        query_index: i,
1843                        train_index: i,
1844                        distance: 0.0,
1845                        second_best_distance: None,
1846                        ratio: None,
1847                        confidence: Some(1.0),
1848                    })
1849                    .collect()
1850            })
1851            .collect();
1852
1853        // Initial poses: truth, but the trailing two are drifted.
1854        let mut initial = truth.clone();
1855        for f in [3usize, 4] {
1856            initial[f] = Pose {
1857                world_to_camera: SE3::new(
1858                    UnitQuaternion::identity(),
1859                    truth[f].world_to_camera.translation + Vector3::new(0.06, 0.04, 0.05),
1860                ),
1861            };
1862        }
1863
1864        let config = StereoVoBaConfig {
1865            fix_pose_prefix: 3,
1866            ..StereoVoBaConfig::default()
1867        };
1868        let refinement = refine_stereo_vo_with_ba(
1869            &camera,
1870            baseline,
1871            &initial,
1872            &left,
1873            &right,
1874            &stereo,
1875            &temporal_matches,
1876            &config,
1877        )
1878        .expect("BA should succeed");
1879
1880        // The fixed prefix (poses 0,1,2) is bit-for-bit unchanged.
1881        for (f, initial_pose) in initial.iter().enumerate().take(3) {
1882            let d = (refinement.refined_poses[f].world_to_camera.translation
1883                - initial_pose.world_to_camera.translation)
1884                .norm();
1885            assert!(d < 1e-12, "fixed prefix pose {f} moved by {d}");
1886        }
1887        // The drifted trailing poses are pulled back toward truth.
1888        for f in [3usize, 4] {
1889            let before = (initial[f].world_to_camera.translation
1890                - truth[f].world_to_camera.translation)
1891                .norm();
1892            let after = (refinement.refined_poses[f].world_to_camera.translation
1893                - truth[f].world_to_camera.translation)
1894                .norm();
1895            assert!(
1896                after < before * 0.5,
1897                "trailing pose {f}: expected correction, before {before:.4} after {after:.4}"
1898            );
1899        }
1900    }
1901
1902    /// Inject a small drift on pose 2 and confirm BA corrects it back toward
1903    /// the correct trajectory.
1904    #[test]
1905    fn ba_corrects_injected_translation_drift() {
1906        let camera = kitti_camera();
1907        let baseline = 0.537;
1908        let landmarks = synthetic_landmark_grid();
1909
1910        let correct_poses = vec![
1911            Pose::identity(),
1912            Pose {
1913                world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, -0.8)),
1914            },
1915            Pose {
1916                world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, -1.6)),
1917            },
1918        ];
1919        // Build observations from CORRECT poses (the "true" image content).
1920        let mut left = Vec::new();
1921        let mut right = Vec::new();
1922        let mut stereo = Vec::new();
1923        for p in &correct_poses {
1924            let (l, r, s) = project_to_pixels(&camera, p, &landmarks, baseline);
1925            left.push(l);
1926            right.push(r);
1927            stereo.push(s);
1928        }
1929        let temporal_matches: Vec<Vec<DescriptorMatch>> = (0..correct_poses.len() - 1)
1930            .map(|f| {
1931                let n = left[f].keypoints.len().min(left[f + 1].keypoints.len());
1932                (0..n)
1933                    .map(|i| DescriptorMatch {
1934                        query_index: i,
1935                        train_index: i,
1936                        distance: 0.0,
1937                        second_best_distance: None,
1938                        ratio: None,
1939                        confidence: Some(1.0),
1940                    })
1941                    .collect()
1942            })
1943            .collect();
1944
1945        // Inject 5 cm drift on pose 2's y component (the seq08 failure mode).
1946        let mut drifted = correct_poses.clone();
1947        drifted[2].world_to_camera.translation.y += 0.05;
1948
1949        let config = StereoVoBaConfig::default();
1950        let refinement = refine_stereo_vo_with_ba(
1951            &camera,
1952            baseline,
1953            &drifted,
1954            &left,
1955            &right,
1956            &stereo,
1957            &temporal_matches,
1958            &config,
1959        )
1960        .expect("BA should succeed on drifted synthetic scene");
1961
1962        let initial_err = 0.05f64;
1963        let final_err = (refinement.refined_poses[2].world_to_camera.translation
1964            - correct_poses[2].world_to_camera.translation)
1965            .norm();
1966        assert!(
1967            final_err < initial_err * 0.2,
1968            "BA failed to correct injected drift: initial {initial_err:.4} final {final_err:.4}"
1969        );
1970    }
1971
1972    /// Stereo VO BA refiner accepts an optional `gravity_prior` from
1973    /// `StereoVoBaConfig` and applies it on the constructed bundle. This is the
1974    /// wiring smoke — on a well-conditioned synthetic stereo scene, reprojection
1975    /// alone is enough to correct injected pitch drift, so the test only asserts
1976    /// that the prior is accepted, the refinement still converges, and the
1977    /// recovered rotation is at parity (no worse) with the no-prior baseline.
1978    /// Deeper "gravity prior recovers rotation" coverage lives in
1979    /// `tests/bundle_adjustment.rs::gravity_prior_recovers_pitched_pose`, which
1980    /// uses an under-constrained 6-point mono bundle where the prior is actually
1981    /// load-bearing.
1982    #[test]
1983    fn ba_with_gravity_prior_wires_through_config() {
1984        let camera = kitti_camera();
1985        let baseline = 0.537;
1986        let landmarks = synthetic_landmark_grid();
1987
1988        let correct_poses = vec![
1989            Pose::identity(),
1990            Pose {
1991                world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, -0.8)),
1992            },
1993            Pose {
1994                world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, -1.6)),
1995            },
1996        ];
1997        let mut left = Vec::new();
1998        let mut right = Vec::new();
1999        let mut stereo = Vec::new();
2000        for p in &correct_poses {
2001            let (l, r, s) = project_to_pixels(&camera, p, &landmarks, baseline);
2002            left.push(l);
2003            right.push(r);
2004            stereo.push(s);
2005        }
2006        let temporal_matches: Vec<Vec<DescriptorMatch>> = (0..correct_poses.len() - 1)
2007            .map(|f| {
2008                let n = left[f].keypoints.len().min(left[f + 1].keypoints.len());
2009                (0..n)
2010                    .map(|i| DescriptorMatch {
2011                        query_index: i,
2012                        train_index: i,
2013                        distance: 0.0,
2014                        second_best_distance: None,
2015                        ratio: None,
2016                        confidence: Some(1.0),
2017                    })
2018                    .collect()
2019            })
2020            .collect();
2021
2022        // Inject 0.05 rad pitch on pose 2 (rotation around camera x-axis),
2023        // preserving the truth camera centre.
2024        let pitch = 0.05_f64;
2025        let r2 = UnitQuaternion::from_axis_angle(&Vector3::x_axis(), pitch);
2026        let truth_center_2 = -correct_poses[2].world_to_camera.translation;
2027        let mut drifted = correct_poses;
2028        drifted[2].world_to_camera = SE3::new(r2, -(r2.transform_vector(&truth_center_2)));
2029
2030        // Baseline: BA without gravity prior.
2031        let base_refinement = refine_stereo_vo_with_ba(
2032            &camera,
2033            baseline,
2034            &drifted,
2035            &left,
2036            &right,
2037            &stereo,
2038            &temporal_matches,
2039            &StereoVoBaConfig::default(),
2040        )
2041        .expect("BA should succeed without gravity prior");
2042        let base_rot_err = base_refinement.refined_poses[2]
2043            .world_to_camera
2044            .rotation
2045            .angle_to(&UnitQuaternion::identity());
2046
2047        // With gravity prior: world up = +y (KITTI cameras y-down → gravity
2048        // points down in world, so g_world = (0, 9.81, 0) and the same
2049        // direction is observed in any level camera).
2050        let mut cfg_grav = StereoVoBaConfig::default();
2051        cfg_grav.gravity_prior = Some(GravityPrior {
2052            g_world: Vector3::new(0.0, 9.81, 0.0),
2053            g_camera_observed: Vector3::new(0.0, 9.81, 0.0),
2054            weight: 20.0,
2055        });
2056        let grav_refinement = refine_stereo_vo_with_ba(
2057            &camera,
2058            baseline,
2059            &drifted,
2060            &left,
2061            &right,
2062            &stereo,
2063            &temporal_matches,
2064            &cfg_grav,
2065        )
2066        .expect("BA should succeed with gravity prior");
2067        let grav_rot_err = grav_refinement.refined_poses[2]
2068            .world_to_camera
2069            .rotation
2070            .angle_to(&UnitQuaternion::identity());
2071
2072        // On this well-constrained stereo scene reprojection alone reaches
2073        // ~0 rad rotation residual; the wiring assertion is parity with that
2074        // baseline within a small tolerance plus a hard 0.01 rad ceiling.
2075        let tol = 5.0e-3;
2076        assert!(
2077            grav_rot_err <= base_rot_err + tol,
2078            "gravity prior must not measurably worsen rotation error; \
2079             base={base_rot_err:.5} rad, with_prior={grav_rot_err:.5} rad"
2080        );
2081        assert!(
2082            grav_rot_err < 0.01,
2083            "gravity prior pass must keep pose 2 rotation < 0.01 rad; got {grav_rot_err:.5}"
2084        );
2085    }
2086
2087    /// Stereo VO BA refiner accepts an optional `per_pose_gravity_prior`
2088    /// from `StereoVoBaConfig` and applies it on the constructed bundle.
2089    /// Like the global `gravity_prior` wiring smoke, this asserts the
2090    /// configured prior is wired through and does not measurably worsen
2091    /// the no-prior baseline rotation residual on a well-conditioned
2092    /// stereo scene. Deeper "per-pose prior recovers rotation" coverage
2093    /// lives in `tests/bundle_adjustment.rs::per_pose_gravity_prior_*`.
2094    #[test]
2095    fn ba_with_per_pose_gravity_prior_wires_through_config() {
2096        use crate::{PerPoseGravityObservation, PerPoseGravityPrior};
2097
2098        let camera = kitti_camera();
2099        let baseline = 0.537;
2100        let landmarks = synthetic_landmark_grid();
2101
2102        let correct_poses = vec![
2103            Pose::identity(),
2104            Pose {
2105                world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, -0.8)),
2106            },
2107            Pose {
2108                world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, -1.6)),
2109            },
2110        ];
2111        let mut left = Vec::new();
2112        let mut right = Vec::new();
2113        let mut stereo = Vec::new();
2114        for p in &correct_poses {
2115            let (l, r, s) = project_to_pixels(&camera, p, &landmarks, baseline);
2116            left.push(l);
2117            right.push(r);
2118            stereo.push(s);
2119        }
2120        let temporal_matches: Vec<Vec<DescriptorMatch>> = (0..correct_poses.len() - 1)
2121            .map(|f| {
2122                let n = left[f].keypoints.len().min(left[f + 1].keypoints.len());
2123                (0..n)
2124                    .map(|i| DescriptorMatch {
2125                        query_index: i,
2126                        train_index: i,
2127                        distance: 0.0,
2128                        second_best_distance: None,
2129                        ratio: None,
2130                        confidence: Some(1.0),
2131                    })
2132                    .collect()
2133            })
2134            .collect();
2135
2136        let pitch = 0.05_f64;
2137        let r2 = UnitQuaternion::from_axis_angle(&Vector3::x_axis(), pitch);
2138        let truth_center_2 = -correct_poses[2].world_to_camera.translation;
2139        let mut drifted = correct_poses.clone();
2140        drifted[2].world_to_camera = SE3::new(r2, -(r2.transform_vector(&truth_center_2)));
2141
2142        // Baseline: BA without per-pose gravity prior.
2143        let base_refinement = refine_stereo_vo_with_ba(
2144            &camera,
2145            baseline,
2146            &drifted,
2147            &left,
2148            &right,
2149            &stereo,
2150            &temporal_matches,
2151            &StereoVoBaConfig::default(),
2152        )
2153        .expect("BA should succeed without per-pose gravity prior");
2154        let base_rot_err = base_refinement.refined_poses[2]
2155            .world_to_camera
2156            .rotation
2157            .angle_to(&UnitQuaternion::identity());
2158
2159        // With per-pose gravity prior: every frame observes the level
2160        // direction (0, 9.81, 0) in camera coordinates — i.e. the
2161        // accelerometer-derived observation for a level camera.
2162        let mut cfg_grav = StereoVoBaConfig::default();
2163        let mut prior = PerPoseGravityPrior::new(Vector3::new(0.0, 9.81, 0.0), 20.0);
2164        for i in 0..correct_poses.len() {
2165            prior.push(PerPoseGravityObservation {
2166                keyframe_id: i as u64,
2167                g_camera_observed: Vector3::new(0.0, 9.81, 0.0),
2168                weight: 1.0,
2169            });
2170        }
2171        cfg_grav.per_pose_gravity_prior = Some(prior);
2172        let grav_refinement = refine_stereo_vo_with_ba(
2173            &camera,
2174            baseline,
2175            &drifted,
2176            &left,
2177            &right,
2178            &stereo,
2179            &temporal_matches,
2180            &cfg_grav,
2181        )
2182        .expect("BA should succeed with per-pose gravity prior");
2183        let grav_rot_err = grav_refinement.refined_poses[2]
2184            .world_to_camera
2185            .rotation
2186            .angle_to(&UnitQuaternion::identity());
2187
2188        let tol = 5.0e-3;
2189        assert!(
2190            grav_rot_err <= base_rot_err + tol,
2191            "per-pose gravity prior must not measurably worsen rotation error; \
2192             base={base_rot_err:.5} rad, with_prior={grav_rot_err:.5} rad"
2193        );
2194        assert!(
2195            grav_rot_err < 0.01,
2196            "per-pose gravity prior pass must keep pose 2 rotation < 0.01 rad; got {grav_rot_err:.5}"
2197        );
2198    }
2199
2200    /// `slice_per_pose_gravity_prior_for_window` keeps observations
2201    /// whose keyframe falls inside `[start, end)` and remaps their id
2202    /// to the local window's `0..(end-start)` range. Observations
2203    /// outside the window are dropped. This is the contract the
2204    /// sliding-window BA loop depends on.
2205    #[test]
2206    fn slice_per_pose_gravity_prior_remaps_local_window_ids() {
2207        use crate::{PerPoseGravityObservation, PerPoseGravityPrior};
2208        let mut prior = PerPoseGravityPrior::new(Vector3::new(0.0, 9.81, 0.0), 1.0);
2209        for id in 0..10u64 {
2210            prior.push(PerPoseGravityObservation {
2211                keyframe_id: id,
2212                g_camera_observed: Vector3::new(0.0, 9.81, id as f64 * 0.1),
2213                weight: 1.0,
2214            });
2215        }
2216        let sliced = slice_per_pose_gravity_prior_for_window(&prior, 3, 7);
2217        assert_eq!(sliced.g_world, prior.g_world);
2218        assert_eq!(sliced.weight, prior.weight);
2219        assert_eq!(sliced.observations.len(), 4);
2220        // Local ids should be 0..4 and the per-keyframe observations
2221        // should carry the original z-coordinate (3*0.1, 4*0.1, 5*0.1,
2222        // 6*0.1) so we can confirm the remap kept the right entries.
2223        for (local_id, expected_global) in (0..4u64).zip(3..7u64) {
2224            assert_eq!(sliced.observations[local_id as usize].keyframe_id, local_id);
2225            assert!(
2226                (sliced.observations[local_id as usize].g_camera_observed.z
2227                    - expected_global as f64 * 0.1)
2228                    .abs()
2229                    < 1.0e-12,
2230                "expected local id {local_id} to carry global id {expected_global}'s observation"
2231            );
2232        }
2233    }
2234
2235    /// Drive `refine_stereo_vo_with_ba` with a `StereoVoBaImuInput` that
2236    /// matches the visual truth motion and a deliberately wrong velocity
2237    /// initialisation (which the refiner seeds from the inter-keyframe
2238    /// pose-centre delta — so the seed comes out correct here). The
2239    /// solver must (a) populate `imu_refinement`, (b) recover refined
2240    /// velocities consistent with the truth `(2 m, 0, 0)` motion over
2241    /// 1 second windows, and (c) leave the poses essentially unchanged
2242    /// since the visual + IMU residuals are already at the joint
2243    /// minimum.
2244    #[test]
2245    fn ba_with_imu_input_wires_through_config() {
2246        let camera = kitti_camera();
2247        let baseline = 0.537;
2248        let landmarks = synthetic_landmark_grid();
2249
2250        // 3 frames with constant +x motion: world centres at 0 / 2 / 4 m,
2251        // each 1 s apart. Camera-frame velocity matches body-frame
2252        // velocity because the rotation is identity throughout.
2253        let centers = [0.0_f64, 2.0, 4.0];
2254        let poses: Vec<Pose> = centers
2255            .iter()
2256            .map(|&x| Pose {
2257                world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(-x, 0.0, 0.0)),
2258            })
2259            .collect();
2260
2261        let mut left = Vec::new();
2262        let mut right = Vec::new();
2263        let mut stereo = Vec::new();
2264        for p in &poses {
2265            let (l, r, s) = project_to_pixels(&camera, p, &landmarks, baseline);
2266            left.push(l);
2267            right.push(r);
2268            stereo.push(s);
2269        }
2270        let temporal_matches: Vec<Vec<DescriptorMatch>> = (0..poses.len() - 1)
2271            .map(|f| {
2272                let n = left[f].keypoints.len().min(left[f + 1].keypoints.len());
2273                (0..n)
2274                    .map(|i| DescriptorMatch {
2275                        query_index: i,
2276                        train_index: i,
2277                        distance: 0.0,
2278                        second_best_distance: None,
2279                        ratio: None,
2280                        confidence: Some(1.0),
2281                    })
2282                    .collect()
2283            })
2284            .collect();
2285
2286        // Constant +x acceleration of 2 m/s² for 1 s → world centres at
2287        // 0, 1, 2 m. But our truth scene has centres at 0, 2, 4 m, so
2288        // pick constant velocity 2 m/s instead (zero accel). With zero
2289        // accel, gravity in the IMU equation cancels only if we set
2290        // `gravity_world = 0` — keep the test gravity-free for clarity.
2291        let dt_step = 0.05_f64;
2292        let steps_per_window = 20usize; // 1 s window
2293        let zero = Vector3::<f64>::zeros();
2294        let window: Vec<StereoVoBaImuSample> = (0..steps_per_window)
2295            .map(|_| StereoVoBaImuSample {
2296                dt: dt_step,
2297                gyro: zero,
2298                accel: zero, // zero accel in body frame; gravity = 0 below
2299            })
2300            .collect();
2301        let imu_input = StereoVoBaImuInput::new(
2302            vec![window.clone(), window],
2303            Vector3::zeros(),
2304            1.0,
2305            1.0,
2306            1.0,
2307        );
2308
2309        let mut cfg = StereoVoBaConfig::default();
2310        cfg.imu_input = Some(imu_input);
2311        let refinement = refine_stereo_vo_with_ba(
2312            &camera,
2313            baseline,
2314            &poses,
2315            &left,
2316            &right,
2317            &stereo,
2318            &temporal_matches,
2319            &cfg,
2320        )
2321        .expect("BA with IMU input should succeed");
2322
2323        let imu = refinement
2324            .imu_refinement
2325            .as_ref()
2326            .expect("imu_refinement should be populated when imu_input is set");
2327        assert_eq!(imu.refined_velocities.len(), poses.len());
2328        assert_eq!(imu.refined_bias_gyro.len(), poses.len());
2329        assert_eq!(imu.refined_bias_acc.len(), poses.len());
2330
2331        // All three keyframes participate in at least one IMU window, so
2332        // each velocity slot should be close to the truth (+2, 0, 0).
2333        let truth_v = Vector3::new(2.0, 0.0, 0.0);
2334        for (i, v) in imu.refined_velocities.iter().enumerate() {
2335            let err = (v - truth_v).norm();
2336            assert!(
2337                err < 0.05,
2338                "keyframe {i} velocity {v:?} diverged from truth {truth_v:?}; err={err:.4}"
2339            );
2340        }
2341
2342        // Poses should still match the input (the residuals are zero at
2343        // truth and the seed velocities come from the pose-centre delta
2344        // so the IMU factor contributes a near-zero residual too).
2345        for (i, (refined, original)) in refinement
2346            .refined_poses
2347            .iter()
2348            .zip(poses.iter())
2349            .enumerate()
2350        {
2351            let dt =
2352                (refined.world_to_camera.translation - original.world_to_camera.translation).norm();
2353            assert!(
2354                dt < 5.0e-3,
2355                "frame {i} drifted {dt} from truth under joint visual+IMU BA"
2356            );
2357        }
2358    }
2359
2360    /// Gyro-bias observability scenario. The camera yaws around its
2361    /// y-axis at a known rate while staying at the world origin (rotation
2362    /// only). IMU samples carry the true body-frame angular velocity
2363    /// plus a non-zero true gyro bias; we feed BA the windows with
2364    /// `bias_gyro_init = 0` and `fix_first_bias = false`. The visual
2365    /// factor pins each frame's rotation, so the IMU rotation residual
2366    /// is paid by the bias slot — refined gyro bias must converge to the
2367    /// truth on every IMU-active keyframe. Accel bias stays at zero (no
2368    /// gravity, no linear motion) — this scenario isolates gyro bias
2369    /// observability.
2370    #[test]
2371    fn ba_with_imu_input_recovers_gyro_bias_under_rotation() {
2372        let camera = kitti_camera();
2373        let baseline = 0.537;
2374        let landmarks = synthetic_landmark_grid();
2375
2376        // 4 keyframes; camera centre stays at origin, yaw advances by
2377        // omega_yaw rad each window. Landmarks at depth 10..20 m stay in
2378        // FOV for the full 0..0.18 rad sweep.
2379        let omega_yaw = 0.06_f64;
2380        let dt_window = 1.0_f64;
2381        let n_frames = 4usize;
2382        let poses: Vec<Pose> = (0..n_frames)
2383            .map(|i| {
2384                let yaw = omega_yaw * dt_window * i as f64;
2385                let r = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), yaw);
2386                // Camera centre at origin → world_to_camera translation = 0.
2387                Pose {
2388                    world_to_camera: SE3::new(r, Vector3::zeros()),
2389                }
2390            })
2391            .collect();
2392
2393        let mut left = Vec::new();
2394        let mut right = Vec::new();
2395        let mut stereo = Vec::new();
2396        for p in &poses {
2397            let (l, r, s) = project_to_pixels(&camera, p, &landmarks, baseline);
2398            left.push(l);
2399            right.push(r);
2400            stereo.push(s);
2401        }
2402        let temporal_matches: Vec<Vec<DescriptorMatch>> = (0..poses.len() - 1)
2403            .map(|f| {
2404                let n = left[f].keypoints.len().min(left[f + 1].keypoints.len());
2405                (0..n)
2406                    .map(|i| DescriptorMatch {
2407                        query_index: i,
2408                        train_index: i,
2409                        distance: 0.0,
2410                        second_best_distance: None,
2411                        ratio: None,
2412                        confidence: Some(1.0),
2413                    })
2414                    .collect()
2415            })
2416            .collect();
2417
2418        // Body-frame angular velocity sign: with
2419        // `world_to_camera = exp(+yaw_i ey)` the body (camera) frame is
2420        // rotating around its own y axis at rate `−omega_yaw` (so that
2421        // `R_i^T R_j = exp((yaw_i − yaw_j) ey) = exp(−omega_yaw·Δt ey)`
2422        // matches what pre-integration with `gyro = −omega_yaw ey + truth_bias`
2423        // produces). True bias offsets the +y component by `true_bias_y`;
2424        // with `bias_gyro_init = 0` the pre-integrated ΔR is off by
2425        // `−true_bias_y · dt_window` rad — the bias slot must absorb that.
2426        let true_bias_y = 0.015_f64;
2427        let true_bias = Vector3::new(0.0, true_bias_y, 0.0);
2428        let dt_step = 0.05_f64;
2429        let steps_per_window = (dt_window / dt_step).round() as usize; // 20
2430        let imu_gyro_sample = Vector3::new(0.0, -omega_yaw + true_bias_y, 0.0);
2431        let window: Vec<StereoVoBaImuSample> = (0..steps_per_window)
2432            .map(|_| StereoVoBaImuSample {
2433                dt: dt_step,
2434                gyro: imu_gyro_sample,
2435                accel: Vector3::zeros(),
2436            })
2437            .collect();
2438        let windows = vec![window; n_frames - 1];
2439
2440        let mut imu_input = StereoVoBaImuInput::new(
2441            windows,
2442            Vector3::zeros(),
2443            1.0,  // weight_position
2444            1.0,  // weight_velocity
2445            50.0, // weight_rotation — strong so rotation residual drives the bias
2446        );
2447        imu_input.fix_first_bias = false; // bias slot 0 is free to move
2448        imu_input.fix_first_velocity = true; // anchor velocity gauge at 0
2449        imu_input.bias_random_walk_weight = Some(10.0); // tie bias slots together
2450
2451        let mut cfg = StereoVoBaConfig::default();
2452        cfg.imu_input = Some(imu_input);
2453        let refinement = refine_stereo_vo_with_ba(
2454            &camera,
2455            baseline,
2456            &poses,
2457            &left,
2458            &right,
2459            &stereo,
2460            &temporal_matches,
2461            &cfg,
2462        )
2463        .expect("BA with IMU input should succeed");
2464
2465        let imu = refinement
2466            .imu_refinement
2467            .as_ref()
2468            .expect("imu_refinement populated when imu_input is set");
2469        assert_eq!(imu.refined_bias_gyro.len(), poses.len());
2470        assert_eq!(imu.refined_bias_acc.len(), poses.len());
2471
2472        // Every keyframe is IMU-active (4 keyframes, 3 chained windows),
2473        // so all bias slots should land near truth. Tolerance accounts
2474        // for the first-order linearisation of the bias correction
2475        // (true bias ~0.015 from init=0).
2476        let tol_gyro = 5.0e-3;
2477        for (i, b) in imu.refined_bias_gyro.iter().enumerate() {
2478            let err = (b - true_bias).norm();
2479            assert!(
2480                err < tol_gyro,
2481                "keyframe {i} gyro bias {b:?} diverged from truth {true_bias:?}; \
2482                 err={err:.5} > tol={tol_gyro}"
2483            );
2484        }
2485
2486        // Accel bias should stay close to zero: with gravity = 0 and
2487        // zero accel samples, no signal drives the accel-bias slots away
2488        // from the init. The random-walk tie keeps them mutually close.
2489        let tol_acc = 5.0e-3;
2490        for (i, b) in imu.refined_bias_acc.iter().enumerate() {
2491            assert!(
2492                b.norm() < tol_acc,
2493                "keyframe {i} accel bias {b:?} drifted from zero under no-gravity / no-accel scene; \
2494                 norm={:.5} > tol={tol_acc}",
2495                b.norm()
2496            );
2497        }
2498
2499        // Sanity: poses should still match the input rotation closely.
2500        for (i, (refined, original)) in refinement
2501            .refined_poses
2502            .iter()
2503            .zip(poses.iter())
2504            .enumerate()
2505        {
2506            let r_err = refined
2507                .world_to_camera
2508                .rotation
2509                .angle_to(&original.world_to_camera.rotation);
2510            assert!(
2511                r_err < 2.0e-3,
2512                "frame {i} rotation drifted {r_err:.5} rad under joint visual+IMU BA"
2513            );
2514        }
2515    }
2516
2517    #[test]
2518    fn imu_samples_txt_round_trips_through_pre_integration() {
2519        let text = "\
2520# dt gx gy gz ax ay az
25210.01 0.0 0.0 0.0 2.0 0.0 0.0
2522
25230.01 0.0 0.0 0.0 2.0 0.0 0.0
25240.01 0.0 0.0 0.0 2.0 0.0 0.0
2525";
2526        let samples = parse_stereo_vo_imu_samples_txt(text).expect("parse");
2527        assert_eq!(samples.len(), 3);
2528        assert!((samples[0].dt - 0.01).abs() < 1e-12);
2529        assert_eq!(samples[1].accel, Vector3::new(2.0, 0.0, 0.0));
2530        assert_eq!(samples[2].gyro, Vector3::zeros());
2531    }
2532
2533    #[test]
2534    fn imu_samples_txt_rejects_bad_lines() {
2535        // Wrong column count.
2536        let err = parse_stereo_vo_imu_samples_txt("0.01 0.0 0.0 0.0 2.0 0.0\n")
2537            .expect_err("should fail on 6 columns");
2538        assert!(err.contains("7 numbers"));
2539        // Negative dt.
2540        let err = parse_stereo_vo_imu_samples_txt("-0.01 0 0 0 0 0 0\n")
2541            .expect_err("should fail on negative dt");
2542        assert!(err.contains("positive"));
2543        // Garbage token.
2544        let err = parse_stereo_vo_imu_samples_txt("foo 0 0 0 0 0 0\n")
2545            .expect_err("should fail on non-numeric");
2546        assert!(err.contains("cannot parse"));
2547    }
2548
2549    /// `imu_input.windows.len()` mismatch must produce a structured
2550    /// error rather than a panic. Same for `window_size` + IMU.
2551    #[test]
2552    fn ba_with_imu_input_validates_window_count_and_sliding_window() {
2553        let camera = kitti_camera();
2554        let baseline = 0.537;
2555        let landmarks = synthetic_landmark_grid();
2556        let poses = vec![
2557            Pose::identity(),
2558            Pose {
2559                world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, -1.0)),
2560            },
2561            Pose {
2562                world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, -2.0)),
2563            },
2564        ];
2565        let mut left = Vec::new();
2566        let mut right = Vec::new();
2567        let mut stereo = Vec::new();
2568        for p in &poses {
2569            let (l, r, s) = project_to_pixels(&camera, p, &landmarks, baseline);
2570            left.push(l);
2571            right.push(r);
2572            stereo.push(s);
2573        }
2574        let temporal_matches: Vec<Vec<DescriptorMatch>> = (0..poses.len() - 1)
2575            .map(|f| {
2576                let n = left[f].keypoints.len().min(left[f + 1].keypoints.len());
2577                (0..n)
2578                    .map(|i| DescriptorMatch {
2579                        query_index: i,
2580                        train_index: i,
2581                        distance: 0.0,
2582                        second_best_distance: None,
2583                        ratio: None,
2584                        confidence: Some(1.0),
2585                    })
2586                    .collect()
2587            })
2588            .collect();
2589
2590        // Wrong window count (1 instead of 2).
2591        let mut cfg = StereoVoBaConfig::default();
2592        cfg.imu_input = Some(StereoVoBaImuInput::new(
2593            vec![vec![]],
2594            Vector3::zeros(),
2595            1.0,
2596            1.0,
2597            1.0,
2598        ));
2599        let err = refine_stereo_vo_with_ba(
2600            &camera,
2601            baseline,
2602            &poses,
2603            &left,
2604            &right,
2605            &stereo,
2606            &temporal_matches,
2607            &cfg,
2608        )
2609        .expect_err("should fail with InvalidImuInput");
2610        assert!(matches!(err, StereoVoBaError::InvalidImuInput { .. }));
2611
2612        // Right window count but `window_size` is also set.
2613        cfg.imu_input = Some(StereoVoBaImuInput::new(
2614            vec![vec![], vec![]],
2615            Vector3::zeros(),
2616            1.0,
2617            1.0,
2618            1.0,
2619        ));
2620        cfg.window_size = Some(2);
2621        let err = refine_stereo_vo_with_ba(
2622            &camera,
2623            baseline,
2624            &poses,
2625            &left,
2626            &right,
2627            &stereo,
2628            &temporal_matches,
2629            &cfg,
2630        )
2631        .expect_err("should fail with InvalidImuInput (sliding window)");
2632        assert!(matches!(err, StereoVoBaError::InvalidImuInput { .. }));
2633    }
2634
2635    /// Slicing a globally-timestamped IMU stream should land each sample in
2636    /// the window covering its timestamp and emit `dt` gaps anchored at the
2637    /// preceding keyframe. A trailing fragment is required when the last
2638    /// IMU sample stops short of the next keyframe.
2639    #[test]
2640    fn slice_imu_samples_buckets_by_keyframe_intervals() {
2641        let imu_t = vec![
2642            50_000_000i128, // 0.05 s — falls in window 0 (kf0..kf1).
2643            150_000_000,    // 0.15 s — also in window 0.
2644            350_000_000,    // 0.35 s — in window 1 (kf1..kf2).
2645            900_000_000,    // 0.9 s  — in window 2 (kf2..kf3); trailing fragment expected.
2646        ];
2647        let gyro = vec![
2648            Vector3::new(0.1, 0.0, 0.0),
2649            Vector3::new(0.2, 0.0, 0.0),
2650            Vector3::new(0.3, 0.0, 0.0),
2651            Vector3::new(0.4, 0.0, 0.0),
2652        ];
2653        let accel = vec![
2654            Vector3::new(0.0, 0.0, 9.81),
2655            Vector3::new(0.0, 0.0, 9.82),
2656            Vector3::new(0.0, 0.0, 9.83),
2657            Vector3::new(0.0, 0.0, 9.84),
2658        ];
2659        let kf_t = vec![0i128, 200_000_000, 400_000_000, 1_000_000_000];
2660
2661        let windows = slice_imu_samples_for_keyframes(&imu_t, &gyro, &accel, &kf_t).unwrap();
2662        assert_eq!(windows.len(), 3);
2663
2664        // Window 0: samples at 0.05s + 0.15s plus a 0.05s ZOH tail closing
2665        // the interval at 0.20s (3 entries, total dt = 0.20s).
2666        assert_eq!(windows[0].len(), 3);
2667        assert!((windows[0][0].dt - 0.05).abs() < 1e-9);
2668        assert!((windows[0][1].dt - 0.10).abs() < 1e-9);
2669        assert_eq!(windows[0][1].gyro, Vector3::new(0.2, 0.0, 0.0));
2670        assert!((windows[0][2].dt - 0.05).abs() < 1e-9);
2671        assert_eq!(windows[0][2].gyro, Vector3::new(0.2, 0.0, 0.0));
2672        let total_w0: f64 = windows[0].iter().map(|s| s.dt).sum();
2673        assert!((total_w0 - 0.20).abs() < 1e-9);
2674
2675        // Window 1: sample at 0.35s (dt=0.15) plus a 0.05s tail to 0.40s.
2676        assert_eq!(windows[1].len(), 2);
2677        assert!((windows[1][0].dt - 0.15).abs() < 1e-9);
2678        assert_eq!(windows[1][0].accel, Vector3::new(0.0, 0.0, 9.83));
2679        assert!((windows[1][1].dt - 0.05).abs() < 1e-9);
2680
2681        // Window 2: sample at 0.9s (dt=0.5) plus trailing ZOH fragment to 1.0s (dt=0.1).
2682        assert_eq!(windows[2].len(), 2);
2683        assert!((windows[2][0].dt - 0.5).abs() < 1e-9);
2684        assert_eq!(windows[2][0].gyro, Vector3::new(0.4, 0.0, 0.0));
2685        assert!((windows[2][1].dt - 0.1).abs() < 1e-9);
2686        // Tail step holds the last sample's gyro/accel.
2687        assert_eq!(windows[2][1].gyro, Vector3::new(0.4, 0.0, 0.0));
2688        assert_eq!(windows[2][1].accel, Vector3::new(0.0, 0.0, 9.84));
2689
2690        // Total integrated time across all windows matches the keyframe span.
2691        let total_dt: f64 = windows.iter().flat_map(|w| w.iter()).map(|s| s.dt).sum();
2692        assert!((total_dt - 1.0).abs() < 1e-9);
2693    }
2694
2695    /// A keyframe interval that the IMU stream never covers should produce
2696    /// an empty window (so [`refine_stereo_vo_with_ba`] silently skips the
2697    /// IMU factor for that segment).
2698    #[test]
2699    fn slice_imu_samples_emits_empty_window_when_no_coverage() {
2700        let imu_t = vec![10_000_000i128, 20_000_000];
2701        let gyro = vec![Vector3::zeros(), Vector3::zeros()];
2702        let accel = vec![Vector3::zeros(), Vector3::zeros()];
2703        let kf_t = vec![0i128, 100_000_000, 200_000_000];
2704
2705        let windows = slice_imu_samples_for_keyframes(&imu_t, &gyro, &accel, &kf_t).unwrap();
2706        assert_eq!(windows.len(), 2);
2707        // Window 0: 2 samples + 1 ZOH tail filling the remaining gap to 0.1s.
2708        assert_eq!(windows[0].len(), 3);
2709        // Window 1 has no IMU samples and no `last` to extend, so it stays empty.
2710        assert!(windows[1].is_empty(), "window 1 has no IMU coverage");
2711    }
2712
2713    #[test]
2714    fn slice_imu_samples_validates_lengths_and_monotonicity() {
2715        let gyro = vec![Vector3::zeros(); 2];
2716        let accel = vec![Vector3::zeros(); 2];
2717
2718        // Length mismatch.
2719        let err = slice_imu_samples_for_keyframes(&[0i128, 1, 2], &gyro, &accel, &[0i128, 1])
2720            .expect_err("length mismatch should fail");
2721        assert!(err.contains("length mismatch"));
2722
2723        // Fewer than two keyframes.
2724        let err = slice_imu_samples_for_keyframes(&[0i128, 1], &gyro, &accel, &[0i128])
2725            .expect_err("single keyframe should fail");
2726        assert!(err.contains("at least 2 keyframe"));
2727
2728        // Non-monotonic keyframes.
2729        let err = slice_imu_samples_for_keyframes(&[0i128, 1], &gyro, &accel, &[1i128, 0])
2730            .expect_err("non-monotonic should fail");
2731        assert!(err.contains("keyframe timestamps"));
2732    }
2733}