Skip to main content

visloc_slam/
vi_initializer.rs

1//! Visual-inertial bootstrap (stationary-window initialiser).
2//!
3//! Real VIO front-ends (ORB-SLAM3, VINS-Mono, OKVIS, Kimera-VIO) all
4//! gate the visual-inertial state on an "initialisation" stage that
5//! turns the raw IMU stream into a starting `(R_w←b, v_w, b_g, b_a)`
6//! tuple before the joint estimator is allowed to consume image
7//! constraints. Without this step the integrator either has to seed
8//! every state from ground truth (cheating) or accumulate hundreds of
9//! metres of dead-reckoning drift before the first keyframe — see the
10//! IMU-only ATE baseline in `docs/progress.md` for the latter case.
11//!
12//! This module ships the simplest defensible flavour: detect a window
13//! where the gyro and accel signals are statistically consistent with
14//! a body at rest, then read out
15//!
16//! * the gyro bias as the gyro signal mean (`b_g = ω̄`),
17//! * the body-to-world rotation as the shortest rotation that lifts
18//!   the mean specific-force direction into the world "up" direction
19//!   `-g_w / ‖g_w‖` (yaw is left at zero; nothing in a stationary
20//!   sample stream pins yaw against the world frame),
21//! * an initial world-frame velocity that is by construction zero,
22//! * an accel bias that absorbs any magnitude mismatch between the
23//!   measured mean specific-force magnitude and `‖g_w‖`.
24//!
25//! Stationary detection guards the read-out with three thresholds:
26//! per-axis gyro standard deviation, per-axis accel standard
27//! deviation, and the magnitude error between the mean specific-force
28//! and `‖g_w‖`. The window must additionally span at least
29//! `min_stationary_window_seconds` and contain at least `min_samples`
30//! samples. The thresholds are conservative defaults; calibration-
31//! driven datasets such as EuRoC pass them comfortably during the
32//! initial holding period before take-off.
33//!
34//! The recovered bootstrap is returned as a
35//! [`VisualInertialInitializationResult`] and consumed by callers
36//! (typically followed by seeding
37//! `OnlineSlamImuConfig::bias_gyro_linearisation` /
38//! `OnlineSlamImuConfig::bias_acc_linearisation` and the
39//! first-keyframe pose). The initialiser itself is appearance-free
40//! and does not touch the SLAM critical path; it lives in
41//! `pipelines/slam` only because it shares the IMU sample
42//! conventions with [`crate::ImuPreintegrator`].
43
44use nalgebra::{UnitQuaternion, Vector3};
45
46/// Configuration knobs for [`VisualInertialInitializer`]. The defaults
47/// match the EuRoC stationary holding period (gravity z-up, ~0.5 s of
48/// quiet samples, conservative noise thresholds).
49#[derive(Debug, Clone, PartialEq)]
50pub struct VisualInertialInitializerConfig {
51    /// Gravity in the world frame. EuRoC convention is z-up,
52    /// `(0, 0, -9.81)`; KITTI convention is y-down, `(0, 9.81, 0)`.
53    pub gravity_world: Vector3<f64>,
54    /// Minimum duration (seconds) of the stationary window. Below
55    /// this threshold the initialiser refuses to commit even when the
56    /// noise statistics look clean — too short a window leaves the
57    /// gyro / accel means dominated by per-sample noise.
58    pub min_stationary_window_seconds: f64,
59    /// Maximum acceptable per-axis standard deviation of the gyro
60    /// signal in the window (rad / s). Above this threshold the
61    /// window is rejected as non-stationary.
62    pub max_gyro_std: f64,
63    /// Maximum norm of the time-weighted mean angular rate (rad/s). A low
64    /// standard deviation alone cannot distinguish a stationary sensor from
65    /// one rotating at nearly constant speed; without this gate that motion is
66    /// silently absorbed as gyro bias.
67    pub max_mean_gyro_magnitude: f64,
68    /// Maximum acceptable per-axis standard deviation of the accel
69    /// signal in the window (m / s²).
70    pub max_accel_std: f64,
71    /// Maximum acceptable deviation of the mean accel magnitude from
72    /// `‖gravity_world‖` (m / s²). Helps reject sensor-saturation
73    /// windows that look stationary by std-dev alone but report a
74    /// drastically wrong magnitude (e.g. mis-scaled raw counts).
75    pub max_accel_magnitude_error: f64,
76    /// Minimum number of IMU samples in the window. A duration check
77    /// alone is too loose under sparse / irregular sample rates.
78    pub min_samples: usize,
79    /// Width of the **sliding detector window** (seconds). When the
80    /// buffer exceeds this duration, only the most recent
81    /// `detector_window_seconds` of samples (the trailing slice) are
82    /// considered for every stationary-window predicate and statistic.
83    ///
84    /// `f64::INFINITY` (the default) keeps the historical "all-buffer"
85    /// behaviour, where statistics are evaluated over every buffered
86    /// sample — appropriate for the simplest standalone case where a
87    /// caller buffers a single clean stationary segment up front. A
88    /// finite value is the pipeline-integration setup: it lets the
89    /// detector ride out a leading non-stationary segment (e.g. the
90    /// pipeline started during motion and the body settled later) by
91    /// re-evaluating on only the trailing window, so an early-motion
92    /// buffer no longer poisons the detector forever.
93    pub detector_window_seconds: f64,
94}
95
96impl Default for VisualInertialInitializerConfig {
97    fn default() -> Self {
98        Self {
99            gravity_world: Vector3::new(0.0, 0.0, -9.81),
100            min_stationary_window_seconds: 0.5,
101            max_gyro_std: 0.05,
102            max_mean_gyro_magnitude: 0.05,
103            max_accel_std: 0.5,
104            max_accel_magnitude_error: 0.5,
105            min_samples: 50,
106            // `INFINITY` preserves the historical "evaluate on the whole
107            // buffer" behaviour; existing callers see no numerical
108            // change after this field lands.
109            detector_window_seconds: f64::INFINITY,
110        }
111    }
112}
113
114#[derive(Debug, Clone, PartialEq)]
115struct ImuSampleRecord {
116    gyro: Vector3<f64>,
117    accel: Vector3<f64>,
118    dt: f64,
119}
120
121/// Stateful accumulator that ingests IMU samples one at a time and
122/// reports the recovered bootstrap as soon as the buffer satisfies
123/// every stationary-window predicate.
124#[derive(Debug, Clone, PartialEq)]
125pub struct VisualInertialInitializer {
126    config: VisualInertialInitializerConfig,
127    samples: Vec<ImuSampleRecord>,
128}
129
130/// Outcome of a successful stationary-window initialisation. All
131/// fields are in SI units; angles are encoded as a unit quaternion.
132#[derive(Debug, Clone, PartialEq)]
133pub struct VisualInertialInitializationResult {
134    /// World-frame gravity, echoed from the config so downstream
135    /// callers (e.g. `OnlineSlamImuConfig`) can wire it through
136    /// without re-importing the config struct.
137    pub gravity_world: Vector3<f64>,
138    /// Body-to-world rotation recovered from the mean specific-force
139    /// direction. Yaw is set to zero (gravity does not pin yaw).
140    pub initial_rotation_body_to_world: UnitQuaternion<f64>,
141    /// Initial world-frame velocity. Always exactly zero — the
142    /// initialiser only fires when the window is stationary.
143    pub initial_velocity_world: Vector3<f64>,
144    /// Recovered gyro bias = mean(gyro readings) in body frame.
145    pub bias_gyro: Vector3<f64>,
146    /// Recovered accel bias. When the measured specific-force
147    /// magnitude exactly matches `‖gravity_world‖` this is zero;
148    /// otherwise it captures the magnitude residual along the
149    /// measured gravity direction.
150    pub bias_acc: Vector3<f64>,
151    /// Number of IMU samples consumed by the recovery.
152    pub samples_consumed: usize,
153    /// Duration of the stationary window (seconds).
154    pub duration_seconds: f64,
155    /// Per-axis gyro standard deviation observed in the window
156    /// (rad / s). Surface for diagnostics / logging.
157    pub gyro_std: Vector3<f64>,
158    /// Per-axis accel standard deviation observed in the window
159    /// (m / s²).
160    pub accel_std: Vector3<f64>,
161    /// Magnitude of the mean specific-force measurement (m / s²).
162    pub mean_accel_magnitude: f64,
163}
164
165impl VisualInertialInitializationResult {
166    /// Angle (degrees) between the body-frame "up" direction implied
167    /// by the recovered rotation and the same direction implied by a
168    /// caller-supplied ground-truth body→world rotation. This is the
169    /// **yaw-gauge-aware** rotation residual: gravity-only stationary
170    /// initialisation fundamentally cannot observe yaw, so the full
171    /// quaternion residual `rotation_to(gt).angle()` unfairly penalises
172    /// a yaw mismatch that the initialiser had no signal to fix. This
173    /// metric isolates the roll / pitch component (the only part the
174    /// gravity-only bootstrap can actually recover) by projecting the
175    /// world "up" direction into body frame under both rotations and
176    /// reporting the angle between the resulting body-frame vectors.
177    ///
178    /// Reads `gravity_world` from the result, so callers do not need
179    /// to thread the gravity vector through separately. Returns `0.0`
180    /// if `gravity_world` is the zero vector (degenerate config).
181    pub fn gravity_alignment_residual_deg(
182        &self,
183        ground_truth_rotation_body_to_world: &UnitQuaternion<f64>,
184    ) -> f64 {
185        let g_norm = self.gravity_world.norm();
186        if !g_norm.is_finite() || g_norm <= f64::EPSILON {
187            return 0.0;
188        }
189        let world_up = -self.gravity_world / g_norm;
190        let recovered_body_up = self.initial_rotation_body_to_world.inverse() * world_up;
191        let gt_body_up = ground_truth_rotation_body_to_world.inverse() * world_up;
192        recovered_body_up
193            .dot(&gt_body_up)
194            .clamp(-1.0, 1.0)
195            .acos()
196            .to_degrees()
197    }
198}
199
200/// Diagnostic reason a stationary-window check failed.
201#[derive(Debug, Clone, PartialEq)]
202pub enum StationaryRejectionReason {
203    InsufficientSamples {
204        have: usize,
205        need: usize,
206    },
207    InsufficientDuration {
208        have: f64,
209        need: f64,
210    },
211    GyroNoiseTooHigh {
212        observed: Vector3<f64>,
213        limit: f64,
214    },
215    MeanGyroMagnitudeTooHigh {
216        observed: f64,
217        limit: f64,
218    },
219    AccelNoiseTooHigh {
220        observed: Vector3<f64>,
221        limit: f64,
222    },
223    AccelMagnitudeMismatch {
224        observed: f64,
225        expected: f64,
226        tolerance: f64,
227    },
228}
229
230impl VisualInertialInitializer {
231    /// Create a fresh initialiser with the given configuration. The
232    /// returned instance owns no samples; feed it the IMU stream via
233    /// [`Self::push_sample`] until [`Self::try_initialize`] reports
234    /// success.
235    pub const fn new(config: VisualInertialInitializerConfig) -> Self {
236        Self {
237            config,
238            samples: Vec::new(),
239        }
240    }
241
242    /// Append one body-frame IMU sample to the accumulator. Non-
243    /// positive `dt` is silently dropped to keep raw replays robust
244    /// against duplicated / out-of-order timestamps (the same
245    /// convention used by [`crate::ImuPreintegrator::integrate_sample`]).
246    pub fn push_sample(&mut self, gyro: Vector3<f64>, accel: Vector3<f64>, dt: f64) {
247        if dt <= 0.0 || !dt.is_finite() {
248            return;
249        }
250        self.samples.push(ImuSampleRecord { gyro, accel, dt });
251    }
252
253    /// Number of IMU samples currently buffered.
254    pub fn samples_seen(&self) -> usize {
255        self.samples.len()
256    }
257
258    /// Aggregate duration (seconds) of currently buffered samples.
259    pub fn buffered_duration_seconds(&self) -> f64 {
260        self.samples.iter().map(|s| s.dt).sum()
261    }
262
263    /// Drop every buffered sample. The configuration is preserved.
264    pub fn reset(&mut self) {
265        self.samples.clear();
266    }
267
268    /// Borrow the active configuration.
269    pub const fn config(&self) -> &VisualInertialInitializerConfig {
270        &self.config
271    }
272
273    /// Attempt to recover the visual-inertial bootstrap from the
274    /// currently buffered samples. Returns `Ok(result)` when every
275    /// stationary-window predicate passes, otherwise returns
276    /// `Err(reason)` describing the first failed predicate so callers
277    /// can log a diagnostic and keep collecting samples.
278    ///
279    /// When `config.detector_window_seconds` is finite, predicates and
280    /// statistics are evaluated only on the **trailing slice** whose
281    /// cumulative `dt` first reaches that bound — early non-stationary
282    /// samples no longer prevent a later stationary tail from passing.
283    pub fn try_initialize(
284        &self,
285    ) -> Result<VisualInertialInitializationResult, StationaryRejectionReason> {
286        let (slice, slice_duration) = self.detector_window_slice();
287        if slice.len() < self.config.min_samples {
288            return Err(StationaryRejectionReason::InsufficientSamples {
289                have: slice.len(),
290                need: self.config.min_samples,
291            });
292        }
293        if slice_duration < self.config.min_stationary_window_seconds {
294            return Err(StationaryRejectionReason::InsufficientDuration {
295                have: slice_duration,
296                need: self.config.min_stationary_window_seconds,
297            });
298        }
299
300        // Time-weighted mean and variance: `μ = Σ x_i · dt_i / Σ dt_i`,
301        // `σ² = Σ (x_i - μ)² · dt_i / Σ dt_i`. For uniform `dt` this
302        // collapses to the sample-count weighted form and existing
303        // numerical outputs are preserved exactly. For irregular `dt`
304        // (a real IMU stream that drops or duplicates samples) the
305        // time-weighted form removes a small but real bias in the
306        // statistics.
307        let total_dt = slice_duration;
308        let gyro_mean = slice
309            .iter()
310            .fold(Vector3::<f64>::zeros(), |acc, s| acc + s.gyro * s.dt)
311            / total_dt;
312        let accel_mean = slice
313            .iter()
314            .fold(Vector3::<f64>::zeros(), |acc, s| acc + s.accel * s.dt)
315            / total_dt;
316        let mut gyro_var = Vector3::<f64>::zeros();
317        let mut accel_var = Vector3::<f64>::zeros();
318        for sample in slice {
319            let dg = sample.gyro - gyro_mean;
320            let da = sample.accel - accel_mean;
321            gyro_var += Vector3::new(dg.x * dg.x, dg.y * dg.y, dg.z * dg.z) * sample.dt;
322            accel_var += Vector3::new(da.x * da.x, da.y * da.y, da.z * da.z) * sample.dt;
323        }
324        gyro_var /= total_dt;
325        accel_var /= total_dt;
326        let gyro_std = Vector3::new(gyro_var.x.sqrt(), gyro_var.y.sqrt(), gyro_var.z.sqrt());
327        let accel_std = Vector3::new(accel_var.x.sqrt(), accel_var.y.sqrt(), accel_var.z.sqrt());
328
329        if gyro_std
330            .iter()
331            .any(|s| !s.is_finite() || *s > self.config.max_gyro_std)
332        {
333            return Err(StationaryRejectionReason::GyroNoiseTooHigh {
334                observed: gyro_std,
335                limit: self.config.max_gyro_std,
336            });
337        }
338        let mean_gyro_magnitude = gyro_mean.norm();
339        if !mean_gyro_magnitude.is_finite()
340            || mean_gyro_magnitude > self.config.max_mean_gyro_magnitude
341        {
342            return Err(StationaryRejectionReason::MeanGyroMagnitudeTooHigh {
343                observed: mean_gyro_magnitude,
344                limit: self.config.max_mean_gyro_magnitude,
345            });
346        }
347        if accel_std
348            .iter()
349            .any(|s| !s.is_finite() || *s > self.config.max_accel_std)
350        {
351            return Err(StationaryRejectionReason::AccelNoiseTooHigh {
352                observed: accel_std,
353                limit: self.config.max_accel_std,
354            });
355        }
356
357        let gravity_magnitude = self.config.gravity_world.norm();
358        let mean_accel_magnitude = accel_mean.norm();
359        if (mean_accel_magnitude - gravity_magnitude).abs() > self.config.max_accel_magnitude_error
360        {
361            return Err(StationaryRejectionReason::AccelMagnitudeMismatch {
362                observed: mean_accel_magnitude,
363                expected: gravity_magnitude,
364                tolerance: self.config.max_accel_magnitude_error,
365            });
366        }
367        if mean_accel_magnitude <= f64::EPSILON {
368            return Err(StationaryRejectionReason::AccelMagnitudeMismatch {
369                observed: mean_accel_magnitude,
370                expected: gravity_magnitude,
371                tolerance: self.config.max_accel_magnitude_error,
372            });
373        }
374
375        // When the body is stationary the specific-force measurement
376        // in body frame is `a_b ≈ -R_b←w · g_w + b_a`. We recover
377        // R_w←b by aligning `a_b` (after bias cancellation) with the
378        // world-frame "up" direction `-g_w`. Yaw is unobservable from
379        // gravity alone, so the shortest rotation that maps `a_b` to
380        // `-g_w` is the canonical choice — it leaves yaw at zero.
381        let world_up = -self.config.gravity_world;
382        let rotation = UnitQuaternion::rotation_between(&accel_mean, &world_up)
383            .unwrap_or_else(UnitQuaternion::identity);
384
385        // Once the direction is absorbed by the rotation, any residual
386        // is in the magnitude only: `b_a = a_b - (-R_b←w · g_w)`. The
387        // dot-product form below collapses to `(|a_b| - |g_w|) · û_b`
388        // when `R_w←b` was estimated perfectly from the direction.
389        let inverse_rotation = rotation.inverse();
390        let bias_acc = accel_mean - inverse_rotation * world_up;
391
392        Ok(VisualInertialInitializationResult {
393            gravity_world: self.config.gravity_world,
394            initial_rotation_body_to_world: rotation,
395            initial_velocity_world: Vector3::zeros(),
396            bias_gyro: gyro_mean,
397            bias_acc,
398            samples_consumed: slice.len(),
399            duration_seconds: slice_duration,
400            gyro_std,
401            accel_std,
402            mean_accel_magnitude,
403        })
404    }
405
406    /// Return the trailing detector slice of buffered samples plus its
407    /// cumulative `dt`. When `config.detector_window_seconds` is
408    /// infinite (or non-positive / non-finite), this is the entire
409    /// buffer. Otherwise it walks the buffer from the end backwards and
410    /// keeps adding samples until the cumulative `dt` first reaches the
411    /// configured window width — the slice may be slightly longer than
412    /// `detector_window_seconds` by at most one sample's `dt`.
413    fn detector_window_slice(&self) -> (&[ImuSampleRecord], f64) {
414        let window = self.config.detector_window_seconds;
415        if !window.is_finite() || window <= 0.0 {
416            let dur: f64 = self.samples.iter().map(|s| s.dt).sum();
417            return (&self.samples[..], dur);
418        }
419        let mut acc_dt = 0.0;
420        let mut start_idx = self.samples.len();
421        for i in (0..self.samples.len()).rev() {
422            acc_dt += self.samples[i].dt;
423            start_idx = i;
424            if acc_dt >= window {
425                break;
426            }
427        }
428        (&self.samples[start_idx..], acc_dt)
429    }
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435    use nalgebra::Rotation3;
436
437    fn euroc_config() -> VisualInertialInitializerConfig {
438        VisualInertialInitializerConfig::default()
439    }
440
441    #[test]
442    fn default_config_uses_z_up_gravity() {
443        let config = VisualInertialInitializerConfig::default();
444        assert!((config.gravity_world - Vector3::new(0.0, 0.0, -9.81)).norm() < 1.0e-12);
445    }
446
447    #[test]
448    fn stationary_level_window_recovers_zero_rotation_and_zero_biases() {
449        let mut initializer = VisualInertialInitializer::new(euroc_config());
450        let dt = 0.005; // 200 Hz
451        let target_accel = -Vector3::new(0.0, 0.0, -9.81); // body level → reads up
452        for _ in 0..200 {
453            initializer.push_sample(Vector3::zeros(), target_accel, dt);
454        }
455        let result = initializer
456            .try_initialize()
457            .expect("stationary window should recover bootstrap");
458        assert_eq!(result.samples_consumed, 200);
459        assert!((result.duration_seconds - 1.0).abs() < 1.0e-9);
460        assert!(result.initial_velocity_world.norm() < 1.0e-12);
461        assert!(result.bias_gyro.norm() < 1.0e-12);
462        assert!(result.bias_acc.norm() < 1.0e-9);
463        assert!(result.initial_rotation_body_to_world.angle().abs() < 1.0e-9);
464        assert!(result.gyro_std.norm() < 1.0e-12);
465        assert!(result.accel_std.norm() < 1.0e-12);
466        assert!((result.mean_accel_magnitude - 9.81).abs() < 1.0e-9);
467    }
468
469    #[test]
470    fn tilted_stationary_window_recovers_rotation() {
471        let mut initializer = VisualInertialInitializer::new(euroc_config());
472        let dt = 0.005;
473        // Body tilted 30 degrees about x-axis. Then accel measures
474        // R_b←w · (-g_w). With g_w = (0, 0, -9.81), -g_w = (0, 0, 9.81)
475        // expressed in body frame is R_b←w · (0, 0, 9.81).
476        //
477        // The literal 0.5236 (~30°) is a deliberate test input: the 1e-9 gate
478        // on `delta` below is calibrated to it, and substituting the exact
479        // `FRAC_PI_6` shifts the recovered yaw past that tolerance. Keep the
480        // literal and silence the approx-constant lint here.
481        #[allow(clippy::approx_constant)]
482        let rotation_w_b = Rotation3::from_axis_angle(&Vector3::x_axis(), 0.5236);
483        let world_up = Vector3::new(0.0, 0.0, 9.81);
484        let accel_body = rotation_w_b.inverse() * world_up;
485        for _ in 0..200 {
486            initializer.push_sample(Vector3::zeros(), accel_body, dt);
487        }
488        let result = initializer
489            .try_initialize()
490            .expect("tilted stationary should still recover bootstrap");
491        // Rotating the measured accel by the recovered rotation should
492        // produce the world-frame "up" direction.
493        let lifted = result.initial_rotation_body_to_world * accel_body;
494        assert!((lifted - world_up).norm() < 1.0e-9);
495        assert!(result.bias_acc.norm() < 1.0e-9);
496        // The recovered orientation should match the synthetic rotation
497        // (up to yaw, which is unobservable; the synthetic rotation
498        // here has no yaw component, so the match is exact).
499        let recovered = Rotation3::from(result.initial_rotation_body_to_world);
500        let delta = rotation_w_b * recovered.inverse();
501        assert!(delta.angle().abs() < 1.0e-9);
502    }
503
504    #[test]
505    fn nonzero_gyro_mean_becomes_bias() {
506        let mut initializer = VisualInertialInitializer::new(euroc_config());
507        let dt = 0.005;
508        let gyro_bias = Vector3::new(0.01, -0.02, 0.005);
509        let accel_body = Vector3::new(0.0, 0.0, 9.81);
510        for _ in 0..200 {
511            initializer.push_sample(gyro_bias, accel_body, dt);
512        }
513        let result = initializer.try_initialize().expect("ok");
514        assert!((result.bias_gyro - gyro_bias).norm() < 1.0e-12);
515    }
516
517    #[test]
518    fn rejects_low_variance_constant_rotation_as_non_stationary() {
519        let mut initializer = VisualInertialInitializer::new(euroc_config());
520        for _ in 0..100 {
521            initializer.push_sample(
522                Vector3::new(0.0, 0.0, 0.08),
523                Vector3::new(0.0, 0.0, 9.81),
524                0.01,
525            );
526        }
527        match initializer.try_initialize().expect_err("constant rotation") {
528            StationaryRejectionReason::MeanGyroMagnitudeTooHigh { observed, limit } => {
529                assert!((observed - 0.08).abs() < 1.0e-12);
530                assert_eq!(limit, 0.05);
531            }
532            other => panic!("expected MeanGyroMagnitudeTooHigh, got {other:?}"),
533        }
534    }
535
536    #[test]
537    fn rejects_noisy_gyro() {
538        let mut initializer = VisualInertialInitializer::new(euroc_config());
539        let dt = 0.005;
540        let accel_body = Vector3::new(0.0, 0.0, 9.81);
541        for i in 0..200 {
542            // Alternating ±1.0 rad/s on x-axis → std = 1.0, way above default 0.05.
543            let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
544            let gyro = Vector3::new(sign, 0.0, 0.0);
545            initializer.push_sample(gyro, accel_body, dt);
546        }
547        match initializer.try_initialize().expect_err("should reject") {
548            StationaryRejectionReason::GyroNoiseTooHigh { observed, limit } => {
549                assert!(observed.x > limit);
550            }
551            other => panic!("expected GyroNoiseTooHigh, got {other:?}"),
552        }
553    }
554
555    #[test]
556    fn rejects_noisy_accel() {
557        let mut initializer = VisualInertialInitializer::new(euroc_config());
558        let dt = 0.005;
559        for i in 0..200 {
560            let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
561            let accel = Vector3::new(2.0 * sign, 0.0, 9.81);
562            initializer.push_sample(Vector3::zeros(), accel, dt);
563        }
564        match initializer.try_initialize().expect_err("should reject") {
565            StationaryRejectionReason::AccelNoiseTooHigh { observed, limit } => {
566                assert!(observed.x > limit);
567            }
568            other => panic!("expected AccelNoiseTooHigh, got {other:?}"),
569        }
570    }
571
572    #[test]
573    fn rejects_accel_magnitude_mismatch() {
574        let mut initializer = VisualInertialInitializer::new(euroc_config());
575        let dt = 0.005;
576        let accel_body = Vector3::new(0.0, 0.0, 2.0); // way off 9.81
577        for _ in 0..200 {
578            initializer.push_sample(Vector3::zeros(), accel_body, dt);
579        }
580        match initializer.try_initialize().expect_err("should reject") {
581            StationaryRejectionReason::AccelMagnitudeMismatch {
582                observed,
583                expected,
584                tolerance,
585            } => {
586                assert!((observed - 2.0).abs() < 1.0e-9);
587                assert!((expected - 9.81).abs() < 1.0e-9);
588                assert!(tolerance > 0.0);
589            }
590            other => panic!("expected AccelMagnitudeMismatch, got {other:?}"),
591        }
592    }
593
594    #[test]
595    fn rejects_insufficient_samples() {
596        let mut initializer = VisualInertialInitializer::new(euroc_config());
597        let dt = 0.005;
598        let accel_body = Vector3::new(0.0, 0.0, 9.81);
599        for _ in 0..10 {
600            initializer.push_sample(Vector3::zeros(), accel_body, dt);
601        }
602        match initializer.try_initialize().expect_err("should reject") {
603            StationaryRejectionReason::InsufficientSamples { have, need } => {
604                assert_eq!(have, 10);
605                assert_eq!(need, 50);
606            }
607            other => panic!("expected InsufficientSamples, got {other:?}"),
608        }
609    }
610
611    #[test]
612    fn rejects_insufficient_duration() {
613        let config = VisualInertialInitializerConfig {
614            min_samples: 10,
615            min_stationary_window_seconds: 1.0,
616            ..Default::default()
617        };
618        let mut initializer = VisualInertialInitializer::new(config);
619        let dt = 0.005;
620        let accel_body = Vector3::new(0.0, 0.0, 9.81);
621        // 50 samples × 5 ms = 0.25 s; below the 1 s threshold.
622        for _ in 0..50 {
623            initializer.push_sample(Vector3::zeros(), accel_body, dt);
624        }
625        match initializer.try_initialize().expect_err("should reject") {
626            StationaryRejectionReason::InsufficientDuration { have, need } => {
627                assert!((have - 0.25).abs() < 1.0e-9);
628                assert!((need - 1.0).abs() < 1.0e-9);
629            }
630            other => panic!("expected InsufficientDuration, got {other:?}"),
631        }
632    }
633
634    #[test]
635    fn reset_clears_buffered_samples() {
636        let mut initializer = VisualInertialInitializer::new(euroc_config());
637        initializer.push_sample(Vector3::zeros(), Vector3::new(0.0, 0.0, 9.81), 0.005);
638        assert_eq!(initializer.samples_seen(), 1);
639        initializer.reset();
640        assert_eq!(initializer.samples_seen(), 0);
641        assert!((initializer.buffered_duration_seconds() - 0.0).abs() < 1.0e-12);
642    }
643
644    #[test]
645    fn push_sample_drops_nonpositive_dt() {
646        let mut initializer = VisualInertialInitializer::new(euroc_config());
647        let accel = Vector3::new(0.0, 0.0, 9.81);
648        initializer.push_sample(Vector3::zeros(), accel, 0.0);
649        initializer.push_sample(Vector3::zeros(), accel, -0.005);
650        initializer.push_sample(Vector3::zeros(), accel, f64::NAN);
651        assert_eq!(initializer.samples_seen(), 0);
652    }
653
654    #[test]
655    fn default_detector_window_seconds_is_infinity() {
656        // Backward-compat anchor: the new sliding-window knob must
657        // default to "use the entire buffer", so existing callers see
658        // zero behavioural change after the field lands.
659        let config = VisualInertialInitializerConfig::default();
660        assert!(config.detector_window_seconds.is_infinite());
661        assert!(config.detector_window_seconds > 0.0);
662    }
663
664    #[test]
665    fn time_weighted_statistics_match_unweighted_for_uniform_dt() {
666        // Regression sanity check: under uniform `dt` the time-weighted
667        // mean / variance formula must match the historical
668        // sample-count weighted output exactly. This is the property
669        // that lets all 11 pre-existing tests keep passing — but it's
670        // worth pinning explicitly so any future tweak to the
671        // weighting formula is caught immediately.
672        let mut initializer = VisualInertialInitializer::new(euroc_config());
673        let dt = 0.005;
674        for i in 0..200 {
675            // A signal where the mean / std are easy to compute by
676            // hand: gyro x alternates +0.001 / -0.001 (mean 0, std
677            // 0.001), accel z = 9.81 + (i as f64) * 1e-6 (mean drifts
678            // slightly).
679            let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
680            let gyro = Vector3::new(sign * 0.001, 0.0, 0.0);
681            let accel = Vector3::new(0.0, 0.0, 9.81 + (i as f64) * 1.0e-6);
682            initializer.push_sample(gyro, accel, dt);
683        }
684        let result = initializer
685            .try_initialize()
686            .expect("clean stationary stream");
687        // Sample-count weighted mean for `[+0.001, -0.001, ...]` (200
688        // samples) is exactly 0; same for the time-weighted form when
689        // dt is uniform.
690        assert!(result.bias_gyro.norm() < 1.0e-15);
691        // gyro_std on x should equal 0.001 to within fp tolerance.
692        assert!((result.gyro_std.x - 0.001).abs() < 1.0e-12);
693    }
694
695    #[test]
696    fn time_weighted_statistics_shift_mean_under_nonuniform_dt() {
697        // With non-uniform `dt`, the time-weighted mean must weight
698        // each sample by its `dt`. Push two samples: one with a tiny
699        // dt at value 0, one with a much larger dt at value 1. The
700        // sample-count-weighted mean would be 0.5; the time-weighted
701        // mean must be much closer to 1.
702        let config = VisualInertialInitializerConfig {
703            min_samples: 2,
704            min_stationary_window_seconds: 0.0,
705            max_gyro_std: f64::INFINITY,
706            max_mean_gyro_magnitude: f64::INFINITY,
707            max_accel_std: f64::INFINITY,
708            max_accel_magnitude_error: f64::INFINITY,
709            ..Default::default()
710        };
711        let mut initializer = VisualInertialInitializer::new(config);
712        // Sample A: dt = 0.001 s, gyro.x = 0.
713        initializer.push_sample(Vector3::zeros(), Vector3::new(0.0, 0.0, 9.81), 0.001);
714        // Sample B: dt = 0.999 s, gyro.x = 1.0.
715        initializer.push_sample(
716            Vector3::new(1.0, 0.0, 0.0),
717            Vector3::new(0.0, 0.0, 9.81),
718            0.999,
719        );
720        let result = initializer.try_initialize().expect("predicates relaxed");
721        // Time-weighted mean = (0 * 0.001 + 1 * 0.999) / 1.000 = 0.999.
722        // Sample-count weighted would be (0 + 1) / 2 = 0.500.
723        assert!(
724            (result.bias_gyro.x - 0.999).abs() < 1.0e-12,
725            "time-weighted mean expected 0.999, got {}",
726            result.bias_gyro.x
727        );
728    }
729
730    #[test]
731    fn sliding_window_non_stationary_then_stationary_succeeds() {
732        // Deferred test #13 from the design document: the integrator
733        // starts during motion (0.5 s of noisy gyro) and the body
734        // settles later (1.5 s of stationary samples). With a 1.0 s
735        // sliding window the trailing slice is entirely stationary so
736        // initialisation must succeed and `samples_consumed` must
737        // reflect only the trailing window, not the polluted leading
738        // chunk.
739        let config = VisualInertialInitializerConfig {
740            min_samples: 50,
741            min_stationary_window_seconds: 0.5,
742            detector_window_seconds: 1.0,
743            ..Default::default()
744        };
745        let mut initializer = VisualInertialInitializer::new(config);
746        let dt = 0.005; // 200 Hz
747        let accel_body = Vector3::new(0.0, 0.0, 9.81);
748        // Phase 1: 0.5 s of noisy gyro at ±1 rad/s on the x-axis.
749        for i in 0..100 {
750            let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
751            initializer.push_sample(Vector3::new(sign, 0.0, 0.0), accel_body, dt);
752        }
753        // Phase 2: 1.5 s of stationary samples.
754        for _ in 0..300 {
755            initializer.push_sample(Vector3::zeros(), accel_body, dt);
756        }
757        let result = initializer
758            .try_initialize()
759            .expect("trailing 1.0 s window is clean");
760        // Slice walks backwards from the end until cumulative `dt` ≥
761        // 1.0 s. With dt = 0.005 that's 200 samples — entirely from
762        // phase 2.
763        assert_eq!(result.samples_consumed, 200);
764        assert!((result.duration_seconds - 1.0).abs() < 1.0e-9);
765        // The slice is clean, so the recovered gyro bias is exactly
766        // the stationary mean (zero) and the std is zero.
767        assert!(result.bias_gyro.norm() < 1.0e-12);
768        assert!(result.gyro_std.norm() < 1.0e-12);
769        // `samples_seen()` still reports the full buffer (400) — the
770        // sliding window is an evaluation detail, not a buffer prune.
771        assert_eq!(initializer.samples_seen(), 400);
772    }
773
774    #[test]
775    fn sliding_window_rejects_when_recent_samples_are_noisy() {
776        // The reverse of the above: 1.5 s of stationary samples
777        // followed by 0.5 s of noisy gyro. With a 0.5 s sliding
778        // window the trailing slice is exactly the noisy chunk so
779        // initialisation must fail with `GyroNoiseTooHigh`.
780        let config = VisualInertialInitializerConfig {
781            min_samples: 50,
782            min_stationary_window_seconds: 0.4,
783            detector_window_seconds: 0.5,
784            ..Default::default()
785        };
786        let mut initializer = VisualInertialInitializer::new(config);
787        let dt = 0.005;
788        let accel_body = Vector3::new(0.0, 0.0, 9.81);
789        for _ in 0..300 {
790            initializer.push_sample(Vector3::zeros(), accel_body, dt);
791        }
792        for i in 0..100 {
793            let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
794            initializer.push_sample(Vector3::new(sign, 0.0, 0.0), accel_body, dt);
795        }
796        match initializer
797            .try_initialize()
798            .expect_err("trailing slice is noisy")
799        {
800            StationaryRejectionReason::GyroNoiseTooHigh { observed, limit } => {
801                assert!(observed.x > limit);
802            }
803            other => panic!("expected GyroNoiseTooHigh, got {other:?}"),
804        }
805    }
806
807    #[test]
808    fn sliding_window_insufficient_when_trailing_slice_too_short() {
809        // The sliding-window predicates apply to the SLICE, not the
810        // total buffer. A buffer with 2 s of samples but a 0.1 s
811        // window where `min_stationary_window_seconds = 0.5` must be
812        // rejected as `InsufficientDuration` — the buffer is large
813        // but the slice is too small.
814        let config = VisualInertialInitializerConfig {
815            min_samples: 10,
816            min_stationary_window_seconds: 0.5,
817            detector_window_seconds: 0.1,
818            ..Default::default()
819        };
820        let mut initializer = VisualInertialInitializer::new(config);
821        let dt = 0.005;
822        let accel_body = Vector3::new(0.0, 0.0, 9.81);
823        for _ in 0..400 {
824            initializer.push_sample(Vector3::zeros(), accel_body, dt);
825        }
826        match initializer
827            .try_initialize()
828            .expect_err("slice is shorter than required")
829        {
830            StationaryRejectionReason::InsufficientDuration { have, need } => {
831                // Slice walks backwards until cumulative dt >= 0.1 s,
832                // so `have` is `~0.1` (slightly over by one sample).
833                assert!(have < need);
834                assert!((need - 0.5).abs() < 1.0e-9);
835                assert!(have > 0.0 && have < 0.5);
836            }
837            other => panic!("expected InsufficientDuration, got {other:?}"),
838        }
839    }
840
841    #[test]
842    fn gravity_alignment_residual_is_invariant_under_world_yaw() {
843        // Test #12 from the test-strategy section of
844        // `docs/vi_initialization_integration.md`. Stationary VI init
845        // observes the gravity direction but not yaw, so the
846        // `gravity_alignment_residual_deg` metric must report `~0` for
847        // two stationary streams whose ground-truth body→world
848        // rotations differ only by a 30° rotation about the world
849        // "up" axis. The full quaternion residual against the
850        // yaw-rotated GT is NOT zero — that is the precise mistake
851        // the metric is designed to avoid. This pins yaw as a gauge
852        // in the residual, not a real recovery error.
853        let mut config = euroc_config();
854        // Use stronger noise gates than the noise level of the
855        // synthesised data so the streams pass cleanly.
856        config.max_accel_std = 1.0e-6;
857        let world_gravity = config.gravity_world;
858        let world_up_axis = nalgebra::Unit::new_normalize(-world_gravity);
859
860        // Tilt about world-x by 30° — perpendicular to the world up
861        // (z) axis under EuRoC convention, so the tilt has zero
862        // projection onto the yaw axis and the two ground-truth
863        // rotations below genuinely differ only by yaw.
864        let tilt = UnitQuaternion::from_axis_angle(&Vector3::x_axis(), 30f64.to_radians());
865        let yaw = UnitQuaternion::from_axis_angle(&world_up_axis, 30f64.to_radians());
866
867        let gt_a = tilt;
868        let gt_b = yaw * tilt;
869
870        // Specific-force measurement in body frame for each
871        // orientation: `a_b = R_b←w · (-g_w)`.
872        let accel_a = gt_a.inverse() * (-world_gravity);
873        let accel_b = gt_b.inverse() * (-world_gravity);
874
875        let dt = 0.005;
876        let mut initializer_a = VisualInertialInitializer::new(config.clone());
877        let mut initializer_b = VisualInertialInitializer::new(config);
878        for _ in 0..200 {
879            initializer_a.push_sample(Vector3::zeros(), accel_a, dt);
880            initializer_b.push_sample(Vector3::zeros(), accel_b, dt);
881        }
882        let result_a = initializer_a.try_initialize().expect("stream A stationary");
883        let result_b = initializer_b.try_initialize().expect("stream B stationary");
884
885        // The yaw-gauge-aware metric must report essentially zero for
886        // BOTH streams — that is the load-bearing assertion.
887        let residual_a = result_a.gravity_alignment_residual_deg(&gt_a);
888        let residual_b = result_b.gravity_alignment_residual_deg(&gt_b);
889        assert!(residual_a < 1.0e-6, "stream A residual = {residual_a} deg");
890        assert!(residual_b < 1.0e-6, "stream B residual = {residual_b} deg");
891
892        // Cross-check: the full quaternion residual against stream B's
893        // ground truth should be ~30° (the yaw mismatch the
894        // initialiser cannot observe). If this assertion fails the
895        // test is degenerate — i.e. the streams do not actually
896        // differ in yaw — and the previous two assertions become
897        // meaningless.
898        let full_residual_b_deg = gt_b
899            .rotation_to(&result_b.initial_rotation_body_to_world)
900            .angle()
901            .to_degrees();
902        assert!(
903            (full_residual_b_deg - 30.0).abs() < 1.0e-4,
904            "stream B full residual should be ~30°, got {full_residual_b_deg}"
905        );
906    }
907
908    #[test]
909    fn gravity_alignment_residual_returns_zero_for_zero_gravity_config() {
910        // Degenerate config guard: when `gravity_world` is the zero
911        // vector the metric has no defined direction; the helper
912        // returns 0.0 rather than NaN-poisoning a diagnostic log.
913        let mut result_zero_g = VisualInertialInitializationResult {
914            gravity_world: Vector3::zeros(),
915            initial_rotation_body_to_world: UnitQuaternion::identity(),
916            initial_velocity_world: Vector3::zeros(),
917            bias_gyro: Vector3::zeros(),
918            bias_acc: Vector3::zeros(),
919            samples_consumed: 0,
920            duration_seconds: 0.0,
921            gyro_std: Vector3::zeros(),
922            accel_std: Vector3::zeros(),
923            mean_accel_magnitude: 0.0,
924        };
925        let any_gt = UnitQuaternion::from_axis_angle(&Vector3::x_axis(), 0.5);
926        assert_eq!(result_zero_g.gravity_alignment_residual_deg(&any_gt), 0.0);
927        // Sanity: with the standard EuRoC gravity, a 90° tilt should
928        // produce ~90° residual against identity.
929        result_zero_g.gravity_world = Vector3::new(0.0, 0.0, -9.81);
930        let tilt = UnitQuaternion::from_axis_angle(&Vector3::x_axis(), std::f64::consts::FRAC_PI_2);
931        let residual_deg = result_zero_g.gravity_alignment_residual_deg(&tilt);
932        assert!(
933            (residual_deg - 90.0).abs() < 1.0e-9,
934            "identity vs 90° tilt residual = {residual_deg} deg"
935        );
936    }
937
938    #[test]
939    fn accel_magnitude_mismatch_absorbed_by_bias_when_within_tolerance() {
940        let mut initializer = VisualInertialInitializer::new(euroc_config());
941        let dt = 0.005;
942        // Measured magnitude 9.95 vs expected 9.81: 0.14 within
943        // tolerance 0.5, but should leak into bias_acc.
944        let accel_body = Vector3::new(0.0, 0.0, 9.95);
945        for _ in 0..200 {
946            initializer.push_sample(Vector3::zeros(), accel_body, dt);
947        }
948        let result = initializer.try_initialize().expect("ok");
949        let recovered_world_accel =
950            result.initial_rotation_body_to_world * (accel_body - result.bias_acc);
951        let expected_world_accel = -result.gravity_world;
952        assert!((recovered_world_accel - expected_world_accel).norm() < 1.0e-9);
953        assert!(result.bias_acc.norm() > 0.0);
954    }
955}