Skip to main content

visloc_slam/
map_atlas.rs

1//! Independent visual-map ownership and verified metric SE(3) map welding.
2//!
3//! A [`MapAtlas`] keeps every submap in its own local world frame. Geometry is
4//! transformed only when a verified cross-submap edge aligns that submap to an
5//! already-aligned target. [`MapAtlas::materialize_aligned`] then creates a
6//! collision-free flat [`VisualMap`] for existing consumers; the source maps
7//! remain untouched.
8
9use std::collections::{BTreeMap, HashMap, HashSet};
10use std::error::Error;
11use std::fmt;
12
13use nalgebra::{Matrix3, Point3, UnitQuaternion};
14use visloc_core::geometry::{Pose, SE3};
15use visloc_core::types::{
16    Camera, CameraId, FrameId, Keyframe, Landmark, LandmarkDescriptorStore, LandmarkId,
17    Observation, QueryImage, StereoObservation, VisualMap,
18};
19use visloc_localization::{CandidateSelector, LocalizationPipeline};
20use visloc_vision::matching::Matcher;
21use visloc_vision::ransac::RobustPoseEstimator;
22
23use crate::online_slam::{relocalization_descriptor_cosine, relocalization_mean_descriptor};
24
25pub type SubmapId = u64;
26
27#[derive(Debug, Clone, PartialEq)]
28pub struct AtlasSubmap {
29    pub id: SubmapId,
30    pub map: VisualMap,
31    /// `T_atlas<-local`; `None` means this submap is still independent.
32    pub atlas_from_local: Option<SE3>,
33}
34
35#[derive(Debug, Clone, PartialEq)]
36pub struct SubmapMergeEvidence {
37    pub source_submap_id: SubmapId,
38    pub target_submap_id: SubmapId,
39    /// Metric rigid transform `T_target<-source` recovered from cross-submap
40    /// geometry. Scale is reported separately and must pass the metric gate.
41    pub target_from_source: SE3,
42    pub inlier_count: usize,
43    pub inlier_ratio: f64,
44    pub mean_reprojection_error_px: f64,
45    pub estimated_scale: f64,
46}
47
48#[derive(Debug, Clone, Copy, PartialEq)]
49pub struct SubmapMergeQuality {
50    pub inlier_count: usize,
51    pub inlier_ratio: f64,
52    pub mean_reprojection_error_px: f64,
53    pub estimated_scale: f64,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq)]
57pub struct SubmapMergeVerificationConfig {
58    pub min_inliers: usize,
59    pub min_inlier_ratio: f64,
60    pub max_mean_reprojection_error_px: f64,
61    pub max_metric_scale_error: f64,
62    /// When both maps are already aligned, bound disagreement with the
63    /// existing Atlas transform rather than silently changing its gauge.
64    pub max_existing_translation_disagreement_m: f64,
65    pub max_existing_rotation_disagreement_rad: f64,
66}
67
68impl Default for SubmapMergeVerificationConfig {
69    fn default() -> Self {
70        Self {
71            min_inliers: 30,
72            min_inlier_ratio: 0.3,
73            max_mean_reprojection_error_px: 3.0,
74            max_metric_scale_error: 0.1,
75            max_existing_translation_disagreement_m: 0.5,
76            max_existing_rotation_disagreement_rad: 5.0_f64.to_radians(),
77        }
78    }
79}
80
81/// Appearance retrieval and independent metric-scale checks applied before a
82/// cross-submap PnP bridge is admitted to the Atlas.
83#[derive(Debug, Clone, PartialEq)]
84pub struct CrossSubmapAlignmentConfig {
85    /// Maximum aligned target submaps on which to run descriptor matching and
86    /// PnP. Each submap is represented in retrieval by its best keyframe.
87    pub max_target_submaps: usize,
88    /// Minimum cosine similarity between mean frame descriptors.
89    pub min_appearance_similarity: f32,
90    /// Minimum candidate-keyframe landmark descriptors required for PnP.
91    pub min_candidate_landmarks: usize,
92    /// Bound the quadratic pair-distance scale estimator.
93    pub max_scale_points: usize,
94    /// Ignore 3D pairs with a shorter baseline in either submap.
95    pub min_scale_pair_distance_m: f64,
96    /// Minimum number of pair-distance ratios supporting the scale estimate.
97    pub min_scale_pair_count: usize,
98    /// Relative distance from the median scale counted as scale consensus.
99    pub scale_inlier_relative_tolerance: f64,
100    /// Minimum fraction of distance ratios inside the scale consensus band.
101    pub min_scale_inlier_ratio: f64,
102    /// Maximum median absolute deviation of the inlier scale ratios.
103    pub max_scale_mad: f64,
104    /// Maximum transformed 3D distance for retaining a verified landmark
105    /// equivalence used during map welding.
106    pub max_landmark_match_residual_m: f64,
107    /// Minimum retained source/target landmark equivalences required before
108    /// the bridge may weld map structure.
109    pub min_landmark_matches_for_welding: usize,
110    /// Optional projection window for a causal Atlas-frame pose prior. The
111    /// prior only harvests correspondences; PnP and all merge gates still run.
112    pub projection_search_radius_px: Option<f64>,
113    /// Retry descriptor-global localization when projection-guided PnP fails.
114    pub appearance_fallback_on_projection_failure: bool,
115    pub merge_verification: SubmapMergeVerificationConfig,
116}
117
118impl Default for CrossSubmapAlignmentConfig {
119    fn default() -> Self {
120        Self {
121            max_target_submaps: 5,
122            min_appearance_similarity: 0.2,
123            min_candidate_landmarks: 30,
124            max_scale_points: 64,
125            min_scale_pair_distance_m: 0.05,
126            min_scale_pair_count: 15,
127            scale_inlier_relative_tolerance: 0.1,
128            min_scale_inlier_ratio: 0.6,
129            max_scale_mad: 0.05,
130            max_landmark_match_residual_m: 0.25,
131            min_landmark_matches_for_welding: 8,
132            projection_search_radius_px: Some(30.0),
133            appearance_fallback_on_projection_failure: true,
134            merge_verification: SubmapMergeVerificationConfig::default(),
135        }
136    }
137}
138
139#[derive(Debug, Clone, Copy, PartialEq)]
140pub struct CrossSubmapScaleEstimate {
141    pub estimated_scale: f64,
142    pub pair_count: usize,
143    pub inlier_count: usize,
144    pub inlier_ratio: f64,
145    pub median_absolute_deviation: f64,
146}
147
148#[derive(Debug, Clone, Copy, PartialEq)]
149pub struct CrossSubmapLandmarkMatch {
150    pub source_landmark_id: LandmarkId,
151    pub target_landmark_id: LandmarkId,
152    pub transformed_distance_m: f64,
153}
154
155#[derive(Debug, Clone, PartialEq)]
156pub enum CrossSubmapCandidateFailureReason {
157    TooFewCandidateLandmarks { actual: usize, minimum: usize },
158    LocalizationRejected,
159    TooFewMetricPointCorrespondences { actual: usize, minimum: usize },
160    TooFewScalePairs { actual: usize, minimum: usize },
161    LowScaleInlierRatio { actual: f64, minimum: f64 },
162    HighScaleMedianAbsoluteDeviation { actual: f64, maximum: f64 },
163    RigidAlignmentFailed,
164    TooFewRigidInliers { actual: usize, minimum: usize },
165    TooFewWeldableLandmarkMatches { actual: usize, minimum: usize },
166    MergeRejected(MapAtlasError),
167}
168
169#[derive(Debug, Clone, PartialEq)]
170pub struct CrossSubmapCandidateDiagnostic {
171    pub target_submap_id: SubmapId,
172    pub target_frame_id: FrameId,
173    pub appearance_similarity: f32,
174    pub candidate_landmark_count: usize,
175    pub used_projection_prior: bool,
176    pub localization_correspondence_count: usize,
177    pub localization_inlier_count: usize,
178    pub localization_inlier_ratio: f64,
179    pub mean_reprojection_error_px: Option<f64>,
180    pub scale_estimate: Option<CrossSubmapScaleEstimate>,
181    pub failure_reason: Option<CrossSubmapCandidateFailureReason>,
182}
183
184#[derive(Debug, Clone, PartialEq)]
185pub struct CrossSubmapAlignmentResult {
186    pub source_submap_id: SubmapId,
187    pub source_frame_id: FrameId,
188    pub ranked_candidate_count: usize,
189    pub best_appearance_similarity: Option<f32>,
190    pub diagnostics: Vec<CrossSubmapCandidateDiagnostic>,
191    pub verified_merge: Option<VerifiedSubmapMerge>,
192}
193
194/// Aggregate result for a broader recovery pass over multiple retained source
195/// keyframes. Individual alignment diagnostics remain available so callers
196/// can audit which boundary/current view supplied the verified bridge.
197#[derive(Debug, Clone, PartialEq)]
198pub struct CrossSubmapWindowAlignmentResult {
199    pub source_submap_id: SubmapId,
200    pub requested_source_frame_count: usize,
201    pub attempted_source_frame_ids: Vec<FrameId>,
202    pub alignments: Vec<CrossSubmapAlignmentResult>,
203    pub verified_merge: Option<VerifiedSubmapMerge>,
204}
205
206/// Auditable result of a DROID-style boundary factor: descriptors are matched
207/// directly between the last tracked frame of the old submap and the stereo
208/// seed of the new submap, then verified in metric 3D before Atlas admission.
209#[derive(Debug, Clone, PartialEq)]
210pub struct CrossSubmapBoundaryFactorResult {
211    pub source_submap_id: SubmapId,
212    pub source_frame_id: FrameId,
213    pub target_submap_id: SubmapId,
214    pub target_frame_id: FrameId,
215    pub descriptor_match_count: usize,
216    pub spatial_mutual_match_count: usize,
217    pub metric_correspondence_count: usize,
218    pub projection_refined_correspondence_count: usize,
219    pub projection_refinement_iterations: usize,
220    pub used_transform_prior: bool,
221    pub rigid_inlier_count: usize,
222    pub rigid_inlier_ratio: f64,
223    pub mean_target_reprojection_error_px: Option<f64>,
224    pub scale_estimate: Option<CrossSubmapScaleEstimate>,
225    pub failure_reason: Option<CrossSubmapCandidateFailureReason>,
226    pub verified_merge: Option<VerifiedSubmapMerge>,
227}
228
229#[derive(Debug, Clone, PartialEq)]
230pub struct VerifiedSubmapMerge {
231    pub evidence: SubmapMergeEvidence,
232    pub atlas_from_source: SE3,
233    /// Geometrically verified same-point relations. Empty for pose-only
234    /// bridges supplied through [`MapAtlas::verify_and_align`].
235    pub landmark_matches: Vec<CrossSubmapLandmarkMatch>,
236}
237
238#[derive(Debug, Clone, PartialEq, Eq, Default)]
239pub struct SubmapIdRemap {
240    pub camera_ids: BTreeMap<CameraId, CameraId>,
241    pub frame_ids: BTreeMap<FrameId, FrameId>,
242    pub landmark_ids: BTreeMap<LandmarkId, LandmarkId>,
243}
244
245#[derive(Debug, Clone, PartialEq)]
246pub struct MaterializedAtlas {
247    pub map: VisualMap,
248    pub id_remaps: BTreeMap<SubmapId, SubmapIdRemap>,
249}
250
251#[derive(Debug, Clone, PartialEq)]
252pub enum MapAtlasError {
253    MissingSubmap(SubmapId),
254    MissingKeyframe {
255        submap_id: SubmapId,
256        frame_id: FrameId,
257    },
258    MissingKeyframePose {
259        submap_id: SubmapId,
260        frame_id: FrameId,
261    },
262    MissingLandmark {
263        submap_id: SubmapId,
264        landmark_id: LandmarkId,
265    },
266    NonFiniteLandmarkMatchDistance,
267    TargetSubmapUnaligned(SubmapId),
268    SameSubmapMerge(SubmapId),
269    InsufficientInliers {
270        actual: usize,
271        minimum: usize,
272    },
273    InlierRatioBelowMinimum {
274        actual: f64,
275        minimum: f64,
276    },
277    ReprojectionErrorAboveMaximum {
278        actual: f64,
279        maximum: f64,
280    },
281    MetricScaleInconsistent {
282        actual: f64,
283        maximum_error: f64,
284    },
285    ExistingAlignmentInconsistent {
286        translation_disagreement_m: f64,
287        rotation_disagreement_rad: f64,
288    },
289    NonFiniteTransform,
290    IdSpaceExhausted,
291}
292
293impl fmt::Display for MapAtlasError {
294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295        match self {
296            Self::MissingSubmap(id) => write!(f, "missing submap {id}"),
297            Self::MissingKeyframe {
298                submap_id,
299                frame_id,
300            } => write!(f, "submap {submap_id} is missing keyframe {frame_id}"),
301            Self::MissingKeyframePose {
302                submap_id,
303                frame_id,
304            } => write!(f, "submap {submap_id} keyframe {frame_id} has no pose"),
305            Self::MissingLandmark {
306                submap_id,
307                landmark_id,
308            } => write!(f, "submap {submap_id} is missing landmark {landmark_id}"),
309            Self::NonFiniteLandmarkMatchDistance => {
310                write!(f, "landmark match distance is non-finite or negative")
311            }
312            Self::TargetSubmapUnaligned(id) => write!(f, "target submap {id} is not aligned"),
313            Self::SameSubmapMerge(id) => write!(f, "cannot merge submap {id} with itself"),
314            Self::InsufficientInliers { actual, minimum } => {
315                write!(f, "merge has {actual} inliers; need at least {minimum}")
316            }
317            Self::InlierRatioBelowMinimum { actual, minimum } => {
318                write!(f, "merge inlier ratio {actual} is below {minimum}")
319            }
320            Self::ReprojectionErrorAboveMaximum { actual, maximum } => {
321                write!(f, "merge reprojection error {actual} px exceeds {maximum} px")
322            }
323            Self::MetricScaleInconsistent {
324                actual,
325                maximum_error,
326            } => write!(
327                f,
328                "merge metric scale {actual} differs from one by more than {maximum_error}"
329            ),
330            Self::ExistingAlignmentInconsistent {
331                translation_disagreement_m,
332                rotation_disagreement_rad,
333            } => write!(
334                f,
335                "merge disagrees with Atlas by {translation_disagreement_m} m / {rotation_disagreement_rad} rad"
336            ),
337            Self::NonFiniteTransform => write!(f, "merge transform contains non-finite values"),
338            Self::IdSpaceExhausted => write!(f, "materialized Atlas id space exhausted"),
339        }
340    }
341}
342
343impl Error for MapAtlasError {}
344
345#[derive(Debug, Clone, PartialEq, Default)]
346pub struct MapAtlas {
347    submaps: BTreeMap<SubmapId, AtlasSubmap>,
348    verified_merges: Vec<VerifiedSubmapMerge>,
349    next_submap_id: SubmapId,
350    root_submap_id: Option<SubmapId>,
351}
352
353impl MapAtlas {
354    pub fn new(root_map: VisualMap) -> Self {
355        let mut atlas = Self::default();
356        let root_id = atlas.insert_independent(root_map);
357        atlas.root_submap_id = Some(root_id);
358        atlas.submaps.get_mut(&root_id).unwrap().atlas_from_local = Some(SE3::identity());
359        atlas
360    }
361
362    /// Insert an independent local map without transforming or combining its
363    /// frame/landmark id space with any existing map.
364    pub fn insert_independent(&mut self, map: VisualMap) -> SubmapId {
365        self.try_insert_independent(map)
366            .expect("MapAtlas submap id space exhausted")
367    }
368
369    /// Fallible counterpart to [`Self::insert_independent`] for long-running
370    /// services that must surface identifier exhaustion instead of panicking.
371    pub fn try_insert_independent(&mut self, map: VisualMap) -> Result<SubmapId, MapAtlasError> {
372        let id = self.next_submap_id;
373        self.next_submap_id = self
374            .next_submap_id
375            .checked_add(1)
376            .ok_or(MapAtlasError::IdSpaceExhausted)?;
377        self.submaps.insert(
378            id,
379            AtlasSubmap {
380                id,
381                map,
382                atlas_from_local: None,
383            },
384        );
385        Ok(id)
386    }
387
388    pub const fn root_submap_id(&self) -> Option<SubmapId> {
389        self.root_submap_id
390    }
391
392    pub fn active_submaps(&self) -> impl Iterator<Item = &AtlasSubmap> {
393        self.submaps.values()
394    }
395
396    pub fn submap(&self, id: SubmapId) -> Option<&AtlasSubmap> {
397        self.submaps.get(&id)
398    }
399
400    pub fn submap_mut(&mut self, id: SubmapId) -> Option<&mut AtlasSubmap> {
401        self.submaps.get_mut(&id)
402    }
403
404    /// Refresh an owned submap from its active online pipeline while retaining
405    /// the submap's local gauge and any verified Atlas alignment.
406    pub fn replace_submap_map(
407        &mut self,
408        id: SubmapId,
409        map: VisualMap,
410    ) -> Result<VisualMap, MapAtlasError> {
411        let submap = self
412            .submaps
413            .get_mut(&id)
414            .ok_or(MapAtlasError::MissingSubmap(id))?;
415        Ok(std::mem::replace(&mut submap.map, map))
416    }
417
418    pub fn aligned_submap_count(&self) -> usize {
419        self.submaps
420            .values()
421            .filter(|submap| submap.atlas_from_local.is_some())
422            .count()
423    }
424
425    pub fn independent_submap_count(&self) -> usize {
426        self.submaps
427            .len()
428            .saturating_sub(self.aligned_submap_count())
429    }
430
431    pub fn verified_merges(&self) -> &[VerifiedSubmapMerge] {
432        &self.verified_merges
433    }
434
435    /// Deterministic source window for Atlas-level broader recovery. The
436    /// current view is tried first, followed by the earliest boundary views,
437    /// then recent retained keyframes. This keeps the cheap causal attempt
438    /// first while preserving overlap that may have disappeared after a cliff.
439    pub fn source_keyframe_recovery_window(
440        &self,
441        source_submap_id: SubmapId,
442        current_frame_id: FrameId,
443        maximum: usize,
444    ) -> Result<Vec<FrameId>, MapAtlasError> {
445        let source = self
446            .submaps
447            .get(&source_submap_id)
448            .ok_or(MapAtlasError::MissingSubmap(source_submap_id))?;
449        if !source.map.keyframes.contains_key(&current_frame_id) {
450            return Err(MapAtlasError::MissingKeyframe {
451                submap_id: source_submap_id,
452                frame_id: current_frame_id,
453            });
454        }
455        let maximum = maximum.max(1);
456        let mut sorted = source.map.keyframes.keys().copied().collect::<Vec<_>>();
457        sorted.sort_unstable();
458        let mut window = Vec::with_capacity(maximum.min(sorted.len()));
459        let mut seen = HashSet::new();
460        let mut push = |frame_id: FrameId| {
461            if window.len() < maximum && seen.insert(frame_id) {
462                window.push(frame_id);
463            }
464        };
465        push(current_frame_id);
466        for frame_id in sorted.iter().take(2).copied() {
467            push(frame_id);
468        }
469        for frame_id in sorted.iter().rev().copied() {
470            push(frame_id);
471        }
472        Ok(window)
473    }
474
475    /// Retry cross-submap alignment over retained current/boundary keyframes.
476    /// The map-frame prior derives projection windows only; every candidate
477    /// still passes PnP, metric scale, 3D residual, and merge verification.
478    #[allow(clippy::too_many_arguments)]
479    pub fn align_submap_keyframe_window<M, S, E>(
480        &mut self,
481        source_submap_id: SubmapId,
482        source_frame_ids: &[FrameId],
483        source_camera: &Camera,
484        atlas_from_source_prior: Option<&SE3>,
485        localizer: &LocalizationPipeline<M, S, E>,
486        config: &CrossSubmapAlignmentConfig,
487    ) -> Result<CrossSubmapWindowAlignmentResult, MapAtlasError>
488    where
489        M: Matcher + Clone,
490        S: CandidateSelector + Clone,
491        E: RobustPoseEstimator + Clone,
492    {
493        if !self.submaps.contains_key(&source_submap_id) {
494            return Err(MapAtlasError::MissingSubmap(source_submap_id));
495        }
496        let mut attempted_source_frame_ids = Vec::new();
497        let mut alignments = Vec::new();
498        let mut verified_merge = None;
499        let mut seen = HashSet::new();
500        for source_frame_id in source_frame_ids.iter().copied() {
501            if !seen.insert(source_frame_id) {
502                continue;
503            }
504            let atlas_pose_prior = if let Some(atlas_from_source_prior) = atlas_from_source_prior {
505                let source = self
506                    .submaps
507                    .get(&source_submap_id)
508                    .ok_or(MapAtlasError::MissingSubmap(source_submap_id))?;
509                let keyframe = source.map.keyframes.get(&source_frame_id).ok_or(
510                    MapAtlasError::MissingKeyframe {
511                        submap_id: source_submap_id,
512                        frame_id: source_frame_id,
513                    },
514                )?;
515                let pose =
516                    keyframe
517                        .frame
518                        .pose
519                        .as_ref()
520                        .ok_or(MapAtlasError::MissingKeyframePose {
521                            submap_id: source_submap_id,
522                            frame_id: source_frame_id,
523                        })?;
524                Some(Pose {
525                    world_to_camera: pose
526                        .world_to_camera
527                        .compose(&atlas_from_source_prior.inverse()),
528                })
529            } else {
530                None
531            };
532            attempted_source_frame_ids.push(source_frame_id);
533            let alignment = self.align_submap_keyframe(
534                source_submap_id,
535                source_frame_id,
536                source_camera,
537                atlas_pose_prior.as_ref(),
538                localizer,
539                config,
540            )?;
541            if let Some(verified) = alignment.verified_merge.as_ref() {
542                verified_merge = Some(verified.clone());
543                alignments.push(alignment);
544                break;
545            }
546            alignments.push(alignment);
547        }
548        Ok(CrossSubmapWindowAlignmentResult {
549            source_submap_id,
550            requested_source_frame_count: source_frame_ids.len(),
551            attempted_source_frame_ids,
552            alignments,
553            verified_merge,
554        })
555    }
556
557    #[allow(clippy::too_many_arguments)]
558    /// Align two adjacent submaps from the explicit frame-to-frame factor at
559    /// their tracking boundary. Unlike map-wide relocalization, this retains
560    /// the actual last-good view and its landmark observations across the
561    /// reset. Descriptor matches are only proposals: deterministic metric
562    /// 3D RANSAC, scale consensus, target-view reprojection, and the normal
563    /// Atlas merge gates remain mandatory.
564    pub fn align_adjacent_boundary_factor<M: Matcher>(
565        &mut self,
566        source_submap_id: SubmapId,
567        source_frame_id: FrameId,
568        target_submap_id: SubmapId,
569        target_frame_id: FrameId,
570        target_from_source_prior: Option<&SE3>,
571        matcher: &M,
572        config: &CrossSubmapAlignmentConfig,
573    ) -> Result<CrossSubmapBoundaryFactorResult, MapAtlasError> {
574        let (source_observed, target_observed, target_pose, target_camera) =
575            {
576                let source = self
577                    .submaps
578                    .get(&source_submap_id)
579                    .ok_or(MapAtlasError::MissingSubmap(source_submap_id))?;
580                let target = self
581                    .submaps
582                    .get(&target_submap_id)
583                    .ok_or(MapAtlasError::MissingSubmap(target_submap_id))?;
584                let source_keyframe = source.map.keyframes.get(&source_frame_id).ok_or(
585                    MapAtlasError::MissingKeyframe {
586                        submap_id: source_submap_id,
587                        frame_id: source_frame_id,
588                    },
589                )?;
590                let target_keyframe = target.map.keyframes.get(&target_frame_id).ok_or(
591                    MapAtlasError::MissingKeyframe {
592                        submap_id: target_submap_id,
593                        frame_id: target_frame_id,
594                    },
595                )?;
596                let target_pose = target_keyframe.frame.pose.clone().ok_or(
597                    MapAtlasError::MissingKeyframePose {
598                        submap_id: target_submap_id,
599                        frame_id: target_frame_id,
600                    },
601                )?;
602                let target_camera = target
603                    .map
604                    .cameras
605                    .get(&target_keyframe.frame.camera_id)
606                    .cloned();
607                let source_observed = source_keyframe
608                    .observations
609                    .iter()
610                    .filter_map(|observation| {
611                        let landmark = source.map.landmarks.get(&observation.landmark_id)?;
612                        let descriptor = source_keyframe
613                            .frame
614                            .descriptors
615                            .get(observation.keypoint_index)?;
616                        Some((
617                            observation.landmark_id,
618                            landmark.position,
619                            observation.xy,
620                            descriptor.clone(),
621                        ))
622                    })
623                    .collect::<Vec<_>>();
624                let target_observed = target_keyframe
625                    .observations
626                    .iter()
627                    .filter_map(|observation| {
628                        let landmark = target.map.landmarks.get(&observation.landmark_id)?;
629                        let descriptor = target_keyframe
630                            .frame
631                            .descriptors
632                            .get(observation.keypoint_index)?;
633                        Some((
634                            observation.landmark_id,
635                            landmark.position,
636                            observation.xy,
637                            descriptor.clone(),
638                        ))
639                    })
640                    .collect::<Vec<_>>();
641                (source_observed, target_observed, target_pose, target_camera)
642            };
643
644        let source_descriptors = source_observed
645            .iter()
646            .map(|(_, _, _, descriptor)| descriptor.clone())
647            .collect::<Vec<_>>();
648        let target_descriptors = target_observed
649            .iter()
650            .map(|(_, _, _, descriptor)| descriptor.clone())
651            .collect::<Vec<_>>();
652        let descriptor_matches =
653            matcher.match_descriptors(&source_descriptors, &target_descriptors);
654        let mut result = CrossSubmapBoundaryFactorResult {
655            source_submap_id,
656            source_frame_id,
657            target_submap_id,
658            target_frame_id,
659            descriptor_match_count: descriptor_matches.len(),
660            spatial_mutual_match_count: 0,
661            metric_correspondence_count: 0,
662            projection_refined_correspondence_count: 0,
663            projection_refinement_iterations: 0,
664            used_transform_prior: target_from_source_prior.is_some(),
665            rigid_inlier_count: 0,
666            rigid_inlier_ratio: 0.0,
667            mean_target_reprojection_error_px: None,
668            scale_estimate: None,
669            failure_reason: None,
670            verified_merge: None,
671        };
672        let boundary_radius_px = config
673            .projection_search_radius_px
674            .map_or(f64::INFINITY, |radius| 3.0 * radius);
675        let mut candidate_pairs = Vec::new();
676        for (source_index, (_, _, source_xy, _)) in source_observed.iter().enumerate() {
677            let Some((target_index, distance)) = target_observed
678                .iter()
679                .enumerate()
680                .map(|(index, (_, _, target_xy, _))| (index, (*source_xy - *target_xy).norm()))
681                .min_by(|left, right| left.1.total_cmp(&right.1))
682            else {
683                continue;
684            };
685            if distance > boundary_radius_px {
686                continue;
687            }
688            let reverse_source_index = source_observed
689                .iter()
690                .enumerate()
691                .min_by(|(_, (_, _, left_xy, _)), (_, (_, _, right_xy, _))| {
692                    (*left_xy - target_observed[target_index].2)
693                        .norm()
694                        .total_cmp(&(*right_xy - target_observed[target_index].2).norm())
695                })
696                .map(|(index, _)| index);
697            if reverse_source_index == Some(source_index) {
698                candidate_pairs.push((source_index, target_index));
699            }
700        }
701        result.spatial_mutual_match_count = candidate_pairs.len();
702        for descriptor_match in descriptor_matches {
703            let pair = (descriptor_match.query_index, descriptor_match.train_index);
704            let Some((_, _, source_xy, _)) = source_observed.get(pair.0) else {
705                continue;
706            };
707            let Some((_, _, target_xy, _)) = target_observed.get(pair.1) else {
708                continue;
709            };
710            if (*source_xy - *target_xy).norm() <= boundary_radius_px
711                && !candidate_pairs.contains(&pair)
712            {
713                candidate_pairs.push(pair);
714            }
715        }
716
717        let mut used_source_landmarks = HashSet::new();
718        let mut used_target_landmarks = HashSet::new();
719        let mut metric = Vec::new();
720        for (source_index, target_index) in candidate_pairs {
721            let (source_landmark_id, source_point, _, _) = source_observed[source_index];
722            let (target_landmark_id, target_point, target_xy, _) = &target_observed[target_index];
723            if used_source_landmarks.insert(source_landmark_id)
724                && used_target_landmarks.insert(*target_landmark_id)
725            {
726                metric.push((
727                    source_landmark_id,
728                    *target_landmark_id,
729                    source_point,
730                    *target_point,
731                    *target_xy,
732                ));
733            }
734        }
735        result.metric_correspondence_count = metric.len();
736        if metric.len() < 3 {
737            result.failure_reason = Some(
738                CrossSubmapCandidateFailureReason::TooFewMetricPointCorrespondences {
739                    actual: metric.len(),
740                    minimum: 3,
741                },
742            );
743            return Ok(result);
744        }
745
746        let point_pairs = metric
747            .iter()
748            .map(|(_, _, source, target, _)| (*source, *target))
749            .collect::<Vec<_>>();
750        let Some((mut target_from_source, mut rigid_inlier_indices)) =
751            estimate_boundary_rigid_transform_ransac(
752                &point_pairs,
753                config.max_landmark_match_residual_m,
754                256,
755            )
756        else {
757            result.failure_reason = Some(CrossSubmapCandidateFailureReason::RigidAlignmentFailed);
758            return Ok(result);
759        };
760
761        // Recurrent geometric update: use the first metric seed to reproject
762        // every observed source landmark into the target boundary view,
763        // rebuild one-to-one correspondences, and solve again. This mirrors
764        // DROID's target-update -> BA loop without weakening Atlas admission.
765        if let Some(camera) = target_camera.as_ref() {
766            let refinement_radius_px = config.projection_search_radius_px.unwrap_or(15.0).min(15.0);
767            let mut projection_transform = target_from_source_prior
768                .cloned()
769                .unwrap_or_else(|| target_from_source.clone());
770            for _ in 0..2 {
771                let mut proposals = Vec::new();
772                for (source_index, (_, source_point, _, _)) in source_observed.iter().enumerate() {
773                    let target_point = projection_transform.transform_point(source_point);
774                    let camera_point = target_pose.transform_world_point(&target_point);
775                    let Some(projected) = camera.project(&camera_point) else {
776                        continue;
777                    };
778                    for (target_index, (_, _, target_xy, _)) in target_observed.iter().enumerate() {
779                        let error = (projected - *target_xy).norm();
780                        if error.is_finite() && error <= refinement_radius_px {
781                            proposals.push((error, source_index, target_index));
782                        }
783                    }
784                }
785                proposals.sort_by(|left, right| {
786                    left.0
787                        .total_cmp(&right.0)
788                        .then_with(|| left.1.cmp(&right.1))
789                        .then_with(|| left.2.cmp(&right.2))
790                });
791                let mut used_sources = HashSet::new();
792                let mut used_targets = HashSet::new();
793                let mut refined_metric = Vec::new();
794                for (_, source_index, target_index) in proposals {
795                    if !used_sources.insert(source_index) || !used_targets.insert(target_index) {
796                        continue;
797                    }
798                    let (source_landmark_id, source_point, _, _) = source_observed[source_index];
799                    let (target_landmark_id, target_point, target_xy, _) =
800                        &target_observed[target_index];
801                    refined_metric.push((
802                        source_landmark_id,
803                        *target_landmark_id,
804                        source_point,
805                        *target_point,
806                        *target_xy,
807                    ));
808                }
809                result.projection_refined_correspondence_count = result
810                    .projection_refined_correspondence_count
811                    .max(refined_metric.len());
812                if refined_metric.len() < 3 {
813                    break;
814                }
815                let refined_points = refined_metric
816                    .iter()
817                    .map(|(_, _, source, target, _)| (*source, *target))
818                    .collect::<Vec<_>>();
819                let Some((refined_transform, refined_inliers)) =
820                    estimate_boundary_rigid_transform_ransac(
821                        &refined_points,
822                        config.max_landmark_match_residual_m,
823                        256,
824                    )
825                else {
826                    break;
827                };
828                result.projection_refinement_iterations += 1;
829                if refined_inliers.len() <= rigid_inlier_indices.len() {
830                    break;
831                }
832                metric = refined_metric;
833                target_from_source = refined_transform;
834                rigid_inlier_indices = refined_inliers;
835                projection_transform = target_from_source.clone();
836            }
837        }
838        result.rigid_inlier_count = rigid_inlier_indices.len();
839        result.rigid_inlier_ratio = rigid_inlier_indices.len() as f64 / metric.len() as f64;
840        if rigid_inlier_indices.len() < config.merge_verification.min_inliers {
841            result.failure_reason = Some(CrossSubmapCandidateFailureReason::TooFewRigidInliers {
842                actual: rigid_inlier_indices.len(),
843                minimum: config.merge_verification.min_inliers,
844            });
845            return Ok(result);
846        }
847
848        let scale_points = rigid_inlier_indices
849            .iter()
850            .map(|index| {
851                let (_, _, source, target, _) = metric[*index];
852                (source, target)
853            })
854            .collect::<Vec<_>>();
855        let scale_estimate = match estimate_cross_submap_scale(&scale_points, config) {
856            Ok(estimate) => estimate,
857            Err(reason) => {
858                result.failure_reason = Some(reason);
859                return Ok(result);
860            }
861        };
862        result.scale_estimate = Some(scale_estimate);
863
864        let reprojection_errors = target_camera
865            .as_ref()
866            .map(|camera| {
867                rigid_inlier_indices
868                    .iter()
869                    .filter_map(|index| {
870                        let (_, _, source_point, _, target_xy) = metric[*index];
871                        let target_point = target_from_source.transform_point(&source_point);
872                        let camera_point = target_pose.transform_world_point(&target_point);
873                        camera
874                            .project(&camera_point)
875                            .map(|projected| (projected - target_xy).norm())
876                    })
877                    .collect::<Vec<_>>()
878            })
879            .unwrap_or_default();
880        let mean_reprojection_error_px = (!reprojection_errors.is_empty())
881            .then(|| reprojection_errors.iter().sum::<f64>() / reprojection_errors.len() as f64);
882        result.mean_target_reprojection_error_px = mean_reprojection_error_px;
883
884        let landmark_matches = rigid_inlier_indices
885            .iter()
886            .map(|index| {
887                let (source_landmark_id, target_landmark_id, source, target, _) = metric[*index];
888                CrossSubmapLandmarkMatch {
889                    source_landmark_id,
890                    target_landmark_id,
891                    transformed_distance_m: (target_from_source.transform_point(&source) - target)
892                        .norm(),
893                }
894            })
895            .collect::<Vec<_>>();
896        if landmark_matches.len() < config.min_landmark_matches_for_welding {
897            result.failure_reason = Some(
898                CrossSubmapCandidateFailureReason::TooFewWeldableLandmarkMatches {
899                    actual: landmark_matches.len(),
900                    minimum: config.min_landmark_matches_for_welding,
901                },
902            );
903            return Ok(result);
904        }
905        let evidence = SubmapMergeEvidence {
906            source_submap_id,
907            target_submap_id,
908            target_from_source,
909            inlier_count: rigid_inlier_indices.len(),
910            inlier_ratio: result.rigid_inlier_ratio,
911            mean_reprojection_error_px: mean_reprojection_error_px.unwrap_or(f64::INFINITY),
912            estimated_scale: scale_estimate.estimated_scale,
913        };
914        match self.verify_and_align_with_landmark_matches(
915            evidence,
916            landmark_matches,
917            &config.merge_verification,
918        ) {
919            Ok(verified) => result.verified_merge = Some(verified),
920            Err(error) => {
921                result.failure_reason =
922                    Some(CrossSubmapCandidateFailureReason::MergeRejected(error));
923            }
924        }
925        Ok(result)
926    }
927
928    /// Retrieve aligned target keyframes by global descriptor, relocalize one
929    /// source keyframe against each candidate's 3D landmarks, independently
930    /// verify metric scale from matched 3D-to-3D distances, and admit the
931    /// first bridge that passes [`Self::verify_and_align`]. Ground truth is
932    /// never consulted.
933    pub fn align_submap_keyframe<M, S, E>(
934        &mut self,
935        source_submap_id: SubmapId,
936        source_frame_id: FrameId,
937        source_camera: &Camera,
938        atlas_pose_prior: Option<&Pose>,
939        localizer: &LocalizationPipeline<M, S, E>,
940        config: &CrossSubmapAlignmentConfig,
941    ) -> Result<CrossSubmapAlignmentResult, MapAtlasError>
942    where
943        M: Matcher + Clone,
944        S: CandidateSelector + Clone,
945        E: RobustPoseEstimator + Clone,
946    {
947        let source = self
948            .submaps
949            .get(&source_submap_id)
950            .ok_or(MapAtlasError::MissingSubmap(source_submap_id))?;
951        let source_keyframe = source
952            .map
953            .keyframes
954            .get(&source_frame_id)
955            .ok_or(MapAtlasError::MissingKeyframe {
956                submap_id: source_submap_id,
957                frame_id: source_frame_id,
958            })?
959            .clone();
960        let source_pose = source_keyframe
961            .frame
962            .pose
963            .as_ref()
964            .ok_or(MapAtlasError::MissingKeyframePose {
965                submap_id: source_submap_id,
966                frame_id: source_frame_id,
967            })?
968            .clone();
969        let Some(source_descriptor) =
970            relocalization_mean_descriptor(&source_keyframe.frame.descriptors)
971        else {
972            return Ok(CrossSubmapAlignmentResult {
973                source_submap_id,
974                source_frame_id,
975                ranked_candidate_count: 0,
976                best_appearance_similarity: None,
977                diagnostics: Vec::new(),
978                verified_merge: None,
979            });
980        };
981
982        let mut source_points_by_query = HashMap::new();
983        for observation in &source_keyframe.observations {
984            if let Some(landmark) = source.map.landmarks.get(&observation.landmark_id) {
985                source_points_by_query
986                    .entry(observation.keypoint_index)
987                    .or_insert((observation.landmark_id, landmark.position));
988            }
989        }
990
991        let mut best_keyframe_by_target_submap = BTreeMap::new();
992        for (target_submap_id, target) in &self.submaps {
993            if *target_submap_id == source_submap_id || target.atlas_from_local.is_none() {
994                continue;
995            }
996            for (target_frame_id, target_keyframe) in &target.map.keyframes {
997                let Some(target_descriptor) =
998                    relocalization_mean_descriptor(&target_keyframe.frame.descriptors)
999                else {
1000                    continue;
1001                };
1002                let similarity =
1003                    relocalization_descriptor_cosine(&source_descriptor, &target_descriptor);
1004                if similarity >= config.min_appearance_similarity {
1005                    let entry = best_keyframe_by_target_submap
1006                        .entry(*target_submap_id)
1007                        .or_insert((*target_frame_id, similarity));
1008                    if similarity > entry.1 || (similarity == entry.1 && *target_frame_id < entry.0)
1009                    {
1010                        *entry = (*target_frame_id, similarity);
1011                    }
1012                }
1013            }
1014        }
1015        let mut ranked = best_keyframe_by_target_submap
1016            .into_iter()
1017            .map(|(submap_id, (frame_id, similarity))| (submap_id, frame_id, similarity))
1018            .collect::<Vec<_>>();
1019        ranked.sort_by(|left, right| {
1020            right
1021                .2
1022                .partial_cmp(&left.2)
1023                .unwrap_or(std::cmp::Ordering::Equal)
1024                .then_with(|| left.0.cmp(&right.0))
1025                .then_with(|| left.1.cmp(&right.1))
1026        });
1027        let ranked_candidate_count = ranked.len();
1028        let best_appearance_similarity = ranked.first().map(|candidate| candidate.2);
1029        let query = QueryImage::from_frame(&source_keyframe.frame, source_camera.clone());
1030        let mut diagnostics = Vec::new();
1031
1032        for (target_submap_id, target_frame_id, appearance_similarity) in
1033            ranked.into_iter().take(config.max_target_submaps.max(1))
1034        {
1035            let (candidate_store, localization, used_projection_prior, target_points) = {
1036                let target = self
1037                    .submaps
1038                    .get(&target_submap_id)
1039                    .ok_or(MapAtlasError::MissingSubmap(target_submap_id))?;
1040                let _target_keyframe = target.map.keyframes.get(&target_frame_id).ok_or(
1041                    MapAtlasError::MissingKeyframe {
1042                        submap_id: target_submap_id,
1043                        frame_id: target_frame_id,
1044                    },
1045                )?;
1046                // Retrieval is keyframe-scoped, but PnP consumes the complete
1047                // target submap. Local mapping may retain only a small subset
1048                // of seed landmarks on any one keyframe; restricting the
1049                // bridge store to that subset creates an artificial cliff.
1050                let mut landmark_ids = target.map.landmarks.keys().copied().collect::<Vec<_>>();
1051                landmark_ids.sort_unstable();
1052                landmark_ids.dedup();
1053                let mut store = LandmarkDescriptorStore::new();
1054                for landmark_id in landmark_ids {
1055                    if let Some(descriptor) = target
1056                        .map
1057                        .landmarks
1058                        .get(&landmark_id)
1059                        .and_then(|landmark| landmark.descriptor.as_ref())
1060                    {
1061                        store.insert(landmark_id, descriptor.clone());
1062                    }
1063                }
1064                if store.len() < config.min_candidate_landmarks {
1065                    diagnostics.push(CrossSubmapCandidateDiagnostic {
1066                        target_submap_id,
1067                        target_frame_id,
1068                        appearance_similarity,
1069                        candidate_landmark_count: store.len(),
1070                        used_projection_prior: false,
1071                        localization_correspondence_count: 0,
1072                        localization_inlier_count: 0,
1073                        localization_inlier_ratio: 0.0,
1074                        mean_reprojection_error_px: None,
1075                        scale_estimate: None,
1076                        failure_reason: Some(
1077                            CrossSubmapCandidateFailureReason::TooFewCandidateLandmarks {
1078                                actual: store.len(),
1079                                minimum: config.min_candidate_landmarks,
1080                            },
1081                        ),
1082                    });
1083                    continue;
1084                }
1085                let projection_result = atlas_pose_prior
1086                    .zip(config.projection_search_radius_px)
1087                    .and_then(|(atlas_pose_prior, search_radius_px)| {
1088                        let atlas_from_target = target.atlas_from_local.as_ref()?;
1089                        let target_pose_prior = Pose {
1090                            world_to_camera: atlas_pose_prior
1091                                .world_to_camera
1092                                .compose(atlas_from_target),
1093                        };
1094                        Some(
1095                            localizer.localize_with_projection_window_and_descriptor_store(
1096                                &query,
1097                                &target.map,
1098                                &store,
1099                                localizer.candidate_selector.clone(),
1100                                &target_pose_prior,
1101                                search_radius_px,
1102                            ),
1103                        )
1104                    });
1105                let (localization, used_projection_prior) = match projection_result {
1106                    Some(result)
1107                        if result.success || !config.appearance_fallback_on_projection_failure =>
1108                    {
1109                        (result, true)
1110                    }
1111                    _ => (
1112                        localizer.localize_with_descriptor_store(&query, &target.map, &store),
1113                        false,
1114                    ),
1115                };
1116                let target_points = target
1117                    .map
1118                    .landmarks
1119                    .iter()
1120                    .map(|(id, landmark)| (*id, landmark.position))
1121                    .collect::<HashMap<_, _>>();
1122                (store, localization, used_projection_prior, target_points)
1123            };
1124
1125            let mut diagnostic = CrossSubmapCandidateDiagnostic {
1126                target_submap_id,
1127                target_frame_id,
1128                appearance_similarity,
1129                candidate_landmark_count: candidate_store.len(),
1130                used_projection_prior,
1131                localization_correspondence_count: localization.correspondence_count,
1132                localization_inlier_count: localization.inlier_count,
1133                localization_inlier_ratio: localization.inlier_ratio,
1134                mean_reprojection_error_px: localization.reprojection_error,
1135                scale_estimate: None,
1136                failure_reason: None,
1137            };
1138            let Some(target_pose) = localization
1139                .success
1140                .then_some(localization.pose.as_ref())
1141                .flatten()
1142            else {
1143                diagnostic.failure_reason =
1144                    Some(CrossSubmapCandidateFailureReason::LocalizationRejected);
1145                diagnostics.push(diagnostic);
1146                continue;
1147            };
1148
1149            let mut used_source_landmarks = HashSet::new();
1150            let mut used_target_landmarks = HashSet::new();
1151            let mut metric_landmark_points = Vec::new();
1152            for (query_index, target_landmark_id) in localization
1153                .inlier_query_indices
1154                .iter()
1155                .copied()
1156                .zip(localization.inlier_landmark_ids.iter().copied())
1157            {
1158                let Some(&(source_landmark_id, source_point)) =
1159                    source_points_by_query.get(&query_index)
1160                else {
1161                    continue;
1162                };
1163                let Some(&target_point) = target_points.get(&target_landmark_id) else {
1164                    continue;
1165                };
1166                if used_source_landmarks.insert(source_landmark_id)
1167                    && used_target_landmarks.insert(target_landmark_id)
1168                {
1169                    metric_landmark_points.push((
1170                        source_landmark_id,
1171                        target_landmark_id,
1172                        source_point,
1173                        target_point,
1174                    ));
1175                }
1176            }
1177            if metric_landmark_points.len() < 3 {
1178                diagnostic.failure_reason = Some(
1179                    CrossSubmapCandidateFailureReason::TooFewMetricPointCorrespondences {
1180                        actual: metric_landmark_points.len(),
1181                        minimum: 3,
1182                    },
1183                );
1184                diagnostics.push(diagnostic);
1185                continue;
1186            }
1187            let metric_points = metric_landmark_points
1188                .iter()
1189                .map(|(_, _, source_point, target_point)| (*source_point, *target_point))
1190                .collect::<Vec<_>>();
1191            let scale_estimate = match estimate_cross_submap_scale(&metric_points, config) {
1192                Ok(estimate) => estimate,
1193                Err(reason) => {
1194                    diagnostic.failure_reason = Some(reason);
1195                    diagnostics.push(diagnostic);
1196                    continue;
1197                }
1198            };
1199            diagnostic.scale_estimate = Some(scale_estimate);
1200
1201            let target_from_source = target_pose
1202                .world_to_camera
1203                .inverse()
1204                .compose(&source_pose.world_to_camera);
1205            let evidence = SubmapMergeEvidence {
1206                source_submap_id,
1207                target_submap_id,
1208                target_from_source: target_from_source.clone(),
1209                inlier_count: localization.inlier_count,
1210                inlier_ratio: localization.inlier_ratio,
1211                mean_reprojection_error_px: localization
1212                    .reprojection_error
1213                    .unwrap_or(f64::INFINITY),
1214                estimated_scale: scale_estimate.estimated_scale,
1215            };
1216            if let Err(error) = validate_merge_evidence(&evidence, &config.merge_verification) {
1217                diagnostic.failure_reason =
1218                    Some(CrossSubmapCandidateFailureReason::MergeRejected(error));
1219                diagnostics.push(diagnostic);
1220                continue;
1221            }
1222            let landmark_matches = metric_landmark_points
1223                .iter()
1224                .filter_map(
1225                    |(source_landmark_id, target_landmark_id, source_point, target_point)| {
1226                        let residual = (target_from_source.transform_point(source_point)
1227                            - target_point)
1228                            .norm();
1229                        (residual.is_finite() && residual <= config.max_landmark_match_residual_m)
1230                            .then_some(CrossSubmapLandmarkMatch {
1231                                source_landmark_id: *source_landmark_id,
1232                                target_landmark_id: *target_landmark_id,
1233                                transformed_distance_m: residual,
1234                            })
1235                    },
1236                )
1237                .collect::<Vec<_>>();
1238            if landmark_matches.len() < config.min_landmark_matches_for_welding {
1239                diagnostic.failure_reason = Some(
1240                    CrossSubmapCandidateFailureReason::TooFewWeldableLandmarkMatches {
1241                        actual: landmark_matches.len(),
1242                        minimum: config.min_landmark_matches_for_welding,
1243                    },
1244                );
1245                diagnostics.push(diagnostic);
1246                continue;
1247            }
1248            match self.verify_and_align_with_landmark_matches(
1249                evidence,
1250                landmark_matches,
1251                &config.merge_verification,
1252            ) {
1253                Ok(verified_merge) => {
1254                    diagnostics.push(diagnostic);
1255                    return Ok(CrossSubmapAlignmentResult {
1256                        source_submap_id,
1257                        source_frame_id,
1258                        ranked_candidate_count,
1259                        best_appearance_similarity,
1260                        diagnostics,
1261                        verified_merge: Some(verified_merge),
1262                    });
1263                }
1264                Err(error) => {
1265                    diagnostic.failure_reason =
1266                        Some(CrossSubmapCandidateFailureReason::MergeRejected(error));
1267                    diagnostics.push(diagnostic);
1268                }
1269            }
1270        }
1271
1272        Ok(CrossSubmapAlignmentResult {
1273            source_submap_id,
1274            source_frame_id,
1275            ranked_candidate_count,
1276            best_appearance_similarity,
1277            diagnostics,
1278            verified_merge: None,
1279        })
1280    }
1281
1282    /// Convert a verified cross-submap keyframe pose into the map-frame
1283    /// transform consumed by [`Self::verify_and_align`].
1284    ///
1285    /// `source_camera_from_target_camera` uses the same `a -> b` convention as
1286    /// [`crate::LoopClosureConstraint::relative_pose`]. If target keyframe `a`
1287    /// has `T_ca<-Wt`, source keyframe `b` has `T_cb<-Ws`, and the bridge is
1288    /// `z = T_cb<-ca`, then:
1289    /// `T_Wt<-Ws = T_ca<-Wt^-1 * z^-1 * T_cb<-Ws`.
1290    #[allow(clippy::too_many_arguments)]
1291    pub fn evidence_from_keyframe_bridge(
1292        &self,
1293        source_submap_id: SubmapId,
1294        source_frame_id: FrameId,
1295        target_submap_id: SubmapId,
1296        target_frame_id: FrameId,
1297        source_camera_from_target_camera: &SE3,
1298        quality: SubmapMergeQuality,
1299    ) -> Result<SubmapMergeEvidence, MapAtlasError> {
1300        let source = self
1301            .submaps
1302            .get(&source_submap_id)
1303            .ok_or(MapAtlasError::MissingSubmap(source_submap_id))?;
1304        let target = self
1305            .submaps
1306            .get(&target_submap_id)
1307            .ok_or(MapAtlasError::MissingSubmap(target_submap_id))?;
1308        let source_keyframe =
1309            source
1310                .map
1311                .keyframes
1312                .get(&source_frame_id)
1313                .ok_or(MapAtlasError::MissingKeyframe {
1314                    submap_id: source_submap_id,
1315                    frame_id: source_frame_id,
1316                })?;
1317        let target_keyframe =
1318            target
1319                .map
1320                .keyframes
1321                .get(&target_frame_id)
1322                .ok_or(MapAtlasError::MissingKeyframe {
1323                    submap_id: target_submap_id,
1324                    frame_id: target_frame_id,
1325                })?;
1326        let source_pose =
1327            source_keyframe
1328                .frame
1329                .pose
1330                .as_ref()
1331                .ok_or(MapAtlasError::MissingKeyframePose {
1332                    submap_id: source_submap_id,
1333                    frame_id: source_frame_id,
1334                })?;
1335        let target_pose =
1336            target_keyframe
1337                .frame
1338                .pose
1339                .as_ref()
1340                .ok_or(MapAtlasError::MissingKeyframePose {
1341                    submap_id: target_submap_id,
1342                    frame_id: target_frame_id,
1343                })?;
1344        let target_from_source = target_pose
1345            .world_to_camera
1346            .inverse()
1347            .compose(&source_camera_from_target_camera.inverse())
1348            .compose(&source_pose.world_to_camera);
1349        Ok(SubmapMergeEvidence {
1350            source_submap_id,
1351            target_submap_id,
1352            target_from_source,
1353            inlier_count: quality.inlier_count,
1354            inlier_ratio: quality.inlier_ratio,
1355            mean_reprojection_error_px: quality.mean_reprojection_error_px,
1356            estimated_scale: quality.estimated_scale,
1357        })
1358    }
1359
1360    /// Verify a metric SE(3) edge and align `source` to an already-aligned
1361    /// `target`. A rejected edge leaves both submaps and Atlas transforms
1362    /// unchanged.
1363    pub fn verify_and_align(
1364        &mut self,
1365        evidence: SubmapMergeEvidence,
1366        config: &SubmapMergeVerificationConfig,
1367    ) -> Result<VerifiedSubmapMerge, MapAtlasError> {
1368        self.verify_and_align_with_landmark_matches(evidence, Vec::new(), config)
1369    }
1370
1371    /// [`Self::verify_and_align`] with verified same-landmark relations that
1372    /// will be welded to one output id by [`Self::materialize_aligned`].
1373    pub fn verify_and_align_with_landmark_matches(
1374        &mut self,
1375        evidence: SubmapMergeEvidence,
1376        landmark_matches: Vec<CrossSubmapLandmarkMatch>,
1377        config: &SubmapMergeVerificationConfig,
1378    ) -> Result<VerifiedSubmapMerge, MapAtlasError> {
1379        if evidence.source_submap_id == evidence.target_submap_id {
1380            return Err(MapAtlasError::SameSubmapMerge(evidence.source_submap_id));
1381        }
1382        let source = self
1383            .submaps
1384            .get(&evidence.source_submap_id)
1385            .ok_or(MapAtlasError::MissingSubmap(evidence.source_submap_id))?;
1386        let target = self
1387            .submaps
1388            .get(&evidence.target_submap_id)
1389            .ok_or(MapAtlasError::MissingSubmap(evidence.target_submap_id))?;
1390        for landmark_match in &landmark_matches {
1391            if !source
1392                .map
1393                .landmarks
1394                .contains_key(&landmark_match.source_landmark_id)
1395            {
1396                return Err(MapAtlasError::MissingLandmark {
1397                    submap_id: evidence.source_submap_id,
1398                    landmark_id: landmark_match.source_landmark_id,
1399                });
1400            }
1401            if !target
1402                .map
1403                .landmarks
1404                .contains_key(&landmark_match.target_landmark_id)
1405            {
1406                return Err(MapAtlasError::MissingLandmark {
1407                    submap_id: evidence.target_submap_id,
1408                    landmark_id: landmark_match.target_landmark_id,
1409                });
1410            }
1411            if !landmark_match.transformed_distance_m.is_finite()
1412                || landmark_match.transformed_distance_m < 0.0
1413            {
1414                return Err(MapAtlasError::NonFiniteLandmarkMatchDistance);
1415            }
1416        }
1417        let atlas_from_target =
1418            target
1419                .atlas_from_local
1420                .clone()
1421                .ok_or(MapAtlasError::TargetSubmapUnaligned(
1422                    evidence.target_submap_id,
1423                ))?;
1424        validate_merge_evidence(&evidence, config)?;
1425
1426        let atlas_from_source = atlas_from_target.compose(&evidence.target_from_source);
1427        if let Some(existing) = source.atlas_from_local.as_ref() {
1428            let disagreement = atlas_from_source.compose(&existing.inverse());
1429            let translation_disagreement_m = disagreement.translation.norm();
1430            let rotation_disagreement_rad = disagreement.rotation.angle();
1431            if translation_disagreement_m > config.max_existing_translation_disagreement_m
1432                || rotation_disagreement_rad > config.max_existing_rotation_disagreement_rad
1433            {
1434                return Err(MapAtlasError::ExistingAlignmentInconsistent {
1435                    translation_disagreement_m,
1436                    rotation_disagreement_rad,
1437                });
1438            }
1439        }
1440
1441        self.submaps
1442            .get_mut(&evidence.source_submap_id)
1443            .unwrap()
1444            .atlas_from_local = Some(atlas_from_source.clone());
1445        let verified = VerifiedSubmapMerge {
1446            evidence,
1447            atlas_from_source,
1448            landmark_matches,
1449        };
1450        self.verified_merges.push(verified.clone());
1451        Ok(verified)
1452    }
1453
1454    /// Materialize all currently aligned submaps into one collision-free map.
1455    /// Independent/unverified submaps are intentionally omitted so unrelated
1456    /// coordinate frames can never leak into a flat-map consumer.
1457    pub fn materialize_aligned(&self) -> Result<MaterializedAtlas, MapAtlasError> {
1458        let mut output = VisualMap::new();
1459        let mut id_remaps = BTreeMap::new();
1460        let mut next_camera_id = 0u64;
1461        let mut next_frame_id = 0u64;
1462        let mut next_landmark_id = 0u64;
1463        let landmark_output_ids = aligned_landmark_output_ids(self, &mut next_landmark_id)?;
1464
1465        for (&submap_id, submap) in &self.submaps {
1466            let Some(atlas_from_local) = submap.atlas_from_local.as_ref() else {
1467                continue;
1468            };
1469            let mut remap = SubmapIdRemap::default();
1470
1471            let mut camera_ids = submap.map.cameras.keys().copied().collect::<Vec<_>>();
1472            camera_ids.sort_unstable();
1473            for old_id in camera_ids {
1474                let new_id = allocate_id(&mut next_camera_id)?;
1475                remap.camera_ids.insert(old_id, new_id);
1476                let mut camera = submap.map.cameras[&old_id].clone();
1477                camera.id = new_id;
1478                output.cameras.insert(new_id, camera);
1479            }
1480
1481            let mut frame_ids = submap.map.keyframes.keys().copied().collect::<Vec<_>>();
1482            frame_ids.sort_unstable();
1483            for old_id in frame_ids {
1484                remap
1485                    .frame_ids
1486                    .insert(old_id, allocate_id(&mut next_frame_id)?);
1487            }
1488            let mut landmark_ids = submap.map.landmarks.keys().copied().collect::<Vec<_>>();
1489            landmark_ids.sort_unstable();
1490            for old_id in landmark_ids {
1491                let output_id = *landmark_output_ids.get(&(submap_id, old_id)).ok_or(
1492                    MapAtlasError::MissingLandmark {
1493                        submap_id,
1494                        landmark_id: old_id,
1495                    },
1496                )?;
1497                remap.landmark_ids.insert(old_id, output_id);
1498            }
1499
1500            append_transformed_submap(&mut output, &submap.map, atlas_from_local, &remap);
1501            id_remaps.insert(submap_id, remap);
1502        }
1503
1504        Ok(MaterializedAtlas {
1505            map: output,
1506            id_remaps,
1507        })
1508    }
1509}
1510
1511fn validate_merge_evidence(
1512    evidence: &SubmapMergeEvidence,
1513    config: &SubmapMergeVerificationConfig,
1514) -> Result<(), MapAtlasError> {
1515    let finite_transform = evidence
1516        .target_from_source
1517        .translation
1518        .iter()
1519        .chain(evidence.target_from_source.rotation.coords.iter())
1520        .all(|value| value.is_finite());
1521    if !finite_transform {
1522        return Err(MapAtlasError::NonFiniteTransform);
1523    }
1524    if evidence.inlier_count < config.min_inliers {
1525        return Err(MapAtlasError::InsufficientInliers {
1526            actual: evidence.inlier_count,
1527            minimum: config.min_inliers,
1528        });
1529    }
1530    if !evidence.inlier_ratio.is_finite() || evidence.inlier_ratio < config.min_inlier_ratio {
1531        return Err(MapAtlasError::InlierRatioBelowMinimum {
1532            actual: evidence.inlier_ratio,
1533            minimum: config.min_inlier_ratio,
1534        });
1535    }
1536    if !evidence.mean_reprojection_error_px.is_finite()
1537        || evidence.mean_reprojection_error_px > config.max_mean_reprojection_error_px
1538    {
1539        return Err(MapAtlasError::ReprojectionErrorAboveMaximum {
1540            actual: evidence.mean_reprojection_error_px,
1541            maximum: config.max_mean_reprojection_error_px,
1542        });
1543    }
1544    if !evidence.estimated_scale.is_finite()
1545        || (evidence.estimated_scale - 1.0).abs() > config.max_metric_scale_error
1546    {
1547        return Err(MapAtlasError::MetricScaleInconsistent {
1548            actual: evidence.estimated_scale,
1549            maximum_error: config.max_metric_scale_error,
1550        });
1551    }
1552    Ok(())
1553}
1554
1555fn estimate_boundary_rigid_transform_ransac(
1556    points: &[(Point3<f64>, Point3<f64>)],
1557    inlier_threshold_m: f64,
1558    iterations: usize,
1559) -> Option<(SE3, Vec<usize>)> {
1560    if points.len() < 3 || !inlier_threshold_m.is_finite() || inlier_threshold_m <= 0.0 {
1561        return None;
1562    }
1563    let fit = |indices: &[usize]| {
1564        let source = indices
1565            .iter()
1566            .map(|index| points[*index].0)
1567            .collect::<Vec<_>>();
1568        let target = indices
1569            .iter()
1570            .map(|index| points[*index].1)
1571            .collect::<Vec<_>>();
1572        let transform = visloc_tracking::umeyama_similarity_transform(&source, &target, false)?;
1573        Some(SE3::new(
1574            UnitQuaternion::from_rotation_matrix(&transform.rotation),
1575            transform.translation,
1576        ))
1577    };
1578    let score = |transform: &SE3| {
1579        let mut inliers = Vec::new();
1580        let mut residual_sum = 0.0;
1581        for (index, (source, target)) in points.iter().enumerate() {
1582            let residual = (transform.transform_point(source) - target).norm();
1583            if residual.is_finite() && residual <= inlier_threshold_m {
1584                inliers.push(index);
1585                residual_sum += residual;
1586            }
1587        }
1588        let mean = if inliers.is_empty() {
1589            f64::INFINITY
1590        } else {
1591            residual_sum / inliers.len() as f64
1592        };
1593        (inliers, mean)
1594    };
1595
1596    let all = (0..points.len()).collect::<Vec<_>>();
1597    let mut best = fit(&all).map(|transform| {
1598        let (inliers, mean) = score(&transform);
1599        (transform, inliers, mean)
1600    });
1601    let mut state = 0x9E37_79B9_7F4A_7C15u64 ^ points.len() as u64;
1602    for _ in 0..iterations.max(1) {
1603        let mut sample = [0usize; 3];
1604        for slot in 0..3 {
1605            let mut attempts = 0;
1606            loop {
1607                state = state
1608                    .wrapping_mul(6_364_136_223_846_793_005)
1609                    .wrapping_add(1_442_695_040_888_963_407);
1610                let index = (state as usize) % points.len();
1611                if !sample[..slot].contains(&index) {
1612                    sample[slot] = index;
1613                    break;
1614                }
1615                attempts += 1;
1616                if attempts > points.len() * 2 {
1617                    break;
1618                }
1619            }
1620        }
1621        let Some(transform) = fit(&sample) else {
1622            continue;
1623        };
1624        let (inliers, mean) = score(&transform);
1625        let replace = best.as_ref().is_none_or(|(_, best_inliers, best_mean)| {
1626            inliers.len() > best_inliers.len()
1627                || (inliers.len() == best_inliers.len() && mean < *best_mean)
1628        });
1629        if replace {
1630            best = Some((transform, inliers, mean));
1631        }
1632    }
1633    let (_, best_inliers, _) = best?;
1634    if best_inliers.len() < 3 {
1635        return None;
1636    }
1637    let refined = fit(&best_inliers)?;
1638    let (refined_inliers, _) = score(&refined);
1639    (refined_inliers.len() >= 3).then_some((refined, refined_inliers))
1640}
1641
1642fn estimate_cross_submap_scale(
1643    metric_points: &[(Point3<f64>, Point3<f64>)],
1644    config: &CrossSubmapAlignmentConfig,
1645) -> Result<CrossSubmapScaleEstimate, CrossSubmapCandidateFailureReason> {
1646    let point_count = metric_points.len().min(config.max_scale_points.max(2));
1647    let mut ratios = Vec::new();
1648    for left in 0..point_count {
1649        for right in (left + 1)..point_count {
1650            let source_distance = (metric_points[left].0 - metric_points[right].0).norm();
1651            let target_distance = (metric_points[left].1 - metric_points[right].1).norm();
1652            if !source_distance.is_finite()
1653                || !target_distance.is_finite()
1654                || source_distance < config.min_scale_pair_distance_m
1655                || target_distance < config.min_scale_pair_distance_m
1656            {
1657                continue;
1658            }
1659            let ratio = target_distance / source_distance;
1660            if ratio.is_finite() && ratio > 0.0 {
1661                ratios.push(ratio);
1662            }
1663        }
1664    }
1665    if ratios.len() < config.min_scale_pair_count {
1666        return Err(CrossSubmapCandidateFailureReason::TooFewScalePairs {
1667            actual: ratios.len(),
1668            minimum: config.min_scale_pair_count,
1669        });
1670    }
1671    ratios.sort_by(f64::total_cmp);
1672    let initial_median = median_sorted(&ratios);
1673    let tolerance = config.scale_inlier_relative_tolerance.max(0.0) * initial_median;
1674    let mut inlier_ratios = ratios
1675        .iter()
1676        .copied()
1677        .filter(|ratio| (*ratio - initial_median).abs() <= tolerance)
1678        .collect::<Vec<_>>();
1679    let inlier_ratio = inlier_ratios.len() as f64 / ratios.len() as f64;
1680    if inlier_ratios.is_empty() || inlier_ratio < config.min_scale_inlier_ratio {
1681        return Err(CrossSubmapCandidateFailureReason::LowScaleInlierRatio {
1682            actual: inlier_ratio,
1683            minimum: config.min_scale_inlier_ratio,
1684        });
1685    }
1686    inlier_ratios.sort_by(f64::total_cmp);
1687    let estimated_scale = median_sorted(&inlier_ratios);
1688    let mut deviations = inlier_ratios
1689        .iter()
1690        .map(|ratio| (*ratio - estimated_scale).abs())
1691        .collect::<Vec<_>>();
1692    deviations.sort_by(f64::total_cmp);
1693    let median_absolute_deviation = median_sorted(&deviations);
1694    if median_absolute_deviation > config.max_scale_mad {
1695        return Err(
1696            CrossSubmapCandidateFailureReason::HighScaleMedianAbsoluteDeviation {
1697                actual: median_absolute_deviation,
1698                maximum: config.max_scale_mad,
1699            },
1700        );
1701    }
1702    Ok(CrossSubmapScaleEstimate {
1703        estimated_scale,
1704        pair_count: ratios.len(),
1705        inlier_count: inlier_ratios.len(),
1706        inlier_ratio,
1707        median_absolute_deviation,
1708    })
1709}
1710
1711fn median_sorted(values: &[f64]) -> f64 {
1712    let middle = values.len() / 2;
1713    if values.len().is_multiple_of(2) {
1714        (values[middle - 1] + values[middle]) * 0.5
1715    } else {
1716        values[middle]
1717    }
1718}
1719
1720fn allocate_id(next: &mut u64) -> Result<u64, MapAtlasError> {
1721    let id = *next;
1722    *next = next.checked_add(1).ok_or(MapAtlasError::IdSpaceExhausted)?;
1723    Ok(id)
1724}
1725
1726type AtlasLandmarkKey = (SubmapId, LandmarkId);
1727
1728fn aligned_landmark_output_ids(
1729    atlas: &MapAtlas,
1730    next_output_id: &mut u64,
1731) -> Result<BTreeMap<AtlasLandmarkKey, LandmarkId>, MapAtlasError> {
1732    let mut parent = BTreeMap::new();
1733    for (&submap_id, submap) in &atlas.submaps {
1734        if submap.atlas_from_local.is_none() {
1735            continue;
1736        }
1737        for &landmark_id in submap.map.landmarks.keys() {
1738            parent.insert((submap_id, landmark_id), (submap_id, landmark_id));
1739        }
1740    }
1741    for merge in &atlas.verified_merges {
1742        if atlas
1743            .submaps
1744            .get(&merge.evidence.source_submap_id)
1745            .and_then(|submap| submap.atlas_from_local.as_ref())
1746            .is_none()
1747            || atlas
1748                .submaps
1749                .get(&merge.evidence.target_submap_id)
1750                .and_then(|submap| submap.atlas_from_local.as_ref())
1751                .is_none()
1752        {
1753            continue;
1754        }
1755        for landmark_match in &merge.landmark_matches {
1756            let source_key = (
1757                merge.evidence.source_submap_id,
1758                landmark_match.source_landmark_id,
1759            );
1760            let target_key = (
1761                merge.evidence.target_submap_id,
1762                landmark_match.target_landmark_id,
1763            );
1764            if parent.contains_key(&source_key) && parent.contains_key(&target_key) {
1765                union_landmark_keys(&mut parent, source_key, target_key);
1766            }
1767        }
1768    }
1769
1770    let keys = parent.keys().copied().collect::<Vec<_>>();
1771    let mut component_ids = BTreeMap::new();
1772    let mut output_ids = BTreeMap::new();
1773    for key in keys {
1774        let root = find_landmark_root(&parent, key);
1775        let output_id = match component_ids.get(&root) {
1776            Some(id) => *id,
1777            None => {
1778                let id = allocate_id(next_output_id)?;
1779                component_ids.insert(root, id);
1780                id
1781            }
1782        };
1783        output_ids.insert(key, output_id);
1784    }
1785    Ok(output_ids)
1786}
1787
1788fn find_landmark_root(
1789    parent: &BTreeMap<AtlasLandmarkKey, AtlasLandmarkKey>,
1790    mut key: AtlasLandmarkKey,
1791) -> AtlasLandmarkKey {
1792    while let Some(&next) = parent.get(&key) {
1793        if next == key {
1794            break;
1795        }
1796        key = next;
1797    }
1798    key
1799}
1800
1801fn union_landmark_keys(
1802    parent: &mut BTreeMap<AtlasLandmarkKey, AtlasLandmarkKey>,
1803    left: AtlasLandmarkKey,
1804    right: AtlasLandmarkKey,
1805) {
1806    let left_root = find_landmark_root(parent, left);
1807    let right_root = find_landmark_root(parent, right);
1808    if left_root == right_root {
1809        return;
1810    }
1811    let (root, child) = if left_root <= right_root {
1812        (left_root, right_root)
1813    } else {
1814        (right_root, left_root)
1815    };
1816    parent.insert(child, root);
1817}
1818
1819fn fuse_landmark_estimates(
1820    existing_position: Point3<f64>,
1821    existing_covariance: Option<&Matrix3<f64>>,
1822    source_position: Point3<f64>,
1823    source_covariance: Option<&Matrix3<f64>>,
1824    existing_observation_count: usize,
1825    source_observation_count: usize,
1826) -> (Point3<f64>, Option<Matrix3<f64>>) {
1827    match (existing_covariance, source_covariance) {
1828        (Some(existing_covariance), Some(source_covariance)) => {
1829            if let (Some(existing_information), Some(source_information)) = (
1830                existing_covariance.try_inverse(),
1831                source_covariance.try_inverse(),
1832            ) {
1833                let information = existing_information + source_information;
1834                if let Some(covariance) = information.try_inverse() {
1835                    let position = covariance
1836                        * (existing_information * existing_position.coords
1837                            + source_information * source_position.coords);
1838                    return (Point3::from(position), Some(covariance));
1839                }
1840            }
1841        }
1842        (Some(existing_covariance), None) => {
1843            return (existing_position, Some(*existing_covariance));
1844        }
1845        (None, Some(source_covariance)) => {
1846            return (source_position, Some(*source_covariance));
1847        }
1848        (None, None) => {}
1849    }
1850
1851    let existing_weight = existing_observation_count.max(1) as f64;
1852    let source_weight = source_observation_count.max(1) as f64;
1853    let position = (existing_position.coords * existing_weight
1854        + source_position.coords * source_weight)
1855        / (existing_weight + source_weight);
1856    (
1857        Point3::from(position),
1858        existing_covariance
1859            .cloned()
1860            .or_else(|| source_covariance.cloned()),
1861    )
1862}
1863
1864fn append_transformed_submap(
1865    output: &mut VisualMap,
1866    source: &VisualMap,
1867    atlas_from_local: &SE3,
1868    remap: &SubmapIdRemap,
1869) {
1870    let local_from_atlas = atlas_from_local.inverse();
1871    let rotation = atlas_from_local.rotation.to_rotation_matrix().into_inner();
1872
1873    for (&old_id, &new_id) in &remap.landmark_ids {
1874        let source_landmark = &source.landmarks[&old_id];
1875        let transformed_position = atlas_from_local.transform_point(&source_landmark.position);
1876        let remapped_observations = source_landmark
1877            .observations
1878            .iter()
1879            .filter_map(|observation| remap_observation(observation, remap))
1880            .collect::<Vec<_>>();
1881        let transformed_covariance = source
1882            .landmark_position_covariances
1883            .get(&old_id)
1884            .map(|covariance| rotation * covariance * rotation.transpose());
1885
1886        if let Some(existing) = output.landmarks.get_mut(&new_id) {
1887            let existing_covariance = output.landmark_position_covariances.get(&new_id).cloned();
1888            let existing_observation_count = existing.observations.len().max(1);
1889            let source_observation_count = remapped_observations.len().max(1);
1890            let (fused_position, fused_covariance) = fuse_landmark_estimates(
1891                existing.position,
1892                existing_covariance.as_ref(),
1893                transformed_position,
1894                transformed_covariance.as_ref(),
1895                existing_observation_count,
1896                source_observation_count,
1897            );
1898            existing.position = fused_position;
1899            if existing.descriptor.is_none() {
1900                existing.descriptor = source_landmark.descriptor.clone();
1901            }
1902            let mut known_observations = existing
1903                .observations
1904                .iter()
1905                .map(|observation| {
1906                    (
1907                        observation.frame_id,
1908                        observation.landmark_id,
1909                        observation.keypoint_index,
1910                    )
1911                })
1912                .collect::<HashSet<_>>();
1913            for observation in remapped_observations {
1914                if known_observations.insert((
1915                    observation.frame_id,
1916                    observation.landmark_id,
1917                    observation.keypoint_index,
1918                )) {
1919                    existing.observations.push(observation);
1920                }
1921            }
1922            if let Some(covariance) = fused_covariance {
1923                output
1924                    .landmark_position_covariances
1925                    .insert(new_id, covariance);
1926            }
1927        } else {
1928            let mut landmark = Landmark::new(new_id, transformed_position);
1929            landmark.descriptor = source_landmark.descriptor.clone();
1930            landmark.observations = remapped_observations;
1931            output.landmarks.insert(new_id, landmark);
1932            if let Some(covariance) = transformed_covariance {
1933                output
1934                    .landmark_position_covariances
1935                    .insert(new_id, covariance);
1936            }
1937        }
1938    }
1939
1940    for (&old_id, &new_id) in &remap.frame_ids {
1941        let source_keyframe = &source.keyframes[&old_id];
1942        let mut frame = source_keyframe.frame.clone();
1943        frame.id = new_id;
1944        frame.camera_id = remap.camera_ids[&frame.camera_id];
1945        frame.pose = frame.pose.map(|pose| Pose {
1946            world_to_camera: pose.world_to_camera.compose(&local_from_atlas),
1947        });
1948        let mut observations = Vec::with_capacity(source_keyframe.observations.len());
1949        for source_observation in &source_keyframe.observations {
1950            if let Some(target_observation) = remap_observation(source_observation, remap) {
1951                if let Some(confidence) = source.observation_confidence(source_observation) {
1952                    output.set_observation_confidence(&target_observation, confidence);
1953                }
1954                observations.push(target_observation);
1955            }
1956        }
1957        output.keyframes.insert(
1958            new_id,
1959            Keyframe {
1960                frame,
1961                observations,
1962            },
1963        );
1964    }
1965
1966    for stereo in &source.stereo_observations {
1967        let (Some(&frame_id), Some(&landmark_id), Some(&right_camera_id)) = (
1968            remap.frame_ids.get(&stereo.frame_id),
1969            remap.landmark_ids.get(&stereo.landmark_id),
1970            remap.camera_ids.get(&stereo.right_camera_id),
1971        ) else {
1972            continue;
1973        };
1974        output.stereo_observations.push(StereoObservation {
1975            frame_id,
1976            landmark_id,
1977            right_camera_id,
1978            xy_right: stereo.xy_right,
1979            left_to_right: stereo.left_to_right.clone(),
1980        });
1981    }
1982}
1983
1984fn remap_observation(observation: &Observation, remap: &SubmapIdRemap) -> Option<Observation> {
1985    Some(Observation {
1986        frame_id: *remap.frame_ids.get(&observation.frame_id)?,
1987        landmark_id: *remap.landmark_ids.get(&observation.landmark_id)?,
1988        keypoint_index: observation.keypoint_index,
1989        xy: observation.xy,
1990    })
1991}
1992
1993#[cfg(test)]
1994mod tests {
1995    use super::*;
1996    use nalgebra::{Point2, Point3, UnitQuaternion, Vector3};
1997    use visloc_core::types::{Camera, Frame};
1998    use visloc_vision::matching::BruteForceMatcher;
1999
2000    fn one_point_map(position: Point3<f64>, covariance: Matrix3<f64>) -> VisualMap {
2001        let mut map = VisualMap::new();
2002        map.cameras
2003            .insert(1, Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0));
2004        map.cameras
2005            .insert(2, Camera::pinhole(2, 640, 480, 500.0, 500.0, 320.0, 240.0));
2006        let observation = Observation {
2007            frame_id: 0,
2008            landmark_id: 0,
2009            keypoint_index: 0,
2010            xy: Point2::new(320.0, 240.0),
2011        };
2012        let mut frame = Frame::new(0, 1);
2013        frame.pose = Some(Pose::identity());
2014        frame.keypoints.push(observation.xy);
2015        let mut landmark = Landmark::new(0, position);
2016        landmark.observations.push(observation.clone());
2017        map.landmarks.insert(0, landmark);
2018        map.landmark_position_covariances.insert(0, covariance);
2019        map.keyframes.insert(
2020            0,
2021            Keyframe {
2022                frame,
2023                observations: vec![observation.clone()],
2024            },
2025        );
2026        map.set_observation_confidence(&observation, 0.75);
2027        map.stereo_observations.push(StereoObservation {
2028            frame_id: 0,
2029            landmark_id: 0,
2030            right_camera_id: 2,
2031            xy_right: Point2::new(300.0, 240.0),
2032            left_to_right: SE3::new(UnitQuaternion::identity(), Vector3::new(-0.1, 0.0, 0.0)),
2033        });
2034        map
2035    }
2036
2037    fn strong_evidence(source: SubmapId, target: SubmapId, transform: SE3) -> SubmapMergeEvidence {
2038        SubmapMergeEvidence {
2039            source_submap_id: source,
2040            target_submap_id: target,
2041            target_from_source: transform,
2042            inlier_count: 80,
2043            inlier_ratio: 0.8,
2044            mean_reprojection_error_px: 0.5,
2045            estimated_scale: 1.01,
2046        }
2047    }
2048
2049    fn synthetic_revisit_map(frame_id: FrameId, camera: &Camera, world_scale: f64) -> VisualMap {
2050        let points = [
2051            Point3::new(-1.0, -0.8, 4.0),
2052            Point3::new(0.9, -0.7, 4.4),
2053            Point3::new(-0.8, 0.9, 4.8),
2054            Point3::new(1.1, 0.8, 5.2),
2055            Point3::new(-0.4, -0.2, 5.7),
2056            Point3::new(0.5, -0.3, 6.1),
2057            Point3::new(-0.6, 0.4, 6.6),
2058            Point3::new(0.7, 0.5, 7.0),
2059            Point3::new(-1.2, 0.1, 7.4),
2060            Point3::new(1.3, -0.1, 7.8),
2061            Point3::new(-0.2, 1.1, 8.2),
2062            Point3::new(0.3, -1.0, 8.6),
2063        ];
2064        let mut map = VisualMap::new();
2065        map.cameras.insert(camera.id, camera.clone());
2066        let mut frame = Frame::new(frame_id, camera.id);
2067        frame.pose = Some(Pose::identity());
2068        let mut observations = Vec::new();
2069        for (index, target_point) in points.into_iter().enumerate() {
2070            let source_point = Point3::from(target_point.coords * world_scale);
2071            let xy = camera.project(&source_point).unwrap();
2072            let mut descriptor = vec![0.0_f32; 12];
2073            descriptor[index] = 1.0;
2074            frame.keypoints.push(xy);
2075            frame.descriptors.push(descriptor.clone());
2076            let observation = Observation {
2077                frame_id,
2078                landmark_id: index as u64,
2079                keypoint_index: index,
2080                xy,
2081            };
2082            let mut landmark = Landmark::new(index as u64, source_point);
2083            landmark.descriptor = Some(descriptor);
2084            landmark.observations.push(observation.clone());
2085            map.landmarks.insert(landmark.id, landmark);
2086            observations.push(observation);
2087        }
2088        map.keyframes.insert(
2089            frame_id,
2090            Keyframe {
2091                frame,
2092                observations,
2093            },
2094        );
2095        map
2096    }
2097
2098    fn synthetic_alignment_config() -> CrossSubmapAlignmentConfig {
2099        CrossSubmapAlignmentConfig {
2100            max_target_submaps: 2,
2101            min_candidate_landmarks: 8,
2102            min_scale_pair_count: 10,
2103            merge_verification: SubmapMergeVerificationConfig {
2104                min_inliers: 8,
2105                min_inlier_ratio: 0.6,
2106                max_mean_reprojection_error_px: 2.0,
2107                max_metric_scale_error: 0.1,
2108                ..SubmapMergeVerificationConfig::default()
2109            },
2110            ..CrossSubmapAlignmentConfig::default()
2111        }
2112    }
2113
2114    #[test]
2115    fn independent_maps_remain_separate_until_verified_then_materialize_without_id_collisions() {
2116        let covariance = Matrix3::from_diagonal(&Vector3::new(1.0, 2.0, 3.0));
2117        let mut atlas = MapAtlas::new(one_point_map(Point3::new(1.0, 0.0, 5.0), covariance));
2118        let source =
2119            atlas.insert_independent(one_point_map(Point3::new(2.0, 0.0, 5.0), covariance));
2120
2121        let before = atlas.materialize_aligned().unwrap();
2122        assert_eq!(before.map.keyframes.len(), 1);
2123        assert_eq!(before.map.landmarks.len(), 1);
2124
2125        let target_from_source = SE3::new(
2126            UnitQuaternion::from_euler_angles(0.0, 0.0, std::f64::consts::FRAC_PI_2),
2127            Vector3::new(10.0, 0.0, 0.0),
2128        );
2129        atlas
2130            .verify_and_align(
2131                strong_evidence(source, atlas.root_submap_id().unwrap(), target_from_source),
2132                &SubmapMergeVerificationConfig::default(),
2133            )
2134            .unwrap();
2135        let merged = atlas.materialize_aligned().unwrap();
2136
2137        assert_eq!(merged.map.cameras.len(), 4);
2138        assert_eq!(merged.map.keyframes.len(), 2);
2139        assert_eq!(merged.map.landmarks.len(), 2);
2140        assert_eq!(merged.map.stereo_observations.len(), 2);
2141        assert_eq!(merged.map.observation_confidence_count(), 2);
2142        assert!(merged.map.validate().is_valid());
2143        let root_remap = &merged.id_remaps[&0];
2144        let source_remap = &merged.id_remaps[&source];
2145        assert_ne!(root_remap.frame_ids[&0], source_remap.frame_ids[&0]);
2146        assert_ne!(root_remap.landmark_ids[&0], source_remap.landmark_ids[&0]);
2147        let source_landmark = &merged.map.landmarks[&source_remap.landmark_ids[&0]];
2148        assert!((source_landmark.position - Point3::new(10.0, 2.0, 5.0)).norm() < 1.0e-12);
2149        let source_covariance =
2150            &merged.map.landmark_position_covariances[&source_remap.landmark_ids[&0]];
2151        let expected_covariance = Matrix3::from_diagonal(&Vector3::new(2.0, 1.0, 3.0));
2152        assert!((source_covariance - expected_covariance).norm() < 1.0e-12);
2153        let source_pose = merged.map.keyframes[&source_remap.frame_ids[&0]]
2154            .frame
2155            .pose
2156            .as_ref()
2157            .unwrap();
2158        let expected_pose = Pose {
2159            world_to_camera: atlas
2160                .submap(source)
2161                .unwrap()
2162                .atlas_from_local
2163                .as_ref()
2164                .unwrap()
2165                .inverse(),
2166        };
2167        assert!(
2168            (source_pose.camera_center_world() - expected_pose.camera_center_world()).norm()
2169                < 1.0e-12
2170        );
2171    }
2172
2173    #[test]
2174    fn appearance_pnp_and_metric_scale_align_an_independent_submap() {
2175        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
2176        let mut atlas = MapAtlas::new(synthetic_revisit_map(0, &camera, 1.0));
2177        let source = atlas.insert_independent(synthetic_revisit_map(10, &camera, 1.0));
2178        let localizer = LocalizationPipeline::default();
2179
2180        let result = atlas
2181            .align_submap_keyframe(
2182                source,
2183                10,
2184                &camera,
2185                None,
2186                &localizer,
2187                &synthetic_alignment_config(),
2188            )
2189            .unwrap();
2190
2191        let verified = result.verified_merge.unwrap();
2192        assert_eq!(verified.evidence.source_submap_id, source);
2193        assert_eq!(verified.evidence.target_submap_id, 0);
2194        assert!(verified.evidence.inlier_count >= 8);
2195        assert!((verified.evidence.estimated_scale - 1.0).abs() < 1.0e-9);
2196        assert!(verified.atlas_from_source.translation.norm() < 1.0e-6);
2197        assert!(verified.atlas_from_source.rotation.angle() < 1.0e-6);
2198        assert!(verified.landmark_matches.len() >= 8);
2199        assert_eq!(atlas.aligned_submap_count(), 2);
2200        assert_eq!(result.diagnostics.len(), 1);
2201        assert!(result.diagnostics[0].failure_reason.is_none());
2202        let welded_count = verified.landmark_matches.len();
2203        let materialized = atlas.materialize_aligned().unwrap();
2204        assert_eq!(materialized.map.landmarks.len(), 24 - welded_count);
2205        assert_eq!(materialized.map.keyframes.len(), 2);
2206        for landmark_match in &verified.landmark_matches {
2207            assert_eq!(
2208                materialized.id_remaps[&source].landmark_ids[&landmark_match.source_landmark_id],
2209                materialized.id_remaps[&0].landmark_ids[&landmark_match.target_landmark_id],
2210            );
2211        }
2212    }
2213
2214    #[test]
2215    fn adjacent_boundary_factor_recovers_metric_bridge() {
2216        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
2217        let mut atlas = MapAtlas::new(synthetic_revisit_map(0, &camera, 1.0));
2218        let source = atlas.insert_independent(synthetic_revisit_map(10, &camera, 1.0));
2219
2220        let result = atlas
2221            .align_adjacent_boundary_factor(
2222                source,
2223                10,
2224                0,
2225                0,
2226                None,
2227                &BruteForceMatcher::default(),
2228                &synthetic_alignment_config(),
2229            )
2230            .unwrap();
2231
2232        assert_eq!(result.descriptor_match_count, 12);
2233        assert_eq!(result.metric_correspondence_count, 12);
2234        assert_eq!(result.rigid_inlier_count, 12);
2235        assert!((result.rigid_inlier_ratio - 1.0).abs() < 1.0e-12);
2236        assert!(result.mean_target_reprojection_error_px.unwrap() < 1.0e-9);
2237        assert!(result.failure_reason.is_none());
2238        assert!(result.verified_merge.is_some());
2239        assert_eq!(atlas.aligned_submap_count(), 2);
2240    }
2241
2242    #[test]
2243    fn broader_source_window_recovers_with_retained_boundary_keyframe() {
2244        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
2245        let mut atlas = MapAtlas::new(synthetic_revisit_map(0, &camera, 1.0));
2246        let source = atlas.insert_independent(synthetic_revisit_map(10, &camera, 1.0));
2247        let mut current = atlas.submap(source).unwrap().map.keyframes[&10].clone();
2248        current.frame.id = 20;
2249        current.frame.descriptors.clear();
2250        for observation in &mut current.observations {
2251            observation.frame_id = 20;
2252        }
2253        atlas
2254            .submap_mut(source)
2255            .unwrap()
2256            .map
2257            .keyframes
2258            .insert(20, current);
2259        let window = atlas
2260            .source_keyframe_recovery_window(source, 20, 4)
2261            .unwrap();
2262        assert_eq!(window, vec![20, 10]);
2263
2264        let result = atlas
2265            .align_submap_keyframe_window(
2266                source,
2267                &window,
2268                &camera,
2269                Some(&SE3::identity()),
2270                &LocalizationPipeline::default(),
2271                &synthetic_alignment_config(),
2272            )
2273            .unwrap();
2274
2275        assert_eq!(result.attempted_source_frame_ids, vec![20, 10]);
2276        assert_eq!(result.alignments.len(), 2);
2277        assert!(result.alignments[0].verified_merge.is_none());
2278        assert_eq!(result.alignments[0].ranked_candidate_count, 0);
2279        assert!(result.verified_merge.is_some());
2280        assert!(result.alignments[1].verified_merge.is_some());
2281        assert!(atlas.submap(source).unwrap().atlas_from_local.is_some());
2282    }
2283
2284    #[test]
2285    fn pnp_consistent_but_scale_inconsistent_submap_is_not_aligned() {
2286        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
2287        let mut atlas = MapAtlas::new(synthetic_revisit_map(0, &camera, 1.0));
2288        // Scaling every source point about the camera leaves all pixels
2289        // unchanged, so PnP alone cannot detect this metric inconsistency.
2290        let source = atlas.insert_independent(synthetic_revisit_map(10, &camera, 1.5));
2291        let localizer = LocalizationPipeline::default();
2292
2293        let result = atlas
2294            .align_submap_keyframe(
2295                source,
2296                10,
2297                &camera,
2298                None,
2299                &localizer,
2300                &synthetic_alignment_config(),
2301            )
2302            .unwrap();
2303
2304        assert!(result.verified_merge.is_none());
2305        assert!(atlas.submap(source).unwrap().atlas_from_local.is_none());
2306        let diagnostic = result.diagnostics.first().unwrap();
2307        let scale = diagnostic.scale_estimate.unwrap();
2308        assert!((scale.estimated_scale - (2.0 / 3.0)).abs() < 1.0e-9);
2309        assert!(matches!(
2310            diagnostic.failure_reason,
2311            Some(CrossSubmapCandidateFailureReason::MergeRejected(
2312                MapAtlasError::MetricScaleInconsistent { .. }
2313            ))
2314        ));
2315    }
2316
2317    #[test]
2318    fn verified_landmark_match_welds_geometry_observations_stereo_confidence_and_covariance() {
2319        let covariance = Matrix3::from_diagonal(&Vector3::new(2.0, 4.0, 6.0));
2320        let target_map = one_point_map(Point3::new(0.0, 0.0, 5.0), covariance);
2321        let source_map = one_point_map(Point3::new(0.0, 0.0, 5.0), covariance);
2322        let mut atlas = MapAtlas::new(target_map);
2323        let source = atlas.insert_independent(source_map);
2324        atlas
2325            .verify_and_align_with_landmark_matches(
2326                strong_evidence(source, 0, SE3::identity()),
2327                vec![CrossSubmapLandmarkMatch {
2328                    source_landmark_id: 0,
2329                    target_landmark_id: 0,
2330                    transformed_distance_m: 0.0,
2331                }],
2332                &SubmapMergeVerificationConfig::default(),
2333            )
2334            .unwrap();
2335
2336        let materialized = atlas.materialize_aligned().unwrap();
2337
2338        assert_eq!(materialized.map.landmarks.len(), 1);
2339        assert_eq!(materialized.map.keyframes.len(), 2);
2340        assert_eq!(materialized.map.stereo_observations.len(), 2);
2341        assert_eq!(materialized.map.observation_confidence_count(), 2);
2342        let landmark = materialized.map.landmarks.values().next().unwrap();
2343        assert_eq!(landmark.observations.len(), 2);
2344        let fused_covariance = materialized
2345            .map
2346            .landmark_position_covariances
2347            .values()
2348            .next()
2349            .unwrap();
2350        assert!((fused_covariance - covariance * 0.5).norm() < 1.0e-12);
2351        assert_eq!(
2352            materialized.id_remaps[&0].landmark_ids[&0],
2353            materialized.id_remaps[&source].landmark_ids[&0],
2354        );
2355    }
2356
2357    #[test]
2358    fn scale_inconsistent_merge_is_rejected_without_aligning_source() {
2359        let mut atlas = MapAtlas::new(one_point_map(Point3::origin(), Matrix3::identity()));
2360        let source = atlas.insert_independent(one_point_map(Point3::origin(), Matrix3::identity()));
2361        let mut evidence = strong_evidence(source, 0, SE3::identity());
2362        evidence.estimated_scale = 1.5;
2363
2364        assert!(matches!(
2365            atlas.verify_and_align(evidence, &SubmapMergeVerificationConfig::default()),
2366            Err(MapAtlasError::MetricScaleInconsistent { .. })
2367        ));
2368        assert!(atlas.submap(source).unwrap().atlas_from_local.is_none());
2369        assert_eq!(atlas.verified_merges().len(), 0);
2370    }
2371
2372    #[test]
2373    fn verified_edges_compose_through_an_aligned_submap_chain() {
2374        let map = || one_point_map(Point3::origin(), Matrix3::identity());
2375        let mut atlas = MapAtlas::new(map());
2376        let middle = atlas.insert_independent(map());
2377        let source = atlas.insert_independent(map());
2378        atlas
2379            .verify_and_align(
2380                strong_evidence(
2381                    middle,
2382                    0,
2383                    SE3::new(UnitQuaternion::identity(), Vector3::new(10.0, 0.0, 0.0)),
2384                ),
2385                &SubmapMergeVerificationConfig::default(),
2386            )
2387            .unwrap();
2388        atlas
2389            .verify_and_align(
2390                strong_evidence(
2391                    source,
2392                    middle,
2393                    SE3::new(UnitQuaternion::identity(), Vector3::new(5.0, 0.0, 0.0)),
2394                ),
2395                &SubmapMergeVerificationConfig::default(),
2396            )
2397            .unwrap();
2398
2399        let atlas_from_source = atlas
2400            .submap(source)
2401            .unwrap()
2402            .atlas_from_local
2403            .as_ref()
2404            .unwrap();
2405        assert!((atlas_from_source.translation - Vector3::new(15.0, 0.0, 0.0)).norm() < 1.0e-12);
2406        assert_eq!(atlas.aligned_submap_count(), 3);
2407        assert_eq!(atlas.independent_submap_count(), 0);
2408    }
2409
2410    #[test]
2411    fn keyframe_bridge_recovers_the_target_from_source_map_transform() {
2412        let mut target_map = one_point_map(Point3::origin(), Matrix3::identity());
2413        target_map.keyframes.get_mut(&0).unwrap().frame.pose = Some(Pose::identity());
2414        let mut source_map = one_point_map(Point3::origin(), Matrix3::identity());
2415        // Source world is translated +10 m into target world. The same
2416        // physical camera at target-world origin therefore has T_c<-Ws = +10.
2417        source_map.keyframes.get_mut(&0).unwrap().frame.pose = Some(Pose::from_world_to_camera(
2418            UnitQuaternion::identity(),
2419            Vector3::new(10.0, 0.0, 0.0),
2420        ));
2421        let mut atlas = MapAtlas::new(target_map);
2422        let source = atlas.insert_independent(source_map);
2423        let evidence = atlas
2424            .evidence_from_keyframe_bridge(
2425                source,
2426                0,
2427                0,
2428                0,
2429                &SE3::identity(),
2430                SubmapMergeQuality {
2431                    inlier_count: 80,
2432                    inlier_ratio: 0.8,
2433                    mean_reprojection_error_px: 0.5,
2434                    estimated_scale: 1.0,
2435                },
2436            )
2437            .unwrap();
2438
2439        assert!(
2440            (evidence.target_from_source.translation - Vector3::new(10.0, 0.0, 0.0)).norm()
2441                < 1.0e-12
2442        );
2443        atlas
2444            .verify_and_align(evidence, &SubmapMergeVerificationConfig::default())
2445            .unwrap();
2446        assert_eq!(atlas.aligned_submap_count(), 2);
2447    }
2448
2449    #[test]
2450    fn fallible_insert_rejects_submap_id_exhaustion_without_overwrite() {
2451        let mut atlas = MapAtlas {
2452            next_submap_id: u64::MAX,
2453            ..MapAtlas::default()
2454        };
2455
2456        let result = atlas.try_insert_independent(VisualMap::new());
2457
2458        assert_eq!(result, Err(MapAtlasError::IdSpaceExhausted));
2459        assert_eq!(atlas.active_submaps().count(), 0);
2460        assert_eq!(atlas.next_submap_id, u64::MAX);
2461    }
2462}