Skip to main content

visloc_localization/
lib.rs

1#![forbid(unsafe_code)]
2// The DPVO-port and verification modules document internal (crate-private)
3// items extensively; intra-doc links to them are intentional and resolve
4// under --document-private-items. Tolerated repo-wide until that doc pass.
5#![allow(rustdoc::private_intra_doc_links, rustdoc::broken_intra_doc_links)]
6//! Stateless visual localization pipeline composition.
7//!
8//! The pipeline builds 2D-3D correspondences from query features and a visual
9//! map, runs robust pose estimation, applies optional quality gates, and returns
10//! diagnostics-rich localization results. Map providers, descriptor providers,
11//! candidate selectors, matchers, and pose estimators are all replaceable.
12
13mod binary_index;
14mod correspondence;
15mod keyframe_retrieval;
16mod map_merge;
17mod odom_correction;
18mod wheel_calibration;
19mod wheel_gyro;
20
21use std::collections::HashSet;
22
23use nalgebra::Point3;
24use visloc_core::geometry::Pose;
25use visloc_core::types::{
26    Camera, CameraId, Frame, FrameId, LandmarkDescriptorStore, LandmarkId,
27    LocalizationFailureReason, LocalizationResult, LocalizationSuccess, QueryImage, VisualMap,
28};
29use visloc_vision::features::{FeatureExtractor, FeatureSet};
30use visloc_vision::matching::{BruteForceMatcher, Matcher};
31use visloc_vision::pnp::{
32    estimate_pose_with_focal, Correspondence2D3D, P4PfRansacConfig, PnpMinimalSolver,
33};
34use visloc_vision::ransac::{PnPRansac, RobustPoseEstimator};
35
36pub use binary_index::{BinaryLandmarkIndex, BinaryMatchGates, PackedDescriptors};
37pub use correspondence::{
38    AllLandmarksSelector, CandidateSelector, CorrespondenceBuildError, CorrespondenceBuilder,
39    CorrespondenceSet, FixedLandmarkSelector, IntersectCandidateSelector,
40    ProjectionCorrespondenceBuilder, RadiusLandmarkSelector,
41};
42pub use keyframe_retrieval::KeyframeRetrieval;
43pub use map_merge::{
44    merge_maps, register_map, MapMergeConfig, MapMergeError, MapRegistration, MergedMap,
45};
46pub use odom_correction::{FixOutcome, OdomCorrection, OdomCorrectionConfig};
47pub use wheel_calibration::{
48    CalibrationSource, WheelCalibration, WheelCalibrationConfig, WheelCalibrationEstimate,
49};
50pub use wheel_gyro::{GyroWheelConfig, GyroWheelOdometry};
51
52#[derive(Debug, Clone, PartialEq)]
53pub struct LocalizationConfig {
54    pub ratio: Option<f32>,
55    pub ransac_iterations: usize,
56    pub reprojection_threshold: f64,
57    pub min_inliers: usize,
58    pub min_inlier_ratio: f64,
59    pub max_mean_reprojection_error: Option<f64>,
60    pub max_median_reprojection_error: Option<f64>,
61    pub max_reprojection_error: Option<f64>,
62    /// Minimal PnP solver inside RANSAC. [`PnpMinimalSolver::Dlt`] (the
63    /// default) is degenerate when the matched landmarks are coplanar; set
64    /// [`PnpMinimalSolver::P3p`] for scenes dominated by walls or façades.
65    ///
66    /// Read when the pipeline is built ([`LocalizationPipeline::default`],
67    /// [`LocalizationPipeline::new`],
68    /// [`LocalizationPipeline::with_candidate_selector`]); to change the
69    /// solver of a built pipeline use [`LocalizationPipeline::set_pnp_solver`].
70    /// A pipeline built with [`LocalizationPipeline::with_pose_estimator`]
71    /// uses the estimator it was given and ignores this field.
72    pub pnp_solver: PnpMinimalSolver,
73}
74
75/// The RANSAC PnP estimator of the default [`LocalizationPipeline`]: its
76/// minimal solver is chosen at run time by [`LocalizationConfig::pnp_solver`].
77pub type LocalizationRansac = PnPRansac<PnpMinimalSolver>;
78
79fn localization_ransac(config: &LocalizationConfig) -> LocalizationRansac {
80    let defaults = PnPRansac::default();
81    PnPRansac {
82        pose_estimator: config.pnp_solver,
83        pose_refiner: defaults.pose_refiner,
84        iterations: config.ransac_iterations,
85        reprojection_threshold: config.reprojection_threshold,
86        seed: defaults.seed,
87        early_stop_min_iterations: defaults.early_stop_min_iterations,
88        early_stop_inlier_ratio: defaults.early_stop_inlier_ratio,
89        confidence: defaults.confidence,
90        inlier_refits: 0,
91    }
92}
93
94impl Default for LocalizationConfig {
95    fn default() -> Self {
96        Self {
97            ratio: Some(0.8),
98            ransac_iterations: 128,
99            reprojection_threshold: 4.0,
100            min_inliers: 0,
101            min_inlier_ratio: 0.0,
102            max_mean_reprojection_error: None,
103            max_median_reprojection_error: None,
104            max_reprojection_error: None,
105            pnp_solver: PnpMinimalSolver::default(),
106        }
107    }
108}
109
110/// Result of [`LocalizationPipeline::localize_with_unknown_focal`].
111#[derive(Debug, Clone, PartialEq)]
112pub struct UnknownFocalLocalization {
113    /// The localization, gated like every other `localize_*` result, with the
114    /// pose estimated under [`Self::camera`].
115    pub result: LocalizationResult,
116    /// The query camera with the focal length P4Pf estimated (square pixels,
117    /// the query camera's principal point), or `None` when P4Pf found no
118    /// estimate.
119    pub camera: Option<Camera>,
120}
121
122#[derive(Debug, Clone, PartialEq)]
123pub struct FrameLocalizationResult {
124    pub frame_id: FrameId,
125    pub result: LocalizationResult,
126}
127
128pub trait MapProvider {
129    fn visual_map(&self) -> &VisualMap;
130}
131
132pub trait DescriptorProvider {
133    fn landmark_descriptor_store(&self) -> Option<&LandmarkDescriptorStore>;
134}
135
136#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
137pub struct MapProviderStats {
138    pub camera_count: usize,
139    pub landmark_count: usize,
140    pub keyframe_count: usize,
141    pub descriptor_count: usize,
142}
143
144pub fn map_provider_stats<P>(provider: &P) -> MapProviderStats
145where
146    P: MapProvider + DescriptorProvider,
147{
148    let map = provider.visual_map();
149    let descriptor_count = provider.landmark_descriptor_store().map_or_else(
150        || {
151            map.landmarks
152                .values()
153                .filter(|landmark| landmark.descriptor.is_some())
154                .count()
155        },
156        LandmarkDescriptorStore::len,
157    );
158
159    MapProviderStats {
160        camera_count: map.cameras.len(),
161        landmark_count: map.landmarks.len(),
162        keyframe_count: map.keyframes.len(),
163        descriptor_count,
164    }
165}
166
167#[derive(Debug, Clone, PartialEq)]
168pub struct LocalizationPrior {
169    pub pose: Option<Pose>,
170    pub position_world: Option<Point3<f64>>,
171    pub radius: Option<f64>,
172}
173
174impl LocalizationPrior {
175    pub const fn none() -> Self {
176        Self {
177            pose: None,
178            position_world: None,
179            radius: None,
180        }
181    }
182
183    pub const fn from_pose(pose: Pose, radius: f64) -> Self {
184        Self {
185            pose: Some(pose),
186            position_world: None,
187            radius: Some(radius),
188        }
189    }
190
191    pub const fn from_position(position_world: Point3<f64>, radius: f64) -> Self {
192        Self {
193            pose: None,
194            position_world: Some(position_world),
195            radius: Some(radius),
196        }
197    }
198
199    pub fn center_world(&self) -> Option<Point3<f64>> {
200        if let Some(position_world) = self.position_world {
201            Some(position_world)
202        } else {
203            self.pose.as_ref().map(Pose::camera_center_world)
204        }
205    }
206
207    pub fn to_radius_submap_selector(&self) -> Option<RadiusSubmapSelector> {
208        Some(RadiusSubmapSelector::new(
209            self.center_world()?,
210            self.radius?,
211        ))
212    }
213}
214
215impl Default for LocalizationPrior {
216    fn default() -> Self {
217        Self::none()
218    }
219}
220
221pub trait SubmapSelector<P>
222where
223    P: MapProvider + DescriptorProvider,
224{
225    fn select_submap(&self, provider: &P) -> InMemoryMapProvider;
226}
227
228#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
229pub struct AllMapSelector;
230
231impl<P> SubmapSelector<P> for AllMapSelector
232where
233    P: MapProvider + DescriptorProvider,
234{
235    fn select_submap(&self, provider: &P) -> InMemoryMapProvider {
236        if let Some(descriptor_store) = provider.landmark_descriptor_store() {
237            InMemoryMapProvider::with_descriptor_store(
238                provider.visual_map().clone(),
239                descriptor_store.clone(),
240            )
241        } else {
242            InMemoryMapProvider::new(provider.visual_map().clone())
243        }
244    }
245}
246
247#[derive(Debug, Clone, PartialEq, Eq)]
248pub struct FixedLandmarkSubmapSelector {
249    pub landmark_ids: Vec<LandmarkId>,
250}
251
252impl FixedLandmarkSubmapSelector {
253    pub fn new(mut landmark_ids: Vec<LandmarkId>) -> Self {
254        landmark_ids.sort_unstable();
255        landmark_ids.dedup();
256        Self { landmark_ids }
257    }
258}
259
260impl<P> SubmapSelector<P> for FixedLandmarkSubmapSelector
261where
262    P: MapProvider + DescriptorProvider,
263{
264    fn select_submap(&self, provider: &P) -> InMemoryMapProvider {
265        InMemoryMapProvider::from_provider_landmarks(provider, self.landmark_ids.iter().copied())
266    }
267}
268
269#[derive(Debug, Clone, PartialEq)]
270pub struct RadiusSubmapSelector {
271    pub center_world: Point3<f64>,
272    pub radius: f64,
273}
274
275impl RadiusSubmapSelector {
276    pub const fn new(center_world: Point3<f64>, radius: f64) -> Self {
277        Self {
278            center_world,
279            radius,
280        }
281    }
282}
283
284impl<P> SubmapSelector<P> for RadiusSubmapSelector
285where
286    P: MapProvider + DescriptorProvider,
287{
288    fn select_submap(&self, provider: &P) -> InMemoryMapProvider {
289        InMemoryMapProvider::from_provider_radius(provider, self.center_world, self.radius)
290    }
291}
292
293#[derive(Debug, Clone, PartialEq)]
294pub struct PriorSubmapSelector {
295    pub prior: LocalizationPrior,
296}
297
298impl PriorSubmapSelector {
299    pub const fn new(prior: LocalizationPrior) -> Self {
300        Self { prior }
301    }
302}
303
304impl<P> SubmapSelector<P> for PriorSubmapSelector
305where
306    P: MapProvider + DescriptorProvider,
307{
308    fn select_submap(&self, provider: &P) -> InMemoryMapProvider {
309        if let Some(selector) = self.prior.to_radius_submap_selector() {
310            selector.select_submap(provider)
311        } else {
312            AllMapSelector.select_submap(provider)
313        }
314    }
315}
316
317#[derive(Debug, Clone, PartialEq)]
318pub struct SelectableMapProvider<P, S>
319where
320    P: MapProvider + DescriptorProvider,
321    S: SubmapSelector<P>,
322{
323    pub base_provider: P,
324    pub selector: S,
325    selected_provider: InMemoryMapProvider,
326}
327
328impl<P, S> SelectableMapProvider<P, S>
329where
330    P: MapProvider + DescriptorProvider,
331    S: SubmapSelector<P>,
332{
333    pub fn new(base_provider: P, selector: S) -> Self {
334        let selected_provider = selector.select_submap(&base_provider);
335        Self {
336            base_provider,
337            selector,
338            selected_provider,
339        }
340    }
341
342    pub fn refresh(&mut self) {
343        self.selected_provider = self.selector.select_submap(&self.base_provider);
344    }
345
346    pub const fn selected_provider(&self) -> &InMemoryMapProvider {
347        &self.selected_provider
348    }
349}
350
351impl<P, S> MapProvider for SelectableMapProvider<P, S>
352where
353    P: MapProvider + DescriptorProvider,
354    S: SubmapSelector<P>,
355{
356    fn visual_map(&self) -> &VisualMap {
357        self.selected_provider.visual_map()
358    }
359}
360
361impl<P, S> DescriptorProvider for SelectableMapProvider<P, S>
362where
363    P: MapProvider + DescriptorProvider,
364    S: SubmapSelector<P>,
365{
366    fn landmark_descriptor_store(&self) -> Option<&LandmarkDescriptorStore> {
367        self.selected_provider.landmark_descriptor_store()
368    }
369}
370
371#[derive(Debug, Clone, PartialEq)]
372pub struct InMemoryMapProvider {
373    pub map: VisualMap,
374    pub descriptor_store: Option<LandmarkDescriptorStore>,
375}
376
377impl InMemoryMapProvider {
378    pub const fn new(map: VisualMap) -> Self {
379        Self {
380            map,
381            descriptor_store: None,
382        }
383    }
384
385    pub const fn with_descriptor_store(
386        map: VisualMap,
387        descriptor_store: LandmarkDescriptorStore,
388    ) -> Self {
389        Self {
390            map,
391            descriptor_store: Some(descriptor_store),
392        }
393    }
394
395    pub fn from_provider_landmarks<P, I>(provider: &P, landmark_ids: I) -> Self
396    where
397        P: MapProvider + DescriptorProvider,
398        I: IntoIterator<Item = LandmarkId>,
399    {
400        let source_map = provider.visual_map();
401        let landmark_ids = landmark_ids.into_iter().collect::<HashSet<_>>();
402        let mut map = VisualMap::new();
403        map.cameras = source_map.cameras.clone();
404        map.landmarks = source_map
405            .landmarks
406            .iter()
407            .filter(|(landmark_id, _)| landmark_ids.contains(landmark_id))
408            .map(|(landmark_id, landmark)| (*landmark_id, landmark.clone()))
409            .collect();
410        map.landmark_position_covariances = source_map
411            .landmark_position_covariances
412            .iter()
413            .filter(|(landmark_id, _)| landmark_ids.contains(landmark_id))
414            .map(|(landmark_id, covariance)| (*landmark_id, *covariance))
415            .collect();
416        map.keyframes = source_map
417            .keyframes
418            .iter()
419            .filter_map(|(keyframe_id, keyframe)| {
420                let mut keyframe = keyframe.clone();
421                keyframe
422                    .observations
423                    .retain(|observation| landmark_ids.contains(&observation.landmark_id));
424                if keyframe.observations.is_empty() {
425                    None
426                } else {
427                    Some((*keyframe_id, keyframe))
428                }
429            })
430            .collect();
431
432        let descriptor_store = descriptor_store_for_submap(provider, &map);
433        Self {
434            map,
435            descriptor_store,
436        }
437    }
438
439    pub fn from_provider_radius<P>(provider: &P, center_world: Point3<f64>, radius: f64) -> Self
440    where
441        P: MapProvider + DescriptorProvider,
442    {
443        let landmark_ids = if radius < 0.0 {
444            Vec::new()
445        } else {
446            let radius_squared = radius * radius;
447            provider
448                .visual_map()
449                .landmarks
450                .values()
451                .filter(|landmark| {
452                    (landmark.position - center_world).norm_squared() <= radius_squared
453                })
454                .map(|landmark| landmark.id)
455                .collect::<Vec<_>>()
456        };
457        Self::from_provider_landmarks(provider, landmark_ids)
458    }
459}
460
461impl MapProvider for InMemoryMapProvider {
462    fn visual_map(&self) -> &VisualMap {
463        &self.map
464    }
465}
466
467impl DescriptorProvider for InMemoryMapProvider {
468    fn landmark_descriptor_store(&self) -> Option<&LandmarkDescriptorStore> {
469        self.descriptor_store.as_ref()
470    }
471}
472
473fn descriptor_store_for_submap<P>(
474    provider: &P,
475    submap: &VisualMap,
476) -> Option<LandmarkDescriptorStore>
477where
478    P: MapProvider + DescriptorProvider,
479{
480    let mut descriptor_store = LandmarkDescriptorStore::new();
481    if let Some(source_store) = provider.landmark_descriptor_store() {
482        // Sort the submap landmark ids before iterating so the
483        // insertion order into the new `LandmarkDescriptorStore` is
484        // independent of the per-process `HashMap` SipHash seed. The
485        // store itself is a `HashMap` but downstream callers should
486        // not observe ordering differences across binary builds.
487        let mut landmark_ids: Vec<u64> = submap.landmarks.keys().copied().collect();
488        landmark_ids.sort();
489        for landmark_id in landmark_ids {
490            if let Some(descriptor) = source_store.get(landmark_id) {
491                descriptor_store.insert(landmark_id, descriptor.to_vec());
492            }
493        }
494    } else {
495        descriptor_store = LandmarkDescriptorStore::from_visual_map(submap);
496    }
497
498    if descriptor_store.is_empty() {
499        None
500    } else {
501        Some(descriptor_store)
502    }
503}
504
505#[derive(Debug, Clone)]
506pub struct ImageLocalizer<X, P = LocalizationPipeline> {
507    pub extractor: X,
508    pub pipeline: P,
509}
510
511impl<X> ImageLocalizer<X, LocalizationPipeline>
512where
513    X: FeatureExtractor,
514{
515    pub fn new(extractor: X) -> Self {
516        Self {
517            extractor,
518            pipeline: LocalizationPipeline::default(),
519        }
520    }
521}
522
523impl<X, P> ImageLocalizer<X, P>
524where
525    X: FeatureExtractor,
526{
527    pub const fn with_pipeline(extractor: X, pipeline: P) -> Self {
528        Self {
529            extractor,
530            pipeline,
531        }
532    }
533}
534
535#[derive(Debug, Clone)]
536pub struct LocalizationPipeline<
537    M = BruteForceMatcher,
538    S = AllLandmarksSelector,
539    E = LocalizationRansac,
540> {
541    pub matcher: M,
542    pub candidate_selector: S,
543    pub pose_estimator: E,
544    pub config: LocalizationConfig,
545}
546
547impl Default for LocalizationPipeline<BruteForceMatcher, AllLandmarksSelector, LocalizationRansac> {
548    fn default() -> Self {
549        let config = LocalizationConfig::default();
550        Self {
551            matcher: BruteForceMatcher {
552                ratio: config.ratio,
553            },
554            candidate_selector: AllLandmarksSelector,
555            pose_estimator: localization_ransac(&config),
556            config,
557        }
558    }
559}
560
561impl<M> LocalizationPipeline<M, AllLandmarksSelector, LocalizationRansac>
562where
563    M: Matcher + Clone,
564{
565    pub fn new(matcher: M, config: LocalizationConfig) -> Self {
566        Self {
567            matcher,
568            candidate_selector: AllLandmarksSelector,
569            pose_estimator: localization_ransac(&config),
570            config,
571        }
572    }
573}
574
575impl<M, S> LocalizationPipeline<M, S, LocalizationRansac>
576where
577    M: Matcher + Clone,
578    S: CandidateSelector + Clone,
579{
580    pub fn with_candidate_selector(
581        matcher: M,
582        candidate_selector: S,
583        config: LocalizationConfig,
584    ) -> Self {
585        Self {
586            matcher,
587            candidate_selector,
588            pose_estimator: localization_ransac(&config),
589            config,
590        }
591    }
592}
593
594impl<M, S> LocalizationPipeline<M, S, LocalizationRansac> {
595    /// Switches the RANSAC minimal solver (and [`LocalizationConfig::pnp_solver`]
596    /// with it) on a built pipeline, e.g. to [`PnpMinimalSolver::P3p`] for a
597    /// map dominated by walls.
598    pub fn set_pnp_solver(&mut self, solver: PnpMinimalSolver) {
599        self.config.pnp_solver = solver;
600        self.pose_estimator.pose_estimator = solver;
601    }
602
603    /// Builder form of [`Self::set_pnp_solver`].
604    #[must_use]
605    pub fn with_pnp_solver(mut self, solver: PnpMinimalSolver) -> Self {
606        self.set_pnp_solver(solver);
607        self
608    }
609}
610
611impl<M, S, E> LocalizationPipeline<M, S, E>
612where
613    M: Matcher + Clone,
614    S: CandidateSelector + Clone,
615    E: RobustPoseEstimator + Clone,
616{
617    pub const fn with_pose_estimator(
618        matcher: M,
619        candidate_selector: S,
620        pose_estimator: E,
621        config: LocalizationConfig,
622    ) -> Self {
623        Self {
624            matcher,
625            candidate_selector,
626            pose_estimator,
627            config,
628        }
629    }
630
631    pub fn localize(&self, query: &QueryImage, map: &VisualMap) -> LocalizationResult {
632        let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
633        self.localize_with_descriptor_store(query, map, &descriptor_store)
634    }
635
636    pub fn localize_with_provider<P>(&self, query: &QueryImage, provider: &P) -> LocalizationResult
637    where
638        P: MapProvider + DescriptorProvider,
639    {
640        let map = provider.visual_map();
641        if let Some(descriptor_store) = provider.landmark_descriptor_store() {
642            self.localize_with_descriptor_store(query, map, descriptor_store)
643        } else {
644            let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
645            self.localize_with_descriptor_store(query, map, &descriptor_store)
646        }
647    }
648
649    pub fn localize_image_with_extractor<X>(
650        &self,
651        image: &X::Image,
652        camera: Camera,
653        map: &VisualMap,
654        extractor: &X,
655    ) -> Result<LocalizationResult, X::Error>
656    where
657        X: FeatureExtractor,
658    {
659        let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
660        self.localize_image_with_extractor_and_descriptor_store(
661            image,
662            camera,
663            map,
664            &descriptor_store,
665            extractor,
666        )
667    }
668
669    pub fn localize_image_with_extractor_and_provider<X, P>(
670        &self,
671        image: &X::Image,
672        camera: Camera,
673        provider: &P,
674        extractor: &X,
675    ) -> Result<LocalizationResult, X::Error>
676    where
677        X: FeatureExtractor,
678        P: MapProvider + DescriptorProvider,
679    {
680        let features = extractor.extract(image)?;
681        let query = query_from_features(camera, features);
682        Ok(self.localize_with_provider(&query, provider))
683    }
684
685    pub fn localize_image_with_extractor_and_descriptor_store<X>(
686        &self,
687        image: &X::Image,
688        camera: Camera,
689        map: &VisualMap,
690        descriptor_store: &LandmarkDescriptorStore,
691        extractor: &X,
692    ) -> Result<LocalizationResult, X::Error>
693    where
694        X: FeatureExtractor,
695    {
696        let features = extractor.extract(image)?;
697        let query = query_from_features(camera, features);
698        Ok(self.localize_with_descriptor_store(&query, map, descriptor_store))
699    }
700
701    pub fn localize_frame(&self, frame: &Frame, map: &VisualMap) -> LocalizationResult {
702        let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
703        self.localize_frame_with_descriptor_store(frame, map, &descriptor_store)
704    }
705
706    pub fn localize_frame_with_provider<P>(&self, frame: &Frame, provider: &P) -> LocalizationResult
707    where
708        P: MapProvider + DescriptorProvider,
709    {
710        let map = provider.visual_map();
711        if let Some(descriptor_store) = provider.landmark_descriptor_store() {
712            self.localize_frame_with_descriptor_store(frame, map, descriptor_store)
713        } else {
714            let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
715            self.localize_frame_with_descriptor_store(frame, map, &descriptor_store)
716        }
717    }
718
719    pub fn localize_frame_image_with_extractor<X>(
720        &self,
721        frame_id: FrameId,
722        camera_id: CameraId,
723        image: &X::Image,
724        map: &VisualMap,
725        extractor: &X,
726    ) -> Result<FrameLocalizationResult, X::Error>
727    where
728        X: FeatureExtractor,
729    {
730        let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
731        self.localize_frame_image_with_extractor_and_descriptor_store(
732            frame_id,
733            camera_id,
734            image,
735            map,
736            &descriptor_store,
737            extractor,
738        )
739    }
740
741    pub fn localize_frame_image_with_extractor_and_provider<X, P>(
742        &self,
743        frame_id: FrameId,
744        camera_id: CameraId,
745        image: &X::Image,
746        provider: &P,
747        extractor: &X,
748    ) -> Result<FrameLocalizationResult, X::Error>
749    where
750        X: FeatureExtractor,
751        P: MapProvider + DescriptorProvider,
752    {
753        let map = provider.visual_map();
754        if let Some(descriptor_store) = provider.landmark_descriptor_store() {
755            self.localize_frame_image_with_extractor_and_descriptor_store(
756                frame_id,
757                camera_id,
758                image,
759                map,
760                descriptor_store,
761                extractor,
762            )
763        } else {
764            let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
765            self.localize_frame_image_with_extractor_and_descriptor_store(
766                frame_id,
767                camera_id,
768                image,
769                map,
770                &descriptor_store,
771                extractor,
772            )
773        }
774    }
775
776    pub fn localize_frame_image_with_extractor_and_descriptor_store<X>(
777        &self,
778        frame_id: FrameId,
779        camera_id: CameraId,
780        image: &X::Image,
781        map: &VisualMap,
782        descriptor_store: &LandmarkDescriptorStore,
783        extractor: &X,
784    ) -> Result<FrameLocalizationResult, X::Error>
785    where
786        X: FeatureExtractor,
787    {
788        let Some(camera) = map.cameras.get(&camera_id).cloned() else {
789            return Ok(FrameLocalizationResult {
790                frame_id,
791                result: LocalizationResult::failure(
792                    LocalizationFailureReason::MissingCamera { camera_id },
793                    0,
794                    0,
795                    0,
796                ),
797            });
798        };
799        let result = self.localize_image_with_extractor_and_descriptor_store(
800            image,
801            camera,
802            map,
803            descriptor_store,
804            extractor,
805        )?;
806        Ok(FrameLocalizationResult { frame_id, result })
807    }
808
809    pub fn localize_frames(
810        &self,
811        frames: &[Frame],
812        map: &VisualMap,
813    ) -> Vec<FrameLocalizationResult> {
814        let descriptor_store = LandmarkDescriptorStore::from_visual_map(map);
815        self.localize_frames_with_descriptor_store(frames, map, &descriptor_store)
816    }
817
818    pub fn localize_frame_with_descriptor_store(
819        &self,
820        frame: &Frame,
821        map: &VisualMap,
822        descriptor_store: &LandmarkDescriptorStore,
823    ) -> LocalizationResult {
824        let Some(camera) = map.cameras.get(&frame.camera_id).cloned() else {
825            return LocalizationResult::failure(
826                LocalizationFailureReason::MissingCamera {
827                    camera_id: frame.camera_id,
828                },
829                0,
830                0,
831                0,
832            );
833        };
834        let query = QueryImage::from_frame(frame, camera);
835        self.localize_with_descriptor_store(&query, map, descriptor_store)
836    }
837
838    pub fn localize_frame_with_candidate_selector_and_descriptor_store<S2>(
839        &self,
840        frame: &Frame,
841        map: &VisualMap,
842        descriptor_store: &LandmarkDescriptorStore,
843        candidate_selector: S2,
844    ) -> LocalizationResult
845    where
846        S2: CandidateSelector + Clone,
847    {
848        let Some(camera) = map.cameras.get(&frame.camera_id).cloned() else {
849            return LocalizationResult::failure(
850                LocalizationFailureReason::MissingCamera {
851                    camera_id: frame.camera_id,
852                },
853                0,
854                0,
855                0,
856            );
857        };
858        let query = QueryImage::from_frame(frame, camera);
859        self.localize_with_candidate_selector_and_descriptor_store(
860            &query,
861            map,
862            descriptor_store,
863            candidate_selector,
864        )
865    }
866
867    pub fn localize_frames_with_descriptor_store(
868        &self,
869        frames: &[Frame],
870        map: &VisualMap,
871        descriptor_store: &LandmarkDescriptorStore,
872    ) -> Vec<FrameLocalizationResult> {
873        frames
874            .iter()
875            .map(|frame| FrameLocalizationResult {
876                frame_id: frame.id,
877                result: self.localize_frame_with_descriptor_store(frame, map, descriptor_store),
878            })
879            .collect()
880    }
881
882    pub fn localize_with_candidate_selector_and_descriptor_store<S2>(
883        &self,
884        query: &QueryImage,
885        map: &VisualMap,
886        descriptor_store: &LandmarkDescriptorStore,
887        candidate_selector: S2,
888    ) -> LocalizationResult
889    where
890        S2: CandidateSelector + Clone,
891    {
892        self.run_localization(query, map, descriptor_store, candidate_selector, None)
893    }
894
895    pub fn localize_with_candidate_selector_and_descriptor_store_and_pose_prior<S2>(
896        &self,
897        query: &QueryImage,
898        map: &VisualMap,
899        descriptor_store: &LandmarkDescriptorStore,
900        candidate_selector: S2,
901        pose_prior: Option<&Pose>,
902    ) -> LocalizationResult
903    where
904        S2: CandidateSelector + Clone,
905    {
906        self.run_localization(query, map, descriptor_store, candidate_selector, pose_prior)
907    }
908
909    pub fn localize_with_descriptor_store(
910        &self,
911        query: &QueryImage,
912        map: &VisualMap,
913        descriptor_store: &LandmarkDescriptorStore,
914    ) -> LocalizationResult {
915        self.run_localization(
916            query,
917            map,
918            descriptor_store,
919            self.candidate_selector.clone(),
920            None,
921        )
922    }
923
924    /// ORB-SLAM3-style projection-guided variant of
925    /// [`Self::localize_frame_with_pose_prior_and_descriptor_store`]: instead
926    /// of an appearance-global descriptor search restricted to a radius
927    /// candidate set, each candidate landmark is projected into the frame
928    /// with `pose_prior` and matched only against query keypoints within
929    /// `search_radius_px` pixels of the projection (see
930    /// [`ProjectionCorrespondenceBuilder`]). Falls through to the existing
931    /// pose-estimation-and-quality-gate path unchanged.
932    pub fn localize_frame_with_projection_window_and_descriptor_store(
933        &self,
934        frame: &Frame,
935        map: &VisualMap,
936        descriptor_store: &LandmarkDescriptorStore,
937        pose_prior: &Pose,
938        candidate_radius: Option<f64>,
939        search_radius_px: f64,
940    ) -> LocalizationResult {
941        self.localize_frame_with_projection_window_descriptor_store_and_query_landmark_ratio(
942            frame,
943            map,
944            descriptor_store,
945            pose_prior,
946            candidate_radius,
947            search_radius_px,
948            None,
949        )
950    }
951
952    // This compatibility entry point exposes the existing projection-window
953    // arguments plus the optional reverse-ratio gate without replacing the
954    // shorter public wrapper above.
955    #[allow(clippy::too_many_arguments)]
956    pub fn localize_frame_with_projection_window_descriptor_store_and_query_landmark_ratio(
957        &self,
958        frame: &Frame,
959        map: &VisualMap,
960        descriptor_store: &LandmarkDescriptorStore,
961        pose_prior: &Pose,
962        candidate_radius: Option<f64>,
963        search_radius_px: f64,
964        max_query_landmark_distance_ratio: Option<f32>,
965    ) -> LocalizationResult {
966        let Some(camera) = map.cameras.get(&frame.camera_id).cloned() else {
967            return LocalizationResult::failure(
968                LocalizationFailureReason::MissingCamera {
969                    camera_id: frame.camera_id,
970                },
971                0,
972                0,
973                0,
974            );
975        };
976        let query = QueryImage::from_frame(frame, camera);
977
978        if let Some(radius) = candidate_radius {
979            let radius_selector =
980                RadiusLandmarkSelector::new(pose_prior.camera_center_world(), radius);
981            let candidate_selector =
982                IntersectCandidateSelector::new(self.candidate_selector.clone(), radius_selector);
983            self.localize_with_projection_window_descriptor_store_and_query_landmark_ratio(
984                &query,
985                map,
986                descriptor_store,
987                candidate_selector,
988                pose_prior,
989                search_radius_px,
990                max_query_landmark_distance_ratio,
991            )
992        } else {
993            self.localize_with_projection_window_descriptor_store_and_query_landmark_ratio(
994                &query,
995                map,
996                descriptor_store,
997                self.candidate_selector.clone(),
998                pose_prior,
999                search_radius_px,
1000                max_query_landmark_distance_ratio,
1001            )
1002        }
1003    }
1004
1005    pub fn localize_with_projection_window_and_descriptor_store<S2>(
1006        &self,
1007        query: &QueryImage,
1008        map: &VisualMap,
1009        descriptor_store: &LandmarkDescriptorStore,
1010        candidate_selector: S2,
1011        pose_prior: &Pose,
1012        search_radius_px: f64,
1013    ) -> LocalizationResult
1014    where
1015        S2: CandidateSelector + Clone,
1016    {
1017        self.localize_with_projection_window_descriptor_store_and_query_landmark_ratio(
1018            query,
1019            map,
1020            descriptor_store,
1021            candidate_selector,
1022            pose_prior,
1023            search_radius_px,
1024            None,
1025        )
1026    }
1027
1028    // Keep the selector-generic compatibility entry point parallel to the
1029    // frame wrapper; callers that do not need the reverse ratio use the
1030    // shorter method above.
1031    #[allow(clippy::too_many_arguments)]
1032    pub fn localize_with_projection_window_descriptor_store_and_query_landmark_ratio<S2>(
1033        &self,
1034        query: &QueryImage,
1035        map: &VisualMap,
1036        descriptor_store: &LandmarkDescriptorStore,
1037        candidate_selector: S2,
1038        pose_prior: &Pose,
1039        search_radius_px: f64,
1040        max_query_landmark_distance_ratio: Option<f32>,
1041    ) -> LocalizationResult
1042    where
1043        S2: CandidateSelector + Clone,
1044    {
1045        let correspondence_set = match ProjectionCorrespondenceBuilder::with_candidate_selector(
1046            self.matcher.clone(),
1047            candidate_selector,
1048        )
1049        .build_with_pose_prior_and_query_landmark_ratio(
1050            query,
1051            map,
1052            descriptor_store,
1053            pose_prior,
1054            search_radius_px,
1055            max_query_landmark_distance_ratio,
1056        ) {
1057            Ok(correspondence_set) => correspondence_set,
1058            Err(error) => return result_from_correspondence_error(error),
1059        };
1060        self.estimate_and_gate(&query.camera, correspondence_set, Some(pose_prior))
1061    }
1062
1063    /// Stage-3 local-map refinement: given an already-successful `estimated`
1064    /// localization for `frame`, project `local_map_descriptor_store`'s
1065    /// landmarks with the ESTIMATED pose, harvest additional correspondences
1066    /// within `refinement_search_radius_px`, and re-run pose estimation over
1067    /// the union with `estimated`'s own inlier correspondences (duplicates
1068    /// by landmark id are dropped, preferring the already-known-good inlier
1069    /// entry). Returns `None` when `estimated` carries no pose or the
1070    /// combined correspondence set is too small for the estimator to run;
1071    /// callers are responsible for accept/reject decisions (this method does
1072    /// not compare inlier counts against `estimated`).
1073    pub fn refine_frame_pose_with_local_map_and_descriptor_store(
1074        &self,
1075        frame: &Frame,
1076        map: &VisualMap,
1077        local_map_descriptor_store: &LandmarkDescriptorStore,
1078        estimated: &LocalizationResult,
1079        refinement_search_radius_px: f64,
1080    ) -> Option<LocalizationResult> {
1081        let estimated_pose = estimated.pose.as_ref()?;
1082        let camera = map.cameras.get(&frame.camera_id)?.clone();
1083        let query = QueryImage::from_frame(frame, camera.clone());
1084
1085        let harvested = ProjectionCorrespondenceBuilder::new(self.matcher.clone())
1086            .build_with_pose_prior(
1087                &query,
1088                map,
1089                local_map_descriptor_store,
1090                estimated_pose,
1091                refinement_search_radius_px,
1092            )
1093            .ok();
1094
1095        let mut seen_landmarks: HashSet<LandmarkId> = HashSet::new();
1096        let mut seen_query_indices: HashSet<usize> = HashSet::new();
1097        let mut correspondences = Vec::new();
1098        let mut query_indices = Vec::new();
1099        let mut landmark_ids = Vec::new();
1100
1101        for ((&query_index, &landmark_id), confidence) in estimated
1102            .inlier_query_indices
1103            .iter()
1104            .zip(estimated.inlier_landmark_ids.iter())
1105            .zip(estimated.inlier_confidences.iter().copied())
1106        {
1107            let Some(point2d) = frame.keypoints.get(query_index).copied() else {
1108                continue;
1109            };
1110            let Some(landmark) = map.landmarks.get(&landmark_id) else {
1111                continue;
1112            };
1113            if !seen_landmarks.insert(landmark_id) || !seen_query_indices.insert(query_index) {
1114                continue;
1115            }
1116            correspondences.push(Correspondence2D3D {
1117                point2d,
1118                point3d: landmark.position,
1119                confidence,
1120            });
1121            query_indices.push(query_index);
1122            landmark_ids.push(landmark_id);
1123        }
1124
1125        if let Some(harvested) = &harvested {
1126            for ((correspondence, &query_index), &landmark_id) in harvested
1127                .correspondences
1128                .iter()
1129                .zip(harvested.query_indices.iter())
1130                .zip(harvested.landmark_ids.iter())
1131            {
1132                if !seen_landmarks.insert(landmark_id) || !seen_query_indices.insert(query_index) {
1133                    continue;
1134                }
1135                correspondences.push(correspondence.clone());
1136                query_indices.push(query_index);
1137                landmark_ids.push(landmark_id);
1138            }
1139        }
1140
1141        if same_inlier_assignment(&query_indices, &landmark_ids, estimated) {
1142            return None;
1143        }
1144
1145        let correspondence_count = correspondences.len();
1146        let confidence_weights = correspondence_confidence_weights(&correspondences);
1147        let report = self.pose_estimator.estimate_with_pose_prior_and_weights(
1148            &correspondences,
1149            &camera,
1150            Some(estimated_pose),
1151            confidence_weights.as_deref(),
1152        )?;
1153
1154        let inlier_query_indices = report
1155            .inliers
1156            .iter()
1157            .filter_map(|inlier| query_indices.get(*inlier).copied())
1158            .collect::<Vec<_>>();
1159        let inlier_landmark_ids = report
1160            .inliers
1161            .iter()
1162            .filter_map(|inlier| landmark_ids.get(*inlier).copied())
1163            .collect::<Vec<_>>();
1164        let inlier_confidences = report
1165            .inliers
1166            .iter()
1167            .filter_map(|inlier| correspondences.get(*inlier).map(|corr| corr.confidence))
1168            .collect::<Vec<_>>();
1169
1170        let result = LocalizationResult::success(LocalizationSuccess {
1171            pose: report.pose,
1172            candidate_landmark_count: correspondence_count,
1173            match_count: correspondence_count,
1174            correspondence_count,
1175            inliers: report.inliers,
1176            inlier_query_indices,
1177            inlier_landmark_ids,
1178            inlier_confidences,
1179            inlier_reprojection_errors: report.inlier_reprojection_errors,
1180            mean_reprojection_error: report.mean_reprojection_error,
1181            median_reprojection_error: report.median_reprojection_error,
1182            max_reprojection_error: report.max_reprojection_error,
1183        })
1184        .with_estimator_diagnostics(report.diagnostics);
1185
1186        Some(if passes_quality_gate(&result, &self.config) {
1187            result
1188        } else {
1189            result.rejected_by_quality_gate()
1190        })
1191    }
1192
1193    /// DROID-style correspondence-revision primitive for the sparse tracker:
1194    /// discard the previous 2D-3D assignment, project the local map with the
1195    /// latest pose, rebuild a fresh one-to-one correspondence set, and solve
1196    /// PnP again. Repeating this operation alternates correspondence and pose
1197    /// updates while preserving the existing robust estimator and quality
1198    /// gate. Unlike [`Self::refine_frame_pose_with_local_map_and_descriptor_store`],
1199    /// query keypoints may switch to a different landmark between iterations.
1200    pub fn revise_frame_pose_with_local_map_and_descriptor_store(
1201        &self,
1202        frame: &Frame,
1203        map: &VisualMap,
1204        local_map_descriptor_store: &LandmarkDescriptorStore,
1205        estimated: &LocalizationResult,
1206        refinement_search_radius_px: f64,
1207    ) -> Option<LocalizationResult> {
1208        let estimated_pose = estimated.pose.as_ref()?;
1209        let camera = map.cameras.get(&frame.camera_id)?.clone();
1210        let query = QueryImage::from_frame(frame, camera);
1211        let correspondence_set = ProjectionCorrespondenceBuilder::new(self.matcher.clone())
1212            .build_with_pose_prior(
1213                &query,
1214                map,
1215                local_map_descriptor_store,
1216                estimated_pose,
1217                refinement_search_radius_px,
1218            )
1219            .ok()?;
1220        if same_inlier_assignment(
1221            &correspondence_set.query_indices,
1222            &correspondence_set.landmark_ids,
1223            estimated,
1224        ) {
1225            return None;
1226        }
1227        Some(self.estimate_and_gate(&query.camera, correspondence_set, Some(estimated_pose)))
1228    }
1229
1230    fn run_localization<S2>(
1231        &self,
1232        query: &QueryImage,
1233        map: &VisualMap,
1234        descriptor_store: &LandmarkDescriptorStore,
1235        candidate_selector: S2,
1236        pose_prior: Option<&Pose>,
1237    ) -> LocalizationResult
1238    where
1239        S2: CandidateSelector + Clone,
1240    {
1241        let correspondence_set = match CorrespondenceBuilder::with_candidate_selector(
1242            self.matcher.clone(),
1243            candidate_selector,
1244        )
1245        .build(query, map, descriptor_store)
1246        {
1247            Ok(correspondence_set) => correspondence_set,
1248            Err(error) => {
1249                return result_from_correspondence_error(error);
1250            }
1251        };
1252        self.estimate_and_gate(&query.camera, correspondence_set, pose_prior)
1253    }
1254
1255    /// Pose estimation and quality gate over correspondences built outside
1256    /// the pipeline, e.g. by [`BinaryLandmarkIndex`]: the same tail as every
1257    /// `localize_*` method, so results are gated identically.
1258    pub fn localize_correspondences(
1259        &self,
1260        camera: &Camera,
1261        correspondence_set: CorrespondenceSet,
1262    ) -> LocalizationResult {
1263        self.estimate_and_gate(camera, correspondence_set, None)
1264    }
1265
1266    /// Localize a query whose focal length is unknown, such as a photo with
1267    /// no EXIF or a cropped one: the 2D-3D correspondences are built as in
1268    /// [`Self::localize_with_descriptor_store`], P4Pf RANSAC
1269    /// ([`estimate_pose_with_focal`]) estimates the focal length from them,
1270    /// and the configured pose estimator and quality gate then run with that
1271    /// focal length, so the result is gated exactly like the known-focal path.
1272    ///
1273    /// The focal length in `query.camera` is ignored; its size and principal
1274    /// point (`cx`, `cy`, or the image centre when it has no pinhole
1275    /// intrinsics) are kept. Assumes square pixels and no lens distortion.
1276    pub fn localize_with_unknown_focal(
1277        &self,
1278        query: &QueryImage,
1279        map: &VisualMap,
1280        descriptor_store: &LandmarkDescriptorStore,
1281        focal_config: &P4PfRansacConfig,
1282    ) -> UnknownFocalLocalization {
1283        let correspondence_set = match CorrespondenceBuilder::with_candidate_selector(
1284            self.matcher.clone(),
1285            self.candidate_selector.clone(),
1286        )
1287        .build(query, map, descriptor_store)
1288        {
1289            Ok(set) => set,
1290            Err(error) => {
1291                return UnknownFocalLocalization {
1292                    result: result_from_correspondence_error(error),
1293                    camera: None,
1294                };
1295            }
1296        };
1297        let (width, height) = (query.camera.width, query.camera.height);
1298        let (cx, cy) = query.camera.intrinsics().map_or(
1299            (width as f64 / 2.0, height as f64 / 2.0),
1300            |(_, _, cx, cy)| (cx, cy),
1301        );
1302        let Some(report) = estimate_pose_with_focal(
1303            &correspondence_set.correspondences,
1304            nalgebra::Point2::new(cx, cy),
1305            focal_config,
1306        ) else {
1307            return UnknownFocalLocalization {
1308                result: LocalizationResult::failure(
1309                    LocalizationFailureReason::PoseEstimationFailed {
1310                        correspondence_count: correspondence_set.correspondences.len(),
1311                    },
1312                    correspondence_set.candidate_landmark_count,
1313                    correspondence_set.match_count,
1314                    correspondence_set.correspondences.len(),
1315                ),
1316                camera: None,
1317            };
1318        };
1319        let focal = report.estimate.focal_px;
1320        let camera = Camera::pinhole(query.camera.id, width, height, focal, focal, cx, cy);
1321        UnknownFocalLocalization {
1322            result: self.estimate_and_gate(&camera, correspondence_set, None),
1323            camera: Some(camera),
1324        }
1325    }
1326
1327    /// Shared tail of both `run_localization` (appearance-global) and
1328    /// `localize_with_projection_window_and_descriptor_store`
1329    /// (projection-guided): run the configured `RobustPoseEstimator` over an
1330    /// already-built `CorrespondenceSet` and apply the quality gate. Kept as
1331    /// one function so PnP/gate behaviour cannot drift between the two
1332    /// correspondence-building strategies.
1333    fn estimate_and_gate(
1334        &self,
1335        camera: &Camera,
1336        correspondence_set: CorrespondenceSet,
1337        pose_prior: Option<&Pose>,
1338    ) -> LocalizationResult {
1339        let match_count = correspondence_set.match_count;
1340        let candidate_landmark_count = correspondence_set.candidate_landmark_count;
1341        let correspondence_count = correspondence_set.correspondences.len();
1342
1343        let confidence_weights =
1344            correspondence_confidence_weights(&correspondence_set.correspondences);
1345        let pose_report = if pose_prior.is_some() {
1346            self.pose_estimator.estimate_with_pose_prior_and_weights(
1347                &correspondence_set.correspondences,
1348                camera,
1349                pose_prior,
1350                confidence_weights.as_deref(),
1351            )
1352        } else if let Some(weights) = confidence_weights.as_deref() {
1353            self.pose_estimator.estimate_with_weights(
1354                &correspondence_set.correspondences,
1355                camera,
1356                weights,
1357            )
1358        } else {
1359            self.pose_estimator
1360                .estimate(&correspondence_set.correspondences, camera)
1361        };
1362
1363        let Some(report) = pose_report else {
1364            let result = LocalizationResult::failure(
1365                LocalizationFailureReason::PoseEstimationFailed {
1366                    correspondence_count,
1367                },
1368                candidate_landmark_count,
1369                match_count,
1370                correspondence_count,
1371            );
1372            if let Some(diagnostics) = self
1373                .pose_estimator
1374                .failure_diagnostics(&correspondence_set.correspondences, camera)
1375            {
1376                return result.with_pose_failure_diagnostics(diagnostics);
1377            }
1378            return result;
1379        };
1380
1381        let inlier_query_indices = report
1382            .inliers
1383            .iter()
1384            .filter_map(|inlier| correspondence_set.query_indices.get(*inlier).copied())
1385            .collect::<Vec<_>>();
1386        let inlier_landmark_ids = report
1387            .inliers
1388            .iter()
1389            .filter_map(|inlier| correspondence_set.landmark_ids.get(*inlier).copied())
1390            .collect::<Vec<_>>();
1391        let inlier_confidences = report
1392            .inliers
1393            .iter()
1394            .filter_map(|inlier| {
1395                correspondence_set
1396                    .correspondences
1397                    .get(*inlier)
1398                    .map(|corr| corr.confidence)
1399            })
1400            .collect::<Vec<_>>();
1401
1402        let result = LocalizationResult::success(LocalizationSuccess {
1403            pose: report.pose,
1404            candidate_landmark_count,
1405            match_count,
1406            correspondence_count,
1407            inliers: report.inliers,
1408            inlier_query_indices,
1409            inlier_landmark_ids,
1410            inlier_confidences,
1411            inlier_reprojection_errors: report.inlier_reprojection_errors,
1412            mean_reprojection_error: report.mean_reprojection_error,
1413            median_reprojection_error: report.median_reprojection_error,
1414            max_reprojection_error: report.max_reprojection_error,
1415        })
1416        .with_estimator_diagnostics(report.diagnostics);
1417
1418        if passes_quality_gate(&result, &self.config) {
1419            result
1420        } else {
1421            result.rejected_by_quality_gate()
1422        }
1423    }
1424}
1425
1426fn correspondence_confidence_weights(
1427    correspondences: &[visloc_vision::pnp::Correspondence2D3D],
1428) -> Option<Vec<f32>> {
1429    let weights = correspondences
1430        .iter()
1431        .map(|correspondence| {
1432            correspondence
1433                .confidence
1434                .filter(|confidence| confidence.is_finite() && *confidence > 0.0)
1435                // A missing signal is uniform evidence, per
1436                // `Correspondence2D3D`'s contract. In a mixed classical /
1437                // learned set it must not be turned into a zero-weight
1438                // correspondence merely because another match has a score.
1439                .unwrap_or(1.0)
1440        })
1441        .collect::<Vec<_>>();
1442    weights
1443        .iter()
1444        .zip(correspondences.iter())
1445        .any(|(weight, correspondence)| *weight > 0.0 && correspondence.confidence.is_some())
1446        .then_some(weights)
1447}
1448
1449/// Returns true when rebuilding correspondences produced exactly the same
1450/// one-to-one query/landmark assignment as the current PnP inliers. Re-solving
1451/// an unchanged set is not a correspondence update; it only exposes the
1452/// tracker to another RANSAC/order-dependent pose sample and can accumulate
1453/// drift when repeated every frame.
1454fn same_inlier_assignment(
1455    query_indices: &[usize],
1456    landmark_ids: &[LandmarkId],
1457    estimated: &LocalizationResult,
1458) -> bool {
1459    let new_count = query_indices.len().min(landmark_ids.len());
1460    let old_count = estimated
1461        .inlier_query_indices
1462        .len()
1463        .min(estimated.inlier_landmark_ids.len());
1464    if new_count != old_count {
1465        return false;
1466    }
1467    let mut new_pairs = query_indices
1468        .iter()
1469        .copied()
1470        .zip(landmark_ids.iter().copied())
1471        .take(new_count)
1472        .collect::<Vec<_>>();
1473    let mut old_pairs = estimated
1474        .inlier_query_indices
1475        .iter()
1476        .copied()
1477        .zip(estimated.inlier_landmark_ids.iter().copied())
1478        .take(old_count)
1479        .collect::<Vec<_>>();
1480    new_pairs.sort_unstable();
1481    old_pairs.sort_unstable();
1482    new_pairs == old_pairs
1483}
1484
1485impl<X, M, S, E> ImageLocalizer<X, LocalizationPipeline<M, S, E>>
1486where
1487    X: FeatureExtractor,
1488    M: Matcher + Clone,
1489    S: CandidateSelector + Clone,
1490    E: RobustPoseEstimator + Clone,
1491{
1492    pub fn localize_image(
1493        &self,
1494        image: &X::Image,
1495        camera: Camera,
1496        map: &VisualMap,
1497    ) -> Result<LocalizationResult, X::Error> {
1498        self.pipeline
1499            .localize_image_with_extractor(image, camera, map, &self.extractor)
1500    }
1501
1502    pub fn localize_image_with_descriptor_store(
1503        &self,
1504        image: &X::Image,
1505        camera: Camera,
1506        map: &VisualMap,
1507        descriptor_store: &LandmarkDescriptorStore,
1508    ) -> Result<LocalizationResult, X::Error> {
1509        self.pipeline
1510            .localize_image_with_extractor_and_descriptor_store(
1511                image,
1512                camera,
1513                map,
1514                descriptor_store,
1515                &self.extractor,
1516            )
1517    }
1518
1519    pub fn localize_image_with_provider<P2>(
1520        &self,
1521        image: &X::Image,
1522        camera: Camera,
1523        provider: &P2,
1524    ) -> Result<LocalizationResult, X::Error>
1525    where
1526        P2: MapProvider + DescriptorProvider,
1527    {
1528        self.pipeline.localize_image_with_extractor_and_provider(
1529            image,
1530            camera,
1531            provider,
1532            &self.extractor,
1533        )
1534    }
1535
1536    pub fn localize_frame_image(
1537        &self,
1538        frame_id: FrameId,
1539        camera_id: CameraId,
1540        image: &X::Image,
1541        map: &VisualMap,
1542    ) -> Result<FrameLocalizationResult, X::Error> {
1543        self.pipeline.localize_frame_image_with_extractor(
1544            frame_id,
1545            camera_id,
1546            image,
1547            map,
1548            &self.extractor,
1549        )
1550    }
1551
1552    pub fn localize_frame_image_with_descriptor_store(
1553        &self,
1554        frame_id: FrameId,
1555        camera_id: CameraId,
1556        image: &X::Image,
1557        map: &VisualMap,
1558        descriptor_store: &LandmarkDescriptorStore,
1559    ) -> Result<FrameLocalizationResult, X::Error> {
1560        self.pipeline
1561            .localize_frame_image_with_extractor_and_descriptor_store(
1562                frame_id,
1563                camera_id,
1564                image,
1565                map,
1566                descriptor_store,
1567                &self.extractor,
1568            )
1569    }
1570
1571    pub fn localize_frame_image_with_provider<P2>(
1572        &self,
1573        frame_id: FrameId,
1574        camera_id: CameraId,
1575        image: &X::Image,
1576        provider: &P2,
1577    ) -> Result<FrameLocalizationResult, X::Error>
1578    where
1579        P2: MapProvider + DescriptorProvider,
1580    {
1581        self.pipeline
1582            .localize_frame_image_with_extractor_and_provider(
1583                frame_id,
1584                camera_id,
1585                image,
1586                provider,
1587                &self.extractor,
1588            )
1589    }
1590}
1591
1592pub fn localize(query: QueryImage, map: VisualMap) -> LocalizationResult {
1593    LocalizationPipeline::<BruteForceMatcher, AllLandmarksSelector, LocalizationRansac>::default()
1594        .localize(&query, &map)
1595}
1596
1597pub fn localize_frame(frame: Frame, map: VisualMap) -> LocalizationResult {
1598    LocalizationPipeline::<BruteForceMatcher, AllLandmarksSelector, LocalizationRansac>::default()
1599        .localize_frame(&frame, &map)
1600}
1601
1602pub fn localize_frames(frames: Vec<Frame>, map: VisualMap) -> Vec<FrameLocalizationResult> {
1603    LocalizationPipeline::<BruteForceMatcher, AllLandmarksSelector, LocalizationRansac>::default()
1604        .localize_frames(&frames, &map)
1605}
1606
1607pub fn localize_with_descriptor_store(
1608    query: QueryImage,
1609    map: VisualMap,
1610    descriptor_store: LandmarkDescriptorStore,
1611) -> LocalizationResult {
1612    LocalizationPipeline::<BruteForceMatcher, AllLandmarksSelector, LocalizationRansac>::default()
1613        .localize_with_descriptor_store(&query, &map, &descriptor_store)
1614}
1615
1616pub fn localize_frame_with_descriptor_store(
1617    frame: Frame,
1618    map: VisualMap,
1619    descriptor_store: LandmarkDescriptorStore,
1620) -> LocalizationResult {
1621    LocalizationPipeline::<BruteForceMatcher, AllLandmarksSelector, LocalizationRansac>::default()
1622        .localize_frame_with_descriptor_store(&frame, &map, &descriptor_store)
1623}
1624
1625pub fn localize_frames_with_descriptor_store(
1626    frames: Vec<Frame>,
1627    map: VisualMap,
1628    descriptor_store: LandmarkDescriptorStore,
1629) -> Vec<FrameLocalizationResult> {
1630    LocalizationPipeline::<BruteForceMatcher, AllLandmarksSelector, LocalizationRansac>::default()
1631        .localize_frames_with_descriptor_store(&frames, &map, &descriptor_store)
1632}
1633
1634fn query_from_features(camera: Camera, features: FeatureSet) -> QueryImage {
1635    QueryImage {
1636        camera,
1637        keypoints: features.keypoints,
1638        descriptors: features.descriptors,
1639    }
1640}
1641
1642const fn result_from_correspondence_error(error: CorrespondenceBuildError) -> LocalizationResult {
1643    match error {
1644        CorrespondenceBuildError::QueryFeatureShapeMismatch {
1645            keypoint_count,
1646            descriptor_count,
1647        } => LocalizationResult::failure(
1648            LocalizationFailureReason::QueryFeatureShapeMismatch {
1649                keypoint_count,
1650                descriptor_count,
1651            },
1652            0,
1653            0,
1654            0,
1655        ),
1656        CorrespondenceBuildError::NoCandidateLandmarks => {
1657            LocalizationResult::failure(LocalizationFailureReason::NoCandidateLandmarks, 0, 0, 0)
1658        }
1659        CorrespondenceBuildError::NoMapDescriptors {
1660            candidate_landmark_count,
1661        } => LocalizationResult::failure(
1662            LocalizationFailureReason::NoMapDescriptors,
1663            candidate_landmark_count,
1664            0,
1665            0,
1666        ),
1667        CorrespondenceBuildError::NoDescriptorMatches {
1668            candidate_landmark_count,
1669        } => LocalizationResult::failure(
1670            LocalizationFailureReason::NoDescriptorMatches,
1671            candidate_landmark_count,
1672            0,
1673            0,
1674        ),
1675        CorrespondenceBuildError::InvalidQueryLandmarkRatio => LocalizationResult::failure(
1676            LocalizationFailureReason::InvalidProjectionQueryLandmarkRatio,
1677            0,
1678            0,
1679            0,
1680        ),
1681    }
1682}
1683
1684fn passes_quality_gate(result: &LocalizationResult, config: &LocalizationConfig) -> bool {
1685    if result.inlier_count < config.min_inliers {
1686        return false;
1687    }
1688    if result.inlier_ratio < config.min_inlier_ratio {
1689        return false;
1690    }
1691    if let Some(max_error) = config.max_mean_reprojection_error {
1692        if result.reprojection_error.unwrap_or(f64::INFINITY) > max_error {
1693            return false;
1694        }
1695    }
1696    if let Some(max_error) = config.max_median_reprojection_error {
1697        if result.median_reprojection_error.unwrap_or(f64::INFINITY) > max_error {
1698            return false;
1699        }
1700    }
1701    if let Some(max_error) = config.max_reprojection_error {
1702        if result.max_reprojection_error.unwrap_or(f64::INFINITY) > max_error {
1703            return false;
1704        }
1705    }
1706    true
1707}
1708
1709#[cfg(test)]
1710mod confidence_weight_tests {
1711    use super::*;
1712    use nalgebra::{Point2, Point3};
1713    use visloc_vision::pnp::Correspondence2D3D;
1714
1715    fn correspondence(confidence: Option<f32>) -> Correspondence2D3D {
1716        Correspondence2D3D {
1717            point2d: Point2::origin(),
1718            point3d: Point3::new(0.0, 0.0, 1.0),
1719            confidence,
1720        }
1721    }
1722
1723    #[test]
1724    fn mixed_confidence_keeps_classical_correspondences_uniform() {
1725        let correspondences = vec![correspondence(None), correspondence(Some(0.25))];
1726        assert_eq!(
1727            correspondence_confidence_weights(&correspondences),
1728            Some(vec![1.0, 0.25])
1729        );
1730    }
1731
1732    #[test]
1733    fn all_classical_correspondences_keep_unweighted_path() {
1734        let correspondences = vec![correspondence(None), correspondence(None)];
1735        assert_eq!(correspondence_confidence_weights(&correspondences), None);
1736    }
1737}