Skip to main content

visloc_tracking/
tracker.rs

1//! Frame-to-map tracking: [`Tracker`], [`ImageTracker`], the
2//! [`FrameLocalizer`] abstraction, and covisibility local-map selection.
3
4use super::*;
5
6#[derive(Debug, Clone)]
7pub struct Tracker<P, M = ConstantPoseMotionModel> {
8    localization_pipeline: P,
9    motion_model: M,
10    config: TrackingConfig,
11    state: TrackingState,
12    successive_failures: usize,
13    consecutive_motion_prior_coasts: usize,
14    /// Landmark ids that were PnP inliers on recent successful visual
15    /// tracks (union of the history ring). Used by
16    /// `temporal_landmark_tracking` to re-associate the same 3D points
17    /// before a full-map search.
18    last_tracked_landmark_ids: Vec<LandmarkId>,
19    /// Ring of per-success inlier landmark id sets. Length capped by
20    /// `temporal_landmark_tracking_history_frames`.
21    recent_tracked_landmark_sets: Vec<Vec<LandmarkId>>,
22    last_result: Option<TrackingResult>,
23    last_successful_frame_id: Option<FrameId>,
24    last_successful_pose: Option<Pose>,
25    stats: TrackingStats,
26}
27
28#[derive(Debug, Clone)]
29pub struct ImageTracker<X, T = Tracker<LocalizationPipeline>> {
30    pub extractor: X,
31    pub tracker: T,
32}
33
34impl<X> ImageTracker<X, Tracker<LocalizationPipeline, ConstantPoseMotionModel>>
35where
36    X: FeatureExtractor,
37{
38    pub fn new(extractor: X, config: TrackingConfig) -> Self {
39        Self {
40            extractor,
41            tracker: Tracker::new(LocalizationPipeline::default(), config),
42        }
43    }
44}
45
46impl<X, T> ImageTracker<X, T>
47where
48    X: FeatureExtractor,
49{
50    pub const fn with_tracker(extractor: X, tracker: T) -> Self {
51        Self { extractor, tracker }
52    }
53
54    pub const fn tracker(&self) -> &T {
55        &self.tracker
56    }
57
58    pub const fn tracker_mut(&mut self) -> &mut T {
59        &mut self.tracker
60    }
61
62    pub fn into_parts(self) -> (X, T) {
63        (self.extractor, self.tracker)
64    }
65}
66
67impl<P> Tracker<P, ConstantPoseMotionModel>
68where
69    P: FrameLocalizer,
70{
71    pub fn new(localization_pipeline: P, config: TrackingConfig) -> Self {
72        Self::with_motion_model(localization_pipeline, ConstantPoseMotionModel, config)
73    }
74}
75
76impl<P, M> Tracker<P, M>
77where
78    P: FrameLocalizer,
79    M: MotionModel,
80{
81    pub fn with_motion_model(
82        localization_pipeline: P,
83        motion_model: M,
84        config: TrackingConfig,
85    ) -> Self {
86        Self {
87            localization_pipeline,
88            motion_model,
89            config,
90            state: TrackingState::Uninitialized,
91            successive_failures: 0,
92            consecutive_motion_prior_coasts: 0,
93            last_tracked_landmark_ids: Vec::new(),
94            recent_tracked_landmark_sets: Vec::new(),
95            last_result: None,
96            last_successful_frame_id: None,
97            last_successful_pose: None,
98            stats: TrackingStats::default(),
99        }
100    }
101
102    pub const fn state(&self) -> TrackingState {
103        self.state
104    }
105
106    pub const fn successive_failures(&self) -> usize {
107        self.successive_failures
108    }
109
110    pub const fn last_result(&self) -> Option<&TrackingResult> {
111        self.last_result.as_ref()
112    }
113
114    pub const fn last_successful_frame_id(&self) -> Option<FrameId> {
115        self.last_successful_frame_id
116    }
117
118    pub const fn last_successful_pose(&self) -> Option<&Pose> {
119        self.last_successful_pose.as_ref()
120    }
121
122    pub const fn stats(&self) -> &TrackingStats {
123        &self.stats
124    }
125
126    pub const fn motion_model(&self) -> &M {
127        &self.motion_model
128    }
129
130    /// Mutable access to the configured motion model. Use this to feed
131    /// out-of-band inputs (e.g., raw IMU samples into
132    /// [`ImuPredictiveMotionModel`]) that the per-frame `track_frame*`
133    /// path does not surface.
134    pub const fn motion_model_mut(&mut self) -> &mut M {
135        &mut self.motion_model
136    }
137
138    pub fn reset(&mut self) {
139        self.state = TrackingState::Uninitialized;
140        self.successive_failures = 0;
141        self.consecutive_motion_prior_coasts = 0;
142        self.last_tracked_landmark_ids.clear();
143        self.recent_tracked_landmark_sets.clear();
144        self.last_result = None;
145        self.last_successful_frame_id = None;
146        self.last_successful_pose = None;
147        self.stats = TrackingStats::default();
148        self.motion_model.reset();
149    }
150
151    /// Override the tracker's per-frame history with a successful
152    /// relocalization recovery result. Called by callers that detect
153    /// a primary `track_frame` failure and recover via a separate
154    /// `FrameLocalizer` (e.g. the relocalization-on-tracker-death stage
155    /// in `OnlineSlamPipeline`).
156    ///
157    /// Reverts the failed-frame side-effects from the primary attempt
158    /// (`successive_failures` counter, `last_result` / `last_successful_*`
159    /// fields, `motion_model.observe(failed_result)`) and re-runs them
160    /// as if the recovered result had been the primary outcome. The
161    /// failed-frame audit counter (`stats.failed_frame_count`) is left
162    /// unchanged so the caller can tell that primary tracking dropped
163    /// the frame before relocalization rescued it.
164    ///
165    /// No-op when `result.localization.success == false` (callers must
166    /// gate on success before invoking).
167    pub fn accept_relocalization_result(&mut self, result: TrackingResult) {
168        if !result.localization.success {
169            return;
170        }
171        self.accept_external_tracking_success(result, true);
172    }
173
174    /// Override the tracker's per-frame history with a successful
175    /// GT-seeded segment restart (e.g. stereo re-bootstrap after
176    /// prolonged tracking loss). Same side-effect repair as
177    /// [`Self::accept_relocalization_result`] but does not increment
178    /// `relocalization_count`.
179    pub fn accept_segment_restart_result(&mut self, result: TrackingResult) {
180        if !result.localization.success {
181            return;
182        }
183        self.accept_external_tracking_success(result, false);
184    }
185
186    fn accept_external_tracking_success(
187        &mut self,
188        result: TrackingResult,
189        count_as_relocalization: bool,
190    ) {
191        self.state = TrackingState::Tracking;
192        self.successive_failures = 0;
193        self.consecutive_motion_prior_coasts = 0;
194        if !result.localization.inlier_landmark_ids.is_empty() {
195            self.push_tracked_landmark_set(result.localization.inlier_landmark_ids.clone());
196        }
197        self.last_successful_frame_id = Some(result.frame_id);
198        self.last_successful_pose = result.localization.pose.clone();
199        self.last_result = Some(result.clone());
200        if count_as_relocalization {
201            self.stats.relocalization_count += 1;
202        }
203        self.stats.successful_frame_count += 1;
204        if result.localization.inlier_count > 0 {
205            self.stats.total_inlier_count += result.localization.inlier_count;
206            self.stats.total_correspondence_count += result.localization.correspondence_count;
207        }
208        self.motion_model.observe(&result);
209    }
210
211    /// Apply a rigid world-frame correction to the tracker's continuation
212    /// state: `last_successful_pose` and the motion model's own cached
213    /// world-frame state (e.g. [`ImuPredictiveMotionModel`]'s
214    /// `velocity_world` and cached poses, or [`ConstantVelocityMotionModel`]'s
215    /// cached poses), via [`MotionModel::apply_pose_correction`].
216    ///
217    /// `correction` follows the same convention used to move map
218    /// landmarks after an external pose-graph optimisation: it maps OLD
219    /// world-frame points/poses to NEW world-frame points/poses, i.e.
220    /// `p_new = correction.transform_point(&p_old)`. A cached
221    /// `world_to_camera` pose `T_wc_old` is corrected to
222    /// `T_wc_old.compose(&correction.inverse())` — the pose whose
223    /// projection of the corrected point matches the original
224    /// projection of the old point (see the call site in
225    /// `visloc-slam`'s online loop-closure refinement for the derivation).
226    ///
227    /// This is the tracker-side half of loop-closure correction
228    /// propagation: without it, the very next `track_frame` call would
229    /// predict a prior pose (and, for `pnp_pose_prior_warm_start` /
230    /// covisibility-radius gating, a candidate radius) anchored to the
231    /// pre-correction map even though the landmarks it is about to match
232    /// against just moved.
233    pub fn apply_pose_correction(&mut self, correction: &SE3) {
234        if let Some(pose) = self.last_successful_pose.as_mut() {
235            pose.world_to_camera = pose.world_to_camera.compose(&correction.inverse());
236        }
237        self.motion_model.apply_pose_correction(correction);
238    }
239
240    /// [`Self::apply_pose_correction`]'s counterpart for a `Sim(3)`
241    /// world-frame correction — used after a `Sim(3)` pose-graph solve
242    /// (`visloc-slam`'s online loop-closure refinement `Sim3` solver)
243    /// instead of the rigid `SE(3)` solver, so scale-drift corrections
244    /// keep the tracker's continuation state consistent too.
245    ///
246    /// `last_successful_pose` is a rigid [`Pose`], so only `correction`'s
247    /// rotation+translation part is folded into it (mirroring the map's
248    /// keyframe write-back convention, which likewise keeps
249    /// `map.keyframes[*].frame.pose` rigid); `correction.scale` is left
250    /// to [`MotionModel::apply_similarity_correction`] for models that
251    /// cache a world-frame velocity, where it multiplies that vector
252    /// (see [`ImuPredictiveMotionModel`]'s
253    /// override).
254    pub fn apply_similarity_pose_correction(&mut self, correction: &Sim3) {
255        let se3_part = SE3::new(correction.rotation, correction.translation);
256        if let Some(pose) = self.last_successful_pose.as_mut() {
257            pose.world_to_camera = pose.world_to_camera.compose(&se3_part.inverse());
258        }
259        self.motion_model.apply_similarity_correction(correction);
260    }
261
262    pub fn pose_prior_for_frame(&self, frame: &Frame) -> Option<Pose> {
263        self.motion_model.predict_pose(
264            frame,
265            self.last_result.as_ref(),
266            self.last_successful_pose.as_ref(),
267        )
268    }
269
270    pub fn localization_prior_for_frame(&self, frame: &Frame, radius: f64) -> LocalizationPrior {
271        if let Some(pose_prior) = self.pose_prior_for_frame(frame) {
272            LocalizationPrior::from_pose(pose_prior, radius)
273        } else {
274            LocalizationPrior::none()
275        }
276    }
277
278    pub fn track_frame(&mut self, frame: &Frame, map: &VisualMap) -> TrackingResult {
279        let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
280        self.track_frame_with_descriptor_store(frame, map, &descriptor_store)
281    }
282
283    pub fn track_frames(&mut self, frames: &[Frame], map: &VisualMap) -> Vec<TrackingResult> {
284        let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
285        self.track_frames_with_descriptor_store(frames, map, &descriptor_store)
286    }
287
288    pub fn track_frame_with_provider<P2>(&mut self, frame: &Frame, provider: &P2) -> TrackingResult
289    where
290        P2: MapProvider + DescriptorProvider,
291    {
292        let map = provider.visual_map();
293        let map_stats = map_provider_stats(provider);
294        if let Some(descriptor_store) = provider.landmark_descriptor_store() {
295            self.track_frame_with_descriptor_store_and_map_stats(
296                frame,
297                map,
298                descriptor_store,
299                map_stats,
300            )
301        } else {
302            let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
303            let map_stats = MapProviderStats {
304                descriptor_count: descriptor_store.len(),
305                ..map_stats
306            };
307            self.track_frame_with_descriptor_store_and_map_stats(
308                frame,
309                map,
310                &descriptor_store,
311                map_stats,
312            )
313        }
314    }
315
316    pub fn track_frames_with_provider<P2>(
317        &mut self,
318        frames: &[Frame],
319        provider: &P2,
320    ) -> Vec<TrackingResult>
321    where
322        P2: MapProvider + DescriptorProvider,
323    {
324        frames
325            .iter()
326            .map(|frame| self.track_frame_with_provider(frame, provider))
327            .collect()
328    }
329
330    pub fn track_frame_with_prior_submap_provider<P2>(
331        &mut self,
332        frame: &Frame,
333        provider: &P2,
334        radius: f64,
335    ) -> TrackingResult
336    where
337        P2: MapProvider + DescriptorProvider,
338    {
339        if let Some(pose_prior) = self.pose_prior_for_frame(frame) {
340            let submap_provider = InMemoryMapProvider::from_provider_radius(
341                provider,
342                pose_prior.camera_center_world(),
343                radius,
344            );
345            self.track_frame_with_provider(frame, &submap_provider)
346        } else {
347            self.track_frame_with_provider(frame, provider)
348        }
349    }
350
351    pub fn track_frames_with_prior_submap_provider<P2>(
352        &mut self,
353        frames: &[Frame],
354        provider: &P2,
355        radius: f64,
356    ) -> Vec<TrackingResult>
357    where
358        P2: MapProvider + DescriptorProvider,
359    {
360        frames
361            .iter()
362            .map(|frame| self.track_frame_with_prior_submap_provider(frame, provider, radius))
363            .collect()
364    }
365
366    pub fn track_frame_with_localization_prior_submap_provider<P2>(
367        &mut self,
368        frame: &Frame,
369        provider: &P2,
370        prior: &LocalizationPrior,
371    ) -> TrackingResult
372    where
373        P2: MapProvider + DescriptorProvider,
374    {
375        if let (Some(center_world), Some(radius)) = (prior.center_world(), prior.radius) {
376            let submap_provider =
377                InMemoryMapProvider::from_provider_radius(provider, center_world, radius);
378            let mut result = self.track_frame_with_provider(frame, &submap_provider);
379            result.used_external_localization_prior = true;
380            result.external_localization_prior_radius = Some(radius);
381            self.stats.external_localization_prior_used_count += 1;
382            self.last_result = Some(result.clone());
383            result
384        } else {
385            self.track_frame_with_provider(frame, provider)
386        }
387    }
388
389    pub fn track_frames_with_localization_prior_submap_provider<'a, P2, I>(
390        &mut self,
391        frames_and_priors: I,
392        provider: &P2,
393    ) -> Vec<TrackingResult>
394    where
395        P2: MapProvider + DescriptorProvider,
396        I: IntoIterator<Item = (&'a Frame, Option<&'a LocalizationPrior>)>,
397    {
398        frames_and_priors
399            .into_iter()
400            .map(|(frame, prior)| {
401                if let Some(prior) = prior {
402                    self.track_frame_with_localization_prior_submap_provider(frame, provider, prior)
403                } else {
404                    self.track_frame_with_provider(frame, provider)
405                }
406            })
407            .collect()
408    }
409
410    pub fn track_frame_with_descriptor_store(
411        &mut self,
412        frame: &Frame,
413        map: &VisualMap,
414        descriptor_store: &LandmarkDescriptorStore,
415    ) -> TrackingResult {
416        let map_stats = MapProviderStats {
417            camera_count: map.cameras.len(),
418            landmark_count: map.landmarks.len(),
419            keyframe_count: map.keyframes.len(),
420            descriptor_count: descriptor_store.len(),
421        };
422        self.track_frame_with_descriptor_store_and_map_stats(
423            frame,
424            map,
425            descriptor_store,
426            map_stats,
427        )
428    }
429
430    pub fn track_frames_with_descriptor_store(
431        &mut self,
432        frames: &[Frame],
433        map: &VisualMap,
434        descriptor_store: &LandmarkDescriptorStore,
435    ) -> Vec<TrackingResult> {
436        frames
437            .iter()
438            .map(|frame| self.track_frame_with_descriptor_store(frame, map, descriptor_store))
439            .collect()
440    }
441
442    fn track_frame_with_descriptor_store_and_map_stats(
443        &mut self,
444        frame: &Frame,
445        map: &VisualMap,
446        descriptor_store: &LandmarkDescriptorStore,
447        map_stats: MapProviderStats,
448    ) -> TrackingResult {
449        let pose_prior = self.motion_model.predict_pose(
450            frame,
451            self.last_result.as_ref(),
452            self.last_successful_pose.as_ref(),
453        );
454        let used_pose_prior =
455            pose_prior.is_some() && self.config.last_pose_candidate_radius.is_some();
456
457        let covisibility_local_store =
458            self.build_covisibility_local_map_store(map, descriptor_store);
459        let covisibility_local_map_size =
460            covisibility_local_store.as_ref().map(|store| store.len());
461        let active_descriptor_store: &LandmarkDescriptorStore = covisibility_local_store
462            .as_ref()
463            .unwrap_or(descriptor_store);
464
465        // Temporal landmark track (image-free Basalt-KLT analogue): try
466        // matching against only the previous successful inlier landmarks
467        // before the full appearance / projection path.
468        let temporal_store = if self.config.temporal_landmark_tracking
469            && self.last_tracked_landmark_ids.len()
470                >= self.config.temporal_landmark_tracking_min_landmarks
471        {
472            let store = active_descriptor_store.filtered(&self.last_tracked_landmark_ids);
473            if store.len() >= self.config.temporal_landmark_tracking_min_landmarks {
474                Some(store)
475            } else {
476                None
477            }
478        } else {
479            None
480        };
481
482        // Copied out (the config is `Copy`) rather than borrowed, so the
483        // widen-retry ladder below can take `&mut self` for its stats
484        // bookkeeping without fighting the borrow checker over `self.config`.
485        let projection_guided_config = self.config.projection_guided_tracking;
486        let mut used_temporal_landmark_track = false;
487        let mut localization = if let Some(temporal_store) = temporal_store.as_ref() {
488            self.stats.temporal_landmark_attempt_count += 1;
489            let temporal =
490                self.localize_appearance_global(frame, map, temporal_store, pose_prior.as_ref());
491            if temporal.success {
492                self.stats.temporal_landmark_success_count += 1;
493                used_temporal_landmark_track = true;
494                temporal
495            } else {
496                match (projection_guided_config, pose_prior.as_ref()) {
497                    (Some(projection_config), Some(prior)) => self.run_projection_guided_tracking(
498                        frame,
499                        map,
500                        active_descriptor_store,
501                        prior,
502                        &projection_config,
503                    ),
504                    _ => self.localize_appearance_global(
505                        frame,
506                        map,
507                        active_descriptor_store,
508                        pose_prior.as_ref(),
509                    ),
510                }
511            }
512        } else {
513            match (projection_guided_config, pose_prior.as_ref()) {
514                (Some(projection_config), Some(prior)) => self.run_projection_guided_tracking(
515                    frame,
516                    map,
517                    active_descriptor_store,
518                    prior,
519                    &projection_config,
520                ),
521                _ => self.localize_appearance_global(
522                    frame,
523                    map,
524                    active_descriptor_store,
525                    pose_prior.as_ref(),
526                ),
527            }
528        };
529
530        if localization.success {
531            self.apply_local_map_refinement(
532                frame,
533                map,
534                covisibility_local_store.as_ref(),
535                &mut localization,
536            );
537        }
538
539        let saved_min_inliers = self.config.min_inliers;
540        if used_temporal_landmark_track {
541            self.config.min_inliers = self
542                .config
543                .temporal_landmark_tracking_min_inliers
544                .min(saved_min_inliers);
545        }
546        let (mut tracking_failure_reason, continuation_pose) =
547            self.apply_tracking_quality_gate(frame, map, pose_prior.as_ref(), &mut localization);
548        self.config.min_inliers = saved_min_inliers;
549
550        // IMU/velocity coast: when visual tracking dies but the motion
551        // model still has a predictive prior, accept that prior so the
552        // strapdown window drains and the trajectory stays continuous.
553        // Constant-pose models deliberately refuse this path (frozen
554        // prior would just stamp the last success forever). Cap the
555        // streak — unlimited coast (gate67) collapsed Sim(3) scale.
556        let mut coasted = false;
557        if !localization.success
558            && self.config.accept_motion_prior_on_failure
559            && self.motion_model.allows_pnp_pose_prior_warm_start()
560        {
561            let within_cap = self
562                .config
563                .max_consecutive_motion_prior_coasts
564                .is_none_or(|cap| self.consecutive_motion_prior_coasts < cap);
565            if within_cap {
566                if let Some(prior) = pose_prior.as_ref() {
567                    localization.success = true;
568                    localization.pose = Some(prior.clone());
569                    localization.failure_reason = None;
570                    localization.inlier_count = 0;
571                    localization.inlier_ratio = 0.0;
572                    localization.inliers.clear();
573                    localization.inlier_query_indices.clear();
574                    localization.inlier_landmark_ids.clear();
575                    localization.inlier_confidences.clear();
576                    localization.inlier_reprojection_errors.clear();
577                    localization.reprojection_error = None;
578                    localization.median_reprojection_error = None;
579                    localization.max_reprojection_error = None;
580                    tracking_failure_reason = None;
581                    self.stats.motion_prior_coast_count += 1;
582                    coasted = true;
583                }
584            }
585        }
586        if localization.success && !coasted {
587            self.consecutive_motion_prior_coasts = 0;
588            if !localization.inlier_landmark_ids.is_empty() {
589                self.push_tracked_landmark_set(localization.inlier_landmark_ids.clone());
590            }
591        } else if coasted {
592            self.consecutive_motion_prior_coasts += 1;
593        } else {
594            self.consecutive_motion_prior_coasts = 0;
595        }
596
597        let previous_state = self.state;
598        let event = if localization.success {
599            self.state = TrackingState::Tracking;
600            self.successive_failures = 0;
601            match previous_state {
602                TrackingState::Uninitialized => TrackingEvent::Initialized,
603                TrackingState::Tracking => TrackingEvent::Tracked,
604                TrackingState::Lost => TrackingEvent::Relocalized,
605            }
606        } else {
607            self.successive_failures += 1;
608            if self.successive_failures >= self.config.min_successive_failures_to_lost {
609                self.state = TrackingState::Lost;
610                TrackingEvent::Lost
611            } else if self.state == TrackingState::Uninitialized {
612                self.state = TrackingState::Uninitialized;
613                TrackingEvent::TrackingFailed
614            } else {
615                self.state = TrackingState::Tracking;
616                TrackingEvent::TrackingFailed
617            }
618        };
619
620        let result = TrackingResult {
621            frame_id: frame.id,
622            state: self.state,
623            event,
624            successive_failures: self.successive_failures,
625            pose_prior,
626            used_pose_prior,
627            used_external_localization_prior: false,
628            external_localization_prior_radius: None,
629            tracking_failure_reason,
630            map_landmark_count: map_stats.landmark_count,
631            map_stats,
632            localization,
633            covisibility_local_map_size,
634        };
635
636        let mut continuation_result = result.clone();
637        if let Some(pose) = continuation_pose {
638            continuation_result.localization.pose = Some(pose);
639        }
640        self.update_history(&continuation_result);
641        self.motion_model.observe(&continuation_result);
642        result
643    }
644
645    fn push_tracked_landmark_set(&mut self, landmark_ids: Vec<LandmarkId>) {
646        let history = self.config.temporal_landmark_tracking_history_frames.max(1);
647        self.recent_tracked_landmark_sets.push(landmark_ids);
648        while self.recent_tracked_landmark_sets.len() > history {
649            self.recent_tracked_landmark_sets.remove(0);
650        }
651        let mut union = HashSet::new();
652        for set in &self.recent_tracked_landmark_sets {
653            union.extend(set.iter().copied());
654        }
655        let mut merged: Vec<LandmarkId> = union.into_iter().collect();
656        merged.sort_unstable();
657        self.last_tracked_landmark_ids = merged;
658    }
659
660    /// Today's appearance-global localization path (descriptor search over
661    /// the full radius-filtered candidate set, with the optional PnP
662    /// warm-start). Factored out so it is shared, byte-for-byte, between the
663    /// `projection_guided_tracking == None` default and the widen-retry
664    /// ladder's fallback rung — enabling projection-guided tracking can
665    /// therefore only ADD tracking chances, never remove this one.
666    fn localize_appearance_global(
667        &self,
668        frame: &Frame,
669        map: &VisualMap,
670        descriptor_store: &LandmarkDescriptorStore,
671        pose_prior: Option<&Pose>,
672    ) -> LocalizationResult {
673        if self.config.pnp_pose_prior_warm_start
674            && self.motion_model.allows_pnp_pose_prior_warm_start()
675        {
676            self.localization_pipeline
677                .localize_frame_with_pose_prior_warm_start_and_descriptor_store(
678                    frame,
679                    map,
680                    descriptor_store,
681                    pose_prior,
682                    self.config.last_pose_candidate_radius,
683                )
684        } else {
685            self.localization_pipeline
686                .localize_frame_with_pose_prior_and_descriptor_store(
687                    frame,
688                    map,
689                    descriptor_store,
690                    pose_prior,
691                    self.config.last_pose_candidate_radius,
692                )
693        }
694    }
695
696    /// Stage 1 + widen-retry ladder: try projection-window matching at
697    /// `config.search_radius_px`, multiplying the radius by
698    /// `config.widen_factor` and retrying up to `config.max_widen_retries`
699    /// times when the current radius's result fails the pose-estimation
700    /// quality gate. Falls back to today's appearance-global path
701    /// (`localize_appearance_global`) if every projection attempt fails, so
702    /// enabling this feature can only add tracking chances versus today.
703    fn run_projection_guided_tracking(
704        &mut self,
705        frame: &Frame,
706        map: &VisualMap,
707        descriptor_store: &LandmarkDescriptorStore,
708        pose_prior: &Pose,
709        config: &ProjectionGuidedTrackingConfig,
710    ) -> LocalizationResult {
711        let mut radius = config.search_radius_px;
712        let mut projection_result =
713            LocalizationResult::failure(LocalizationFailureReason::NoDescriptorMatches, 0, 0, 0);
714        for attempt in 0..=config.max_widen_retries {
715            self.stats.projection_guided_attempt_count += 1;
716            projection_result = self
717                .localization_pipeline
718                .localize_frame_with_projection_window_descriptor_store_and_query_landmark_ratio(
719                    frame,
720                    map,
721                    descriptor_store,
722                    pose_prior,
723                    self.config.last_pose_candidate_radius,
724                    radius,
725                    config.max_query_landmark_distance_ratio,
726                );
727            if projection_result.success {
728                break;
729            }
730            if attempt < config.max_widen_retries {
731                self.stats.projection_guided_widen_retry_count += 1;
732                radius *= config.widen_factor;
733            }
734        }
735
736        if projection_result.success {
737            self.stats.projection_guided_success_count += 1;
738            return projection_result;
739        }
740
741        let fallback =
742            self.localize_appearance_global(frame, map, descriptor_store, Some(pose_prior));
743        if fallback.success {
744            self.stats.projection_guided_fallback_success_count += 1;
745        }
746        fallback
747    }
748
749    /// Stage 3: after ANY successful pose estimate (projection path or
750    /// appearance-global fallback), project the covisibility local map (if
751    /// one was built for this frame) with the ESTIMATED pose and re-optimize
752    /// over the union of harvested and existing inlier correspondences.
753    /// Accepts the refined pose only when its inlier count does not
754    /// decrease relative to the pre-refinement result; otherwise
755    /// `localization` is left unchanged. No-op unless
756    /// `projection_guided_tracking` is configured with
757    /// `local_map_refinement = true` AND a covisibility local map exists for
758    /// this frame (there is otherwise no defined local-map landmark set to
759    /// project).
760    fn apply_local_map_refinement(
761        &mut self,
762        frame: &Frame,
763        map: &VisualMap,
764        covisibility_local_store: Option<&LandmarkDescriptorStore>,
765        localization: &mut LocalizationResult,
766    ) {
767        let Some(projection_config) = self.config.projection_guided_tracking else {
768            return;
769        };
770        if !projection_config.local_map_refinement {
771            return;
772        }
773        let Some(local_store) = covisibility_local_store else {
774            return;
775        };
776
777        let iterations = projection_config.refinement_iterations.max(1);
778        let shrink = if projection_config
779            .refinement_radius_shrink_factor
780            .is_finite()
781            && projection_config.refinement_radius_shrink_factor > 0.0
782            && projection_config.refinement_radius_shrink_factor <= 1.0
783        {
784            projection_config.refinement_radius_shrink_factor
785        } else {
786            1.0
787        };
788        let strict_monotonic =
789            iterations > 1 || projection_config.refinement_reassign_correspondences;
790        let mut radius = projection_config.refinement_search_radius_px;
791        let mut attempted_any = false;
792        let mut accepted_any = false;
793
794        for _ in 0..iterations {
795            let refined = if projection_config.refinement_reassign_correspondences {
796                self.localization_pipeline
797                    .revise_pose_with_local_map_and_descriptor_store(
798                        frame,
799                        map,
800                        local_store,
801                        localization,
802                        radius,
803                    )
804            } else {
805                self.localization_pipeline
806                    .refine_pose_with_local_map_and_descriptor_store(
807                        frame,
808                        map,
809                        local_store,
810                        localization,
811                        radius,
812                    )
813            };
814            radius *= shrink;
815
816            let Some(refined) = refined else {
817                continue;
818            };
819            attempted_any = true;
820            self.stats.local_map_refinement_correspondence_gain_total += refined
821                .correspondence_count
822                .saturating_sub(localization.correspondence_count);
823
824            let inliers_improved = refined.inlier_count > localization.inlier_count;
825            let inliers_preserved = refined.inlier_count == localization.inlier_count;
826            let error_not_worse =
827                match (refined.reprojection_error, localization.reprojection_error) {
828                    (Some(refined_error), Some(current_error)) => {
829                        refined_error.is_finite() && refined_error <= current_error + 1.0e-9
830                    }
831                    (Some(refined_error), None) => refined_error.is_finite(),
832                    (None, None) => true,
833                    (None, Some(_)) => false,
834                };
835            let current_pairs = localization
836                .inlier_query_indices
837                .iter()
838                .copied()
839                .zip(localization.inlier_landmark_ids.iter().copied())
840                .collect::<HashSet<_>>();
841            let refined_pairs = refined
842                .inlier_query_indices
843                .iter()
844                .copied()
845                .zip(refined.inlier_landmark_ids.iter().copied())
846                .collect::<HashSet<_>>();
847            let retained_pair_ratio = if current_pairs.is_empty() {
848                1.0
849            } else {
850                current_pairs.intersection(&refined_pairs).count() as f64
851                    / current_pairs.len() as f64
852            };
853            let pair_retention_passes =
854                retained_pair_ratio >= projection_config.refinement_min_inlier_pair_retention_ratio;
855            let (translation_correction_m, rotation_correction_rad) =
856                match (localization.pose.as_ref(), refined.pose.as_ref()) {
857                    (Some(current_pose), Some(refined_pose)) => {
858                        let translation = (refined_pose.camera_center_world()
859                            - current_pose.camera_center_world())
860                        .norm();
861                        let rotation_delta = refined_pose.world_to_camera.rotation
862                            * current_pose.world_to_camera.rotation.inverse();
863                        (translation, rotation_delta.angle())
864                    }
865                    _ => (f64::INFINITY, f64::INFINITY),
866                };
867            let translation_correction_passes = projection_config
868                .refinement_max_pose_translation_correction_m
869                .is_none_or(|max| translation_correction_m <= max);
870            let rotation_correction_passes = projection_config
871                .refinement_max_pose_rotation_correction_rad
872                .is_none_or(|max| rotation_correction_rad <= max);
873            let accept = refined.success
874                && (inliers_improved
875                    || (inliers_preserved && (!strict_monotonic || error_not_worse)))
876                && pair_retention_passes
877                && translation_correction_passes
878                && rotation_correction_passes;
879            if accept {
880                *localization = refined;
881                accepted_any = true;
882            }
883        }
884
885        if accepted_any {
886            self.stats.local_map_refinement_accepted_count += 1;
887        } else if attempted_any {
888            self.stats.local_map_refinement_rejected_count += 1;
889        }
890    }
891
892    /// Build a covisibility-graph-derived descriptor store, if the feature is
893    /// enabled and the surrounding state allows it (tracker is in `Tracking`
894    /// state with a known reference keyframe in `map`, the local-map landmark
895    /// set is above `min_local_map_landmarks`). Returns `None` to signal that
896    /// the caller should fall through to the original descriptor store.
897    fn build_covisibility_local_map_store(
898        &self,
899        map: &VisualMap,
900        descriptor_store: &LandmarkDescriptorStore,
901    ) -> Option<LandmarkDescriptorStore> {
902        let config = self.config.covisibility_local_map.as_ref()?;
903        if self.state != TrackingState::Tracking {
904            return None;
905        }
906        let last_id = self.last_successful_frame_id?;
907        let reference_kf = covisibility_pick_reference_keyframe(map, last_id)?;
908        let local_landmarks = covisibility_local_map_landmarks(map, reference_kf, config);
909        if local_landmarks.len() < config.min_local_map_landmarks {
910            return None;
911        }
912        let mut filtered = LandmarkDescriptorStore::new();
913        // Sort the local-landmark id set before iterating so downstream
914        // consumers see a deterministic insertion order independent of
915        // the per-process `HashSet` SipHash seed. Even though the
916        // `LandmarkDescriptorStore` itself is a `HashMap`, this insulates
917        // any caller that depends on observed insertion order.
918        let mut local_landmark_ids: Vec<u64> = local_landmarks.iter().copied().collect();
919        local_landmark_ids.sort();
920        for landmark_id in &local_landmark_ids {
921            if let Some(descriptor) = descriptor_store.get(*landmark_id) {
922                filtered.insert(*landmark_id, descriptor.to_vec());
923            }
924        }
925        if filtered.len() < config.min_local_map_landmarks {
926            return None;
927        }
928        Some(filtered)
929    }
930
931    fn update_history(&mut self, result: &TrackingResult) {
932        if self.stats.first_frame_id.is_none() {
933            self.stats.first_frame_id = Some(result.frame_id);
934        }
935        self.stats.last_frame_id = Some(result.frame_id);
936        self.stats.frame_count += 1;
937        if result.localization.success {
938            self.stats.successful_frame_count += 1;
939            self.last_successful_frame_id = Some(result.frame_id);
940            self.last_successful_pose = result.localization.pose.clone();
941        } else {
942            self.stats.failed_frame_count += 1;
943        }
944
945        if result.event == TrackingEvent::Lost {
946            self.stats.lost_count += 1;
947        }
948        if result.event == TrackingEvent::Relocalized {
949            self.stats.relocalization_count += 1;
950        }
951        if result.used_pose_prior {
952            self.stats.pose_prior_used_count += 1;
953        }
954        if result.tracking_failure_reason.is_some() {
955            self.stats.tracking_quality_gate_failure_count += 1;
956        }
957        if result.covisibility_local_map_size.is_some() {
958            self.stats.covisibility_local_map_used_count += 1;
959        }
960        self.stats.total_inlier_count += result.localization.inlier_count;
961        self.stats.total_correspondence_count += result.localization.correspondence_count;
962
963        self.last_result = Some(result.clone());
964    }
965
966    fn apply_tracking_quality_gate(
967        &mut self,
968        frame: &Frame,
969        map: &VisualMap,
970        pose_prior: Option<&Pose>,
971        localization: &mut LocalizationResult,
972    ) -> (Option<TrackingFailureReason>, Option<Pose>) {
973        if !localization.success {
974            return (None, None);
975        }
976
977        if localization.inlier_count < self.config.min_inliers {
978            *localization = localization.clone().rejected_by_quality_gate();
979            return (
980                Some(TrackingFailureReason::InsufficientInliers {
981                    inlier_count: localization.inlier_count,
982                    min_inliers: self.config.min_inliers,
983                }),
984                None,
985            );
986        }
987
988        if localization.inlier_ratio < self.config.min_inlier_ratio {
989            *localization = localization.clone().rejected_by_quality_gate();
990            return (
991                Some(TrackingFailureReason::InlierRatioTooLow {
992                    inlier_ratio: localization.inlier_ratio,
993                    min_inlier_ratio: self.config.min_inlier_ratio,
994                }),
995                None,
996            );
997        }
998
999        if let (Some(reprojection_error), Some(max_reprojection_error)) = (
1000            localization.reprojection_error,
1001            self.config.max_mean_reprojection_error,
1002        ) {
1003            if reprojection_error > max_reprojection_error {
1004                *localization = localization.clone().rejected_by_quality_gate();
1005                return (
1006                    Some(TrackingFailureReason::MeanReprojectionErrorTooHigh {
1007                        reprojection_error,
1008                        max_reprojection_error,
1009                    }),
1010                    None,
1011                );
1012            }
1013        }
1014
1015        let Some(max_translation_error) = self.config.max_pose_prior_translation_error else {
1016            return (None, None);
1017        };
1018        let Some(pose_prior) = pose_prior else {
1019            return (None, None);
1020        };
1021        let Some(estimated_pose) = localization.pose.as_ref() else {
1022            return (None, None);
1023        };
1024
1025        let translation_error =
1026            (estimated_pose.camera_center_world() - pose_prior.camera_center_world()).norm();
1027
1028        let mut max_translation_error = if self.config.pose_jump_gap_scaling {
1029            // The pose prior comes from the motion model, which (for the
1030            // constant-pose / constant-velocity models used here) is
1031            // anchored to `last_successful_pose`. If tracking has been
1032            // failing for several frames, that prior is stale — it hasn't
1033            // moved while the true camera pose has. Scale the gate by how
1034            // long the prior has been frozen so a good post-gap PnP
1035            // solution isn't rejected against a fixed radius measured from
1036            // a pose the camera left several frames ago.
1037            let frames_since_last_tracking_success = self
1038                .last_successful_frame_id
1039                .map_or(1, |last_id| frame.id.saturating_sub(last_id))
1040                .max(1);
1041            let multiplier = pose_jump_gap_scaling_multiplier(
1042                frames_since_last_tracking_success,
1043                self.config.pose_jump_gap_scaling_max_multiplier,
1044            );
1045            max_translation_error * multiplier as f64
1046        } else {
1047            max_translation_error
1048        };
1049
1050        let mut continuation_pose = None;
1051        if let Some(override_config) = self.config.pose_prior_visual_override {
1052            let rotation_error = pose_prior
1053                .camera_to_world()
1054                .rotation
1055                .rotation_to(&estimated_pose.camera_to_world().rotation)
1056                .angle();
1057            if let Some(widened) = pose_prior_visual_override_threshold(
1058                override_config,
1059                localization,
1060                translation_error,
1061                rotation_error,
1062                max_translation_error,
1063            ) {
1064                max_translation_error = widened;
1065                self.stats.pose_prior_visual_override_count += 1;
1066                continuation_pose = covariance_weighted_continuation_pose(
1067                    frame,
1068                    map,
1069                    pose_prior,
1070                    estimated_pose,
1071                    localization,
1072                    override_config,
1073                )
1074                .or_else(|| Some(pose_prior.clone()));
1075            }
1076        }
1077
1078        if translation_error <= max_translation_error {
1079            return (None, continuation_pose);
1080        }
1081
1082        *localization = localization.clone().rejected_by_quality_gate();
1083        (
1084            Some(TrackingFailureReason::PosePriorTranslationErrorExceeded {
1085                translation_error,
1086                max_translation_error,
1087            }),
1088            None,
1089        )
1090    }
1091}
1092
1093fn pose_prior_visual_override_satisfied(
1094    config: crate::PosePriorVisualOverrideConfig,
1095    localization: &LocalizationResult,
1096) -> bool {
1097    config.min_inliers > 0
1098        && config.min_inlier_ratio.is_finite()
1099        && (0.0..=1.0).contains(&config.min_inlier_ratio)
1100        && config.max_translation_error_multiplier.is_finite()
1101        && config.min_translation_error_multiplier.is_finite()
1102        && config.min_translation_error_multiplier >= 1.0
1103        && config.min_translation_error_multiplier <= config.max_translation_error_multiplier
1104        && config.max_translation_error_multiplier >= 1.0
1105        && localization.inlier_count >= config.min_inliers
1106        && localization.inlier_ratio.is_finite()
1107        && localization.inlier_ratio >= config.min_inlier_ratio
1108        && config.max_mean_reprojection_error.is_none_or(|maximum| {
1109            maximum.is_finite()
1110                && maximum >= 0.0
1111                && localization
1112                    .reprojection_error
1113                    .is_some_and(|value| value.is_finite() && value <= maximum)
1114        })
1115}
1116
1117fn pose_prior_visual_override_threshold(
1118    config: crate::PosePriorVisualOverrideConfig,
1119    localization: &LocalizationResult,
1120    translation_error: f64,
1121    rotation_error: f64,
1122    base_threshold: f64,
1123) -> Option<f64> {
1124    let minimum = base_threshold * config.min_translation_error_multiplier;
1125    let maximum = base_threshold * config.max_translation_error_multiplier;
1126    (base_threshold.is_finite()
1127        && base_threshold > 0.0
1128        && translation_error.is_finite()
1129        && translation_error >= minimum
1130        && translation_error <= maximum
1131        && config.max_rotation_error_radians.is_none_or(|maximum| {
1132            maximum.is_finite()
1133                && maximum >= 0.0
1134                && rotation_error.is_finite()
1135                && rotation_error <= maximum
1136        })
1137        && pose_prior_visual_override_satisfied(config, localization))
1138    .then_some(maximum)
1139}
1140
1141fn covariance_weighted_continuation_pose(
1142    frame: &Frame,
1143    map: &VisualMap,
1144    pose_prior: &Pose,
1145    estimated_pose: &Pose,
1146    localization: &LocalizationResult,
1147    config: crate::PosePriorVisualOverrideConfig,
1148) -> Option<Pose> {
1149    let camera = map.cameras.get(&frame.camera_id)?;
1150    let prior_std = config.continuation_prior_translation_std_m;
1151    let pixel_sigma = config.continuation_visual_pixel_sigma_px;
1152    let max_gain = config.continuation_max_gain;
1153    let max_condition = config.continuation_max_condition_number;
1154    if !prior_std.is_finite()
1155        || prior_std <= 0.0
1156        || !pixel_sigma.is_finite()
1157        || pixel_sigma <= 0.0
1158        || !max_gain.is_finite()
1159        || !(0.0..=1.0).contains(&max_gain)
1160        || !max_condition.is_finite()
1161        || max_condition < 1.0
1162    {
1163        return None;
1164    }
1165
1166    let rotation = estimated_pose.world_to_camera.rotation;
1167    let center = estimated_pose.camera_center_world().coords;
1168    let eps = 1.0e-4;
1169    let mut hessian = Matrix3::<f64>::zeros();
1170    let mut used = 0usize;
1171    for landmark_id in &localization.inlier_landmark_ids {
1172        let Some(landmark) = map.landmarks.get(landmark_id) else {
1173            continue;
1174        };
1175        let mut jacobian = nalgebra::SMatrix::<f64, 2, 3>::zeros();
1176        let mut valid = true;
1177        for axis in 0..3 {
1178            let mut plus_center = center;
1179            let mut minus_center = center;
1180            plus_center[axis] += eps;
1181            minus_center[axis] -= eps;
1182            let plus_translation = -(rotation.transform_vector(&plus_center));
1183            let minus_translation = -(rotation.transform_vector(&minus_center));
1184            let plus_pose = Pose::from_world_to_camera(rotation, plus_translation);
1185            let minus_pose = Pose::from_world_to_camera(rotation, minus_translation);
1186            let Some(plus) = camera.project(&plus_pose.transform_world_point(&landmark.position))
1187            else {
1188                valid = false;
1189                break;
1190            };
1191            let Some(minus) = camera.project(&minus_pose.transform_world_point(&landmark.position))
1192            else {
1193                valid = false;
1194                break;
1195            };
1196            jacobian.set_column(axis, &((plus - minus) / (2.0 * eps)));
1197        }
1198        if valid && jacobian.iter().all(|value| value.is_finite()) {
1199            hessian += jacobian.transpose() * jacobian / (pixel_sigma * pixel_sigma);
1200            used += 1;
1201        }
1202    }
1203    if used < 6 {
1204        return None;
1205    }
1206    let eigenvalues = hessian.symmetric_eigen().eigenvalues;
1207    let minimum = eigenvalues.iter().copied().fold(f64::INFINITY, f64::min);
1208    let maximum = eigenvalues.iter().copied().fold(0.0_f64, f64::max);
1209    if !minimum.is_finite()
1210        || !maximum.is_finite()
1211        || minimum <= 0.0
1212        || maximum / minimum > max_condition
1213    {
1214        return None;
1215    }
1216    let visual_covariance = hessian.try_inverse()?;
1217    let prior_variance = prior_std * prior_std;
1218    let prior_covariance = Matrix3::<f64>::identity() * prior_variance;
1219    let innovation_covariance = prior_covariance + visual_covariance;
1220    let mut gain = prior_covariance * innovation_covariance.try_inverse()?;
1221    gain = (gain + gain.transpose()) * 0.5;
1222    let gain_maximum = gain
1223        .symmetric_eigen()
1224        .eigenvalues
1225        .iter()
1226        .copied()
1227        .fold(0.0_f64, f64::max);
1228    if !gain_maximum.is_finite() || gain_maximum <= 0.0 {
1229        return None;
1230    }
1231    if gain_maximum > max_gain {
1232        gain *= max_gain / gain_maximum;
1233    }
1234
1235    let prior_center = pose_prior.camera_center_world().coords;
1236    let estimated_center = estimated_pose.camera_center_world().coords;
1237    let fused_center = prior_center + gain * (estimated_center - prior_center);
1238    let rotation_gain = (gain.trace() / 3.0).clamp(0.0, max_gain);
1239    let fused_rotation = pose_prior
1240        .world_to_camera
1241        .rotation
1242        .slerp(&estimated_pose.world_to_camera.rotation, rotation_gain);
1243    let fused_translation = -(fused_rotation.transform_vector(&fused_center));
1244    Some(Pose::from_world_to_camera(
1245        fused_rotation,
1246        fused_translation,
1247    ))
1248}
1249
1250/// Multiplier applied to `max_pose_prior_translation_error` when
1251/// `pose_jump_gap_scaling` is enabled: the frame gap since the last
1252/// successful track, capped at `max_multiplier` and floored at 1. A gap of
1253/// 1 (the common case — the immediately preceding frame tracked
1254/// successfully) reproduces the unscaled gate.
1255fn pose_jump_gap_scaling_multiplier(
1256    frames_since_last_tracking_success: FrameId,
1257    max_multiplier: usize,
1258) -> FrameId {
1259    frames_since_last_tracking_success
1260        .min(max_multiplier as FrameId)
1261        .max(1)
1262}
1263
1264/// Resolve the reference keyframe for covisibility-based local-map selection.
1265///
1266/// Prefers a keyframe whose `frame.id` matches `last_id` exactly (when the
1267/// last successful frame was itself promoted to a keyframe). Otherwise falls
1268/// back to the keyframe with the largest `frame.id <= last_id` so we still
1269/// anchor to a temporally-nearby past keyframe.
1270fn covisibility_pick_reference_keyframe(map: &VisualMap, last_id: FrameId) -> Option<u64> {
1271    if map.keyframes.contains_key(&last_id) {
1272        return Some(last_id);
1273    }
1274    let mut best: Option<u64> = None;
1275    for kf_id in map.keyframes.keys() {
1276        if *kf_id > last_id {
1277            continue;
1278        }
1279        match best {
1280            None => best = Some(*kf_id),
1281            Some(current) if *kf_id > current => best = Some(*kf_id),
1282            _ => {}
1283        }
1284    }
1285    best
1286}
1287
1288/// Compute the covisibility-derived local-map landmark set: union of
1289/// landmarks observed by the reference keyframe and the keyframes that share
1290/// at least `min_shared_landmarks` landmarks with it (capped at
1291/// `max_keyframes` co-visible neighbours, ranked by descending shared count).
1292fn covisibility_local_map_landmarks(
1293    map: &VisualMap,
1294    reference_kf_id: u64,
1295    config: &CovisibilityLocalMapConfig,
1296) -> HashSet<u64> {
1297    let mut local_landmarks: HashSet<u64> = HashSet::new();
1298
1299    let Some(reference_kf) = map.keyframes.get(&reference_kf_id) else {
1300        return local_landmarks;
1301    };
1302
1303    let reference_landmarks: HashSet<u64> = reference_kf
1304        .observations
1305        .iter()
1306        .map(|obs| obs.landmark_id)
1307        .collect();
1308    if reference_landmarks.is_empty() {
1309        return local_landmarks;
1310    }
1311    local_landmarks.extend(reference_landmarks.iter().copied());
1312
1313    let mut shared_counts: HashMap<u64, usize> = HashMap::new();
1314    for landmark_id in &reference_landmarks {
1315        let Some(landmark) = map.landmarks.get(landmark_id) else {
1316            continue;
1317        };
1318        for obs in &landmark.observations {
1319            let kf_id = obs.frame_id;
1320            if kf_id == reference_kf_id {
1321                continue;
1322            }
1323            if !map.keyframes.contains_key(&kf_id) {
1324                continue;
1325            }
1326            *shared_counts.entry(kf_id).or_insert(0) += 1;
1327        }
1328    }
1329
1330    let mut ranked: Vec<(u64, usize)> = shared_counts
1331        .into_iter()
1332        .filter(|(_, count)| *count >= config.min_shared_landmarks)
1333        .collect();
1334    ranked.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1335    if let Some(cap) = config.max_keyframes {
1336        ranked.truncate(cap);
1337    }
1338
1339    for (kf_id, _) in &ranked {
1340        if let Some(kf) = map.keyframes.get(kf_id) {
1341            for obs in &kf.observations {
1342                local_landmarks.insert(obs.landmark_id);
1343            }
1344        }
1345    }
1346
1347    local_landmarks
1348}
1349
1350impl<X, P, M> ImageTracker<X, Tracker<P, M>>
1351where
1352    X: FeatureExtractor,
1353    P: FrameLocalizer,
1354    M: MotionModel,
1355{
1356    pub fn reset(&mut self) {
1357        self.tracker.reset();
1358    }
1359
1360    pub fn track_frame_image(
1361        &mut self,
1362        frame_id: FrameId,
1363        camera_id: CameraId,
1364        image: &X::Image,
1365        map: &VisualMap,
1366    ) -> Result<TrackingResult, X::Error> {
1367        let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
1368        self.track_frame_image_with_descriptor_store(
1369            frame_id,
1370            camera_id,
1371            image,
1372            map,
1373            &descriptor_store,
1374        )
1375    }
1376
1377    pub fn track_frame_images<'a, I>(
1378        &mut self,
1379        frames: I,
1380        map: &VisualMap,
1381    ) -> Result<Vec<TrackingResult>, X::Error>
1382    where
1383        X::Image: 'a,
1384        I: IntoIterator<Item = (FrameId, CameraId, &'a X::Image)>,
1385    {
1386        let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
1387        self.track_frame_images_with_descriptor_store(frames, map, &descriptor_store)
1388    }
1389
1390    pub fn track_frame_image_with_descriptor_store(
1391        &mut self,
1392        frame_id: FrameId,
1393        camera_id: CameraId,
1394        image: &X::Image,
1395        map: &VisualMap,
1396        descriptor_store: &LandmarkDescriptorStore,
1397    ) -> Result<TrackingResult, X::Error> {
1398        let features = self.extractor.extract(image)?;
1399        let frame = frame_from_features(frame_id, camera_id, features);
1400        Ok(self
1401            .tracker
1402            .track_frame_with_descriptor_store(&frame, map, descriptor_store))
1403    }
1404
1405    pub fn track_frame_images_with_descriptor_store<'a, I>(
1406        &mut self,
1407        frames: I,
1408        map: &VisualMap,
1409        descriptor_store: &LandmarkDescriptorStore,
1410    ) -> Result<Vec<TrackingResult>, X::Error>
1411    where
1412        X::Image: 'a,
1413        I: IntoIterator<Item = (FrameId, CameraId, &'a X::Image)>,
1414    {
1415        let mut results = Vec::new();
1416        for (frame_id, camera_id, image) in frames {
1417            results.push(self.track_frame_image_with_descriptor_store(
1418                frame_id,
1419                camera_id,
1420                image,
1421                map,
1422                descriptor_store,
1423            )?);
1424        }
1425        Ok(results)
1426    }
1427
1428    pub fn track_frame_image_with_provider<P2>(
1429        &mut self,
1430        frame_id: FrameId,
1431        camera_id: CameraId,
1432        image: &X::Image,
1433        provider: &P2,
1434    ) -> Result<TrackingResult, X::Error>
1435    where
1436        P2: MapProvider + DescriptorProvider,
1437    {
1438        let features = self.extractor.extract(image)?;
1439        let frame = frame_from_features(frame_id, camera_id, features);
1440        Ok(self.tracker.track_frame_with_provider(&frame, provider))
1441    }
1442
1443    pub fn track_frame_images_with_provider<'a, I, P2>(
1444        &mut self,
1445        frames: I,
1446        provider: &P2,
1447    ) -> Result<Vec<TrackingResult>, X::Error>
1448    where
1449        X::Image: 'a,
1450        I: IntoIterator<Item = (FrameId, CameraId, &'a X::Image)>,
1451        P2: MapProvider + DescriptorProvider,
1452    {
1453        let mut results = Vec::new();
1454        for (frame_id, camera_id, image) in frames {
1455            results
1456                .push(self.track_frame_image_with_provider(frame_id, camera_id, image, provider)?);
1457        }
1458        Ok(results)
1459    }
1460
1461    pub fn track_frame_image_with_prior_submap_provider<P2>(
1462        &mut self,
1463        frame_id: FrameId,
1464        camera_id: CameraId,
1465        image: &X::Image,
1466        provider: &P2,
1467        radius: f64,
1468    ) -> Result<TrackingResult, X::Error>
1469    where
1470        P2: MapProvider + DescriptorProvider,
1471    {
1472        let features = self.extractor.extract(image)?;
1473        let frame = frame_from_features(frame_id, camera_id, features);
1474        Ok(self
1475            .tracker
1476            .track_frame_with_prior_submap_provider(&frame, provider, radius))
1477    }
1478
1479    pub fn track_frame_image_with_localization_prior_submap_provider<P2>(
1480        &mut self,
1481        frame_id: FrameId,
1482        camera_id: CameraId,
1483        image: &X::Image,
1484        provider: &P2,
1485        prior: &LocalizationPrior,
1486    ) -> Result<TrackingResult, X::Error>
1487    where
1488        P2: MapProvider + DescriptorProvider,
1489    {
1490        let features = self.extractor.extract(image)?;
1491        let frame = frame_from_features(frame_id, camera_id, features);
1492        Ok(self
1493            .tracker
1494            .track_frame_with_localization_prior_submap_provider(&frame, provider, prior))
1495    }
1496
1497    pub fn track_frame_images_with_prior_submap_provider<'a, I, P2>(
1498        &mut self,
1499        frames: I,
1500        provider: &P2,
1501        radius: f64,
1502    ) -> Result<Vec<TrackingResult>, X::Error>
1503    where
1504        X::Image: 'a,
1505        I: IntoIterator<Item = (FrameId, CameraId, &'a X::Image)>,
1506        P2: MapProvider + DescriptorProvider,
1507    {
1508        let mut results = Vec::new();
1509        for (frame_id, camera_id, image) in frames {
1510            results.push(self.track_frame_image_with_prior_submap_provider(
1511                frame_id, camera_id, image, provider, radius,
1512            )?);
1513        }
1514        Ok(results)
1515    }
1516}
1517
1518fn frame_from_features(frame_id: FrameId, camera_id: CameraId, features: FeatureSet) -> Frame {
1519    Frame {
1520        id: frame_id,
1521        camera_id,
1522        keypoints: features.keypoints,
1523        descriptors: features.descriptors,
1524        pose: None,
1525    }
1526}
1527
1528pub trait FrameLocalizer {
1529    fn localize_frame_with_descriptor_store(
1530        &self,
1531        frame: &Frame,
1532        map: &VisualMap,
1533        descriptor_store: &LandmarkDescriptorStore,
1534    ) -> LocalizationResult;
1535
1536    fn localize_frame_with_pose_prior_and_descriptor_store(
1537        &self,
1538        frame: &Frame,
1539        map: &VisualMap,
1540        descriptor_store: &LandmarkDescriptorStore,
1541        _pose_prior: Option<&Pose>,
1542        _candidate_radius: Option<f64>,
1543    ) -> LocalizationResult {
1544        self.localize_frame_with_descriptor_store(frame, map, descriptor_store)
1545    }
1546
1547    /// Variant that, in addition to the radius candidate filter, ALSO threads
1548    /// the pose prior into the PnP RANSAC as a warm-start hypothesis. Default
1549    /// impl falls back to the non-warm-start variant so existing implementors
1550    /// don't need to change.
1551    fn localize_frame_with_pose_prior_warm_start_and_descriptor_store(
1552        &self,
1553        frame: &Frame,
1554        map: &VisualMap,
1555        descriptor_store: &LandmarkDescriptorStore,
1556        pose_prior: Option<&Pose>,
1557        candidate_radius: Option<f64>,
1558    ) -> LocalizationResult {
1559        self.localize_frame_with_pose_prior_and_descriptor_store(
1560            frame,
1561            map,
1562            descriptor_store,
1563            pose_prior,
1564            candidate_radius,
1565        )
1566    }
1567
1568    /// ORB-SLAM3-style projection-guided variant: for each candidate
1569    /// landmark, project it into the frame with `pose_prior` and match its
1570    /// descriptor only against query keypoints within `search_radius_px` of
1571    /// the projection (rather than an appearance-global search over the
1572    /// whole candidate set). Default implementation ignores the projection
1573    /// window and falls back to the appearance-global
1574    /// `_pose_prior_and_descriptor_store` variant, so a `FrameLocalizer`
1575    /// implementor that hasn't opted in still produces a (non-projection)
1576    /// result the tracker's widen-retry ladder can fall through to.
1577    fn localize_frame_with_projection_window_and_descriptor_store(
1578        &self,
1579        frame: &Frame,
1580        map: &VisualMap,
1581        descriptor_store: &LandmarkDescriptorStore,
1582        pose_prior: &Pose,
1583        candidate_radius: Option<f64>,
1584        _search_radius_px: f64,
1585    ) -> LocalizationResult {
1586        self.localize_frame_with_pose_prior_and_descriptor_store(
1587            frame,
1588            map,
1589            descriptor_store,
1590            Some(pose_prior),
1591            candidate_radius,
1592        )
1593    }
1594
1595    /// Projection-guided localization with an additional reverse
1596    /// query-keypoint -> landmark ambiguity ratio. Implementors without a
1597    /// specialized path retain the projection/default behavior above.
1598    #[allow(clippy::too_many_arguments)]
1599    fn localize_frame_with_projection_window_descriptor_store_and_query_landmark_ratio(
1600        &self,
1601        frame: &Frame,
1602        map: &VisualMap,
1603        descriptor_store: &LandmarkDescriptorStore,
1604        pose_prior: &Pose,
1605        candidate_radius: Option<f64>,
1606        search_radius_px: f64,
1607        _max_query_landmark_distance_ratio: Option<f32>,
1608    ) -> LocalizationResult {
1609        self.localize_frame_with_projection_window_and_descriptor_store(
1610            frame,
1611            map,
1612            descriptor_store,
1613            pose_prior,
1614            candidate_radius,
1615            search_radius_px,
1616        )
1617    }
1618
1619    /// Stage-3 local-map refinement: given an already-successful `estimated`
1620    /// localization, project `local_map_descriptor_store`'s landmarks with
1621    /// the ESTIMATED pose and harvest additional correspondences within
1622    /// `refinement_search_radius_px`, then re-run pose estimation over the
1623    /// union with `estimated`'s inliers. Returns `None` when the implementor
1624    /// doesn't support refinement (default) or no usable correspondences
1625    /// could be harvested; callers (see `Tracker`) independently gate
1626    /// acceptance on inlier count, since this method does not compare
1627    /// against `estimated` itself.
1628    fn refine_pose_with_local_map_and_descriptor_store(
1629        &self,
1630        _frame: &Frame,
1631        _map: &VisualMap,
1632        _local_map_descriptor_store: &LandmarkDescriptorStore,
1633        _estimated: &LocalizationResult,
1634        _refinement_search_radius_px: f64,
1635    ) -> Option<LocalizationResult> {
1636        None
1637    }
1638
1639    /// Rebuild projection-guided correspondences from scratch around the
1640    /// latest pose so 2D keypoints can change landmark assignment between
1641    /// rounds. Implementors without a specialized revision path retain the
1642    /// conservative refinement behavior.
1643    fn revise_pose_with_local_map_and_descriptor_store(
1644        &self,
1645        frame: &Frame,
1646        map: &VisualMap,
1647        local_map_descriptor_store: &LandmarkDescriptorStore,
1648        estimated: &LocalizationResult,
1649        refinement_search_radius_px: f64,
1650    ) -> Option<LocalizationResult> {
1651        self.refine_pose_with_local_map_and_descriptor_store(
1652            frame,
1653            map,
1654            local_map_descriptor_store,
1655            estimated,
1656            refinement_search_radius_px,
1657        )
1658    }
1659}
1660
1661impl<M, S, E> FrameLocalizer for LocalizationPipeline<M, S, E>
1662where
1663    M: Matcher + Clone,
1664    S: CandidateSelector + Clone,
1665    E: RobustPoseEstimator + Clone,
1666{
1667    fn localize_frame_with_descriptor_store(
1668        &self,
1669        frame: &Frame,
1670        map: &VisualMap,
1671        descriptor_store: &LandmarkDescriptorStore,
1672    ) -> LocalizationResult {
1673        LocalizationPipeline::localize_frame_with_descriptor_store(
1674            self,
1675            frame,
1676            map,
1677            descriptor_store,
1678        )
1679    }
1680
1681    fn localize_frame_with_pose_prior_and_descriptor_store(
1682        &self,
1683        frame: &Frame,
1684        map: &VisualMap,
1685        descriptor_store: &LandmarkDescriptorStore,
1686        pose_prior: Option<&Pose>,
1687        candidate_radius: Option<f64>,
1688    ) -> LocalizationResult {
1689        let Some(radius) = candidate_radius else {
1690            return self.localize_frame_with_descriptor_store(frame, map, descriptor_store);
1691        };
1692        let Some(pose_prior) = pose_prior else {
1693            return self.localize_frame_with_descriptor_store(frame, map, descriptor_store);
1694        };
1695
1696        let radius_selector = RadiusLandmarkSelector::new(pose_prior.camera_center_world(), radius);
1697        let candidate_selector =
1698            IntersectCandidateSelector::new(self.candidate_selector.clone(), radius_selector);
1699
1700        LocalizationPipeline::localize_frame_with_candidate_selector_and_descriptor_store(
1701            self,
1702            frame,
1703            map,
1704            descriptor_store,
1705            candidate_selector,
1706        )
1707    }
1708
1709    fn localize_frame_with_pose_prior_warm_start_and_descriptor_store(
1710        &self,
1711        frame: &Frame,
1712        map: &VisualMap,
1713        descriptor_store: &LandmarkDescriptorStore,
1714        pose_prior: Option<&Pose>,
1715        candidate_radius: Option<f64>,
1716    ) -> LocalizationResult {
1717        let Some(pose_prior) = pose_prior else {
1718            return self.localize_frame_with_descriptor_store(frame, map, descriptor_store);
1719        };
1720        let Some(camera) = map.cameras.get(&frame.camera_id).cloned() else {
1721            return LocalizationResult::failure(
1722                LocalizationFailureReason::MissingCamera {
1723                    camera_id: frame.camera_id,
1724                },
1725                0,
1726                0,
1727                0,
1728            );
1729        };
1730        let query = QueryImage::from_frame(frame, camera);
1731
1732        if let Some(radius) = candidate_radius {
1733            let radius_selector =
1734                RadiusLandmarkSelector::new(pose_prior.camera_center_world(), radius);
1735            let candidate_selector =
1736                IntersectCandidateSelector::new(self.candidate_selector.clone(), radius_selector);
1737            self.localize_with_candidate_selector_and_descriptor_store_and_pose_prior(
1738                &query,
1739                map,
1740                descriptor_store,
1741                candidate_selector,
1742                Some(pose_prior),
1743            )
1744        } else {
1745            self.localize_with_candidate_selector_and_descriptor_store_and_pose_prior(
1746                &query,
1747                map,
1748                descriptor_store,
1749                self.candidate_selector.clone(),
1750                Some(pose_prior),
1751            )
1752        }
1753    }
1754
1755    fn localize_frame_with_projection_window_and_descriptor_store(
1756        &self,
1757        frame: &Frame,
1758        map: &VisualMap,
1759        descriptor_store: &LandmarkDescriptorStore,
1760        pose_prior: &Pose,
1761        candidate_radius: Option<f64>,
1762        search_radius_px: f64,
1763    ) -> LocalizationResult {
1764        LocalizationPipeline::localize_frame_with_projection_window_and_descriptor_store(
1765            self,
1766            frame,
1767            map,
1768            descriptor_store,
1769            pose_prior,
1770            candidate_radius,
1771            search_radius_px,
1772        )
1773    }
1774
1775    #[allow(clippy::too_many_arguments)]
1776    fn localize_frame_with_projection_window_descriptor_store_and_query_landmark_ratio(
1777        &self,
1778        frame: &Frame,
1779        map: &VisualMap,
1780        descriptor_store: &LandmarkDescriptorStore,
1781        pose_prior: &Pose,
1782        candidate_radius: Option<f64>,
1783        search_radius_px: f64,
1784        max_query_landmark_distance_ratio: Option<f32>,
1785    ) -> LocalizationResult {
1786        LocalizationPipeline::localize_frame_with_projection_window_descriptor_store_and_query_landmark_ratio(
1787            self,
1788            frame,
1789            map,
1790            descriptor_store,
1791            pose_prior,
1792            candidate_radius,
1793            search_radius_px,
1794            max_query_landmark_distance_ratio,
1795        )
1796    }
1797
1798    fn refine_pose_with_local_map_and_descriptor_store(
1799        &self,
1800        frame: &Frame,
1801        map: &VisualMap,
1802        local_map_descriptor_store: &LandmarkDescriptorStore,
1803        estimated: &LocalizationResult,
1804        refinement_search_radius_px: f64,
1805    ) -> Option<LocalizationResult> {
1806        LocalizationPipeline::refine_frame_pose_with_local_map_and_descriptor_store(
1807            self,
1808            frame,
1809            map,
1810            local_map_descriptor_store,
1811            estimated,
1812            refinement_search_radius_px,
1813        )
1814    }
1815
1816    fn revise_pose_with_local_map_and_descriptor_store(
1817        &self,
1818        frame: &Frame,
1819        map: &VisualMap,
1820        local_map_descriptor_store: &LandmarkDescriptorStore,
1821        estimated: &LocalizationResult,
1822        refinement_search_radius_px: f64,
1823    ) -> Option<LocalizationResult> {
1824        LocalizationPipeline::revise_frame_pose_with_local_map_and_descriptor_store(
1825            self,
1826            frame,
1827            map,
1828            local_map_descriptor_store,
1829            estimated,
1830            refinement_search_radius_px,
1831        )
1832    }
1833}
1834
1835#[derive(Debug, Clone, Default, PartialEq, Eq)]
1836pub struct TrackingStats {
1837    pub first_frame_id: Option<FrameId>,
1838    pub last_frame_id: Option<FrameId>,
1839    pub frame_count: usize,
1840    pub successful_frame_count: usize,
1841    pub failed_frame_count: usize,
1842    pub lost_count: usize,
1843    pub relocalization_count: usize,
1844    pub pose_prior_used_count: usize,
1845    pub external_localization_prior_used_count: usize,
1846    pub tracking_quality_gate_failure_count: usize,
1847    /// Number of frames accepted only because a strong visual solution
1848    /// activated the bounded pose-prior translation-gate widening.
1849    pub pose_prior_visual_override_count: usize,
1850    /// Number of frames accepted by substituting the motion-model prior
1851    /// after visual localization / quality gates failed.
1852    pub motion_prior_coast_count: usize,
1853    /// Temporal-landmark-track attempts (previous-inlier descriptor store).
1854    pub temporal_landmark_attempt_count: usize,
1855    /// Temporal-landmark-track attempts that produced a successful pose.
1856    pub temporal_landmark_success_count: usize,
1857    pub total_inlier_count: usize,
1858    pub total_correspondence_count: usize,
1859    pub covisibility_local_map_used_count: usize,
1860    /// Number of stage-1 projection-guided pose-estimation attempts made
1861    /// across all frames (one per widen-retry rung tried, including the
1862    /// first). Zero when `projection_guided_tracking` is disabled or no pose
1863    /// prior was available for a frame. Populated live by `Tracker`; unlike
1864    /// most other counters here, NOT reconstructed by
1865    /// [`TrackingStats::from_results`] (the per-attempt detail is not carried
1866    /// on `TrackingResult`).
1867    pub projection_guided_attempt_count: usize,
1868    /// Number of widen-retry rungs actually taken (i.e. attempts beyond the
1869    /// first that used a widened radius after the previous rung failed the
1870    /// quality gate).
1871    pub projection_guided_widen_retry_count: usize,
1872    /// Number of frames where a projection-guided attempt (at any widen
1873    /// rung) produced the accepted pose estimate.
1874    pub projection_guided_success_count: usize,
1875    /// Number of frames where every projection-guided attempt failed and
1876    /// the appearance-global fallback path produced the accepted pose
1877    /// estimate.
1878    pub projection_guided_fallback_success_count: usize,
1879    /// Sum, across frames where local-map refinement ran, of additional
1880    /// correspondences harvested beyond the pre-refinement correspondence
1881    /// count (0 when refinement harvested nothing new).
1882    pub local_map_refinement_correspondence_gain_total: usize,
1883    /// Number of frames where local-map refinement ran and its result was
1884    /// accepted (inlier count did not decrease).
1885    pub local_map_refinement_accepted_count: usize,
1886    /// Number of frames where local-map refinement ran but was rejected
1887    /// (inlier count decreased, or the refined estimate failed its own
1888    /// quality gate).
1889    pub local_map_refinement_rejected_count: usize,
1890}
1891
1892#[derive(Debug, Clone, Default, PartialEq)]
1893pub struct TrackingEvaluationConfig {
1894    pub min_success_rate: Option<f64>,
1895    pub max_failure_rate: Option<f64>,
1896    pub max_lost_count: Option<usize>,
1897    pub max_tracking_quality_gate_failure_count: Option<usize>,
1898    pub min_external_localization_prior_usage_rate: Option<f64>,
1899    pub min_overall_inlier_ratio: Option<f64>,
1900    pub min_mean_inliers_per_successful_frame: Option<f64>,
1901}
1902
1903#[derive(Debug, Clone, PartialEq)]
1904pub struct TrackingEvaluationResult {
1905    pub passed: bool,
1906    pub stats: TrackingStats,
1907    pub config: TrackingEvaluationConfig,
1908    pub failures: Vec<TrackingEvaluationFailure>,
1909}
1910
1911#[derive(Debug, Clone, PartialEq)]
1912pub enum TrackingEvaluationFailure {
1913    SuccessRateTooLow { actual: f64, minimum: f64 },
1914    FailureRateTooHigh { actual: f64, maximum: f64 },
1915    LostCountTooHigh { actual: usize, maximum: usize },
1916    QualityGateFailureCountTooHigh { actual: usize, maximum: usize },
1917    ExternalLocalizationPriorUsageRateTooLow { actual: f64, minimum: f64 },
1918    OverallInlierRatioTooLow { actual: f64, minimum: f64 },
1919    MeanInliersPerSuccessfulFrameTooLow { actual: f64, minimum: f64 },
1920}
1921
1922impl TrackingStats {
1923    pub fn from_results(results: &[TrackingResult]) -> Self {
1924        let mut stats = Self::default();
1925        for result in results {
1926            if stats.first_frame_id.is_none() {
1927                stats.first_frame_id = Some(result.frame_id);
1928            }
1929            stats.last_frame_id = Some(result.frame_id);
1930            stats.frame_count += 1;
1931            if result.localization.success {
1932                stats.successful_frame_count += 1;
1933            } else {
1934                stats.failed_frame_count += 1;
1935            }
1936            if result.event == TrackingEvent::Lost {
1937                stats.lost_count += 1;
1938            }
1939            if result.event == TrackingEvent::Relocalized {
1940                stats.relocalization_count += 1;
1941            }
1942            if result.used_pose_prior {
1943                stats.pose_prior_used_count += 1;
1944            }
1945            if result.used_external_localization_prior {
1946                stats.external_localization_prior_used_count += 1;
1947            }
1948            if result.tracking_failure_reason.is_some() {
1949                stats.tracking_quality_gate_failure_count += 1;
1950            }
1951            stats.total_inlier_count += result.localization.inlier_count;
1952            stats.total_correspondence_count += result.localization.correspondence_count;
1953            if result.covisibility_local_map_size.is_some() {
1954                stats.covisibility_local_map_used_count += 1;
1955            }
1956        }
1957        stats
1958    }
1959
1960    pub fn success_rate(&self) -> f64 {
1961        ratio(self.successful_frame_count, self.frame_count)
1962    }
1963
1964    pub fn failure_rate(&self) -> f64 {
1965        ratio(self.failed_frame_count, self.frame_count)
1966    }
1967
1968    pub fn pose_prior_usage_rate(&self) -> f64 {
1969        ratio(self.pose_prior_used_count, self.frame_count)
1970    }
1971
1972    pub fn external_localization_prior_usage_rate(&self) -> f64 {
1973        ratio(
1974            self.external_localization_prior_used_count,
1975            self.frame_count,
1976        )
1977    }
1978
1979    pub fn overall_inlier_ratio(&self) -> f64 {
1980        ratio(self.total_inlier_count, self.total_correspondence_count)
1981    }
1982
1983    pub fn mean_inliers_per_successful_frame(&self) -> f64 {
1984        ratio(self.total_inlier_count, self.successful_frame_count)
1985    }
1986
1987    pub fn to_json(&self) -> String {
1988        format!(
1989            concat!(
1990                "{{\n",
1991                "  \"first_frame_id\": {},\n",
1992                "  \"last_frame_id\": {},\n",
1993                "  \"frame_count\": {},\n",
1994                "  \"successful_frame_count\": {},\n",
1995                "  \"failed_frame_count\": {},\n",
1996                "  \"lost_count\": {},\n",
1997                "  \"relocalization_count\": {},\n",
1998                "  \"pose_prior_used_count\": {},\n",
1999                "  \"external_localization_prior_used_count\": {},\n",
2000                "  \"tracking_quality_gate_failure_count\": {},\n",
2001                "  \"total_inlier_count\": {},\n",
2002                "  \"total_correspondence_count\": {},\n",
2003                "  \"success_rate\": {},\n",
2004                "  \"failure_rate\": {},\n",
2005                "  \"pose_prior_usage_rate\": {},\n",
2006                "  \"external_localization_prior_usage_rate\": {},\n",
2007                "  \"overall_inlier_ratio\": {},\n",
2008                "  \"mean_inliers_per_successful_frame\": {},\n",
2009                "  \"projection_guided_attempt_count\": {},\n",
2010                "  \"projection_guided_widen_retry_count\": {},\n",
2011                "  \"projection_guided_success_count\": {},\n",
2012                "  \"projection_guided_fallback_success_count\": {},\n",
2013                "  \"local_map_refinement_correspondence_gain_total\": {},\n",
2014                "  \"local_map_refinement_accepted_count\": {},\n",
2015                "  \"local_map_refinement_rejected_count\": {}\n",
2016                "}}\n"
2017            ),
2018            optional_frame_id_json(self.first_frame_id),
2019            optional_frame_id_json(self.last_frame_id),
2020            self.frame_count,
2021            self.successful_frame_count,
2022            self.failed_frame_count,
2023            self.lost_count,
2024            self.relocalization_count,
2025            self.pose_prior_used_count,
2026            self.external_localization_prior_used_count,
2027            self.tracking_quality_gate_failure_count,
2028            self.total_inlier_count,
2029            self.total_correspondence_count,
2030            self.success_rate(),
2031            self.failure_rate(),
2032            self.pose_prior_usage_rate(),
2033            self.external_localization_prior_usage_rate(),
2034            self.overall_inlier_ratio(),
2035            self.mean_inliers_per_successful_frame(),
2036            self.projection_guided_attempt_count,
2037            self.projection_guided_widen_retry_count,
2038            self.projection_guided_success_count,
2039            self.projection_guided_fallback_success_count,
2040            self.local_map_refinement_correspondence_gain_total,
2041            self.local_map_refinement_accepted_count,
2042            self.local_map_refinement_rejected_count,
2043        )
2044    }
2045
2046    fn to_json_inline(&self) -> String {
2047        format!(
2048            concat!(
2049                "{{",
2050                "\"first_frame_id\": {}, ",
2051                "\"last_frame_id\": {}, ",
2052                "\"frame_count\": {}, ",
2053                "\"successful_frame_count\": {}, ",
2054                "\"failed_frame_count\": {}, ",
2055                "\"lost_count\": {}, ",
2056                "\"relocalization_count\": {}, ",
2057                "\"pose_prior_used_count\": {}, ",
2058                "\"external_localization_prior_used_count\": {}, ",
2059                "\"tracking_quality_gate_failure_count\": {}, ",
2060                "\"total_inlier_count\": {}, ",
2061                "\"total_correspondence_count\": {}, ",
2062                "\"success_rate\": {}, ",
2063                "\"failure_rate\": {}, ",
2064                "\"pose_prior_usage_rate\": {}, ",
2065                "\"external_localization_prior_usage_rate\": {}, ",
2066                "\"overall_inlier_ratio\": {}, ",
2067                "\"mean_inliers_per_successful_frame\": {}, ",
2068                "\"projection_guided_attempt_count\": {}, ",
2069                "\"projection_guided_widen_retry_count\": {}, ",
2070                "\"projection_guided_success_count\": {}, ",
2071                "\"projection_guided_fallback_success_count\": {}, ",
2072                "\"local_map_refinement_correspondence_gain_total\": {}, ",
2073                "\"local_map_refinement_accepted_count\": {}, ",
2074                "\"local_map_refinement_rejected_count\": {}",
2075                "}}"
2076            ),
2077            optional_frame_id_json(self.first_frame_id),
2078            optional_frame_id_json(self.last_frame_id),
2079            self.frame_count,
2080            self.successful_frame_count,
2081            self.failed_frame_count,
2082            self.lost_count,
2083            self.relocalization_count,
2084            self.pose_prior_used_count,
2085            self.external_localization_prior_used_count,
2086            self.tracking_quality_gate_failure_count,
2087            self.total_inlier_count,
2088            self.total_correspondence_count,
2089            self.success_rate(),
2090            self.failure_rate(),
2091            self.pose_prior_usage_rate(),
2092            self.external_localization_prior_usage_rate(),
2093            self.overall_inlier_ratio(),
2094            self.mean_inliers_per_successful_frame(),
2095            self.projection_guided_attempt_count,
2096            self.projection_guided_widen_retry_count,
2097            self.projection_guided_success_count,
2098            self.projection_guided_fallback_success_count,
2099            self.local_map_refinement_correspondence_gain_total,
2100            self.local_map_refinement_accepted_count,
2101            self.local_map_refinement_rejected_count,
2102        )
2103    }
2104
2105    pub fn write_json(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
2106        std::fs::write(path, self.to_json())
2107    }
2108
2109    pub fn evaluate(&self, config: TrackingEvaluationConfig) -> TrackingEvaluationResult {
2110        TrackingEvaluationResult::from_stats(self.clone(), config)
2111    }
2112}
2113
2114impl TrackingEvaluationResult {
2115    pub fn from_stats(stats: TrackingStats, config: TrackingEvaluationConfig) -> Self {
2116        let mut failures = Vec::new();
2117
2118        if let Some(minimum) = config.min_success_rate {
2119            let actual = stats.success_rate();
2120            if actual < minimum {
2121                failures.push(TrackingEvaluationFailure::SuccessRateTooLow { actual, minimum });
2122            }
2123        }
2124
2125        if let Some(maximum) = config.max_failure_rate {
2126            let actual = stats.failure_rate();
2127            if actual > maximum {
2128                failures.push(TrackingEvaluationFailure::FailureRateTooHigh { actual, maximum });
2129            }
2130        }
2131
2132        if let Some(maximum) = config.max_lost_count {
2133            if stats.lost_count > maximum {
2134                failures.push(TrackingEvaluationFailure::LostCountTooHigh {
2135                    actual: stats.lost_count,
2136                    maximum,
2137                });
2138            }
2139        }
2140
2141        if let Some(maximum) = config.max_tracking_quality_gate_failure_count {
2142            if stats.tracking_quality_gate_failure_count > maximum {
2143                failures.push(TrackingEvaluationFailure::QualityGateFailureCountTooHigh {
2144                    actual: stats.tracking_quality_gate_failure_count,
2145                    maximum,
2146                });
2147            }
2148        }
2149
2150        if let Some(minimum) = config.min_external_localization_prior_usage_rate {
2151            let actual = stats.external_localization_prior_usage_rate();
2152            if actual < minimum {
2153                failures.push(
2154                    TrackingEvaluationFailure::ExternalLocalizationPriorUsageRateTooLow {
2155                        actual,
2156                        minimum,
2157                    },
2158                );
2159            }
2160        }
2161
2162        if let Some(minimum) = config.min_overall_inlier_ratio {
2163            let actual = stats.overall_inlier_ratio();
2164            if actual < minimum {
2165                failures
2166                    .push(TrackingEvaluationFailure::OverallInlierRatioTooLow { actual, minimum });
2167            }
2168        }
2169
2170        if let Some(minimum) = config.min_mean_inliers_per_successful_frame {
2171            let actual = stats.mean_inliers_per_successful_frame();
2172            if actual < minimum {
2173                failures.push(
2174                    TrackingEvaluationFailure::MeanInliersPerSuccessfulFrameTooLow {
2175                        actual,
2176                        minimum,
2177                    },
2178                );
2179            }
2180        }
2181
2182        let passed = failures.is_empty();
2183        Self {
2184            passed,
2185            stats,
2186            config,
2187            failures,
2188        }
2189    }
2190
2191    pub fn to_json(&self) -> String {
2192        format!(
2193            concat!(
2194                "{{\n",
2195                "  \"passed\": {},\n",
2196                "  \"config\": {},\n",
2197                "  \"stats\": {},\n",
2198                "  \"failures\": {}\n",
2199                "}}\n"
2200            ),
2201            self.passed,
2202            self.config.to_json_inline(),
2203            self.stats.to_json_inline(),
2204            tracking_evaluation_failures_json(&self.failures)
2205        )
2206    }
2207
2208    pub fn write_json(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
2209        std::fs::write(path, self.to_json())
2210    }
2211}
2212
2213impl TrackingEvaluationConfig {
2214    fn to_json_inline(&self) -> String {
2215        format!(
2216            concat!(
2217                "{{",
2218                "\"min_success_rate\": {}, ",
2219                "\"max_failure_rate\": {}, ",
2220                "\"max_lost_count\": {}, ",
2221                "\"max_tracking_quality_gate_failure_count\": {}, ",
2222                "\"min_external_localization_prior_usage_rate\": {}, ",
2223                "\"min_overall_inlier_ratio\": {}, ",
2224                "\"min_mean_inliers_per_successful_frame\": {}",
2225                "}}"
2226            ),
2227            optional_f64_json(self.min_success_rate),
2228            optional_f64_json(self.max_failure_rate),
2229            optional_usize_json(self.max_lost_count),
2230            optional_usize_json(self.max_tracking_quality_gate_failure_count),
2231            optional_f64_json(self.min_external_localization_prior_usage_rate),
2232            optional_f64_json(self.min_overall_inlier_ratio),
2233            optional_f64_json(self.min_mean_inliers_per_successful_frame)
2234        )
2235    }
2236}
2237
2238impl TrackingEvaluationFailure {
2239    pub const fn reason(&self) -> &'static str {
2240        match self {
2241            Self::SuccessRateTooLow { .. } => "success_rate_too_low",
2242            Self::FailureRateTooHigh { .. } => "failure_rate_too_high",
2243            Self::LostCountTooHigh { .. } => "lost_count_too_high",
2244            Self::QualityGateFailureCountTooHigh { .. } => "quality_gate_failure_count_too_high",
2245            Self::ExternalLocalizationPriorUsageRateTooLow { .. } => {
2246                "external_localization_prior_usage_rate_too_low"
2247            }
2248            Self::OverallInlierRatioTooLow { .. } => "overall_inlier_ratio_too_low",
2249            Self::MeanInliersPerSuccessfulFrameTooLow { .. } => {
2250                "mean_inliers_per_successful_frame_too_low"
2251            }
2252        }
2253    }
2254
2255    fn to_json_inline(&self) -> String {
2256        match self {
2257            Self::SuccessRateTooLow { actual, minimum }
2258            | Self::ExternalLocalizationPriorUsageRateTooLow { actual, minimum }
2259            | Self::OverallInlierRatioTooLow { actual, minimum }
2260            | Self::MeanInliersPerSuccessfulFrameTooLow { actual, minimum } => format!(
2261                "{{\"reason\": \"{}\", \"actual\": {}, \"minimum\": {}}}",
2262                self.reason(),
2263                actual,
2264                minimum
2265            ),
2266            Self::FailureRateTooHigh { actual, maximum } => format!(
2267                "{{\"reason\": \"{}\", \"actual\": {}, \"maximum\": {}}}",
2268                self.reason(),
2269                actual,
2270                maximum
2271            ),
2272            Self::LostCountTooHigh { actual, maximum }
2273            | Self::QualityGateFailureCountTooHigh { actual, maximum } => format!(
2274                "{{\"reason\": \"{}\", \"actual\": {}, \"maximum\": {}}}",
2275                self.reason(),
2276                actual,
2277                maximum
2278            ),
2279        }
2280    }
2281}
2282
2283fn tracking_evaluation_failures_json(failures: &[TrackingEvaluationFailure]) -> String {
2284    let mut output = String::from("[");
2285    for (index, failure) in failures.iter().enumerate() {
2286        if index > 0 {
2287            output.push_str(", ");
2288        }
2289        output.push_str(&failure.to_json_inline());
2290    }
2291    output.push(']');
2292    output
2293}
2294
2295fn ratio(numerator: usize, denominator: usize) -> f64 {
2296    if denominator == 0 {
2297        0.0
2298    } else {
2299        numerator as f64 / denominator as f64
2300    }
2301}
2302
2303#[cfg(test)]
2304mod covisibility_local_map_tests {
2305    use super::*;
2306    use nalgebra::Point2;
2307    use visloc_core::types::{Camera, Keyframe, Landmark, Observation};
2308
2309    fn make_camera() -> Camera {
2310        Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0)
2311    }
2312
2313    fn make_keyframe(id: u64) -> Keyframe {
2314        Keyframe {
2315            frame: Frame::new(id, 1),
2316            observations: Vec::new(),
2317        }
2318    }
2319
2320    fn make_landmark(id: u64) -> Landmark {
2321        Landmark::new(id, Point3::new(0.0, 0.0, 5.0))
2322    }
2323
2324    fn link_observation(map: &mut VisualMap, kf_id: u64, landmark_id: u64) {
2325        let obs = Observation {
2326            frame_id: kf_id,
2327            landmark_id,
2328            keypoint_index: 0,
2329            xy: Point2::new(0.0, 0.0),
2330        };
2331        if let Some(kf) = map.keyframes.get_mut(&kf_id) {
2332            kf.observations.push(obs.clone());
2333        }
2334        if let Some(lm) = map.landmarks.get_mut(&landmark_id) {
2335            lm.observations.push(obs);
2336        }
2337    }
2338
2339    fn make_three_kf_map() -> VisualMap {
2340        let mut map = VisualMap::new();
2341        let camera = make_camera();
2342        map.cameras.insert(camera.id, camera);
2343        for kf_id in [1, 2, 3] {
2344            map.keyframes.insert(kf_id, make_keyframe(kf_id));
2345        }
2346        for lm_id in 1..=20 {
2347            map.landmarks.insert(lm_id, make_landmark(lm_id));
2348        }
2349        for lm_id in 1..=10 {
2350            link_observation(&mut map, 1, lm_id);
2351            link_observation(&mut map, 2, lm_id);
2352        }
2353        for lm_id in 11..=15 {
2354            link_observation(&mut map, 2, lm_id);
2355            link_observation(&mut map, 3, lm_id);
2356        }
2357        for lm_id in 16..=20 {
2358            link_observation(&mut map, 3, lm_id);
2359        }
2360        map
2361    }
2362
2363    #[test]
2364    fn picks_exact_keyframe_when_last_frame_id_matches() {
2365        let map = make_three_kf_map();
2366        assert_eq!(covisibility_pick_reference_keyframe(&map, 2), Some(2));
2367    }
2368
2369    #[test]
2370    fn picks_nearest_prior_keyframe_when_last_frame_id_misses() {
2371        let map = make_three_kf_map();
2372        assert_eq!(covisibility_pick_reference_keyframe(&map, 5), Some(3));
2373    }
2374
2375    #[test]
2376    fn returns_none_when_no_keyframe_is_in_past() {
2377        let map = make_three_kf_map();
2378        assert!(covisibility_pick_reference_keyframe(&map, 0).is_none());
2379    }
2380
2381    #[test]
2382    fn covisibility_local_map_includes_reference_landmarks_and_neighbours() {
2383        let map = make_three_kf_map();
2384        let config = CovisibilityLocalMapConfig {
2385            max_keyframes: Some(5),
2386            min_shared_landmarks: 1,
2387            min_local_map_landmarks: 1,
2388        };
2389        let local = covisibility_local_map_landmarks(&map, 2, &config);
2390        // KF=2 sees landmarks {1..=15}. Co-visible with KF=1 (shares 1..=10) and
2391        // KF=3 (shares 11..=15). Union ∪ KF1 ∪ KF3 covers 1..=20.
2392        for lm in 1..=20 {
2393            assert!(local.contains(&lm), "missing landmark {}", lm);
2394        }
2395    }
2396
2397    #[test]
2398    fn covisibility_local_map_drops_low_shared_neighbours() {
2399        let map = make_three_kf_map();
2400        let config = CovisibilityLocalMapConfig {
2401            max_keyframes: Some(5),
2402            min_shared_landmarks: 6, // KF3 shares only 5 with KF2, so it's dropped
2403            min_local_map_landmarks: 1,
2404        };
2405        let local = covisibility_local_map_landmarks(&map, 2, &config);
2406        // KF1 shares 10 with KF2 → kept (landmarks 1..=10 contributed via KF1).
2407        // KF3 shares 5 with KF2 → dropped, so landmarks 16..=20 (only in KF3)
2408        // should NOT appear.
2409        for lm in 1..=15 {
2410            assert!(local.contains(&lm), "expected landmark {}", lm);
2411        }
2412        for lm in 16..=20 {
2413            assert!(!local.contains(&lm), "unexpected landmark {}", lm);
2414        }
2415    }
2416
2417    #[test]
2418    fn covisibility_local_map_respects_max_keyframes_cap() {
2419        let map = make_three_kf_map();
2420        let config = CovisibilityLocalMapConfig {
2421            max_keyframes: Some(1), // only the strongest neighbour
2422            min_shared_landmarks: 1,
2423            min_local_map_landmarks: 1,
2424        };
2425        let local = covisibility_local_map_landmarks(&map, 2, &config);
2426        // Strongest neighbour of KF2 is KF1 (10 shared) > KF3 (5 shared).
2427        // So KF3-only landmarks (16..=20) must NOT appear.
2428        for lm in 16..=20 {
2429            assert!(!local.contains(&lm), "unexpected landmark {} from KF3", lm);
2430        }
2431        // But reference-only landmarks 11..=15 (only in KF2 + KF3) should still
2432        // appear because they are in the reference KF.
2433        for lm in 11..=15 {
2434            assert!(local.contains(&lm), "expected reference landmark {}", lm);
2435        }
2436    }
2437}
2438
2439#[cfg(test)]
2440mod pose_jump_gap_scaling_tests {
2441    use super::*;
2442
2443    #[test]
2444    fn gap_of_one_reproduces_unscaled_gate() {
2445        // The common case: the immediately preceding frame tracked
2446        // successfully, so the gap is 1 and the multiplier is a no-op.
2447        assert_eq!(pose_jump_gap_scaling_multiplier(1, 10), 1);
2448    }
2449
2450    #[test]
2451    fn gap_scales_up_to_the_configured_cap() {
2452        assert_eq!(pose_jump_gap_scaling_multiplier(3, 10), 3);
2453        assert_eq!(pose_jump_gap_scaling_multiplier(10, 10), 10);
2454        assert_eq!(pose_jump_gap_scaling_multiplier(50, 10), 10);
2455    }
2456
2457    #[test]
2458    fn multiplier_never_drops_below_one_even_with_a_zero_cap() {
2459        assert_eq!(pose_jump_gap_scaling_multiplier(0, 10), 1);
2460        assert_eq!(pose_jump_gap_scaling_multiplier(5, 0), 1);
2461    }
2462}
2463
2464#[cfg(test)]
2465mod pose_prior_visual_override_tests {
2466    use super::*;
2467    use crate::PosePriorVisualOverrideConfig;
2468    use visloc_core::types::{
2469        Camera, Frame, Landmark, LocalizationFailureReason, LocalizationResult,
2470    };
2471
2472    fn localization(
2473        inliers: usize,
2474        correspondences: usize,
2475        reprojection: f64,
2476    ) -> LocalizationResult {
2477        let mut result = LocalizationResult::failure(
2478            LocalizationFailureReason::QualityGateFailed,
2479            correspondences,
2480            correspondences,
2481            correspondences,
2482        );
2483        result.inlier_count = inliers;
2484        result.inlier_ratio = inliers as f64 / correspondences as f64;
2485        result.reprojection_error = Some(reprojection);
2486        result
2487    }
2488
2489    #[test]
2490    fn strong_visual_solution_enables_bounded_override() {
2491        let result = localization(150, 200, 1.5);
2492        assert!(pose_prior_visual_override_satisfied(
2493            PosePriorVisualOverrideConfig::default(),
2494            &result
2495        ));
2496    }
2497
2498    #[test]
2499    fn weak_or_high_error_visual_solution_cannot_override_prior() {
2500        let config = PosePriorVisualOverrideConfig::default();
2501        assert!(!pose_prior_visual_override_satisfied(
2502            config,
2503            &localization(99, 120, 1.0)
2504        ));
2505        assert!(!pose_prior_visual_override_satisfied(
2506            config,
2507            &localization(150, 300, 1.0)
2508        ));
2509        assert!(!pose_prior_visual_override_satisfied(
2510            config,
2511            &localization(150, 200, 3.1)
2512        ));
2513    }
2514
2515    #[test]
2516    fn invalid_override_config_is_fail_closed() {
2517        let result = localization(150, 200, 1.0);
2518        assert!(!pose_prior_visual_override_satisfied(
2519            PosePriorVisualOverrideConfig {
2520                max_translation_error_multiplier: 0.5,
2521                ..PosePriorVisualOverrideConfig::default()
2522            },
2523            &result
2524        ));
2525    }
2526
2527    #[test]
2528    fn hysteresis_rejects_marginal_crossing_but_accepts_cliff_innovation() {
2529        let result = localization(306, 467, 2.0);
2530        let config = PosePriorVisualOverrideConfig::default();
2531        assert_eq!(
2532            pose_prior_visual_override_threshold(config, &result, 0.216, 0.01, 0.2),
2533            None
2534        );
2535        assert_eq!(
2536            pose_prior_visual_override_threshold(config, &result, 0.311, 0.005, 0.2),
2537            Some(0.5)
2538        );
2539        assert_eq!(
2540            pose_prior_visual_override_threshold(config, &result, 0.6, 0.005, 0.2),
2541            None,
2542            "bounded override must still reject a teleport"
2543        );
2544        assert_eq!(
2545            pose_prior_visual_override_threshold(config, &result, 0.311, 0.03, 0.2),
2546            None,
2547            "large rotation innovation must reject the visual override"
2548        );
2549    }
2550
2551    #[test]
2552    fn continuation_pose_uses_capped_covariance_gain() {
2553        let camera = Camera::pinhole(1, 640, 480, 400.0, 400.0, 320.0, 240.0);
2554        let frame = Frame::new(10, 1);
2555        let mut map = VisualMap::new();
2556        map.cameras.insert(1, camera);
2557        let mut result = localization(12, 12, 1.0);
2558        for (index, (x, y, z)) in [
2559            (-1.0, -0.5, 3.0),
2560            (0.0, -0.5, 3.5),
2561            (1.0, -0.5, 4.0),
2562            (-1.0, 0.5, 4.5),
2563            (0.0, 0.5, 5.0),
2564            (1.0, 0.5, 5.5),
2565            (-0.7, -0.2, 6.0),
2566            (0.7, -0.2, 6.5),
2567            (-0.7, 0.2, 7.0),
2568            (0.7, 0.2, 7.5),
2569            (-0.2, 0.0, 8.0),
2570            (0.2, 0.0, 8.5),
2571        ]
2572        .into_iter()
2573        .enumerate()
2574        {
2575            let id = index as u64 + 1;
2576            map.landmarks
2577                .insert(id, Landmark::new(id, Point3::new(x, y, z)));
2578            result.inlier_landmark_ids.push(id);
2579        }
2580        let prior = Pose::identity();
2581        let estimated =
2582            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.3, 0.0, 0.0));
2583        let fused = covariance_weighted_continuation_pose(
2584            &frame,
2585            &map,
2586            &prior,
2587            &estimated,
2588            &result,
2589            PosePriorVisualOverrideConfig::default(),
2590        )
2591        .expect("well-conditioned inlier geometry should yield covariance");
2592        let x = fused.camera_center_world().x;
2593        assert!(x > 0.0 && x <= 0.15 + 1.0e-12, "fused x={x}");
2594    }
2595}