Skip to main content

visloc_slam/
vi_motion_initializer.rs

1//! Motion-based VI initialiser — first cut (VIBA1, stereo / known-scale
2//! path).
3//!
4//! Companion to the stationary-window [`crate::VisualInertialInitializer`].
5//! Where the static seed recovers `(R_w←b, b_g, b_a)` from a stationary
6//! IMU window (yaw and monocular scale unobservable, accel-bias
7//! observability partial), this stage refines the per-keyframe
8//! `(R_w←b, v_w, b_g, b_a)` once the body has moved enough to give the
9//! IMU translational excitation. It is the analogue of ORB-SLAM3's
10//! `VIBA1` step.
11//!
12//! Triggering. The state machine accumulates camera centres reported by
13//! the pipeline via [`MotionBasedViInitializer::register_keyframe`] and
14//! fires when **both** of these are satisfied (defaults from
15//! [`MotionBasedViInitializerConfig::default`], drawn from the design
16//! note `docs/motion_based_vi_alignment.md`):
17//!
18//! * `keyframes_observed >= min_keyframes` (default `10`)
19//! * `cumulative_translation_meters >= min_translation_meters` (default `2.0`)
20//!
21//! Solve. [`MotionBasedViInitializer::try_initialize`] invokes
22//! [`crate::run_inertial_only_vi_ba`] over the accumulated keyframe set,
23//! which holds the vision-only poses fixed and optimises velocities plus a
24//! shared short-window bias against IMU preintegration factors (landmarks are
25//! not touched). Scale is fixed at `1.0`; stereo / RGB-D sequences and
26//! monocular sequences with a known metric anchor are well-served.
27//!
28//! The optional VIBA2 outer loop handles experimental monocular scale
29//! recovery. Full joint visual-inertial BA and consistent marginalization
30//! remain separate follow-ups.
31
32use std::collections::{BTreeMap, BTreeSet};
33
34use nalgebra::{DMatrix, DVector, Matrix3, Point3, UnitQuaternion, Vector3};
35use visloc_core::geometry::SE3;
36use visloc_core::types::VisualMap;
37
38use crate::bundle::{BaConfig, BaCostBreakdown, BaResult};
39use crate::imu_preintegration::{ImuPreintegratedDelta, ImuPreintegrationFactor};
40use crate::online_slam_vi_ba::{
41    run_inertial_only_vi_ba, run_inertial_only_vi_ba_with_options, run_viba2_inertial_with_scale,
42    KeyframeImuState, Viba2Config,
43};
44use crate::vi_initializer::VisualInertialInitializationResult;
45use crate::LinearSolver;
46
47/// A second, higher excitation gate gating when [`MotionBasedViInitializer`]
48/// is allowed to release the gyro/accel bias slots to the LM solver.
49///
50/// Motivation: firing the VIBA1 inertial-only solve with bias free from the
51/// very first eligible window — a short (as few as 3-keyframe) span just
52/// past the base `min_keyframes` / `min_translation_meters` gates — let the
53/// recovered accelerometer bias diverge to magnitudes around 12 m/s² on a
54/// moving-start EuRoC sequence. The base gates only guarantee *some*
55/// translational excitation exists; they say nothing about whether that
56/// excitation is enough to make bias jointly observable alongside velocity
57/// over such a short window.
58///
59/// When configured, [`MotionBasedViInitializer::try_initialize_with_bias_seed`]
60/// runs a two-stage schedule instead of a single solve:
61///
62/// * **Stage A ("velocity stage")**: while `keyframes_observed <
63///   min_keyframes` or `cumulative_translation_meters < min_translation_meters`
64///   (this schedule's own, typically stricter, thresholds — independent of
65///   the initializer's base gates), the solve holds every bias slot fixed at
66///   the seed and refines only per-keyframe velocities via
67///   [`crate::run_inertial_only_vi_ba_with_options`] with `solve_bias =
68///   false`. Stage A fires **once**; its result is cached
69///   ([`MotionBasedViInitializer::velocity_stage_result`]) but does NOT park
70///   the initializer in the terminal `Initialised` state, so the pipeline
71///   keeps registering keyframes / translation toward the release gate.
72/// * **Stage B ("bias release")**: once both thresholds are met, the normal
73///   solve runs with biases free (dispatching to VIBA2 when configured),
74///   exactly like the legacy single-stage behaviour. Success here is
75///   terminal, as usual.
76///
77/// `None` (the default) preserves the legacy behaviour: bias is free from
78/// the very first solve that clears the initializer's base gates.
79#[derive(Debug, Clone, Copy, PartialEq)]
80pub struct BiasReleaseSchedule {
81    /// Minimum keyframe count (mirrors [`MotionBasedViInitializerConfig::min_keyframes`]'s
82    /// role, but gates bias release rather than the first solve attempt).
83    pub min_keyframes: usize,
84    /// Minimum cumulative camera-centre translation in metres before bias
85    /// is released to the solver.
86    pub min_translation_meters: f64,
87}
88
89/// Configuration for [`MotionBasedViInitializer`].
90#[derive(Debug, Clone, PartialEq)]
91pub struct MotionBasedViInitializerConfig {
92    /// Minimum number of keyframes (registered after the static seed)
93    /// before the VIBA1 trigger is allowed to fire. Default `10`.
94    pub min_keyframes: usize,
95    /// Minimum cumulative camera-centre translation in metres before
96    /// VIBA1 fires. Default `2.0`. Set to `0.0` to disable the
97    /// translation gate.
98    pub min_translation_meters: f64,
99    /// When `Some(n)`, the inertial solve uses only the earliest `n`
100    /// registered keyframes (after the min-keyframe / min-translation
101    /// gates pass). `None` uses the full registered set. Early keyframes
102    /// are the least contaminated by later VO scale drift; gyro-bias
103    /// recovery still searches 3–5 keyframe subwindows over the full
104    /// registered history.
105    pub max_solve_keyframes: Option<usize>,
106    /// World-frame gravity vector. Echoed onto the BA result for
107    /// downstream diagnostics; the IMU factors fed into the solve carry
108    /// their own gravity already.
109    pub gravity_world: Vector3<f64>,
110    /// Rigid transform from the tracked camera/sensor frame into the IMU body
111    /// frame (EuRoC `T_BS` for cam0). The visual map stores world-to-camera
112    /// poses while preintegration residuals operate on world-to-body poses.
113    /// Identity preserves the co-located body/camera convention.
114    pub body_to_camera: SE3,
115    /// Inner LM solver config. Default mirrors
116    /// [`crate::OnlineSlamLocalBaConfig::default`] (sparse linear
117    /// solver, 10 LM iterations).
118    pub ba_config: BaConfig,
119    /// Optional VIBA2 hand-off. When `Some`, the initialiser runs an
120    /// outer scale-recovery loop on top of the VIBA1 inertial-only
121    /// solve. Stereo / RGB-D / known-scale paths should leave this
122    /// `None` or set `recover_scale = false`; monocular paths set
123    /// `recover_scale = true`. See [`crate::Viba2Config`] for the
124    /// outer-loop knobs. Default `None`.
125    pub viba2: Option<Viba2Config>,
126    /// Post-solve sanity gate on the recovered per-keyframe
127    /// `velocity_world` magnitudes. When `Some(v)`, the initialiser
128    /// rejects the inner LM result if any keyframe's
129    /// `||velocity_world|| > v` and parks itself in the `Waiting` state
130    /// with [`MotionBasedViRejectionReason::VelocityOutOfRange`].
131    /// `None` (default) preserves the legacy behaviour of accepting any
132    /// LM-converged result. Indoor V1-class EuRoC sequences run safely
133    /// at `Some(10.0)` (~36 km/h ceiling); set higher for outdoor
134    /// driving datasets.
135    pub max_velocity_magnitude_mps: Option<f64>,
136    /// Optional post-solve upper bound on every recovered gyro-bias vector
137    /// magnitude (rad/s). `None` preserves legacy behavior.
138    pub max_gyro_bias_magnitude_rad_s: Option<f64>,
139    /// Optional post-solve upper bound on every recovered accelerometer-bias
140    /// vector magnitude (m/s²). `None` preserves legacy behavior.
141    pub max_accel_bias_magnitude_mps2: Option<f64>,
142    /// Optional statistical consistency gate on the final whitened IMU
143    /// residual. The value is NIS divided by 9 residual DoF per factor;
144    /// a well-modelled solve is expected near one. `None` preserves the
145    /// historical behavior.
146    pub max_final_imu_nis_per_dof: Option<f64>,
147    /// Coarse physical-unit gate for fixed-pose initialization. Unlike NIS,
148    /// these bounds do not assume the visual keyframe poses are already
149    /// statistically consistent with the IMU covariance.
150    pub max_final_imu_rotation_residual_rms_rad: Option<f64>,
151    pub max_final_imu_velocity_residual_rms_mps: Option<f64>,
152    pub max_final_imu_position_residual_rms_meters: Option<f64>,
153    /// Optional staged bias-release schedule. `None` (default) preserves
154    /// the legacy behaviour: bias is free from the first solve that clears
155    /// `min_keyframes` / `min_translation_meters`. `Some(schedule)` inserts
156    /// a bias-fixed "velocity stage" before bias is released — see
157    /// [`BiasReleaseSchedule`] for the full contract and the divergence
158    /// this guards against.
159    pub bias_release: Option<BiasReleaseSchedule>,
160    /// Estimate the world-frame gravity DIRECTION from this window's IMU
161    /// preintegration factors plus the fixed visual poses, instead of
162    /// trusting `gravity_world` as ground truth. See
163    /// [`estimate_gravity_and_velocities`] and
164    /// `docs/motion_based_vi_alignment.md`'s "Gravity-direction recovery"
165    /// section for the motivating diagnosis: on moving-start sequences
166    /// where the static [`crate::VisualInertialInitializer`] never fires,
167    /// each identity-seeded (sub)map's world frame has gravity pointing in
168    /// an ARBITRARY direction — the legacy behaviour (trusting
169    /// `gravity_world` from config as truth) then makes every IMU residual
170    /// dominated by that misalignment rather than by real inconsistency,
171    /// and every promotion is rejected by the raw-residual gates. When
172    /// `true`, [`MotionBasedViInitializer::try_initialize_with_bias_seed`]
173    /// runs the linear alignment first, feeds the solver factors carrying
174    /// the ESTIMATED gravity (rather than the configured one), and seeds
175    /// velocities from the same alignment instead of finite differences.
176    /// Default `false` preserves the legacy behaviour.
177    pub estimate_gravity: bool,
178    /// Observability gate for `estimate_gravity`: the UNCONSTRAINED linear
179    /// solve's raw gravity norm (see
180    /// [`GravityVelocityAlignment::raw_gravity_norm`]) must fall within
181    /// this fraction of `gravity_world.norm()` before the estimate is
182    /// trusted — a well-conditioned window recovers a norm near the true
183    /// magnitude on its own, with no norm constraint imposed, so a large
184    /// deviation signals the window's IMU excitation does not yet make
185    /// gravity direction reliably observable. `0.3` (30%) is a
186    /// conservative default; tighten once per-dataset noise floors are
187    /// characterised. Ignored when `estimate_gravity` is `false`.
188    pub max_gravity_norm_deviation_ratio: f64,
189    /// Estimate the shared gyro bias from ROTATION-ONLY alignment against
190    /// this window's fixed visual poses, BEFORE gravity/velocity alignment
191    /// and before the staged solve. See [`estimate_gyro_bias`] and
192    /// `docs/motion_based_vi_alignment.md`'s "Gyro-bias recovery" section
193    /// for the motivating diagnosis: on a moving-start EuRoC fixture the
194    /// final fitted IMU rotation residual RMS sat at 0.014-0.022 rad
195    /// against a 0.01 gate, bit-identical with/without gravity estimation
196    /// (the rotation residual is gravity-independent) — consistent with
197    /// EuRoC's typical gyro bias (~0.08 rad/s norm) accumulating over each
198    /// factor's `delta_time`, with the bias seed fixed at the configured
199    /// zero the whole time. When `true`,
200    /// [`MotionBasedViInitializer::try_initialize_with_bias_seed`] runs this
201    /// alignment first (right after the body-pose conversion, before
202    /// gravity recovery) and, on success, substitutes the recovered bias
203    /// for `bias_gyro_seed` everywhere downstream of that point in the same
204    /// attempt: the gravity/velocity alignment's own bias-corrected deltas,
205    /// the per-keyframe `initial_states` seeding, and (when a
206    /// [`BiasReleaseSchedule`] Stage A fires) the fixed-bias solve, which
207    /// then fixes gyro bias at the ESTIMATE rather than the raw seed
208    /// (accelerometer bias stays fixed at the seed either way — this stage
209    /// has no accelerometer evidence). Default `false` preserves the legacy
210    /// behaviour of trusting `bias_gyro_seed` verbatim.
211    pub estimate_gyro_bias: bool,
212}
213
214impl Default for MotionBasedViInitializerConfig {
215    fn default() -> Self {
216        Self {
217            min_keyframes: 10,
218            min_translation_meters: 2.0,
219            max_solve_keyframes: None,
220            gravity_world: Vector3::new(0.0, 9.81, 0.0),
221            body_to_camera: SE3::identity(),
222            ba_config: BaConfig {
223                linear_solver: LinearSolver::Sparse,
224                max_iterations: 10,
225                ..BaConfig::default()
226            },
227            viba2: None,
228            max_velocity_magnitude_mps: None,
229            max_gyro_bias_magnitude_rad_s: None,
230            max_accel_bias_magnitude_mps2: None,
231            max_final_imu_nis_per_dof: None,
232            max_final_imu_rotation_residual_rms_rad: None,
233            max_final_imu_velocity_residual_rms_mps: None,
234            max_final_imu_position_residual_rms_meters: None,
235            bias_release: None,
236            estimate_gravity: false,
237            max_gravity_norm_deviation_ratio: 0.3,
238            estimate_gyro_bias: false,
239        }
240    }
241}
242
243/// VIBA1 / VIBA2 outcome.
244#[derive(Debug, Clone, PartialEq)]
245pub struct MotionBasedViInitializationResult {
246    /// Refined per-keyframe `(velocity_world, bias_gyro, bias_acc)`.
247    pub keyframe_states: BTreeMap<u64, KeyframeImuState>,
248    /// Sorted keyframe ids covered by the solve.
249    pub keyframe_ids: Vec<u64>,
250    /// Number of IMU factors fed into the solve.
251    pub imu_factors_used: usize,
252    /// Scale factor recovered by the solve. `1.0` on the VIBA1-only
253    /// path (no `viba2` config or `recover_scale = false`); the closed-
254    /// form least-squares scale on the VIBA2 monocular path.
255    pub scale: f64,
256    /// Outer-loop scale history when VIBA2 ran (one entry per outer
257    /// iteration, starting with `Viba2Config::initial_scale`). Empty
258    /// on the VIBA1-only path.
259    pub scale_history: Vec<f64>,
260    /// Number of VIBA2 outer iterations executed. `0` on the VIBA1-only
261    /// path.
262    pub viba2_iterations_run: usize,
263    /// Cumulative translation (m) since the static seed at the moment
264    /// the trigger fired. Surface for logging / diagnostics.
265    pub trigger_translation_meters: f64,
266    /// Inner LM solve outcome (from the final VIBA2 inner solve when
267    /// applicable, else the single VIBA1 solve).
268    pub ba_result: BaResult,
269    pub initial_cost_breakdown: BaCostBreakdown,
270    pub final_cost_breakdown: BaCostBreakdown,
271    /// `true` when this result's biases were solved for (legacy path, or
272    /// [`BiasReleaseSchedule`] Stage B); `false` when this is a
273    /// [`BiasReleaseSchedule`] Stage A "velocity stage" result — every
274    /// keyframe's `(bias_gyro, bias_acc)` above equals the seed passed into
275    /// [`MotionBasedViInitializer::try_initialize_with_bias_seed`], and the
276    /// caller should NOT treat this as the terminal motion-VI-init outcome.
277    /// See [`BiasReleaseSchedule`] for the full contract.
278    pub bias_released: bool,
279    /// Gravity vector recovered by [`MotionBasedViInitializerConfig::estimate_gravity`],
280    /// `None` when that feature is off (the legacy path). When `Some`, the
281    /// pipeline mirrors it into every downstream gravity sink — see
282    /// `crate::OnlineSlamPipeline::promote_motion_vi_init_result`'s doc
283    /// comment for the full mirroring list. The map gauge itself is NEVER
284    /// rotated to match; only the gravity ASSUMPTION used by future
285    /// factor-staging and VI solves moves. See
286    /// `docs/motion_based_vi_alignment.md`'s "Gravity-direction recovery"
287    /// section.
288    pub estimated_gravity_world: Option<Vector3<f64>>,
289    /// Gyro bias recovered by [`MotionBasedViInitializerConfig::estimate_gyro_bias`]'s
290    /// rotation-only alignment, `None` when that feature is off (the legacy
291    /// path). When `Some`, every `keyframe_states` entry's `bias_gyro`
292    /// already reflects this estimate (fixed at it on a
293    /// [`BiasReleaseSchedule`] Stage A result, refined from it as the
294    /// starting point on Stage B / legacy / VIBA2), so the existing
295    /// promotion bias-mirroring picks it up with no extra plumbing. See
296    /// `docs/motion_based_vi_alignment.md`'s "Gyro-bias recovery" section.
297    pub estimated_gyro_bias: Option<Vector3<f64>>,
298}
299
300/// Why a [`MotionBasedViInitializer::try_initialize`] call returned
301/// without a fresh result.
302#[derive(Debug, Clone, PartialEq)]
303pub enum MotionBasedViRejectionReason {
304    /// Fewer than `min_keyframes` keyframes have been registered.
305    InsufficientKeyframes { have: usize, need: usize },
306    /// Accumulated camera-centre translation is below the trigger
307    /// threshold.
308    InsufficientTranslation { have: f64, need: f64 },
309    /// The keyframe set has at least `min_keyframes` entries and meets
310    /// the translation gate, but none of the supplied preintegration
311    /// factors connect any pair of registered keyframes — the IMU
312    /// stream has not yet emitted factors over this window, or the
313    /// caller passed an unrelated factor slice.
314    NoUsableImuFactors,
315    /// One or more registered keyframes are missing their pose, or the
316    /// camera lookup failed.
317    MissingKeyframeData,
318    /// Inner LM solver failed to converge (singular system, etc.).
319    SolverFailed,
320    /// Inner LM solver returned, but at least one per-keyframe
321    /// `||velocity_world||` exceeded
322    /// `MotionBasedViInitializerConfig::max_velocity_magnitude_mps`. The
323    /// solver's bias / velocity slots are NOT promoted to `self.completed`,
324    /// and its speculative map poses are discarded, so the next trigger
325    /// re-runs from the same linearisation point. `kf_id` is the worst-offender keyframe;
326    /// `magnitude_mps` is its recovered speed; `limit_mps` echoes the
327    /// configured gate.
328    VelocityOutOfRange {
329        kf_id: u64,
330        magnitude_mps: f64,
331        limit_mps: f64,
332    },
333    /// A recovered gyro bias exceeded the configured physical sanity bound.
334    GyroBiasOutOfRange {
335        kf_id: u64,
336        magnitude_rad_s: f64,
337        limit_rad_s: f64,
338    },
339    /// A recovered accelerometer bias exceeded the configured physical sanity
340    /// bound.
341    AccelBiasOutOfRange {
342        kf_id: u64,
343        magnitude_mps2: f64,
344        limit_mps2: f64,
345    },
346    /// The covariance-whitened IMU residual is statistically inconsistent
347    /// with the proposed state, so promotion would hand a bad
348    /// linearisation point to local VI-BA.
349    ImuNisOutOfRange {
350        normalized_nis_per_dof: f64,
351        rotation_residual_rms_rad: Option<f64>,
352        velocity_residual_rms_mps: Option<f64>,
353        position_residual_rms_meters: Option<f64>,
354        limit: f64,
355    },
356    /// The fixed-pose inertial initializer is too far from the IMU in
357    /// physical units to seed the subsequent joint visual-inertial solve.
358    ImuRawResidualOutOfRange {
359        rotation_residual_rms_rad: Option<f64>,
360        velocity_residual_rms_mps: Option<f64>,
361        position_residual_rms_meters: Option<f64>,
362        max_rotation_residual_rms_rad: Option<f64>,
363        max_velocity_residual_rms_mps: Option<f64>,
364        max_position_residual_rms_meters: Option<f64>,
365    },
366    /// A [`BiasReleaseSchedule`] Stage A ("velocity stage") solve has
367    /// already fired, but the schedule's bias-release gates are not yet
368    /// met, so there is nothing new to solve — the caller should keep
369    /// registering keyframes / translation and retry later. `have_*`
370    /// report the current accumulated metrics; `need_*` echo the
371    /// configured [`BiasReleaseSchedule`] thresholds.
372    AwaitingBiasReleaseExcitation {
373        have_keyframes: usize,
374        need_keyframes: usize,
375        have_translation_meters: f64,
376        need_translation_meters: f64,
377    },
378    /// [`MotionBasedViInitializerConfig::estimate_gravity`] is `true`, but
379    /// the gravity/velocity alignment degenerated: fewer than 2 usable
380    /// in-window IMU factors survived the alignment's own windowing, or
381    /// the unconstrained linear solve produced a non-finite or near-zero
382    /// gravity vector. Distinct from [`Self::NoUsableImuFactors`], which
383    /// covers the (looser) "the solver has nothing to solve at all" case;
384    /// this variant means the alignment specifically could not condition
385    /// well enough to propose a gravity estimate at all.
386    GravityEstimateDegenerate,
387    /// [`MotionBasedViInitializerConfig::estimate_gravity`] recovered a
388    /// gravity vector whose UNCONSTRAINED magnitude (`raw_norm_mps2`) sits
389    /// further from the expected magnitude (`expected_mps2`, i.e.
390    /// `config.gravity_world.norm()`) than
391    /// `max_deviation_ratio` allows. This is the observability gate: a
392    /// well-conditioned window recovers the true magnitude on its own with
393    /// no norm constraint imposed, so a large deviation means the window's
394    /// IMU excitation does not yet make gravity direction reliably
395    /// observable.
396    GravityEstimateOutOfRange {
397        raw_norm_mps2: f64,
398        expected_mps2: f64,
399        max_deviation_ratio: f64,
400    },
401    /// [`MotionBasedViInitializerConfig::estimate_gyro_bias`] is `true`, but
402    /// the rotation-only alignment degenerated: fewer than 2 usable
403    /// in-window IMU factors survived the alignment's own windowing (a
404    /// missing keyframe pose counts as unusable too), or the Gauss-Newton
405    /// normal equations were singular on the very first iteration.
406    GyroBiasEstimateDegenerate,
407}
408
409/// Read-only snapshot of [`MotionBasedViInitializer`]'s internal state.
410#[derive(Debug, Clone, PartialEq)]
411pub enum MotionBasedViInitializationStatus {
412    /// Trigger has not yet fired. Reports the accumulated metrics plus
413    /// the last `Err(...)` returned by [`MotionBasedViInitializer::try_initialize`]
414    /// (if any) so callers can render diagnostic progress.
415    Waiting {
416        keyframes_observed: usize,
417        cumulative_translation_meters: f64,
418        last_rejection: Option<MotionBasedViRejectionReason>,
419        /// `true` once a [`BiasReleaseSchedule`] Stage A ("velocity stage")
420        /// solve has fired and is cached on
421        /// [`MotionBasedViInitializer::velocity_stage_result`]. Always
422        /// `false` when `bias_release` is not configured (legacy path never
423        /// parks in a non-terminal `Waiting` success).
424        velocity_stage_completed: bool,
425        /// Mirrors [`MotionBasedViInitializer::last_gravity_alignment`]: the
426        /// most recent gravity/velocity alignment attempt, kept even when
427        /// `last_rejection` reports a later gate rejected it. `None` when
428        /// `estimate_gravity` is off or no attempt has run yet.
429        last_gravity_alignment: Option<GravityVelocityAlignment>,
430        /// Mirrors [`MotionBasedViInitializer::last_gyro_bias_alignment`]:
431        /// the most recent gyro-bias rotation-only alignment attempt, kept
432        /// even when `last_rejection` reports a later gate rejected it.
433        /// `None` when `estimate_gyro_bias` is off or no attempt has run
434        /// yet.
435        last_gyro_bias_alignment: Option<GyroBiasAlignment>,
436    },
437    /// VIBA1 has fired and succeeded; the result is the recovered
438    /// refinement.
439    Initialised {
440        result: MotionBasedViInitializationResult,
441    },
442}
443
444/// State machine that fires a single VIBA1 inertial-only solve once the
445/// keyframe count + cumulative-translation thresholds are met. See the
446/// module docstring and the design note
447/// `docs/motion_based_vi_alignment.md` for the full contract.
448#[derive(Debug, Clone, PartialEq)]
449pub struct MotionBasedViInitializer {
450    config: MotionBasedViInitializerConfig,
451    keyframes: Vec<(u64, Point3<f64>)>,
452    cumulative_translation: f64,
453    completed: Option<MotionBasedViInitializationResult>,
454    last_rejection: Option<MotionBasedViRejectionReason>,
455    /// Track whether this initializer's `register_keyframe` should
456    /// charge the inter-keyframe distance against the
457    /// `cumulative_translation` running sum. Always `true` after the
458    /// first `register_keyframe` call; the first call only seeds the
459    /// chain (zero translation by definition).
460    has_seed_center: bool,
461    /// Cached [`BiasReleaseSchedule`] Stage A ("velocity stage") result.
462    /// `Some` once that non-terminal solve has fired; cleared by
463    /// [`Self::reset`]. Never populated when `config.bias_release` is
464    /// `None` (the legacy path goes straight to a terminal result).
465    velocity_stage: Option<MotionBasedViInitializationResult>,
466    /// The most recent [`estimate_gravity_and_velocities`] output, kept
467    /// regardless of whether the attempt that produced it went on to be
468    /// accepted or rejected by a LATER gate (`GravityEstimateOutOfRange`,
469    /// `ImuRawResidualOutOfRange`, `ImuNisOutOfRange`, etc). Diagnostic
470    /// visibility only: promotion never reads this field, only the return
471    /// value threaded through `try_initialize_with_bias_seed`'s own control
472    /// flow. `None` when `config.estimate_gravity` is `false`, or once
473    /// `reset` is called. See [`Self::last_gravity_alignment`] and
474    /// `docs/motion_based_vi_alignment.md`'s "Gravity-direction recovery"
475    /// section — this is the fix for that section's observed gap: on real
476    /// data most attempts are rejected by a downstream residual gate before
477    /// ever reaching a terminal `Initialised` state, so without this field
478    /// the recovered gravity vector was invisible on every run except a
479    /// lucky first-attempt success.
480    last_gravity_alignment: Option<GravityVelocityAlignment>,
481    /// The most recent [`estimate_gyro_bias`] output, kept regardless of
482    /// whether the attempt that produced it went on to be accepted or
483    /// rejected by a later gate. Diagnostic visibility only, mirroring
484    /// [`Self::last_gravity_alignment`]'s rationale exactly. `None` when
485    /// `config.estimate_gyro_bias` is `false`, or once `reset` is called.
486    last_gyro_bias_alignment: Option<GyroBiasAlignment>,
487}
488
489impl MotionBasedViInitializer {
490    /// Construct with the given config; carries no keyframes yet.
491    pub const fn new(config: MotionBasedViInitializerConfig) -> Self {
492        Self {
493            config,
494            keyframes: Vec::new(),
495            cumulative_translation: 0.0,
496            completed: None,
497            last_rejection: None,
498            has_seed_center: false,
499            velocity_stage: None,
500            last_gravity_alignment: None,
501            last_gyro_bias_alignment: None,
502        }
503    }
504
505    /// Borrow the active configuration.
506    pub const fn config(&self) -> &MotionBasedViInitializerConfig {
507        &self.config
508    }
509
510    /// Overwrite the running config's `gravity_world`. Used by
511    /// `crate::OnlineSlamPipeline::promote_motion_vi_init_result` to mirror
512    /// a freshly-`estimate_gravity`-recovered gravity vector back into this
513    /// initializer so a LATER window (a subsequent
514    /// [`BiasReleaseSchedule`] Stage B, or a fresh sequence after
515    /// `reset_sequence_state`) starts from the corrected assumption instead
516    /// of the original (possibly wrong) config value. Does not touch any
517    /// cached result or registered keyframe/translation state.
518    pub const fn set_gravity_world(&mut self, gravity_world: Vector3<f64>) {
519        self.config.gravity_world = gravity_world;
520    }
521
522    /// Drop every accumulated keyframe and the cached VIBA1 result. The
523    /// configuration is preserved. Mirrors
524    /// [`crate::VisualInertialInitializer::reset`].
525    pub fn reset(&mut self) {
526        self.keyframes.clear();
527        self.cumulative_translation = 0.0;
528        self.completed = None;
529        self.last_rejection = None;
530        self.has_seed_center = false;
531        self.velocity_stage = None;
532        self.last_gravity_alignment = None;
533        self.last_gyro_bias_alignment = None;
534    }
535
536    /// Number of keyframes registered since construction / last reset.
537    pub fn keyframes_observed(&self) -> usize {
538        self.keyframes.len()
539    }
540
541    /// Cumulative camera-centre translation (m) along the registered
542    /// keyframe chain.
543    pub const fn cumulative_translation_meters(&self) -> f64 {
544        self.cumulative_translation
545    }
546
547    /// Note a freshly-registered keyframe's camera centre in world
548    /// frame. The first call after construction / reset only seeds the
549    /// chain; subsequent calls add the inter-keyframe distance to the
550    /// running cumulative-translation total.
551    ///
552    /// Idempotent against re-registering the same `keyframe_id`: a
553    /// second call with the same id silently overwrites the prior
554    /// centre without double-counting. (This matters when a pipeline
555    /// fires a "new keyframe" event and immediately corrects the pose
556    /// via local-BA on the same frame.)
557    pub fn register_keyframe(&mut self, keyframe_id: u64, camera_center_world: Point3<f64>) {
558        if let Some(slot) = self.keyframes.iter_mut().find(|(id, _)| *id == keyframe_id) {
559            slot.1 = camera_center_world;
560            return;
561        }
562        if self.has_seed_center {
563            if let Some(prev) = self.keyframes.last() {
564                self.cumulative_translation += (camera_center_world - prev.1).norm();
565            }
566        } else {
567            self.has_seed_center = true;
568        }
569        self.keyframes.push((keyframe_id, camera_center_world));
570    }
571
572    /// `true` once both trigger gates (keyframe count + translation)
573    /// are satisfied. `try_initialize` will still return Err if no IMU
574    /// factor connects any pair, but `is_ready` is the cheap pre-check
575    /// the pipeline can poll on every frame.
576    pub fn is_ready(&self) -> bool {
577        self.completed.is_none()
578            && self.keyframes.len() >= self.config.min_keyframes
579            && self.cumulative_translation >= self.config.min_translation_meters
580    }
581
582    /// Returns the cached result if VIBA1 has already fired.
583    pub const fn result(&self) -> Option<&MotionBasedViInitializationResult> {
584        self.completed.as_ref()
585    }
586
587    /// Returns the cached [`BiasReleaseSchedule`] Stage A ("velocity
588    /// stage") result, if one has fired. Always `None` when
589    /// `config().bias_release` is `None`, or once the initializer has
590    /// reached the terminal `Initialised` state (Stage A's cache is not
591    /// cleared on Stage B success, but callers should prefer
592    /// [`Self::result`] at that point).
593    pub const fn velocity_stage_result(&self) -> Option<&MotionBasedViInitializationResult> {
594        self.velocity_stage.as_ref()
595    }
596
597    /// Test-only seam: directly inject a cached [`BiasReleaseSchedule`]
598    /// Stage A ("velocity stage") result without replaying the full
599    /// numeric solve. Exists so pipeline-level tests (see
600    /// `online_slam.rs`'s `vi_initialization_pending` tests) can exercise
601    /// [`Self::velocity_stage_result`] / [`crate::OnlineSlamMotionViInitState::velocity_stage_fired`]
602    /// without reconstructing an entire synthetic map + IMU-factor solve
603    /// just to reach Stage A — that solve path is already covered by this
604    /// module's own `bias_release_schedule_stage_a_fires_*` tests.
605    #[cfg(test)]
606    pub(crate) fn set_velocity_stage_result_for_test(
607        &mut self,
608        result: MotionBasedViInitializationResult,
609    ) {
610        self.velocity_stage = Some(result);
611    }
612
613    /// Returns the most recent [`estimate_gravity_and_velocities`] outcome,
614    /// if `config().estimate_gravity` has ever produced one — regardless of
615    /// whether that attempt went on to be accepted or rejected by a later
616    /// gate. `None` when `estimate_gravity` is off, when no in-window
617    /// attempt has run yet, or after [`Self::reset`]. See the field-level
618    /// doc comment on `last_gravity_alignment` for why this exists
619    /// separately from the terminal [`Self::result`].
620    pub const fn last_gravity_alignment(&self) -> Option<&GravityVelocityAlignment> {
621        self.last_gravity_alignment.as_ref()
622    }
623
624    /// Returns the most recent [`estimate_gyro_bias`] outcome, if
625    /// `config().estimate_gyro_bias` has ever produced one — regardless of
626    /// whether that attempt went on to be accepted or rejected by a later
627    /// gate. `None` when `estimate_gyro_bias` is off, when no in-window
628    /// attempt has run yet, or after [`Self::reset`]. See the field-level
629    /// doc comment on `last_gyro_bias_alignment` for why this exists
630    /// separately from the terminal [`Self::result`].
631    pub const fn last_gyro_bias_alignment(&self) -> Option<&GyroBiasAlignment> {
632        self.last_gyro_bias_alignment.as_ref()
633    }
634
635    /// Render a read-only snapshot of the current state.
636    pub fn status(&self) -> MotionBasedViInitializationStatus {
637        if let Some(result) = &self.completed {
638            MotionBasedViInitializationStatus::Initialised {
639                result: result.clone(),
640            }
641        } else {
642            MotionBasedViInitializationStatus::Waiting {
643                keyframes_observed: self.keyframes.len(),
644                cumulative_translation_meters: self.cumulative_translation,
645                last_rejection: self.last_rejection.clone(),
646                velocity_stage_completed: self.velocity_stage.is_some(),
647                last_gravity_alignment: self.last_gravity_alignment.clone(),
648                last_gyro_bias_alignment: self.last_gyro_bias_alignment,
649            }
650        }
651    }
652
653    /// Attempt to fire VIBA1 over the registered keyframes.
654    ///
655    /// On success, the inertial-only solve refines `map.keyframes[*]`'s
656    /// poses in place and the cached
657    /// [`MotionBasedViInitializationResult`] is returned. The
658    /// initialiser is single-shot: a successful firing parks the
659    /// initialiser in the `Initialised` state and subsequent calls
660    /// short-circuit to the cached result. Call [`Self::reset`] to
661    /// re-arm for a new sequence.
662    ///
663    /// `static_seed` is consumed only as a sanity seed for downstream
664    /// `keyframe_states` (the inertial-only solver pulls per-keyframe
665    /// initial values from `map.keyframes[*]`'s poses + the static
666    /// seed's biases / velocity).
667    pub fn try_initialize(
668        &mut self,
669        map: &mut VisualMap,
670        preintegration_factors: &[ImuPreintegrationFactor],
671        static_seed: &VisualInertialInitializationResult,
672    ) -> Result<&MotionBasedViInitializationResult, MotionBasedViRejectionReason> {
673        self.try_initialize_with_bias_seed(
674            map,
675            preintegration_factors,
676            static_seed.bias_gyro,
677            static_seed.bias_acc,
678        )
679    }
680
681    /// Motion-based initialization from explicit bias linearisation values.
682    /// This is the safe fallback entry point for sequences that begin in
683    /// motion: the caller may retain its calibrated/configured biases after a
684    /// stationary initializer gives up, without fabricating a false static
685    /// gravity/bias result. The solver still requires its normal keyframe and
686    /// translation excitation gates.
687    ///
688    /// When `config().bias_release` is `Some(schedule)`, this call may
689    /// instead run [`BiasReleaseSchedule`] Stage A (the bias-fixed
690    /// "velocity stage"): see the type-level docs on
691    /// [`BiasReleaseSchedule`] for the full two-stage contract. Check
692    /// `result.bias_released` — `false` means this is a non-terminal Stage
693    /// A result; `true` means the legacy path or Stage B fired and the
694    /// initializer is now `Initialised`.
695    pub fn try_initialize_with_bias_seed(
696        &mut self,
697        map: &mut VisualMap,
698        preintegration_factors: &[ImuPreintegrationFactor],
699        bias_gyro_seed: Vector3<f64>,
700        bias_acc_seed: Vector3<f64>,
701    ) -> Result<&MotionBasedViInitializationResult, MotionBasedViRejectionReason> {
702        if let Some(_existing) = &self.completed {
703            // SAFETY: borrow checker — re-fetch by `Option::as_ref` so
704            // the `&mut self` borrow above can release before the
705            // `&self` borrow below acquires.
706            return Ok(self.completed.as_ref().expect("just checked"));
707        }
708
709        let observed = self.keyframes.len();
710        if observed < self.config.min_keyframes {
711            let err = MotionBasedViRejectionReason::InsufficientKeyframes {
712                have: observed,
713                need: self.config.min_keyframes,
714            };
715            self.last_rejection = Some(err.clone());
716            return Err(err);
717        }
718        if self.cumulative_translation < self.config.min_translation_meters {
719            let err = MotionBasedViRejectionReason::InsufficientTranslation {
720                have: self.cumulative_translation,
721                need: self.config.min_translation_meters,
722            };
723            self.last_rejection = Some(err.clone());
724            return Err(err);
725        }
726
727        // Staged bias release (`BiasReleaseSchedule`): `bias_free` gates
728        // whether THIS solve is allowed to touch bias. `None` (legacy)
729        // always reports `bias_free = true` — bias is free the moment the
730        // base gates above are cleared, as before.
731        let bias_free = self.config.bias_release.is_none_or(|schedule| {
732            self.keyframes.len() >= schedule.min_keyframes
733                && self.cumulative_translation >= schedule.min_translation_meters
734        });
735        if !bias_free && self.velocity_stage.is_some() {
736            // Stage A has already fired once and is cached; there is
737            // nothing new to solve until the release gate itself is met.
738            let schedule = self
739                .config
740                .bias_release
741                .expect("bias_release must be Some when velocity_stage is populated");
742            let err = MotionBasedViRejectionReason::AwaitingBiasReleaseExcitation {
743                have_keyframes: self.keyframes.len(),
744                need_keyframes: schedule.min_keyframes,
745                have_translation_meters: self.cumulative_translation,
746                need_translation_meters: schedule.min_translation_meters,
747            };
748            self.last_rejection = Some(err.clone());
749            return Err(err);
750        }
751
752        // Seed per-keyframe states for the solver. The first keyframe
753        // (the gauge anchor for the inertial-only solve) inherits the
754        // static seed's biases + zero velocity; subsequent keyframes
755        // also start from those biases but seed velocity from the
756        // inter-keyframe centre displacement and the connecting IMU
757        // factor's `delta_time` when available.
758        let all_kf_ids: Vec<u64> = self.keyframes.iter().map(|(id, _)| *id).collect();
759        let mut kf_ids = all_kf_ids.clone();
760        if let Some(max_solve) = self.config.max_solve_keyframes {
761            if max_solve >= 2 && kf_ids.len() > max_solve {
762                kf_ids = kf_ids[..max_solve].to_vec();
763            }
764        }
765
766        let seed_initial_states = |kf_ids: &[u64], bias_gyro: Vector3<f64>| {
767            let mut initial_states: BTreeMap<u64, KeyframeImuState> = BTreeMap::new();
768            for (idx, &kf_id) in kf_ids.iter().enumerate() {
769                let velocity = if idx == 0 {
770                    Vector3::zeros()
771                } else {
772                    let prev_id = kf_ids[idx - 1];
773                    let factor = preintegration_factors
774                        .iter()
775                        .find(|f| f.keyframe_id_from == prev_id && f.keyframe_id_to == kf_id);
776                    match factor {
777                        Some(f) if f.delta.delta_time > 0.0 => {
778                            let prev_center = self
779                                .keyframes
780                                .iter()
781                                .find(|(id, _)| *id == prev_id)
782                                .expect("previous solve keyframe is registered")
783                                .1;
784                            let curr_center = self
785                                .keyframes
786                                .iter()
787                                .find(|(id, _)| *id == kf_id)
788                                .expect("current solve keyframe is registered")
789                                .1;
790                            (curr_center - prev_center) / f.delta.delta_time
791                        }
792                        _ => Vector3::zeros(),
793                    }
794                };
795                initial_states.insert(
796                    kf_id,
797                    KeyframeImuState {
798                        velocity_world: velocity,
799                        bias_gyro,
800                        bias_acc: bias_acc_seed,
801                    },
802                );
803            }
804            initial_states
805        };
806        let mut initial_states = seed_initial_states(&kf_ids, bias_gyro_seed);
807
808        // Validate that all registered keyframes have a pose in `map`.
809        for kf_id in &kf_ids {
810            let Some(kf) = map.keyframes.get(kf_id) else {
811                let err = MotionBasedViRejectionReason::MissingKeyframeData;
812                self.last_rejection = Some(err.clone());
813                return Err(err);
814            };
815            if kf.frame.pose.is_none() {
816                let err = MotionBasedViRejectionReason::MissingKeyframeData;
817                self.last_rejection = Some(err.clone());
818                return Err(err);
819            }
820        }
821
822        // Solve transactionally. The inertial BA helpers write refined poses
823        // into their map argument before returning, but post-solve velocity
824        // gates below may still reject the result. Keep those speculative
825        // poses on a clone and publish them only after every gate passes.
826        let mut candidate_map = map.clone();
827        // The visual map stores T_cw, while the IMU factors are expressed in
828        // body coordinates. EuRoC T_BS for cam0 is T_bc (camera/sensor to
829        // body), hence T_bw = T_bc * T_cw. This conversion is speculative and
830        // exists only on the solver clone; the tracked camera map is never
831        // overwritten with body poses.
832        for kf_id in &all_kf_ids {
833            let Some(pose) = candidate_map
834                .keyframes
835                .get_mut(kf_id)
836                .and_then(|kf| kf.frame.pose.as_mut())
837            else {
838                continue;
839            };
840            pose.world_to_camera = self.config.body_to_camera.compose(&pose.world_to_camera);
841        }
842
843        // Gyro-bias recovery (`estimate_gyro_bias`): run the rotation-only
844        // alignment over `candidate_map`'s just-converted body poses FIRST —
845        // before gravity/velocity recovery and before the staged solve.
846        // This is the classical first step ORB-SLAM3 / VINS-Mono run before
847        // gravity alignment: the rotation residual is entirely
848        // gravity-independent, so a wrong gyro bias leaves the SAME
849        // residual whether or not gravity is estimated (see
850        // `docs/motion_based_vi_alignment.md`'s "Gyro-bias recovery"
851        // section for the motivating real-data diagnosis). On success, the
852        // estimate replaces `bias_gyro_seed` for the REST of this attempt:
853        // the gravity/velocity alignment call below, the `initial_states`
854        // seeding above, and (via `initial_states`) any
855        // `BiasReleaseSchedule` Stage A fixed-bias solve.
856        let mut effective_bias_gyro = bias_gyro_seed;
857        let mut estimated_gyro_bias: Option<Vector3<f64>> = None;
858        if self.config.estimate_gyro_bias {
859            let alignment = estimate_gyro_bias_with_window(
860                &candidate_map,
861                &all_kf_ids,
862                preintegration_factors,
863                bias_gyro_seed,
864            );
865            let (alignment, window_ids) = match alignment {
866                Some(found) => found,
867                None => {
868                    self.last_gyro_bias_alignment = None;
869                    let err = MotionBasedViRejectionReason::GyroBiasEstimateDegenerate;
870                    self.last_rejection = Some(err.clone());
871                    return Err(err);
872                }
873            };
874            // Record the attempt BEFORE the magnitude gate below, mirroring
875            // `last_gravity_alignment`'s rationale: a rejected estimate is
876            // exactly as diagnostically interesting as an accepted one.
877            self.last_gyro_bias_alignment = Some(alignment);
878            let magnitude_rad_s = alignment.bias_gyro.norm();
879            if let Some(limit) = self.config.max_gyro_bias_magnitude_rad_s {
880                if magnitude_rad_s > limit {
881                    let err = MotionBasedViRejectionReason::GyroBiasOutOfRange {
882                        kf_id: window_ids.first().copied().unwrap_or(kf_ids[0]),
883                        magnitude_rad_s,
884                        limit_rad_s: limit,
885                    };
886                    self.last_rejection = Some(err.clone());
887                    return Err(err);
888                }
889            }
890            if window_ids.len() >= 2 {
891                kf_ids = window_ids;
892            }
893            effective_bias_gyro = alignment.bias_gyro;
894            estimated_gyro_bias = Some(alignment.bias_gyro);
895            initial_states = seed_initial_states(&kf_ids, effective_bias_gyro);
896        }
897
898        // Gravity-direction recovery (`estimate_gravity`): run the linear
899        // alignment over `candidate_map`'s just-converted body poses
900        // BEFORE dispatching to the inertial-only solver. On success, every
901        // in-window factor is fed to the solver with `gravity_world`
902        // overwritten to the estimate (instead of the configured value),
903        // and the finite-difference velocity seeds above are overwritten
904        // with the alignment's own velocities. See
905        // `docs/motion_based_vi_alignment.md`'s "Gravity-direction
906        // recovery" section for the motivating diagnosis and the full
907        // formulation.
908        let mut estimated_gravity: Option<Vector3<f64>> = None;
909        if self.config.estimate_gravity {
910            let expected_magnitude = self.config.gravity_world.norm();
911            let alignment = estimate_gravity_and_velocities(
912                &candidate_map,
913                &kf_ids,
914                preintegration_factors,
915                effective_bias_gyro,
916                bias_acc_seed,
917                expected_magnitude,
918            );
919            let alignment = match alignment {
920                Some(alignment) => alignment,
921                None => {
922                    self.last_gravity_alignment = None;
923                    let err = MotionBasedViRejectionReason::GravityEstimateDegenerate;
924                    self.last_rejection = Some(err.clone());
925                    return Err(err);
926                }
927            };
928            // Record the attempt BEFORE the observability gate below: a
929            // rejected estimate is exactly as diagnostically interesting as
930            // an accepted one (more so, on real data — see
931            // `docs/motion_based_vi_alignment.md`'s "Gravity-direction
932            // recovery" section), and every later raw-residual /
933            // NIS / velocity / bias gate rejection further down this
934            // function must not erase it either.
935            self.last_gravity_alignment = Some(alignment.clone());
936            let deviation_ratio = if expected_magnitude > 0.0 {
937                (alignment.raw_gravity_norm - expected_magnitude).abs() / expected_magnitude
938            } else {
939                f64::INFINITY
940            };
941            if !deviation_ratio.is_finite()
942                || deviation_ratio > self.config.max_gravity_norm_deviation_ratio
943            {
944                let err = MotionBasedViRejectionReason::GravityEstimateOutOfRange {
945                    raw_norm_mps2: alignment.raw_gravity_norm,
946                    expected_mps2: expected_magnitude,
947                    max_deviation_ratio: self.config.max_gravity_norm_deviation_ratio,
948                };
949                self.last_rejection = Some(err.clone());
950                return Err(err);
951            }
952            for (kf_id, velocity) in &alignment.velocities {
953                if let Some(state) = initial_states.get_mut(kf_id) {
954                    state.velocity_world = *velocity;
955                }
956            }
957            estimated_gravity = Some(alignment.gravity_world);
958        }
959        // In-window factors carrying the estimated gravity when
960        // `estimate_gravity` fired, otherwise the caller's factors
961        // unchanged (legacy path). Every downstream dispatch branch below
962        // solves against this slice instead of `preintegration_factors`
963        // directly.
964        let gravity_adjusted_factors: Option<Vec<ImuPreintegrationFactor>> =
965            estimated_gravity.map(|g| {
966                preintegration_factors
967                    .iter()
968                    .map(|f| {
969                        let mut adjusted = f.clone();
970                        adjusted.gravity_world = g;
971                        adjusted
972                    })
973                    .collect()
974            });
975        let solve_factors: &[ImuPreintegrationFactor] = gravity_adjusted_factors
976            .as_deref()
977            .unwrap_or(preintegration_factors);
978
979        // Dispatch, in priority order:
980        // 1. `!bias_free` (`BiasReleaseSchedule` Stage A / "velocity
981        //    stage"): bias is fixed at the seed regardless of `viba2` —
982        //    scale recovery needs free bias, so VIBA2 never runs here.
983        // 2. `bias_free` + `viba2` configured: the VIBA2 outer
984        //    scale-recovery loop (legacy path, or Stage B).
985        // 3. `bias_free`, no `viba2`: the standalone VIBA1 inertial-only
986        //    path (legacy path, or Stage B).
987        // All three return the same `MotionBasedViInitializationResult`
988        // shape; only the VIBA2 branch populates `scale_history` /
989        // `viba2_iterations_run`.
990        let result = if !bias_free {
991            let stats = run_inertial_only_vi_ba_with_options(
992                &mut candidate_map,
993                &kf_ids,
994                solve_factors,
995                &initial_states,
996                &self.config.ba_config,
997                false,
998            );
999            let stats = match stats {
1000                Some(s) => s,
1001                None => {
1002                    let any_in_window = solve_factors.iter().any(|f| {
1003                        kf_ids.contains(&f.keyframe_id_from) && kf_ids.contains(&f.keyframe_id_to)
1004                    });
1005                    let err = if any_in_window {
1006                        MotionBasedViRejectionReason::SolverFailed
1007                    } else {
1008                        MotionBasedViRejectionReason::NoUsableImuFactors
1009                    };
1010                    self.last_rejection = Some(err.clone());
1011                    return Err(err);
1012                }
1013            };
1014            MotionBasedViInitializationResult {
1015                keyframe_states: stats.keyframe_states,
1016                keyframe_ids: stats.keyframe_ids,
1017                imu_factors_used: stats.imu_factor_count,
1018                scale: 1.0,
1019                scale_history: Vec::new(),
1020                viba2_iterations_run: 0,
1021                trigger_translation_meters: self.cumulative_translation,
1022                ba_result: stats.ba_result,
1023                initial_cost_breakdown: stats.initial_cost_breakdown,
1024                final_cost_breakdown: stats.final_cost_breakdown,
1025                bias_released: false,
1026                estimated_gravity_world: estimated_gravity,
1027                estimated_gyro_bias,
1028            }
1029        } else if let Some(viba2_cfg) = self.config.viba2.clone() {
1030            let stats = run_viba2_inertial_with_scale(
1031                &mut candidate_map,
1032                &kf_ids,
1033                solve_factors,
1034                &initial_states,
1035                &viba2_cfg,
1036            );
1037            let stats = match stats {
1038                Some(s) => s,
1039                None => {
1040                    let any_in_window = solve_factors.iter().any(|f| {
1041                        kf_ids.contains(&f.keyframe_id_from) && kf_ids.contains(&f.keyframe_id_to)
1042                    });
1043                    let err = if any_in_window {
1044                        MotionBasedViRejectionReason::SolverFailed
1045                    } else {
1046                        MotionBasedViRejectionReason::NoUsableImuFactors
1047                    };
1048                    self.last_rejection = Some(err.clone());
1049                    return Err(err);
1050                }
1051            };
1052            MotionBasedViInitializationResult {
1053                keyframe_states: stats.keyframe_states,
1054                keyframe_ids: stats.keyframe_ids,
1055                imu_factors_used: stats.imu_factor_count,
1056                scale: stats.scale,
1057                scale_history: stats.scale_history,
1058                viba2_iterations_run: stats.outer_iterations_run,
1059                trigger_translation_meters: self.cumulative_translation,
1060                ba_result: stats.ba_result,
1061                initial_cost_breakdown: stats.initial_cost_breakdown,
1062                final_cost_breakdown: stats.final_cost_breakdown,
1063                bias_released: true,
1064                estimated_gravity_world: estimated_gravity,
1065                estimated_gyro_bias,
1066            }
1067        } else {
1068            let stats = run_inertial_only_vi_ba(
1069                &mut candidate_map,
1070                &kf_ids,
1071                solve_factors,
1072                &initial_states,
1073                &self.config.ba_config,
1074            );
1075            let stats = match stats {
1076                Some(s) => s,
1077                None => {
1078                    let any_in_window = solve_factors.iter().any(|f| {
1079                        kf_ids.contains(&f.keyframe_id_from) && kf_ids.contains(&f.keyframe_id_to)
1080                    });
1081                    let err = if any_in_window {
1082                        MotionBasedViRejectionReason::SolverFailed
1083                    } else {
1084                        MotionBasedViRejectionReason::NoUsableImuFactors
1085                    };
1086                    self.last_rejection = Some(err.clone());
1087                    return Err(err);
1088                }
1089            };
1090            MotionBasedViInitializationResult {
1091                keyframe_states: stats.keyframe_states,
1092                keyframe_ids: stats.keyframe_ids,
1093                imu_factors_used: stats.imu_factor_count,
1094                scale: 1.0,
1095                scale_history: Vec::new(),
1096                viba2_iterations_run: 0,
1097                trigger_translation_meters: self.cumulative_translation,
1098                ba_result: stats.ba_result,
1099                initial_cost_breakdown: stats.initial_cost_breakdown,
1100                final_cost_breakdown: stats.final_cost_breakdown,
1101                bias_released: true,
1102                estimated_gravity_world: estimated_gravity,
1103                estimated_gyro_bias,
1104            }
1105        };
1106
1107        let final_cost = &result.final_cost_breakdown;
1108        let rotation_exceeded = self
1109            .config
1110            .max_final_imu_rotation_residual_rms_rad
1111            .is_some_and(|limit| {
1112                final_cost
1113                    .imu_rotation_residual_rms_rad
1114                    .is_none_or(|value| !value.is_finite() || value > limit)
1115            });
1116        let velocity_exceeded = self
1117            .config
1118            .max_final_imu_velocity_residual_rms_mps
1119            .is_some_and(|limit| {
1120                final_cost
1121                    .imu_velocity_residual_rms_mps
1122                    .is_none_or(|value| !value.is_finite() || value > limit)
1123            });
1124        let position_exceeded = self
1125            .config
1126            .max_final_imu_position_residual_rms_meters
1127            .is_some_and(|limit| {
1128                final_cost
1129                    .imu_position_residual_rms_meters
1130                    .is_none_or(|value| !value.is_finite() || value > limit)
1131            });
1132        if rotation_exceeded || velocity_exceeded || position_exceeded {
1133            let err = MotionBasedViRejectionReason::ImuRawResidualOutOfRange {
1134                rotation_residual_rms_rad: final_cost.imu_rotation_residual_rms_rad,
1135                velocity_residual_rms_mps: final_cost.imu_velocity_residual_rms_mps,
1136                position_residual_rms_meters: final_cost.imu_position_residual_rms_meters,
1137                max_rotation_residual_rms_rad: self.config.max_final_imu_rotation_residual_rms_rad,
1138                max_velocity_residual_rms_mps: self.config.max_final_imu_velocity_residual_rms_mps,
1139                max_position_residual_rms_meters: self
1140                    .config
1141                    .max_final_imu_position_residual_rms_meters,
1142            };
1143            self.last_rejection = Some(err.clone());
1144            return Err(err);
1145        }
1146
1147        if let Some(limit) = self.config.max_final_imu_nis_per_dof {
1148            if let Some(normalized_nis_per_dof) = result
1149                .final_cost_breakdown
1150                .imu_normalized_squared_residual_per_dof
1151                .filter(|value| !value.is_finite() || *value > limit)
1152            {
1153                let err = MotionBasedViRejectionReason::ImuNisOutOfRange {
1154                    normalized_nis_per_dof,
1155                    rotation_residual_rms_rad: result
1156                        .final_cost_breakdown
1157                        .imu_rotation_residual_rms_rad,
1158                    velocity_residual_rms_mps: result
1159                        .final_cost_breakdown
1160                        .imu_velocity_residual_rms_mps,
1161                    position_residual_rms_meters: result
1162                        .final_cost_breakdown
1163                        .imu_position_residual_rms_meters,
1164                    limit,
1165                };
1166                self.last_rejection = Some(err.clone());
1167                return Err(err);
1168            }
1169        }
1170
1171        if let Some(limit) = self.config.max_velocity_magnitude_mps {
1172            let mut worst: Option<(u64, f64)> = None;
1173            for (kf_id, state) in &result.keyframe_states {
1174                let mag = state.velocity_world.norm();
1175                if mag > limit && worst.is_none_or(|(_, m)| mag > m) {
1176                    worst = Some((*kf_id, mag));
1177                }
1178            }
1179            if let Some((kf_id, mag)) = worst {
1180                let err = MotionBasedViRejectionReason::VelocityOutOfRange {
1181                    kf_id,
1182                    magnitude_mps: mag,
1183                    limit_mps: limit,
1184                };
1185                self.last_rejection = Some(err.clone());
1186                return Err(err);
1187            }
1188        }
1189        if let Some(limit) = self.config.max_gyro_bias_magnitude_rad_s {
1190            let worst = result
1191                .keyframe_states
1192                .iter()
1193                .map(|(kf_id, state)| (*kf_id, state.bias_gyro.norm()))
1194                .filter(|(_, magnitude)| *magnitude > limit)
1195                .max_by(|left, right| left.1.total_cmp(&right.1));
1196            if let Some((kf_id, magnitude_rad_s)) = worst {
1197                let err = MotionBasedViRejectionReason::GyroBiasOutOfRange {
1198                    kf_id,
1199                    magnitude_rad_s,
1200                    limit_rad_s: limit,
1201                };
1202                self.last_rejection = Some(err.clone());
1203                return Err(err);
1204            }
1205        }
1206        if let Some(limit) = self.config.max_accel_bias_magnitude_mps2 {
1207            let worst = result
1208                .keyframe_states
1209                .iter()
1210                .map(|(kf_id, state)| (*kf_id, state.bias_acc.norm()))
1211                .filter(|(_, magnitude)| *magnitude > limit)
1212                .max_by(|left, right| left.1.total_cmp(&right.1));
1213            if let Some((kf_id, magnitude_mps2)) = worst {
1214                let err = MotionBasedViRejectionReason::AccelBiasOutOfRange {
1215                    kf_id,
1216                    magnitude_mps2,
1217                    limit_mps2: limit,
1218                };
1219                self.last_rejection = Some(err.clone());
1220                return Err(err);
1221            }
1222        }
1223
1224        if result.bias_released {
1225            // Legacy path or Stage B: terminal success.
1226            self.completed = Some(result);
1227            self.last_rejection = None;
1228            Ok(self.completed.as_ref().expect("just inserted"))
1229        } else {
1230            // Stage A: cache the velocity-only result but stay non-terminal
1231            // so the caller keeps registering keyframes / translation
1232            // toward the bias-release gate.
1233            self.velocity_stage = Some(result);
1234            self.last_rejection = None;
1235            Ok(self.velocity_stage.as_ref().expect("just inserted"))
1236        }
1237    }
1238}
1239
1240/// Outcome of [`estimate_gravity_and_velocities`]: the world-frame gravity
1241/// vector recovered from IMU preintegration factors against FIXED visual
1242/// poses, plus the per-keyframe velocities that come along for free from
1243/// the same linear solve.
1244#[derive(Debug, Clone, PartialEq)]
1245pub struct GravityVelocityAlignment {
1246    /// Recovered gravity vector, magnitude-constrained to the caller's
1247    /// `expected_gravity_magnitude` via the VINS-Mono-style tangent-space
1248    /// refinement described on [`estimate_gravity_and_velocities`].
1249    pub gravity_world: Vector3<f64>,
1250    /// Norm of the UNCONSTRAINED linear solve's gravity estimate, before
1251    /// the magnitude-refinement pass. This is the observability check: a
1252    /// well-conditioned window recovers a norm near the true magnitude on
1253    /// its own, with no norm constraint imposed anywhere in that solve.
1254    /// Callers gate promotion on how close this sits to the expected
1255    /// magnitude (see
1256    /// [`MotionBasedViInitializerConfig::max_gravity_norm_deviation_ratio`]).
1257    pub raw_gravity_norm: f64,
1258    /// Per-keyframe world-frame velocities from the final refinement
1259    /// iteration (or from the unconstrained solve, on the plain
1260    /// scale-to-norm fallback — see the function doc comment). Keyed by
1261    /// keyframe id; only keyframes included in the (possibly capped, see
1262    /// below) alignment window are present.
1263    pub velocities: BTreeMap<u64, Vector3<f64>>,
1264    /// RMS of the stacked position + velocity preintegration residual (6
1265    /// scalar components per in-window factor) evaluated at the final
1266    /// `(gravity_world, velocities)` estimate. Mixes position (m) and
1267    /// velocity (m/s) residual components into one scalar, so treat as a
1268    /// relative diagnostic rather than a physically-calibrated quantity —
1269    /// the initializer's actual promotion decision continues to rely on
1270    /// the existing raw-residual gates, evaluated by the solver AFTER this
1271    /// alignment feeds it the estimated gravity.
1272    pub mean_residual_after: f64,
1273    /// Number of keyframes in the (possibly window-capped, see
1274    /// `MAX_ALIGNMENT_WINDOW` on [`estimate_gravity_and_velocities`])
1275    /// alignment window this estimate was solved over. Diagnostic only —
1276    /// lets a caller logging [`MotionBasedViInitializer::last_gravity_alignment`]
1277    /// distinguish "recovered from 10 well-spaced keyframes" from "recovered
1278    /// from the bare minimum of 2".
1279    pub window_keyframes: usize,
1280}
1281
1282/// One IMU preintegration factor's contribution to the gravity/velocity
1283/// alignment's linear system, precomputed once so both the unconstrained
1284/// solve, the tangent-space refinement, and the final residual check can
1285/// share it without re-deriving the per-factor geometry each time.
1286struct AlignmentFactorRow {
1287    /// Index (into the alignment's local keyframe ordering) of the
1288    /// factor's `keyframe_id_from`.
1289    idx_from: usize,
1290    /// Index of `keyframe_id_to`.
1291    idx_to: usize,
1292    delta_time: f64,
1293    /// `(p_j - p_i) - R_wb_i * Δp_ij` — the position equation's known
1294    /// right-hand side once `(v_i, g)` are moved to the left. See the
1295    /// function doc comment for the full derivation.
1296    rhs_position: Vector3<f64>,
1297    /// `R_wb_i * Δv_ij` — the velocity equation's known right-hand side.
1298    rhs_velocity: Vector3<f64>,
1299}
1300
1301/// Recover the world-frame gravity vector and per-keyframe velocities from
1302/// a window of IMU preintegration factors evaluated against FIXED visual
1303/// body poses (`map`'s poses are assumed already converted to
1304/// world-to-body, exactly as [`MotionBasedViInitializer::try_initialize_with_bias_seed`]'s
1305/// `candidate_map` conversion produces).
1306///
1307/// This is the missing piece that lets the motion-based initializer
1308/// recover from an identity-seeded (sub)map whose world frame has gravity
1309/// pointing in an arbitrary direction: rather than trusting
1310/// `expected_gravity_magnitude`'s DIRECTION (only the magnitude is used,
1311/// as the physical constant the recovered vector must match), the world
1312/// frame's actual gravity direction is estimated from the IMU evidence
1313/// itself. See `docs/motion_based_vi_alignment.md`'s "Gravity-direction
1314/// recovery" section for the full motivating diagnosis.
1315///
1316/// ## Formulation
1317///
1318/// With poses known (fixed), the preintegration relations (Forster et al.
1319/// 2017; ORB-SLAM3 inertial-only MAP) become LINEAR in the unknowns
1320/// `x = [v_1 .. v_N, g]` (all in world frame), one keyframe velocity per
1321/// window keyframe plus the shared gravity vector:
1322///
1323/// * Position: `v_i · Δt + ½ · g · Δt² = (p_j − p_i) − R_wb_i · Δp_ij`
1324/// * Velocity: `−v_i + v_j − g · Δt = R_wb_i · Δv_ij`
1325///
1326/// where `R_wb_i` is keyframe `i`'s body-to-world rotation, `Δp_ij` /
1327/// `Δv_ij` are the bias-corrected preintegrated deltas (first-order
1328/// corrected at `(bias_gyro_seed, bias_acc_seed)` via
1329/// [`crate::imu_preintegration::ImuPreintegratedDelta::corrected`] when
1330/// the delta carries bias Jacobians, a no-op correction otherwise), and
1331/// `Δt` is the factor's `delta_time`. Each factor contributes 6 rows; the
1332/// window is capped to the most recent `MAX_ALIGNMENT_WINDOW` keyframes
1333/// (currently 10) since a dense SVD solve over the full un-capped window
1334/// is unnecessary — a handful of well-spaced factors already fully
1335/// constrains 3-DoF gravity, and 10 keeps the dense system small
1336/// regardless of how long a [`BiasReleaseSchedule`] Stage A window grows
1337/// while awaiting its release gate.
1338///
1339/// ## Norm-constrained refinement
1340///
1341/// The unconstrained least-squares solve above (via `nalgebra`'s SVD) is
1342/// evaluated first; its gravity estimate's norm (`raw_gravity_norm`) is
1343/// the observability check callers gate on. The vector is then refined to
1344/// match `expected_gravity_magnitude` exactly using the VINS-Mono
1345/// tangent-space parameterization (Qin & Shen 2018, eq. 7-9):
1346/// `g = mag · normalize(ĝ + w1·b1 + w2·b2)` where `(b1, b2)` is an
1347/// orthonormal basis tangent to the current unit estimate `ĝ`. Each
1348/// iteration re-solves the linear system with `g`'s 3 free components
1349/// replaced by the 2 tangent coordinates `(w1, w2)`, updates `ĝ`, and
1350/// rebuilds the tangent basis; 4 iterations are run unconditionally
1351/// (empirically sufficient for this magnitude of nonlinearity). If any
1352/// iteration's solve fails (singular system) or produces a non-finite
1353/// update, refinement stops early and the FALLBACK — a plain
1354/// scale-to-norm of the unconstrained estimate (`mag · ĝ_raw`), paired
1355/// with the unconstrained solve's own velocities — is returned instead.
1356/// This fallback is deliberately the ONLY plain-rescale path: it is never
1357/// taken when the tangent iteration converges.
1358///
1359/// Returns `None` on degeneracy: fewer than 2 usable in-window factors
1360/// (after applying the window cap and requiring `delta_time > 0`), any
1361/// windowed keyframe missing its pose, or the unconstrained solve itself
1362/// producing a non-finite / near-zero gravity vector.
1363pub fn estimate_gravity_and_velocities(
1364    map: &VisualMap,
1365    keyframe_ids: &[u64],
1366    factors: &[ImuPreintegrationFactor],
1367    bias_gyro_seed: Vector3<f64>,
1368    bias_acc_seed: Vector3<f64>,
1369    expected_gravity_magnitude: f64,
1370) -> Option<GravityVelocityAlignment> {
1371    const MAX_ALIGNMENT_WINDOW: usize = 10;
1372    const REFINEMENT_ITERATIONS: usize = 4;
1373
1374    if !expected_gravity_magnitude.is_finite() || expected_gravity_magnitude <= 0.0 {
1375        return None;
1376    }
1377
1378    let mut ids: Vec<u64> = keyframe_ids.to_vec();
1379    ids.sort_unstable();
1380    ids.dedup();
1381    if ids.len() > MAX_ALIGNMENT_WINDOW {
1382        let start = ids.len() - MAX_ALIGNMENT_WINDOW;
1383        ids = ids[start..].to_vec();
1384    }
1385    if ids.len() < 2 {
1386        return None;
1387    }
1388    let in_window: BTreeSet<u64> = ids.iter().copied().collect();
1389    let index_of: BTreeMap<u64, usize> =
1390        ids.iter().enumerate().map(|(idx, id)| (*id, idx)).collect();
1391
1392    // Body-to-world rotation (`R_wb_i`) and world-frame body position
1393    // (`p_i`) per windowed keyframe. `map`'s poses are already `T_bw`
1394    // (world-to-body) at the call sites in this module.
1395    let mut rotation_body_to_world: BTreeMap<u64, UnitQuaternion<f64>> = BTreeMap::new();
1396    let mut position_world: BTreeMap<u64, Vector3<f64>> = BTreeMap::new();
1397    for id in &ids {
1398        let pose = map.keyframes.get(id)?.frame.pose.as_ref()?;
1399        let world_from_body = pose.camera_to_world();
1400        rotation_body_to_world.insert(*id, world_from_body.rotation);
1401        position_world.insert(*id, world_from_body.translation);
1402    }
1403
1404    let mut rows: Vec<AlignmentFactorRow> = Vec::new();
1405    for factor in factors {
1406        if !in_window.contains(&factor.keyframe_id_from)
1407            || !in_window.contains(&factor.keyframe_id_to)
1408        {
1409            continue;
1410        }
1411        let delta_time = factor.delta.delta_time;
1412        if delta_time.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {
1413            continue;
1414        }
1415        let idx_from = *index_of.get(&factor.keyframe_id_from).expect("windowed id");
1416        let idx_to = *index_of.get(&factor.keyframe_id_to).expect("windowed id");
1417        let r_i = *rotation_body_to_world
1418            .get(&factor.keyframe_id_from)
1419            .expect("windowed id");
1420        let p_i = *position_world
1421            .get(&factor.keyframe_id_from)
1422            .expect("windowed id");
1423        let p_j = *position_world
1424            .get(&factor.keyframe_id_to)
1425            .expect("windowed id");
1426        let (_, delta_velocity, delta_position) =
1427            factor.delta.corrected(&bias_gyro_seed, &bias_acc_seed);
1428        rows.push(AlignmentFactorRow {
1429            idx_from,
1430            idx_to,
1431            delta_time,
1432            rhs_position: (p_j - p_i) - r_i.transform_vector(&delta_position),
1433            rhs_velocity: r_i.transform_vector(&delta_velocity),
1434        });
1435    }
1436    if rows.len() < 2 {
1437        return None;
1438    }
1439
1440    let num_kf = ids.len();
1441    let num_rows = 6 * rows.len();
1442
1443    // Unconstrained solve: unknowns `[v_1 .. v_N, g]`.
1444    let mut a = DMatrix::<f64>::zeros(num_rows, 3 * num_kf + 3);
1445    let mut b = DVector::<f64>::zeros(num_rows);
1446    for (r, row) in rows.iter().enumerate() {
1447        let base = 6 * r;
1448        for k in 0..3 {
1449            a[(base + k, 3 * row.idx_from + k)] = row.delta_time;
1450            a[(base + k, 3 * num_kf + k)] = 0.5 * row.delta_time * row.delta_time;
1451            b[base + k] = row.rhs_position[k];
1452
1453            a[(base + 3 + k, 3 * row.idx_from + k)] = -1.0;
1454            a[(base + 3 + k, 3 * row.idx_to + k)] = 1.0;
1455            a[(base + 3 + k, 3 * num_kf + k)] = -row.delta_time;
1456            b[base + 3 + k] = row.rhs_velocity[k];
1457        }
1458    }
1459    let raw_solution = a.svd(true, true).solve(&b, 1.0e-9).ok()?;
1460    let raw_gravity = Vector3::new(
1461        raw_solution[3 * num_kf],
1462        raw_solution[3 * num_kf + 1],
1463        raw_solution[3 * num_kf + 2],
1464    );
1465    let raw_gravity_norm = raw_gravity.norm();
1466    if !raw_gravity_norm.is_finite() || raw_gravity_norm < 1.0e-6 {
1467        return None;
1468    }
1469    let raw_velocities: Vec<Vector3<f64>> = (0..num_kf)
1470        .map(|k| {
1471            Vector3::new(
1472                raw_solution[3 * k],
1473                raw_solution[3 * k + 1],
1474                raw_solution[3 * k + 2],
1475            )
1476        })
1477        .collect();
1478
1479    // Norm-constrained refinement (VINS-Mono tangent-space iteration).
1480    // Falls back to a plain scale-to-norm of `raw_gravity` (paired with
1481    // `raw_velocities`) the moment any iteration fails to solve or
1482    // produces a non-finite update.
1483    let mag = expected_gravity_magnitude;
1484    let mut g_hat = raw_gravity / raw_gravity_norm;
1485    let mut velocities_final = raw_velocities;
1486    let mut refined = false;
1487    for _ in 0..REFINEMENT_ITERATIONS {
1488        let (b1, b2) = tangent_basis(&g_hat);
1489        let g0 = mag * g_hat;
1490        let mut a2 = DMatrix::<f64>::zeros(num_rows, 3 * num_kf + 2);
1491        let mut b2vec = DVector::<f64>::zeros(num_rows);
1492        for (r, row) in rows.iter().enumerate() {
1493            let base = 6 * r;
1494            for k in 0..3 {
1495                a2[(base + k, 3 * row.idx_from + k)] = row.delta_time;
1496                a2[(base + k, 3 * num_kf)] = 0.5 * row.delta_time * row.delta_time * mag * b1[k];
1497                a2[(base + k, 3 * num_kf + 1)] =
1498                    0.5 * row.delta_time * row.delta_time * mag * b2[k];
1499                b2vec[base + k] =
1500                    row.rhs_position[k] - 0.5 * row.delta_time * row.delta_time * g0[k];
1501
1502                a2[(base + 3 + k, 3 * row.idx_from + k)] = -1.0;
1503                a2[(base + 3 + k, 3 * row.idx_to + k)] = 1.0;
1504                a2[(base + 3 + k, 3 * num_kf)] = -row.delta_time * mag * b1[k];
1505                a2[(base + 3 + k, 3 * num_kf + 1)] = -row.delta_time * mag * b2[k];
1506                b2vec[base + 3 + k] = row.rhs_velocity[k] + row.delta_time * g0[k];
1507            }
1508        }
1509        let Ok(solution) = a2.svd(true, true).solve(&b2vec, 1.0e-9) else {
1510            break;
1511        };
1512        let w1 = solution[3 * num_kf];
1513        let w2 = solution[3 * num_kf + 1];
1514        if !w1.is_finite() || !w2.is_finite() {
1515            break;
1516        }
1517        let candidate = g_hat + w1 * b1 + w2 * b2;
1518        let candidate_norm = candidate.norm();
1519        if !candidate_norm.is_finite() || candidate_norm < 1.0e-9 {
1520            break;
1521        }
1522        g_hat = candidate / candidate_norm;
1523        velocities_final = (0..num_kf)
1524            .map(|k| Vector3::new(solution[3 * k], solution[3 * k + 1], solution[3 * k + 2]))
1525            .collect();
1526        refined = true;
1527    }
1528
1529    let gravity_world = if refined {
1530        mag * g_hat
1531    } else {
1532        mag * (raw_gravity / raw_gravity_norm)
1533    };
1534
1535    let mut residual_sum_sq = 0.0;
1536    for row in &rows {
1537        let v_i = velocities_final[row.idx_from];
1538        let v_j = velocities_final[row.idx_to];
1539        let r_pos = (v_i * row.delta_time + 0.5 * row.delta_time * row.delta_time * gravity_world)
1540            - row.rhs_position;
1541        let r_vel = (-v_i + v_j - row.delta_time * gravity_world) - row.rhs_velocity;
1542        residual_sum_sq += r_pos.norm_squared() + r_vel.norm_squared();
1543    }
1544    let mean_residual_after = (residual_sum_sq / (6.0 * rows.len() as f64)).sqrt();
1545
1546    let velocities: BTreeMap<u64, Vector3<f64>> = ids
1547        .iter()
1548        .enumerate()
1549        .map(|(k, id)| (*id, velocities_final[k]))
1550        .collect();
1551
1552    Some(GravityVelocityAlignment {
1553        gravity_world,
1554        raw_gravity_norm,
1555        velocities,
1556        mean_residual_after,
1557        window_keyframes: num_kf,
1558    })
1559}
1560
1561/// Orthonormal basis `(b1, b2)` tangent to the unit vector `g_hat`, used
1562/// by [`estimate_gravity_and_velocities`]'s norm-constrained refinement
1563/// (VINS-Mono style: any basis spanning the tangent plane works, since the
1564/// refinement re-derives it fresh from the updated `g_hat` every
1565/// iteration).
1566fn tangent_basis(g_hat: &Vector3<f64>) -> (Vector3<f64>, Vector3<f64>) {
1567    let reference = if g_hat.x.abs() < 0.9 {
1568        Vector3::x()
1569    } else {
1570        Vector3::y()
1571    };
1572    let b1 = g_hat.cross(&reference).normalize();
1573    let b2 = g_hat.cross(&b1).normalize();
1574    (b1, b2)
1575}
1576
1577/// Outcome of [`estimate_gyro_bias`]: the shared gyro bias recovered from
1578/// ROTATION-ONLY alignment against a window's fixed visual poses, run
1579/// BEFORE gravity/velocity alignment — see `docs/motion_based_vi_alignment.md`'s
1580/// "Gyro-bias recovery" section for the motivating real-data diagnosis and
1581/// the full derivation.
1582#[derive(Debug, Clone, Copy, PartialEq)]
1583pub struct GyroBiasAlignment {
1584    /// Recovered gyro bias, in the same units/frame as
1585    /// [`ImuPreintegrationFactor::delta`]'s bias linearisation (rad/s,
1586    /// body frame).
1587    pub bias_gyro: Vector3<f64>,
1588    /// Number of Gauss-Newton iterations actually run (capped at 5,
1589    /// possibly fewer on early convergence — see [`estimate_gyro_bias`]).
1590    pub iterations: usize,
1591    /// RMS of the per-factor rotation residual `Log(ΔR_corrected(b_g_seed)⁻¹
1592    /// · R_iᵀ · R_j)` evaluated at the CALLER's `bias_gyro_seed`, before any
1593    /// Gauss-Newton update. Diagnostic: compare against
1594    /// `rotation_residual_rms_after` to see how much the alignment moved
1595    /// the residual.
1596    pub rotation_residual_rms_before: f64,
1597    /// RMS of the same rotation residual evaluated at the FINAL
1598    /// `bias_gyro` estimate.
1599    pub rotation_residual_rms_after: f64,
1600}
1601
1602/// Recover the shared gyro bias from a window of IMU preintegration
1603/// factors' ROTATION component evaluated against FIXED visual body poses
1604/// (`map`'s poses are assumed already converted to world-to-body, exactly
1605/// as [`MotionBasedViInitializer::try_initialize_with_bias_seed`]'s
1606/// `candidate_map` conversion produces — same precondition as
1607/// [`estimate_gravity_and_velocities`]).
1608///
1609/// ## Formulation
1610///
1611/// This is the classical first step of ORB-SLAM3's inertial-only MAP
1612/// estimator and VINS-Mono's IMU initialization (Qin & Shen 2018, §5.2):
1613/// with poses known (fixed), the ONLY unknown left in the rotation-only
1614/// preintegration relation is the gyro bias `b_g`. Per in-window
1615/// consecutive factor `i→j`, define the residual
1616///
1617/// `r_ij(b_g) = Log( ΔR_ij(b_g)⁻¹ · R_iᵀ · R_j )`
1618///
1619/// where `ΔR_ij(b_g)` is [`crate::imu_preintegration::ImuPreintegratedDelta::corrected`]'s
1620/// bias-corrected rotation at `b_g` (accelerometer bias held at the
1621/// factor's own linearisation point — this residual has no accelerometer
1622/// dependence) and `R_i`, `R_j` are the windowed keyframes' body-to-world
1623/// rotations. Gauss-Newton solves `min_{b_g} Σ ||r_ij(b_g)||²` using the
1624/// preintegrator's own `∂(Log ΔR)/∂b_g` Jacobian
1625/// ([`crate::imu_preintegration::ImuPreintegratedDelta::j_rotation_bg`]) as
1626/// the (first-order, and thus approximately step-invariant near the
1627/// linearisation point) local model per iteration:
1628///
1629/// `(Σ Jᵢⱼᵀ Jᵢⱼ) · δ = Σ Jᵢⱼᵀ · r_ij(b_g)`, then `b_g ← b_g + δ`
1630///
1631/// re-evaluating the exact (nonlinear) residual `r_ij` at the updated `b_g`
1632/// each iteration. Up to 5 iterations run, stopping early once `‖δ‖ <
1633/// 1e-10`. This is the same normal-equation shape used by VINS-Mono's
1634/// `solveGyroscopeBias` (there run as a single linear solve at `b_g = 0`);
1635/// iterating a few times here lets the alignment start from a nonzero
1636/// `bias_gyro_seed` and re-linearise around the improving estimate.
1637///
1638/// The window is capped to the most recent 10 keyframes (mirroring
1639/// [`estimate_gravity_and_velocities`]'s `MAX_ALIGNMENT_WINDOW`). Returns
1640/// `None` on degeneracy: fewer than 2 usable in-window factors (missing
1641/// keyframe poses, non-positive `delta_time`, or a factor connecting two
1642/// keyframes outside the window all count as unusable), or a singular
1643/// normal-equation system on the very first iteration.
1644pub fn estimate_gyro_bias(
1645    map: &VisualMap,
1646    keyframe_ids: &[u64],
1647    factors: &[ImuPreintegrationFactor],
1648    bias_gyro_seed: Vector3<f64>,
1649) -> Option<GyroBiasAlignment> {
1650    estimate_gyro_bias_with_window(map, keyframe_ids, factors, bias_gyro_seed)
1651        .map(|(alignment, _)| alignment)
1652}
1653
1654fn estimate_gyro_bias_with_window(
1655    map: &VisualMap,
1656    keyframe_ids: &[u64],
1657    factors: &[ImuPreintegrationFactor],
1658    bias_gyro_seed: Vector3<f64>,
1659) -> Option<(GyroBiasAlignment, Vec<u64>)> {
1660    const MAX_ALIGNMENT_WINDOW: usize = 5;
1661    const MIN_ALIGNMENT_WINDOW: usize = 3;
1662
1663    let mut ids: Vec<u64> = keyframe_ids.to_vec();
1664    ids.sort_unstable();
1665    ids.dedup();
1666    if ids.len() < MIN_ALIGNMENT_WINDOW {
1667        let alignment = estimate_gyro_bias_on_ids(map, &ids, factors, bias_gyro_seed)?;
1668        return Some((alignment, ids));
1669    }
1670
1671    let max_w = MAX_ALIGNMENT_WINDOW.min(ids.len());
1672    let mut best: Option<(GyroBiasAlignment, Vec<u64>)> = None;
1673    for w in MIN_ALIGNMENT_WINDOW..=max_w {
1674        for start in 0..=ids.len() - w {
1675            let subset = ids[start..start + w].to_vec();
1676            let Some(alignment) = estimate_gyro_bias_on_ids(map, &subset, factors, bias_gyro_seed)
1677            else {
1678                continue;
1679            };
1680            if best.as_ref().is_none_or(|(current, _)| {
1681                alignment.rotation_residual_rms_after < current.rotation_residual_rms_after
1682            }) {
1683                best = Some((alignment, subset));
1684            }
1685        }
1686    }
1687    best.or_else(|| {
1688        let alignment = estimate_gyro_bias_on_ids(map, &ids, factors, bias_gyro_seed)?;
1689        Some((alignment, ids))
1690    })
1691}
1692
1693fn estimate_gyro_bias_on_ids(
1694    map: &VisualMap,
1695    ids: &[u64],
1696    factors: &[ImuPreintegrationFactor],
1697    bias_gyro_seed: Vector3<f64>,
1698) -> Option<GyroBiasAlignment> {
1699    const MAX_ITERATIONS: usize = 5;
1700    const CONVERGENCE_STEP_NORM: f64 = 1.0e-10;
1701    if ids.len() < 2 {
1702        return None;
1703    }
1704    let in_window: BTreeSet<u64> = ids.iter().copied().collect();
1705
1706    let mut rotation_body_to_world: BTreeMap<u64, UnitQuaternion<f64>> = BTreeMap::new();
1707    for id in ids {
1708        let pose = map.keyframes.get(id)?.frame.pose.as_ref()?;
1709        rotation_body_to_world.insert(*id, pose.camera_to_world().rotation);
1710    }
1711
1712    struct GyroBiasRow {
1713        r_i: UnitQuaternion<f64>,
1714        r_j: UnitQuaternion<f64>,
1715        delta_index: usize,
1716    }
1717    let mut rows: Vec<GyroBiasRow> = Vec::new();
1718    let mut deltas: Vec<&ImuPreintegratedDelta> = Vec::new();
1719    for factor in factors {
1720        if !in_window.contains(&factor.keyframe_id_from)
1721            || !in_window.contains(&factor.keyframe_id_to)
1722        {
1723            continue;
1724        }
1725        if factor.delta.delta_time <= 0.0 {
1726            continue;
1727        }
1728        let Some(&r_i) = rotation_body_to_world.get(&factor.keyframe_id_from) else {
1729            continue;
1730        };
1731        let Some(&r_j) = rotation_body_to_world.get(&factor.keyframe_id_to) else {
1732            continue;
1733        };
1734        deltas.push(&factor.delta);
1735        rows.push(GyroBiasRow {
1736            r_i,
1737            r_j,
1738            delta_index: deltas.len() - 1,
1739        });
1740    }
1741    if rows.len() < 2 {
1742        return None;
1743    }
1744
1745    // Rotation residual at a given gyro bias: `Log(ΔR_corrected(b_g)⁻¹ ·
1746    // R_iᵀ · R_j)`, matching `ImuPreintegrationFactor::residual_corrected_internal`'s
1747    // `r_rot` sign/ordering convention exactly. Accelerometer bias is held
1748    // at each delta's own linearisation point (`δb_a = 0`) since this
1749    // residual has no accelerometer dependence.
1750    let residual_at = |bias_gyro: &Vector3<f64>| -> Vec<Vector3<f64>> {
1751        rows.iter()
1752            .map(|row| {
1753                let delta = deltas[row.delta_index];
1754                let (delta_rot, _, _) = delta.corrected(bias_gyro, &delta.bias_acc_linearisation);
1755                let q_rel = delta_rot.quaternion().inverse() * row.r_i.inverse() * row.r_j;
1756                q_rel.scaled_axis()
1757            })
1758            .collect()
1759    };
1760    let rms = |residuals: &[Vector3<f64>]| -> f64 {
1761        let sum_sq: f64 = residuals.iter().map(|r| r.norm_squared()).sum();
1762        (sum_sq / (3.0 * residuals.len() as f64)).sqrt()
1763    };
1764
1765    let residuals_before = residual_at(&bias_gyro_seed);
1766    let rotation_residual_rms_before = rms(&residuals_before);
1767
1768    let mut bias_gyro = bias_gyro_seed;
1769    let mut residuals_current = residuals_before;
1770    let mut iterations = 0usize;
1771    for iteration in 0..MAX_ITERATIONS {
1772        let mut ata = Matrix3::zeros();
1773        let mut atb = Vector3::zeros();
1774        for (row, residual) in rows.iter().zip(residuals_current.iter()) {
1775            let j = deltas[row.delta_index].j_rotation_bg;
1776            ata += j.transpose() * j;
1777            atb += j.transpose() * *residual;
1778        }
1779        let Some(ata_inv) = ata.try_inverse() else {
1780            if iteration == 0 {
1781                return None;
1782            }
1783            break;
1784        };
1785        let delta_step = ata_inv * atb;
1786        if !delta_step.iter().all(|v| v.is_finite()) {
1787            if iteration == 0 {
1788                return None;
1789            }
1790            break;
1791        }
1792        bias_gyro += delta_step;
1793        iterations += 1;
1794        residuals_current = residual_at(&bias_gyro);
1795        if delta_step.norm() < CONVERGENCE_STEP_NORM {
1796            break;
1797        }
1798    }
1799    let rotation_residual_rms_after = rms(&residuals_current);
1800
1801    Some(GyroBiasAlignment {
1802        bias_gyro,
1803        iterations,
1804        rotation_residual_rms_before,
1805        rotation_residual_rms_after,
1806    })
1807}
1808
1809#[cfg(test)]
1810mod tests {
1811    use super::*;
1812
1813    use nalgebra::{Point3, UnitQuaternion};
1814    use visloc_core::geometry::{Pose, SO3};
1815    use visloc_core::types::{Camera, Frame, Keyframe, VisualMap};
1816
1817    use crate::imu_preintegration::ImuPreintegratedDelta;
1818
1819    fn pinhole_camera() -> Camera {
1820        Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0)
1821    }
1822
1823    fn pose_at_world_center(c: Vector3<f64>) -> Pose {
1824        // World-to-camera with identity orientation: t = -R·C = -C.
1825        let r = UnitQuaternion::identity();
1826        Pose::from_world_to_camera(r, -r.transform_vector(&c))
1827    }
1828
1829    fn synthetic_seed() -> VisualInertialInitializationResult {
1830        VisualInertialInitializationResult {
1831            gravity_world: Vector3::new(0.0, 9.81, 0.0),
1832            initial_rotation_body_to_world: UnitQuaternion::identity(),
1833            initial_velocity_world: Vector3::zeros(),
1834            bias_gyro: Vector3::zeros(),
1835            bias_acc: Vector3::zeros(),
1836            samples_consumed: 2000,
1837            duration_seconds: 1.0,
1838            gyro_std: Vector3::zeros(),
1839            accel_std: Vector3::zeros(),
1840            mean_accel_magnitude: 9.81,
1841        }
1842    }
1843
1844    fn no_acceleration_factor(
1845        from_id: u64,
1846        to_id: u64,
1847        delta_t: f64,
1848        gravity: Vector3<f64>,
1849    ) -> ImuPreintegrationFactor {
1850        // Synthetic factor for an identity-oriented body with NO
1851        // proper acceleration (i.e., stationary or constant-velocity
1852        // in world frame). The IMU still senses gravity as specific
1853        // force, so the pre-integrated body-frame deltas are:
1854        //   ΔR = identity
1855        //   Δv = -g · Δt
1856        //   Δp = -0.5 · g · Δt²
1857        // With these, the residual
1858        //   r_v = R_b←w · (v_j - v_i - g·Δt) - Δv
1859        //       = (v_j - v_i - g·Δt) + g·Δt = v_j - v_i
1860        // is exactly satisfied for stationary AND for constant-velocity
1861        // motion (because the IMU integration's gravity term cancels the
1862        // residual's gravity term), as required for the "no proper
1863        // acceleration" synthetic scenarios used in these unit tests.
1864        let mut delta = ImuPreintegratedDelta::identity();
1865        delta.delta_time = delta_t;
1866        delta.delta_velocity = -gravity * delta_t;
1867        delta.delta_position = -0.5 * gravity * delta_t * delta_t;
1868        ImuPreintegrationFactor {
1869            keyframe_id_from: from_id,
1870            keyframe_id_to: to_id,
1871            delta,
1872            gravity_world: gravity,
1873            weight_position: 1.0,
1874            weight_velocity: 1.0,
1875            weight_rotation: 1.0,
1876        }
1877    }
1878
1879    /// Like [`no_acceleration_factor`] but decouples the TRUE gravity baked
1880    /// into the synthetic `(Δv, Δp)` from the ASSUMED gravity stamped onto
1881    /// `ImuPreintegrationFactor::gravity_world`. Models the diagnosed
1882    /// real-data bug directly: the physical IMU evidence is ground truth
1883    /// (built from `true_gravity`), while the factor's `gravity_world` is
1884    /// whatever the caller's (possibly wrong) config assumes — exactly what
1885    /// the legacy (`estimate_gravity: false`) path feeds the solver
1886    /// verbatim, and what the `estimate_gravity: true` path OVERWRITES with
1887    /// its own recovered estimate before solving (see
1888    /// `estimate_gravity_and_velocities`'s call site in
1889    /// `try_initialize_with_bias_seed`).
1890    fn no_acceleration_factor_with_assumed_gravity(
1891        from_id: u64,
1892        to_id: u64,
1893        delta_t: f64,
1894        true_gravity: Vector3<f64>,
1895        assumed_gravity: Vector3<f64>,
1896    ) -> ImuPreintegrationFactor {
1897        let mut delta = ImuPreintegratedDelta::identity();
1898        delta.delta_time = delta_t;
1899        delta.delta_velocity = -true_gravity * delta_t;
1900        delta.delta_position = -0.5 * true_gravity * delta_t * delta_t;
1901        ImuPreintegrationFactor {
1902            keyframe_id_from: from_id,
1903            keyframe_id_to: to_id,
1904            delta,
1905            gravity_world: assumed_gravity,
1906            weight_position: 1.0,
1907            weight_velocity: 1.0,
1908            weight_rotation: 1.0,
1909        }
1910    }
1911
1912    /// Build a `num_keyframes`-long map of identity-oriented keyframes on a
1913    /// straight-line, constant-world-velocity trajectory `p_i = velocity *
1914    /// i * dt`. Generalises [`build_constant_velocity_map`] (which is
1915    /// pinned to unit-speed +x motion) to an arbitrary off-axis velocity,
1916    /// needed so the gravity/velocity alignment tests below can exercise a
1917    /// trajectory that is not co-linear with the true gravity vector under
1918    /// test.
1919    fn build_map_at_velocity(num_keyframes: usize, dt: f64, velocity: Vector3<f64>) -> VisualMap {
1920        let mut map = VisualMap::new();
1921        let camera = pinhole_camera();
1922        map.cameras.insert(camera.id, camera.clone());
1923        for i in 0..num_keyframes {
1924            let center = velocity * (i as f64) * dt;
1925            let pose = pose_at_world_center(center);
1926            let frame_id = (i as u64) + 1;
1927            let mut frame = Frame::new(frame_id, camera.id);
1928            frame.pose = Some(pose);
1929            let kf = Keyframe {
1930                frame,
1931                observations: Vec::new(),
1932            };
1933            map.keyframes.insert(frame_id, kf);
1934        }
1935        map
1936    }
1937
1938    fn build_constant_velocity_map(num_keyframes: usize) -> VisualMap {
1939        let mut map = VisualMap::new();
1940        let camera = pinhole_camera();
1941        map.cameras.insert(camera.id, camera.clone());
1942        for i in 0..num_keyframes {
1943            let center = Vector3::new(i as f64, 0.0, 0.0);
1944            let pose = pose_at_world_center(center);
1945            let frame_id = (i as u64) + 1;
1946            let mut frame = Frame::new(frame_id, camera.id);
1947            frame.pose = Some(pose);
1948            let kf = Keyframe {
1949                frame,
1950                observations: Vec::new(),
1951            };
1952            map.keyframes.insert(frame_id, kf);
1953        }
1954        map
1955    }
1956
1957    #[test]
1958    fn trigger_blocked_until_keyframe_threshold_is_met() {
1959        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
1960            min_keyframes: 5,
1961            min_translation_meters: 0.0,
1962            ..MotionBasedViInitializerConfig::default()
1963        });
1964        for i in 0..4 {
1965            init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
1966        }
1967        assert!(!init.is_ready(), "fewer keyframes than the threshold");
1968        let mut map = build_constant_velocity_map(4);
1969        let seed = synthetic_seed();
1970        let err = init
1971            .try_initialize(&mut map, &[], &seed)
1972            .expect_err("threshold not met");
1973        match err {
1974            MotionBasedViRejectionReason::InsufficientKeyframes { have, need } => {
1975                assert_eq!(have, 4);
1976                assert_eq!(need, 5);
1977            }
1978            other => panic!("unexpected rejection: {other:?}"),
1979        }
1980    }
1981
1982    #[test]
1983    fn trigger_blocked_until_translation_threshold_is_met() {
1984        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
1985            min_keyframes: 3,
1986            min_translation_meters: 5.0,
1987            ..MotionBasedViInitializerConfig::default()
1988        });
1989        init.register_keyframe(1, Point3::new(0.0, 0.0, 0.0));
1990        init.register_keyframe(2, Point3::new(1.0, 0.0, 0.0));
1991        init.register_keyframe(3, Point3::new(2.0, 0.0, 0.0));
1992        assert_eq!(init.keyframes_observed(), 3);
1993        assert!(
1994            (init.cumulative_translation_meters() - 2.0).abs() < 1e-12,
1995            "cumulative_translation tracks chain length, not endpoint distance"
1996        );
1997        assert!(!init.is_ready());
1998        let mut map = build_constant_velocity_map(3);
1999        let seed = synthetic_seed();
2000        let err = init
2001            .try_initialize(&mut map, &[], &seed)
2002            .expect_err("translation threshold not met");
2003        match err {
2004            MotionBasedViRejectionReason::InsufficientTranslation { have, need } => {
2005                assert!((have - 2.0).abs() < 1e-12);
2006                assert!((need - 5.0).abs() < 1e-12);
2007            }
2008            other => panic!("unexpected rejection: {other:?}"),
2009        }
2010    }
2011
2012    #[test]
2013    fn re_registering_same_keyframe_does_not_double_count_translation() {
2014        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig::default());
2015        init.register_keyframe(1, Point3::new(0.0, 0.0, 0.0));
2016        init.register_keyframe(2, Point3::new(1.0, 0.0, 0.0));
2017        init.register_keyframe(2, Point3::new(1.5, 0.0, 0.0));
2018        assert_eq!(init.keyframes_observed(), 2);
2019        // Only the inter-frame displacement from the FIRST insertion is
2020        // counted — the re-registration overwrites the centre but does
2021        // not append to the chain.
2022        assert!((init.cumulative_translation_meters() - 1.0).abs() < 1e-12);
2023    }
2024
2025    #[test]
2026    fn no_usable_factor_is_reported_distinctly_from_solver_failure() {
2027        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2028            min_keyframes: 3,
2029            min_translation_meters: 1.0,
2030            ..MotionBasedViInitializerConfig::default()
2031        });
2032        for i in 0..3 {
2033            init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2034        }
2035        assert!(init.is_ready());
2036        let mut map = build_constant_velocity_map(3);
2037        let seed = synthetic_seed();
2038        let err = init
2039            .try_initialize(&mut map, &[], &seed)
2040            .expect_err("no factors registered");
2041        match err {
2042            MotionBasedViRejectionReason::NoUsableImuFactors => {}
2043            other => panic!("unexpected rejection: {other:?}"),
2044        }
2045    }
2046
2047    #[test]
2048    fn successful_solve_is_cached_and_reset_re_arms() {
2049        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2050            min_keyframes: 3,
2051            min_translation_meters: 1.0,
2052            ..MotionBasedViInitializerConfig::default()
2053        });
2054        let gravity = init.config().gravity_world;
2055        for i in 0..3 {
2056            init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2057        }
2058        let mut map = build_constant_velocity_map(3);
2059        let map_before = map.clone();
2060        let seed = synthetic_seed();
2061        let factors = vec![
2062            no_acceleration_factor(1, 2, 1.0, gravity),
2063            no_acceleration_factor(2, 3, 1.0, gravity),
2064        ];
2065
2066        let result = init
2067            .try_initialize(&mut map, &factors, &seed)
2068            .expect("VIBA1 must succeed on synthetic constant-velocity stream")
2069            .clone();
2070        assert_eq!(
2071            map, map_before,
2072            "inertial-only initialization must keep the visual trajectory fixed"
2073        );
2074        assert_eq!(result.keyframe_ids, vec![1, 2, 3]);
2075        assert_eq!(result.imu_factors_used, 2);
2076        assert!((result.scale - 1.0).abs() < 1e-12);
2077        assert!((result.trigger_translation_meters - 2.0).abs() < 1e-12);
2078        // Solver populated every registered keyframe with a state slot,
2079        // preserved the fixed vision-only trajectory, and terminated below
2080        // the initial cost.
2081        for kf_id in [1u64, 2, 3] {
2082            assert!(result.keyframe_states.contains_key(&kf_id));
2083        }
2084        assert!(result.ba_result.final_cost <= result.ba_result.initial_cost + 1e-9);
2085        match init.status() {
2086            MotionBasedViInitializationStatus::Initialised { .. } => {}
2087            other => panic!("expected Initialised, got {other:?}"),
2088        }
2089
2090        // Re-firing returns the cached result rather than re-running.
2091        let cached = init.try_initialize(&mut map, &factors, &seed).unwrap();
2092        assert_eq!(cached.keyframe_ids, result.keyframe_ids);
2093
2094        // After reset, the state machine returns to Waiting and can
2095        // re-fire on a fresh sequence.
2096        init.reset();
2097        assert_eq!(init.keyframes_observed(), 0);
2098        assert!((init.cumulative_translation_meters() - 0.0).abs() < 1e-12);
2099        match init.status() {
2100            MotionBasedViInitializationStatus::Waiting {
2101                keyframes_observed,
2102                cumulative_translation_meters,
2103                ..
2104            } => {
2105                assert_eq!(keyframes_observed, 0);
2106                assert!(cumulative_translation_meters.abs() < 1e-12);
2107            }
2108            other => panic!("expected Waiting after reset, got {other:?}"),
2109        }
2110    }
2111
2112    #[test]
2113    fn stereo_stationary_replay_is_identity() {
2114        // VIBA1 on three coincident keyframes (zero motion) reproduces
2115        // the static seed: zero velocity, zero biases. The trigger is
2116        // forced by relaxing `min_keyframes` and `min_translation_meters`
2117        // so the "no motion" case is still solvable for the no-op check.
2118        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2119            min_keyframes: 3,
2120            min_translation_meters: 0.0,
2121            ..MotionBasedViInitializerConfig::default()
2122        });
2123        let gravity = init.config().gravity_world;
2124        for i in 0..3 {
2125            init.register_keyframe((i as u64) + 1, Point3::new(0.0, 0.0, 0.0));
2126        }
2127        let mut map = VisualMap::new();
2128        let camera = pinhole_camera();
2129        map.cameras.insert(camera.id, camera.clone());
2130        for i in 0..3 {
2131            let pose = pose_at_world_center(Vector3::zeros());
2132            let frame_id = (i as u64) + 1;
2133            let mut frame = Frame::new(frame_id, camera.id);
2134            frame.pose = Some(pose);
2135            let kf = Keyframe {
2136                frame,
2137                observations: Vec::new(),
2138            };
2139            map.keyframes.insert(frame_id, kf);
2140        }
2141        let seed = synthetic_seed();
2142        let factors = vec![
2143            no_acceleration_factor(1, 2, 0.1, gravity),
2144            no_acceleration_factor(2, 3, 0.1, gravity),
2145        ];
2146        let result = init
2147            .try_initialize(&mut map, &factors, &seed)
2148            .expect("identity replay should succeed");
2149        for state in result.keyframe_states.values() {
2150            assert!(
2151                state.velocity_world.norm() < 1e-6,
2152                "vel = {:?}",
2153                state.velocity_world
2154            );
2155            assert!(state.bias_gyro.norm() < 1e-6, "b_g = {:?}", state.bias_gyro);
2156            assert!(state.bias_acc.norm() < 1e-6, "b_a = {:?}", state.bias_acc);
2157        }
2158    }
2159
2160    #[test]
2161    fn max_velocity_magnitude_gate_rejects_when_exceeded() {
2162        // Run a known-converging setup TWICE: once without the gate to
2163        // record the actual recovered max-velocity magnitude, then once
2164        // with `max_velocity_magnitude_mps = Some(max / 2.0)` so the
2165        // post-solve sanity gate must fire. Decoupling the threshold
2166        // from a hard-coded magnitude keeps the test stable against
2167        // inner-LM precision drift.
2168        let mut probe = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2169            min_keyframes: 3,
2170            min_translation_meters: 1.0,
2171            ..MotionBasedViInitializerConfig::default()
2172        });
2173        let gravity = probe.config().gravity_world;
2174        for i in 0..3 {
2175            probe.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2176        }
2177        let mut probe_map = build_constant_velocity_map(3);
2178        let seed = synthetic_seed();
2179        let factors = vec![
2180            no_acceleration_factor(1, 2, 1.0, gravity),
2181            no_acceleration_factor(2, 3, 1.0, gravity),
2182        ];
2183        let probe_result = probe
2184            .try_initialize(&mut probe_map, &factors, &seed)
2185            .expect("probe run must converge")
2186            .clone();
2187        let max_mag = probe_result
2188            .keyframe_states
2189            .values()
2190            .map(|s| s.velocity_world.norm())
2191            .fold(0.0_f64, f64::max);
2192        // The inner LM in this setup converges very near v=0 but not
2193        // exactly zero (small residual from the gravity term); pick the
2194        // gate threshold below the actual recovered magnitude so the
2195        // post-solve check has something to reject.
2196        assert!(
2197            max_mag > 1.0e-12,
2198            "probe max |v| too small to test the gate: {max_mag}"
2199        );
2200
2201        let mut gated = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2202            min_keyframes: 3,
2203            min_translation_meters: 1.0,
2204            max_velocity_magnitude_mps: Some(max_mag / 2.0),
2205            ..MotionBasedViInitializerConfig::default()
2206        });
2207        for i in 0..3 {
2208            gated.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2209        }
2210        let mut gated_map = build_constant_velocity_map(3);
2211        let gated_map_before = gated_map.clone();
2212        let err = gated
2213            .try_initialize(&mut gated_map, &factors, &seed)
2214            .expect_err("velocity gate must reject the LM result");
2215        assert_eq!(
2216            gated_map, gated_map_before,
2217            "a rejected speculative motion-VI solve must not write poses back"
2218        );
2219        match err {
2220            MotionBasedViRejectionReason::VelocityOutOfRange {
2221                kf_id,
2222                magnitude_mps,
2223                limit_mps,
2224            } => {
2225                assert!([1u64, 2, 3].contains(&kf_id), "kf_id = {kf_id}");
2226                assert!(magnitude_mps > limit_mps);
2227                assert!((limit_mps - max_mag / 2.0).abs() < 1.0e-12);
2228            }
2229            other => panic!("expected VelocityOutOfRange, got {other:?}"),
2230        }
2231        // The stage stays in `Waiting` after a gate rejection so the
2232        // caller can re-fire on a future trigger.
2233        match gated.status() {
2234            MotionBasedViInitializationStatus::Waiting { last_rejection, .. } => {
2235                assert!(matches!(
2236                    last_rejection,
2237                    Some(MotionBasedViRejectionReason::VelocityOutOfRange { .. })
2238                ));
2239            }
2240            other => panic!("expected Waiting after gate rejection, got {other:?}"),
2241        }
2242    }
2243
2244    #[test]
2245    fn normalized_imu_nis_gate_rejects_inconsistent_promotion() {
2246        let mut probe = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2247            min_keyframes: 3,
2248            min_translation_meters: 1.0,
2249            ..MotionBasedViInitializerConfig::default()
2250        });
2251        let gravity = probe.config().gravity_world;
2252        for i in 0..3 {
2253            probe.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2254        }
2255        let factors = vec![
2256            no_acceleration_factor(1, 2, 1.0, gravity),
2257            no_acceleration_factor(2, 3, 1.0, gravity),
2258        ];
2259        let seed = synthetic_seed();
2260        let mut probe_map = build_constant_velocity_map(3);
2261        let observed = probe
2262            .try_initialize(&mut probe_map, &factors, &seed)
2263            .expect("probe solve")
2264            .final_cost_breakdown
2265            .imu_normalized_squared_residual_per_dof
2266            .expect("IMU factors produce a normalized residual");
2267        assert!(observed.is_finite() && observed > 0.0);
2268
2269        let limit = observed * 0.5;
2270        let mut gated = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2271            min_keyframes: 3,
2272            min_translation_meters: 1.0,
2273            max_final_imu_nis_per_dof: Some(limit),
2274            ..MotionBasedViInitializerConfig::default()
2275        });
2276        for i in 0..3 {
2277            gated.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2278        }
2279        let mut gated_map = build_constant_velocity_map(3);
2280        let map_before = gated_map.clone();
2281        let error = gated
2282            .try_initialize(&mut gated_map, &factors, &seed)
2283            .expect_err("NIS gate must reject the inconsistent promotion");
2284        assert_eq!(gated_map, map_before);
2285        assert!(matches!(
2286            error,
2287            MotionBasedViRejectionReason::ImuNisOutOfRange {
2288                normalized_nis_per_dof,
2289                rotation_residual_rms_rad: _,
2290                velocity_residual_rms_mps: _,
2291                position_residual_rms_meters: _,
2292                limit: rejected_limit,
2293            } if (normalized_nis_per_dof - observed).abs() < 1.0e-9
2294                && (rejected_limit - limit).abs() < 1.0e-12
2295        ));
2296    }
2297
2298    #[test]
2299    fn physical_imu_residual_gate_rejects_inconsistent_promotion() {
2300        let mut probe = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2301            min_keyframes: 3,
2302            min_translation_meters: 1.0,
2303            ..MotionBasedViInitializerConfig::default()
2304        });
2305        let gravity = probe.config().gravity_world;
2306        for i in 0..3 {
2307            probe.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2308        }
2309        let factors = vec![
2310            no_acceleration_factor(1, 2, 1.0, gravity),
2311            no_acceleration_factor(2, 3, 1.0, gravity),
2312        ];
2313        let seed = synthetic_seed();
2314        let mut probe_map = build_constant_velocity_map(3);
2315        let observed = probe
2316            .try_initialize(&mut probe_map, &factors, &seed)
2317            .expect("probe solve")
2318            .final_cost_breakdown
2319            .imu_velocity_residual_rms_mps
2320            .expect("velocity residual");
2321        assert!(observed.is_finite() && observed > 0.0);
2322
2323        let limit = observed * 0.5;
2324        let mut gated = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2325            min_keyframes: 3,
2326            min_translation_meters: 1.0,
2327            max_final_imu_velocity_residual_rms_mps: Some(limit),
2328            ..MotionBasedViInitializerConfig::default()
2329        });
2330        for i in 0..3 {
2331            gated.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2332        }
2333        let mut gated_map = build_constant_velocity_map(3);
2334        let map_before = gated_map.clone();
2335        let error = gated
2336            .try_initialize(&mut gated_map, &factors, &seed)
2337            .expect_err("physical residual gate must reject promotion");
2338        assert_eq!(gated_map, map_before);
2339        assert!(matches!(
2340            error,
2341            MotionBasedViRejectionReason::ImuRawResidualOutOfRange {
2342                velocity_residual_rms_mps: Some(value),
2343                max_velocity_residual_rms_mps: Some(rejected_limit),
2344                ..
2345            } if (value - observed).abs() < 1.0e-9
2346                && (rejected_limit - limit).abs() < 1.0e-12
2347        ));
2348    }
2349
2350    #[test]
2351    fn max_velocity_magnitude_gate_passes_when_under_limit() {
2352        // Same setup but with a generous limit; the inner result is
2353        // promoted to `completed` as usual.
2354        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2355            min_keyframes: 3,
2356            min_translation_meters: 1.0,
2357            max_velocity_magnitude_mps: Some(1.0e6),
2358            ..MotionBasedViInitializerConfig::default()
2359        });
2360        let gravity = init.config().gravity_world;
2361        for i in 0..3 {
2362            init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2363        }
2364        let mut map = build_constant_velocity_map(3);
2365        let seed = synthetic_seed();
2366        let factors = vec![
2367            no_acceleration_factor(1, 2, 1.0, gravity),
2368            no_acceleration_factor(2, 3, 1.0, gravity),
2369        ];
2370        let _ = init
2371            .try_initialize(&mut map, &factors, &seed)
2372            .expect("generous limit must accept the LM result");
2373        match init.status() {
2374            MotionBasedViInitializationStatus::Initialised { .. } => {}
2375            other => panic!("expected Initialised, got {other:?}"),
2376        }
2377    }
2378
2379    #[test]
2380    fn gyro_bias_gate_rejects_transactionally() {
2381        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2382            min_keyframes: 3,
2383            min_translation_meters: 1.0,
2384            max_gyro_bias_magnitude_rad_s: Some(0.05),
2385            ..MotionBasedViInitializerConfig::default()
2386        });
2387        let gravity = init.config().gravity_world;
2388        for i in 0..3 {
2389            init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2390        }
2391        let mut map = build_constant_velocity_map(3);
2392        let map_before = map.clone();
2393        let factors = vec![
2394            no_acceleration_factor(1, 2, 1.0, gravity),
2395            no_acceleration_factor(2, 3, 1.0, gravity),
2396        ];
2397        let err = init
2398            .try_initialize_with_bias_seed(
2399                &mut map,
2400                &factors,
2401                Vector3::new(0.1, 0.0, 0.0),
2402                Vector3::zeros(),
2403            )
2404            .expect_err("anchored gyro bias must exceed the configured gate");
2405        assert_eq!(map, map_before, "rejected solve must not mutate the map");
2406        assert!(matches!(
2407            err,
2408            MotionBasedViRejectionReason::GyroBiasOutOfRange {
2409                magnitude_rad_s,
2410                limit_rad_s,
2411                ..
2412            } if magnitude_rad_s > limit_rad_s && (limit_rad_s - 0.05).abs() < 1.0e-12
2413        ));
2414    }
2415
2416    #[test]
2417    fn accel_bias_gate_rejects_transactionally() {
2418        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2419            min_keyframes: 3,
2420            min_translation_meters: 1.0,
2421            max_accel_bias_magnitude_mps2: Some(1.0),
2422            ..MotionBasedViInitializerConfig::default()
2423        });
2424        let gravity = init.config().gravity_world;
2425        for i in 0..3 {
2426            init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2427        }
2428        let mut map = build_constant_velocity_map(3);
2429        let map_before = map.clone();
2430        let factors = vec![
2431            no_acceleration_factor(1, 2, 1.0, gravity),
2432            no_acceleration_factor(2, 3, 1.0, gravity),
2433        ];
2434        let err = init
2435            .try_initialize_with_bias_seed(
2436                &mut map,
2437                &factors,
2438                Vector3::zeros(),
2439                Vector3::new(2.0, 0.0, 0.0),
2440            )
2441            .expect_err("anchored accel bias must exceed the configured gate");
2442        assert_eq!(map, map_before, "rejected solve must not mutate the map");
2443        assert!(matches!(
2444            err,
2445            MotionBasedViRejectionReason::AccelBiasOutOfRange {
2446                magnitude_mps2,
2447                limit_mps2,
2448                ..
2449            } if magnitude_mps2 > limit_mps2 && (limit_mps2 - 1.0).abs() < 1.0e-12
2450        ));
2451    }
2452
2453    /// Helper: SO3 type sanity (compile coverage for the test imports).
2454    #[test]
2455    fn so3_identity_is_quaternion_identity() {
2456        let r = SO3::identity();
2457        let q = r.quaternion();
2458        assert!((q.w - 1.0).abs() < 1e-12);
2459        assert!((q.i.abs() + q.j.abs() + q.k.abs()) < 1e-12);
2460    }
2461
2462    // ============================================================
2463    // VIBA2 hand-off tests.
2464    // ============================================================
2465
2466    #[test]
2467    fn viba2_handoff_runs_when_configured_and_reports_scale_history() {
2468        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2469            min_keyframes: 3,
2470            min_translation_meters: 1.0,
2471            gravity_world: Vector3::zeros(),
2472            viba2: Some(Viba2Config {
2473                initial_scale: 1.0,
2474                recover_scale: true,
2475                max_outer_iterations: 3,
2476                scale_tolerance: 1.0e-4,
2477                ..Viba2Config::default()
2478            }),
2479            ..MotionBasedViInitializerConfig::default()
2480        });
2481        let gravity = init.config().gravity_world;
2482        for i in 0..3 {
2483            init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2484        }
2485        let mut map = VisualMap::new();
2486        let camera = pinhole_camera();
2487        map.cameras.insert(camera.id, camera.clone());
2488        for i in 0..3 {
2489            let center = Vector3::new(i as f64, 0.0, 0.0);
2490            let pose = pose_at_world_center(center);
2491            let frame_id = (i as u64) + 1;
2492            let mut frame = Frame::new(frame_id, camera.id);
2493            frame.pose = Some(pose);
2494            let kf = Keyframe {
2495                frame,
2496                observations: Vec::new(),
2497            };
2498            map.keyframes.insert(frame_id, kf);
2499        }
2500        let seed = synthetic_seed();
2501        let factors = vec![
2502            no_acceleration_factor(1, 2, 1.0, gravity),
2503            no_acceleration_factor(2, 3, 1.0, gravity),
2504        ];
2505        let result = init
2506            .try_initialize(&mut map, &factors, &seed)
2507            .expect("VIBA2 path should succeed");
2508        // VIBA2 ran at least once; scale history starts with the initial
2509        // scale and may have one more entry per outer iteration. The
2510        // exact length depends on whether the kinematic denominator was
2511        // identifiable, which on this zero-gravity-zero-Δp synthetic is
2512        // degenerate (so the outer loop bails after one inner solve and
2513        // freezes scale at 1.0).
2514        assert!(result.scale.is_finite());
2515        assert!(result.viba2_iterations_run >= 1);
2516        assert!(!result.scale_history.is_empty());
2517        assert!((result.scale_history[0] - 1.0).abs() < 1e-12);
2518    }
2519
2520    #[test]
2521    fn no_viba2_config_keeps_scale_history_empty() {
2522        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2523            min_keyframes: 3,
2524            min_translation_meters: 1.0,
2525            ..MotionBasedViInitializerConfig::default()
2526        });
2527        let gravity = init.config().gravity_world;
2528        for i in 0..3 {
2529            init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2530        }
2531        let mut map = VisualMap::new();
2532        let camera = pinhole_camera();
2533        map.cameras.insert(camera.id, camera.clone());
2534        for i in 0..3 {
2535            let pose = pose_at_world_center(Vector3::new(i as f64, 0.0, 0.0));
2536            let frame_id = (i as u64) + 1;
2537            let mut frame = Frame::new(frame_id, camera.id);
2538            frame.pose = Some(pose);
2539            let kf = Keyframe {
2540                frame,
2541                observations: Vec::new(),
2542            };
2543            map.keyframes.insert(frame_id, kf);
2544        }
2545        let seed = synthetic_seed();
2546        let factors = vec![
2547            no_acceleration_factor(1, 2, 1.0, gravity),
2548            no_acceleration_factor(2, 3, 1.0, gravity),
2549        ];
2550        let result = init
2551            .try_initialize(&mut map, &factors, &seed)
2552            .expect("VIBA1 path should succeed");
2553        assert!((result.scale - 1.0).abs() < 1e-12);
2554        assert!(result.scale_history.is_empty());
2555        assert_eq!(result.viba2_iterations_run, 0);
2556    }
2557
2558    // ============================================================
2559    // Staged bias release (`BiasReleaseSchedule`) tests.
2560    // ============================================================
2561
2562    #[test]
2563    fn legacy_path_without_bias_release_schedule_reports_bias_released_true() {
2564        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2565            min_keyframes: 3,
2566            min_translation_meters: 1.0,
2567            ..MotionBasedViInitializerConfig::default()
2568        });
2569        assert!(init.config().bias_release.is_none());
2570        let gravity = init.config().gravity_world;
2571        for i in 0..3 {
2572            init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2573        }
2574        let mut map = build_constant_velocity_map(3);
2575        let seed = synthetic_seed();
2576        let factors = vec![
2577            no_acceleration_factor(1, 2, 1.0, gravity),
2578            no_acceleration_factor(2, 3, 1.0, gravity),
2579        ];
2580        let result = init
2581            .try_initialize(&mut map, &factors, &seed)
2582            .expect("legacy path must succeed");
2583        assert!(
2584            result.bias_released,
2585            "legacy path (bias_release=None) must report bias_released=true"
2586        );
2587        assert!(
2588            init.velocity_stage_result().is_none(),
2589            "legacy path never populates the velocity stage"
2590        );
2591        match init.status() {
2592            MotionBasedViInitializationStatus::Initialised { .. } => {}
2593            other => panic!("expected terminal Initialised, got {other:?}"),
2594        }
2595    }
2596
2597    #[test]
2598    fn bias_release_schedule_stage_a_fires_then_awaits_release_gate() {
2599        // Base gates (min_keyframes=3, min_translation_meters=1.0) are
2600        // satisfied by 3 keyframes spaced 1 m apart, but the schedule's own
2601        // release gate (min_keyframes=5, min_translation_meters=3.0) is not.
2602        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2603            min_keyframes: 3,
2604            min_translation_meters: 1.0,
2605            bias_release: Some(BiasReleaseSchedule {
2606                min_keyframes: 5,
2607                min_translation_meters: 3.0,
2608            }),
2609            ..MotionBasedViInitializerConfig::default()
2610        });
2611        let gravity = init.config().gravity_world;
2612        for i in 0..3 {
2613            init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2614        }
2615        assert!(init.is_ready(), "base gates must be satisfied");
2616        let mut map = build_constant_velocity_map(3);
2617        let seed = synthetic_seed();
2618        let factors = vec![
2619            no_acceleration_factor(1, 2, 1.0, gravity),
2620            no_acceleration_factor(2, 3, 1.0, gravity),
2621        ];
2622
2623        let stage_a = init
2624            .try_initialize(&mut map, &factors, &seed)
2625            .expect("Stage A must fire once the base gates are met")
2626            .clone();
2627        assert!(!stage_a.bias_released, "Stage A must not release bias");
2628        for state in stage_a.keyframe_states.values() {
2629            assert!(
2630                (state.bias_gyro - seed.bias_gyro).norm() < 1.0e-12,
2631                "Stage A must not move gyro bias off the seed"
2632            );
2633            assert!(
2634                (state.bias_acc - seed.bias_acc).norm() < 1.0e-12,
2635                "Stage A must not move accel bias off the seed"
2636            );
2637        }
2638        assert!(init.velocity_stage_result().is_some());
2639        match init.status() {
2640            MotionBasedViInitializationStatus::Waiting {
2641                velocity_stage_completed,
2642                ..
2643            } => assert!(
2644                velocity_stage_completed,
2645                "status() must report the completed velocity stage"
2646            ),
2647            other => panic!("expected non-terminal Waiting after Stage A, got {other:?}"),
2648        }
2649
2650        // A second call before the release gate is met has nothing new to
2651        // solve: Stage A already fired and is cached.
2652        let err = init
2653            .try_initialize(&mut map, &factors, &seed)
2654            .expect_err("release gate not yet met");
2655        match err {
2656            MotionBasedViRejectionReason::AwaitingBiasReleaseExcitation {
2657                have_keyframes,
2658                need_keyframes,
2659                have_translation_meters,
2660                need_translation_meters,
2661            } => {
2662                assert_eq!(have_keyframes, 3);
2663                assert_eq!(need_keyframes, 5);
2664                assert!((have_translation_meters - 2.0).abs() < 1.0e-12);
2665                assert!((need_translation_meters - 3.0).abs() < 1.0e-12);
2666            }
2667            other => panic!("expected AwaitingBiasReleaseExcitation, got {other:?}"),
2668        }
2669    }
2670
2671    #[test]
2672    fn bias_release_schedule_stage_b_fires_once_gate_is_met() {
2673        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2674            min_keyframes: 3,
2675            min_translation_meters: 1.0,
2676            bias_release: Some(BiasReleaseSchedule {
2677                min_keyframes: 5,
2678                min_translation_meters: 3.0,
2679            }),
2680            ..MotionBasedViInitializerConfig::default()
2681        });
2682        let gravity = init.config().gravity_world;
2683        for i in 0..3 {
2684            init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2685        }
2686        let mut map = build_constant_velocity_map(5);
2687        let seed = synthetic_seed();
2688        let factors = vec![
2689            no_acceleration_factor(1, 2, 1.0, gravity),
2690            no_acceleration_factor(2, 3, 1.0, gravity),
2691            no_acceleration_factor(3, 4, 1.0, gravity),
2692            no_acceleration_factor(4, 5, 1.0, gravity),
2693        ];
2694
2695        let stage_a = init
2696            .try_initialize(&mut map, &factors, &seed)
2697            .expect("Stage A must fire")
2698            .clone();
2699        assert!(!stage_a.bias_released);
2700
2701        // Register the remaining keyframes to clear the release gate:
2702        // 5 keyframes total, 4 m cumulative translation.
2703        init.register_keyframe(4, Point3::new(3.0, 0.0, 0.0));
2704        init.register_keyframe(5, Point3::new(4.0, 0.0, 0.0));
2705        assert_eq!(init.keyframes_observed(), 5);
2706        assert!((init.cumulative_translation_meters() - 4.0).abs() < 1.0e-9);
2707
2708        let stage_b = init
2709            .try_initialize(&mut map, &factors, &seed)
2710            .expect("Stage B must fire once the release gate is met")
2711            .clone();
2712        assert!(
2713            stage_b.bias_released,
2714            "Stage B must release bias like the legacy path"
2715        );
2716        match init.status() {
2717            MotionBasedViInitializationStatus::Initialised { .. } => {}
2718            other => panic!("expected terminal Initialised after Stage B, got {other:?}"),
2719        }
2720    }
2721
2722    #[test]
2723    fn reset_clears_velocity_stage() {
2724        let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2725            min_keyframes: 3,
2726            min_translation_meters: 1.0,
2727            bias_release: Some(BiasReleaseSchedule {
2728                min_keyframes: 5,
2729                min_translation_meters: 3.0,
2730            }),
2731            ..MotionBasedViInitializerConfig::default()
2732        });
2733        let gravity = init.config().gravity_world;
2734        for i in 0..3 {
2735            init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2736        }
2737        let mut map = build_constant_velocity_map(3);
2738        let seed = synthetic_seed();
2739        let factors = vec![
2740            no_acceleration_factor(1, 2, 1.0, gravity),
2741            no_acceleration_factor(2, 3, 1.0, gravity),
2742        ];
2743        init.try_initialize(&mut map, &factors, &seed)
2744            .expect("Stage A must fire");
2745        assert!(init.velocity_stage_result().is_some());
2746
2747        init.reset();
2748        assert!(
2749            init.velocity_stage_result().is_none(),
2750            "reset() must clear the cached velocity stage"
2751        );
2752        match init.status() {
2753            MotionBasedViInitializationStatus::Waiting {
2754                velocity_stage_completed,
2755                ..
2756            } => assert!(!velocity_stage_completed),
2757            other => panic!("expected Waiting after reset, got {other:?}"),
2758        }
2759    }
2760
2761    // ============================================================
2762    // Gravity-direction recovery (`estimate_gravity`) tests.
2763    // See `docs/motion_based_vi_alignment.md`'s "Gravity-direction
2764    // recovery" section for the motivating real-data diagnosis.
2765    // ============================================================
2766
2767    /// [`estimate_gravity_and_velocities`] direct unit tests (not routed
2768    /// through the initializer state machine).
2769    mod gravity_velocity_alignment {
2770        use super::*;
2771
2772        #[test]
2773        fn recovers_off_axis_gravity_and_velocities_from_a_consistent_window() {
2774            // True gravity is off every coordinate axis (and off the
2775            // codebase's Y-axis config default) while the body moves at a
2776            // constant, also off-axis, world velocity. With visual poses
2777            // held fixed and zero proper acceleration baked into every
2778            // factor, the linear system is EXACTLY consistent, so the
2779            // unconstrained solve must recover both quantities to numerical
2780            // precision.
2781            let true_gravity = Vector3::new(6.54, -3.27, 6.54); // |g| = 9.81
2782            let velocity = Vector3::new(1.2, -0.7, 0.3);
2783            let map = build_map_at_velocity(5, 1.0, velocity);
2784            let ids: Vec<u64> = (1..=5).collect();
2785            let factors = vec![
2786                no_acceleration_factor(1, 2, 1.0, true_gravity),
2787                no_acceleration_factor(2, 3, 1.0, true_gravity),
2788                no_acceleration_factor(3, 4, 1.0, true_gravity),
2789                no_acceleration_factor(4, 5, 1.0, true_gravity),
2790            ];
2791            let alignment = estimate_gravity_and_velocities(
2792                &map,
2793                &ids,
2794                &factors,
2795                Vector3::zeros(),
2796                Vector3::zeros(),
2797                9.81,
2798            )
2799            .expect("well-conditioned, exactly-consistent window must align");
2800            assert!(
2801                (alignment.gravity_world - true_gravity).norm() < 1.0e-6,
2802                "g_est = {:?}",
2803                alignment.gravity_world
2804            );
2805            assert!(
2806                (alignment.raw_gravity_norm - 9.81).abs() < 1.0e-6,
2807                "raw_gravity_norm = {}",
2808                alignment.raw_gravity_norm
2809            );
2810            for (kf_id, v) in &alignment.velocities {
2811                assert!(
2812                    (v - velocity).norm() < 1.0e-6,
2813                    "kf {kf_id}: v_est = {v:?}, expected {velocity:?}"
2814                );
2815            }
2816        }
2817
2818        #[test]
2819        fn degenerate_window_with_a_single_factor_returns_none() {
2820            // Fewer than 2 usable in-window factors (1 factor = 6 rows <
2821            // the 6 unknowns already contributed by that one factor's own
2822            // endpoints, but the function's own documented floor is "< 2
2823            // factors") is degenerate by construction — distinct from a
2824            // stationary window, which would instead solve to a near-zero
2825            // raw gravity norm (also degenerate, via the `< 1e-6` guard).
2826            let velocity = Vector3::new(1.0, 0.0, 0.0);
2827            let map = build_map_at_velocity(2, 1.0, velocity);
2828            let ids: Vec<u64> = vec![1, 2];
2829            let factors = vec![no_acceleration_factor(
2830                1,
2831                2,
2832                1.0,
2833                Vector3::new(0.0, 9.81, 0.0),
2834            )];
2835            let alignment = estimate_gravity_and_velocities(
2836                &map,
2837                &ids,
2838                &factors,
2839                Vector3::zeros(),
2840                Vector3::zeros(),
2841                9.81,
2842            );
2843            assert!(
2844                alignment.is_none(),
2845                "a single-factor window must be reported degenerate"
2846            );
2847        }
2848
2849        #[test]
2850        fn norm_constrained_refinement_pins_the_magnitude_when_raw_solve_drifts() {
2851            // Start from the exactly-consistent fixture above, then inject
2852            // a small measurement inconsistency into one factor's velocity
2853            // delta (as if that window's IMU evidence were noisy). The
2854            // unconstrained solve is pulled off the true magnitude by the
2855            // inconsistency, but the VINS-Mono-style tangent refinement
2856            // must still land the FINAL `gravity_world` exactly on the
2857            // caller's expected magnitude.
2858            let true_gravity = Vector3::new(6.54, -3.27, 6.54); // |g| = 9.81
2859            let velocity = Vector3::new(1.2, -0.7, 0.3);
2860            let map = build_map_at_velocity(4, 1.0, velocity);
2861            let ids: Vec<u64> = (1..=4).collect();
2862            let mut factors = vec![
2863                no_acceleration_factor(1, 2, 1.0, true_gravity),
2864                no_acceleration_factor(2, 3, 1.0, true_gravity),
2865                no_acceleration_factor(3, 4, 1.0, true_gravity),
2866            ];
2867            factors[1].delta.delta_velocity += Vector3::new(0.35, -0.2, 0.15);
2868
2869            let alignment = estimate_gravity_and_velocities(
2870                &map,
2871                &ids,
2872                &factors,
2873                Vector3::zeros(),
2874                Vector3::zeros(),
2875                9.81,
2876            )
2877            .expect("a mild inconsistency must still be solvable");
2878            assert!(
2879                (alignment.raw_gravity_norm - 9.81).abs() > 1.0e-6,
2880                "fixture must actually perturb the unconstrained solve off the true magnitude, raw = {}",
2881                alignment.raw_gravity_norm
2882            );
2883            assert!(
2884                (alignment.gravity_world.norm() - 9.81).abs() < 1.0e-9,
2885                "the constrained estimate must be pinned to the expected magnitude, got {}",
2886                alignment.gravity_world.norm()
2887            );
2888            assert!(
2889                alignment.mean_residual_after > 0.0,
2890                "an inconsistent window must leave a nonzero residual"
2891            );
2892        }
2893    }
2894
2895    /// Initializer-level (`try_initialize` / `try_initialize_with_bias_seed`)
2896    /// tests exercising the `estimate_gravity` config knob end to end.
2897    mod estimate_gravity_initializer {
2898        use super::*;
2899
2900        #[test]
2901        fn recovers_from_rotated_true_gravity_where_the_legacy_path_rejects() {
2902            // Diagnosed real-data scenario: the specific-force reaction
2903            // lands on an axis (here Z) 90 degrees away from the config's
2904            // assumed `gravity_world` (Y), with the body moving along a
2905            // third axis (X). The legacy path trusts the config axis as
2906            // truth and the raw-residual gate must reject it; enabling
2907            // `estimate_gravity` recovers the true direction and clears
2908            // the SAME gate.
2909            let true_gravity = Vector3::new(0.0, 0.0, 9.81);
2910            let assumed_gravity = Vector3::new(0.0, 9.81, 0.0);
2911            let factors = vec![
2912                no_acceleration_factor_with_assumed_gravity(
2913                    1,
2914                    2,
2915                    1.0,
2916                    true_gravity,
2917                    assumed_gravity,
2918                ),
2919                no_acceleration_factor_with_assumed_gravity(
2920                    2,
2921                    3,
2922                    1.0,
2923                    true_gravity,
2924                    assumed_gravity,
2925                ),
2926                no_acceleration_factor_with_assumed_gravity(
2927                    3,
2928                    4,
2929                    1.0,
2930                    true_gravity,
2931                    assumed_gravity,
2932                ),
2933                no_acceleration_factor_with_assumed_gravity(
2934                    4,
2935                    5,
2936                    1.0,
2937                    true_gravity,
2938                    assumed_gravity,
2939                ),
2940            ];
2941            let seed = synthetic_seed();
2942
2943            // Probe: legacy solve with NO residual gate, just to read the
2944            // actual velocity-residual RMS the misaligned assumption
2945            // produces on this fixture (decouples the gate threshold below
2946            // from a hard-coded magnitude, same technique as
2947            // `max_velocity_magnitude_gate_rejects_when_exceeded`).
2948            let mut probe = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2949                min_keyframes: 3,
2950                min_translation_meters: 1.0,
2951                gravity_world: assumed_gravity,
2952                ..MotionBasedViInitializerConfig::default()
2953            });
2954            for i in 0..5 {
2955                probe.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2956            }
2957            let mut probe_map = build_constant_velocity_map(5);
2958            let probe_residual = probe
2959                .try_initialize(&mut probe_map, &factors, &seed)
2960                .expect("legacy solve still converges; only the gate is missing here")
2961                .final_cost_breakdown
2962                .imu_velocity_residual_rms_mps
2963                .expect("IMU factors produce a velocity residual");
2964            assert!(
2965                probe_residual > 0.5,
2966                "a 90-degree gravity misalignment should leave a substantial residual, got {probe_residual}"
2967            );
2968            let gate = probe_residual * 0.5;
2969
2970            // A: legacy path (estimate_gravity = false) must be rejected
2971            // by the gate.
2972            let mut legacy = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2973                min_keyframes: 3,
2974                min_translation_meters: 1.0,
2975                gravity_world: assumed_gravity,
2976                max_final_imu_velocity_residual_rms_mps: Some(gate),
2977                ..MotionBasedViInitializerConfig::default()
2978            });
2979            for i in 0..5 {
2980                legacy.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
2981            }
2982            let mut legacy_map = build_constant_velocity_map(5);
2983            let err = legacy
2984                .try_initialize(&mut legacy_map, &factors, &seed)
2985                .expect_err(
2986                    "misaligned gravity assumption must be rejected by the raw-residual gate",
2987                );
2988            assert!(
2989                matches!(
2990                    err,
2991                    MotionBasedViRejectionReason::ImuRawResidualOutOfRange { .. }
2992                ),
2993                "unexpected rejection: {err:?}"
2994            );
2995
2996            // B: estimate_gravity = true recovers the true direction and
2997            // clears the SAME gate.
2998            let mut estimated = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
2999                min_keyframes: 3,
3000                min_translation_meters: 1.0,
3001                gravity_world: assumed_gravity,
3002                estimate_gravity: true,
3003                max_final_imu_velocity_residual_rms_mps: Some(gate),
3004                ..MotionBasedViInitializerConfig::default()
3005            });
3006            for i in 0..5 {
3007                estimated.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3008            }
3009            let mut estimated_map = build_constant_velocity_map(5);
3010            let result = estimated
3011                .try_initialize(&mut estimated_map, &factors, &seed)
3012                .expect("gravity estimation must recover enough to clear the same gate");
3013            let g_est = result
3014                .estimated_gravity_world
3015                .expect("estimate_gravity=true must report the recovered vector");
3016            assert!(
3017                (g_est - true_gravity).norm() < 0.05,
3018                "recovered gravity {g_est:?} should match the true {true_gravity:?}"
3019            );
3020        }
3021
3022        #[test]
3023        fn norm_gate_rejects_an_implausible_recovered_magnitude() {
3024            // A well-conditioned window recovers a norm near the TRUE
3025            // magnitude with no constraint imposed anywhere in the
3026            // unconstrained solve; deliberately feeding it evidence
3027            // consistent with a magnitude nowhere near 9.81 must trip the
3028            // observability gate rather than silently rescaling and
3029            // promoting.
3030            let true_gravity = Vector3::new(0.0, 0.0, 3.0);
3031            let assumed_gravity = Vector3::new(0.0, 9.81, 0.0);
3032            let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3033                min_keyframes: 3,
3034                min_translation_meters: 1.0,
3035                gravity_world: assumed_gravity,
3036                estimate_gravity: true,
3037                ..MotionBasedViInitializerConfig::default()
3038            });
3039            for i in 0..3 {
3040                init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3041            }
3042            let mut map = build_constant_velocity_map(3);
3043            let seed = synthetic_seed();
3044            let factors = vec![
3045                no_acceleration_factor_with_assumed_gravity(
3046                    1,
3047                    2,
3048                    1.0,
3049                    true_gravity,
3050                    assumed_gravity,
3051                ),
3052                no_acceleration_factor_with_assumed_gravity(
3053                    2,
3054                    3,
3055                    1.0,
3056                    true_gravity,
3057                    assumed_gravity,
3058                ),
3059            ];
3060            let err = init
3061                .try_initialize(&mut map, &factors, &seed)
3062                .expect_err("implausible recovered magnitude must be rejected");
3063            match err {
3064                MotionBasedViRejectionReason::GravityEstimateOutOfRange {
3065                    raw_norm_mps2,
3066                    expected_mps2,
3067                    max_deviation_ratio,
3068                } => {
3069                    assert!(
3070                        (raw_norm_mps2 - 3.0).abs() < 1.0e-6,
3071                        "raw_norm_mps2 = {raw_norm_mps2}"
3072                    );
3073                    assert!((expected_mps2 - 9.81).abs() < 1.0e-9);
3074                    assert!((max_deviation_ratio - 0.3).abs() < 1.0e-9);
3075                }
3076                other => panic!("expected GravityEstimateOutOfRange, got {other:?}"),
3077            }
3078        }
3079
3080        #[test]
3081        fn degenerate_when_no_factors_connect_the_window() {
3082            let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3083                min_keyframes: 3,
3084                min_translation_meters: 1.0,
3085                estimate_gravity: true,
3086                ..MotionBasedViInitializerConfig::default()
3087            });
3088            for i in 0..3 {
3089                init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3090            }
3091            let mut map = build_constant_velocity_map(3);
3092            let seed = synthetic_seed();
3093            let err = init
3094                .try_initialize(&mut map, &[], &seed)
3095                .expect_err("no factors means the alignment cannot condition at all");
3096            assert!(matches!(
3097                err,
3098                MotionBasedViRejectionReason::GravityEstimateDegenerate
3099            ));
3100        }
3101
3102        #[test]
3103        fn composes_with_staged_bias_release_stage_a() {
3104            // `estimate_gravity` and `BiasReleaseSchedule` are independent
3105            // knobs; a Stage A ("velocity stage") firing must still report
3106            // + apply the recovered gravity while leaving biases pinned at
3107            // the seed, exactly as Stage A does for legacy (non-estimated)
3108            // gravity.
3109            let true_gravity = Vector3::new(0.0, 0.0, 9.81);
3110            let assumed_gravity = Vector3::new(0.0, 9.81, 0.0);
3111            let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3112                min_keyframes: 3,
3113                min_translation_meters: 1.0,
3114                gravity_world: assumed_gravity,
3115                estimate_gravity: true,
3116                bias_release: Some(BiasReleaseSchedule {
3117                    min_keyframes: 5,
3118                    min_translation_meters: 3.0,
3119                }),
3120                ..MotionBasedViInitializerConfig::default()
3121            });
3122            for i in 0..3 {
3123                init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3124            }
3125            let mut map = build_constant_velocity_map(3);
3126            let seed = synthetic_seed();
3127            let factors = vec![
3128                no_acceleration_factor_with_assumed_gravity(
3129                    1,
3130                    2,
3131                    1.0,
3132                    true_gravity,
3133                    assumed_gravity,
3134                ),
3135                no_acceleration_factor_with_assumed_gravity(
3136                    2,
3137                    3,
3138                    1.0,
3139                    true_gravity,
3140                    assumed_gravity,
3141                ),
3142            ];
3143            let result = init
3144                .try_initialize(&mut map, &factors, &seed)
3145                .expect("Stage A must fire even with gravity estimation enabled")
3146                .clone();
3147            assert!(!result.bias_released, "Stage A must not release bias");
3148            let g_est = result
3149                .estimated_gravity_world
3150                .expect("estimate must be reported on a Stage A result too");
3151            assert!(
3152                (g_est - true_gravity).norm() < 0.05,
3153                "recovered gravity {g_est:?} should match the true {true_gravity:?}"
3154            );
3155            for state in result.keyframe_states.values() {
3156                assert!(
3157                    (state.bias_gyro - seed.bias_gyro).norm() < 1.0e-9,
3158                    "Stage A must not move gyro bias off the seed even with gravity estimation"
3159                );
3160                assert!(
3161                    (state.bias_acc - seed.bias_acc).norm() < 1.0e-9,
3162                    "Stage A must not move accel bias off the seed even with gravity estimation"
3163                );
3164            }
3165        }
3166    }
3167
3168    // ============================================================
3169    // Gyro-bias recovery (`estimate_gyro_bias`) tests.
3170    // See `docs/motion_based_vi_alignment.md`'s "Gyro-bias recovery"
3171    // section for the motivating real-data diagnosis: the fitted IMU
3172    // rotation residual RMS sat at 0.014-0.022 rad vs a 0.01 gate,
3173    // bit-identical with/without gravity estimation (the rotation
3174    // residual is gravity-independent), consistent with EuRoC-scale gyro
3175    // bias (~0.08 rad/s) accumulating over each factor's `delta_time`
3176    // while the bias seed stays fixed at the configured zero.
3177    // ============================================================
3178
3179    /// [`estimate_gyro_bias`] direct unit tests (not routed through the
3180    /// initializer state machine), driving the REAL [`ImuPreintegrator`]
3181    /// rather than a hand-built delta.
3182    mod gyro_bias_alignment {
3183        use super::*;
3184        use crate::imu_preintegration::ImuPreintegrator;
3185
3186        /// Build a two-factor window over a translating (`build_constant_velocity_map`),
3187        /// non-rotating body whose raw gyro stream is a known CONSTANT bias
3188        /// (no other angular excitation), integrated through the REAL
3189        /// preintegrator at a zero bias-seed linearisation. The window is
3190        /// short enough (0.02 s at a ~5e-4 rad/s bias) that the total
3191        /// rotation angle stays tiny, keeping the first-order bias-Jacobian
3192        /// correction accurate to well below the tolerance asserted below.
3193        fn real_integrated_factors_with_constant_gyro_bias(
3194            bias_gyro_true: Vector3<f64>,
3195            steps: usize,
3196            dt: f64,
3197        ) -> Vec<ImuPreintegrationFactor> {
3198            [(1u64, 2u64), (2, 3)]
3199                .into_iter()
3200                .map(|(from_id, to_id)| {
3201                    let mut pre =
3202                        ImuPreintegrator::new_with_bias(Vector3::zeros(), Vector3::zeros());
3203                    for _ in 0..steps {
3204                        pre.integrate_sample(bias_gyro_true, Vector3::new(0.0, 9.81, 0.0), dt);
3205                    }
3206                    ImuPreintegrationFactor {
3207                        keyframe_id_from: from_id,
3208                        keyframe_id_to: to_id,
3209                        delta: pre.delta(),
3210                        gravity_world: Vector3::new(0.0, 9.81, 0.0),
3211                        weight_position: 1.0,
3212                        weight_velocity: 1.0,
3213                        weight_rotation: 1.0,
3214                    }
3215                })
3216                .collect()
3217        }
3218
3219        #[test]
3220        fn recovers_a_known_constant_bias_through_the_real_preintegrator() {
3221            let bias_gyro_true = Vector3::new(0.0005, -0.0003, 0.0002);
3222            let factors =
3223                real_integrated_factors_with_constant_gyro_bias(bias_gyro_true, 20, 0.001);
3224            let map = build_constant_velocity_map(3);
3225            let ids: Vec<u64> = vec![1, 2, 3];
3226
3227            let alignment = estimate_gyro_bias(&map, &ids, &factors, Vector3::zeros())
3228                .expect("well-conditioned window must align");
3229            assert!(
3230                (alignment.bias_gyro - bias_gyro_true).norm() < 1.0e-6,
3231                "b_g_est = {:?}, b_g_true = {:?}",
3232                alignment.bias_gyro,
3233                bias_gyro_true
3234            );
3235            assert!(
3236                alignment.rotation_residual_rms_before > 0.0,
3237                "an uncorrected constant bias must leave a nonzero residual"
3238            );
3239            assert!(
3240                alignment.rotation_residual_rms_after
3241                    < alignment.rotation_residual_rms_before * 1.0e-3,
3242                "rms_before={}, rms_after={}",
3243                alignment.rotation_residual_rms_before,
3244                alignment.rotation_residual_rms_after
3245            );
3246        }
3247
3248        #[test]
3249        fn degenerate_window_with_a_single_factor_returns_none() {
3250            let factors = real_integrated_factors_with_constant_gyro_bias(
3251                Vector3::new(0.001, 0.0, 0.0),
3252                20,
3253                0.001,
3254            );
3255            let single_factor = vec![factors[0].clone()];
3256            let map = build_constant_velocity_map(2);
3257            let ids: Vec<u64> = vec![1, 2];
3258            assert!(
3259                estimate_gyro_bias(&map, &ids, &single_factor, Vector3::zeros()).is_none(),
3260                "a single-factor window must be reported degenerate"
3261            );
3262        }
3263
3264        #[test]
3265        fn real_preintegrator_regression_gyro_bias_then_gravity_recovery() {
3266            // Closes the gap noted in the gravity-alignment tests above (all
3267            // of which use hand-built factors): drive raw IMU samples
3268            // carrying BOTH a known constant gyro bias AND an off-axis
3269            // gravity through the REAL preintegrator, run `estimate_gyro_bias`
3270            // first, then feed its recovered bias into
3271            // `estimate_gravity_and_velocities` as the (corrected) bias
3272            // seed — mirroring the exact order
3273            // `try_initialize_with_bias_seed` runs them in.
3274            let true_gravity = Vector3::new(6.54, -3.27, 6.54); // |g| = 9.81
3275            let velocity = Vector3::new(1.2, -0.7, 0.3);
3276            let bias_gyro_true = Vector3::new(0.0005, -0.0003, 0.0002);
3277            let dt_step = 0.001;
3278            let steps = 20;
3279            let window = (steps as f64) * dt_step;
3280            let map = build_map_at_velocity(5, window, velocity);
3281            let ids: Vec<u64> = (1..=5).collect();
3282            let mut factors = Vec::new();
3283            for (from_id, to_id) in [(1u64, 2u64), (2, 3), (3, 4), (4, 5)] {
3284                let mut pre = ImuPreintegrator::new_with_bias(Vector3::zeros(), Vector3::zeros());
3285                for _ in 0..steps {
3286                    pre.integrate_sample(bias_gyro_true, -true_gravity, dt_step);
3287                }
3288                factors.push(ImuPreintegrationFactor {
3289                    keyframe_id_from: from_id,
3290                    keyframe_id_to: to_id,
3291                    delta: pre.delta(),
3292                    gravity_world: true_gravity,
3293                    weight_position: 1.0,
3294                    weight_velocity: 1.0,
3295                    weight_rotation: 1.0,
3296                });
3297            }
3298
3299            let gyro_alignment = estimate_gyro_bias(&map, &ids, &factors, Vector3::zeros())
3300                .expect("well-conditioned window must align");
3301            assert!(
3302                (gyro_alignment.bias_gyro - bias_gyro_true).norm() < 1.0e-6,
3303                "b_g_est = {:?}",
3304                gyro_alignment.bias_gyro
3305            );
3306
3307            let gravity_alignment = estimate_gravity_and_velocities(
3308                &map,
3309                &ids,
3310                &factors,
3311                gyro_alignment.bias_gyro,
3312                Vector3::zeros(),
3313                9.81,
3314            )
3315            .expect("gravity alignment must still condition well after gyro-bias correction");
3316            assert!(
3317                (gravity_alignment.gravity_world - true_gravity).norm() < 1.0e-4,
3318                "g_est = {:?}",
3319                gravity_alignment.gravity_world
3320            );
3321        }
3322    }
3323
3324    /// Initializer-level (`try_initialize` / `try_initialize_with_bias_seed`)
3325    /// tests exercising the `estimate_gyro_bias` config knob end to end.
3326    mod estimate_gyro_bias_initializer {
3327        use super::*;
3328
3329        /// Like [`no_acceleration_factor`] but the STORED delta carries an
3330        /// uncompensated gyro bias: the naively-integrated (bias-seed-zero)
3331        /// `ΔR` shows a spurious rotation of `Exp(bias_gyro_true *
3332        /// delta_t)`, with an EXACT bias Jacobian
3333        /// `j_rotation_bg = -delta_t·I` (the near-static-window first-order
3334        /// value — see [`estimate_gyro_bias`]'s doc comment). Since
3335        /// `Exp(a) ⊗ Exp(-a)` is exactly the identity for any vector `a`,
3336        /// the rotation-only residual at `bias_gyro = bias_gyro_true` is
3337        /// EXACT zero regardless of `bias_gyro_true`'s direction, letting
3338        /// the tests below pin an exactly recovered bias.
3339        fn no_acceleration_factor_with_gyro_bias(
3340            from_id: u64,
3341            to_id: u64,
3342            delta_t: f64,
3343            gravity: Vector3<f64>,
3344            bias_gyro_true: Vector3<f64>,
3345        ) -> ImuPreintegrationFactor {
3346            let mut delta = ImuPreintegratedDelta::identity();
3347            delta.delta_time = delta_t;
3348            delta.delta_velocity = -gravity * delta_t;
3349            delta.delta_position = -0.5 * gravity * delta_t * delta_t;
3350            delta.delta_rotation =
3351                SO3::from_quaternion(UnitQuaternion::from_scaled_axis(bias_gyro_true * delta_t));
3352            delta.j_rotation_bg = Matrix3::identity() * (-delta_t);
3353            ImuPreintegrationFactor {
3354                keyframe_id_from: from_id,
3355                keyframe_id_to: to_id,
3356                delta,
3357                gravity_world: gravity,
3358                weight_position: 1.0,
3359                weight_velocity: 1.0,
3360                weight_rotation: 1.0,
3361            }
3362        }
3363
3364        /// Combines [`no_acceleration_factor_with_gyro_bias`] with
3365        /// [`no_acceleration_factor_with_assumed_gravity`]'s TRUE-vs-ASSUMED
3366        /// gravity decoupling, for the composition test exercising
3367        /// `estimate_gyro_bias` and `estimate_gravity` together.
3368        fn no_acceleration_factor_with_assumed_gravity_and_gyro_bias(
3369            from_id: u64,
3370            to_id: u64,
3371            delta_t: f64,
3372            true_gravity: Vector3<f64>,
3373            assumed_gravity: Vector3<f64>,
3374            bias_gyro_true: Vector3<f64>,
3375        ) -> ImuPreintegrationFactor {
3376            let mut delta = ImuPreintegratedDelta::identity();
3377            delta.delta_time = delta_t;
3378            delta.delta_velocity = -true_gravity * delta_t;
3379            delta.delta_position = -0.5 * true_gravity * delta_t * delta_t;
3380            delta.delta_rotation =
3381                SO3::from_quaternion(UnitQuaternion::from_scaled_axis(bias_gyro_true * delta_t));
3382            delta.j_rotation_bg = Matrix3::identity() * (-delta_t);
3383            ImuPreintegrationFactor {
3384                keyframe_id_from: from_id,
3385                keyframe_id_to: to_id,
3386                delta,
3387                gravity_world: assumed_gravity,
3388                weight_position: 1.0,
3389                weight_velocity: 1.0,
3390                weight_rotation: 1.0,
3391            }
3392        }
3393
3394        #[test]
3395        fn recovers_from_gyro_bias_where_the_legacy_bias_fixed_path_rejects() {
3396            // Mirrors the EuRoC diagnosis directly: a `BiasReleaseSchedule`
3397            // Stage A window (bias fixed at the seed) sees a rotation
3398            // residual driven ENTIRELY by uncompensated gyro bias —
3399            // independent of velocity, position, or gravity, since bias is
3400            // not free to move and rotation residual depends only on the
3401            // (fixed) visual poses and the (bias-fixed) IMU delta.
3402            let gravity = Vector3::new(0.0, 9.81, 0.0);
3403            let bias_gyro_true = Vector3::new(0.05, -0.03, 0.02); // EuRoC-scale, |b| ~ 0.062 rad/s
3404            let delta_t = 0.15; // matches the diagnosed per-factor Δt
3405            let factors = vec![
3406                no_acceleration_factor_with_gyro_bias(1, 2, delta_t, gravity, bias_gyro_true),
3407                no_acceleration_factor_with_gyro_bias(2, 3, delta_t, gravity, bias_gyro_true),
3408            ];
3409            let schedule = BiasReleaseSchedule {
3410                min_keyframes: 5,
3411                min_translation_meters: 3.0,
3412            };
3413            let seed = synthetic_seed();
3414
3415            // Probe: bias-fixed Stage A with NO residual gate, just to read
3416            // the actual rotation-residual RMS this fixture's uncompensated
3417            // bias leaves (decouples the gate threshold below from a
3418            // hard-coded magnitude — same technique as
3419            // `max_velocity_magnitude_gate_rejects_when_exceeded`).
3420            let mut probe = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3421                min_keyframes: 3,
3422                min_translation_meters: 1.0,
3423                gravity_world: gravity,
3424                bias_release: Some(schedule),
3425                ..MotionBasedViInitializerConfig::default()
3426            });
3427            for i in 0..3 {
3428                probe.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3429            }
3430            let mut probe_map = build_constant_velocity_map(3);
3431            let probe_residual = probe
3432                .try_initialize(&mut probe_map, &factors, &seed)
3433                .expect("bias-fixed Stage A still converges; only the gate is missing here")
3434                .final_cost_breakdown
3435                .imu_rotation_residual_rms_rad
3436                .expect("IMU factors produce a rotation residual");
3437            assert!(
3438                probe_residual > 0.0,
3439                "an uncompensated gyro bias should leave a nonzero rotation residual, got {probe_residual}"
3440            );
3441            let gate = probe_residual * 0.5;
3442
3443            let mut legacy = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3444                min_keyframes: 3,
3445                min_translation_meters: 1.0,
3446                gravity_world: gravity,
3447                bias_release: Some(schedule),
3448                max_final_imu_rotation_residual_rms_rad: Some(gate),
3449                ..MotionBasedViInitializerConfig::default()
3450            });
3451            for i in 0..3 {
3452                legacy.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3453            }
3454            let mut legacy_map = build_constant_velocity_map(3);
3455            let err = legacy
3456                .try_initialize(&mut legacy_map, &factors, &seed)
3457                .expect_err("bias-fixed Stage A must be rejected by the rotation-residual gate");
3458            assert!(
3459                matches!(
3460                    err,
3461                    MotionBasedViRejectionReason::ImuRawResidualOutOfRange { .. }
3462                ),
3463                "unexpected rejection: {err:?}"
3464            );
3465
3466            let mut estimated = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3467                min_keyframes: 3,
3468                min_translation_meters: 1.0,
3469                gravity_world: gravity,
3470                bias_release: Some(schedule),
3471                max_final_imu_rotation_residual_rms_rad: Some(gate),
3472                estimate_gyro_bias: true,
3473                ..MotionBasedViInitializerConfig::default()
3474            });
3475            for i in 0..3 {
3476                estimated.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3477            }
3478            let mut estimated_map = build_constant_velocity_map(3);
3479            let result = estimated
3480                .try_initialize(&mut estimated_map, &factors, &seed)
3481                .expect("gyro-bias estimation must clear the same gate")
3482                .clone();
3483            assert!(
3484                !result.bias_released,
3485                "still Stage A — the schedule's release gate is not met"
3486            );
3487            let b_g_est = result
3488                .estimated_gyro_bias
3489                .expect("estimate_gyro_bias=true must report the recovered vector");
3490            assert!(
3491                (b_g_est - bias_gyro_true).norm() < 1.0e-6,
3492                "recovered bias {b_g_est:?} should match the true {bias_gyro_true:?}"
3493            );
3494            for state in result.keyframe_states.values() {
3495                assert!(
3496                    (state.bias_gyro - bias_gyro_true).norm() < 1.0e-9,
3497                    "Stage A must fix gyro bias at the ESTIMATE, not the raw seed"
3498                );
3499                assert!(
3500                    (state.bias_acc - seed.bias_acc).norm() < 1.0e-9,
3501                    "Stage A must leave accel bias at the seed"
3502                );
3503            }
3504        }
3505
3506        #[test]
3507        fn degenerate_when_no_factors_connect_the_window() {
3508            let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3509                min_keyframes: 3,
3510                min_translation_meters: 1.0,
3511                estimate_gyro_bias: true,
3512                ..MotionBasedViInitializerConfig::default()
3513            });
3514            for i in 0..3 {
3515                init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3516            }
3517            let mut map = build_constant_velocity_map(3);
3518            let seed = synthetic_seed();
3519            let err = init
3520                .try_initialize(&mut map, &[], &seed)
3521                .expect_err("no factors means the alignment cannot condition at all");
3522            assert!(matches!(
3523                err,
3524                MotionBasedViRejectionReason::GyroBiasEstimateDegenerate
3525            ));
3526        }
3527
3528        #[test]
3529        fn composes_with_gravity_estimation_and_staged_bias_release_stage_a() {
3530            let true_gravity = Vector3::new(0.0, 0.0, 9.81);
3531            let assumed_gravity = Vector3::new(0.0, 9.81, 0.0);
3532            let bias_gyro_true = Vector3::new(0.05, -0.03, 0.02);
3533            let mut init = MotionBasedViInitializer::new(MotionBasedViInitializerConfig {
3534                min_keyframes: 3,
3535                min_translation_meters: 1.0,
3536                gravity_world: assumed_gravity,
3537                estimate_gravity: true,
3538                estimate_gyro_bias: true,
3539                bias_release: Some(BiasReleaseSchedule {
3540                    min_keyframes: 5,
3541                    min_translation_meters: 3.0,
3542                }),
3543                ..MotionBasedViInitializerConfig::default()
3544            });
3545            for i in 0..3 {
3546                init.register_keyframe((i as u64) + 1, Point3::new(i as f64, 0.0, 0.0));
3547            }
3548            let mut map = build_constant_velocity_map(3);
3549            let seed = synthetic_seed();
3550            let factors = vec![
3551                no_acceleration_factor_with_assumed_gravity_and_gyro_bias(
3552                    1,
3553                    2,
3554                    0.15,
3555                    true_gravity,
3556                    assumed_gravity,
3557                    bias_gyro_true,
3558                ),
3559                no_acceleration_factor_with_assumed_gravity_and_gyro_bias(
3560                    2,
3561                    3,
3562                    0.15,
3563                    true_gravity,
3564                    assumed_gravity,
3565                    bias_gyro_true,
3566                ),
3567            ];
3568            let result = init
3569                .try_initialize(&mut map, &factors, &seed)
3570                .expect("Stage A must fire with both estimations enabled")
3571                .clone();
3572            assert!(!result.bias_released, "Stage A must not release bias");
3573            let g_est = result
3574                .estimated_gravity_world
3575                .expect("gravity estimate must be reported alongside the gyro-bias estimate");
3576            assert!(
3577                (g_est - true_gravity).norm() < 0.05,
3578                "recovered gravity {g_est:?} should match the true {true_gravity:?}"
3579            );
3580            let b_g_est = result
3581                .estimated_gyro_bias
3582                .expect("gyro-bias estimate must be reported alongside the gravity estimate");
3583            assert!(
3584                (b_g_est - bias_gyro_true).norm() < 1.0e-6,
3585                "recovered bias {b_g_est:?} should match the true {bias_gyro_true:?}"
3586            );
3587            for state in result.keyframe_states.values() {
3588                assert!(
3589                    (state.bias_gyro - bias_gyro_true).norm() < 1.0e-9,
3590                    "Stage A must fix gyro bias at the ESTIMATE"
3591                );
3592            }
3593        }
3594    }
3595}