visloc_slam/online_slam_vi_init.rs
1//! Pipeline-side glue for the stationary-window VI initialiser.
2//!
3//! The standalone [`crate::VisualInertialInitializer`] is appearance-free
4//! and only knows how to ingest IMU samples. This module is the boundary
5//! between that initialiser and [`crate::OnlineSlamPipeline`]'s running
6//! IMU / local-VI-BA state: it ships the public config / event types the
7//! pipeline exposes to callers, and the private `OnlineSlamViInitState`
8//! that the pipeline owns and mutates atomically on a successful
9//! bootstrap. See [`docs/vi_initialization_integration.md`](../../../docs/vi_initialization_integration.md)
10//! for the design contract this implements (in particular the rotation-
11//! direction promotion and stale-factor-gate sections, which are
12//! load-bearing).
13
14use nalgebra::Vector3;
15use visloc_core::geometry::SE3;
16
17use crate::vi_initializer::{
18 StationaryRejectionReason, VisualInertialInitializationResult, VisualInertialInitializer,
19 VisualInertialInitializerConfig,
20};
21
22/// Behaviour when the pipeline's auto-bootstrap stage runs out of buffer
23/// space or wall-clock IMU duration without successfully recovering a
24/// stationary window.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum ViInitFallback {
27 /// Keep the caller-supplied [`crate::OnlineSlamImuConfig`] seeds as
28 /// the running bias / rotation. The pipeline never touches
29 /// `imu_state`; the staleness gate is lifted so subsequent IMU
30 /// factors flow with those original defaults.
31 KeepExistingSeed,
32 /// Disable the IMU stage entirely for the rest of the sequence by
33 /// dropping `imu_state` and `local_vi_ba_state` and clearing
34 /// `config.imu` / `config.local_vi_ba`.
35 DisableImuStage,
36}
37
38/// Optional auto-bootstrap stage that runs a
39/// [`crate::VisualInertialInitializer`] over the pipeline's incoming IMU
40/// stream and atomically promotes the recovered `(R_w←b, b_g, b_a)` into
41/// the running pre-integrator on the first keyframe.
42///
43/// Requires [`crate::OnlineSlamConfig::imu`] to be `Some(_)`. See
44/// [`docs/vi_initialization_integration.md`](../../../docs/vi_initialization_integration.md)
45/// for the full design contract, including the rotation-direction
46/// conversion and stale-factor-gate semantics.
47#[derive(Debug, Clone, PartialEq)]
48pub struct OnlineSlamViInitConfig {
49 /// Inner stationary-window initialiser config.
50 pub initializer: VisualInertialInitializerConfig,
51 /// Body-to-camera SE(3) extrinsic. When the IMU and camera share
52 /// orientation, pass [`SE3::identity()`].
53 pub body_to_camera: SE3,
54 /// Whether to overwrite the just-registered first keyframe's
55 /// `Pose.rotation` with `R_c←w = (R_w←b · R_b←c)^T` on success. The
56 /// camera centre is preserved (the stationary-window flavour cannot
57 /// observe absolute position).
58 pub seed_first_keyframe_rotation: bool,
59 /// Behaviour when [`Self::max_wait_duration_seconds`] or
60 /// [`Self::max_buffered_samples`] is reached without success.
61 pub on_persistent_rejection: ViInitFallback,
62 /// Semantic cap: stop trying once this much wall-clock IMU duration
63 /// has been buffered. `0.0` disables the duration cap.
64 pub max_wait_duration_seconds: f64,
65 /// Memory guard: refuse to buffer more than this many raw samples
66 /// regardless of duration. `0` disables the memory cap.
67 pub max_buffered_samples: usize,
68 /// When `true`, `OnlineSlamPipeline::run_vi_init_step` calls the inner
69 /// `try_initialize` on EVERY frame rather than only on frames that
70 /// registered a new keyframe. The default (`false`) preserves the
71 /// historical contract that "VI-init's recovered rotation attaches to
72 /// the just-registered first keyframe", which couples promotion to
73 /// the keyframe cadence. Setting `true` lets the stage promote as
74 /// soon as the IMU's stationary-window detector accepts; on success
75 /// without a new KF this frame, the promotion binds to the latest
76 /// existing keyframe (or no keyframe if the map is empty), and the
77 /// `seed_first_keyframe_rotation` rewrite is skipped when there is
78 /// no candidate keyframe. Phase-19 lever — lifts the structural gate
79 /// that made Phase-16's promotion-time BA trigger unreachable.
80 pub try_initialize_on_every_frame: bool,
81}
82
83impl Default for OnlineSlamViInitConfig {
84 fn default() -> Self {
85 Self {
86 initializer: VisualInertialInitializerConfig::default(),
87 body_to_camera: SE3::identity(),
88 seed_first_keyframe_rotation: true,
89 on_persistent_rejection: ViInitFallback::KeepExistingSeed,
90 max_wait_duration_seconds: 5.0,
91 max_buffered_samples: 2000,
92 try_initialize_on_every_frame: false,
93 }
94 }
95}
96
97/// Configuration-level error raised on [`crate::OnlineSlamPipeline::new`]
98/// (and exposed by [`crate::OnlineSlamConfig::validate`]) for invalid
99/// combinations the type system cannot rule out.
100#[derive(Debug, Clone, PartialEq)]
101pub enum OnlineSlamConfigError {
102 /// `vi_init: Some(_)` but `imu: None`. The VI init stage needs the
103 /// running IMU pre-integrator to promote its result into.
104 ViInitRequiresImu,
105 /// `vi_init.initializer.gravity_world != imu.gravity_world`. The two
106 /// fields are deliberately duplicated (the initialiser is also used
107 /// standalone) but they must agree at the pipeline boundary.
108 GravityMismatch {
109 imu_gravity_world: Vector3<f64>,
110 vi_init_gravity_world: Vector3<f64>,
111 },
112 /// `vi_motion_init: Some(_)` but `imu: None`. The motion-based stage
113 /// consumes IMU pre-integration factors emitted by the running
114 /// pipeline; without an IMU stage they are never produced.
115 MotionViInitRequiresImu,
116 /// `vi_motion_init: Some(_)` but `vi_init: None`. The motion-based stage
117 /// needs the static stage to select either its recovered bias seed or the
118 /// explicit terminal give-up fallback.
119 MotionViInitRequiresStaticViInit,
120 /// Post-static-give-up motion initialization was requested, but the static
121 /// fallback removes the IMU stage whose configured biases are required.
122 MotionViInitAfterGiveUpRequiresKeepExistingSeed,
123 /// `vi_motion_init.initializer.gravity_world != imu.gravity_world`.
124 /// As with the static stage these are intentionally duplicated
125 /// (the standalone module is also callable) but they must agree at
126 /// the pipeline boundary.
127 MotionGravityMismatch {
128 imu_gravity_world: Vector3<f64>,
129 motion_gravity_world: Vector3<f64>,
130 },
131 /// The stationary and motion-based stages were configured with different
132 /// camera-to-body extrinsics. The motion solver converts the fixed visual
133 /// camera trajectory into body poses, so both bootstrap stages must use
134 /// the same calibrated transform.
135 MotionExtrinsicMismatch,
136 /// Local VI-BA and VI initialization were configured with different
137 /// camera-to-body extrinsics, which would make the promoted inertial state
138 /// and the subsequent joint residuals refer to different body frames.
139 LocalViBaExtrinsicMismatch,
140 /// Local VI-BA random-walk information weights must both be finite and
141 /// strictly positive when configured.
142 InvalidLocalViBaBiasRandomWalkWeights,
143 /// Sparse keyframe factor lifecycle thresholds are internally invalid.
144 InvalidSparseFactorGraphConfig,
145}
146
147impl std::fmt::Display for OnlineSlamConfigError {
148 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149 match self {
150 Self::ViInitRequiresImu => write!(
151 f,
152 "OnlineSlamConfig.vi_init is Some(_) but OnlineSlamConfig.imu is None: \
153 the auto-bootstrap stage requires the running IMU pre-integrator"
154 ),
155 Self::GravityMismatch {
156 imu_gravity_world,
157 vi_init_gravity_world,
158 } => write!(
159 f,
160 "OnlineSlamConfig.imu.gravity_world ({imu_gravity_world:?}) and \
161 OnlineSlamConfig.vi_init.initializer.gravity_world \
162 ({vi_init_gravity_world:?}) must agree"
163 ),
164 Self::MotionViInitRequiresImu => write!(
165 f,
166 "OnlineSlamConfig.vi_motion_init is Some(_) but OnlineSlamConfig.imu \
167 is None: the motion-based stage consumes IMU pre-integration factors"
168 ),
169 Self::MotionViInitRequiresStaticViInit => write!(
170 f,
171 "OnlineSlamConfig.vi_motion_init is Some(_) but OnlineSlamConfig.vi_init \
172 is None: the motion-based stage refines the static seed produced by \
173 the static VI init stage"
174 ),
175 Self::MotionViInitAfterGiveUpRequiresKeepExistingSeed => write!(
176 f,
177 "motion VI init from configured biases requires \
178 OnlineSlamConfig.vi_init.on_persistent_rejection=KeepExistingSeed"
179 ),
180 Self::MotionGravityMismatch {
181 imu_gravity_world,
182 motion_gravity_world,
183 } => write!(
184 f,
185 "OnlineSlamConfig.imu.gravity_world ({imu_gravity_world:?}) and \
186 OnlineSlamConfig.vi_motion_init.initializer.gravity_world \
187 ({motion_gravity_world:?}) must agree"
188 ),
189 Self::MotionExtrinsicMismatch => write!(
190 f,
191 "OnlineSlamConfig.vi_init.body_to_camera and \
192 OnlineSlamConfig.vi_motion_init.initializer.body_to_camera must agree"
193 ),
194 Self::LocalViBaExtrinsicMismatch => write!(
195 f,
196 "OnlineSlamConfig.vi_init.body_to_camera and \
197 OnlineSlamConfig.local_vi_ba.body_to_camera must agree"
198 ),
199 Self::InvalidLocalViBaBiasRandomWalkWeights => write!(
200 f,
201 "OnlineSlamConfig.local_vi_ba.bias_random_walk_weights must contain \
202 finite, strictly positive gyro and accelerometer weights"
203 ),
204 Self::InvalidSparseFactorGraphConfig => write!(
205 f,
206 "OnlineSlamConfig.sparse_factor_graph contains invalid window, confidence, \
207 proximity, budget, age, or damping thresholds"
208 ),
209 }
210 }
211}
212
213impl std::error::Error for OnlineSlamConfigError {}
214
215/// Read-only snapshot of the pipeline's VI initialisation stage.
216/// Returned by [`crate::OnlineSlamPipeline::vi_initialization_status`].
217#[derive(Debug, Clone, PartialEq)]
218pub enum ViInitializationStatus {
219 /// IMU + VI init both disabled, or only IMU is enabled (the
220 /// pipeline never runs the auto-bootstrap when `vi_init: None`).
221 Disabled,
222 /// Buffering samples; `try_initialize` has not yet succeeded.
223 Buffering {
224 samples_buffered: usize,
225 buffered_duration_seconds: f64,
226 last_rejection: Option<StationaryRejectionReason>,
227 },
228 /// `try_initialize` succeeded; the carried result reflects what
229 /// was promoted into the pipeline's running state.
230 Initialised {
231 result: VisualInertialInitializationResult,
232 },
233 /// Cap exceeded; the configured fallback has already been applied.
234 GaveUp {
235 last_reason: StationaryRejectionReason,
236 fallback: ViInitFallback,
237 },
238}
239
240/// State-transition event exposed on [`crate::OnlineSlamResult::vi_init`].
241/// `Some` only on the frame where the auto-bootstrap stage actually
242/// transitioned state; `None` otherwise. The terminal events
243/// (`Succeeded` / `GaveUp`) are emitted at most once per sequence.
244#[derive(Debug, Clone, PartialEq)]
245pub enum ViInitializationEvent {
246 /// `try_initialize` succeeded this frame. The pipeline has atomically:
247 /// 1. Reset `imu_state.preintegrator` with the new bias linearisation.
248 /// 2. Mirrored `imu_state.config.{bias_gyro, bias_acc}` to the new values.
249 /// 3. Rewritten the just-registered keyframe's `Pose` if
250 /// `seed_first_keyframe_rotation` was true (rotation only; camera
251 /// centre preserved).
252 /// 4. Seeded `local_vi_ba_state.keyframe_state[first_keyframe_id]`
253 /// with `velocity_world = 0, bias = (b_g, b_a)`.
254 Succeeded {
255 result: VisualInertialInitializationResult,
256 first_keyframe_id: Option<u64>,
257 discarded_stale_factor_count: usize,
258 },
259 /// `try_initialize` was attempted this frame and rejected; the
260 /// buffer is preserved and the next attempt will run on the next
261 /// keyframe.
262 StillBuffering { reason: StationaryRejectionReason },
263 /// `max_wait_duration_seconds` or `max_buffered_samples` was reached
264 /// without success. The pipeline applied
265 /// [`OnlineSlamViInitConfig::on_persistent_rejection`].
266 GaveUp {
267 last_reason: StationaryRejectionReason,
268 fallback: ViInitFallback,
269 },
270}
271
272/// Private. Owned only by [`crate::OnlineSlamPipeline`] so the
273/// `completed` / `imu_state` / `map.keyframes` invariants cannot drift.
274#[derive(Debug, Clone, PartialEq)]
275pub(crate) struct OnlineSlamViInitState {
276 pub(crate) config: OnlineSlamViInitConfig,
277 pub(crate) initializer: VisualInertialInitializer,
278 pub(crate) completed: Option<VisualInertialInitializationResult>,
279 pub(crate) gave_up: Option<StationaryRejectionReason>,
280 pub(crate) last_rejection: Option<StationaryRejectionReason>,
281 pub(crate) samples_buffered: usize,
282 pub(crate) buffered_duration_seconds: f64,
283 /// IMU factors that would have been staged by
284 /// [`crate::OnlineSlamPipeline::stage_imu_factor_on_new_keyframe`]
285 /// while the stale-factor gate was active. Counted so the
286 /// `Succeeded` event can report the audit number; the underlying
287 /// factor data itself is dropped.
288 pub(crate) discarded_stale_factor_count: usize,
289}
290
291impl OnlineSlamViInitState {
292 pub(crate) fn new(config: OnlineSlamViInitConfig) -> Self {
293 let initializer = VisualInertialInitializer::new(config.initializer.clone());
294 Self {
295 config,
296 initializer,
297 completed: None,
298 gave_up: None,
299 last_rejection: None,
300 samples_buffered: 0,
301 buffered_duration_seconds: 0.0,
302 discarded_stale_factor_count: 0,
303 }
304 }
305
306 pub(crate) fn reset(&mut self) {
307 self.initializer.reset();
308 self.completed = None;
309 self.gave_up = None;
310 self.last_rejection = None;
311 self.samples_buffered = 0;
312 self.buffered_duration_seconds = 0.0;
313 self.discarded_stale_factor_count = 0;
314 }
315
316 /// `true` while the auto-bootstrap stage is still active — neither
317 /// `Succeeded` nor `GaveUp` has fired. Drives the stale-factor gate
318 /// (factors staged in this state are discarded rather than exposed).
319 pub(crate) const fn is_active(&self) -> bool {
320 self.completed.is_none() && self.gave_up.is_none()
321 }
322
323 pub(crate) fn snapshot(&self) -> ViInitializationStatus {
324 if let Some(result) = &self.completed {
325 ViInitializationStatus::Initialised {
326 result: result.clone(),
327 }
328 } else if let Some(reason) = &self.gave_up {
329 ViInitializationStatus::GaveUp {
330 last_reason: reason.clone(),
331 fallback: self.config.on_persistent_rejection,
332 }
333 } else {
334 ViInitializationStatus::Buffering {
335 samples_buffered: self.samples_buffered,
336 buffered_duration_seconds: self.buffered_duration_seconds,
337 last_rejection: self.last_rejection.clone(),
338 }
339 }
340 }
341
342 /// Returns `true` if either configured cap (duration / sample count)
343 /// has been exceeded. Caps of `0.0` / `0` disable the corresponding
344 /// check.
345 pub(crate) fn cap_exceeded(&self) -> bool {
346 let duration_cap = self.config.max_wait_duration_seconds;
347 let sample_cap = self.config.max_buffered_samples;
348 let duration_exceeded =
349 duration_cap > 0.0 && self.buffered_duration_seconds >= duration_cap;
350 let sample_exceeded = sample_cap > 0 && self.samples_buffered >= sample_cap;
351 duration_exceeded || sample_exceeded
352 }
353}
354
355#[cfg(test)]
356mod tests {
357 use super::*;
358
359 #[test]
360 fn default_try_initialize_on_every_frame_is_false() {
361 let cfg = OnlineSlamViInitConfig::default();
362 assert!(!cfg.try_initialize_on_every_frame);
363 }
364
365 #[test]
366 fn config_round_trips_try_initialize_on_every_frame_override() {
367 let cfg = OnlineSlamViInitConfig {
368 try_initialize_on_every_frame: true,
369 ..OnlineSlamViInitConfig::default()
370 };
371 assert!(cfg.try_initialize_on_every_frame);
372 }
373}