Skip to main content

visloc_tracking/
motion.rs

1//! Motion models (constant-pose/velocity, IMU-predictive, adaptive) and
2//! the visual-odometry frontend prior plumbing.
3
4use super::*;
5
6pub trait MotionModel {
7    fn predict_pose(
8        &self,
9        frame: &Frame,
10        last_result: Option<&TrackingResult>,
11        last_successful_pose: Option<&Pose>,
12    ) -> Option<Pose>;
13
14    fn observe(&mut self, _result: &TrackingResult) {}
15
16    fn reset(&mut self) {}
17
18    /// Whether this model's prediction is informative enough to seed the
19    /// PnP optimizer itself. Candidate selection and pose-quality gating may
20    /// still use every returned prior when this is `false`.
21    ///
22    /// A constant-pose prediction is deliberately excluded: on a moving
23    /// camera, injecting "no motion" into PnP creates a self-reinforcing
24    /// frozen-pose solution. Predictive velocity and IMU models retain the
25    /// historical warm-start behavior.
26    fn allows_pnp_pose_prior_warm_start(&self) -> bool {
27        true
28    }
29
30    /// Apply a rigid world-frame correction to any cached world-frame
31    /// state the model carries (velocities, cached poses). `correction`
32    /// maps OLD world-frame points/poses to NEW world-frame points/poses:
33    /// `p_new = correction.transform_point(&p_old)`. Called by
34    /// [`crate::Tracker::apply_pose_correction`] after an external
35    /// pose-graph optimisation (e.g. `visloc-slam`'s online loop-closure
36    /// refinement) rewrites keyframe poses, so the model's own state
37    /// stays consistent with the corrected map instead of predicting the
38    /// next prior from stale, pre-correction poses/velocities.
39    ///
40    /// Default no-op — correct for stateless models (e.g.
41    /// [`ConstantPoseMotionModel`]) that read `last_successful_pose`
42    /// fresh from the [`Tracker`] on every call and so
43    /// need no cache of their own to correct.
44    fn apply_pose_correction(&mut self, _correction: &SE3) {}
45
46    /// Apply a rigid-plus-scale (`Sim(3)`) world-frame correction —
47    /// [`apply_pose_correction`](Self::apply_pose_correction)'s
48    /// counterpart for a `Sim(3)` pose-graph solve (see `visloc-slam`'s
49    /// online loop-closure refinement `Sim3` solver, which corrects
50    /// monocular-style scale drift a rigid `SE(3)` graph cannot
51    /// represent). `correction` follows the same OLD-world -> NEW-world
52    /// convention as `apply_pose_correction`, generalised with a scale
53    /// factor: `p_new = correction.transform_point(&p_old)`.
54    ///
55    /// The default projects `correction` down to its rotation+translation
56    /// `SE(3)` part (dropping scale) and forwards to
57    /// [`apply_pose_correction`](Self::apply_pose_correction) — correct
58    /// for any cached poses, since
59    /// [`crate::Tracker::apply_similarity_pose_correction`] applies the
60    /// caller-visible `last_successful_pose` update itself. Models that
61    /// also cache a world-frame *velocity* (a vector, not a point —
62    /// translation does not apply, but the scale does: a Sim(3)
63    /// correction scales a vector by `s * R`) must override this to also
64    /// multiply that cached velocity by `correction.scale`.
65    fn apply_similarity_correction(&mut self, correction: &Sim3) {
66        let se3_part = SE3::new(correction.rotation, correction.translation);
67        self.apply_pose_correction(&se3_part);
68    }
69}
70
71pub trait VisualOdometryFrontend {
72    type Error;
73
74    fn estimate_relative_pose(
75        &self,
76        previous_frame: &Frame,
77        current_frame: &Frame,
78    ) -> Result<Option<VisualOdometryEstimate>, Self::Error>;
79}
80
81#[derive(Debug, Clone, PartialEq)]
82pub struct VisualOdometryEstimate {
83    pub previous_frame_id: FrameId,
84    pub current_frame_id: FrameId,
85    pub previous_to_current: SE3,
86    pub match_count: usize,
87    pub inlier_count: usize,
88    pub mean_reprojection_error: Option<f64>,
89}
90
91impl VisualOdometryEstimate {
92    pub const fn new(
93        previous_frame_id: FrameId,
94        current_frame_id: FrameId,
95        previous_to_current: SE3,
96    ) -> Self {
97        Self {
98            previous_frame_id,
99            current_frame_id,
100            previous_to_current,
101            match_count: 0,
102            inlier_count: 0,
103            mean_reprojection_error: None,
104        }
105    }
106
107    pub fn pose_prior_from_previous_pose(&self, previous_pose: &Pose) -> Pose {
108        Pose {
109            world_to_camera: self
110                .previous_to_current
111                .compose(&previous_pose.world_to_camera),
112        }
113    }
114}
115
116#[derive(Debug, Clone, PartialEq)]
117pub struct VisualOdometryPosePrior {
118    pub estimate: VisualOdometryEstimate,
119    pub pose: Pose,
120}
121
122#[derive(Debug, Clone, PartialEq)]
123pub struct VisualOdometryPriorProvider<F> {
124    frontend: F,
125}
126
127impl<F> VisualOdometryPriorProvider<F> {
128    pub const fn new(frontend: F) -> Self {
129        Self { frontend }
130    }
131
132    pub const fn frontend(&self) -> &F {
133        &self.frontend
134    }
135
136    pub const fn frontend_mut(&mut self) -> &mut F {
137        &mut self.frontend
138    }
139
140    pub fn into_inner(self) -> F {
141        self.frontend
142    }
143}
144
145impl<F> VisualOdometryPriorProvider<F>
146where
147    F: VisualOdometryFrontend,
148{
149    pub fn predict_pose_prior(
150        &self,
151        previous_frame: &Frame,
152        previous_pose: &Pose,
153        current_frame: &Frame,
154    ) -> Result<Option<VisualOdometryPosePrior>, F::Error> {
155        let Some(estimate) = self
156            .frontend
157            .estimate_relative_pose(previous_frame, current_frame)?
158        else {
159            return Ok(None);
160        };
161        let pose = estimate.pose_prior_from_previous_pose(previous_pose);
162        Ok(Some(VisualOdometryPosePrior { estimate, pose }))
163    }
164}
165
166#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
167pub struct NoopVisualOdometryFrontend;
168
169impl VisualOdometryFrontend for NoopVisualOdometryFrontend {
170    type Error = std::convert::Infallible;
171
172    fn estimate_relative_pose(
173        &self,
174        _previous_frame: &Frame,
175        _current_frame: &Frame,
176    ) -> Result<Option<VisualOdometryEstimate>, Self::Error> {
177        Ok(None)
178    }
179}
180
181#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
182pub struct ConstantPoseMotionModel;
183
184impl MotionModel for ConstantPoseMotionModel {
185    fn predict_pose(
186        &self,
187        _frame: &Frame,
188        _last_result: Option<&TrackingResult>,
189        last_successful_pose: Option<&Pose>,
190    ) -> Option<Pose> {
191        last_successful_pose.cloned()
192    }
193
194    fn allows_pnp_pose_prior_warm_start(&self) -> bool {
195        false
196    }
197}
198
199/// Inertial pose predictor: a "loosely coupled" replacement for
200/// [`ConstantPoseMotionModel`] / [`ConstantVelocityMotionModel`] that
201/// integrates body-frame IMU samples forward from the previous
202/// successful pose to produce the next pose prior. Mirrors the inputs of
203/// [`crate::Tracker`]'s motion-model slot so it can be dropped in via
204/// `Tracker::new_with_motion_model`.
205///
206/// Lifecycle:
207///
208/// 1. The caller pushes inter-frame IMU samples via
209///    [`Self::push_imu_measurement`] (mutable, accumulates in
210///    `pending_samples`).
211/// 2. The tracker invokes [`MotionModel::predict_pose`] (read-only): the
212///    model forward-Eulers `(R_bw, v_w, p_bw)` from `last_successful_pose`
213///    using the pending samples + the configured gravity / biases + the
214///    current `velocity_world` and returns the predicted
215///    `world_to_camera` pose.
216/// 3. The tracker invokes [`MotionModel::observe`]: on success the
217///    pending samples are drained (the next inter-frame window starts
218///    fresh). The model itself does NOT re-estimate `velocity_world`
219///    from the tracker's output — that update is the caller's
220///    responsibility (e.g., from a downstream local VI-BA's refined
221///    velocity, or from a finite-difference of camera centres over the
222///    integrated window). Without an explicit update, the predictor
223///    re-uses the last set velocity, which is the same constant-velocity
224///    behaviour [`ConstantVelocityMotionModel`] gives.
225///
226/// Coordinate conventions match the IMU pre-integrator: gyro and accel
227/// are body-frame; gravity is in the world frame (KITTI y-down default:
228/// `(0, 9.81, 0)`); accel includes gravity such that a stationary IMU
229/// reads `R_wb^T · (−gravity_world)`.
230#[derive(Debug, Clone, PartialEq)]
231pub struct ImuPredictiveMotionModel {
232    /// Static configuration (gravity, biases). Update biases via
233    /// [`Self::set_biases`] when a downstream VI-BA refines them.
234    pub config: ImuPredictiveMotionModelConfig,
235    /// Buffered `(gyro, accel, dt)` tuples to integrate at the next
236    /// `predict_pose` call.
237    pending_samples: Vec<ImuPredictivePendingSample>,
238    /// World-frame velocity at the last successful pose. Used as the
239    /// initial velocity of the strapdown integration. The model does
240    /// NOT auto-update this on `observe`; downstream code (e.g., the
241    /// local VI-BA in `OnlineSlamPipeline`) should call
242    /// [`Self::set_velocity_world`] with the refined velocity after the
243    /// next BA pass.
244    velocity_world: nalgebra::Vector3<f64>,
245    /// `true` when at least one pending sample was integrated by the
246    /// most recent `predict_pose` call. Used by `observe` to decide
247    /// whether to drain the buffer (a `predict_pose` call without any
248    /// samples must NOT drain anything pushed *after* it).
249    last_predict_consumed_samples: bool,
250    /// Camera pose passed to the previous successful `observe`. Used by
251    /// the carry-forward path to re-anchor the integration before
252    /// committing the advanced `velocity_world`. Stays `None` until the
253    /// first successful frame; ignored entirely when
254    /// `config.carry_forward_velocity_world` is `false`.
255    last_successful_pose: Option<Pose>,
256}
257
258/// Static parameters for [`ImuPredictiveMotionModel`].
259#[derive(Debug, Clone, PartialEq)]
260pub struct ImuPredictiveMotionModelConfig {
261    /// World-frame gravity vector. KITTI y-down default `(0, 9.81, 0)`;
262    /// EuRoC z-up convention uses `(0, 0, -9.81)`.
263    pub gravity_world: nalgebra::Vector3<f64>,
264    /// Gyro bias subtracted from every sample before integration.
265    pub bias_gyro: nalgebra::Vector3<f64>,
266    /// Accel bias subtracted from every sample before integration.
267    pub bias_acc: nalgebra::Vector3<f64>,
268    /// `T_BS` body-from-sensor (= body-from-camera) rigid transform:
269    /// `p_body = body_to_sensor · p_sensor`. Used by `predict_pose` to
270    /// (a) convert the input camera pose to a body pose before
271    /// strapdown integration, and (b) convert the integrated body pose
272    /// back to a camera pose on the way out. Defaults to identity
273    /// (body == camera, the assumption the original wire-up made).
274    /// EuRoC's `cam0/sensor.yaml::T_BS` is exactly this transform: pass
275    /// the parsed [`SE3`] verbatim. The camera-relative offset is
276    /// ~0.1 m on EuRoC, so the identity default is a usable
277    /// approximation but a metric-tight prediction wants the real
278    /// extrinsic.
279    pub body_to_sensor: SE3,
280    /// When `true`, `observe` re-integrates the pending IMU
281    /// samples from the previously-tracked pose to advance
282    /// `velocity_world` for the next frame. Without this, the seed
283    /// velocity stays frozen at the last `set_velocity_world`
284    /// (i.e., last VI-BA mirror) until the next mirror fires — so on
285    /// frames between mirrors, the strapdown integration restarts from
286    /// the KF-time velocity rather than the velocity at the just-tracked
287    /// frame. Defaults to `false` for backwards compatibility.
288    pub carry_forward_velocity_world: bool,
289}
290
291impl Default for ImuPredictiveMotionModelConfig {
292    fn default() -> Self {
293        Self {
294            gravity_world: nalgebra::Vector3::new(0.0, 9.81, 0.0),
295            bias_gyro: nalgebra::Vector3::zeros(),
296            bias_acc: nalgebra::Vector3::zeros(),
297            body_to_sensor: SE3::identity(),
298            carry_forward_velocity_world: false,
299        }
300    }
301}
302
303#[derive(Debug, Clone, PartialEq)]
304struct ImuPredictivePendingSample {
305    gyro: nalgebra::Vector3<f64>,
306    accel: nalgebra::Vector3<f64>,
307    dt: f64,
308}
309
310impl ImuPredictiveMotionModel {
311    pub fn new(config: ImuPredictiveMotionModelConfig) -> Self {
312        Self {
313            config,
314            pending_samples: Vec::new(),
315            velocity_world: nalgebra::Vector3::zeros(),
316            last_predict_consumed_samples: false,
317            last_successful_pose: None,
318        }
319    }
320
321    /// Append one body-frame `(gyro, accel)` sample with the elapsed
322    /// time `dt` (seconds) since the previous sample. Non-positive
323    /// `dt` is silently dropped to keep raw IMU replays robust.
324    pub fn push_imu_measurement(
325        &mut self,
326        gyro: nalgebra::Vector3<f64>,
327        accel: nalgebra::Vector3<f64>,
328        dt: f64,
329    ) {
330        if dt <= 0.0 || dt.is_nan() {
331            return;
332        }
333        self.pending_samples
334            .push(ImuPredictivePendingSample { gyro, accel, dt });
335    }
336
337    /// Overwrite the world-frame velocity carried into the next
338    /// `predict_pose`. Call this after a downstream solver (e.g., the
339    /// `OnlineSlamPipeline` local VI-BA) refines the velocity at the
340    /// most recent keyframe.
341    pub const fn set_velocity_world(&mut self, velocity_world: nalgebra::Vector3<f64>) {
342        self.velocity_world = velocity_world;
343    }
344
345    /// Non-mutating finite-difference body-frame world-velocity from
346    /// two successive camera poses and the elapsed time between them.
347    /// Returns `None` when `dt_seconds` is not strictly positive/finite.
348    /// Callers that want to write the result into `velocity_world`
349    /// should use [`Self::update_velocity_from_camera_pose_difference`];
350    /// callers that need to combine multiple finite-differences (e.g.
351    /// the Phase-25 ThreePoseSmoother refresh policy averages two)
352    /// use this directly to avoid intermediate state writes.
353    pub fn body_velocity_from_camera_pose_difference(
354        &self,
355        prev: &Pose,
356        curr: &Pose,
357        dt_seconds: f64,
358    ) -> Option<nalgebra::Vector3<f64>> {
359        if dt_seconds <= 0.0 || !dt_seconds.is_finite() {
360            return None;
361        }
362        let body_prev = self
363            .config
364            .body_to_sensor
365            .compose(&prev.world_to_camera)
366            .inverse()
367            .translation;
368        let body_curr = self
369            .config
370            .body_to_sensor
371            .compose(&curr.world_to_camera)
372            .inverse()
373            .translation;
374        Some((body_curr - body_prev) / dt_seconds)
375    }
376
377    /// Update `velocity_world` to a finite-difference estimate from two
378    /// successive camera poses and the elapsed time between them.
379    /// Internally converts each camera pose to a body pose via
380    /// `body_to_sensor` so the velocity is the body's world-frame
381    /// velocity (the integrator's expected initial-velocity semantics),
382    /// not the camera's. Non-positive `dt_seconds` is silently dropped.
383    /// This is the recommended hook for callers that do not run a
384    /// downstream VI-BA (which would normally refine velocity) — without
385    /// it, `velocity_world` stays at the constructor default (zero) and
386    /// the position integration only picks up the quadratic accel term,
387    /// systematically under-predicting motion on a moving body.
388    pub fn update_velocity_from_camera_pose_difference(
389        &mut self,
390        prev: &Pose,
391        curr: &Pose,
392        dt_seconds: f64,
393    ) {
394        if let Some(v) = self.body_velocity_from_camera_pose_difference(prev, curr, dt_seconds) {
395            self.velocity_world = v;
396        }
397    }
398
399    /// Overwrite the gyro / accel bias linearisation points.
400    pub const fn set_biases(
401        &mut self,
402        bias_gyro: nalgebra::Vector3<f64>,
403        bias_acc: nalgebra::Vector3<f64>,
404    ) {
405        self.config.bias_gyro = bias_gyro;
406        self.config.bias_acc = bias_acc;
407    }
408
409    /// Read-only access to the current pending-sample count, mostly for
410    /// tests / diagnostics.
411    pub fn pending_samples_len(&self) -> usize {
412        self.pending_samples.len()
413    }
414
415    /// Sum of `dt` over all currently-pending IMU samples. Useful for
416    /// callers (e.g. [`AdaptiveImuPoseMotionModel`]) that need to know
417    /// the elapsed wall-clock time between the previous successful
418    /// `observe()` (which drained the buffer) and the moment this is
419    /// queried — typically immediately before the next `observe()`
420    /// drain. Returns `0.0` when no samples are pending.
421    pub fn pending_samples_total_dt(&self) -> f64 {
422        self.pending_samples.iter().map(|s| s.dt).sum()
423    }
424
425    /// Read-only access to the current world-frame velocity.
426    pub const fn velocity_world(&self) -> nalgebra::Vector3<f64> {
427        self.velocity_world
428    }
429}
430
431impl MotionModel for ImuPredictiveMotionModel {
432    fn predict_pose(
433        &self,
434        _frame: &Frame,
435        _last_result: Option<&TrackingResult>,
436        last_successful_pose: Option<&Pose>,
437    ) -> Option<Pose> {
438        let prev = last_successful_pose?;
439        if self.pending_samples.is_empty() {
440            return Some(prev.clone());
441        }
442        // Convert the input camera pose `T_cw = prev.world_to_camera` to
443        // a body pose `T_bw = T_bs · T_cw` (body-from-world). Then take
444        // its inverse to get `T_wb`, whose rotation is the body-to-world
445        // orientation `R_wb` (transforms body-frame vectors to world)
446        // and whose translation is the body centre in world `p_wb`.
447        // With `body_to_sensor = identity` this reduces to the original
448        // `r_bw = R_wc, p_bw = camera_center_world` extraction.
449        let t_bw_initial = self.config.body_to_sensor.compose(&prev.world_to_camera);
450        let t_wb_initial = t_bw_initial.inverse();
451        let mut r_wb = t_wb_initial.rotation;
452        let mut p_wb = t_wb_initial.translation;
453        let mut v_w = self.velocity_world;
454        for sample in &self.pending_samples {
455            let gyro_unbiased = sample.gyro - self.config.bias_gyro;
456            let accel_unbiased = sample.accel - self.config.bias_acc;
457            let accel_world = r_wb.transform_vector(&accel_unbiased) + self.config.gravity_world;
458            // Forward-Euler strapdown step. Position uses the velocity at
459            // step start (mid-point integration would be more accurate but
460            // matches the post-IMU-factor pre-integration semantics: tiny
461            // `dt`s amortise the second-order error).
462            p_wb += v_w * sample.dt + 0.5 * accel_world * sample.dt * sample.dt;
463            v_w += accel_world * sample.dt;
464            r_wb *= UnitQuaternion::from_scaled_axis(gyro_unbiased * sample.dt);
465        }
466        // Build the new body-in-world pose, invert to body-from-world,
467        // and compose with `T_cb = body_to_sensor⁻¹` to recover the new
468        // camera-from-world pose: `T_cw_new = T_cb · T_bw_new`.
469        let t_wb_new = SE3::new(r_wb, p_wb);
470        let t_bw_new = t_wb_new.inverse();
471        let t_cw_new = self.config.body_to_sensor.inverse().compose(&t_bw_new);
472        Some(Pose {
473            world_to_camera: t_cw_new,
474        })
475    }
476
477    fn observe(&mut self, result: &TrackingResult) {
478        if !result.localization.success {
479            return;
480        }
481        // Carry-forward path: when enabled and a previous successful
482        // pose exists, re-run the same strapdown integration that
483        // `predict_pose` performed (using the *previous* pose as anchor)
484        // and commit the post-integration `v_w` as the new initial
485        // velocity for the next `predict_pose` call. Without this, the
486        // seed velocity stays frozen at the last `set_velocity_world`
487        // (i.e. last VI-BA mirror) for every frame in the KF window,
488        // so per-frame predictions silently restart from the KF-time
489        // velocity instead of the velocity at the just-tracked frame.
490        if self.config.carry_forward_velocity_world {
491            if let Some(prev) = self.last_successful_pose.as_ref() {
492                let t_bw_initial = self.config.body_to_sensor.compose(&prev.world_to_camera);
493                let t_wb_initial = t_bw_initial.inverse();
494                let mut r_wb = t_wb_initial.rotation;
495                let mut v_w = self.velocity_world;
496                for sample in &self.pending_samples {
497                    let gyro_unbiased = sample.gyro - self.config.bias_gyro;
498                    let accel_unbiased = sample.accel - self.config.bias_acc;
499                    let accel_world =
500                        r_wb.transform_vector(&accel_unbiased) + self.config.gravity_world;
501                    v_w += accel_world * sample.dt;
502                    r_wb *= UnitQuaternion::from_scaled_axis(gyro_unbiased * sample.dt);
503                }
504                self.velocity_world = v_w;
505            }
506            if let Some(pose) = result.localization.pose.as_ref() {
507                self.last_successful_pose = Some(pose.clone());
508            }
509        }
510        // Drain the pending window after a successful frame so the next
511        // inter-frame integration starts fresh.
512        self.pending_samples.clear();
513        self.last_predict_consumed_samples = false;
514    }
515
516    fn reset(&mut self) {
517        self.pending_samples.clear();
518        self.velocity_world = nalgebra::Vector3::zeros();
519        self.last_predict_consumed_samples = false;
520        self.last_successful_pose = None;
521    }
522
523    fn apply_pose_correction(&mut self, correction: &SE3) {
524        // `velocity_world` is a world-frame vector (a difference of
525        // positions), so only the rotation component of a rigid world
526        // correction applies — the translation term cancels.
527        self.velocity_world = correction.rotation.transform_vector(&self.velocity_world);
528        if let Some(pose) = self.last_successful_pose.as_mut() {
529            pose.world_to_camera = pose.world_to_camera.compose(&correction.inverse());
530        }
531    }
532
533    fn apply_similarity_correction(&mut self, correction: &Sim3) {
534        let se3_part = SE3::new(correction.rotation, correction.translation);
535        self.apply_pose_correction(&se3_part);
536        // `velocity_world` is a vector, so the Sim(3) correction acts on
537        // it as `s * R * v` (translation does not apply to a vector) —
538        // the rotation was already applied by `apply_pose_correction`
539        // above, so only the extra scale factor is left to fold in.
540        self.velocity_world *= correction.scale;
541    }
542}
543
544#[derive(Debug, Clone, Default, PartialEq)]
545pub struct ConstantVelocityMotionModel {
546    previous_successful_pose: Option<Pose>,
547    latest_successful_pose: Option<Pose>,
548}
549
550impl ConstantVelocityMotionModel {
551    pub fn new() -> Self {
552        Self::default()
553    }
554}
555
556impl MotionModel for ConstantVelocityMotionModel {
557    fn predict_pose(
558        &self,
559        _frame: &Frame,
560        _last_result: Option<&TrackingResult>,
561        last_successful_pose: Option<&Pose>,
562    ) -> Option<Pose> {
563        let (Some(previous), Some(latest)) = (
564            self.previous_successful_pose.as_ref(),
565            self.latest_successful_pose.as_ref(),
566        ) else {
567            return last_successful_pose.cloned();
568        };
569
570        let previous_center = previous.camera_center_world();
571        let latest_center = latest.camera_center_world();
572        let predicted_center = latest_center + (latest_center - previous_center);
573        let rotation = latest.world_to_camera.rotation;
574        let translation = -(rotation.transform_vector(&predicted_center.coords));
575        Some(Pose::from_world_to_camera(rotation, translation))
576    }
577
578    fn observe(&mut self, result: &TrackingResult) {
579        if !result.localization.success {
580            return;
581        }
582        let Some(pose) = result.localization.pose.as_ref() else {
583            return;
584        };
585        self.previous_successful_pose = self.latest_successful_pose.take();
586        self.latest_successful_pose = Some(pose.clone());
587    }
588
589    fn reset(&mut self) {
590        self.previous_successful_pose = None;
591        self.latest_successful_pose = None;
592    }
593
594    fn apply_pose_correction(&mut self, correction: &SE3) {
595        let inverse = correction.inverse();
596        if let Some(pose) = self.previous_successful_pose.as_mut() {
597            pose.world_to_camera = pose.world_to_camera.compose(&inverse);
598        }
599        if let Some(pose) = self.latest_successful_pose.as_mut() {
600            pose.world_to_camera = pose.world_to_camera.compose(&inverse);
601        }
602    }
603}
604
605/// Configuration for the adaptive IMU↔ConstantPose motion model
606/// ([`AdaptiveImuPoseMotionModel`]).
607///
608/// The Phase-23 EuRoC sweep
609/// (`docs/motion_based_vi_alignment.md` §Phase-23 #2 follow-up)
610/// established a clean accuracy↔survival trade-off:
611///
612/// - `--motion-model imu` produces tight pre-cliff trajectories
613///   (V2_01 rigid ATE `0.0021 m`, similarity scale `1.000044`) but
614///   the IMU's predictive aggressiveness triggers the
615///   `--max-pose-jump-meters` gate at the universal cliff.
616/// - `--motion-model pose` survives 25-313 % longer (MH_01 7 → 29
617///   keyframes) but degrades rigid ATE 4-100× and collapses the
618///   similarity scale.
619///
620/// The adaptive model defaults to IMU mode for accuracy and
621/// transparently falls back to constant-pose after enough consecutive
622/// tracking failures, then switches back to IMU once the tracker has
623/// recovered. The intent is to keep IMU's tight predictions on the
624/// healthy regime while the pose model carries the tracker through
625/// the cliff transition.
626/// How the [`AdaptiveImuPoseMotionModel`] refreshes the wrapped IMU
627/// model's `velocity_world` at every Pose → IMU mode switch.
628///
629/// The motivation comes from the Phase-23 #4 oscillation: while the
630/// adaptive wrapper sits in Pose mode, the IMU keeps absorbing raw
631/// samples but never sees a successful visual `observe`, so its seed
632/// `velocity_world` rapidly drifts away from the true body motion. The
633/// first IMU prediction after the switch-back then mispredicts and
634/// fires another failure — the wrapper oscillates Pose↔IMU.
635///
636/// The Phase-24 hook introduced [`Self::FiniteDifference`] to address
637/// that. Phase-25 added [`Self::ZeroReset`] and
638/// [`Self::ThreePoseSmoother`] as A/B alternatives after the
639/// finite-difference variant produced only V1_01 wins (MH_01 / V2_01
640/// were neutral-to-worse).
641#[derive(Debug, Clone, Copy, PartialEq, Eq)]
642pub enum ImuVelocityRefreshPolicy {
643    /// Phase-23 #4 behavior. Leave the IMU's `velocity_world`
644    /// unchanged at every switch-back. The IMU continues integrating
645    /// from whatever seed velocity it last computed; pose-mode-induced
646    /// staleness is unmitigated.
647    None,
648    /// Phase-24 behavior (the post-refactor default). Recompute
649    /// `velocity_world` from a finite-difference of the two most
650    /// recent successful visual poses, divided by the IMU's
651    /// pending-sample dt sum captured at the moment of the latest
652    /// successful `observe`. Cheapest non-trivial reset; injects PnP
653    /// noise from both poses into the velocity estimate.
654    FiniteDifference,
655    /// Phase-25 #1 (zero-reset) variant. Overwrite `velocity_world`
656    /// with the zero vector at every switch-back. Cheapest possible
657    /// reset; useful as a control when the cliff-region pose-mode
658    /// poses are themselves PnP-noise-dominated (in which case any
659    /// non-zero finite-difference seed is worse than zero).
660    ZeroReset,
661    /// Phase-25 #2 (smoothed finite-difference) variant. Computes two
662    /// finite-difference velocities across the three most recent
663    /// successful visual poses (oldest→previous and
664    /// previous→latest) and averages them, then writes the result
665    /// into `velocity_world`. Falls back to single
666    /// finite-difference behavior when fewer than three poses are
667    /// available. Aims to halve the PnP-noise variance compared with
668    /// [`Self::FiniteDifference`].
669    ThreePoseSmoother,
670}
671
672impl Default for ImuVelocityRefreshPolicy {
673    /// Phase-25 default: three-pose smoothed finite-difference reset
674    /// on switch. Empirically (Phase-25 EuRoC sweep, see
675    /// `target/euroc_phase25_refresh_policy_ab/SUMMARY.md`) strictly
676    /// improves on or matches [`Self::FiniteDifference`] on every
677    /// 3-seq × 2-threshold case tested: identical at f=3/s=10 where
678    /// the hook never fires or its result is washed out, and -25 %
679    /// V2_01 / -1 % MH_01 / identical V1_01 rigid ATE at f=2/s=5
680    /// compared with Phase-24's FiniteDifference default.
681    fn default() -> Self {
682        Self::ThreePoseSmoother
683    }
684}
685
686#[derive(Debug, Clone, PartialEq)]
687pub struct AdaptiveImuPoseMotionModelConfig {
688    /// Number of consecutive failed-tracking frames (under IMU mode)
689    /// that triggers a switch to constant-pose mode. Lower values
690    /// react faster but oscillate more on noisy regimes.
691    pub failures_to_switch_to_pose: usize,
692    /// Number of consecutive successful-tracking frames (under
693    /// constant-pose mode) that triggers a switch back to IMU mode.
694    /// Higher values bias toward stability — the model stays in pose
695    /// mode longer before re-trusting the IMU prediction.
696    pub successes_to_switch_to_imu: usize,
697    /// Policy for refreshing the wrapped IMU model's `velocity_world`
698    /// at every Pose → IMU switch-back. See
699    /// [`ImuVelocityRefreshPolicy`] for the semantics of each variant
700    /// and the motivation behind the Phase-24 / Phase-25 thread.
701    pub imu_velocity_refresh_policy: ImuVelocityRefreshPolicy,
702}
703
704impl Default for AdaptiveImuPoseMotionModelConfig {
705    fn default() -> Self {
706        Self {
707            failures_to_switch_to_pose: 2,
708            successes_to_switch_to_imu: 5,
709            imu_velocity_refresh_policy: ImuVelocityRefreshPolicy::default(),
710        }
711    }
712}
713
714/// Diagnostic snapshot of which inner motion model the adaptive
715/// wrapper is currently dispatching predictions through.
716#[derive(Debug, Clone, Copy, PartialEq, Eq)]
717pub enum AdaptiveMotionMode {
718    Imu,
719    Pose,
720}
721
722/// Adaptive motion model that wraps an [`ImuPredictiveMotionModel`]
723/// and a [`ConstantPoseMotionModel`] and dispatches `predict_pose`
724/// through whichever inner model the per-frame
725/// failure / success counters select. Both inner models are kept
726/// fed at all times by [`Self::observe`] so the switch is
727/// instantaneous when it fires (the IMU's pending-sample buffer and
728/// last-successful-pose anchor stay current even while
729/// constant-pose is dispatching predictions).
730///
731/// The IMU sample stream is forwarded into the inner IMU model via
732/// the public [`Self::imu_mut`] accessor — the [`MotionModel`] trait
733/// itself does not expose a sample-feeding entry point, so callers
734/// who construct an `AdaptiveImuPoseMotionModel` and want the IMU
735/// integration to stay current must push samples directly into the
736/// wrapped model.
737#[derive(Debug, Clone)]
738pub struct AdaptiveImuPoseMotionModel {
739    imu: ImuPredictiveMotionModel,
740    pose: ConstantPoseMotionModel,
741    config: AdaptiveImuPoseMotionModelConfig,
742    mode: AdaptiveMotionMode,
743    consecutive_failures_under_imu: usize,
744    consecutive_successes_under_pose: usize,
745    switches_to_pose: u64,
746    switches_to_imu: u64,
747    /// Pose from the third-most-recent successful `observe()`. Used
748    /// only by the
749    /// [`ImuVelocityRefreshPolicy::ThreePoseSmoother`] policy to form
750    /// a second finite-difference velocity that gets averaged with the
751    /// most recent finite-difference. `None` until at least three
752    /// successful observations have occurred since construction or the
753    /// last [`Self::reset`].
754    oldest_successful_pose: Option<Pose>,
755    /// Pose from the second-most-recent successful `observe()`. Paired
756    /// with [`Self::latest_successful_pose`] +
757    /// [`Self::dt_between_latest_two_observations`] to recompute the
758    /// IMU `velocity_world` from a visual finite-difference at every
759    /// Pose → IMU switch event under
760    /// [`ImuVelocityRefreshPolicy::FiniteDifference`] /
761    /// [`ImuVelocityRefreshPolicy::ThreePoseSmoother`].
762    previous_successful_pose: Option<Pose>,
763    latest_successful_pose: Option<Pose>,
764    /// Wall-clock seconds elapsed between
765    /// [`Self::oldest_successful_pose`] and
766    /// [`Self::previous_successful_pose`]. Captured as the value of
767    /// [`Self::dt_between_latest_two_observations`] one shift ago.
768    /// Used only by [`ImuVelocityRefreshPolicy::ThreePoseSmoother`].
769    dt_between_previous_two_observations: f64,
770    /// Wall-clock seconds elapsed between
771    /// [`Self::previous_successful_pose`] and
772    /// [`Self::latest_successful_pose`], captured as the IMU's
773    /// `pending_samples_total_dt()` value at the moment of the
774    /// `latest_successful_pose`'s `observe()` call (i.e. before that
775    /// call drained the pending buffer).
776    dt_between_latest_two_observations: f64,
777    /// Cumulative number of `imu_velocity_refresh_policy` hooks that
778    /// actually fired (i.e. switches at which the configured policy
779    /// found enough state to write a new `velocity_world`). Smaller
780    /// than or equal to [`Self::switches_to_imu`]; useful for
781    /// telemetry on whether the refresh policy is engaging.
782    velocity_refreshes_on_switch_to_imu: u64,
783}
784
785impl AdaptiveImuPoseMotionModel {
786    pub const fn new(
787        imu: ImuPredictiveMotionModel,
788        pose: ConstantPoseMotionModel,
789        config: AdaptiveImuPoseMotionModelConfig,
790    ) -> Self {
791        Self {
792            imu,
793            pose,
794            config,
795            mode: AdaptiveMotionMode::Imu,
796            consecutive_failures_under_imu: 0,
797            consecutive_successes_under_pose: 0,
798            switches_to_pose: 0,
799            switches_to_imu: 0,
800            oldest_successful_pose: None,
801            previous_successful_pose: None,
802            latest_successful_pose: None,
803            dt_between_previous_two_observations: 0.0,
804            dt_between_latest_two_observations: 0.0,
805            velocity_refreshes_on_switch_to_imu: 0,
806        }
807    }
808
809    /// Construct an adaptive model with default-config inner models.
810    /// Convenience for callers that want a one-shot setup with the
811    /// default IMU gravity / biases / extrinsics.
812    pub fn with_defaults() -> Self {
813        Self::new(
814            ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default()),
815            ConstantPoseMotionModel,
816            AdaptiveImuPoseMotionModelConfig::default(),
817        )
818    }
819
820    pub const fn imu(&self) -> &ImuPredictiveMotionModel {
821        &self.imu
822    }
823
824    /// Mutable access to the wrapped IMU model. Callers use this to
825    /// forward raw IMU samples via
826    /// [`ImuPredictiveMotionModel::push_imu_measurement`] and to
827    /// mirror VI-BA-refined velocity / biases into the IMU state.
828    pub const fn imu_mut(&mut self) -> &mut ImuPredictiveMotionModel {
829        &mut self.imu
830    }
831
832    pub const fn config(&self) -> &AdaptiveImuPoseMotionModelConfig {
833        &self.config
834    }
835
836    pub const fn mode(&self) -> AdaptiveMotionMode {
837        self.mode
838    }
839
840    /// Cumulative number of times the wrapper has switched from
841    /// IMU → ConstantPose since construction (or last `reset`).
842    pub const fn switches_to_pose(&self) -> u64 {
843        self.switches_to_pose
844    }
845
846    /// Cumulative number of times the wrapper has switched from
847    /// ConstantPose → IMU since construction (or last `reset`).
848    pub const fn switches_to_imu(&self) -> u64 {
849        self.switches_to_imu
850    }
851
852    /// Cumulative number of times the Phase-24
853    /// refresh-IMU-velocity-on-switch-to-IMU hook has actually fired
854    /// (i.e. the wrapper switched back to IMU AND
855    /// `refresh_imu_velocity_on_switch_to_imu` was enabled AND both
856    /// previous + latest visual poses were available AND
857    /// `dt_between_latest_two_observations > 0`). Less than or equal
858    /// to [`Self::switches_to_imu`].
859    pub const fn velocity_refreshes_on_switch_to_imu(&self) -> u64 {
860        self.velocity_refreshes_on_switch_to_imu
861    }
862}
863
864impl MotionModel for AdaptiveImuPoseMotionModel {
865    fn predict_pose(
866        &self,
867        frame: &Frame,
868        last_result: Option<&TrackingResult>,
869        last_successful_pose: Option<&Pose>,
870    ) -> Option<Pose> {
871        match self.mode {
872            AdaptiveMotionMode::Imu => {
873                self.imu
874                    .predict_pose(frame, last_result, last_successful_pose)
875            }
876            AdaptiveMotionMode::Pose => {
877                self.pose
878                    .predict_pose(frame, last_result, last_successful_pose)
879            }
880        }
881    }
882
883    fn allows_pnp_pose_prior_warm_start(&self) -> bool {
884        self.mode == AdaptiveMotionMode::Imu
885    }
886
887    fn observe(&mut self, result: &TrackingResult) {
888        // Capture the IMU's pending-sample dt sum BEFORE forwarding to
889        // inner models — `imu.observe()` drains the pending buffer on
890        // success, so this is the only window in which we can read the
891        // wall-clock time elapsed since the previous successful
892        // `observe()`. Used by the Phase-24
893        // refresh-IMU-velocity-on-switch hook to compute a visual
894        // finite-difference velocity at the moment of a Pose → IMU
895        // switch.
896        let pending_dt_before_observe = self.imu.pending_samples_total_dt();
897        // Keep both inner models current regardless of which one is
898        // currently dispatching predictions — when the switch fires
899        // the previously-dormant model must have a coherent state.
900        self.imu.observe(result);
901        self.pose.observe(result);
902        if result.localization.success {
903            if let Some(pose) = result.localization.pose.as_ref() {
904                self.oldest_successful_pose = self.previous_successful_pose.take();
905                self.previous_successful_pose = self.latest_successful_pose.take();
906                self.latest_successful_pose = Some(pose.clone());
907                self.dt_between_previous_two_observations = self.dt_between_latest_two_observations;
908                self.dt_between_latest_two_observations = pending_dt_before_observe;
909            }
910            match self.mode {
911                AdaptiveMotionMode::Imu => {
912                    self.consecutive_failures_under_imu = 0;
913                }
914                AdaptiveMotionMode::Pose => {
915                    self.consecutive_successes_under_pose += 1;
916                    if self.consecutive_successes_under_pose
917                        >= self.config.successes_to_switch_to_imu
918                    {
919                        self.mode = AdaptiveMotionMode::Imu;
920                        self.switches_to_imu += 1;
921                        self.consecutive_failures_under_imu = 0;
922                        self.consecutive_successes_under_pose = 0;
923                        self.maybe_refresh_imu_velocity_on_switch_to_imu();
924                    }
925                }
926            }
927        } else {
928            match self.mode {
929                AdaptiveMotionMode::Imu => {
930                    self.consecutive_failures_under_imu += 1;
931                    if self.consecutive_failures_under_imu >= self.config.failures_to_switch_to_pose
932                    {
933                        self.mode = AdaptiveMotionMode::Pose;
934                        self.switches_to_pose += 1;
935                        self.consecutive_failures_under_imu = 0;
936                        self.consecutive_successes_under_pose = 0;
937                    }
938                }
939                AdaptiveMotionMode::Pose => {
940                    self.consecutive_successes_under_pose = 0;
941                }
942            }
943        }
944    }
945
946    fn reset(&mut self) {
947        self.imu.reset();
948        self.pose.reset();
949        self.mode = AdaptiveMotionMode::Imu;
950        self.consecutive_failures_under_imu = 0;
951        self.consecutive_successes_under_pose = 0;
952        self.switches_to_pose = 0;
953        self.switches_to_imu = 0;
954        self.oldest_successful_pose = None;
955        self.previous_successful_pose = None;
956        self.latest_successful_pose = None;
957        self.dt_between_previous_two_observations = 0.0;
958        self.dt_between_latest_two_observations = 0.0;
959        self.velocity_refreshes_on_switch_to_imu = 0;
960    }
961
962    fn apply_pose_correction(&mut self, correction: &SE3) {
963        self.imu.apply_pose_correction(correction);
964        self.pose.apply_pose_correction(correction);
965        let inverse = correction.inverse();
966        for pose in [
967            self.oldest_successful_pose.as_mut(),
968            self.previous_successful_pose.as_mut(),
969            self.latest_successful_pose.as_mut(),
970        ]
971        .into_iter()
972        .flatten()
973        {
974            pose.world_to_camera = pose.world_to_camera.compose(&inverse);
975        }
976    }
977
978    fn apply_similarity_correction(&mut self, correction: &Sim3) {
979        self.imu.apply_similarity_correction(correction);
980        self.pose.apply_similarity_correction(correction);
981        // The finite-difference smoother poses are rigid `Pose`s; fold
982        // in the rotation+translation part the same way
983        // `apply_pose_correction` does above (their velocity role is
984        // recomputed fresh from pose differences, so there is no cached
985        // velocity vector here to additionally scale).
986        let se3_part = SE3::new(correction.rotation, correction.translation);
987        let inverse = se3_part.inverse();
988        for pose in [
989            self.oldest_successful_pose.as_mut(),
990            self.previous_successful_pose.as_mut(),
991            self.latest_successful_pose.as_mut(),
992        ]
993        .into_iter()
994        .flatten()
995        {
996            pose.world_to_camera = pose.world_to_camera.compose(&inverse);
997        }
998    }
999}
1000
1001impl AdaptiveImuPoseMotionModel {
1002    /// Phase-24 / Phase-25 IMU-velocity-refresh hook. Called at the
1003    /// instant of every Pose → IMU mode transition from
1004    /// [`MotionModel::observe`]. Dispatches on
1005    /// [`AdaptiveImuPoseMotionModelConfig::imu_velocity_refresh_policy`]
1006    /// and increments [`Self::velocity_refreshes_on_switch_to_imu`]
1007    /// every time it actually writes a new `velocity_world` (so the
1008    /// counter is `0` under [`ImuVelocityRefreshPolicy::None`] and
1009    /// whenever the configured policy lacks enough state to compute a
1010    /// value). Silent no-op when the policy cannot fire — the IMU
1011    /// then continues with its current `velocity_world`.
1012    fn maybe_refresh_imu_velocity_on_switch_to_imu(&mut self) {
1013        match self.config.imu_velocity_refresh_policy {
1014            ImuVelocityRefreshPolicy::None => {}
1015            ImuVelocityRefreshPolicy::ZeroReset => {
1016                self.imu.set_velocity_world(nalgebra::Vector3::zeros());
1017                self.velocity_refreshes_on_switch_to_imu += 1;
1018            }
1019            ImuVelocityRefreshPolicy::FiniteDifference => {
1020                let (Some(prev), Some(curr)) = (
1021                    self.previous_successful_pose.as_ref(),
1022                    self.latest_successful_pose.as_ref(),
1023                ) else {
1024                    return;
1025                };
1026                let dt = self.dt_between_latest_two_observations;
1027                let Some(v) = self
1028                    .imu
1029                    .body_velocity_from_camera_pose_difference(prev, curr, dt)
1030                else {
1031                    return;
1032                };
1033                self.imu.set_velocity_world(v);
1034                self.velocity_refreshes_on_switch_to_imu += 1;
1035            }
1036            ImuVelocityRefreshPolicy::ThreePoseSmoother => {
1037                let (Some(prev), Some(curr)) = (
1038                    self.previous_successful_pose.as_ref(),
1039                    self.latest_successful_pose.as_ref(),
1040                ) else {
1041                    return;
1042                };
1043                let dt_latest = self.dt_between_latest_two_observations;
1044                let Some(v_latest) = self
1045                    .imu
1046                    .body_velocity_from_camera_pose_difference(prev, curr, dt_latest)
1047                else {
1048                    return;
1049                };
1050                // If the oldest pose + a valid older dt are available,
1051                // compute a second finite-difference and average. When
1052                // they're not (fewer than 3 successes), fall back to
1053                // single-finite-difference semantics so the policy
1054                // degrades gracefully into FiniteDifference rather
1055                // than no-op'ing.
1056                let v_write = match self.oldest_successful_pose.as_ref() {
1057                    Some(oldest) => self
1058                        .imu
1059                        .body_velocity_from_camera_pose_difference(
1060                            oldest,
1061                            prev,
1062                            self.dt_between_previous_two_observations,
1063                        )
1064                        .map_or(v_latest, |v_prev| (v_prev + v_latest) * 0.5),
1065                    None => v_latest,
1066                };
1067                self.imu.set_velocity_world(v_write);
1068                self.velocity_refreshes_on_switch_to_imu += 1;
1069            }
1070        }
1071    }
1072}
1073
1074#[cfg(test)]
1075mod imu_predictive_motion_tests {
1076    use super::*;
1077    use nalgebra::{UnitQuaternion, Vector3};
1078    use visloc_core::geometry::Pose;
1079    use visloc_core::types::Frame;
1080
1081    fn make_dummy_frame() -> Frame {
1082        Frame::new(1, 1)
1083    }
1084
1085    fn rotation_angle_deg(a: &Pose, b: &Pose) -> f64 {
1086        let q_a = a.world_to_camera.rotation;
1087        let q_b = b.world_to_camera.rotation;
1088        q_a.rotation_to(&q_b).angle().to_degrees()
1089    }
1090
1091    #[test]
1092    fn imu_predictive_motion_returns_last_pose_when_no_samples_pushed() {
1093        let model = ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default());
1094        let prev =
1095            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 5.0));
1096        let predicted = model
1097            .predict_pose(&make_dummy_frame(), None, Some(&prev))
1098            .expect("predicted pose");
1099        assert_eq!(
1100            predicted.world_to_camera.translation,
1101            prev.world_to_camera.translation
1102        );
1103        assert_eq!(
1104            predicted.world_to_camera.rotation,
1105            prev.world_to_camera.rotation
1106        );
1107    }
1108
1109    #[test]
1110    fn imu_predictive_motion_returns_none_when_no_previous_pose() {
1111        let mut model = ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default());
1112        model.push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
1113        assert!(model
1114            .predict_pose(&make_dummy_frame(), None, None)
1115            .is_none());
1116    }
1117
1118    #[test]
1119    fn imu_predictive_motion_stationary_under_gravity_holds_pose() {
1120        // Body stationary at world origin, gravity_world = (0, 0, -9.81)
1121        // (z-up). Accelerometer reads R_wb^T · (−g) = (0, 0, 9.81) when the
1122        // body is identity-oriented. With zero velocity / zero gyro, the
1123        // predicted pose must match the input exactly (no drift).
1124        let config = ImuPredictiveMotionModelConfig {
1125            gravity_world: Vector3::new(0.0, 0.0, -9.81),
1126            ..ImuPredictiveMotionModelConfig::default()
1127        };
1128        let mut model = ImuPredictiveMotionModel::new(config);
1129        for _ in 0..10 {
1130            model.push_imu_measurement(Vector3::zeros(), Vector3::new(0.0, 0.0, 9.81), 0.05);
1131        }
1132        let prev = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1133        let predicted = model
1134            .predict_pose(&make_dummy_frame(), None, Some(&prev))
1135            .expect("predicted");
1136        let predicted_center = predicted.camera_center_world();
1137        assert!(
1138            predicted_center.coords.norm() < 1.0e-9,
1139            "predicted center should stay at origin under stationary IMU, got {:?}",
1140            predicted_center
1141        );
1142        assert!(rotation_angle_deg(&predicted, &prev) < 1.0e-6);
1143    }
1144
1145    #[test]
1146    fn imu_predictive_motion_pure_yaw_rotation_propagates_rotation() {
1147        // Zero gravity scene, body rotates at π/2 rad/s around world-z for
1148        // 1.0 s. Accel reading is zero (free fall in zero gravity).
1149        // Predicted pose's rotation should be a +90° yaw of the input.
1150        let config = ImuPredictiveMotionModelConfig {
1151            gravity_world: Vector3::zeros(),
1152            ..ImuPredictiveMotionModelConfig::default()
1153        };
1154        let mut model = ImuPredictiveMotionModel::new(config);
1155        let yaw_rate = std::f64::consts::FRAC_PI_2;
1156        for _ in 0..100 {
1157            model.push_imu_measurement(Vector3::new(0.0, 0.0, yaw_rate), Vector3::zeros(), 0.01);
1158        }
1159        let prev = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1160        let predicted = model
1161            .predict_pose(&make_dummy_frame(), None, Some(&prev))
1162            .expect("predicted");
1163        // The body rotated +π/2 about world-z → R_bw is now a +90° rotation
1164        // about world-z → R_wc = R_bw⁻¹ is a -90° rotation about world-z.
1165        let expected_r_bw = UnitQuaternion::from_axis_angle(&Vector3::z_axis(), yaw_rate);
1166        let expected_r_wc = expected_r_bw.inverse();
1167        let actual_r_wc = predicted.world_to_camera.rotation;
1168        let angle_err = actual_r_wc.rotation_to(&expected_r_wc).angle().to_degrees();
1169        assert!(
1170            angle_err < 0.1,
1171            "yaw rotation drift too large: {angle_err} deg"
1172        );
1173    }
1174
1175    #[test]
1176    fn imu_predictive_motion_constant_velocity_translates_position() {
1177        // Zero gravity, zero gyro, zero accel, but `velocity_world = (1, 0, 0)`
1178        // and 1 s of pending samples. Predicted position must be the input
1179        // position + (1, 0, 0).
1180        let config = ImuPredictiveMotionModelConfig {
1181            gravity_world: Vector3::zeros(),
1182            ..ImuPredictiveMotionModelConfig::default()
1183        };
1184        let mut model = ImuPredictiveMotionModel::new(config);
1185        model.set_velocity_world(Vector3::new(1.0, 0.0, 0.0));
1186        for _ in 0..100 {
1187            model.push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.01);
1188        }
1189        let prev = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1190        let predicted = model
1191            .predict_pose(&make_dummy_frame(), None, Some(&prev))
1192            .expect("predicted");
1193        let center = predicted.camera_center_world();
1194        assert!(
1195            (center.x - 1.0).abs() < 1.0e-9,
1196            "predicted x should be 1.0 (start 0 + 1 m/s * 1 s), got {}",
1197            center.x
1198        );
1199        assert!(center.y.abs() < 1.0e-9);
1200        assert!(center.z.abs() < 1.0e-9);
1201    }
1202
1203    #[test]
1204    fn imu_predictive_motion_observe_drains_pending_window_on_success() {
1205        use visloc_core::types::LocalizationSuccess;
1206        let mut model = ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default());
1207        for _ in 0..3 {
1208            model.push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.05);
1209        }
1210        assert_eq!(model.pending_samples_len(), 3);
1211        let pose = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1212        let localization = LocalizationResult::success(LocalizationSuccess {
1213            pose,
1214            candidate_landmark_count: 4,
1215            match_count: 4,
1216            correspondence_count: 4,
1217            inliers: vec![0, 1, 2, 3],
1218            inlier_query_indices: vec![0, 1, 2, 3],
1219            inlier_landmark_ids: vec![1, 2, 3, 4],
1220            inlier_confidences: vec![None; 4],
1221            inlier_reprojection_errors: vec![0.0; 4],
1222            mean_reprojection_error: 0.0,
1223            median_reprojection_error: 0.0,
1224            max_reprojection_error: 0.0,
1225        });
1226        let success = TrackingResult {
1227            frame_id: 1,
1228            state: TrackingState::Tracking,
1229            event: TrackingEvent::Tracked,
1230            successive_failures: 0,
1231            pose_prior: None,
1232            used_pose_prior: false,
1233            used_external_localization_prior: false,
1234            external_localization_prior_radius: None,
1235            tracking_failure_reason: None,
1236            map_landmark_count: 0,
1237            map_stats: MapProviderStats::default(),
1238            localization,
1239            covisibility_local_map_size: None,
1240        };
1241        model.observe(&success);
1242        assert_eq!(model.pending_samples_len(), 0);
1243    }
1244
1245    #[test]
1246    fn imu_predictive_motion_reset_clears_velocity_and_samples() {
1247        let mut model = ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default());
1248        model.set_velocity_world(Vector3::new(3.0, 0.0, 0.0));
1249        model.push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.05);
1250        model.reset();
1251        assert_eq!(model.pending_samples_len(), 0);
1252        assert_eq!(model.velocity_world(), Vector3::zeros());
1253    }
1254
1255    #[test]
1256    fn imu_predictive_motion_carry_forward_default_off_leaves_velocity_frozen() {
1257        use visloc_core::types::LocalizationSuccess;
1258        // Default config: carry_forward_velocity_world = false. After
1259        // observe, velocity_world must equal the value set before push
1260        // (Phase-7 / pre-Phase-22 behaviour).
1261        let config = ImuPredictiveMotionModelConfig {
1262            gravity_world: Vector3::zeros(),
1263            ..ImuPredictiveMotionModelConfig::default()
1264        };
1265        let mut model = ImuPredictiveMotionModel::new(config);
1266        model.set_velocity_world(Vector3::new(1.0, 0.0, 0.0));
1267        for _ in 0..10 {
1268            model.push_imu_measurement(Vector3::zeros(), Vector3::new(2.0, 0.0, 0.0), 0.1);
1269        }
1270        let pose = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1271        let localization = LocalizationResult::success(LocalizationSuccess {
1272            pose,
1273            candidate_landmark_count: 4,
1274            match_count: 4,
1275            correspondence_count: 4,
1276            inliers: vec![0, 1, 2, 3],
1277            inlier_query_indices: vec![0, 1, 2, 3],
1278            inlier_landmark_ids: vec![1, 2, 3, 4],
1279            inlier_confidences: vec![None; 4],
1280            inlier_reprojection_errors: vec![0.0; 4],
1281            mean_reprojection_error: 0.0,
1282            median_reprojection_error: 0.0,
1283            max_reprojection_error: 0.0,
1284        });
1285        let result = TrackingResult {
1286            frame_id: 1,
1287            state: TrackingState::Tracking,
1288            event: TrackingEvent::Tracked,
1289            successive_failures: 0,
1290            pose_prior: None,
1291            used_pose_prior: false,
1292            used_external_localization_prior: false,
1293            external_localization_prior_radius: None,
1294            tracking_failure_reason: None,
1295            map_landmark_count: 0,
1296            map_stats: MapProviderStats::default(),
1297            localization,
1298            covisibility_local_map_size: None,
1299        };
1300        model.observe(&result);
1301        let v = model.velocity_world();
1302        assert!((v - Vector3::new(1.0, 0.0, 0.0)).norm() < 1.0e-12);
1303    }
1304
1305    #[test]
1306    fn imu_predictive_motion_carry_forward_on_advances_velocity_per_frame() {
1307        use visloc_core::types::LocalizationSuccess;
1308        // Zero gravity, identity body_to_sensor, accel (2,0,0) m/s² for
1309        // 1.0 s with initial v=(1,0,0). The body integrates to
1310        // v=(1+2*1.0,0,0)=(3,0,0). With carry-forward on, observe must
1311        // commit this back into velocity_world.
1312        let config = ImuPredictiveMotionModelConfig {
1313            gravity_world: Vector3::zeros(),
1314            carry_forward_velocity_world: true,
1315            ..ImuPredictiveMotionModelConfig::default()
1316        };
1317        let mut model = ImuPredictiveMotionModel::new(config);
1318        model.set_velocity_world(Vector3::new(1.0, 0.0, 0.0));
1319        // Seed last_successful_pose with the body-at-origin pose by
1320        // running an initial observe (no pending samples → integration
1321        // is a no-op; effect is to populate last_successful_pose).
1322        let pose_zero = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1323        let localization_zero = LocalizationResult::success(LocalizationSuccess {
1324            pose: pose_zero.clone(),
1325            candidate_landmark_count: 4,
1326            match_count: 4,
1327            correspondence_count: 4,
1328            inliers: vec![0, 1, 2, 3],
1329            inlier_query_indices: vec![0, 1, 2, 3],
1330            inlier_landmark_ids: vec![1, 2, 3, 4],
1331            inlier_confidences: vec![None; 4],
1332            inlier_reprojection_errors: vec![0.0; 4],
1333            mean_reprojection_error: 0.0,
1334            median_reprojection_error: 0.0,
1335            max_reprojection_error: 0.0,
1336        });
1337        let make_result = |pose: Pose| TrackingResult {
1338            frame_id: 1,
1339            state: TrackingState::Tracking,
1340            event: TrackingEvent::Tracked,
1341            successive_failures: 0,
1342            pose_prior: None,
1343            used_pose_prior: false,
1344            used_external_localization_prior: false,
1345            external_localization_prior_radius: None,
1346            tracking_failure_reason: None,
1347            map_landmark_count: 0,
1348            map_stats: MapProviderStats::default(),
1349            localization: LocalizationResult::success(LocalizationSuccess {
1350                pose,
1351                candidate_landmark_count: 4,
1352                match_count: 4,
1353                correspondence_count: 4,
1354                inliers: vec![0, 1, 2, 3],
1355                inlier_query_indices: vec![0, 1, 2, 3],
1356                inlier_landmark_ids: vec![1, 2, 3, 4],
1357                inlier_confidences: vec![None; 4],
1358                inlier_reprojection_errors: vec![0.0; 4],
1359                mean_reprojection_error: 0.0,
1360                median_reprojection_error: 0.0,
1361                max_reprojection_error: 0.0,
1362            }),
1363            covisibility_local_map_size: None,
1364        };
1365        // First observe: populate last_successful_pose. No samples yet.
1366        model.observe(&TrackingResult {
1367            localization: localization_zero,
1368            ..make_result(pose_zero)
1369        });
1370        // Second window: push 1.0 s of accel (2,0,0) samples, then observe.
1371        for _ in 0..10 {
1372            model.push_imu_measurement(Vector3::zeros(), Vector3::new(2.0, 0.0, 0.0), 0.1);
1373        }
1374        // The "tracked" pose passed to this observe is irrelevant for
1375        // the v_w commit (the integration anchors on the *previous*
1376        // pose); use any plausible value.
1377        let pose_next =
1378            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-2.0, 0.0, 0.0));
1379        model.observe(&make_result(pose_next));
1380        let v = model.velocity_world();
1381        assert!(
1382            (v - Vector3::new(3.0, 0.0, 0.0)).norm() < 1.0e-9,
1383            "velocity_world should have advanced from (1,0,0) by ∫(2,0,0) dt = (2,0,0) to (3,0,0); got {v:?}",
1384        );
1385    }
1386
1387    #[test]
1388    fn imu_predictive_motion_carry_forward_reset_clears_last_successful_pose() {
1389        use visloc_core::types::LocalizationSuccess;
1390        // After reset, a single observe with carry-forward on but no
1391        // prior pose should NOT touch velocity_world (no anchor to
1392        // integrate from). Verifies the optional gate.
1393        let config = ImuPredictiveMotionModelConfig {
1394            gravity_world: Vector3::zeros(),
1395            carry_forward_velocity_world: true,
1396            ..ImuPredictiveMotionModelConfig::default()
1397        };
1398        let mut model = ImuPredictiveMotionModel::new(config);
1399        let pose = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1400        let localization = LocalizationResult::success(LocalizationSuccess {
1401            pose,
1402            candidate_landmark_count: 4,
1403            match_count: 4,
1404            correspondence_count: 4,
1405            inliers: vec![0, 1, 2, 3],
1406            inlier_query_indices: vec![0, 1, 2, 3],
1407            inlier_landmark_ids: vec![1, 2, 3, 4],
1408            inlier_confidences: vec![None; 4],
1409            inlier_reprojection_errors: vec![0.0; 4],
1410            mean_reprojection_error: 0.0,
1411            median_reprojection_error: 0.0,
1412            max_reprojection_error: 0.0,
1413        });
1414        let result = TrackingResult {
1415            frame_id: 1,
1416            state: TrackingState::Tracking,
1417            event: TrackingEvent::Tracked,
1418            successive_failures: 0,
1419            pose_prior: None,
1420            used_pose_prior: false,
1421            used_external_localization_prior: false,
1422            external_localization_prior_radius: None,
1423            tracking_failure_reason: None,
1424            map_landmark_count: 0,
1425            map_stats: MapProviderStats::default(),
1426            localization,
1427            covisibility_local_map_size: None,
1428        };
1429        model.observe(&result);
1430        model.set_velocity_world(Vector3::new(5.0, 0.0, 0.0));
1431        model.push_imu_measurement(Vector3::zeros(), Vector3::new(99.0, 0.0, 0.0), 0.1);
1432        model.reset();
1433        // After reset, last_successful_pose is cleared; next observe
1434        // with pending samples must NOT advance velocity_world (it stays
1435        // at the post-reset zero).
1436        model.push_imu_measurement(Vector3::zeros(), Vector3::new(99.0, 0.0, 0.0), 0.1);
1437        model.observe(&result);
1438        assert_eq!(model.velocity_world(), Vector3::zeros());
1439    }
1440
1441    #[test]
1442    fn imu_predictive_motion_t_bs_offset_preserves_extrinsic_under_translation() {
1443        // Body translates at +1 m/s along world-x for 0.5 s under
1444        // zero-gravity, zero gyro, zero accel. The camera sits at a
1445        // body-frame offset of (0.1, 0, 0): `body_to_sensor.translation`
1446        // is the body-frame coords of the sensor origin (i.e., the
1447        // camera origin expressed in body coords). The body moves from
1448        // 0 to 0.5 m, so the body should end at world-x 0.5 m and the
1449        // camera should end at world-x 0.6 m. The starting camera pose
1450        // is set up consistent with body-at-origin, so this is a clean
1451        // round-trip test of the T_BS plumbing.
1452        let body_to_sensor = SE3::new(UnitQuaternion::identity(), Vector3::new(0.1, 0.0, 0.0));
1453        let config = ImuPredictiveMotionModelConfig {
1454            gravity_world: Vector3::zeros(),
1455            body_to_sensor,
1456            ..ImuPredictiveMotionModelConfig::default()
1457        };
1458        let mut model = ImuPredictiveMotionModel::new(config);
1459        model.set_velocity_world(Vector3::new(1.0, 0.0, 0.0));
1460        for _ in 0..50 {
1461            model.push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.01);
1462        }
1463        // Starting camera pose: body at world origin with identity
1464        // rotation → camera centre in world = body_to_sensor.translation.
1465        // The world_to_camera SE3 with `R_cw = I, t_cw = -(0.1, 0, 0)`
1466        // places `camera_center_world = (0.1, 0, 0)`.
1467        let prev =
1468            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.1, 0.0, 0.0));
1469        let predicted = model
1470            .predict_pose(&make_dummy_frame(), None, Some(&prev))
1471            .expect("predicted");
1472        let center = predicted.camera_center_world();
1473        assert!(
1474            (center.x - 0.6).abs() < 1.0e-9,
1475            "predicted camera x should be 0.6 (body 0.5 + extrinsic 0.1), got {}",
1476            center.x
1477        );
1478        assert!(center.y.abs() < 1.0e-9);
1479        assert!(center.z.abs() < 1.0e-9);
1480        // Camera orientation should be unchanged (pure translation).
1481        assert!(rotation_angle_deg(&predicted, &prev) < 1.0e-6);
1482    }
1483
1484    #[test]
1485    fn imu_predictive_motion_update_velocity_from_camera_pose_diff_recovers_body_velocity() {
1486        // Body moved from (0,0,0) to (0.5, 0, 0) over 0.5 s → world-frame
1487        // body velocity should be (1, 0, 0). With `body_to_sensor =
1488        // identity` body==camera, so the camera-pose difference directly
1489        // reflects body motion.
1490        let mut model = ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default());
1491        let prev = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
1492        let curr =
1493            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.5, 0.0, 0.0));
1494        model.update_velocity_from_camera_pose_difference(&prev, &curr, 0.5);
1495        let v = model.velocity_world();
1496        assert!((v.x - 1.0).abs() < 1.0e-9);
1497        assert!(v.y.abs() < 1.0e-9);
1498        assert!(v.z.abs() < 1.0e-9);
1499    }
1500
1501    #[test]
1502    fn imu_predictive_motion_update_velocity_with_lever_arm_uses_body_centre() {
1503        // Body translates from (0,0,0) to (0.5, 0, 0). The camera sits
1504        // 0.1 m ahead of body in body-x. So the camera moves from
1505        // (0.1, 0, 0) to (0.6, 0, 0). The velocity-update method must
1506        // strip the lever-arm offset and report the body's velocity
1507        // (1, 0, 0) instead of the camera's (which would be the same
1508        // here, but with a rotation the two would differ).
1509        let body_to_sensor = SE3::new(UnitQuaternion::identity(), Vector3::new(0.1, 0.0, 0.0));
1510        let mut model = ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig {
1511            body_to_sensor,
1512            ..ImuPredictiveMotionModelConfig::default()
1513        });
1514        // Camera centre = (0.1, 0, 0) at t=0; (0.6, 0, 0) at t=0.5.
1515        // World_to_camera translation = -R_cw * camera_center_world.
1516        let prev =
1517            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.1, 0.0, 0.0));
1518        let curr =
1519            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.6, 0.0, 0.0));
1520        model.update_velocity_from_camera_pose_difference(&prev, &curr, 0.5);
1521        let v = model.velocity_world();
1522        assert!((v.x - 1.0).abs() < 1.0e-9);
1523    }
1524
1525    #[test]
1526    fn imu_predictive_motion_update_velocity_rejects_nonpositive_dt() {
1527        let mut model = ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default());
1528        model.set_velocity_world(Vector3::new(5.0, 0.0, 0.0));
1529        let p = Pose::identity();
1530        model.update_velocity_from_camera_pose_difference(&p, &p, 0.0);
1531        assert_eq!(model.velocity_world(), Vector3::new(5.0, 0.0, 0.0));
1532        model.update_velocity_from_camera_pose_difference(&p, &p, -1.0);
1533        assert_eq!(model.velocity_world(), Vector3::new(5.0, 0.0, 0.0));
1534        model.update_velocity_from_camera_pose_difference(&p, &p, f64::NAN);
1535        assert_eq!(model.velocity_world(), Vector3::new(5.0, 0.0, 0.0));
1536    }
1537
1538    #[test]
1539    fn imu_predictive_motion_t_bs_offset_propagates_rotation_with_lever_arm() {
1540        // Body rotates +π/2 about world-z over 1.0 s under zero gravity,
1541        // zero accel, zero initial velocity. Camera sits 0.1 m ahead of
1542        // body in body-frame x. As the body rotates +90° about z, the
1543        // camera's world position should trace an arc: start (0.1, 0, 0)
1544        // → end (0, 0.1, 0). With `body_to_sensor = identity` the camera
1545        // would just rotate in place at the origin — so this test is
1546        // specifically validating the T_BS lever-arm contribution to the
1547        // predicted camera centre.
1548        let body_to_sensor = SE3::new(UnitQuaternion::identity(), Vector3::new(0.1, 0.0, 0.0));
1549        let config = ImuPredictiveMotionModelConfig {
1550            gravity_world: Vector3::zeros(),
1551            body_to_sensor,
1552            ..ImuPredictiveMotionModelConfig::default()
1553        };
1554        let mut model = ImuPredictiveMotionModel::new(config);
1555        let yaw_rate = std::f64::consts::FRAC_PI_2;
1556        for _ in 0..100 {
1557            model.push_imu_measurement(Vector3::new(0.0, 0.0, yaw_rate), Vector3::zeros(), 0.01);
1558        }
1559        // Starting camera pose corresponds to body at world origin
1560        // identity-oriented → camera centre = (0.1, 0, 0).
1561        let prev =
1562            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.1, 0.0, 0.0));
1563        let predicted = model
1564            .predict_pose(&make_dummy_frame(), None, Some(&prev))
1565            .expect("predicted");
1566        let center = predicted.camera_center_world();
1567        // After +90° yaw, body's +x-axis points to world +y. Camera is
1568        // at body-x=0.1, so its world position is (0, 0.1, 0).
1569        assert!(
1570            center.x.abs() < 1.0e-3,
1571            "predicted camera x should be ≈0 after +90° yaw with lever arm, got {}",
1572            center.x
1573        );
1574        assert!(
1575            (center.y - 0.1).abs() < 1.0e-3,
1576            "predicted camera y should be ≈0.1 after +90° yaw, got {}",
1577            center.y
1578        );
1579        assert!(center.z.abs() < 1.0e-9);
1580    }
1581}