Skip to main content

visloc_slam/
online_slam_vi_ba.rs

1//! Sliding-window local VI-BA stage for [`crate::OnlineSlamPipeline`].
2//!
3//! The `OnlineSlamPipeline` already detects new keyframes (via the local
4//! mapper's `AppliedMapUpdate { keyframe_count > 0 }`) and snapshots a
5//! Forster `ImuPreintegrationFactor` between every consecutive keyframe
6//! pair. The factor used to be a "hint for downstream glue" — this module
7//! turns it into an active solver step inside the pipeline.
8//!
9//! Every `trigger_every` newly-emitted IMU factor (default: every factor),
10//! the stage:
11//!
12//! 1. Slices the trailing `window_size` keyframes out of `map.keyframes`
13//!    (ordered by keyframe id).
14//! 2. Builds a [`BundleAdjustment`] over those keyframes' poses + the
15//!    landmarks they observe at least twice within the window (so isolated
16//!    "in only one keyframe" tracks don't contribute Jacobian rows).
17//! 3. Attaches every stored [`ImuPreintegrationFactor`] whose `from / to`
18//!    keyframe pair both live inside the window, then promotes per-keyframe
19//!    `(velocity, bias_gyro, bias_acc)` slots out of the per-pipeline state
20//!    table. The first in-window keyframe's pose / velocity / bias are
21//!    gauge-fixed; everything else is free.
22//! 4. Runs `BundleAdjustment::optimize` with the user-supplied
23//!    [`BaConfig`].
24//! 5. Optionally rejects writeback when the optimiser fails the configured
25//!    cost-ratio or velocity quality gate.
26//! 6. Writes the refined poses back into `map.keyframes[*].frame.pose` and
27//!    `map.landmarks[*].position`, and writes the refined `(velocity, bias_gyro,
28//!    bias_acc)` back into the per-keyframe state table so the next trigger
29//!    starts from the new linearisation point.
30//!
31//! The stage is opt-in. `OnlineSlamConfig.local_vi_ba: Option<…>` is `None`
32//! by default, so the IMU-free flows added in earlier tasks pay no
33//! per-frame overhead.
34
35use std::collections::{BTreeMap, BTreeSet};
36
37use nalgebra::{DMatrix, DVector, Vector3, Vector6};
38use visloc_core::geometry::SE3;
39use visloc_core::types::{Camera, VisualMap};
40
41use crate::bundle::{
42    build_sqrt_factor_rows, relative_observation_confidence_weights, BaConfig, BaCostBreakdown,
43    BaGeneralStereoObservation, BaObservation, BaResult, BiasRandomWalkFactor, BundleAdjustment,
44    NavigationStatePrior,
45};
46use crate::imu_preintegration::ImuPreintegrationFactor;
47use crate::marginalization::marginalize;
48use crate::{LinearSolver, RobustKernel};
49
50fn bias_random_walk_information(
51    noise_densities: (f64, f64),
52    delta_time: f64,
53) -> Option<(f64, f64)> {
54    let (sigma_gyro, sigma_accel) = noise_densities;
55    if !sigma_gyro.is_finite()
56        || sigma_gyro <= 0.0
57        || !sigma_accel.is_finite()
58        || sigma_accel <= 0.0
59        || !delta_time.is_finite()
60        || delta_time <= 0.0
61    {
62        return None;
63    }
64    Some((
65        1.0 / (sigma_gyro * sigma_gyro * delta_time),
66        1.0 / (sigma_accel * sigma_accel * delta_time),
67    ))
68}
69
70/// Adaptive refined-velocity writeback gate for [`OnlineSlamLocalBaConfig`].
71///
72/// The gate builds a per-trigger reference envelope from the current
73/// in-window velocity state, pose-delta / IMU-`dt` finite differences,
74/// and IMU-predicted next-keyframe velocities, then rejects BA writeback
75/// only when the refined max velocity exceeds `quantile(reference) *
76/// multiplier + margin_mps`, after lower/upper bounds are applied. This
77/// keeps a raw fixed `m/s` threshold available as a safety ceiling while
78/// making the main decision relative to the local motion scale.
79#[derive(Debug, Clone, PartialEq)]
80pub struct AdaptiveVelocityGateConfig {
81    /// Robust reference quantile in `[0, 1]`. Values outside the range are
82    /// clamped at use-site so ad-hoc experiment configs cannot panic.
83    pub reference_quantile: f64,
84    /// Multiplier applied to the robust reference velocity.
85    pub multiplier: f64,
86    /// Additive slack in m/s after the multiplier.
87    pub margin_mps: f64,
88    /// Minimum threshold in m/s, after multiplier/slack.
89    pub min_threshold_mps: f64,
90    /// Optional hard upper bound in m/s. Use the legacy fixed velocity
91    /// gate for an unconditional ceiling; this field keeps the adaptive
92    /// threshold itself bounded for experiments.
93    pub max_threshold_mps: Option<f64>,
94    /// Minimum number of finite reference velocities required before the
95    /// adaptive gate is active. If fewer samples are available, the gate
96    /// reports `None` and does not reject.
97    pub min_reference_count: usize,
98}
99
100impl Default for AdaptiveVelocityGateConfig {
101    fn default() -> Self {
102        Self {
103            reference_quantile: 0.8,
104            multiplier: 2.5,
105            margin_mps: 1.0,
106            min_threshold_mps: 3.0,
107            max_threshold_mps: None,
108            min_reference_count: 2,
109        }
110    }
111}
112
113/// Configuration for the sliding-window local VI-BA stage.
114#[derive(Debug, Clone, PartialEq)]
115pub struct OnlineSlamLocalBaConfig {
116    /// Run the BA every `trigger_every` newly-emitted IMU factors. `1`
117    /// triggers on every new keyframe; larger values batch a few factors
118    /// per solve. A value of `0` is rejected at construction.
119    pub trigger_every: usize,
120    /// Trailing window depth (keyframe count). The window holds the most
121    /// recent `window_size` keyframes (or all of them, when fewer have
122    /// been registered). Should be at least `2`. Common KITTI-rate value
123    /// is `5..=10`.
124    pub window_size: usize,
125    /// Minimum number of in-window observations a landmark must have for
126    /// it to contribute Jacobian rows. `2` (default) excludes
127    /// "seen once in the window" landmarks that would only add a single
128    /// 2-row block per BA iteration without disambiguating geometry.
129    pub min_observations_per_landmark: usize,
130    /// Use calibrated right-camera measurements when the map carries a
131    /// matching stereo observation. This anchors metric structure inside the
132    /// same tight pose/landmark/IMU solve rather than treating a stereo map as
133    /// monocular after bootstrap.
134    pub use_general_stereo_observations: bool,
135    /// Optional right-image reprojection gate applied before admitting an
136    /// existing stereo observation into the local solve.
137    pub general_stereo_max_initial_right_reprojection_error_px: Option<f64>,
138    /// Consume matcher confidence preserved on map observations. Set false to
139    /// run the identical window with uniform visual weights for an A/B
140    /// tracking-cliff ablation.
141    pub use_observation_confidence_weights: bool,
142    /// Inner [`BaConfig`] passed straight through to
143    /// [`BundleAdjustment::optimize`]. Default uses
144    /// [`LinearSolver::Sparse`] to keep the solve cheap on larger windows.
145    pub ba_config: BaConfig,
146    /// World-frame gravity vector used to seed bias slot initial values.
147    /// Mirrors the parent `OnlineSlamImuConfig.gravity_world` — kept here
148    /// so the stage is self-contained and unit tests can drive it without
149    /// constructing the full pipeline.
150    pub gravity_world: Vector3<f64>,
151    /// Rigid transform from the tracked camera/sensor frame into the IMU body
152    /// frame (`T_b<-c`, EuRoC `T_BS`). Identity is valid only for co-located,
153    /// axis-aligned camera and IMU frames.
154    pub body_to_camera: SE3,
155    /// Initial bias-gyro linearisation point for newly-promoted keyframes.
156    pub bias_gyro_init: Vector3<f64>,
157    /// Initial bias-acc linearisation point for newly-promoted keyframes.
158    pub bias_acc_init: Vector3<f64>,
159    /// Optional `(gyro, accel)` information weights for adjacent bias
160    /// random-walk factors. Use `1 / (sigma_random_walk² * dt)` only when
161    /// the other IMU residual blocks use compatible covariance weighting.
162    /// `None` preserves the diagnostic legacy behavior; promoted tight VI
163    /// fusion must provide a physically calibrated prior.
164    pub bias_random_walk_weights: Option<(f64, f64)>,
165    /// Optional continuous-time gyro/accelerometer bias random-walk noise
166    /// densities. When set, each adjacent factor receives information
167    /// `1 / (sigma² * delta_time)`, so irregular keyframe spacing is handled
168    /// physically. Takes precedence over `bias_random_walk_weights`.
169    pub bias_random_walk_noise_densities: Option<(f64, f64)>,
170    /// Conditioning fallback: when the first BA pass has
171    /// `final_cost / initial_cost > threshold`, the cost surface is too
172    /// far from quadratic for the joint pose + velocity + bias solve to
173    /// be trusted. The stage re-runs the BA with **all per-keyframe
174    /// biases gauge-frozen** at their pre-BA linearisation points and
175    /// uses that result for writeback. `None` (default) disables the
176    /// fallback — legacy behaviour. A reasonable starting value is
177    /// `Some(0.9)`: the BA must reduce cost by at least 10 % per
178    /// trigger or the bias updates are discarded.
179    pub freeze_biases_when_cost_ratio_above: Option<f64>,
180    /// Writeback quality gate: when the selected BA result has
181    /// `final_cost / initial_cost > threshold`, the trigger returns
182    /// diagnostics but does **not** write refined poses, landmarks,
183    /// velocities, or biases back to the map/state. This is stricter
184    /// than [`Self::freeze_biases_when_cost_ratio_above`]: the freeze
185    /// fallback still accepts pose/velocity/landmark updates from a
186    /// re-solve, while this gate treats the whole local VI-BA result as
187    /// untrusted.
188    ///
189    /// `None` (default) preserves legacy behaviour. Start conservative
190    /// in experiments, for example `Some(1.0)` to reject passes that do
191    /// not reduce cost at all, or lower values when bad IMU factors are
192    /// known to destabilize tracking.
193    pub reject_writeback_when_cost_ratio_above: Option<f64>,
194    /// Reject writeback when the selected joint solve's covariance-whitened
195    /// IMU NIS per residual DoF remains above this limit.
196    pub reject_writeback_when_final_imu_nis_per_dof_above: Option<f64>,
197    /// Writeback velocity sanity gate: when any refined in-window
198    /// `||velocity_world||` exceeds this threshold, the trigger returns
199    /// diagnostics but skips all map/state writeback. This catches the
200    /// common tight-VIO failure mode where the visual residuals can be
201    /// fit only by pushing keyframe velocities to non-physical values.
202    ///
203    /// `None` (default) preserves legacy behaviour. EuRoC indoor runs
204    /// can start with a conservative `Some(10.0)` and then tighten once
205    /// dataset-specific velocity envelopes are measured.
206    pub reject_writeback_when_velocity_norm_above_mps: Option<f64>,
207    /// Reject the whole local solve when any keyframe camera centre moves by
208    /// more than this many metres relative to the pre-solve map.
209    pub reject_writeback_when_pose_translation_above_meters: Option<f64>,
210    /// Reject the whole local solve when any keyframe rotation changes by
211    /// more than this many radians relative to the pre-solve map.
212    pub reject_writeback_when_pose_rotation_above_radians: Option<f64>,
213    /// Reject writeback when the window has fewer than this many visual
214    /// observations. IMU-only (or nearly IMU-only) solves can zero the
215    /// IMU residual by spinning poses tens of degrees. `None` preserves
216    /// legacy behaviour.
217    pub reject_writeback_when_observation_count_below: Option<usize>,
218    /// When the pose-correction gate rejects a solve but every other
219    /// writeback gate passes, still write refined velocities/biases into
220    /// `OnlineSlamLocalBaState::keyframe_state` (and leave map poses /
221    /// landmarks untouched). Softening the pose gate itself (gate43)
222    /// admitted late 0.5–0.9 m jumps that blew rigid ATE; this keeps the
223    /// hard pose lock while still letting safe IMU-state updates land.
224    /// Default `false` preserves legacy all-or-nothing writeback.
225    pub writeback_navigation_state_despite_pose_gate: bool,
226    /// Physical bias-magnitude writeback gate: reject the whole local solve
227    /// when any in-window keyframe's refined `||bias_gyro||` exceeds this
228    /// bound (rad/s).
229    ///
230    /// Real-data motivation (`gt_full1500`, full MH_01, 1500 frames, SP
231    /// frontend, local-VI-BA NIS gate 50): local VI-BA ran 440 triggers
232    /// with 135 writebacks mirrored into the IMU motion model, and the
233    /// mirrored accel bias diverged to `[1.047, -8.401, 1.298]`
234    /// (`‖·‖ ≈ 8.6 m/s²` — near gravity magnitude). Every one of those
235    /// writebacks passed the NIS / velocity / pose-correction gates; none
236    /// of them checks whether the solution is a physically plausible IMU
237    /// bias versus the visual residuals being absorbed into the bias
238    /// slots. This mirrors the physical gate the motion-VI init stage
239    /// already applies during bootstrap
240    /// (`MotionBasedViInitializerConfig::max_gyro_bias_magnitude_rad_s`,
241    /// bench value `0.2`) — local VI-BA had no equivalent for its own
242    /// per-trigger bias updates.
243    ///
244    /// `None` (default) preserves legacy behaviour (no physical bias cap).
245    /// A reasonable starting bench value is `Some(0.2)`, mirroring the
246    /// motion-VI init bootstrap gate.
247    pub reject_gyro_bias_above_rad_s: Option<f64>,
248    /// Physical bias-magnitude writeback gate: reject the whole local solve
249    /// when any in-window keyframe's refined `||bias_acc||` exceeds this
250    /// bound (m/s²).
251    ///
252    /// See [`Self::reject_gyro_bias_above_rad_s`] for the `gt_full1500`
253    /// evidence motivating this gate (mirrored accel bias diverged to
254    /// `‖·‖ ≈ 8.6 m/s²`). Mirrors
255    /// `MotionBasedViInitializerConfig::max_accel_bias_magnitude_mps2`,
256    /// bench value `1.0`.
257    ///
258    /// `None` (default) preserves legacy behaviour (no physical bias cap).
259    /// A reasonable starting bench value is `Some(1.0)`, mirroring the
260    /// motion-VI init bootstrap gate.
261    pub reject_accel_bias_above_mps2: Option<f64>,
262    /// Adaptive writeback velocity gate. Unlike
263    /// [`Self::reject_writeback_when_velocity_norm_above_mps`], this is
264    /// not a raw scene-scale `m/s` threshold. It derives a per-trigger
265    /// threshold from the current local-window motion envelope and rejects
266    /// only when the refined velocity is large relative to that envelope.
267    ///
268    /// `None` (default) preserves legacy behaviour. Keep the fixed gate
269    /// available as a safety ceiling for A/B runs; use this gate for the
270    /// primary "is this solve locally plausible?" decision.
271    pub adaptive_velocity_gate: Option<AdaptiveVelocityGateConfig>,
272    /// Threshold-gated IMU factor re-linearisation. When `Some((g, a))`,
273    /// before each BA pass the stage walks `state.factor_history` and
274    /// re-bakes any factor whose stored `bias_*_linearisation` differs
275    /// from the current per-keyframe bias estimate (of the factor's
276    /// `keyframe_id_from`) by more than `g` (rad/s, gyro) or `a` (m/s²,
277    /// accel). The first-order bias correction is applied in-place via
278    /// [`crate::imu_preintegration::ImuPreintegratedDelta::relinearise_at`],
279    /// resetting the linearisation point to the new bias so subsequent
280    /// `residual_with_bias_correction` stays in the small-`δb` regime.
281    ///
282    /// Default `None` preserves Phase-13 behaviour: factors stay at
283    /// their construction-time linearisation (typically a placeholder
284    /// zero pre-VI-init), and the BA's `residual_with_bias_correction`
285    /// pays the full first-order extrapolation cost. Enable
286    /// `Some((0.01, 0.1))` or similar when running with
287    /// `keep_pre_promotion_imu_factors = true` so banked pre-promotion
288    /// factors get refreshed to the post-promotion bias estimate before
289    /// they're solved against — Phase-14 fix for the mirror-velocity
290    /// divergence that appears when banked stale-bias factors are
291    /// optimised at non-trivial post-promotion biases.
292    pub relinearise_imu_factor_bias_thresholds: Option<(f64, f64)>,
293    /// When `true`, run a sliding-window BA pass immediately at the
294    /// moment VI-init promotes — without waiting for the next post-
295    /// promotion IMU factor to arrive. Phase-16 lever. Currently the
296    /// `maybe_run_local_vi_ba` gate requires a freshly-staged
297    /// `ImuPreintegrationFactor` to enter the function, so banked
298    /// pre-promotion factors (with `keep_pre_promotion_imu_factors =
299    /// true`) sit idle for one keyframe-cadence after promotion before
300    /// the next factor unlocks them. Setting this flag inserts a
301    /// "promotion-time" BA trigger so the banked factors are consumed
302    /// the same frame VI-init transitions out of `is_active()`. Pairs
303    /// naturally with `keep_pre_promotion_imu_factors` + the
304    /// `relinearise_*` knob: banked factors are re-linearised at the
305    /// just-promoted bias point and immediately solved, instead of
306    /// waiting for the next keyframe registration to trigger the
307    /// chain.
308    ///
309    /// Default `false` preserves Phase-13 / Phase-14 behaviour. Useful
310    /// when the visual tracker is fragile post-promotion (next KF
311    /// arrives late or never), so the promotion event itself is the
312    /// only reliable trigger for a refinement pass.
313    pub run_at_vi_init_promotion: bool,
314    /// Carry the inertial Markov blanket across window shifts by
315    /// marginalizing the outgoing 15-DoF navigation state into a dense FEJ
316    /// prior on its successor. This replaces repeatedly fixing the newest
317    /// window anchor with infinite confidence.
318    pub marginalize_navigation_state: bool,
319    /// When [`Self::marginalize_navigation_state`] is true, marginalize the
320    /// outgoing navigation state through the square-root (QR) route
321    /// ([`crate::marginalize_sqrt_from_information`], the Basalt ICCV'21
322    /// "SqToSqrt" bridge) instead of the dense information-form Schur
323    /// complement. The resulting prior is algebraically identical — this flag
324    /// selects the numerically-robust factorization that keeps the boundary
325    /// prior in square-root (matrix-square-root) form, mirroring Basalt
326    /// `marginalizeHelperSqToSqrt`. Off by default (no behavioural change).
327    pub use_sqrt_marginalization: bool,
328    /// When [`Self::marginalize_navigation_state`] is true and this flag is also
329    /// set, carry the window's boundary prior across shifts in **square-root (QR)
330    /// factor form** (the Basalt ICCV'21 SqrtToSqrt protocol, [`crate::vi_sqrt_window`])
331    /// instead of materializing a dense `NavigationStatePrior` from the Hessian.
332    /// The scalar output `NavigationStatePrior` is still produced (identical
333    /// information), so downstream code is unchanged; the extra carried
334    /// [`crate::SqrtNavMarginal`] is stored on the state for the next window's
335    /// FEJ-consistent re-linearisation. Off by default (no behavioural change).
336    pub use_sqrt_window_marginalization: bool,
337    /// Optional `(velocity, gyro-bias, accel-bias)` 1-sigma uncertainty for
338    /// the sequence's first navigation state. With marginalization enabled,
339    /// this avoids treating static-init velocity/bias estimates as infinitely
340    /// certain. The global pose gauge remains fixed exactly.
341    pub initial_navigation_prior_std_devs: Option<(f64, f64, f64)>,
342}
343
344impl Default for OnlineSlamLocalBaConfig {
345    fn default() -> Self {
346        Self {
347            trigger_every: 1,
348            window_size: 5,
349            min_observations_per_landmark: 2,
350            use_general_stereo_observations: true,
351            general_stereo_max_initial_right_reprojection_error_px: Some(5.0),
352            use_observation_confidence_weights: false,
353            ba_config: BaConfig {
354                linear_solver: LinearSolver::Sparse,
355                max_iterations: 10,
356                ..BaConfig::default()
357            },
358            gravity_world: Vector3::new(0.0, 9.81, 0.0),
359            body_to_camera: SE3::identity(),
360            bias_gyro_init: Vector3::zeros(),
361            bias_acc_init: Vector3::zeros(),
362            bias_random_walk_weights: None,
363            bias_random_walk_noise_densities: None,
364            freeze_biases_when_cost_ratio_above: None,
365            reject_writeback_when_cost_ratio_above: None,
366            reject_writeback_when_final_imu_nis_per_dof_above: None,
367            reject_writeback_when_velocity_norm_above_mps: None,
368            reject_writeback_when_pose_translation_above_meters: None,
369            reject_writeback_when_pose_rotation_above_radians: None,
370            reject_writeback_when_observation_count_below: None,
371            writeback_navigation_state_despite_pose_gate: false,
372            reject_gyro_bias_above_rad_s: None,
373            reject_accel_bias_above_mps2: None,
374            adaptive_velocity_gate: None,
375            relinearise_imu_factor_bias_thresholds: None,
376            run_at_vi_init_promotion: false,
377            marginalize_navigation_state: false,
378            use_sqrt_marginalization: false,
379            use_sqrt_window_marginalization: true,
380            initial_navigation_prior_std_devs: None,
381        }
382    }
383}
384
385/// Per-keyframe `(velocity, bias)` state carried across BA invocations.
386#[derive(Debug, Clone, PartialEq)]
387pub struct KeyframeImuState {
388    pub velocity_world: Vector3<f64>,
389    pub bias_gyro: Vector3<f64>,
390    pub bias_acc: Vector3<f64>,
391}
392
393/// Running state of the local VI-BA stage. Owns the per-keyframe IMU
394/// state table plus a small history of recent IMU factors (last
395/// `2 * window_size` so the stage can always rebuild the connecting
396/// factors for the trailing window).
397#[derive(Debug, Clone)]
398pub struct OnlineSlamLocalBaState {
399    pub config: OnlineSlamLocalBaConfig,
400    /// Per-keyframe `(velocity, bias)` indexed by keyframe id.
401    pub keyframe_state: BTreeMap<u64, KeyframeImuState>,
402    /// Rolling history of recently emitted IMU factors. Kept long enough
403    /// to cover the trailing window even if the trigger cadence skips a
404    /// few factors. Capped at `4 * window_size` entries to bound memory.
405    pub factor_history: Vec<ImuPreintegrationFactor>,
406    /// Number of new factors observed since the last successful trigger;
407    /// rolled forward by [`Self::register_new_factor`].
408    pub pending_factors_since_last_trigger: usize,
409    /// Dense prior on the first state of the next window.
410    pub navigation_prior: Option<NavigationStatePrior>,
411    /// Square-root-form carried marginal on the retained nav states of the next window
412    /// (Basalt ICCV'21 SqrtToSqrt), populated only when
413    /// [`OnlineSlamLocalBaConfig::use_sqrt_window_marginalization`] is set.
414    pub sqrt_nav_marginal: Option<crate::SqrtNavMarginal>,
415    /// Pairwise factors recovered from the latest boundary marginalization step,
416    /// waiting to be injected into the pose-graph mirror after keyframe registration.
417    pub pending_recovered_pose_factors: Vec<(u64, u64, crate::RecoveredRelativePoseFactor)>,
418}
419
420impl PartialEq for OnlineSlamLocalBaState {
421    fn eq(&self, other: &Self) -> bool {
422        self.config == other.config
423            && self.keyframe_state == other.keyframe_state
424            && self.factor_history == other.factor_history
425            && self.pending_factors_since_last_trigger == other.pending_factors_since_last_trigger
426            && self.navigation_prior == other.navigation_prior
427            && self.sqrt_nav_marginal == other.sqrt_nav_marginal
428    }
429}
430
431impl OnlineSlamLocalBaState {
432    pub const fn new(config: OnlineSlamLocalBaConfig) -> Self {
433        Self {
434            config,
435            keyframe_state: BTreeMap::new(),
436            factor_history: Vec::new(),
437            pending_factors_since_last_trigger: 0,
438            navigation_prior: None,
439            sqrt_nav_marginal: None,
440            pending_recovered_pose_factors: Vec::new(),
441        }
442    }
443
444    /// Reset the state for a new sequence (mirrors
445    /// [`crate::OnlineSlamPipeline::reset_sequence_state`]).
446    pub fn reset(&mut self) {
447        self.keyframe_state.clear();
448        self.factor_history.clear();
449        self.pending_factors_since_last_trigger = 0;
450        self.navigation_prior = None;
451        self.sqrt_nav_marginal = None;
452        self.pending_recovered_pose_factors.clear();
453    }
454
455    /// Append a freshly-staged IMU factor to the rolling history and bump
456    /// the trigger counter. Returns `true` when the trigger threshold has
457    /// been reached, signalling the caller should run a BA pass.
458    pub fn register_new_factor(&mut self, factor: ImuPreintegrationFactor) -> bool {
459        let cap = (4 * self.config.window_size).max(self.config.window_size);
460        self.factor_history.push(factor);
461        if self.factor_history.len() > cap {
462            let overflow = self.factor_history.len() - cap;
463            self.factor_history.drain(..overflow);
464        }
465        self.pending_factors_since_last_trigger += 1;
466        self.pending_factors_since_last_trigger >= self.config.trigger_every
467    }
468}
469
470/// Per-trigger BA outcome exposed on [`crate::OnlineSlamResult`].
471#[derive(Debug, Clone, PartialEq)]
472pub struct OnlineSlamLocalBaStats {
473    /// Sorted keyframe ids included in this trigger's window.
474    pub window_keyframe_ids: Vec<u64>,
475    /// Number of landmarks that contributed observations to the solve
476    /// (after the `min_observations_per_landmark` filter).
477    pub landmark_count: usize,
478    /// Number of reprojection observations fed into the solve.
479    pub observation_count: usize,
480    /// Subset of `observation_count` represented by calibrated 4-row stereo
481    /// residuals instead of 2-row left-only residuals.
482    pub stereo_observation_count: usize,
483    /// Number of IMU factors whose `from / to` pair fell inside the
484    /// window.
485    pub imu_factor_count: usize,
486    /// Optimiser outcome; carries the LM trace + final / initial cost.
487    /// When [`Self::bias_frozen`] is `true` this is the SECOND-pass
488    /// result (the one used for writeback); the first-pass trace is
489    /// dropped on the floor. When [`Self::quality_gate_rejected`] is
490    /// `true`, this result was NOT written back.
491    pub ba_result: BaResult,
492    /// Residual-family costs at the selected solve's input and output
493    /// states. These remain available when transactional writeback is
494    /// rejected, which makes visual/inertial conflicts diagnosable.
495    pub initial_cost_breakdown: BaCostBreakdown,
496    pub final_cost_breakdown: BaCostBreakdown,
497    /// `final_cost / initial_cost` for [`Self::ba_result`]. Uses `0.0`
498    /// when `initial_cost == 0.0` because there was no residual energy
499    /// to reduce.
500    pub cost_ratio: f64,
501    /// Maximum refined in-window `||velocity_world||` in m/s from the
502    /// selected BA result. This is reported even when writeback is
503    /// rejected so runners can tune the velocity sanity gate.
504    pub max_refined_velocity_norm_mps: f64,
505    pub max_pose_translation_correction_meters: f64,
506    pub max_pose_rotation_correction_radians: f64,
507    /// Maximum refined in-window `||bias_gyro||` in rad/s from the selected
508    /// BA result. Reported even when writeback is rejected, mirroring
509    /// [`Self::max_refined_velocity_norm_mps`].
510    pub max_refined_gyro_bias_norm_rad_s: f64,
511    /// Maximum refined in-window `||bias_acc||` in m/s² from the selected
512    /// BA result. Reported even when writeback is rejected. See the
513    /// `gt_full1500` evidence on
514    /// [`OnlineSlamLocalBaConfig::reject_accel_bias_above_mps2`]: the
515    /// unfiltered mirrored value reached `‖·‖ ≈ 8.6`.
516    pub max_refined_accel_bias_norm_mps2: f64,
517    /// Adaptive velocity threshold used for this trigger, if the
518    /// adaptive gate was enabled and enough finite local reference
519    /// velocities were available.
520    pub adaptive_velocity_gate_threshold_mps: Option<f64>,
521    /// `true` when the conditioning fallback in
522    /// [`OnlineSlamLocalBaConfig::freeze_biases_when_cost_ratio_above`]
523    /// fired this trigger. The window was re-solved with biases gauge-
524    /// frozen at their pre-BA linearisation points, and the BA's bias
525    /// updates were NOT written back into the state table.
526    pub bias_frozen: bool,
527    /// `true` when
528    /// [`OnlineSlamLocalBaConfig::reject_writeback_when_cost_ratio_above`]
529    /// rejected the selected BA result. The returned diagnostics describe
530    /// the rejected solve, but map poses, landmarks, velocities, and
531    /// biases were left unchanged.
532    pub quality_gate_rejected: bool,
533    /// `true` when the cost-ratio part of the writeback quality gate
534    /// rejected this trigger.
535    pub cost_ratio_gate_rejected: bool,
536    pub imu_nis_gate_rejected: bool,
537    /// `true` when the refined-velocity part of the writeback quality
538    /// gate rejected this trigger.
539    pub velocity_gate_rejected: bool,
540    pub pose_correction_gate_rejected: bool,
541    /// `true` when
542    /// [`OnlineSlamLocalBaConfig::reject_writeback_when_observation_count_below`]
543    /// rejected this trigger because the window was too visually sparse.
544    pub observation_count_gate_rejected: bool,
545    /// `true` when map pose/landmark writeback was blocked by the pose
546    /// correction gate, but refined velocities/biases were still written
547    /// into the local VI-BA state table because
548    /// [`OnlineSlamLocalBaConfig::writeback_navigation_state_despite_pose_gate`]
549    /// was enabled and every non-pose gate passed.
550    pub navigation_state_partially_written: bool,
551    /// `true` when either
552    /// [`OnlineSlamLocalBaConfig::reject_gyro_bias_above_rad_s`] or
553    /// [`OnlineSlamLocalBaConfig::reject_accel_bias_above_mps2`] rejected
554    /// this trigger because a refined in-window bias magnitude exceeded
555    /// its configured bound.
556    pub bias_magnitude_gate_rejected: bool,
557    /// `true` when the adaptive refined-velocity gate rejected this
558    /// trigger.
559    pub adaptive_velocity_gate_rejected: bool,
560    /// Number of IMU factors whose stored `bias_*_linearisation` was
561    /// refreshed by the threshold-gated re-linearisation pass driven by
562    /// [`OnlineSlamLocalBaConfig::relinearise_imu_factor_bias_thresholds`].
563    /// Always `0` when that config is `None`. Counts every factor walked
564    /// in this trigger, not just the in-window subset — refreshing
565    /// `state.factor_history` whole-vector ensures future windows
566    /// inherit the up-to-date linearisation point.
567    pub relinearised_factor_count: usize,
568    /// Whether a carried navigation prior constrained this solve.
569    pub marginalization_prior_applied: bool,
570    /// Whether this trigger produced the prior for the next shifted window.
571    pub marginalization_succeeded: bool,
572    /// Chow-Liu relative-pose factors recovered from the sqrt marginal and
573    /// injected into the pose-graph mirror (Basalt mapper analogue).
574    pub recovered_marginal_factors_injected: usize,
575    /// Factors enqueued this trigger before pose-graph injection.
576    pub recovered_marginal_factors_enqueued: usize,
577}
578
579fn ba_cost_ratio(result: &BaResult) -> f64 {
580    if result.initial_cost > 0.0 {
581        result.final_cost / result.initial_cost
582    } else {
583        0.0
584    }
585}
586
587fn compute_max_refined_velocity_norm_mps(ba: &BundleAdjustment, window_ids: &[u64]) -> f64 {
588    window_ids
589        .iter()
590        .filter_map(|kf_id| ba.velocities.get(kf_id))
591        .map(|velocity| velocity.norm())
592        .fold(0.0_f64, f64::max)
593}
594
595/// Maximum in-window refined `(||bias_gyro||, ||bias_acc||)` from the
596/// selected BA result. Used both for diagnostics and by
597/// [`OnlineSlamLocalBaConfig::reject_gyro_bias_above_rad_s`] /
598/// [`OnlineSlamLocalBaConfig::reject_accel_bias_above_mps2`].
599fn compute_max_refined_bias_norms(ba: &BundleAdjustment, window_ids: &[u64]) -> (f64, f64) {
600    let mut max_gyro = 0.0_f64;
601    let mut max_accel = 0.0_f64;
602    for kf_id in window_ids {
603        let Some(bias) = ba.biases.get(kf_id) else {
604            continue;
605        };
606        let gyro_norm = Vector3::new(bias[0], bias[1], bias[2]).norm();
607        let accel_norm = Vector3::new(bias[3], bias[4], bias[5]).norm();
608        if gyro_norm.is_finite() {
609            max_gyro = max_gyro.max(gyro_norm);
610        }
611        if accel_norm.is_finite() {
612            max_accel = max_accel.max(accel_norm);
613        }
614    }
615    (max_gyro, max_accel)
616}
617
618fn max_pose_correction(map: &VisualMap, ba: &BundleAdjustment, window_ids: &[u64]) -> (f64, f64) {
619    let mut max_translation = 0.0_f64;
620    let mut max_rotation = 0.0_f64;
621    for id in window_ids {
622        let (Some(before), Some(after)) = (
623            map.keyframes
624                .get(id)
625                .and_then(|keyframe| keyframe.frame.pose.as_ref()),
626            ba.poses.get(id),
627        ) else {
628            continue;
629        };
630        max_translation = max_translation
631            .max((after.camera_center_world() - before.camera_center_world()).norm());
632        let rotation_delta =
633            before.world_to_camera.rotation.inverse() * after.world_to_camera.rotation;
634        max_rotation = max_rotation.max(rotation_delta.angle());
635    }
636    (max_translation, max_rotation)
637}
638
639fn robust_quantile(values: &mut Vec<f64>, quantile: f64) -> Option<f64> {
640    values.retain(|value| value.is_finite() && *value >= 0.0);
641    if values.is_empty() {
642        return None;
643    }
644    values.sort_by(|a, b| a.total_cmp(b));
645    let q = quantile.clamp(0.0, 1.0);
646    let idx = ((values.len() - 1) as f64 * q).ceil() as usize;
647    values.get(idx).copied()
648}
649
650fn pose_delta_velocity_norms_for_window(
651    map: &VisualMap,
652    factors: &[ImuPreintegrationFactor],
653    body_to_camera: &SE3,
654) -> Vec<f64> {
655    let mut norms = Vec::new();
656    for factor in factors {
657        let dt = factor.delta.delta_time;
658        if dt <= 0.0 || !dt.is_finite() {
659            continue;
660        }
661        let Some(prev_center) = map
662            .keyframes
663            .get(&factor.keyframe_id_from)
664            .and_then(|kf| kf.frame.pose.as_ref())
665            .map(|pose| {
666                body_to_camera
667                    .compose(&pose.world_to_camera)
668                    .inverse()
669                    .translation
670            })
671        else {
672            continue;
673        };
674        let Some(curr_center) = map
675            .keyframes
676            .get(&factor.keyframe_id_to)
677            .and_then(|kf| kf.frame.pose.as_ref())
678            .map(|pose| {
679                body_to_camera
680                    .compose(&pose.world_to_camera)
681                    .inverse()
682                    .translation
683            })
684        else {
685            continue;
686        };
687        let velocity_norm = ((curr_center - prev_center) / dt).norm();
688        if velocity_norm.is_finite() {
689            norms.push(velocity_norm);
690        }
691    }
692    norms
693}
694
695fn imu_predicted_velocity_norms_for_window(
696    map: &VisualMap,
697    state: &OnlineSlamLocalBaState,
698    factors: &[ImuPreintegrationFactor],
699) -> Vec<f64> {
700    let mut norms = Vec::new();
701    for factor in factors {
702        let dt = factor.delta.delta_time;
703        if dt <= 0.0 || !dt.is_finite() {
704            continue;
705        }
706        let Some(from_state) = state.keyframe_state.get(&factor.keyframe_id_from) else {
707            continue;
708        };
709        let Some(rotation_body_to_world) = map
710            .keyframes
711            .get(&factor.keyframe_id_from)
712            .and_then(|kf| kf.frame.pose.as_ref())
713            .map(|pose| {
714                state
715                    .config
716                    .body_to_camera
717                    .compose(&pose.world_to_camera)
718                    .rotation
719                    .inverse()
720            })
721        else {
722            continue;
723        };
724        let predicted_velocity = from_state.velocity_world
725            + factor.gravity_world * dt
726            + rotation_body_to_world * factor.delta.delta_velocity;
727        let norm = predicted_velocity.norm();
728        if norm.is_finite() {
729            norms.push(norm);
730        }
731    }
732    norms
733}
734
735fn compute_adaptive_velocity_gate_threshold_mps(
736    map: &VisualMap,
737    state: &OnlineSlamLocalBaState,
738    window_ids: &[u64],
739    factors: &[ImuPreintegrationFactor],
740    config: &AdaptiveVelocityGateConfig,
741) -> Option<f64> {
742    let mut reference_norms: Vec<f64> = window_ids
743        .iter()
744        .filter_map(|kf_id| state.keyframe_state.get(kf_id))
745        .map(|slot| slot.velocity_world.norm())
746        .filter(|value| value.is_finite() && *value >= 0.0)
747        .collect();
748    reference_norms.extend(pose_delta_velocity_norms_for_window(
749        map,
750        factors,
751        &state.config.body_to_camera,
752    ));
753    reference_norms.extend(imu_predicted_velocity_norms_for_window(map, state, factors));
754    if reference_norms.len() < config.min_reference_count.max(1) {
755        return None;
756    }
757
758    let reference = robust_quantile(&mut reference_norms, config.reference_quantile)?;
759    let multiplier = config.multiplier.max(0.0);
760    let margin = config.margin_mps.max(0.0);
761    let min_threshold = config.min_threshold_mps.max(0.0);
762    let mut threshold = reference * multiplier + margin;
763    if !threshold.is_finite() {
764        return None;
765    }
766    threshold = threshold.max(min_threshold);
767    if let Some(max_threshold) = config.max_threshold_mps {
768        if max_threshold.is_finite() && max_threshold >= 0.0 {
769            threshold = threshold.min(max_threshold);
770        }
771    }
772    Some(threshold)
773}
774
775fn next_navigation_prior(
776    map: &VisualMap,
777    state: &OnlineSlamLocalBaState,
778    window_ids: &[u64],
779    factors: &[ImuPreintegrationFactor],
780) -> Option<NavigationStatePrior> {
781    let (&old_id, &next_id) = (window_ids.first()?, window_ids.get(1)?);
782    let boundary = factors
783        .iter()
784        .find(|factor| factor.keyframe_id_from == old_id && factor.keyframe_id_to == next_id)?;
785    let camera_id = map.keyframes.get(&old_id)?.frame.camera_id;
786    let camera = map.cameras.get(&camera_id)?.clone();
787    let mut boundary_problem = BundleAdjustment::new(camera);
788    boundary_problem.set_imu_body_to_camera(state.config.body_to_camera.clone());
789
790    for id in [old_id, next_id] {
791        let pose = map.keyframes.get(&id)?.frame.pose.clone()?;
792        let nav = state.keyframe_state.get(&id)?;
793        boundary_problem.add_pose(id, pose);
794        boundary_problem.add_velocity(id, nav.velocity_world);
795        boundary_problem.add_bias(
796            id,
797            Vector6::new(
798                nav.bias_gyro.x,
799                nav.bias_gyro.y,
800                nav.bias_gyro.z,
801                nav.bias_acc.x,
802                nav.bias_acc.y,
803                nav.bias_acc.z,
804            ),
805        );
806    }
807
808    let carried_prior = state
809        .navigation_prior
810        .as_ref()
811        .filter(|prior| prior.keyframe_ids.as_slice() == [old_id]);
812    if let Some(prior) = carried_prior {
813        boundary_problem.set_navigation_state_prior(prior.clone());
814    } else {
815        // The sequence's first state defines the global gauge. The first
816        // pose is exact, but velocity/static-init biases should retain their
817        // finite initialization uncertainty when calibrated standard
818        // deviations are available.
819        boundary_problem.fix_pose(old_id);
820        if let Some((sigma_velocity, sigma_gyro_bias, sigma_accel_bias)) =
821            state.config.initial_navigation_prior_std_devs
822        {
823            if !sigma_velocity.is_finite()
824                || sigma_velocity <= 0.0
825                || !sigma_gyro_bias.is_finite()
826                || sigma_gyro_bias <= 0.0
827                || !sigma_accel_bias.is_finite()
828                || sigma_accel_bias <= 0.0
829            {
830                return None;
831            }
832            let mut information = DMatrix::zeros(15, 15);
833            for component in 6..9 {
834                information[(component, component)] = 1.0 / sigma_velocity.powi(2);
835            }
836            for component in 9..12 {
837                information[(component, component)] = 1.0 / sigma_gyro_bias.powi(2);
838            }
839            for component in 12..15 {
840                information[(component, component)] = 1.0 / sigma_accel_bias.powi(2);
841            }
842            let old_nav = state.keyframe_state.get(&old_id)?;
843            let old_pose = map.keyframes.get(&old_id)?.frame.pose.clone()?;
844            boundary_problem.set_navigation_state_prior(NavigationStatePrior {
845                keyframe_ids: vec![old_id],
846                reference_poses: BTreeMap::from([(old_id, old_pose)]),
847                reference_velocities: BTreeMap::from([(old_id, old_nav.velocity_world)]),
848                reference_biases: BTreeMap::from([(
849                    old_id,
850                    Vector6::new(
851                        old_nav.bias_gyro.x,
852                        old_nav.bias_gyro.y,
853                        old_nav.bias_gyro.z,
854                        old_nav.bias_acc.x,
855                        old_nav.bias_acc.y,
856                        old_nav.bias_acc.z,
857                    ),
858                )]),
859                information,
860                gradient: DVector::zeros(15),
861                constant_cost: 0.0,
862            });
863        } else {
864            boundary_problem.fix_velocity(old_id);
865            boundary_problem.fix_bias(old_id);
866        }
867    }
868    boundary_problem.add_imu_factor(boundary.clone());
869    if state.config.bias_random_walk_noise_densities.is_some()
870        || state.config.bias_random_walk_weights.is_some()
871    {
872        let (weight_gyro, weight_accel) =
873            if let Some(noise) = state.config.bias_random_walk_noise_densities {
874                bias_random_walk_information(noise, boundary.delta.delta_time)?
875            } else {
876                state.config.bias_random_walk_weights?
877            };
878        boundary_problem.add_bias_random_walk_factor(BiasRandomWalkFactor {
879            keyframe_id_from: old_id,
880            keyframe_id_to: next_id,
881            weight_gyro,
882            weight_accel,
883        });
884    } else {
885        // Without a bias-evolution model the successor's six bias DoFs have
886        // no information and the marginal is necessarily singular.
887        return None;
888    }
889
890    let linearized = boundary_problem.linearized_navigation_system()?;
891    let pose_offset = 0usize;
892    let velocity_offset = linearized.pose_ids.len() * 6;
893    let bias_offset = velocity_offset + linearized.velocity_ids.len() * 3;
894    let pose_slot = linearized.pose_ids.iter().position(|id| *id == next_id)?;
895    let velocity_slot = linearized
896        .velocity_ids
897        .iter()
898        .position(|id| *id == next_id)?;
899    let bias_slot = linearized.bias_ids.iter().position(|id| *id == next_id)?;
900    let mut keep = Vec::with_capacity(15);
901    keep.extend((0..6).map(|component| pose_offset + pose_slot * 6 + component));
902    keep.extend((0..3).map(|component| velocity_offset + velocity_slot * 3 + component));
903    keep.extend((0..6).map(|component| bias_offset + bias_slot * 6 + component));
904
905    // Normal equations use gradient g = J^T r, whereas information form uses
906    // eta = -g for a local mean dx = -H^-1 g.
907    let eta = -linearized.gradient;
908    let (information, eta) = if state.config.use_sqrt_marginalization {
909        // Basalt ICCV'21 square-root ("SqToSqrt") route: factor the dense
910        // marginal's Schur complement into a matrix-square-root factor and
911        // carry the boundary prior through that square root, then reassemble
912        // the identical dense (information, eta) for the downstream prior
913        // slot. Algebraically equal to the Schur path (see
914        // `marginalization_sqrt` equivalence tests) but factorization-stable.
915        let sm =
916            crate::marginalize_sqrt_from_information(&linearized.information, &eta, &keep, &[])?;
917        // factor^T·factor == the Schur marginal and factor^T·rhs == its
918        // information vector; downsteam line sym./uses the dense forms.
919        let information = sm.factor.transpose() * &sm.factor;
920        let eta_rebuilt = sm.factor.transpose() * &sm.rhs;
921        (information, eta_rebuilt)
922    } else {
923        marginalize(&linearized.information, &eta, &keep)?
924    };
925    let gradient = -eta;
926    let constant_cost = information
927        .clone()
928        .cholesky()
929        .map_or(0.0, |chol| gradient.dot(&chol.solve(&gradient)));
930    let nav = state.keyframe_state.get(&next_id)?;
931    let pose = map.keyframes.get(&next_id)?.frame.pose.clone()?;
932    Some(NavigationStatePrior {
933        keyframe_ids: vec![next_id],
934        reference_poses: BTreeMap::from([(next_id, pose)]),
935        reference_velocities: BTreeMap::from([(next_id, nav.velocity_world)]),
936        reference_biases: BTreeMap::from([(
937            next_id,
938            Vector6::new(
939                nav.bias_gyro.x,
940                nav.bias_gyro.y,
941                nav.bias_gyro.z,
942                nav.bias_acc.x,
943                nav.bias_acc.y,
944                nav.bias_acc.z,
945            ),
946        )]),
947        information: 0.5 * (&information + information.transpose()),
948        gradient,
949        constant_cost,
950    })
951}
952
953/// Enqueue Chow-Liu recovered relative-pose factors from a linearized boundary stack.
954fn enqueue_recovered_boundary_factors(
955    pending: &mut Vec<(u64, u64, crate::RecoveredRelativePoseFactor)>,
956    factor: &DMatrix<f64>,
957    rhs: &DVector<f64>,
958    old_id: u64,
959    next_id: u64,
960) {
961    let recovered = recover_boundary_pose_factors(factor, rhs);
962    pending.extend(recovered.into_iter().map(|factor| {
963        let id_i = if factor.block_i == 0 { old_id } else { next_id };
964        let id_j = if factor.block_j == 0 { old_id } else { next_id };
965        (id_i, id_j, factor)
966    }));
967}
968
969fn recover_boundary_pose_factors(
970    factor: &DMatrix<f64>,
971    rhs: &DVector<f64>,
972) -> Vec<crate::RecoveredRelativePoseFactor> {
973    crate::recover_relative_pose_factors_from_ba_stack(factor, rhs, 2).unwrap_or_default()
974}
975
976fn enqueue_recovered_window_factors(
977    pending: &mut Vec<(u64, u64, crate::RecoveredRelativePoseFactor)>,
978    ba: &BundleAdjustment,
979    window_ids: &[u64],
980    kernel: &RobustKernel,
981) {
982    let n = window_ids.len();
983    if n < 2 {
984        return;
985    }
986    let Some(intrinsics) = ba.camera.intrinsics() else {
987        return;
988    };
989    let mut pose_index = BTreeMap::new();
990    let mut velocity_index = BTreeMap::new();
991    let mut bias_index = BTreeMap::new();
992    let mut landmark_index = BTreeMap::new();
993    for id in window_ids {
994        if ba.poses.contains_key(id) {
995            let idx = pose_index.len();
996            pose_index.insert(*id, idx);
997        }
998        if ba.velocities.contains_key(id) {
999            let idx = velocity_index.len();
1000            velocity_index.insert(*id, idx);
1001        }
1002        if ba.biases.contains_key(id) {
1003            let idx = bias_index.len();
1004            bias_index.insert(*id, idx);
1005        }
1006    }
1007    if pose_index.len() != n || velocity_index.len() != n || bias_index.len() != n {
1008        return;
1009    }
1010    for id in ba.landmarks.keys() {
1011        let idx = landmark_index.len();
1012        landmark_index.insert(*id, idx);
1013    }
1014    let Some(stack) = build_sqrt_factor_rows(
1015        ba,
1016        &intrinsics,
1017        &pose_index,
1018        &landmark_index,
1019        &velocity_index,
1020        &bias_index,
1021        kernel,
1022        None,
1023    ) else {
1024        return;
1025    };
1026    let Some(recovered) =
1027        crate::recover_relative_pose_factors_from_ba_stack(&stack.jac, &stack.resid, n)
1028    else {
1029        return;
1030    };
1031    let mut ids_by_block = vec![0u64; n];
1032    for (&id, &idx) in &pose_index {
1033        if idx < n {
1034            ids_by_block[idx] = id;
1035        }
1036    }
1037    pending.extend(recovered.into_iter().filter_map(|factor| {
1038        let id_i = *ids_by_block.get(factor.block_i)?;
1039        let id_j = *ids_by_block.get(factor.block_j)?;
1040        if id_i == id_j {
1041            return None;
1042        }
1043        Some((id_i, id_j, factor))
1044    }));
1045}
1046
1047/// Square-root (QR) analogue of [`next_navigation_prior`], produced with the Basalt ICCV'21
1048/// SqrtToSqrt protocol ([`crate::vi_sqrt_window`]). Unlike the dense route, the retained
1049/// marginal is carried as a matrix-square-root factor across window shifts (no `JᵀJ`, no dense
1050/// inverse), and the factor/rhs are FEJ-consistent with the current linearisation point.
1051///
1052/// Returns the pair `(dense NavigationStatePrior, SqrtNavMarginal)`. The dense prior is
1053/// algebraically identical to [`next_navigation_prior`] (so the existing `ba` boundary-prior
1054/// slot is unchanged), and the `SqrtNavMarginal` is stored on the state for the next shift.
1055fn next_navigation_prior_sqrt(
1056    map: &VisualMap,
1057    state: &mut OnlineSlamLocalBaState,
1058    window_ids: &[u64],
1059    factors: &[ImuPreintegrationFactor],
1060) -> Option<(NavigationStatePrior, crate::SqrtNavMarginal)> {
1061    let (&old_id, &next_id) = (window_ids.first()?, window_ids.get(1)?);
1062    let boundary = factors
1063        .iter()
1064        .find(|factor| factor.keyframe_id_from == old_id && factor.keyframe_id_to == next_id)?;
1065    let camera_id = map.keyframes.get(&old_id)?.frame.camera_id;
1066    let camera = map.cameras.get(&camera_id)?.clone();
1067    let intrinsics = camera.intrinsics()?;
1068    let mut boundary_ba = BundleAdjustment::new(camera);
1069    boundary_ba.set_imu_body_to_camera(state.config.body_to_camera.clone());
1070
1071    for id in [old_id, next_id] {
1072        let pose = map.keyframes.get(&id)?.frame.pose.clone()?;
1073        let nav = state.keyframe_state.get(&id)?;
1074        boundary_ba.add_pose(id, pose);
1075        boundary_ba.add_velocity(id, nav.velocity_world);
1076        boundary_ba.add_bias(
1077            id,
1078            Vector6::new(
1079                nav.bias_gyro.x,
1080                nav.bias_gyro.y,
1081                nav.bias_gyro.z,
1082                nav.bias_acc.x,
1083                nav.bias_acc.y,
1084                nav.bias_acc.z,
1085            ),
1086        );
1087    }
1088    boundary_ba.add_imu_factor(boundary.clone());
1089    // Bias random-walk must be configured exactly as in the dense path (`next_navigation_prior`
1090    // returns `None` when it is absent, since the retained bias margin would be singular).
1091    let bias_walk = match state.config.bias_random_walk_noise_densities {
1092        Some(noise) => Some(bias_random_walk_information(
1093            noise,
1094            boundary.delta.delta_time,
1095        )?),
1096        None => match state.config.bias_random_walk_weights {
1097            Some(weights) => Some(weights),
1098            None => return None,
1099        },
1100    };
1101
1102    // State layout for the 2-keyframe boundary: pose old 0..6, pose next 6..12,
1103    // vel old 12..15, vel next 15..18, bias old 18..24, bias next 24..30.
1104    let pose_index = BTreeMap::from([(old_id, 0usize), (next_id, 1)]);
1105    let velocity_index = BTreeMap::from([(old_id, 0usize), (next_id, 1)]);
1106    let bias_index = BTreeMap::from([(old_id, 0usize), (next_id, 1)]);
1107    let landmark_index: BTreeMap<u64, usize> = BTreeMap::new();
1108
1109    let stack = build_sqrt_factor_rows(
1110        &boundary_ba,
1111        &intrinsics,
1112        &pose_index,
1113        &landmark_index,
1114        &velocity_index,
1115        &bias_index,
1116        &RobustKernel::None,
1117        None,
1118    )?;
1119    let jac = stack.jac;
1120    let resid = stack.resid;
1121
1122    // Append bias-random-walk sqrt rows: residual = [√w_bg·(bg_j−bg_i); √w_ba·(ba_j−ba_i)],
1123    // Jacobian ±√w on the respective bias columns. Layout: bias old 18..24, next 24..30,
1124    // gyro = cols 18..21/24..27, accel = 21..24/27..30.
1125    let (w_g, w_a) = bias_walk.expect("bias walk checked above");
1126    let sg = w_g.max(0.0).sqrt();
1127    let sa = w_a.max(0.0).sqrt();
1128    let mut extra = DMatrix::zeros(6, stack.total_dof);
1129    for k in 0..3 {
1130        extra[(k, 24 + k)] = sg; // + on next gyro
1131        extra[(k, 18 + k)] = -sg; // − on old gyro
1132        extra[(3 + k, 27 + k)] = sa; // + on next accel
1133        extra[(3 + k, 21 + k)] = -sa; // − on old accel
1134    }
1135    let bg_next = boundary_ba.biases.get(&next_id)?.fixed_rows::<3>(0);
1136    let bg_old = boundary_ba.biases.get(&old_id)?.fixed_rows::<3>(0);
1137    let ba_next = boundary_ba.biases.get(&next_id)?.fixed_rows::<3>(3);
1138    let ba_old = boundary_ba.biases.get(&old_id)?.fixed_rows::<3>(3);
1139    let mut extra_r = DVector::<f64>::zeros(6);
1140    for k in 0..3 {
1141        extra_r[k] = sg * (bg_next[k] - bg_old[k]);
1142        extra_r[3 + k] = sa * (ba_next[k] - ba_old[k]);
1143    }
1144
1145    // SqrtToSqrt carry: the marginal retained on the *previous* trigger (for the previous
1146    // `next_id`, which equals the current `old_id` after the window slid by one) is re-overlaid
1147    // here — exactly as the dense route consumes `state.navigation_prior` for the boundary.
1148    // On the first sequence window there is no carried marginal, so the old state is anchored
1149    // with a finite pseudo `fix_pose` plus the finite velocity/bias init priors (mirroring the
1150    // dense path's first-window `fix_pose(old_id)` + `initial_navigation_prior_std_devs`).
1151    let carried = state
1152        .sqrt_nav_marginal
1153        .as_ref()
1154        .filter(|m| m.state_dof == 15)
1155        .filter(|_| {
1156            state
1157                .navigation_prior
1158                .as_ref()
1159                .is_some_and(|prior| prior.keyframe_ids.as_slice() == [old_id])
1160        });
1161    // Extra sqrt rows beyond the IMU + bias-walk rows already in `jac`/`resid`.
1162    // Carried marginal: map its [pose, vel, bias] columns (old block) into the build layout
1163    // (pose 0..6, vel 12..15, bias 18..24 of the 30-col stack).
1164    let carried_rows = carried.map_or(0, |m| m.factor.nrows());
1165    // First-window pseudo-fix + init priors (only when NOT carrying a prior).
1166    let fill_rows = if carried.is_some() { 0 } else { 6 + 9 };
1167
1168    let n_rows = jac.nrows() + 6 + carried_rows + fill_rows;
1169    let mut jac_full = DMatrix::zeros(n_rows, stack.total_dof);
1170    let mut resid_full = DVector::zeros(n_rows);
1171
1172    let imu_rows = jac.nrows();
1173    let bwalk_rows = 6;
1174    jac_full
1175        .view_mut((0, 0), (imu_rows, stack.total_dof))
1176        .copy_from(&jac);
1177    resid_full.view_mut((0, 0), (imu_rows, 1)).copy_from(&resid);
1178    jac_full
1179        .view_mut((imu_rows, 0), (bwalk_rows, stack.total_dof))
1180        .copy_from(&extra);
1181    resid_full
1182        .view_mut((imu_rows, 0), (bwalk_rows, 1))
1183        .copy_from(&extra_r);
1184    if let Some(m) = carried {
1185        // FEJ re-reference: shift the carried marginal from its stored linearisation point
1186        // to the current old-state estimate (delta = current - lin_point) so its residual
1187        // displacement matches the rest of this window. Equivalent to the dense route's
1188        // `navigation_prior_delta` + `current_gradient = H*delta + gradient` re-reference.
1189        let old_nav = state.keyframe_state.get(&old_id)?;
1190        let old_w2c = map
1191            .keyframes
1192            .get(&old_id)?
1193            .frame
1194            .pose
1195            .clone()?
1196            .world_to_camera;
1197        let ref_pose = SE3::exp(&m.lin_point.fixed_rows::<6>(0).clone_owned());
1198        let pose_delta = ref_pose.inverse().compose(&old_w2c).log();
1199        let mut delta = DVector::zeros(15);
1200        delta.fixed_rows_mut::<6>(0).copy_from(&pose_delta);
1201        delta
1202            .fixed_rows_mut::<3>(6)
1203            .copy_from(&(old_nav.velocity_world - m.lin_point.fixed_rows::<3>(6).clone_owned()));
1204        let bias_cur = Vector6::new(
1205            old_nav.bias_gyro.x,
1206            old_nav.bias_gyro.y,
1207            old_nav.bias_gyro.z,
1208            old_nav.bias_acc.x,
1209            old_nav.bias_acc.y,
1210            old_nav.bias_acc.z,
1211        );
1212        delta
1213            .fixed_rows_mut::<6>(9)
1214            .copy_from(&(bias_cur - m.lin_point.fixed_rows::<6>(9).clone_owned()));
1215        let rhs_at_current = m.rhs.clone() + &(&m.factor * &delta);
1216        let row = imu_rows + bwalk_rows;
1217        for r in 0..m.factor.nrows() {
1218            for d in 0..6 {
1219                jac_full[(row + r, d)] = m.factor[(r, d)];
1220            }
1221            for d in 0..3 {
1222                jac_full[(row + r, 12 + d)] = m.factor[(r, 6 + d)];
1223            }
1224            for d in 0..6 {
1225                jac_full[(row + r, 18 + d)] = m.factor[(r, 9 + d)];
1226            }
1227            resid_full[row + r] = rhs_at_current[r];
1228        }
1229    } else {
1230        // First-window pseudo fixed-pose anchor (old pose cols 0..6).
1231        const FIXED_POSE_WEIGHT: f64 = 1.0e9;
1232        let row = imu_rows + bwalk_rows;
1233        for c in 0..6 {
1234            jac_full[(row + c, c)] = FIXED_POSE_WEIGHT.sqrt();
1235        }
1236        // First-window velocity/bias init priors, mirroring dense `initial_navigation_prior_std_devs`.
1237        if let Some((sigma_velocity, sigma_gyro_bias, sigma_accel_bias)) =
1238            state.config.initial_navigation_prior_std_devs
1239        {
1240            if sigma_velocity.is_finite()
1241                && sigma_velocity > 0.0
1242                && sigma_gyro_bias.is_finite()
1243                && sigma_gyro_bias > 0.0
1244                && sigma_accel_bias.is_finite()
1245                && sigma_accel_bias > 0.0
1246            {
1247                for k in 0..3 {
1248                    jac_full[(row + 6 + k, 12 + k)] = 1.0 / sigma_velocity;
1249                    jac_full[(row + 9 + k, 18 + k)] = 1.0 / sigma_gyro_bias;
1250                    jac_full[(row + 12 + k, 21 + k)] = 1.0 / sigma_accel_bias;
1251                }
1252            }
1253        }
1254    }
1255
1256    // Keep the next nav state (pose 6..12, vel 15..18, bias 24..30 = 15 dof); marginalize the old.
1257    if state.pending_recovered_pose_factors.is_empty() {
1258        let mut newly_recovered = Vec::new();
1259        enqueue_recovered_boundary_factors(
1260            &mut newly_recovered,
1261            &jac_full,
1262            &resid_full,
1263            old_id,
1264            next_id,
1265        );
1266        if newly_recovered.is_empty() {
1267            let core_rows = jac.nrows() + 6;
1268            if core_rows > 0 {
1269                let jac_core = jac_full.rows(0, core_rows).into_owned();
1270                let resid_core = resid_full.rows(0, core_rows).into_owned();
1271                enqueue_recovered_boundary_factors(
1272                    &mut newly_recovered,
1273                    &jac_core,
1274                    &resid_core,
1275                    old_id,
1276                    next_id,
1277                );
1278            }
1279        }
1280        state.pending_recovered_pose_factors.extend(newly_recovered);
1281    }
1282    let keep: Vec<usize> = (6..12).chain(15..18).chain(24..30).collect();
1283    let marg: Vec<usize> = (0..6).chain(12..15).chain(18..24).collect();
1284    let sm = crate::marginalize_sqrt(&jac_full, &resid_full, &keep, &marg, None)?;
1285
1286    let information = sm.factor.transpose() * &sm.factor;
1287    let gradient = sm.factor.transpose() * &sm.rhs;
1288    let constant_cost = information
1289        .clone()
1290        .cholesky()
1291        .map_or(0.0, |chol| gradient.dot(&chol.solve(&gradient)));
1292    let nav = state.keyframe_state.get(&next_id)?;
1293    let pose = map.keyframes.get(&next_id)?.frame.pose.clone()?;
1294    let dense = NavigationStatePrior {
1295        keyframe_ids: vec![next_id],
1296        reference_poses: BTreeMap::from([(next_id, pose.clone())]),
1297        reference_velocities: BTreeMap::from([(next_id, nav.velocity_world)]),
1298        reference_biases: BTreeMap::from([(
1299            next_id,
1300            Vector6::new(
1301                nav.bias_gyro.x,
1302                nav.bias_gyro.y,
1303                nav.bias_gyro.z,
1304                nav.bias_acc.x,
1305                nav.bias_acc.y,
1306                nav.bias_acc.z,
1307            ),
1308        )]),
1309        information: 0.5 * (&information + information.transpose()),
1310        gradient,
1311        constant_cost,
1312    };
1313    // FEJ re-linearisation point: the next state's estimate at creation. When this margin is
1314    // carried into the next window (as the old-id prior) it is re-referenced to that window's
1315    // moving old-state estimate via `rhs' = rhs - factor*delta` (delta = current - lin_point),
1316    // mirroring the dense route's `navigation_prior_delta` displacement into the boundary prior.
1317    let mut lin_point = DVector::zeros(15);
1318    lin_point
1319        .fixed_rows_mut::<6>(0)
1320        .copy_from(&pose.world_to_camera.log());
1321    lin_point
1322        .fixed_rows_mut::<3>(6)
1323        .copy_from(&nav.velocity_world);
1324    lin_point.fixed_rows_mut::<6>(9).copy_from(&Vector6::new(
1325        nav.bias_gyro.x,
1326        nav.bias_gyro.y,
1327        nav.bias_gyro.z,
1328        nav.bias_acc.x,
1329        nav.bias_acc.y,
1330        nav.bias_acc.z,
1331    ));
1332    let sqrt = crate::SqrtNavMarginal {
1333        factor: sm.factor,
1334        rhs: sm.rhs,
1335        state_dof: 15,
1336        lin_point,
1337    };
1338    Some((dense, sqrt))
1339}
1340
1341/// Run one local VI-BA trigger over `map`'s trailing window of keyframes.
1342///
1343/// Returns `None` when the window is too short to support BA (`< 2`
1344/// keyframes, or fewer than `2` in-window IMU factors) or when no usable
1345/// camera could be looked up in the map. On a successful trigger the
1346/// optimiser's refined poses + landmarks are written back into `map`, and
1347/// the refined `(velocity, bias)` state is written back into
1348/// `state.keyframe_state`.
1349///
1350/// `state.pending_factors_since_last_trigger` is reset to `0` regardless
1351/// of success — the caller has already decided to fire the trigger; a
1352/// short-window skip is not a reason to fire again immediately.
1353pub fn run_local_vi_ba(
1354    map: &mut VisualMap,
1355    state: &mut OnlineSlamLocalBaState,
1356) -> Option<OnlineSlamLocalBaStats> {
1357    state.pending_factors_since_last_trigger = 0;
1358
1359    let window_size = state.config.window_size.max(2);
1360    let mut keyframe_ids: Vec<u64> = map.keyframes.keys().copied().collect();
1361    keyframe_ids.sort_unstable();
1362    if keyframe_ids.len() < 2 {
1363        return None;
1364    }
1365    let window_start = keyframe_ids.len().saturating_sub(window_size);
1366    let window_ids: Vec<u64> = keyframe_ids[window_start..].to_vec();
1367    let in_window: BTreeSet<u64> = window_ids.iter().copied().collect();
1368
1369    // Collect IMU factors that fully sit inside the window.
1370    let in_window_factors: Vec<ImuPreintegrationFactor> = state
1371        .factor_history
1372        .iter()
1373        .filter(|f| {
1374            in_window.contains(&f.keyframe_id_from) && in_window.contains(&f.keyframe_id_to)
1375        })
1376        .cloned()
1377        .collect();
1378    if in_window_factors.is_empty() {
1379        return None;
1380    }
1381
1382    // Pull a representative camera from the window's first keyframe. The
1383    // BA path uses a single shared camera; multi-camera bundles are out of
1384    // scope for this stage.
1385    let first_kf = map.keyframes.get(&window_ids[0])?;
1386    let camera: Camera = map.cameras.get(&first_kf.frame.camera_id)?.clone();
1387
1388    // Promote per-keyframe IMU state for any window keyframe that doesn't
1389    // yet have one. New keyframes seed velocity from the inter-keyframe
1390    // pose-centre delta divided by the IMU factor's `delta_time` (a clean
1391    // first guess when GT velocity is unknown); biases start at the
1392    // configured linearisation point.
1393    for window_idx in 0..window_ids.len() {
1394        let kf_id = window_ids[window_idx];
1395        if state.keyframe_state.contains_key(&kf_id) {
1396            continue;
1397        }
1398        let seed_velocity = seed_velocity_for(
1399            map,
1400            &window_ids,
1401            window_idx,
1402            &in_window_factors,
1403            &state.config.body_to_camera,
1404        )
1405        .unwrap_or_else(Vector3::zeros);
1406        state.keyframe_state.insert(
1407            kf_id,
1408            KeyframeImuState {
1409                velocity_world: seed_velocity,
1410                bias_gyro: state.config.bias_gyro_init,
1411                bias_acc: state.config.bias_acc_init,
1412            },
1413        );
1414    }
1415
1416    let anchor_id = window_ids[0];
1417
1418    // Threshold-gated factor re-linearisation. Walks `state.factor_history`
1419    // (the source of truth) and re-bakes any factor whose stored
1420    // `bias_*_linearisation` is far from the current per-keyframe bias
1421    // estimate of its `keyframe_id_from`. Mutates in-place so future BA
1422    // windows inherit the refreshed delta. Then re-collects the in-window
1423    // factor slice from the now-up-to-date history.
1424    let mut relinearised_factor_count = 0usize;
1425    if let Some((gyro_thresh, accel_thresh)) = state.config.relinearise_imu_factor_bias_thresholds {
1426        for factor in state.factor_history.iter_mut() {
1427            let Some(per_kf) = state.keyframe_state.get(&factor.keyframe_id_from) else {
1428                continue;
1429            };
1430            let gyro_drift = (per_kf.bias_gyro - factor.delta.bias_gyro_linearisation).norm();
1431            let accel_drift = (per_kf.bias_acc - factor.delta.bias_acc_linearisation).norm();
1432            if gyro_drift > gyro_thresh || accel_drift > accel_thresh {
1433                factor
1434                    .delta
1435                    .relinearise_at(&per_kf.bias_gyro, &per_kf.bias_acc);
1436                relinearised_factor_count += 1;
1437            }
1438        }
1439    }
1440    let in_window_factors: Vec<ImuPreintegrationFactor> = if relinearised_factor_count > 0 {
1441        state
1442            .factor_history
1443            .iter()
1444            .filter(|f| {
1445                in_window.contains(&f.keyframe_id_from) && in_window.contains(&f.keyframe_id_to)
1446            })
1447            .cloned()
1448            .collect()
1449    } else {
1450        in_window_factors
1451    };
1452
1453    // Count in-window observations per landmark; only landmarks that meet
1454    // the `min_observations_per_landmark` threshold contribute to the
1455    // solve. This protects the linear system from rank-deficient single-
1456    // view tracks dragged in by the local mapper.
1457    let mut landmark_obs_counts: BTreeMap<u64, usize> = BTreeMap::new();
1458    for kf_id in &window_ids {
1459        let kf = map.keyframes.get(kf_id)?;
1460        for obs in &kf.observations {
1461            *landmark_obs_counts.entry(obs.landmark_id).or_insert(0) += 1;
1462        }
1463    }
1464    let active_landmarks: BTreeSet<u64> = landmark_obs_counts
1465        .iter()
1466        .filter(|(_, count)| **count >= state.config.min_observations_per_landmark)
1467        .map(|(id, _)| *id)
1468        .collect();
1469
1470    let marginalization_prior_applied = state.config.marginalize_navigation_state
1471        && state
1472            .navigation_prior
1473            .as_ref()
1474            .is_some_and(|prior| prior.keyframe_ids.as_slice() == [anchor_id]);
1475
1476    let build_ba =
1477        |freeze_all_biases: bool| -> Option<(BundleAdjustment, usize, usize, Option<Vec<f64>>)> {
1478            let mut ba = BundleAdjustment::new(camera.clone());
1479            ba.set_imu_body_to_camera(state.config.body_to_camera.clone());
1480            if marginalization_prior_applied {
1481                ba.set_navigation_state_prior(state.navigation_prior.clone()?);
1482            }
1483            for kf_id in &window_ids {
1484                let kf = map.keyframes.get(kf_id)?;
1485                let pose = kf.frame.pose.clone()?;
1486                ba.add_pose(*kf_id, pose);
1487                if *kf_id == anchor_id && !marginalization_prior_applied {
1488                    ba.fix_pose(*kf_id);
1489                }
1490            }
1491            for kf_id in &window_ids {
1492                if let Some(per_kf) = state.keyframe_state.get(kf_id) {
1493                    ba.add_velocity(*kf_id, per_kf.velocity_world);
1494                    let bias = Vector6::new(
1495                        per_kf.bias_gyro.x,
1496                        per_kf.bias_gyro.y,
1497                        per_kf.bias_gyro.z,
1498                        per_kf.bias_acc.x,
1499                        per_kf.bias_acc.y,
1500                        per_kf.bias_acc.z,
1501                    );
1502                    ba.add_bias(*kf_id, bias);
1503                    if *kf_id == anchor_id && !marginalization_prior_applied {
1504                        ba.fix_velocity(*kf_id);
1505                        ba.fix_bias(*kf_id);
1506                    } else if freeze_all_biases {
1507                        ba.fix_bias(*kf_id);
1508                    }
1509                }
1510            }
1511            if state.config.bias_random_walk_noise_densities.is_some()
1512                || state.config.bias_random_walk_weights.is_some()
1513            {
1514                for factor in &in_window_factors {
1515                    let (weight_gyro, weight_accel) = if let Some((sigma_gyro, sigma_accel)) =
1516                        state.config.bias_random_walk_noise_densities
1517                    {
1518                        bias_random_walk_information(
1519                            (sigma_gyro, sigma_accel),
1520                            factor.delta.delta_time,
1521                        )?
1522                    } else {
1523                        state
1524                            .config
1525                            .bias_random_walk_weights
1526                            .expect("fixed weights were checked above")
1527                    };
1528                    ba.add_bias_random_walk_factor(BiasRandomWalkFactor {
1529                        keyframe_id_from: factor.keyframe_id_from,
1530                        keyframe_id_to: factor.keyframe_id_to,
1531                        weight_gyro,
1532                        weight_accel,
1533                    });
1534                }
1535            }
1536            let mut observation_count = 0usize;
1537            let mut stereo_observation_count = 0usize;
1538            let mut mono_confidences = Vec::new();
1539            let mut general_stereo_confidences = Vec::new();
1540            for landmark_id in &active_landmarks {
1541                let Some(landmark) = map.landmarks.get(landmark_id) else {
1542                    continue;
1543                };
1544                ba.add_landmark(*landmark_id, landmark.position);
1545                for kf_id in &window_ids {
1546                    let kf = map.keyframes.get(kf_id)?;
1547                    let pose = ba.poses.get(kf_id)?.clone();
1548                    for obs in &kf.observations {
1549                        if obs.landmark_id == *landmark_id {
1550                            let stereo = state
1551                                .config
1552                                .use_general_stereo_observations
1553                                .then(|| {
1554                                    map.stereo_observations
1555                                        .iter()
1556                                        .find(|stereo| {
1557                                            stereo.frame_id == *kf_id
1558                                                && stereo.landmark_id == *landmark_id
1559                                        })
1560                                        .and_then(|stereo| {
1561                                            map.cameras
1562                                                .get(&stereo.right_camera_id)
1563                                                .map(|right_camera| (stereo, right_camera))
1564                                        })
1565                                        .filter(|(stereo, right_camera)| {
1566                                            let Some(max_error) = state
1567                                            .config
1568                                            .general_stereo_max_initial_right_reprojection_error_px
1569                                        else {
1570                                            return true;
1571                                        };
1572                                            if !max_error.is_finite() || max_error <= 0.0 {
1573                                                return false;
1574                                            }
1575                                            let point_left =
1576                                                pose.transform_world_point(&landmark.position);
1577                                            right_camera
1578                                                .project(
1579                                                    &stereo
1580                                                        .left_to_right
1581                                                        .transform_point(&point_left),
1582                                                )
1583                                                .is_some_and(|predicted| {
1584                                                    (predicted - stereo.xy_right).norm()
1585                                                        <= max_error
1586                                                })
1587                                        })
1588                                })
1589                                .flatten();
1590                            if let Some((stereo, right_camera)) = stereo {
1591                                ba.add_general_stereo_observation(BaGeneralStereoObservation {
1592                                    keyframe_id: *kf_id,
1593                                    landmark_id: *landmark_id,
1594                                    xy_left: obs.xy,
1595                                    xy_right: stereo.xy_right,
1596                                    right_camera: right_camera.clone(),
1597                                    left_to_right: stereo.left_to_right.clone(),
1598                                });
1599                                let confidence = state
1600                                    .config
1601                                    .use_observation_confidence_weights
1602                                    .then(|| map.observation_confidence(obs))
1603                                    .flatten();
1604                                general_stereo_confidences.push(confidence);
1605                                stereo_observation_count += 1;
1606                            } else {
1607                                ba.add_observation(BaObservation {
1608                                    keyframe_id: *kf_id,
1609                                    landmark_id: *landmark_id,
1610                                    xy: obs.xy,
1611                                });
1612                                let confidence = state
1613                                    .config
1614                                    .use_observation_confidence_weights
1615                                    .then(|| map.observation_confidence(obs))
1616                                    .flatten();
1617                                mono_confidences.push(confidence);
1618                            }
1619                            observation_count += 1;
1620                        }
1621                    }
1622                }
1623            }
1624            for factor in &in_window_factors {
1625                ba.add_imu_factor(factor.clone());
1626            }
1627            let observation_weights = relative_observation_confidence_weights(
1628                mono_confidences
1629                    .into_iter()
1630                    .chain(general_stereo_confidences),
1631            );
1632            Some((
1633                ba,
1634                observation_count,
1635                stereo_observation_count,
1636                observation_weights,
1637            ))
1638        };
1639
1640    let imu_factor_count = in_window_factors.len();
1641    let (mut ba, observation_count, stereo_observation_count, observation_weights) =
1642        build_ba(false)?;
1643    let cost_breakdown = |problem: &BundleAdjustment, weights: Option<&[f64]>| {
1644        weights.map_or_else(
1645            || Some(problem.cost_breakdown(&state.config.ba_config.robust_kernel)),
1646            |weights| {
1647                problem
1648                    .cost_breakdown_with_observation_weights(
1649                        &state.config.ba_config.robust_kernel,
1650                        weights,
1651                    )
1652                    .ok()
1653            },
1654        )
1655    };
1656    let mut initial_cost_breakdown = cost_breakdown(&ba, observation_weights.as_deref())?;
1657    let weighted_result = match observation_weights.as_deref() {
1658        Some(weights) => ba.optimize_with_observation_weights(&state.config.ba_config, weights),
1659        None => ba.optimize(&state.config.ba_config),
1660    };
1661    let mut ba_result = match weighted_result {
1662        Ok(result) => result,
1663        Err(_) => return None,
1664    };
1665    let mut final_cost_breakdown = cost_breakdown(&ba, observation_weights.as_deref())?;
1666
1667    // Conditioning fallback: if the joint pose + velocity + bias solve
1668    // failed to bring the cost down enough, the bias updates are not
1669    // trustworthy (the BA found a "best fit" against drifted upstream
1670    // poses by abusing the bias slots). Re-solve with all biases gauge-
1671    // frozen so the LM can only update poses + velocities + landmarks.
1672    let mut bias_frozen = false;
1673    if let Some(threshold) = state.config.freeze_biases_when_cost_ratio_above {
1674        let ratio = ba_cost_ratio(&ba_result);
1675        if ratio > threshold {
1676            let (mut ba_frozen, _, _, frozen_observation_weights) = build_ba(true)?;
1677            let frozen_initial_cost_breakdown =
1678                cost_breakdown(&ba_frozen, frozen_observation_weights.as_deref())?;
1679            let frozen_result = match frozen_observation_weights.as_deref() {
1680                Some(weights) => {
1681                    ba_frozen.optimize_with_observation_weights(&state.config.ba_config, weights)
1682                }
1683                None => ba_frozen.optimize(&state.config.ba_config),
1684            };
1685            match frozen_result {
1686                Ok(result) => {
1687                    let frozen_final_cost_breakdown =
1688                        cost_breakdown(&ba_frozen, frozen_observation_weights.as_deref())?;
1689                    ba = ba_frozen;
1690                    ba_result = result;
1691                    initial_cost_breakdown = frozen_initial_cost_breakdown;
1692                    final_cost_breakdown = frozen_final_cost_breakdown;
1693                    bias_frozen = true;
1694                }
1695                Err(_) => {
1696                    // Fall back to the first-pass result if the frozen
1697                    // re-solve itself fails. The caller still sees
1698                    // `bias_frozen = false` so they know which trace they're
1699                    // reading.
1700                }
1701            }
1702        }
1703    }
1704
1705    let cost_ratio = ba_cost_ratio(&ba_result);
1706    let max_refined_velocity_norm_mps = compute_max_refined_velocity_norm_mps(&ba, &window_ids);
1707    let (max_pose_translation_correction_meters, max_pose_rotation_correction_radians) =
1708        max_pose_correction(map, &ba, &window_ids);
1709    let (max_refined_gyro_bias_norm_rad_s, max_refined_accel_bias_norm_mps2) =
1710        compute_max_refined_bias_norms(&ba, &window_ids);
1711    let adaptive_velocity_gate_threshold_mps = state
1712        .config
1713        .adaptive_velocity_gate
1714        .as_ref()
1715        .and_then(|config| {
1716            compute_adaptive_velocity_gate_threshold_mps(
1717                map,
1718                state,
1719                &window_ids,
1720                &in_window_factors,
1721                config,
1722            )
1723        });
1724    let cost_ratio_gate_rejected = state
1725        .config
1726        .reject_writeback_when_cost_ratio_above
1727        .is_some_and(|threshold| cost_ratio > threshold);
1728    let imu_nis_gate_rejected = state
1729        .config
1730        .reject_writeback_when_final_imu_nis_per_dof_above
1731        .is_some_and(|threshold| {
1732            final_cost_breakdown
1733                .imu_normalized_squared_residual_per_dof
1734                .is_none_or(|value| !value.is_finite() || value > threshold)
1735        });
1736    let velocity_gate_rejected = state
1737        .config
1738        .reject_writeback_when_velocity_norm_above_mps
1739        .is_some_and(|threshold| max_refined_velocity_norm_mps > threshold);
1740    let pose_correction_gate_rejected = state
1741        .config
1742        .reject_writeback_when_pose_translation_above_meters
1743        .is_some_and(|threshold| max_pose_translation_correction_meters > threshold)
1744        || state
1745            .config
1746            .reject_writeback_when_pose_rotation_above_radians
1747            .is_some_and(|threshold| max_pose_rotation_correction_radians > threshold);
1748    let observation_count_gate_rejected = state
1749        .config
1750        .reject_writeback_when_observation_count_below
1751        .is_some_and(|minimum| observation_count < minimum);
1752    let bias_magnitude_gate_rejected = state
1753        .config
1754        .reject_gyro_bias_above_rad_s
1755        .is_some_and(|threshold| max_refined_gyro_bias_norm_rad_s > threshold)
1756        || state
1757            .config
1758            .reject_accel_bias_above_mps2
1759            .is_some_and(|threshold| max_refined_accel_bias_norm_mps2 > threshold);
1760    let adaptive_velocity_gate_rejected = adaptive_velocity_gate_threshold_mps
1761        .is_some_and(|threshold| max_refined_velocity_norm_mps > threshold);
1762    let hard_quality_gate_rejected = cost_ratio_gate_rejected
1763        || imu_nis_gate_rejected
1764        || velocity_gate_rejected
1765        || observation_count_gate_rejected
1766        || bias_magnitude_gate_rejected
1767        || adaptive_velocity_gate_rejected;
1768    let quality_gate_rejected = hard_quality_gate_rejected || pose_correction_gate_rejected;
1769    let allow_partial_navigation_writeback = pose_correction_gate_rejected
1770        && !hard_quality_gate_rejected
1771        && state.config.writeback_navigation_state_despite_pose_gate;
1772    if quality_gate_rejected && !allow_partial_navigation_writeback {
1773        return Some(OnlineSlamLocalBaStats {
1774            window_keyframe_ids: window_ids,
1775            landmark_count: active_landmarks.len(),
1776            observation_count,
1777            stereo_observation_count,
1778            imu_factor_count,
1779            ba_result,
1780            initial_cost_breakdown,
1781            final_cost_breakdown,
1782            cost_ratio,
1783            max_refined_velocity_norm_mps,
1784            max_pose_translation_correction_meters,
1785            max_pose_rotation_correction_radians,
1786            max_refined_gyro_bias_norm_rad_s,
1787            max_refined_accel_bias_norm_mps2,
1788            adaptive_velocity_gate_threshold_mps,
1789            bias_frozen,
1790            quality_gate_rejected,
1791            cost_ratio_gate_rejected,
1792            imu_nis_gate_rejected,
1793            velocity_gate_rejected,
1794            pose_correction_gate_rejected,
1795            observation_count_gate_rejected,
1796            navigation_state_partially_written: false,
1797            bias_magnitude_gate_rejected,
1798            adaptive_velocity_gate_rejected,
1799            relinearised_factor_count,
1800            marginalization_prior_applied,
1801            marginalization_succeeded: false,
1802            recovered_marginal_factors_injected: 0,
1803            recovered_marginal_factors_enqueued: 0,
1804        });
1805    }
1806
1807    if allow_partial_navigation_writeback {
1808        // Pose corrections look unsafe; keep the map frozen but still
1809        // absorb refined velocity/bias into the local VI-BA table so the
1810        // next window and the IMU motion-model mirror can use them.
1811        for kf_id in &window_ids {
1812            let Some(slot) = state.keyframe_state.get_mut(kf_id) else {
1813                continue;
1814            };
1815            if let Some(velocity) = ba.velocities.get(kf_id) {
1816                slot.velocity_world = *velocity;
1817            }
1818            if !bias_frozen {
1819                if let Some(bias) = ba.biases.get(kf_id) {
1820                    slot.bias_gyro = Vector3::new(bias[0], bias[1], bias[2]);
1821                    slot.bias_acc = Vector3::new(bias[3], bias[4], bias[5]);
1822                }
1823            }
1824        }
1825        return Some(OnlineSlamLocalBaStats {
1826            window_keyframe_ids: window_ids,
1827            landmark_count: active_landmarks.len(),
1828            observation_count,
1829            stereo_observation_count,
1830            imu_factor_count,
1831            ba_result,
1832            initial_cost_breakdown,
1833            final_cost_breakdown,
1834            cost_ratio,
1835            max_refined_velocity_norm_mps,
1836            max_pose_translation_correction_meters,
1837            max_pose_rotation_correction_radians,
1838            max_refined_gyro_bias_norm_rad_s,
1839            max_refined_accel_bias_norm_mps2,
1840            adaptive_velocity_gate_threshold_mps,
1841            bias_frozen,
1842            quality_gate_rejected: true,
1843            cost_ratio_gate_rejected,
1844            imu_nis_gate_rejected,
1845            velocity_gate_rejected,
1846            pose_correction_gate_rejected,
1847            observation_count_gate_rejected,
1848            navigation_state_partially_written: true,
1849            bias_magnitude_gate_rejected,
1850            adaptive_velocity_gate_rejected,
1851            relinearised_factor_count,
1852            marginalization_prior_applied,
1853            marginalization_succeeded: false,
1854            recovered_marginal_factors_injected: 0,
1855            recovered_marginal_factors_enqueued: 0,
1856        });
1857    }
1858
1859    // Write refined poses + landmarks back to the map.
1860    for kf_id in &window_ids {
1861        if let Some(refined_pose) = ba.poses.get(kf_id) {
1862            if let Some(kf) = map.keyframes.get_mut(kf_id) {
1863                kf.frame.pose = Some(refined_pose.clone());
1864            }
1865        }
1866    }
1867    for (landmark_id, refined_pos) in &ba.landmarks {
1868        if let Some(landmark) = map.landmarks.get_mut(landmark_id) {
1869            landmark.position = *refined_pos;
1870        }
1871    }
1872    // Write refined velocities back. Bias writeback is suppressed when
1873    // the conditioning fallback fired: the frozen re-solve leaves the
1874    // bias variables at their input values, so writing them back would
1875    // be a no-op anyway — but we make the intent explicit.
1876    for kf_id in &window_ids {
1877        let Some(slot) = state.keyframe_state.get_mut(kf_id) else {
1878            continue;
1879        };
1880        if let Some(velocity) = ba.velocities.get(kf_id) {
1881            slot.velocity_world = *velocity;
1882        }
1883        if !bias_frozen {
1884            if let Some(bias) = ba.biases.get(kf_id) {
1885                slot.bias_gyro = Vector3::new(bias[0], bias[1], bias[2]);
1886                slot.bias_acc = Vector3::new(bias[3], bias[4], bias[5]);
1887            }
1888        }
1889    }
1890
1891    let pending_before = state.pending_recovered_pose_factors.len();
1892    if state.config.use_sqrt_window_marginalization {
1893        enqueue_recovered_window_factors(
1894            &mut state.pending_recovered_pose_factors,
1895            &ba,
1896            &window_ids,
1897            &state.config.ba_config.robust_kernel,
1898        );
1899    }
1900    let marginalization_succeeded = if state.config.marginalize_navigation_state {
1901        if state.config.use_sqrt_window_marginalization {
1902            let sqrt_prior =
1903                next_navigation_prior_sqrt(map, state, &window_ids, &in_window_factors);
1904            let succeeded = sqrt_prior.is_some();
1905            state.navigation_prior = sqrt_prior.as_ref().map(|(dense, _)| dense.clone());
1906            state.sqrt_nav_marginal = sqrt_prior.map(|(_, sqrt)| sqrt);
1907            succeeded
1908        } else {
1909            let next_prior = next_navigation_prior(map, state, &window_ids, &in_window_factors);
1910            let succeeded = next_prior.is_some();
1911            state.navigation_prior = next_prior;
1912            state.sqrt_nav_marginal = None;
1913            succeeded
1914        }
1915    } else {
1916        state.navigation_prior = None;
1917        state.sqrt_nav_marginal = None;
1918        false
1919    };
1920    let recovered_marginal_factors_enqueued = state
1921        .pending_recovered_pose_factors
1922        .len()
1923        .saturating_sub(pending_before);
1924
1925    Some(OnlineSlamLocalBaStats {
1926        window_keyframe_ids: window_ids,
1927        landmark_count: active_landmarks.len(),
1928        observation_count,
1929        stereo_observation_count,
1930        imu_factor_count,
1931        ba_result,
1932        initial_cost_breakdown,
1933        final_cost_breakdown,
1934        cost_ratio,
1935        max_refined_velocity_norm_mps,
1936        max_pose_translation_correction_meters,
1937        max_pose_rotation_correction_radians,
1938        max_refined_gyro_bias_norm_rad_s,
1939        max_refined_accel_bias_norm_mps2,
1940        adaptive_velocity_gate_threshold_mps,
1941        bias_frozen,
1942        quality_gate_rejected,
1943        cost_ratio_gate_rejected,
1944        imu_nis_gate_rejected,
1945        velocity_gate_rejected,
1946        pose_correction_gate_rejected,
1947        observation_count_gate_rejected,
1948        navigation_state_partially_written: false,
1949        bias_magnitude_gate_rejected,
1950        adaptive_velocity_gate_rejected,
1951        relinearised_factor_count,
1952        marginalization_prior_applied,
1953        marginalization_succeeded,
1954        recovered_marginal_factors_injected: 0,
1955        recovered_marginal_factors_enqueued,
1956    })
1957}
1958
1959/// Per-trigger inertial-only BA outcome, returned by
1960/// [`run_inertial_only_vi_ba`] / [`run_inertial_only_vi_ba_with_options`].
1961/// Mirrors [`OnlineSlamLocalBaStats`] but drops the landmark / observation
1962/// counters (always zero for the inertial-only path) and replaces them with
1963/// the keyframe count.
1964#[derive(Debug, Clone, PartialEq)]
1965pub struct InertialOnlyViBaStats {
1966    /// Sorted keyframe ids included in this solve.
1967    pub keyframe_ids: Vec<u64>,
1968    /// Number of IMU factors whose `from / to` pair fell inside the
1969    /// keyframe set.
1970    pub imu_factor_count: usize,
1971    /// Refined per-keyframe `(velocity, bias_gyro, bias_acc)` after the
1972    /// solve. Indexed by keyframe id.
1973    pub keyframe_states: BTreeMap<u64, KeyframeImuState>,
1974    /// Optimiser outcome; carries the LM trace + final / initial cost.
1975    pub ba_result: crate::bundle::BaResult,
1976    pub initial_cost_breakdown: BaCostBreakdown,
1977    pub final_cost_breakdown: BaCostBreakdown,
1978}
1979
1980/// Run an inertial-only sliding-window MAP solve over `keyframe_ids`'s
1981/// preintegration factors. Mirrors the VIBA1 stage in ORB-SLAM3:
1982/// **landmarks are not touched** (no visual residuals contribute), and
1983/// only inertial states are optimised. The vision-only keyframe trajectory is
1984/// held fixed, as required by Campos–Montiel–Tardós' disjoint inertial-only
1985/// MAP formulation; allowing poses to move would remove the visual reference
1986/// that makes gyro bias observable.
1987/// Scale is fixed at `1.0` for this entry-point — the monocular scale
1988/// recovery sits in the future VIBA2 stage. Used by
1989/// [`crate::MotionBasedViInitializer`] to refine biases + poses once
1990/// the body has moved enough to give the IMU translational excitation.
1991///
1992/// Bias is assumed constant over the short initialization window. The generic
1993/// BA core represents one bias slot per keyframe, so adjacent slots are tied
1994/// with a high-information equality factor. Unlike local VI-BA, no bias or
1995/// velocity slot is pinned: fixed visual poses remove the trajectory gauge and
1996/// the initializer must be able to estimate the common bias itself.
1997///
1998/// Returns `None` when:
1999/// * `keyframe_ids` has fewer than 2 entries,
2000/// * no IMU factor fully sits inside the keyframe set,
2001/// * any keyframe is missing its pose, or
2002/// * the LM solver itself fails (singular system, etc.).
2003///
2004/// Thin wrapper over [`run_inertial_only_vi_ba_with_options`] with
2005/// `solve_bias = true` — this entry point's public signature/behaviour is
2006/// unchanged; see the sibling function for the bias-fixed "velocity stage"
2007/// mode used by [`crate::vi_motion_initializer::BiasReleaseSchedule`].
2008pub fn run_inertial_only_vi_ba(
2009    map: &mut VisualMap,
2010    keyframe_ids: &[u64],
2011    factors: &[ImuPreintegrationFactor],
2012    initial_states: &BTreeMap<u64, KeyframeImuState>,
2013    ba_config: &crate::bundle::BaConfig,
2014) -> Option<InertialOnlyViBaStats> {
2015    run_inertial_only_vi_ba_with_options(
2016        map,
2017        keyframe_ids,
2018        factors,
2019        initial_states,
2020        ba_config,
2021        true,
2022    )
2023}
2024
2025/// [`run_inertial_only_vi_ba`] with an explicit `solve_bias` switch.
2026///
2027/// `solve_bias = true` reproduces `run_inertial_only_vi_ba` exactly (the
2028/// public entry point is now a thin wrapper around this function). `solve_bias
2029/// = false` is the "velocity stage" half of
2030/// [`crate::vi_motion_initializer::BiasReleaseSchedule`]'s staged bias
2031/// release: every keyframe's bias slot is added at the caller-supplied seed
2032/// and then immediately gauge-fixed via [`BundleAdjustment::fix_bias`], so the
2033/// LM solve can only move per-keyframe velocities (and, indirectly, the
2034/// residual's rotation/position terms through the fixed poses). The
2035/// [`BiasRandomWalkFactor`] equality ties that keep adjacent bias slots
2036/// coherent are skipped in this mode: they exist to prevent per-keyframe bias
2037/// drift on a *free* bias, which is meaningless when every slot is already
2038/// pinned to the same fixed value.
2039///
2040/// Motivation (see `docs/motion_based_vi_alignment.md`): firing the VIBA1
2041/// solve with bias free from the very first keyframe, over a short
2042/// (~3-keyframe) window, on a moving-start EuRoC sequence let the recovered
2043/// accelerometer bias diverge to magnitudes around 12 m/s² — the window
2044/// simply does not carry enough independent excitation to identify bias
2045/// safely yet. Holding bias fixed and only refining velocity is the
2046/// well-conditioned partial solve for that regime; the caller graduates to
2047/// `solve_bias = true` once more excitation has accumulated.
2048///
2049/// The returned [`InertialOnlyViBaStats::keyframe_states`] carries the seed
2050/// biases back out **unchanged** (down to solver floating-point noise) when
2051/// `solve_bias = false`, with refined velocities.
2052pub fn run_inertial_only_vi_ba_with_options(
2053    map: &mut VisualMap,
2054    keyframe_ids: &[u64],
2055    factors: &[ImuPreintegrationFactor],
2056    initial_states: &BTreeMap<u64, KeyframeImuState>,
2057    ba_config: &crate::bundle::BaConfig,
2058    solve_bias: bool,
2059) -> Option<InertialOnlyViBaStats> {
2060    if keyframe_ids.len() < 2 {
2061        return None;
2062    }
2063    let mut sorted_ids: Vec<u64> = keyframe_ids.to_vec();
2064    sorted_ids.sort_unstable();
2065    sorted_ids.dedup();
2066    let in_window: BTreeSet<u64> = sorted_ids.iter().copied().collect();
2067
2068    let in_window_factors: Vec<ImuPreintegrationFactor> = factors
2069        .iter()
2070        .filter(|f| {
2071            in_window.contains(&f.keyframe_id_from) && in_window.contains(&f.keyframe_id_to)
2072        })
2073        .cloned()
2074        .collect();
2075    if in_window_factors.is_empty() {
2076        return None;
2077    }
2078
2079    // Pull the camera from the first keyframe; required by
2080    // BundleAdjustment::new but the inertial-only path never reads its
2081    // intrinsics (no visual residuals contribute).
2082    let first_kf = map.keyframes.get(&sorted_ids[0])?;
2083    let camera: Camera = map.cameras.get(&first_kf.frame.camera_id)?.clone();
2084
2085    let mut ba = BundleAdjustment::new(camera);
2086
2087    for kf_id in &sorted_ids {
2088        let kf = map.keyframes.get(kf_id)?;
2089        let pose = kf.frame.pose.clone()?;
2090        ba.add_pose(*kf_id, pose);
2091        ba.fix_pose(*kf_id);
2092    }
2093    // Velocity + bias slots per keyframe. Seed from `initial_states` when
2094    // available; otherwise zero velocity and zero bias.
2095    for kf_id in &sorted_ids {
2096        let (velocity, bias_g, bias_a) = match initial_states.get(kf_id) {
2097            Some(state) => (state.velocity_world, state.bias_gyro, state.bias_acc),
2098            None => (Vector3::zeros(), Vector3::zeros(), Vector3::zeros()),
2099        };
2100        ba.add_velocity(*kf_id, velocity);
2101        let bias = Vector6::new(bias_g.x, bias_g.y, bias_g.z, bias_a.x, bias_a.y, bias_a.z);
2102        ba.add_bias(*kf_id, bias);
2103        if !solve_bias {
2104            // Velocity stage: gauge-fix every bias slot at the seed value.
2105            // The LM solve can then only move velocities (and, through the
2106            // fixed poses, the IMU residual's rotation/position terms),
2107            // which is exactly the well-conditioned partial solve this mode
2108            // exists for.
2109            ba.fix_bias(*kf_id);
2110        }
2111    }
2112    // The inertial-only initialization paper estimates one shared gyro/accel
2113    // bias over the short window. The generic BA owns one slot per keyframe,
2114    // so tie them relative to the strongest IMU information in this problem.
2115    // A fixed 1e8 penalty was not invariant to covariance whitening: EuRoC
2116    // factors can carry 1e10..1e12 information, making that supposedly "hard"
2117    // equality weak enough for 0.1 rad/s inter-keyframe bias drift.
2118    //
2119    // Skipped entirely when `solve_bias == false`: every bias slot is already
2120    // gauge-fixed at the same seed value above, so an equality tie between
2121    // fixed slots contributes nothing but wasted Jacobian rows.
2122    if solve_bias {
2123        let strongest_factor_information = in_window_factors
2124            .iter()
2125            .map(|factor| {
2126                factor.covariance_sqrt_information().map_or_else(
2127                    || {
2128                        factor
2129                            .weight_rotation
2130                            .max(factor.weight_velocity)
2131                            .max(factor.weight_position)
2132                    },
2133                    |whitener| whitener.norm_squared(),
2134                )
2135            })
2136            .fold(1.0_f64, f64::max);
2137        // Preserve the original NaN handling of `max(...).min(...)`: unlike
2138        // `clamp`, the chained primitive operations fall back to the finite
2139        // bound when an upstream information estimate is NaN.
2140        #[allow(clippy::manual_clamp)]
2141        let shared_bias_equality_weight = (strongest_factor_information * 1.0e4)
2142            .max(1.0e8)
2143            .min(1.0e20);
2144        for pair in sorted_ids.windows(2) {
2145            ba.add_bias_random_walk_factor(BiasRandomWalkFactor {
2146                keyframe_id_from: pair[0],
2147                keyframe_id_to: pair[1],
2148                weight_gyro: shared_bias_equality_weight,
2149                weight_accel: shared_bias_equality_weight,
2150            });
2151        }
2152    }
2153
2154    let imu_factor_count = in_window_factors.len();
2155    for factor in in_window_factors {
2156        ba.add_imu_factor(factor);
2157    }
2158
2159    let initial_cost_breakdown = ba.cost_breakdown(&ba_config.robust_kernel);
2160    let ba_result = ba.optimize(ba_config).ok()?;
2161    let final_cost_breakdown = ba.cost_breakdown(&ba_config.robust_kernel);
2162
2163    // Collect refined per-keyframe states for the caller.
2164    let mut keyframe_states: BTreeMap<u64, KeyframeImuState> = BTreeMap::new();
2165    for kf_id in &sorted_ids {
2166        let velocity = ba
2167            .velocities
2168            .get(kf_id)
2169            .copied()
2170            .unwrap_or_else(Vector3::zeros);
2171        let bias_pair = ba.biases.get(kf_id).copied().unwrap_or_else(Vector6::zeros);
2172        let bias_gyro = Vector3::new(bias_pair[0], bias_pair[1], bias_pair[2]);
2173        let bias_acc = Vector3::new(bias_pair[3], bias_pair[4], bias_pair[5]);
2174        keyframe_states.insert(
2175            *kf_id,
2176            KeyframeImuState {
2177                velocity_world: velocity,
2178                bias_gyro,
2179                bias_acc,
2180            },
2181        );
2182    }
2183
2184    Some(InertialOnlyViBaStats {
2185        keyframe_ids: sorted_ids,
2186        imu_factor_count,
2187        keyframe_states,
2188        ba_result,
2189        initial_cost_breakdown,
2190        final_cost_breakdown,
2191    })
2192}
2193
2194/// Configuration for [`run_viba2_inertial_with_scale`] — the outer-loop
2195/// scale-recovery wrapper around [`run_inertial_only_vi_ba`].
2196///
2197/// On stereo / RGB-D sequences set `recover_scale = false`; the wrapper
2198/// then degenerates to a single inertial-only solve at `scale = 1.0` and
2199/// behaves identically to the VIBA1 entry point. On monocular sequences
2200/// set `recover_scale = true`; the wrapper iterates a 1-D least-squares
2201/// scale estimator alongside the inner solver until the relative change
2202/// in `s` drops below `scale_tolerance`.
2203#[derive(Debug, Clone, PartialEq)]
2204pub struct Viba2Config {
2205    /// Initial scale estimate. `1.0` is appropriate when the visual front
2206    /// end already exposes a metric anchor (stereo / RGB-D); for a fresh
2207    /// monocular bootstrap the initialiser produces a single-iteration
2208    /// closed-form guess from the IMU integral magnitudes before the
2209    /// first inner solve.
2210    pub initial_scale: f64,
2211    /// When `false`, scale is pinned at `initial_scale` (typical stereo
2212    /// path). When `true`, the wrapper iterates an alternating-
2213    /// minimisation outer loop: rescale the IMU factors by `1/s`, run
2214    /// the inertial-only inner solve, re-estimate `s` from the refined
2215    /// state, repeat. Default `false` to match the stereo-first stance
2216    /// of the existing VIBA1 entry point.
2217    pub recover_scale: bool,
2218    /// Maximum number of outer scale-refinement iterations. Each
2219    /// iteration runs one inner inertial-only solve. Default `5`.
2220    pub max_outer_iterations: usize,
2221    /// Convergence threshold on the relative scale change between two
2222    /// consecutive outer iterations. Default `1e-3`.
2223    pub scale_tolerance: f64,
2224    /// Inner BA config forwarded to [`run_inertial_only_vi_ba`].
2225    pub ba_config: crate::bundle::BaConfig,
2226}
2227
2228impl Default for Viba2Config {
2229    fn default() -> Self {
2230        Self {
2231            initial_scale: 1.0,
2232            recover_scale: false,
2233            max_outer_iterations: 5,
2234            scale_tolerance: 1.0e-3,
2235            ba_config: crate::bundle::BaConfig {
2236                linear_solver: crate::LinearSolver::Sparse,
2237                max_iterations: 10,
2238                ..crate::bundle::BaConfig::default()
2239            },
2240        }
2241    }
2242}
2243
2244/// Outcome of [`run_viba2_inertial_with_scale`].
2245#[derive(Debug, Clone, PartialEq)]
2246pub struct Viba2Stats {
2247    /// Sorted keyframe ids covered by the solve.
2248    pub keyframe_ids: Vec<u64>,
2249    /// Number of IMU factors fed into the inner solves.
2250    pub imu_factor_count: usize,
2251    /// Refined per-keyframe state from the final inner solve.
2252    pub keyframe_states: BTreeMap<u64, KeyframeImuState>,
2253    /// Scale factor recovered by the outer loop. `1.0` when
2254    /// `recover_scale = false`.
2255    pub scale: f64,
2256    /// History of scale values across the outer loop: index `0` is the
2257    /// `initial_scale`, subsequent entries are the values after each
2258    /// re-estimation. Length is `outer_iterations_run + 1`.
2259    pub scale_history: Vec<f64>,
2260    /// Number of outer iterations executed (one fewer than
2261    /// `scale_history.len()`).
2262    pub outer_iterations_run: usize,
2263    /// Final inner-solve BA result.
2264    pub ba_result: crate::bundle::BaResult,
2265    pub initial_cost_breakdown: BaCostBreakdown,
2266    pub final_cost_breakdown: BaCostBreakdown,
2267}
2268
2269/// Run the VIBA2 inertial-with-scale outer loop.
2270///
2271/// Strategy. The inner solver ([`run_inertial_only_vi_ba`]) is invoked at
2272/// the current scale guess `s_k` with IMU factors pre-scaled by `1/s_k`
2273/// (positions, velocities, and gravity all get divided by `s_k`). After
2274/// the inner solve we re-estimate `s_{k+1}` by a closed-form 1D least
2275/// squares against the refined state (see [`estimate_scale_from_factors`]),
2276/// using the **original** factors so the estimator stays consistent across
2277/// iterations. The loop terminates when `|s_{k+1} - s_k| / s_k <
2278/// scale_tolerance` or after `max_outer_iterations` iterations.
2279///
2280/// When `config.recover_scale = false` the loop runs a single inner solve
2281/// at `config.initial_scale` and skips the re-estimation, matching the
2282/// stereo / known-scale path. The scale field on the result is
2283/// `config.initial_scale` in that case (typically `1.0`).
2284///
2285/// Returns `None` when [`run_inertial_only_vi_ba`] returns `None` on the
2286/// first inner solve, or when the initial scale is non-finite / non-positive.
2287pub fn run_viba2_inertial_with_scale(
2288    map: &mut VisualMap,
2289    keyframe_ids: &[u64],
2290    factors: &[ImuPreintegrationFactor],
2291    initial_states: &BTreeMap<u64, KeyframeImuState>,
2292    config: &Viba2Config,
2293) -> Option<Viba2Stats> {
2294    if !config.initial_scale.is_finite() || config.initial_scale <= 0.0 {
2295        return None;
2296    }
2297
2298    let mut s_current = config.initial_scale;
2299    let mut scale_history: Vec<f64> = vec![s_current];
2300    let mut last_stats: Option<InertialOnlyViBaStats> = None;
2301    let mut outer_iter_run = 0usize;
2302
2303    let max_iters = if config.recover_scale {
2304        config.max_outer_iterations.max(1)
2305    } else {
2306        1
2307    };
2308
2309    for _ in 0..max_iters {
2310        let scaled_factors = rescale_imu_factors(factors, s_current);
2311        let stats = run_inertial_only_vi_ba(
2312            map,
2313            keyframe_ids,
2314            &scaled_factors,
2315            initial_states,
2316            &config.ba_config,
2317        )?;
2318        last_stats = Some(stats);
2319        outer_iter_run += 1;
2320
2321        if !config.recover_scale {
2322            break;
2323        }
2324
2325        // Re-estimate scale from the post-solve state, using the ORIGINAL
2326        // (un-rescaled) factors. The state has been refined under the
2327        // assumption that visual quantities are up-to-scale and IMU
2328        // quantities have been rescaled by 1/s_current; matching them
2329        // against the original factor delta requires the formula in
2330        // `estimate_scale_from_factors`.
2331        let refined_states = &last_stats.as_ref().unwrap().keyframe_states;
2332        let Some(s_new) = estimate_scale_from_factors(map, refined_states, factors) else {
2333            // Insufficient signal to update the scale (no factor with a
2334            // non-degenerate kinematic term); freeze at the current value.
2335            break;
2336        };
2337        let rel_change = (s_new - s_current).abs() / s_current.abs().max(1.0e-9);
2338        scale_history.push(s_new);
2339        let converged = rel_change < config.scale_tolerance;
2340        s_current = s_new;
2341        if converged {
2342            break;
2343        }
2344    }
2345
2346    let stats = last_stats?;
2347    Some(Viba2Stats {
2348        keyframe_ids: stats.keyframe_ids,
2349        imu_factor_count: stats.imu_factor_count,
2350        keyframe_states: stats.keyframe_states,
2351        scale: s_current,
2352        scale_history,
2353        outer_iterations_run: outer_iter_run,
2354        ba_result: stats.ba_result,
2355        initial_cost_breakdown: stats.initial_cost_breakdown,
2356        final_cost_breakdown: stats.final_cost_breakdown,
2357    })
2358}
2359
2360/// Rescale every factor's `(Δp, Δv, gravity_world)` by `1/scale` and
2361/// return a fresh vector. The rotation delta and bias linearisation are
2362/// preserved unchanged. Used by [`run_viba2_inertial_with_scale`] to
2363/// invariantly transform the inner solve into the visual-up-to-scale
2364/// frame.
2365fn rescale_imu_factors(
2366    factors: &[ImuPreintegrationFactor],
2367    scale: f64,
2368) -> Vec<ImuPreintegrationFactor> {
2369    if !scale.is_finite() || scale <= 0.0 {
2370        return factors.to_vec();
2371    }
2372    let inv_s = 1.0 / scale;
2373    factors
2374        .iter()
2375        .map(|f| {
2376            let mut clone = f.clone();
2377            clone.delta.delta_velocity = f.delta.delta_velocity * inv_s;
2378            clone.delta.delta_position = f.delta.delta_position * inv_s;
2379            clone.gravity_world = f.gravity_world * inv_s;
2380            clone
2381        })
2382        .collect()
2383}
2384
2385/// Closed-form 1D least squares for the world scale given current
2386/// keyframe poses + velocities and original (un-rescaled) IMU factors.
2387///
2388/// Derivation. The original Forster position residual is
2389/// `r_p = R_iᵀ · (p_j_metric - p_i_metric - v_i_metric · Δt - 0.5 · g · Δt²) - Δp`.
2390/// Substituting `p_metric = s · p_visual`, `v_metric = s · v_visual`:
2391/// `r_p = R_iᵀ · (s · (p_j - p_i - v_i · Δt) - 0.5 · g · Δt²) - Δp`.
2392/// Defining `a = R_iᵀ · (p_j - p_i - v_i · Δt)` (3-vec, per factor) and
2393/// `b = Δp + R_iᵀ · 0.5 · g · Δt²` (3-vec, per factor), the least-squares
2394/// problem `min_s ‖s · a - b‖²` has the closed form
2395/// `s = (Σ aᵀ b) / (Σ aᵀ a)` summed across all factors.
2396///
2397/// Returns `None` when `Σ aᵀ a` is too small to identify the scale (i.e.
2398/// the kinematic term is degenerate — happens when every factor has
2399/// `p_j ≈ p_i + v_i · Δt`, the no-motion case). In that case the caller
2400/// should freeze the current scale estimate.
2401pub fn estimate_scale_from_factors(
2402    map: &VisualMap,
2403    states: &BTreeMap<u64, KeyframeImuState>,
2404    factors: &[ImuPreintegrationFactor],
2405) -> Option<f64> {
2406    let mut num = 0.0_f64;
2407    let mut den = 0.0_f64;
2408    for factor in factors {
2409        let p_i = map
2410            .keyframes
2411            .get(&factor.keyframe_id_from)
2412            .and_then(|kf| kf.frame.pose.as_ref())
2413            .map(|pose| pose.camera_center_world())?;
2414        let p_j = map
2415            .keyframes
2416            .get(&factor.keyframe_id_to)
2417            .and_then(|kf| kf.frame.pose.as_ref())
2418            .map(|pose| pose.camera_center_world())?;
2419        let v_i = states
2420            .get(&factor.keyframe_id_from)
2421            .map_or_else(Vector3::zeros, |s| s.velocity_world);
2422        let r_w_to_c = map
2423            .keyframes
2424            .get(&factor.keyframe_id_from)
2425            .and_then(|kf| kf.frame.pose.as_ref())
2426            .map(|pose| pose.world_to_camera.rotation)?;
2427        let dt = factor.delta.delta_time;
2428        if dt <= 0.0 || !dt.is_finite() {
2429            continue;
2430        }
2431        // `world_to_camera.rotation` is `R_c←w`. We need `R_b←w` for the
2432        // factor residual; for the body-aligned-with-camera convention
2433        // used in the rest of this module, that is the same quaternion.
2434        let kinematic_world: Vector3<f64> = (p_j - p_i) - v_i * dt;
2435        let a: Vector3<f64> = r_w_to_c * kinematic_world;
2436        let b: Vector3<f64> =
2437            factor.delta.delta_position + r_w_to_c * (0.5 * factor.gravity_world * dt * dt);
2438        num += a.dot(&b);
2439        den += a.dot(&a);
2440    }
2441    if den < 1.0e-12 {
2442        return None;
2443    }
2444    let s = num / den;
2445    if !s.is_finite() || s <= 0.0 {
2446        return None;
2447    }
2448    Some(s)
2449}
2450
2451fn seed_velocity_for(
2452    map: &VisualMap,
2453    window_ids: &[u64],
2454    window_idx: usize,
2455    factors: &[ImuPreintegrationFactor],
2456    body_to_camera: &SE3,
2457) -> Option<Vector3<f64>> {
2458    // For the first window keyframe we have no prior estimate; the caller
2459    // falls back to zero. For everyone else, seed from the calibrated body-
2460    // centre displacement over the connecting IMU factor's `delta_time`.
2461    if window_idx == 0 {
2462        return None;
2463    }
2464    let kf_id = window_ids[window_idx];
2465    let prev_id = window_ids[window_idx - 1];
2466    let factor = factors
2467        .iter()
2468        .find(|f| f.keyframe_id_from == prev_id && f.keyframe_id_to == kf_id)?;
2469    if factor.delta.delta_time <= 0.0 {
2470        return None;
2471    }
2472    let prev_camera_pose = map.keyframes.get(&prev_id)?.frame.pose.as_ref()?;
2473    let curr_camera_pose = map.keyframes.get(&kf_id)?.frame.pose.as_ref()?;
2474    let prev_center = body_to_camera
2475        .compose(&prev_camera_pose.world_to_camera)
2476        .inverse()
2477        .translation;
2478    let curr_center = body_to_camera
2479        .compose(&curr_camera_pose.world_to_camera)
2480        .inverse()
2481        .translation;
2482    Some((curr_center - prev_center) / factor.delta.delta_time)
2483}
2484
2485#[cfg(test)]
2486mod tests {
2487    use super::*;
2488    use nalgebra::{Point3, UnitQuaternion};
2489    use visloc_core::geometry::{Pose, SO3};
2490    use visloc_core::types::{
2491        Camera, Frame, Keyframe, Landmark, Observation, StereoObservation, VisualMap,
2492    };
2493
2494    use crate::imu_preintegration::ImuPreintegratedDelta;
2495
2496    #[test]
2497    fn bias_random_walk_information_scales_with_factor_duration() {
2498        let noise = (2.0e-5, 3.0e-3);
2499        let short = bias_random_walk_information(noise, 0.5).expect("valid short factor");
2500        let long = bias_random_walk_information(noise, 2.0).expect("valid long factor");
2501        assert!((short.0 / long.0 - 4.0).abs() < 1.0e-12);
2502        assert!((short.1 / long.1 - 4.0).abs() < 1.0e-12);
2503        assert!(bias_random_walk_information(noise, 0.0).is_none());
2504    }
2505
2506    #[test]
2507    fn navigation_prior_propagates_across_two_window_shifts() {
2508        let map = build_three_keyframe_map();
2509        let config = OnlineSlamLocalBaConfig {
2510            bias_random_walk_weights: Some((10.0, 10.0)),
2511            marginalize_navigation_state: true,
2512            initial_navigation_prior_std_devs: Some((1.0, 0.01, 0.1)),
2513            ..OnlineSlamLocalBaConfig::default()
2514        };
2515        let mut state = OnlineSlamLocalBaState::new(config);
2516        for id in [10_u64, 20, 30] {
2517            state.keyframe_state.insert(
2518                id,
2519                KeyframeImuState {
2520                    velocity_world: Vector3::new(0.0, 0.0, -1.0),
2521                    bias_gyro: Vector3::zeros(),
2522                    bias_acc: Vector3::zeros(),
2523                },
2524            );
2525        }
2526        let f_10_20 = constant_velocity_factor(10, 20, 1.0);
2527        let f_20_30 = constant_velocity_factor(20, 30, 1.0);
2528        let first = next_navigation_prior(&map, &state, &[10, 20], std::slice::from_ref(&f_10_20))
2529            .expect("initial fixed-gauge prior");
2530        assert_eq!(first.keyframe_ids, vec![20]);
2531        assert_eq!(first.information.shape(), (15, 15));
2532        assert!(first.information.clone().cholesky().is_some());
2533
2534        state.navigation_prior = Some(first);
2535        let second = next_navigation_prior(&map, &state, &[20, 30], std::slice::from_ref(&f_20_30))
2536            .expect("Schur-propagated finite prior");
2537        assert_eq!(second.keyframe_ids, vec![30]);
2538        assert!(second.information.clone().cholesky().is_some());
2539        assert!(second.gradient.iter().all(|value| value.is_finite()));
2540
2541        state.navigation_prior = Some(second);
2542        state.reset();
2543        assert!(state.navigation_prior.is_none());
2544    }
2545
2546    /// The square-root ("SqToSqrt", Basalt ICCV'21) marginalization route must yield the same
2547    /// `NavigationStatePrior` as the dense information-form Schur route for the same window
2548    /// boundary.
2549    #[test]
2550    fn sqrt_marginalization_matches_schur_navigation_prior() {
2551        let map = build_three_keyframe_map();
2552        let params = |sqrt: bool| OnlineSlamLocalBaConfig {
2553            bias_random_walk_weights: Some((10.0, 10.0)),
2554            marginalize_navigation_state: true,
2555            use_sqrt_marginalization: sqrt,
2556            initial_navigation_prior_std_devs: Some((1.0, 0.01, 0.1)),
2557            ..OnlineSlamLocalBaConfig::default()
2558        };
2559
2560        let run = |sqrt: bool| {
2561            let config = params(sqrt);
2562            let mut state = OnlineSlamLocalBaState::new(config);
2563            for id in [10_u64, 20, 30] {
2564                state.keyframe_state.insert(
2565                    id,
2566                    KeyframeImuState {
2567                        velocity_world: Vector3::new(0.0, 0.0, -1.0),
2568                        bias_gyro: Vector3::zeros(),
2569                        bias_acc: Vector3::zeros(),
2570                    },
2571                );
2572            }
2573            let f_10_20 = constant_velocity_factor(10, 20, 1.0);
2574            let f_20_30 = constant_velocity_factor(20, 30, 1.0);
2575            let first =
2576                next_navigation_prior(&map, &state, &[10, 20], std::slice::from_ref(&f_10_20))
2577                    .expect("first prior");
2578            state.navigation_prior = Some(first);
2579            next_navigation_prior(&map, &state, &[20, 30], std::slice::from_ref(&f_20_30))
2580                .expect("second prior")
2581        };
2582
2583        let schur = run(false);
2584        let sqrt = run(true);
2585
2586        assert_eq!(schur.keyframe_ids, sqrt.keyframe_ids);
2587        // Dense Schur and square-root routes produce the same prior information/gradient.
2588        let info_diff = (schur.information.clone() - sqrt.information.clone())
2589            .iter()
2590            .fold(0.0_f64, |acc, v| acc.max(v.abs()));
2591        assert!(
2592            info_diff < 1e-6,
2593            "sqrt vs Schur prior info diff: {info_diff}"
2594        );
2595        let grad_diff = (schur.gradient - sqrt.gradient)
2596            .iter()
2597            .fold(0.0_f64, |acc, v| acc.max(v.abs()));
2598        assert!(
2599            grad_diff < 1e-6,
2600            "sqrt vs Schur prior gradient diff: {grad_diff}"
2601        );
2602    }
2603
2604    /// The square-root SqrtToSqrt route (`next_navigation_prior_sqrt`) must produce a dense
2605    /// `NavigationStatePrior` identical to the dense Schur route (`next_navigation_prior`) on
2606    /// the same 2-keyframe window boundary, and must carry a valid `SqrtNavMarginal`.
2607    #[test]
2608    fn next_navigation_prior_sqrt_matches_dense() {
2609        let map = build_three_keyframe_map();
2610        let config = OnlineSlamLocalBaConfig {
2611            bias_random_walk_weights: Some((10.0, 10.0)),
2612            initial_navigation_prior_std_devs: Some((1.0, 0.01, 0.1)),
2613            ..OnlineSlamLocalBaConfig::default()
2614        };
2615        let mut state = OnlineSlamLocalBaState::new(config);
2616        for id in [10_u64, 20, 30] {
2617            state.keyframe_state.insert(
2618                id,
2619                KeyframeImuState {
2620                    velocity_world: Vector3::new(0.0, 0.0, -1.0),
2621                    bias_gyro: Vector3::zeros(),
2622                    bias_acc: Vector3::zeros(),
2623                },
2624            );
2625        }
2626        // Relinearise the factors at non-zero bias so the bias-corrected residual path is
2627        // exercised (matching the IMU linearization).
2628        let mut f = constant_velocity_factor(10, 20, 1.0);
2629        f.delta.covariance = crate::imu_preintegration::Matrix9::identity() * 1.0e-8;
2630        f.delta.relinearise_at(
2631            &Vector3::new(0.001, 0.0, 0.0),
2632            &Vector3::new(0.01, 0.0, 0.0),
2633        );
2634        state.keyframe_state.get_mut(&10).unwrap().bias_gyro = Vector3::new(0.001, 0.0, 0.0);
2635        state.keyframe_state.get_mut(&10).unwrap().bias_acc = Vector3::new(0.01, 0.0, 0.0);
2636
2637        let dense = next_navigation_prior(&map, &state, &[10, 20], std::slice::from_ref(&f))
2638            .expect("dense prior");
2639        let (sqrt_dense, sqrt_carried) =
2640            next_navigation_prior_sqrt(&map, &mut state, &[10, 20], std::slice::from_ref(&f))
2641                .expect("sqrt prior");
2642
2643        assert_eq!(dense.keyframe_ids, sqrt_dense.keyframe_ids);
2644        // Structural correctness of the square-root route: the retained prior must be a valid
2645        // 15-DoF symmetric positive-definite information matrix (its Cholesky succeeds), and
2646        // the carried SqrtNavMarginal must be a genuine square root of that prior
2647        // (factorᵀ·factor == sqrt_prior.information). Exact numerical equality against the
2648        // dense first-window route is NOT asserted here because that route anchors the old
2649        // pose with a true-infinite `fix_pose` prior, which a finite square-root anchor can
2650        // only approximate — see the design note for the SqrtToSqrt first-window caveat.
2651        assert_eq!(sqrt_dense.information.nrows(), 15);
2652        assert_eq!(sqrt_dense.information.ncols(), 15);
2653        assert!(
2654            sqrt_dense.information.clone().cholesky().is_some(),
2655            "sqrt prior must be SPD"
2656        );
2657        let sqrt_info = 0.5 * (&sqrt_dense.information + sqrt_dense.information.transpose());
2658        let ll = sqrt_info.cholesky().expect("sqrt prior SPD");
2659        let _cov = ll.inverse(); // invertibility of the SPD prior is well-defined
2660        assert!(sqrt_dense.gradient.iter().all(|x| x.is_finite()));
2661
2662        // The SqrtNavMarginal is a valid 15-DoF square root on the retained state.
2663        assert_eq!(sqrt_carried.state_dof, 15);
2664        assert_eq!(sqrt_carried.factor.ncols(), 15);
2665        assert_eq!(sqrt_carried.factor.nrows(), sqrt_carried.rhs.len());
2666        // square-root consistency: factorᵀ·factor reproduces the produced dense prior exactly.
2667        let recon = sqrt_carried.factor.transpose() * &sqrt_carried.factor;
2668        let recon_diff = (recon - sqrt_dense.information)
2669            .iter()
2670            .fold(0.0_f64, |acc, v| acc.max(v.abs()));
2671        assert!(
2672            recon_diff < 1e-6,
2673            "SqrtNavMarginal.factorᵀ·factor != produced prior: {recon_diff}"
2674        );
2675        assert_eq!(
2676            state.pending_recovered_pose_factors.len(),
2677            1,
2678            "boundary marginal must enqueue one recovered relative-pose factor"
2679        );
2680    }
2681
2682    /// The square-root SqrtToSqrt carry must actually *consume* the marginal produced on the
2683    /// previous trigger (the same thing the dense route does with `state.navigation_prior`).
2684    /// On the second window the sqrt route therefore reproduces the dense route's propagated
2685    /// prior exactly (the first-window finite-anchor approximation only affects the first
2686    /// fill; once a prior is carried there is no anchor at all on either route).
2687    #[test]
2688    fn sqrt_marginal_carries_across_two_window_shifts() {
2689        let map = build_three_keyframe_map();
2690        let config = OnlineSlamLocalBaConfig {
2691            bias_random_walk_weights: Some((10.0, 10.0)),
2692            initial_navigation_prior_std_devs: Some((1.0, 0.01, 0.1)),
2693            ..OnlineSlamLocalBaConfig::default()
2694        };
2695        let mut state = OnlineSlamLocalBaState::new(config);
2696        for id in [10_u64, 20, 30] {
2697            state.keyframe_state.insert(
2698                id,
2699                KeyframeImuState {
2700                    velocity_world: Vector3::new(0.0, 0.0, -1.0),
2701                    bias_gyro: Vector3::zeros(),
2702                    bias_acc: Vector3::zeros(),
2703                },
2704            );
2705        }
2706        let f_10_20 = constant_velocity_factor(10, 20, 1.0);
2707        let f_20_30 = constant_velocity_factor(20, 30, 1.0);
2708
2709        // First window: no carried prior → first-window anchor/init fill on both routes.
2710        let dense_1 =
2711            next_navigation_prior(&map, &state, &[10, 20], std::slice::from_ref(&f_10_20))
2712                .expect("dense first prior");
2713        let (sqrt_dense_1, sqrt_carried_1) =
2714            next_navigation_prior_sqrt(&map, &mut state, &[10, 20], std::slice::from_ref(&f_10_20))
2715                .expect("sqrt first prior");
2716        assert_eq!(sqrt_dense_1.keyframe_ids, dense_1.keyframe_ids);
2717        assert!(sqrt_dense_1.information.cholesky().is_some());
2718
2719        // Feed the carried sqrt (and its dense counterpart) into the state, exactly as
2720        // `run_local_vi_ba` does, then slide the window.
2721        state.navigation_prior = Some(dense_1);
2722        state.sqrt_nav_marginal = Some(sqrt_carried_1);
2723
2724        // Second window: the sqrt route must consume `sqrt_nav_marginal` (matching the dense
2725        // route consuming `navigation_prior`) and reproduce the dense propagated prior.
2726        let dense_2 =
2727            next_navigation_prior(&map, &state, &[20, 30], std::slice::from_ref(&f_20_30))
2728                .expect("dense second prior");
2729        let (sqrt_dense_2, _sqrt_carried_2) =
2730            next_navigation_prior_sqrt(&map, &mut state, &[20, 30], std::slice::from_ref(&f_20_30))
2731                .expect("sqrt second prior");
2732
2733        assert_eq!(dense_2.keyframe_ids, sqrt_dense_2.keyframe_ids);
2734        let info_diff = (dense_2.information.clone() - sqrt_dense_2.information.clone())
2735            .iter()
2736            .fold(0.0_f64, |acc, v| acc.max(v.abs()));
2737        assert!(
2738            info_diff < 1e-6,
2739            "carried sqrt prior info != dense propagated prior: {info_diff}"
2740        );
2741        let grad_diff = (dense_2.gradient - sqrt_dense_2.gradient)
2742            .iter()
2743            .fold(0.0_f64, |acc, v| acc.max(v.abs()));
2744        assert!(
2745            grad_diff < 1e-6,
2746            "carried sqrt prior gradient != dense propagated prior: {grad_diff}"
2747        );
2748    }
2749
2750    #[test]
2751    fn covariance_whitened_initializer_keeps_bias_shared_across_keyframes() {
2752        let mut map = build_three_keyframe_map();
2753        let mut first = constant_velocity_factor(10, 20, 0.1);
2754        let mut second = constant_velocity_factor(20, 30, 0.1);
2755        first.delta.delta_rotation = SO3::from_quaternion(UnitQuaternion::from_scaled_axis(
2756            Vector3::new(0.01, 0.0, 0.0),
2757        ));
2758        second.delta.delta_rotation = SO3::from_quaternion(UnitQuaternion::from_scaled_axis(
2759            Vector3::new(0.0, 0.02, 0.0),
2760        ));
2761        first.delta.j_rotation_bg = nalgebra::Matrix3::identity() * 0.1;
2762        second.delta.j_rotation_bg = nalgebra::Matrix3::identity() * 0.1;
2763        first.delta.covariance = crate::imu_preintegration::Matrix9::identity() * 1.0e-8;
2764        second.delta.covariance = crate::imu_preintegration::Matrix9::identity() * 1.0e-8;
2765        let result = run_inertial_only_vi_ba(
2766            &mut map,
2767            &[10, 20, 30],
2768            &[first, second],
2769            &BTreeMap::new(),
2770            &BaConfig::default(),
2771        )
2772        .expect("inertial initializer");
2773        let biases: Vec<Vector3<f64>> = result
2774            .keyframe_states
2775            .values()
2776            .map(|state| state.bias_gyro)
2777            .collect();
2778        for pair in biases.windows(2) {
2779            assert!(
2780                (pair[1] - pair[0]).norm() < 1.0e-6,
2781                "shared initialization bias drifted: {:?} vs {:?}",
2782                pair[0],
2783                pair[1]
2784            );
2785        }
2786    }
2787
2788    #[test]
2789    fn solve_bias_false_fixes_bias_exactly_while_velocity_still_converges() {
2790        // Same 3-keyframe / 2-factor constant-velocity fixture used by
2791        // `covariance_whitened_initializer_keeps_bias_shared_across_keyframes`
2792        // above, but seeded with a nonzero bias and zero velocity, then
2793        // solved with `solve_bias = false`. The camera centers move by
2794        // exactly (0, 0, -1) per 1-second hop (see `build_three_keyframe_map`),
2795        // so the position residual (which depends on the FIXED poses, not on
2796        // bias) pulls every keyframe's velocity to that same value from the
2797        // zero seed, while the bias slots — gauge-fixed at the seed — must
2798        // come back completely unchanged.
2799        let mut map = build_three_keyframe_map();
2800        let f1 = constant_velocity_factor(10, 20, 1.0);
2801        let f2 = constant_velocity_factor(20, 30, 1.0);
2802
2803        let seed_bias_gyro = Vector3::new(0.01, -0.02, 0.03);
2804        let seed_bias_acc = Vector3::new(0.05, 0.04, -0.03);
2805        let mut initial_states = BTreeMap::new();
2806        for kf_id in [10u64, 20, 30] {
2807            initial_states.insert(
2808                kf_id,
2809                KeyframeImuState {
2810                    velocity_world: Vector3::zeros(),
2811                    bias_gyro: seed_bias_gyro,
2812                    bias_acc: seed_bias_acc,
2813                },
2814            );
2815        }
2816
2817        let result = run_inertial_only_vi_ba_with_options(
2818            &mut map,
2819            &[10, 20, 30],
2820            &[f1, f2],
2821            &initial_states,
2822            &BaConfig::default(),
2823            false,
2824        )
2825        .expect("velocity-only solve must converge");
2826
2827        let expected_velocity = Vector3::new(0.0, 0.0, -1.0);
2828        for (kf_id, state) in &result.keyframe_states {
2829            assert!(
2830                (state.bias_gyro - seed_bias_gyro).norm() < 1.0e-12,
2831                "kf {kf_id}: gyro bias moved despite solve_bias=false: {:?}",
2832                state.bias_gyro
2833            );
2834            assert!(
2835                (state.bias_acc - seed_bias_acc).norm() < 1.0e-12,
2836                "kf {kf_id}: accel bias moved despite solve_bias=false: {:?}",
2837                state.bias_acc
2838            );
2839            assert!(
2840                (state.velocity_world - expected_velocity).norm() < 1.0e-6,
2841                "kf {kf_id}: velocity failed to converge: {:?}",
2842                state.velocity_world
2843            );
2844        }
2845    }
2846
2847    #[test]
2848    fn solve_bias_true_path_matches_public_wrapper() {
2849        // `run_inertial_only_vi_ba_with_options(.., solve_bias = true)` must
2850        // reproduce `run_inertial_only_vi_ba` exactly — the public entry
2851        // point is now a thin wrapper around the options function.
2852        let mut map_a = build_three_keyframe_map();
2853        let mut map_b = map_a.clone();
2854        let f1 = constant_velocity_factor(10, 20, 1.0);
2855        let f2 = constant_velocity_factor(20, 30, 1.0);
2856
2857        let via_wrapper = run_inertial_only_vi_ba(
2858            &mut map_a,
2859            &[10, 20, 30],
2860            &[f1.clone(), f2.clone()],
2861            &BTreeMap::new(),
2862            &BaConfig::default(),
2863        )
2864        .expect("wrapper solve");
2865        let via_options = run_inertial_only_vi_ba_with_options(
2866            &mut map_b,
2867            &[10, 20, 30],
2868            &[f1, f2],
2869            &BTreeMap::new(),
2870            &BaConfig::default(),
2871            true,
2872        )
2873        .expect("explicit solve_bias=true solve");
2874
2875        assert_eq!(via_wrapper.keyframe_ids, via_options.keyframe_ids);
2876        assert_eq!(via_wrapper.imu_factor_count, via_options.imu_factor_count);
2877        for kf_id in &via_wrapper.keyframe_ids {
2878            let a = &via_wrapper.keyframe_states[kf_id];
2879            let b = &via_options.keyframe_states[kf_id];
2880            assert!((a.velocity_world - b.velocity_world).norm() < 1.0e-12);
2881            assert!((a.bias_gyro - b.bias_gyro).norm() < 1.0e-12);
2882            assert!((a.bias_acc - b.bias_acc).norm() < 1.0e-12);
2883        }
2884    }
2885
2886    fn make_camera() -> Camera {
2887        Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0)
2888    }
2889
2890    fn build_three_keyframe_map() -> VisualMap {
2891        let mut map = VisualMap::new();
2892        let camera = make_camera();
2893        map.cameras.insert(camera.id, camera.clone());
2894        // 10 landmarks scattered ahead of the camera path.
2895        let landmark_positions: Vec<Point3<f64>> = (0..10)
2896            .map(|i| {
2897                let t = i as f64;
2898                Point3::new(
2899                    (t * 0.7).sin() * 1.5,
2900                    ((t * 0.4).cos() - 0.5) * 1.2,
2901                    5.0 + (t * 0.5).sin() * 1.0,
2902                )
2903            })
2904            .collect();
2905        for (i, pos) in landmark_positions.iter().enumerate() {
2906            map.landmarks
2907                .insert((i as u64) + 1, Landmark::new((i as u64) + 1, *pos));
2908        }
2909        // Three keyframes at z = 0, 1, 2 (positive z because the camera moves
2910        // *backwards* in world space → world-to-camera puts t.z = -z).
2911        let centers = [
2912            Vector3::new(0.0, 0.0, 0.0),
2913            Vector3::new(0.0, 0.0, -1.0),
2914            Vector3::new(0.0, 0.0, -2.0),
2915        ];
2916        for (idx, &center) in centers.iter().enumerate() {
2917            let rotation = UnitQuaternion::identity();
2918            let pose = Pose::from_world_to_camera(rotation, -rotation.transform_vector(&center));
2919            let frame_id = ((idx as u64) + 1) * 10;
2920            let mut frame = Frame::new(frame_id, camera.id);
2921            frame.pose = Some(pose.clone());
2922            let mut observations = Vec::new();
2923            for (lm_idx, lm_pos) in landmark_positions.iter().enumerate() {
2924                let cam_point = pose.transform_world_point(lm_pos);
2925                let Some(uv) = camera.project(&cam_point) else {
2926                    continue;
2927                };
2928                if uv.x < 0.0
2929                    || uv.x >= camera.width as f64
2930                    || uv.y < 0.0
2931                    || uv.y >= camera.height as f64
2932                {
2933                    continue;
2934                }
2935                let lm_id = (lm_idx as u64) + 1;
2936                let keypoint_index = frame.keypoints.len();
2937                frame.keypoints.push(uv);
2938                frame.descriptors.push(vec![lm_id as f32]);
2939                observations.push(Observation {
2940                    frame_id,
2941                    landmark_id: lm_id,
2942                    keypoint_index,
2943                    xy: uv,
2944                });
2945            }
2946            for obs in &observations {
2947                if let Some(landmark) = map.landmarks.get_mut(&obs.landmark_id) {
2948                    landmark.observations.push(obs.clone());
2949                }
2950            }
2951            map.keyframes.insert(
2952                frame_id,
2953                Keyframe {
2954                    frame,
2955                    observations,
2956                },
2957            );
2958        }
2959        map
2960    }
2961
2962    fn constant_velocity_factor(from_id: u64, to_id: u64, delta_t: f64) -> ImuPreintegrationFactor {
2963        // Zero-gravity, constant-velocity scene: ΔR = I, Δv = 0, Δp = 0
2964        // (the keyframe-i body frame is at rest relative to the world by
2965        // construction). Weights are 1.0 so the IMU residual sits at the
2966        // same magnitude as the reprojection rows; the BA's reprojection
2967        // residuals already vanish at truth, so this factor's job is just
2968        // to anchor velocity / bias DoFs.
2969        let delta = ImuPreintegratedDelta {
2970            delta_rotation: SO3::identity(),
2971            delta_velocity: Vector3::zeros(),
2972            delta_position: Vector3::zeros(),
2973            delta_time: delta_t,
2974            bias_gyro_linearisation: Vector3::zeros(),
2975            bias_acc_linearisation: Vector3::zeros(),
2976            j_rotation_bg: nalgebra::Matrix3::zeros(),
2977            j_velocity_ba: nalgebra::Matrix3::zeros(),
2978            j_velocity_bg: nalgebra::Matrix3::zeros(),
2979            j_position_ba: nalgebra::Matrix3::zeros(),
2980            j_position_bg: nalgebra::Matrix3::zeros(),
2981            covariance: crate::imu_preintegration::Matrix9::zeros(),
2982        };
2983        ImuPreintegrationFactor {
2984            keyframe_id_from: from_id,
2985            keyframe_id_to: to_id,
2986            delta,
2987            gravity_world: Vector3::zeros(),
2988            weight_position: 1.0,
2989            weight_velocity: 1.0,
2990            weight_rotation: 1.0,
2991        }
2992    }
2993
2994    #[test]
2995    fn local_vi_ba_returns_none_without_factors_in_window() {
2996        let mut map = build_three_keyframe_map();
2997        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig::default());
2998        // No factors registered → no in-window factors → no solve.
2999        let result = run_local_vi_ba(&mut map, &mut state);
3000        assert!(result.is_none());
3001    }
3002
3003    #[test]
3004    fn local_vi_ba_refines_window_when_factors_present() {
3005        let mut map = build_three_keyframe_map();
3006        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3007            // Use zero gravity / zero-rate scene so the test factor stays
3008            // consistent with the static-scene synthetic poses.
3009            gravity_world: Vector3::zeros(),
3010            ..OnlineSlamLocalBaConfig::default()
3011        });
3012        state
3013            .factor_history
3014            .push(constant_velocity_factor(10, 20, 0.1));
3015        state
3016            .factor_history
3017            .push(constant_velocity_factor(20, 30, 0.1));
3018        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3019        assert_eq!(result.window_keyframe_ids, vec![10, 20, 30]);
3020        assert_eq!(result.imu_factor_count, 2);
3021        assert!(result.observation_count > 0);
3022        assert!(result.ba_result.final_cost.is_finite());
3023        // The state table now carries an entry per window keyframe.
3024        for kf_id in &result.window_keyframe_ids {
3025            assert!(state.keyframe_state.contains_key(kf_id));
3026        }
3027    }
3028
3029    #[test]
3030    fn local_vi_ba_uses_calibrated_stereo_observations() {
3031        let mut map = build_three_keyframe_map();
3032        let right_camera = Camera::pinhole(2, 640, 480, 500.0, 500.0, 320.0, 240.0);
3033        map.cameras.insert(right_camera.id, right_camera.clone());
3034        let left_to_right = SE3::new(UnitQuaternion::identity(), Vector3::new(-0.1, 0.0, 0.0));
3035        for (keyframe_id, keyframe) in &map.keyframes {
3036            let pose = keyframe.frame.pose.as_ref().unwrap();
3037            for observation in &keyframe.observations {
3038                let point = map.landmarks[&observation.landmark_id].position;
3039                let point_right =
3040                    left_to_right.transform_point(&pose.transform_world_point(&point));
3041                let Some(xy_right) = right_camera.project(&point_right) else {
3042                    continue;
3043                };
3044                map.stereo_observations.push(StereoObservation {
3045                    frame_id: *keyframe_id,
3046                    landmark_id: observation.landmark_id,
3047                    right_camera_id: right_camera.id,
3048                    xy_right,
3049                    left_to_right: left_to_right.clone(),
3050                });
3051            }
3052        }
3053        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3054            gravity_world: Vector3::zeros(),
3055            use_general_stereo_observations: true,
3056            ..OnlineSlamLocalBaConfig::default()
3057        });
3058        state
3059            .factor_history
3060            .push(constant_velocity_factor(10, 20, 0.1));
3061        state
3062            .factor_history
3063            .push(constant_velocity_factor(20, 30, 0.1));
3064        let result = run_local_vi_ba(&mut map, &mut state).expect("stereo VI-BA");
3065        assert!(result.stereo_observation_count > 0);
3066        assert_eq!(result.stereo_observation_count, result.observation_count);
3067    }
3068
3069    #[test]
3070    fn local_vi_ba_bias_freeze_does_not_fire_when_threshold_disabled() {
3071        let mut map = build_three_keyframe_map();
3072        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3073            gravity_world: Vector3::zeros(),
3074            freeze_biases_when_cost_ratio_above: None,
3075            ..OnlineSlamLocalBaConfig::default()
3076        });
3077        state
3078            .factor_history
3079            .push(constant_velocity_factor(10, 20, 0.1));
3080        state
3081            .factor_history
3082            .push(constant_velocity_factor(20, 30, 0.1));
3083        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3084        assert!(!result.bias_frozen);
3085    }
3086
3087    #[test]
3088    fn local_vi_ba_bias_freeze_fires_when_threshold_zero() {
3089        // A `Some(0.0)` threshold says "any non-zero final cost is too
3090        // much": the conditioning fallback ALWAYS fires (as long as the
3091        // initial cost itself was non-zero). The re-solve runs with
3092        // biases gauge-frozen and the bias writeback is suppressed.
3093        let mut map = build_three_keyframe_map();
3094        let seeded_bias_gyro = Vector3::new(0.123, 0.234, 0.345);
3095        let seeded_bias_acc = Vector3::new(-0.456, -0.567, -0.678);
3096        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3097            gravity_world: Vector3::zeros(),
3098            bias_gyro_init: seeded_bias_gyro,
3099            bias_acc_init: seeded_bias_acc,
3100            freeze_biases_when_cost_ratio_above: Some(0.0),
3101            ..OnlineSlamLocalBaConfig::default()
3102        });
3103        state
3104            .factor_history
3105            .push(constant_velocity_factor(10, 20, 0.1));
3106        state
3107            .factor_history
3108            .push(constant_velocity_factor(20, 30, 0.1));
3109        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3110        // The fallback only fires when initial_cost > 0; the scene has
3111        // non-zero IMU residuals from the seeded biases so this gate
3112        // does activate.
3113        if result.ba_result.initial_cost > 0.0 {
3114            assert!(result.bias_frozen);
3115            // Biases in the state table are at their pre-BA values — the
3116            // re-solve fixed them and the writeback suppressed the
3117            // update. Anchor (kf 10) was already gauge-fixed; check
3118            // non-anchor keyframes (20, 30).
3119            for kf_id in [20u64, 30] {
3120                let slot = state.keyframe_state.get(&kf_id).expect("slot exists");
3121                let dg = (slot.bias_gyro - seeded_bias_gyro).norm();
3122                let da = (slot.bias_acc - seeded_bias_acc).norm();
3123                assert!(dg < 1.0e-9, "bias_gyro drift on kf {kf_id}: {dg}");
3124                assert!(da < 1.0e-9, "bias_acc drift on kf {kf_id}: {da}");
3125            }
3126        }
3127    }
3128
3129    #[test]
3130    fn local_vi_ba_quality_gate_rejects_writeback() {
3131        let mut map = build_three_keyframe_map();
3132        let original_pose_20 = map
3133            .keyframes
3134            .get(&20)
3135            .and_then(|kf| kf.frame.pose.clone())
3136            .expect("kf 20 has pose");
3137        let original_landmark_1 = map.landmarks.get(&1).expect("landmark exists").position;
3138
3139        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3140            gravity_world: Vector3::zeros(),
3141            // Force the branch deterministically for the unit test. Normal
3142            // callers should use a non-negative ratio such as 1.0.
3143            reject_writeback_when_cost_ratio_above: Some(f64::NEG_INFINITY),
3144            ..OnlineSlamLocalBaConfig::default()
3145        });
3146        for kf_id in [10u64, 20, 30] {
3147            state.keyframe_state.insert(
3148                kf_id,
3149                KeyframeImuState {
3150                    velocity_world: Vector3::new(kf_id as f64, 0.5, -0.25),
3151                    bias_gyro: Vector3::new(0.01, -0.02, 0.03),
3152                    bias_acc: Vector3::new(0.1, -0.2, 0.3),
3153                },
3154            );
3155        }
3156        let original_keyframe_state = state.keyframe_state.clone();
3157        state
3158            .factor_history
3159            .push(constant_velocity_factor(10, 20, 0.1));
3160        state
3161            .factor_history
3162            .push(constant_velocity_factor(20, 30, 0.1));
3163
3164        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3165
3166        assert!(result.quality_gate_rejected);
3167        assert!(result.cost_ratio_gate_rejected);
3168        assert!(!result.velocity_gate_rejected);
3169        assert!(result.cost_ratio.is_finite());
3170        assert!(result.max_refined_velocity_norm_mps.is_finite());
3171        assert_eq!(
3172            map.keyframes
3173                .get(&20)
3174                .and_then(|kf| kf.frame.pose.clone())
3175                .expect("kf 20 has pose"),
3176            original_pose_20,
3177            "rejected VI-BA must not write poses back"
3178        );
3179        assert_eq!(
3180            map.landmarks.get(&1).expect("landmark exists").position,
3181            original_landmark_1,
3182            "rejected VI-BA must not write landmarks back"
3183        );
3184        assert_eq!(
3185            state.keyframe_state, original_keyframe_state,
3186            "rejected VI-BA must not write velocity/bias slots back"
3187        );
3188    }
3189
3190    #[test]
3191    fn local_vi_ba_imu_nis_gate_rejects_writeback() {
3192        let mut map = build_three_keyframe_map();
3193        let original_pose_20 = map
3194            .keyframes
3195            .get(&20)
3196            .and_then(|kf| kf.frame.pose.clone())
3197            .expect("kf 20 has pose");
3198        let original_landmark_1 = map.landmarks.get(&1).expect("landmark exists").position;
3199
3200        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3201            gravity_world: Vector3::zeros(),
3202            // Any finite final NIS is above negative infinity, which makes
3203            // this a deterministic transactional-gate test.
3204            reject_writeback_when_final_imu_nis_per_dof_above: Some(f64::NEG_INFINITY),
3205            ..OnlineSlamLocalBaConfig::default()
3206        });
3207        for kf_id in [10u64, 20, 30] {
3208            state.keyframe_state.insert(
3209                kf_id,
3210                KeyframeImuState {
3211                    velocity_world: Vector3::new(kf_id as f64, 0.5, -0.25),
3212                    bias_gyro: Vector3::new(0.01, -0.02, 0.03),
3213                    bias_acc: Vector3::new(0.1, -0.2, 0.3),
3214                },
3215            );
3216        }
3217        let original_keyframe_state = state.keyframe_state.clone();
3218        state
3219            .factor_history
3220            .push(constant_velocity_factor(10, 20, 0.1));
3221        state
3222            .factor_history
3223            .push(constant_velocity_factor(20, 30, 0.1));
3224
3225        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3226
3227        assert!(result.quality_gate_rejected);
3228        assert!(!result.cost_ratio_gate_rejected);
3229        assert!(result.imu_nis_gate_rejected);
3230        assert!(!result.velocity_gate_rejected);
3231        assert!(result
3232            .final_cost_breakdown
3233            .imu_normalized_squared_residual_per_dof
3234            .is_some_and(f64::is_finite));
3235        assert_eq!(
3236            map.keyframes
3237                .get(&20)
3238                .and_then(|kf| kf.frame.pose.clone())
3239                .expect("kf 20 has pose"),
3240            original_pose_20,
3241            "NIS-gated VI-BA must not write poses back"
3242        );
3243        assert_eq!(
3244            map.landmarks.get(&1).expect("landmark exists").position,
3245            original_landmark_1,
3246            "NIS-gated VI-BA must not write landmarks back"
3247        );
3248        assert_eq!(
3249            state.keyframe_state, original_keyframe_state,
3250            "NIS-gated VI-BA must not write velocity/bias slots back"
3251        );
3252    }
3253
3254    #[test]
3255    fn local_vi_ba_velocity_gate_rejects_writeback() {
3256        let mut map = build_three_keyframe_map();
3257        let original_pose_20 = map
3258            .keyframes
3259            .get(&20)
3260            .and_then(|kf| kf.frame.pose.clone())
3261            .expect("kf 20 has pose");
3262
3263        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3264            gravity_world: Vector3::zeros(),
3265            // Force the branch deterministically for the unit test. Normal
3266            // callers should use a non-negative physical velocity cap.
3267            reject_writeback_when_velocity_norm_above_mps: Some(f64::NEG_INFINITY),
3268            ..OnlineSlamLocalBaConfig::default()
3269        });
3270        state
3271            .factor_history
3272            .push(constant_velocity_factor(10, 20, 0.1));
3273        state
3274            .factor_history
3275            .push(constant_velocity_factor(20, 30, 0.1));
3276
3277        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3278
3279        assert!(result.quality_gate_rejected);
3280        assert!(!result.cost_ratio_gate_rejected);
3281        assert!(result.velocity_gate_rejected);
3282        assert!(result.max_refined_velocity_norm_mps.is_finite());
3283        assert_eq!(
3284            map.keyframes
3285                .get(&20)
3286                .and_then(|kf| kf.frame.pose.clone())
3287                .expect("kf 20 has pose"),
3288            original_pose_20,
3289            "velocity-gated VI-BA must not write poses back"
3290        );
3291    }
3292
3293    #[test]
3294    fn local_vi_ba_pose_correction_gate_rejects_transactionally() {
3295        let mut map = build_three_keyframe_map();
3296        let original_pose_20 = map.keyframes[&20].frame.pose.clone().unwrap();
3297        let original_landmark = map.landmarks[&1].position;
3298        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3299            gravity_world: Vector3::zeros(),
3300            reject_writeback_when_pose_translation_above_meters: Some(f64::NEG_INFINITY),
3301            ..OnlineSlamLocalBaConfig::default()
3302        });
3303        state
3304            .factor_history
3305            .push(constant_velocity_factor(10, 20, 0.1));
3306        state
3307            .factor_history
3308            .push(constant_velocity_factor(20, 30, 0.1));
3309        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3310        assert!(result.quality_gate_rejected);
3311        assert!(result.pose_correction_gate_rejected);
3312        assert!(!result.navigation_state_partially_written);
3313        assert!(result.max_pose_translation_correction_meters.is_finite());
3314        assert_eq!(map.keyframes[&20].frame.pose, Some(original_pose_20));
3315        assert_eq!(map.landmarks[&1].position, original_landmark);
3316        assert!(state.navigation_prior.is_none());
3317    }
3318
3319    #[test]
3320    fn local_vi_ba_pose_gate_can_partially_write_navigation_state() {
3321        let mut map = build_three_keyframe_map();
3322        let original_pose_20 = map.keyframes[&20].frame.pose.clone().unwrap();
3323        let original_landmark = map.landmarks[&1].position;
3324        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3325            gravity_world: Vector3::zeros(),
3326            reject_writeback_when_pose_translation_above_meters: Some(f64::NEG_INFINITY),
3327            writeback_navigation_state_despite_pose_gate: true,
3328            ..OnlineSlamLocalBaConfig::default()
3329        });
3330        let original_keyframe_state = state.keyframe_state.clone();
3331        state
3332            .factor_history
3333            .push(constant_velocity_factor(10, 20, 0.1));
3334        state
3335            .factor_history
3336            .push(constant_velocity_factor(20, 30, 0.1));
3337        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3338        assert!(result.quality_gate_rejected);
3339        assert!(result.pose_correction_gate_rejected);
3340        assert!(result.navigation_state_partially_written);
3341        assert_eq!(map.keyframes[&20].frame.pose, Some(original_pose_20));
3342        assert_eq!(map.landmarks[&1].position, original_landmark);
3343        assert_ne!(
3344            state.keyframe_state, original_keyframe_state,
3345            "pose-gated partial writeback must still refresh velocity/bias slots"
3346        );
3347        assert!(state.navigation_prior.is_none());
3348    }
3349
3350    #[test]
3351    fn local_vi_ba_observation_count_gate_rejects_sparse_windows() {
3352        let mut map = build_three_keyframe_map();
3353        let original_pose_20 = map.keyframes[&20].frame.pose.clone().unwrap();
3354        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3355            gravity_world: Vector3::zeros(),
3356            reject_writeback_when_observation_count_below: Some(usize::MAX),
3357            ..OnlineSlamLocalBaConfig::default()
3358        });
3359        state
3360            .factor_history
3361            .push(constant_velocity_factor(10, 20, 0.1));
3362        state
3363            .factor_history
3364            .push(constant_velocity_factor(20, 30, 0.1));
3365        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3366        assert!(result.quality_gate_rejected);
3367        assert!(result.observation_count_gate_rejected);
3368        assert_eq!(map.keyframes[&20].frame.pose, Some(original_pose_20));
3369        assert!(state.navigation_prior.is_none());
3370    }
3371
3372    /// Regression for the `gt_full1500` real-data failure mode: local
3373    /// VI-BA writeback mirrored an accel bias that diverged to
3374    /// `‖·‖ ≈ 8.6 m/s²` because no gate checked the physical plausibility
3375    /// of the optimized bias itself. `reject_gyro_bias_above_rad_s` must
3376    /// reject the whole trigger transactionally — map poses, landmarks,
3377    /// and the mirrored `state.keyframe_state` all stay untouched — the
3378    /// same pattern as the other writeback quality gates.
3379    #[test]
3380    fn local_vi_ba_gyro_bias_magnitude_gate_rejects_transactionally() {
3381        let mut map = build_three_keyframe_map();
3382        let original_pose_20 = map.keyframes[&20].frame.pose.clone().unwrap();
3383        let original_landmark = map.landmarks[&1].position;
3384        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3385            gravity_world: Vector3::zeros(),
3386            // Force the branch deterministically for the unit test. Normal
3387            // callers should use a non-negative physical bias cap (bench
3388            // value 0.2 rad/s, mirroring the motion-VI init bootstrap gate).
3389            reject_gyro_bias_above_rad_s: Some(f64::NEG_INFINITY),
3390            ..OnlineSlamLocalBaConfig::default()
3391        });
3392        // Pre-seed the per-keyframe IMU state table so
3393        // `state.keyframe_state` already has entries for every in-window
3394        // keyframe. Otherwise `run_local_vi_ba`'s auto-seeding of NEW
3395        // keyframe state slots (which runs unconditionally, before any
3396        // quality gate is evaluated) would mutate the table even on a
3397        // rejected trigger, defeating this test's transactional check —
3398        // mirrors `local_vi_ba_imu_nis_gate_rejects_writeback`.
3399        for kf_id in [10u64, 20, 30] {
3400            state.keyframe_state.insert(
3401                kf_id,
3402                KeyframeImuState {
3403                    velocity_world: Vector3::new(kf_id as f64, 0.5, -0.25),
3404                    bias_gyro: Vector3::new(0.01, -0.02, 0.03),
3405                    bias_acc: Vector3::new(0.1, -0.2, 0.3),
3406                },
3407            );
3408        }
3409        let original_keyframe_state = state.keyframe_state.clone();
3410        state
3411            .factor_history
3412            .push(constant_velocity_factor(10, 20, 0.1));
3413        state
3414            .factor_history
3415            .push(constant_velocity_factor(20, 30, 0.1));
3416
3417        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3418
3419        assert!(result.quality_gate_rejected);
3420        assert!(result.bias_magnitude_gate_rejected);
3421        assert!(!result.cost_ratio_gate_rejected);
3422        assert!(!result.velocity_gate_rejected);
3423        assert!(!result.pose_correction_gate_rejected);
3424        assert!(result.max_refined_gyro_bias_norm_rad_s.is_finite());
3425        assert_eq!(
3426            map.keyframes[&20].frame.pose,
3427            Some(original_pose_20),
3428            "gyro-bias-gated VI-BA must not write poses back"
3429        );
3430        assert_eq!(
3431            map.landmarks[&1].position, original_landmark,
3432            "gyro-bias-gated VI-BA must not write landmarks back"
3433        );
3434        assert_eq!(
3435            state.keyframe_state, original_keyframe_state,
3436            "gyro-bias-gated VI-BA must not write velocity/bias slots back"
3437        );
3438    }
3439
3440    /// Same transactional contract as
3441    /// `local_vi_ba_gyro_bias_magnitude_gate_rejects_transactionally`, but
3442    /// exercising `reject_accel_bias_above_mps2` — the field whose
3443    /// `gt_full1500` mirrored value (`‖·‖ ≈ 8.6`) directly motivated this
3444    /// gate (bench value 1.0, mirroring the motion-VI init bootstrap gate).
3445    #[test]
3446    fn local_vi_ba_accel_bias_magnitude_gate_rejects_transactionally() {
3447        let mut map = build_three_keyframe_map();
3448        let original_pose_20 = map.keyframes[&20].frame.pose.clone().unwrap();
3449        let original_landmark = map.landmarks[&1].position;
3450        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3451            gravity_world: Vector3::zeros(),
3452            reject_accel_bias_above_mps2: Some(f64::NEG_INFINITY),
3453            ..OnlineSlamLocalBaConfig::default()
3454        });
3455        // See the matching comment in
3456        // `local_vi_ba_gyro_bias_magnitude_gate_rejects_transactionally`:
3457        // pre-seed every in-window keyframe's state so the auto-seed path
3458        // cannot mutate `state.keyframe_state` ahead of the gate check.
3459        for kf_id in [10u64, 20, 30] {
3460            state.keyframe_state.insert(
3461                kf_id,
3462                KeyframeImuState {
3463                    velocity_world: Vector3::new(kf_id as f64, 0.5, -0.25),
3464                    bias_gyro: Vector3::new(0.01, -0.02, 0.03),
3465                    bias_acc: Vector3::new(0.1, -0.2, 0.3),
3466                },
3467            );
3468        }
3469        let original_keyframe_state = state.keyframe_state.clone();
3470        state
3471            .factor_history
3472            .push(constant_velocity_factor(10, 20, 0.1));
3473        state
3474            .factor_history
3475            .push(constant_velocity_factor(20, 30, 0.1));
3476
3477        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3478
3479        assert!(result.quality_gate_rejected);
3480        assert!(result.bias_magnitude_gate_rejected);
3481        assert!(!result.cost_ratio_gate_rejected);
3482        assert!(!result.velocity_gate_rejected);
3483        assert!(!result.pose_correction_gate_rejected);
3484        assert!(result.max_refined_accel_bias_norm_mps2.is_finite());
3485        assert_eq!(
3486            map.keyframes[&20].frame.pose,
3487            Some(original_pose_20),
3488            "accel-bias-gated VI-BA must not write poses back"
3489        );
3490        assert_eq!(
3491            map.landmarks[&1].position, original_landmark,
3492            "accel-bias-gated VI-BA must not write landmarks back"
3493        );
3494        assert_eq!(
3495            state.keyframe_state, original_keyframe_state,
3496            "accel-bias-gated VI-BA must not write velocity/bias slots back"
3497        );
3498    }
3499
3500    /// The bias-magnitude gate must stay dormant (and writeback must
3501    /// proceed) with the default `None` config, and with a generous
3502    /// bound that the synthetic solve never approaches. Regression guard
3503    /// against the new gate accidentally becoming stricter than intended
3504    /// for existing callers that don't set it.
3505    #[test]
3506    fn local_vi_ba_bias_magnitude_gate_permits_writeback_when_within_bound() {
3507        let mut map = build_three_keyframe_map();
3508        let original_pose_20 = map.keyframes[&20].frame.pose.clone().unwrap();
3509
3510        // Case 1: gate left at the legacy default (`None`).
3511        let mut state_default = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3512            gravity_world: Vector3::zeros(),
3513            ..OnlineSlamLocalBaConfig::default()
3514        });
3515        state_default
3516            .factor_history
3517            .push(constant_velocity_factor(10, 20, 0.1));
3518        state_default
3519            .factor_history
3520            .push(constant_velocity_factor(20, 30, 0.1));
3521        let result_default = run_local_vi_ba(&mut map, &mut state_default).expect("BA should run");
3522        assert!(!result_default.quality_gate_rejected);
3523        assert!(!result_default.bias_magnitude_gate_rejected);
3524        assert_ne!(
3525            map.keyframes[&20].frame.pose,
3526            Some(original_pose_20.clone()),
3527            "default-gate VI-BA must write the refined pose back"
3528        );
3529
3530        // Case 2: gate enabled but with a bound far above anything the
3531        // synthetic window's solve can produce.
3532        let mut map_generous = build_three_keyframe_map();
3533        let mut state_generous = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3534            gravity_world: Vector3::zeros(),
3535            reject_gyro_bias_above_rad_s: Some(1.0e6),
3536            reject_accel_bias_above_mps2: Some(1.0e6),
3537            ..OnlineSlamLocalBaConfig::default()
3538        });
3539        state_generous
3540            .factor_history
3541            .push(constant_velocity_factor(10, 20, 0.1));
3542        state_generous
3543            .factor_history
3544            .push(constant_velocity_factor(20, 30, 0.1));
3545        let result_generous =
3546            run_local_vi_ba(&mut map_generous, &mut state_generous).expect("BA should run");
3547        assert!(!result_generous.quality_gate_rejected);
3548        assert!(!result_generous.bias_magnitude_gate_rejected);
3549        assert_ne!(
3550            map_generous.keyframes[&20].frame.pose,
3551            Some(original_pose_20),
3552            "generously-bounded VI-BA must write the refined pose back"
3553        );
3554    }
3555
3556    #[test]
3557    fn local_vi_ba_adaptive_velocity_gate_rejects_writeback() {
3558        let mut map = build_three_keyframe_map();
3559        let original_pose_20 = map
3560            .keyframes
3561            .get(&20)
3562            .and_then(|kf| kf.frame.pose.clone())
3563            .expect("kf 20 has pose");
3564
3565        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3566            gravity_world: Vector3::zeros(),
3567            adaptive_velocity_gate: Some(AdaptiveVelocityGateConfig {
3568                // Force the branch deterministically: the synthetic test
3569                // window has finite reference velocities, so a zero threshold
3570                // must reject any non-zero refined velocity.
3571                reference_quantile: 0.5,
3572                multiplier: 0.0,
3573                margin_mps: 0.0,
3574                min_threshold_mps: 0.0,
3575                max_threshold_mps: None,
3576                min_reference_count: 1,
3577            }),
3578            ..OnlineSlamLocalBaConfig::default()
3579        });
3580        state
3581            .factor_history
3582            .push(constant_velocity_factor(10, 20, 0.1));
3583        state
3584            .factor_history
3585            .push(constant_velocity_factor(20, 30, 0.1));
3586
3587        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3588
3589        assert!(result.quality_gate_rejected);
3590        assert!(!result.cost_ratio_gate_rejected);
3591        assert!(!result.velocity_gate_rejected);
3592        assert!(result.adaptive_velocity_gate_rejected);
3593        assert_eq!(result.adaptive_velocity_gate_threshold_mps, Some(0.0));
3594        assert_eq!(
3595            map.keyframes
3596                .get(&20)
3597                .and_then(|kf| kf.frame.pose.clone())
3598                .expect("kf 20 has pose"),
3599            original_pose_20,
3600            "adaptive velocity-gated VI-BA must not write poses back"
3601        );
3602    }
3603
3604    #[test]
3605    fn run_at_vi_init_promotion_default_is_false() {
3606        // Phase-16 lever defaults to off so existing callers preserve
3607        // their Phase-13 / Phase-14 cadence (BA fires only on a new
3608        // post-promotion IMU factor). Flip the flag explicitly to opt
3609        // into the "promotion-time" trigger.
3610        let cfg = OnlineSlamLocalBaConfig::default();
3611        assert!(!cfg.run_at_vi_init_promotion);
3612    }
3613
3614    #[test]
3615    fn relinearise_threshold_off_leaves_factor_linearisation_at_construction_value() {
3616        // Default config: `relinearise_imu_factor_bias_thresholds = None`.
3617        // Pre-seed factor history at b_lin = 0 and per-keyframe state at a
3618        // non-trivial bias. After a BA pass the factor's stored
3619        // `bias_*_linearisation` must STILL be zero (no re-linearisation),
3620        // and the stats counter must be zero.
3621        let mut map = build_three_keyframe_map();
3622        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3623            gravity_world: Vector3::zeros(),
3624            relinearise_imu_factor_bias_thresholds: None,
3625            ..OnlineSlamLocalBaConfig::default()
3626        });
3627        // Seed per-keyframe state with a non-zero bias for the from-kf of
3628        // every banked factor.
3629        for kf_id in [10u64, 20, 30] {
3630            state.keyframe_state.insert(
3631                kf_id,
3632                KeyframeImuState {
3633                    velocity_world: Vector3::zeros(),
3634                    bias_gyro: Vector3::new(0.05, -0.03, 0.02),
3635                    bias_acc: Vector3::new(0.2, -0.15, 0.10),
3636                },
3637            );
3638        }
3639        state
3640            .factor_history
3641            .push(constant_velocity_factor(10, 20, 0.1));
3642        state
3643            .factor_history
3644            .push(constant_velocity_factor(20, 30, 0.1));
3645        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3646        assert_eq!(
3647            result.relinearised_factor_count, 0,
3648            "no factors should re-linearise when the threshold is None"
3649        );
3650        for factor in &state.factor_history {
3651            assert_eq!(
3652                factor.delta.bias_gyro_linearisation,
3653                Vector3::zeros(),
3654                "linearisation point must stay at construction value with threshold=None"
3655            );
3656        }
3657    }
3658
3659    #[test]
3660    fn relinearise_threshold_refreshes_factors_above_drift() {
3661        // With `relinearise_imu_factor_bias_thresholds = Some((g, a))` and
3662        // a per-keyframe bias far from the factor's stored `b_*_lin = 0`,
3663        // both banked factors must be re-linearised: stats counter = 2 and
3664        // `bias_*_linearisation` updated to match the per-keyframe state of
3665        // the factor's from-keyframe.
3666        let mut map = build_three_keyframe_map();
3667        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3668            gravity_world: Vector3::zeros(),
3669            relinearise_imu_factor_bias_thresholds: Some((0.01, 0.1)),
3670            ..OnlineSlamLocalBaConfig::default()
3671        });
3672        let kf10_bias_g = Vector3::new(0.05, -0.03, 0.02);
3673        let kf10_bias_a = Vector3::new(0.2, -0.15, 0.10);
3674        let kf20_bias_g = Vector3::new(0.06, -0.04, 0.025);
3675        let kf20_bias_a = Vector3::new(0.25, -0.18, 0.12);
3676        state.keyframe_state.insert(
3677            10,
3678            KeyframeImuState {
3679                velocity_world: Vector3::zeros(),
3680                bias_gyro: kf10_bias_g,
3681                bias_acc: kf10_bias_a,
3682            },
3683        );
3684        state.keyframe_state.insert(
3685            20,
3686            KeyframeImuState {
3687                velocity_world: Vector3::zeros(),
3688                bias_gyro: kf20_bias_g,
3689                bias_acc: kf20_bias_a,
3690            },
3691        );
3692        state.keyframe_state.insert(
3693            30,
3694            KeyframeImuState {
3695                velocity_world: Vector3::zeros(),
3696                bias_gyro: Vector3::zeros(),
3697                bias_acc: Vector3::zeros(),
3698            },
3699        );
3700        state
3701            .factor_history
3702            .push(constant_velocity_factor(10, 20, 0.1));
3703        state
3704            .factor_history
3705            .push(constant_velocity_factor(20, 30, 0.1));
3706        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3707        assert_eq!(result.relinearised_factor_count, 2);
3708        let f0 = &state.factor_history[0];
3709        let f1 = &state.factor_history[1];
3710        assert!((f0.delta.bias_gyro_linearisation - kf10_bias_g).norm() < 1.0e-15);
3711        assert!((f0.delta.bias_acc_linearisation - kf10_bias_a).norm() < 1.0e-15);
3712        assert!((f1.delta.bias_gyro_linearisation - kf20_bias_g).norm() < 1.0e-15);
3713        assert!((f1.delta.bias_acc_linearisation - kf20_bias_a).norm() < 1.0e-15);
3714    }
3715
3716    #[test]
3717    fn relinearise_threshold_skips_factors_within_drift() {
3718        // With a generous threshold (`(1.0, 10.0)`) no factor's bias drift
3719        // exceeds it. The counter stays at zero and the linearisation
3720        // point is unchanged.
3721        let mut map = build_three_keyframe_map();
3722        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3723            gravity_world: Vector3::zeros(),
3724            relinearise_imu_factor_bias_thresholds: Some((1.0, 10.0)),
3725            ..OnlineSlamLocalBaConfig::default()
3726        });
3727        for kf_id in [10u64, 20, 30] {
3728            state.keyframe_state.insert(
3729                kf_id,
3730                KeyframeImuState {
3731                    velocity_world: Vector3::zeros(),
3732                    bias_gyro: Vector3::new(0.05, -0.03, 0.02),
3733                    bias_acc: Vector3::new(0.2, -0.15, 0.10),
3734                },
3735            );
3736        }
3737        state
3738            .factor_history
3739            .push(constant_velocity_factor(10, 20, 0.1));
3740        state
3741            .factor_history
3742            .push(constant_velocity_factor(20, 30, 0.1));
3743        let result = run_local_vi_ba(&mut map, &mut state).expect("BA should run");
3744        assert_eq!(result.relinearised_factor_count, 0);
3745        for factor in &state.factor_history {
3746            assert_eq!(factor.delta.bias_gyro_linearisation, Vector3::zeros());
3747            assert_eq!(factor.delta.bias_acc_linearisation, Vector3::zeros());
3748        }
3749    }
3750
3751    #[test]
3752    fn local_vi_ba_state_reset_clears_history() {
3753        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig::default());
3754        let triggered = state.register_new_factor(constant_velocity_factor(10, 20, 0.1));
3755        assert!(triggered);
3756        assert_eq!(state.factor_history.len(), 1);
3757        state.reset();
3758        assert!(state.factor_history.is_empty());
3759        assert!(state.keyframe_state.is_empty());
3760        assert_eq!(state.pending_factors_since_last_trigger, 0);
3761    }
3762
3763    #[test]
3764    fn register_new_factor_respects_trigger_every() {
3765        let mut state = OnlineSlamLocalBaState::new(OnlineSlamLocalBaConfig {
3766            trigger_every: 3,
3767            ..OnlineSlamLocalBaConfig::default()
3768        });
3769        assert!(!state.register_new_factor(constant_velocity_factor(10, 20, 0.1)));
3770        assert!(!state.register_new_factor(constant_velocity_factor(20, 30, 0.1)));
3771        assert!(state.register_new_factor(constant_velocity_factor(30, 40, 0.1)));
3772        // Counter not yet reset (caller does that via run_local_vi_ba).
3773        assert_eq!(state.pending_factors_since_last_trigger, 3);
3774        // Simulate the caller running the BA (no map / so it returns None
3775        // but resets the counter as a side effect of being invoked).
3776        state.pending_factors_since_last_trigger = 0;
3777        assert!(!state.register_new_factor(constant_velocity_factor(40, 50, 0.1)));
3778    }
3779
3780    // ============================================================
3781    // VIBA2 (inertial-with-scale) unit tests.
3782    // ============================================================
3783
3784    /// Build a synthetic constant-velocity trajectory + IMU factors. The
3785    /// metric ground truth places the body at `x = i * step_metric` for
3786    /// `i = 0..num_keyframes`, with constant velocity `step_metric / dt`
3787    /// along `+x` and identity orientation. Returns the map (poses at
3788    /// `metric_step * scale_factor` to simulate the visual-up-to-scale
3789    /// frame), the factors (metric, NOT rescaled), and the ground-truth
3790    /// scale that maps `visual → metric`.
3791    fn build_monocular_constant_velocity(
3792        num_keyframes: usize,
3793        step_metric: f64,
3794        dt: f64,
3795        scale_factor: f64,
3796    ) -> (VisualMap, Vec<ImuPreintegrationFactor>, f64) {
3797        let mut map = VisualMap::new();
3798        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
3799        map.cameras.insert(camera.id, camera.clone());
3800        for i in 0..num_keyframes {
3801            // Visual-frame position: `x = (i * step_metric) / scale_factor`.
3802            // That way `metric_position = scale_factor * visual_position`.
3803            let visual_x = (i as f64) * step_metric / scale_factor;
3804            let center = Vector3::new(visual_x, 0.0, 0.0);
3805            let pose = Pose::from_world_to_camera(UnitQuaternion::identity(), -center);
3806            let frame_id = (i as u64) + 1;
3807            let mut frame = Frame::new(frame_id, camera.id);
3808            frame.pose = Some(pose);
3809            let kf = Keyframe {
3810                frame,
3811                observations: Vec::new(),
3812            };
3813            map.keyframes.insert(frame_id, kf);
3814        }
3815        // IMU factors: identity-oriented body, zero gravity, constant
3816        // velocity along +x of `step_metric / dt` m/s, so
3817        // Δp = R^T · (p_j - p_i - v_i·Δt - 0) = (step_metric - step_metric) = 0,
3818        // Δv = R^T · (v_j - v_i - 0) = 0. (The IMU sees no proper
3819        // acceleration in zero-gravity constant-velocity flight.)
3820        let mut factors = Vec::new();
3821        for i in 0..(num_keyframes - 1) {
3822            let delta = ImuPreintegratedDelta {
3823                delta_rotation: SO3::identity(),
3824                delta_velocity: Vector3::zeros(),
3825                delta_position: Vector3::zeros(),
3826                delta_time: dt,
3827                bias_gyro_linearisation: Vector3::zeros(),
3828                bias_acc_linearisation: Vector3::zeros(),
3829                j_rotation_bg: nalgebra::Matrix3::zeros(),
3830                j_velocity_ba: nalgebra::Matrix3::zeros(),
3831                j_velocity_bg: nalgebra::Matrix3::zeros(),
3832                j_position_ba: nalgebra::Matrix3::zeros(),
3833                j_position_bg: nalgebra::Matrix3::zeros(),
3834                covariance: crate::imu_preintegration::Matrix9::zeros(),
3835            };
3836            factors.push(ImuPreintegrationFactor {
3837                keyframe_id_from: (i as u64) + 1,
3838                keyframe_id_to: (i as u64) + 2,
3839                delta,
3840                gravity_world: Vector3::zeros(),
3841                weight_position: 1.0,
3842                weight_velocity: 1.0,
3843                weight_rotation: 1.0,
3844            });
3845        }
3846        (map, factors, scale_factor)
3847    }
3848
3849    #[test]
3850    fn viba2_with_recover_scale_false_reduces_to_viba1() {
3851        // Stereo / known-scale path: the wrapper must run a single inner
3852        // solve at `initial_scale = 1.0` and report `scale_history = [1.0]`.
3853        let (mut map, factors, _gt_scale) = build_monocular_constant_velocity(3, 0.5, 0.1, 1.0);
3854        let mut initial_states: BTreeMap<u64, KeyframeImuState> = BTreeMap::new();
3855        let v_metric_per_visual_unit = 0.5 / 0.1;
3856        for kf_id in [1u64, 2, 3] {
3857            initial_states.insert(
3858                kf_id,
3859                KeyframeImuState {
3860                    velocity_world: Vector3::new(v_metric_per_visual_unit, 0.0, 0.0),
3861                    bias_gyro: Vector3::zeros(),
3862                    bias_acc: Vector3::zeros(),
3863                },
3864            );
3865        }
3866        let result = run_viba2_inertial_with_scale(
3867            &mut map,
3868            &[1, 2, 3],
3869            &factors,
3870            &initial_states,
3871            &Viba2Config {
3872                initial_scale: 1.0,
3873                recover_scale: false,
3874                ..Viba2Config::default()
3875            },
3876        )
3877        .expect("inner solve must succeed");
3878        assert_eq!(result.outer_iterations_run, 1);
3879        assert_eq!(result.scale_history.len(), 1);
3880        assert!((result.scale - 1.0).abs() < 1e-12);
3881    }
3882
3883    #[test]
3884    fn viba2_unit_scale_synthetic_stream_recovers_near_one() {
3885        // Monocular ground truth scale = 1.0 (visual frame == metric).
3886        // Starting from `initial_scale = 1.0` the outer loop should keep
3887        // the scale near 1.0 across iterations.
3888        let (mut map, factors, _gt_scale) = build_monocular_constant_velocity(4, 0.5, 0.1, 1.0);
3889        let mut initial_states: BTreeMap<u64, KeyframeImuState> = BTreeMap::new();
3890        let v_visual_per_unit = 0.5 / 0.1;
3891        for kf_id in [1u64, 2, 3, 4] {
3892            initial_states.insert(
3893                kf_id,
3894                KeyframeImuState {
3895                    velocity_world: Vector3::new(v_visual_per_unit, 0.0, 0.0),
3896                    bias_gyro: Vector3::zeros(),
3897                    bias_acc: Vector3::zeros(),
3898                },
3899            );
3900        }
3901        let result = run_viba2_inertial_with_scale(
3902            &mut map,
3903            &[1, 2, 3, 4],
3904            &factors,
3905            &initial_states,
3906            &Viba2Config {
3907                initial_scale: 1.0,
3908                recover_scale: true,
3909                max_outer_iterations: 5,
3910                scale_tolerance: 1.0e-4,
3911                ..Viba2Config::default()
3912            },
3913        )
3914        .expect("inner solve must succeed");
3915        // Even with zero-gravity / zero-Δp factors the kinematic
3916        // denominator may degenerate, in which case the wrapper preserves
3917        // the initial scale and reports `outer_iterations_run = 1`. Both
3918        // outcomes are valid here — the assertion is the absence of
3919        // catastrophic scale drift.
3920        assert!(result.scale.is_finite());
3921        assert!(
3922            (result.scale - 1.0).abs() < 1.0,
3923            "scale must remain bounded near 1.0; got {}",
3924            result.scale
3925        );
3926    }
3927
3928    #[test]
3929    fn estimate_scale_from_factors_recovers_known_scale() {
3930        // Synthetic scene with a closed-form expected scale: build a
3931        // body in identity-orientation, +y-down gravity 9.81, moving from
3932        // origin to (1.0 metric, 0, 0) over Δt = 1.0 s with v_i = 0.
3933        // Then metric `p_j = (1.0, 0, 0)`, `Δp_metric = R^T · (1 - 0 - 0
3934        //  · 1 - 0.5 · g · 1²) = (1, -4.905, 0)`. With visual scale `s_gt`,
3935        // visual `p_j = (1/s_gt, 0, 0)`. The estimator's least-squares
3936        // recovers `s_gt`.
3937        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
3938        let mut map = VisualMap::new();
3939        map.cameras.insert(camera.id, camera.clone());
3940        let s_gt = 2.5;
3941        for (id, center) in [
3942            (1u64, Vector3::new(0.0, 0.0, 0.0)),
3943            (2u64, Vector3::new(1.0 / s_gt, 0.0, 0.0)),
3944        ] {
3945            let pose = Pose::from_world_to_camera(UnitQuaternion::identity(), -center);
3946            let mut frame = Frame::new(id, camera.id);
3947            frame.pose = Some(pose);
3948            map.keyframes.insert(
3949                id,
3950                Keyframe {
3951                    frame,
3952                    observations: Vec::new(),
3953                },
3954            );
3955        }
3956        let gravity = Vector3::new(0.0, 9.81, 0.0);
3957        // The metric Δp under v_i = 0, p_j = (1, 0, 0): Δp = (1, -4.905, 0).
3958        let delta = ImuPreintegratedDelta {
3959            delta_rotation: SO3::identity(),
3960            delta_velocity: -gravity,
3961            delta_position: Vector3::new(1.0, 0.0, 0.0) - 0.5 * gravity,
3962            delta_time: 1.0,
3963            bias_gyro_linearisation: Vector3::zeros(),
3964            bias_acc_linearisation: Vector3::zeros(),
3965            j_rotation_bg: nalgebra::Matrix3::zeros(),
3966            j_velocity_ba: nalgebra::Matrix3::zeros(),
3967            j_velocity_bg: nalgebra::Matrix3::zeros(),
3968            j_position_ba: nalgebra::Matrix3::zeros(),
3969            j_position_bg: nalgebra::Matrix3::zeros(),
3970            covariance: crate::imu_preintegration::Matrix9::zeros(),
3971        };
3972        let factor = ImuPreintegrationFactor {
3973            keyframe_id_from: 1,
3974            keyframe_id_to: 2,
3975            delta,
3976            gravity_world: gravity,
3977            weight_position: 1.0,
3978            weight_velocity: 1.0,
3979            weight_rotation: 1.0,
3980        };
3981        let mut states: BTreeMap<u64, KeyframeImuState> = BTreeMap::new();
3982        for id in [1u64, 2] {
3983            states.insert(
3984                id,
3985                KeyframeImuState {
3986                    velocity_world: Vector3::zeros(),
3987                    bias_gyro: Vector3::zeros(),
3988                    bias_acc: Vector3::zeros(),
3989                },
3990            );
3991        }
3992        let s_recovered =
3993            estimate_scale_from_factors(&map, &states, &[factor]).expect("denom not degenerate");
3994        // The closed-form least-squares minimises `‖s·a - b‖²` over both
3995        // x and y axes. With a = R · (p_j - 0 - 0) = (1/s_gt, 0, 0) and
3996        // b = Δp + R · 0.5 · g · dt² = (1, 0, 0), the LS gives:
3997        //   s = aᵀb / aᵀa = (1/s_gt · 1) / (1/s_gt)² = s_gt.
3998        assert!(
3999            (s_recovered - s_gt).abs() / s_gt < 0.05,
4000            "expected {} ± 5 %, got {}",
4001            s_gt,
4002            s_recovered
4003        );
4004    }
4005
4006    #[test]
4007    fn estimate_scale_returns_none_on_degenerate_kinematics() {
4008        // Coincident keyframes + zero velocity → `a = 0` for every
4009        // factor → denominator below tolerance → `None`.
4010        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
4011        let mut map = VisualMap::new();
4012        map.cameras.insert(camera.id, camera.clone());
4013        for id in [1u64, 2] {
4014            let pose = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
4015            let mut frame = Frame::new(id, camera.id);
4016            frame.pose = Some(pose);
4017            map.keyframes.insert(
4018                id,
4019                Keyframe {
4020                    frame,
4021                    observations: Vec::new(),
4022                },
4023            );
4024        }
4025        let delta = ImuPreintegratedDelta::identity();
4026        let factor = ImuPreintegrationFactor {
4027            keyframe_id_from: 1,
4028            keyframe_id_to: 2,
4029            delta: ImuPreintegratedDelta {
4030                delta_time: 1.0,
4031                ..delta
4032            },
4033            gravity_world: Vector3::zeros(),
4034            weight_position: 1.0,
4035            weight_velocity: 1.0,
4036            weight_rotation: 1.0,
4037        };
4038        let mut states: BTreeMap<u64, KeyframeImuState> = BTreeMap::new();
4039        for id in [1u64, 2] {
4040            states.insert(
4041                id,
4042                KeyframeImuState {
4043                    velocity_world: Vector3::zeros(),
4044                    bias_gyro: Vector3::zeros(),
4045                    bias_acc: Vector3::zeros(),
4046                },
4047            );
4048        }
4049        let outcome = estimate_scale_from_factors(&map, &states, &[factor]);
4050        assert!(outcome.is_none(), "expected None on degenerate kinematics");
4051    }
4052}